Linux cryptographic layer development
 help / color / mirror / Atom feed
* [PATCH 00/11] Migrate x86_64 AES-GCM code into library
@ 2026-11-29 20:02 Eric Biggers
  2026-11-29 20:02 ` [PATCH 01/11] crypto: aes - Flush dcache in CBC-CTS and XTS linear fast paths Eric Biggers
                   ` (10 more replies)
  0 siblings, 11 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, 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 aes-gcm-x86-v1

This series migrates the x86_64 optimized AES-GCM code into lib/crypto/,
fully optimizing the AES-GCM library functions on x86_64.

(As usual, it also fixes the longstanding issue where the
architecture-optimized code was disabled by default.  The library always
enables optimizations, as long as the algorithm is enabled at all.)

It's divided into several parts:

- Patches 1-2 fix a couple existing bugs.

- Patches 3-4 add architecture hooks for one-shot AES-GCM and add a
  linear fast path to AES-GCM.  These are needed for parity with the
  existing short message optimizations used in aesni-intel_glue.c.

- Patches 5-7 replace the existing, not very well optimized GHASH and
  POLYVAL library code with new highly optimized code.  It's roughly
  based on the GHASH code in the three AES-GCM assembly files, and like
  the AES-GCM code there are three versions for different CPU feature
  sets: pclmul, vpclmul+avx2, and vpclmul+avx512.

  This was a prerequisite for migrating the AES-GCM code (since the
  AES-GCM library uses the GHASH library, including its key format).
  But I've gone a bit further and unified the GHASH and POLYVAL code as
  well, with the same assembly macros generating support for both.
  GHASH and POLYVAL are nearly identical, so this makes a lot of sense.

- Patches 8-10 migrate the x86_64 optimized AES-GCM code into the
  library, one patch per assembly file.

- Patch 11 deletes the aesni-intel module (which no longer has any
  functionality left in it) and keeps CRYPTO_AES_NI_INTEL only as a
  transitional symbol that causes AES-XTS support to be selected.

On long lengths, the KUnit benchmarks of the crypto library code on AMD
Ryzen 9 9950X (Zen 5) show the following performance improvements:

    GHASH:    1928 MB/s => 39348 MB/s
    POLYVAL: 10689 MB/s => 39020 MB/s
    AES-GCM:  1747 MB/s => 26937 MB/s

Patches 5-10 contain more library benchmark results.

AES-GCM crypto_aead performance did not significantly change (except for
very long associated data lengths without VAES, which got much faster).
HCTR2 crypto_skcipher performance got faster due to the POLYVAL speedup.

AI disclosure: AI coding tools were used to help write, revise, and
review this patchset.  But as usual it went through a lot of iterations,
with extensive manual review and editing (and prompting) to get things
the way I wanted.

Eric Biggers (11):
  crypto: aes - Flush dcache in CBC-CTS and XTS linear fast paths
  lib/crypto: gf128hash: Link libgf128hash before libaes
  lib/crypto: aes-gcm: Add one-shot AES-GCM arch hooks
  crypto: aes - Add linear fast path for AES-GCM
  lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with PCLMULQDQ
    and AVX
  lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with VPCLMULQDQ
    and AVX2
  lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with VPCLMULQDQ
    and AVX512
  lib/crypto: x86/aes-gcm: Migrate AES-NI optimized code into library
  lib/crypto: x86/aes-gcm: Migrate VAES+AVX2 optimized code into library
  lib/crypto: x86/aes-gcm: Migrate VAES+AVX512 optimized code into
    library
  crypto: x86/aesni-intel - Remove empty module

 Documentation/filesystems/fscrypt.rst         |   2 -
 arch/x86/crypto/Kconfig                       |  25 -
 arch/x86/crypto/Makefile                      |   6 -
 arch/x86/crypto/aesni-intel_glue.c            | 888 ------------------
 crypto/Kconfig                                |   9 +
 crypto/aes.c                                  | 213 ++++-
 include/crypto/gf128hash.h                    |  48 +-
 lib/crypto/Kconfig                            |   2 +-
 lib/crypto/Makefile                           |  64 +-
 lib/crypto/aes.c                              |  97 +-
 .../crypto/x86}/aes-gcm-aesni-x86_64.S        | 414 +++-----
 .../crypto/x86}/aes-gcm-vaes-avx2.S           | 419 ++-------
 .../crypto/x86}/aes-gcm-vaes-avx512.S         | 374 ++------
 lib/crypto/x86/aes.h                          | 352 ++++++-
 lib/crypto/x86/gf128hash-cpu.h                |  54 ++
 lib/crypto/x86/gf128hash-pclmul.S             | 559 +++++++++++
 lib/crypto/x86/gf128hash-vpclmul-avx2.S       | 537 +++++++++++
 lib/crypto/x86/gf128hash-vpclmul-avx512.S     | 516 ++++++++++
 lib/crypto/x86/gf128hash.h                    | 322 +++++--
 lib/crypto/x86/ghash-pclmul.S                 | 127 ---
 lib/crypto/x86/polyval-pclmul-avx.S           | 319 -------
 21 files changed, 2933 insertions(+), 2414 deletions(-)
 delete mode 100644 arch/x86/crypto/aesni-intel_glue.c
 rename {arch/x86/crypto => lib/crypto/x86}/aes-gcm-aesni-x86_64.S (75%)
 rename {arch/x86/crypto => lib/crypto/x86}/aes-gcm-vaes-avx2.S (69%)
 rename {arch/x86/crypto => lib/crypto/x86}/aes-gcm-vaes-avx512.S (74%)
 create mode 100644 lib/crypto/x86/gf128hash-cpu.h
 create mode 100644 lib/crypto/x86/gf128hash-pclmul.S
 create mode 100644 lib/crypto/x86/gf128hash-vpclmul-avx2.S
 create mode 100644 lib/crypto/x86/gf128hash-vpclmul-avx512.S
 delete mode 100644 lib/crypto/x86/ghash-pclmul.S
 delete mode 100644 lib/crypto/x86/polyval-pclmul-avx.S


base-commit: 7845a3cc6e006f849ff882737afbd46584168eac
-- 
2.56.1


^ permalink raw reply	[flat|nested] 12+ messages in thread

* [PATCH 01/11] crypto: aes - Flush dcache in CBC-CTS and XTS linear fast paths
  2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
@ 2026-11-29 20:02 ` Eric Biggers
  2026-11-29 20:02 ` [PATCH 02/11] lib/crypto: gf128hash: Link libgf128hash before libaes Eric Biggers
                   ` (9 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, Eric Biggers, stable

The linear fast paths in crypto_aes_cbc_cts_{en,de}crypt() and
crypto_aes_xts_{en,de}crypt() write directly to sg_virt(req->dst)
without going through scatterwalk_done_dst(), so they fail to flush the
dcache on architectures where ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE is true.

Add a small __always_inline helper sg_flush_dcache() and call it from
those fast paths.  When !ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE, the helper
compiles out completely.

Fixes: 20df21a482aa ("crypto: aes - Add CBC and CBC-CTS support using library")
Fixes: 94efa0c9fb36 ("crypto: aes - Add XTS support using library")
Cc: stable@vger.kernel.org
Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 crypto/aes.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/crypto/aes.c b/crypto/aes.c
index a2db6351feefa..c4541f5bc6e32 100644
--- a/crypto/aes.c
+++ b/crypto/aes.c
@@ -240,6 +240,19 @@ skcipher_request_is_linear_lowmem(const struct skcipher_request *req)
 	       req->src->length >= req->cryptlen;
 }
 
+/*
+ * Flush the dcache for a linear region [off, off + len) within a single
+ * scatterlist element @sg.  This must be called after writing directly to
+ * sg_virt(sg) without going through scatterwalk_done_dst().
+ */
+static __always_inline void sg_flush_dcache(struct scatterlist *sg,
+					    unsigned int off, unsigned int len)
+{
+	if (ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE)
+		__scatterwalk_flush_dcache_pages(sg_page(sg), sg->offset + off,
+						 len);
+}
+
 /*
  * Call crypt_func() (a function that operates on simple virtual addresses) zero
  * or more times to en/decrypt 'cryptlen' bytes of data from the source
@@ -462,6 +475,7 @@ crypto_aes_cbc_cts_encrypt(struct skcipher_request *req)
 		/* Fast path */
 		aes_cbc_cts_encrypt(sg_virt(req->dst), sg_virt(req->src),
 				    req->cryptlen, req->iv, key);
+		sg_flush_dcache(req->dst, 0, req->cryptlen);
 		return 0;
 	}
 	return crypto_aes_cbc_cts_crypt_nonlinear(req, /* enc= */ true);
@@ -479,6 +493,7 @@ crypto_aes_cbc_cts_decrypt(struct skcipher_request *req)
 		/* Fast path */
 		aes_cbc_cts_decrypt(sg_virt(req->dst), sg_virt(req->src),
 				    req->cryptlen, req->iv, key);
+		sg_flush_dcache(req->dst, 0, req->cryptlen);
 		return 0;
 	}
 	return crypto_aes_cbc_cts_crypt_nonlinear(req, /* enc= */ false);
@@ -584,6 +599,7 @@ static __maybe_unused int crypto_aes_xts_encrypt(struct skcipher_request *req)
 		/* Fast path */
 		aes_xts_encrypt(sg_virt(req->dst), sg_virt(req->src),
 				req->cryptlen, req->iv, key, /* cont= */ false);
+		sg_flush_dcache(req->dst, 0, req->cryptlen);
 		return 0;
 	}
 	return crypto_aes_xts_crypt_nonlinear(req, /* enc= */ true);
@@ -600,6 +616,7 @@ static __maybe_unused int crypto_aes_xts_decrypt(struct skcipher_request *req)
 		/* Fast path */
 		aes_xts_decrypt(sg_virt(req->dst), sg_virt(req->src),
 				req->cryptlen, req->iv, key, /* cont= */ false);
+		sg_flush_dcache(req->dst, 0, req->cryptlen);
 		return 0;
 	}
 	return crypto_aes_xts_crypt_nonlinear(req, /* enc= */ false);
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH 02/11] lib/crypto: gf128hash: Link libgf128hash before libaes
  2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
  2026-11-29 20:02 ` [PATCH 01/11] crypto: aes - Flush dcache in CBC-CTS and XTS linear fast paths Eric Biggers
@ 2026-11-29 20:02 ` Eric Biggers
  2026-11-29 20:02 ` [PATCH 03/11] lib/crypto: aes-gcm: Add one-shot AES-GCM arch hooks Eric Biggers
                   ` (8 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, Eric Biggers, stable

Move libgf128hash above libaes in lib/crypto/Makefile so that
gf128hash_mod_init() runs first when both libgf128hash and libaes are
built-in.

This is relevant to the AES-GCM FIPS self-test, which previously didn't
use the architecture-optimized GHASH code in this case.

Fixes: fbdb43c0007b ("lib/crypto: aes: Add FIPS self-tests for GCM and CCM")
Cc: stable@vger.kernel.org
Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 lib/crypto/Makefile | 58 +++++++++++++++++++++++----------------------
 1 file changed, 30 insertions(+), 28 deletions(-)

diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile
index cefec4304d808..5ddf64ce1d453 100644
--- a/lib/crypto/Makefile
+++ b/lib/crypto/Makefile
@@ -21,6 +21,36 @@ libcryptoutils-y				:= memneq.o utils.o
 
 ################################################################################
 
+# The AES-GCM support in libaes uses libgf128hash.  Link libgf128hash before
+# libaes so that the libgf128hash initcall runs first when both are built-in.
+obj-$(CONFIG_CRYPTO_LIB_GF128HASH) += libgf128hash.o
+libgf128hash-y := gf128hash.o
+ifeq ($(CONFIG_CRYPTO_LIB_GF128HASH_ARCH),y)
+CFLAGS_gf128hash.o += -I$(src)/$(SRCARCH)
+libgf128hash-$(CONFIG_ARM) += arm/ghash-neon-core.o
+libgf128hash-$(CONFIG_ARM64) += arm64/ghash-neon-core.o \
+				arm64/polyval-ce-core.o
+
+ifeq ($(CONFIG_PPC),y)
+libgf128hash-y += powerpc/ghashp8-ppc.o
+quiet_cmd_perlasm_ghash = PERLASM $@
+      cmd_perlasm_ghash = $(PERL) $< $(ppc64-perlasm-flavour-y) $@
+$(obj)/powerpc/ghashp8-ppc.S: $(src)/powerpc/ghashp8-ppc.pl FORCE
+	$(call if_changed,perlasm_ghash)
+targets += powerpc/ghashp8-ppc.S
+OBJECT_FILES_NON_STANDARD_powerpc/ghashp8-ppc.o := y
+endif
+
+libgf128hash-$(CONFIG_RISCV) += riscv/ghash-riscv64-zvkg.o
+libgf128hash-$(CONFIG_X86) += x86/ghash-pclmul.o \
+			      x86/polyval-pclmul-avx.o
+endif # CONFIG_CRYPTO_LIB_GF128HASH_ARCH
+
+# clean-files must be defined unconditionally
+clean-files += powerpc/ghashp8-ppc.S
+
+################################################################################
+
 obj-$(CONFIG_CRYPTO_LIB_AES) += libaes.o
 libaes-y := aes.o
 ifeq ($(CONFIG_CRYPTO_LIB_AES_ARCH),y)
@@ -168,34 +198,6 @@ libdes-y					:= des.o
 
 ################################################################################
 
-obj-$(CONFIG_CRYPTO_LIB_GF128HASH) += libgf128hash.o
-libgf128hash-y := gf128hash.o
-ifeq ($(CONFIG_CRYPTO_LIB_GF128HASH_ARCH),y)
-CFLAGS_gf128hash.o += -I$(src)/$(SRCARCH)
-libgf128hash-$(CONFIG_ARM) += arm/ghash-neon-core.o
-libgf128hash-$(CONFIG_ARM64) += arm64/ghash-neon-core.o \
-				arm64/polyval-ce-core.o
-
-ifeq ($(CONFIG_PPC),y)
-libgf128hash-y += powerpc/ghashp8-ppc.o
-quiet_cmd_perlasm_ghash = PERLASM $@
-      cmd_perlasm_ghash = $(PERL) $< $(ppc64-perlasm-flavour-y) $@
-$(obj)/powerpc/ghashp8-ppc.S: $(src)/powerpc/ghashp8-ppc.pl FORCE
-	$(call if_changed,perlasm_ghash)
-targets += powerpc/ghashp8-ppc.S
-OBJECT_FILES_NON_STANDARD_powerpc/ghashp8-ppc.o := y
-endif
-
-libgf128hash-$(CONFIG_RISCV) += riscv/ghash-riscv64-zvkg.o
-libgf128hash-$(CONFIG_X86) += x86/ghash-pclmul.o \
-			      x86/polyval-pclmul-avx.o
-endif # CONFIG_CRYPTO_LIB_GF128HASH_ARCH
-
-# clean-files must be defined unconditionally
-clean-files += powerpc/ghashp8-ppc.S
-
-################################################################################
-
 obj-$(CONFIG_CRYPTO_LIB_MD5) += libmd5.o
 libmd5-y := md5.o
 
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH 03/11] lib/crypto: aes-gcm: Add one-shot AES-GCM arch hooks
  2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
  2026-11-29 20:02 ` [PATCH 01/11] crypto: aes - Flush dcache in CBC-CTS and XTS linear fast paths Eric Biggers
  2026-11-29 20:02 ` [PATCH 02/11] lib/crypto: gf128hash: Link libgf128hash before libaes Eric Biggers
@ 2026-11-29 20:02 ` Eric Biggers
  2026-11-29 20:02 ` [PATCH 04/11] crypto: aes - Add linear fast path for AES-GCM Eric Biggers
                   ` (7 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, Eric Biggers

The incremental AES-GCM API has a fair bit of per-message overhead due
to multiple SIMD/FPU sections, separate J_0 encryption and GHASH calls,
tag copying, etc.

Therefore, add hooks to the one-shot AES-GCM en/decryption functions to
allow architectures to optimize the full AES-GCM.

This will be useful in two cases:

- Direct calls to aes_gcm_encrypt() and aes_gcm_decrypt()

- Calls to aes_gcm_encrypt() and aes_gcm_decrypt() via crypto_aead for
  linear requests, once crypto/aes.c is updated to make those calls.

The latter is needed to avoid regressing "gcm(aes)" crypto_aead
performance on short messages once the "gcm(aes)" crypto_aead
implementations in arch/x86/crypto/ (which have similar short-message
optimizations) are superseded by the library-based code.

For efficiency, pass a pointer to 'struct aes_gcm_key' rather than its
embedded 'struct aes_enckey' and 'struct ghash_key' separately.  Update
aes_gcm_{en,de}crypt_update_arch() to use this convention too, which
conveniently makes all their arguments fit into registers on x86_64.

Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 lib/crypto/aes.c | 97 +++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 83 insertions(+), 14 deletions(-)

diff --git a/lib/crypto/aes.c b/lib/crypto/aes.c
index 13d934ba712c3..7b0486953b4df 100644
--- a/lib/crypto/aes.c
+++ b/lib/crypto/aes.c
@@ -1483,8 +1483,7 @@ static inline void aes_xts_fips_test(void)
 static bool aes_gcm_encrypt_update_arch(u8 *dst, const u8 *src, size_t len,
 					struct polyval_elem *ghash_acc,
 					const __be32 ctr32[4],
-					const struct aes_enckey *aes_key,
-					const struct ghash_key *ghash_key)
+					const struct aes_gcm_key *key)
 {
 	return false;
 }
@@ -1493,8 +1492,35 @@ static bool aes_gcm_encrypt_update_arch(u8 *dst, const u8 *src, size_t len,
 static bool aes_gcm_decrypt_update_arch(u8 *dst, const u8 *src, size_t len,
 					struct polyval_elem *ghash_acc,
 					const __be32 ctr32[4],
-					const struct aes_enckey *aes_key,
-					const struct ghash_key *ghash_key)
+					const struct aes_gcm_key *key)
+{
+	return false;
+}
+#endif
+
+/*
+ * Hooks for optimized one-shot AES-GCM implementations, overridable by the
+ * architecture to avoid the overhead of the incremental API.
+ *
+ * Returning false causes the incremental implementation to be used instead.
+ *
+ * The decryption hook (if it returns true) must check the auth tag and store
+ * the status (0 or -EBADMSG) at *err.
+ */
+#ifndef aes_gcm_encrypt_arch
+static bool aes_gcm_encrypt_arch(u8 *dst, const u8 *src, size_t data_len,
+				 u8 *authtag, const u8 *ad, size_t ad_len,
+				 const u8 nonce[12],
+				 const struct aes_gcm_key *key)
+{
+	return false;
+}
+#endif
+#ifndef aes_gcm_decrypt_arch
+static bool aes_gcm_decrypt_arch(u8 *dst, const u8 *src, size_t data_len,
+				 const u8 *authtag, const u8 *ad, size_t ad_len,
+				 const u8 nonce[12],
+				 const struct aes_gcm_key *key, int *err)
 {
 	return false;
 }
@@ -1598,7 +1624,7 @@ static __always_inline void aes_gcm_crypt_update(struct aes_gcm_ctx *ctx,
 		if (enc) {
 			if (likely(aes_gcm_encrypt_update_arch(
 				    dst, src, n, &ctx->ghash.acc, ctx->ctr32,
-				    &ctx->key->aes, &ctx->key->ghash))) {
+				    ctx->key))) {
 				be32_add_cpu(&ctx->ctr32[3],
 					     n / AES_BLOCK_SIZE);
 			} else {
@@ -1608,7 +1634,7 @@ static __always_inline void aes_gcm_crypt_update(struct aes_gcm_ctx *ctx,
 		} else {
 			if (likely(aes_gcm_decrypt_update_arch(
 				    dst, src, n, &ctx->ghash.acc, ctx->ctr32,
-				    &ctx->key->aes, &ctx->key->ghash))) {
+				    ctx->key))) {
 				be32_add_cpu(&ctx->ctr32[3],
 					     n / AES_BLOCK_SIZE);
 			} else {
@@ -1706,9 +1732,15 @@ int aes_gcm_decrypt_final(struct aes_gcm_ctx *ctx, const u8 *authtag)
 }
 EXPORT_SYMBOL_GPL(aes_gcm_decrypt_final);
 
-void aes_gcm_encrypt(u8 *dst, const u8 *src, size_t data_len, u8 *authtag,
-		     const u8 *ad, size_t ad_len, const u8 nonce[12],
-		     const struct aes_gcm_key *key)
+#ifdef aes_gcm_encrypt_arch
+/* Keep struct aes_gcm_ctx out of the fast path stack frame. */
+static noinline void
+#else
+static inline void
+#endif
+aes_gcm_encrypt_fallback(u8 *dst, const u8 *src, size_t data_len, u8 *authtag,
+			 const u8 *ad, size_t ad_len, const u8 nonce[12],
+			 const struct aes_gcm_key *key)
 {
 	struct aes_gcm_ctx ctx;
 
@@ -1717,19 +1749,56 @@ void aes_gcm_encrypt(u8 *dst, const u8 *src, size_t data_len, u8 *authtag,
 	aes_gcm_encrypt_update(&ctx, dst, src, data_len);
 	aes_gcm_encrypt_final(&ctx, authtag);
 }
+
+void aes_gcm_encrypt(u8 *dst, const u8 *src, size_t data_len, u8 *authtag,
+		     const u8 *ad, size_t ad_len, const u8 nonce[12],
+		     const struct aes_gcm_key *key)
+{
+	WARN_ON_ONCE((u64)ad_len > AES_GCM_MAX_AD_LEN);
+	WARN_ON_ONCE((u64)data_len > AES_GCM_MAX_DATA_LEN);
+
+	if (likely(aes_gcm_encrypt_arch(dst, src, data_len, authtag, ad, ad_len,
+					nonce, key)))
+		return;
+	aes_gcm_encrypt_fallback(dst, src, data_len, authtag, ad, ad_len, nonce,
+				 key);
+}
 EXPORT_SYMBOL_GPL(aes_gcm_encrypt);
 
-int aes_gcm_decrypt(u8 *dst, const u8 *src, size_t data_len, const u8 *authtag,
-		    const u8 *ad, size_t ad_len, const u8 nonce[12],
-		    const struct aes_gcm_key *key)
+#ifdef aes_gcm_decrypt_arch
+/* Keep struct aes_gcm_ctx out of the fast path stack frame. */
+static noinline int
+#else
+static inline int
+#endif
+aes_gcm_decrypt_fallback(u8 *dst, const u8 *src, size_t data_len,
+			 const u8 *authtag, const u8 *ad, size_t ad_len,
+			 const u8 nonce[12], const struct aes_gcm_key *key)
 {
 	struct aes_gcm_ctx ctx;
-	int err;
 
 	aes_gcm_init(&ctx, nonce, key);
 	aes_gcm_auth_update(&ctx, ad, ad_len);
 	aes_gcm_decrypt_update(&ctx, dst, src, data_len);
-	err = aes_gcm_decrypt_final(&ctx, authtag);
+	return aes_gcm_decrypt_final(&ctx, authtag);
+}
+
+int aes_gcm_decrypt(u8 *dst, const u8 *src, size_t data_len, const u8 *authtag,
+		    const u8 *ad, size_t ad_len, const u8 nonce[12],
+		    const struct aes_gcm_key *key)
+{
+	int err;
+
+	if (WARN_ON_ONCE((u64)ad_len > AES_GCM_MAX_AD_LEN) ||
+	    WARN_ON_ONCE((u64)data_len > AES_GCM_MAX_DATA_LEN))
+		return -EBADMSG;
+
+	if (likely(aes_gcm_decrypt_arch(dst, src, data_len, authtag, ad, ad_len,
+					nonce, key, &err)))
+		goto out;
+	err = aes_gcm_decrypt_fallback(dst, src, data_len, authtag, ad, ad_len,
+				       nonce, key);
+out:
 	if (unlikely(err) && data_len) {
 		/*
 		 * Clear the inauthentic decrypted data so that callers won't
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH 04/11] crypto: aes - Add linear fast path for AES-GCM
  2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
                   ` (2 preceding siblings ...)
  2026-11-29 20:02 ` [PATCH 03/11] lib/crypto: aes-gcm: Add one-shot AES-GCM arch hooks Eric Biggers
@ 2026-11-29 20:02 ` Eric Biggers
  2026-11-29 20:02 ` [PATCH 05/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with PCLMULQDQ and AVX Eric Biggers
                   ` (6 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, Eric Biggers

The "gcm(aes)" crypto_aead implementations in arch/x86/crypto/ currently
have several optimizations that reduce overhead for short messages, such
as using a single kernel-mode FPU section in most cases, and comparing
authentication tags in assembly code.

gcm-aes-lib currently executes each aead_request using the incremental
AES-GCM API, which is less efficient.

Therefore, add a "fast path" similar to what the xts-aes-lib has: if
!CONFIG_HIGHMEM, check if the associated data, source data, destination
data, and authentication tag are each linear, and if so, call
aes_gcm_encrypt() or aes_gcm_decrypt().

This allows the library to dispatch the operation to
aes_gcm_encrypt_arch() and aes_gcm_decrypt_arch().

Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 crypto/aes.c | 192 ++++++++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 184 insertions(+), 8 deletions(-)

diff --git a/crypto/aes.c b/crypto/aes.c
index c4541f5bc6e32..e360756385cdf 100644
--- a/crypto/aes.c
+++ b/crypto/aes.c
@@ -787,9 +787,97 @@ static void aes_gcm_decrypt_update_helper(u8 *dst, const u8 *src,
 	aes_gcm_decrypt_update(ctx, dst, src, len);
 }
 
-static int crypto_aes_gcm_encrypt_common(struct aead_request *req,
-					 const struct aes_gcm_key *key,
-					 u8 iv[12], unsigned int assoclen)
+/*
+ * Given a scatterlist @sg containing @assoclen bytes of associated data,
+ * @data_len bytes of en/decrypted data, and @tag_len bytes of authentication
+ * tag, check whether each of those regions (when non-empty) is contiguous in
+ * low memory.  Each region may share a scatterlist element with the previous
+ * region or begin in the immediately following scatterlist element.
+ *
+ * This enables a fast path for the common case where an AEAD request's regions
+ * are linear in low memory, allowing crypto_aes_gcm_{en,de}crypt_common() to
+ * call the one-shot aes_gcm_encrypt() / aes_gcm_decrypt() library functions
+ * directly, avoiding the overhead of incremental processing.
+ */
+static __always_inline bool
+aead_sg_get_linear(struct scatterlist *sg, unsigned int assoclen,
+		   unsigned int data_len, unsigned int tag_len,
+		   const u8 **ad_out, u8 **data_out,
+		   struct scatterlist **data_sg_out, unsigned int *data_off_out,
+		   u8 **tag_out, struct scatterlist **tag_sg_out,
+		   unsigned int *tag_off_out)
+{
+	unsigned int off = 0;
+	u8 *virt = NULL;
+
+	if (IS_ENABLED(CONFIG_HIGHMEM))
+		return false;
+
+	if (assoclen) {
+		if (!sg || sg->length < assoclen)
+			return false;
+		if (ad_out) {
+			virt = sg_virt(sg);
+			*ad_out = virt;
+		}
+		off = assoclen;
+	} else if (ad_out) {
+		*ad_out = NULL;
+	}
+
+	if (data_len) {
+		if (off && sg->length == off) {
+			sg = sg_next(sg);
+			off = 0;
+			virt = NULL;
+		}
+		if (!sg || sg->length < (u64)off + data_len)
+			return false;
+		if (!virt)
+			virt = sg_virt(sg);
+		*data_out = virt + off;
+		if (data_sg_out) {
+			*data_sg_out = sg;
+			*data_off_out = off;
+		}
+		off += data_len;
+	} else {
+		*data_out = NULL;
+		if (data_sg_out) {
+			*data_sg_out = NULL;
+			*data_off_out = 0;
+		}
+	}
+
+	if (tag_len) {
+		if (off && sg->length == off) {
+			sg = sg_next(sg);
+			off = 0;
+			virt = NULL;
+		}
+		if (!sg || sg->length < (u64)off + tag_len)
+			return false;
+		if (!virt)
+			virt = sg_virt(sg);
+		*tag_out = virt + off;
+		if (tag_sg_out) {
+			*tag_sg_out = sg;
+			*tag_off_out = off;
+		}
+	}
+
+	return true;
+}
+
+/*
+ * This handles AES-GCM encryption requests that use a nonlinear scatterlist
+ * layout or where HIGHMEM is enabled.  It is explicitly 'noinline' to keep the
+ * on-stack buffers out of the stack frame of the fast path.
+ */
+static noinline int
+crypto_aes_gcm_encrypt_nonlinear(struct aead_request *req,
+				 const struct aes_gcm_key *key, u8 iv[12],
+				 unsigned int assoclen)
 {
 	struct aes_gcm_ctx ctx;
 	u8 authtag[16];
@@ -805,20 +893,69 @@ static int crypto_aes_gcm_encrypt_common(struct aead_request *req,
 	return 0;
 }
 
-static int crypto_aes_gcm_decrypt_common(struct aead_request *req,
+/*
+ * Common AES-GCM encryption helper for gcm(aes) and rfc4106(gcm(aes)).
+ * @assoclen is the number of bytes of associated data to authenticate, which is
+ * req->assoclen for gcm(aes) and req->assoclen - 8 for rfc4106(gcm(aes)) (where
+ * the 8-byte explicit IV sits between the AAD and the data in the scatterlist).
+ */
+static int crypto_aes_gcm_encrypt_common(struct aead_request *req,
 					 const struct aes_gcm_key *key,
 					 u8 iv[12], unsigned int assoclen)
+{
+	struct scatterlist *dst_sg, *tag_sg;
+	unsigned int dst_off, tag_off;
+	const u8 *ad;
+	u8 *src, *dst, *tag;
+
+	if (req->src == req->dst) {
+		if (unlikely(!aead_sg_get_linear(
+			    req->src, req->assoclen, req->cryptlen,
+			    key->authtag_len, &ad, &dst, &dst_sg, &dst_off,
+			    &tag, &tag_sg, &tag_off)))
+			return crypto_aes_gcm_encrypt_nonlinear(req, key, iv,
+								assoclen);
+		src = dst;
+	} else {
+		if (unlikely(!aead_sg_get_linear(
+				     req->src, req->assoclen, req->cryptlen, 0,
+				     &ad, &src, NULL, NULL, NULL, NULL, NULL) ||
+			     !aead_sg_get_linear(
+				     req->dst, req->assoclen, req->cryptlen,
+				     key->authtag_len, NULL, &dst, &dst_sg,
+				     &dst_off, &tag, &tag_sg, &tag_off)))
+			return crypto_aes_gcm_encrypt_nonlinear(req, key, iv,
+								assoclen);
+	}
+
+	aes_gcm_encrypt(dst, src, req->cryptlen, tag, ad, assoclen, iv, key);
+	if (dst_sg == tag_sg) {
+		sg_flush_dcache(dst_sg, dst_off,
+				req->cryptlen + key->authtag_len);
+	} else {
+		if (dst_sg)
+			sg_flush_dcache(dst_sg, dst_off, req->cryptlen);
+		sg_flush_dcache(tag_sg, tag_off, key->authtag_len);
+	}
+	return 0;
+}
+
+/*
+ * This handles AES-GCM decryption requests that use a nonlinear scatterlist
+ * layout or where HIGHMEM is enabled.  It is explicitly 'noinline' to keep the
+ * on-stack buffers out of the stack frame of the fast path.
+ */
+static noinline int
+crypto_aes_gcm_decrypt_nonlinear(struct aead_request *req,
+				 const struct aes_gcm_key *key, u8 iv[12],
+				 unsigned int assoclen, unsigned int data_len)
 {
 	struct aes_gcm_ctx ctx;
-	unsigned int data_len;
 	u8 authtag[16];
 	int err;
 
 	aes_gcm_init(&ctx, iv, key);
 	crypto_aes_gcm_auth_update(&ctx, req->src, assoclen);
-
-	/* crypto_aead_decrypt() already checked cryptlen >= authtag_len. */
-	data_len = req->cryptlen - key->authtag_len;
 	AES_CRYPT_SG(aes_gcm_decrypt_update_helper, req->dst, req->src,
 		     data_len, req->assoclen, &ctx);
 
@@ -829,6 +966,45 @@ static int crypto_aes_gcm_decrypt_common(struct aead_request *req,
 	return err;
 }
 
+/*
+ * Common AES-GCM decryption helper; see crypto_aes_gcm_encrypt_common() for
+ * @assoclen.
+ */
+static int crypto_aes_gcm_decrypt_common(struct aead_request *req,
+					 const struct aes_gcm_key *key,
+					 u8 iv[12], unsigned int assoclen)
+{
+	/* crypto_aead_decrypt() already checked cryptlen >= authtag_len. */
+	unsigned int data_len = req->cryptlen - key->authtag_len;
+	struct scatterlist *src_sg, *dst_sg;
+	unsigned int src_off, dst_off;
+	const u8 *ad;
+	u8 *src, *dst, *tag;
+	int err;
+
+	if (unlikely(!aead_sg_get_linear(req->src, req->assoclen, data_len,
+					 key->authtag_len, &ad, &src, &src_sg,
+					 &src_off, &tag, NULL, NULL)))
+		return crypto_aes_gcm_decrypt_nonlinear(req, key, iv, assoclen,
+							data_len);
+	if (req->src == req->dst || !data_len) {
+		dst_sg = src_sg;
+		dst_off = src_off;
+		dst = src;
+	} else {
+		if (unlikely(!aead_sg_get_linear(
+			    req->dst, req->assoclen, data_len, 0, NULL, &dst,
+			    &dst_sg, &dst_off, NULL, NULL, NULL)))
+			return crypto_aes_gcm_decrypt_nonlinear(
+				req, key, iv, assoclen, data_len);
+	}
+
+	err = aes_gcm_decrypt(dst, src, data_len, tag, ad, assoclen, iv, key);
+	if (data_len)
+		sg_flush_dcache(dst_sg, dst_off, data_len);
+	return err;
+}
+
 static __maybe_unused int crypto_aes_gcm_encrypt(struct aead_request *req)
 {
 	struct crypto_aead *tfm = crypto_aead_reqtfm(req);
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH 05/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with PCLMULQDQ and AVX
  2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
                   ` (3 preceding siblings ...)
  2026-11-29 20:02 ` [PATCH 04/11] crypto: aes - Add linear fast path for AES-GCM Eric Biggers
@ 2026-11-29 20:02 ` Eric Biggers
  2026-11-29 20:02 ` [PATCH 06/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with VPCLMULQDQ and AVX2 Eric Biggers
                   ` (5 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, Eric Biggers

Currently, the x86_64 GHASH and POLYVAL code is fragmented and in many
cases inefficient:

- The GHASH library (used by the AES-GCM library and the "gcm" template)
  is optimized only with a slow one-block-at-a-time implementation using
  PCLMULQDQ only (no AVX).  It optimizes for old CPUs with slow
  pclmulqdq support by using Karatsuba multiplication and the
  multiplication-less reduction algorithm.

- The POLYVAL library (used by HCTR2) is optimized with an
  8-blocks-at-a-time implementation using PCLMULQDQ + AVX.  It optimizes
  for CPUs with fast pclmulqdq support by using schoolbook
  multiplication and the two-multiplication reduction algorithm.

- The x86_64 "gcm(aes)" code in arch/x86/crypto/aes-gcm-*.S has several
  implementations of GHASH, using PCLMULQDQ, PCLMULQDQ + AVX, VPCLMULQDQ
  + AVX2, and VPCLMULQDQ + AVX512.  They differ slightly in their
  implementation strategies.  E.g., the VPCLMULQDQ ones are parallelized
  across multiple vectors while the PCLMULQDQ one is parallelized only
  in the combined GHASH + AES-CTR, and the AVX512 one uses schoolbook
  multiplication while the others use Karatsuba multiplication.

The main problem is that the AES-GCM library isn't properly optimized.
Solving that requires migrating the GHASH and AES-GCM code in
arch/x86/crypto/aes-gcm-*.S to lib/crypto/ and making the AES-GCM
assembly code use the same GHASH key struct as the GHASH library.

However, there's more that's worth fixing too:

- The PCLMULQDQ code paths lack full parallelization of GHASH.

- POLYVAL lacks VPCLMULQDQ optimization, so HCTR2 isn't properly
  optimized on recent x86_64 CPUs.  Yet, POLYVAL is nearly identical to
  GHASH.  If the code is structured properly, we can easily optimize
  both together.  (Indeed, this was one of the reasons to have a single
  gf128hash module instead of separate ghash and polyval.)

- POLYVAL is unoptimized on CPUs without AVX support.  This isn't too
  important, but it's another inconsistency.

- POLYVAL uses schoolbook multiplication, whereas the PCLMULQDQ
  optimized GHASH code uses Karatsuba multiplication.  Again, these
  algorithms are nearly identical, so if one strategy is better it
  should be used for both.  As I determined earlier when I wrote
  aes-gcm-aesni-x86_64.S, Karatsuba seems like a better choice, since it
  helps on AMD CPUs as well as older Intel CPUs, and with the narrow
  128-bit vectors there's easily space for the XOR'd key powers.

This commit begins the process of fixing this.  Specifically, it handles
the PCLMULQDQ (non-VPCLMULQDQ) case: it introduces a shared
'struct gf128hash_key_x86' (208 bytes, growing 'struct ghash_key' from
16 bytes and 'struct polyval_key' from 128 bytes on x86_64) and shared
CPU feature predicates in lib/crypto/x86/gf128hash-cpu.h, and replaces
ghash-pclmul.S and polyval-pclmul-avx.S with a new file
gf128hash-pclmul.S which provides:

- gf128hash_mul_pclmul{,_avx}()
- {ghash,polyval}_preparekey_pclmul{,_avx}()
- {ghash,polyval}_blocks_pclmul{,_avx}()

The file is derived from aes-gcm-aesni-x86_64.S, so it inherits its
copyright and license.

The following implementation choices are made:

- The AVX and non-AVX code is mostly unified, as is the GHASH and
  POLYVAL code.

- Key powers H^8 through H^1 are precomputed, and up to 8 blocks are
  processed in parallel with a single deferred reduction.  (This is like
  polyval-pclmul-avx.S and the combined GHASH + AES-CTR code in
  aes-gcm-aesni-x86_64.S.)

- Bulk data processing is optimized with Karatsuba multiplication and
  the two-multiplication reduction algorithm (multiplication-less
  reduction isn't used).  H^1 * x^-64 mod G(x) is precomputed and stored
  in key->h_times_xm64 so that both the key-power loop and single-block
  multiplications (gf128hash_mul_pclmul{,_avx}() and the nblocks == 1
  path) need only a single reduction step.

Since parts of the key structs are now initialized in assembly code,
make CRYPTO_LIB_GF128HASH_ARCH depend on !KMSAN.

Benchmark results on AMD Ryzen 9 9950X (Zen 5) using ghash_kunit and
polyval_kunit:

    Length   GHASH before  GHASH after   POLYVAL before  POLYVAL after
    ------   ------------  -----------   --------------  -------------
         1        99 MB/s     129 MB/s          98 MB/s       131 MB/s
        16      1287 MB/s    2105 MB/s        1650 MB/s      2278 MB/s
        64      1694 MB/s    5881 MB/s        5646 MB/s      6015 MB/s
       127      1792 MB/s    6017 MB/s        5612 MB/s      6161 MB/s
       128      1791 MB/s    8796 MB/s        7513 MB/s      8726 MB/s
       200      1758 MB/s    7658 MB/s        6815 MB/s      7728 MB/s
       256      1865 MB/s   10651 MB/s        8744 MB/s     10620 MB/s
       511      1897 MB/s   10212 MB/s        8711 MB/s     10478 MB/s
       512      1897 MB/s   11991 MB/s        9653 MB/s     12082 MB/s
      1024      1916 MB/s   13081 MB/s       10250 MB/s     12857 MB/s
      3173      1921 MB/s   13096 MB/s       10400 MB/s     13118 MB/s
      4096      1919 MB/s   13535 MB/s       10490 MB/s     13351 MB/s
     16384      1928 MB/s   13446 MB/s       10689 MB/s     13233 MB/s

Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 include/crypto/gf128hash.h          |  24 +-
 lib/crypto/Kconfig                  |   2 +-
 lib/crypto/Makefile                 |   3 +-
 lib/crypto/x86/gf128hash-cpu.h      |  26 ++
 lib/crypto/x86/gf128hash-pclmul.S   | 559 ++++++++++++++++++++++++++++
 lib/crypto/x86/gf128hash.h          | 225 +++++++----
 lib/crypto/x86/ghash-pclmul.S       | 127 -------
 lib/crypto/x86/polyval-pclmul-avx.S | 319 ----------------
 8 files changed, 766 insertions(+), 519 deletions(-)
 create mode 100644 lib/crypto/x86/gf128hash-cpu.h
 create mode 100644 lib/crypto/x86/gf128hash-pclmul.S
 delete mode 100644 lib/crypto/x86/ghash-pclmul.S
 delete mode 100644 lib/crypto/x86/polyval-pclmul-avx.S

diff --git a/include/crypto/gf128hash.h b/include/crypto/gf128hash.h
index 41c557d559655..c8b523a2d33cf 100644
--- a/include/crypto/gf128hash.h
+++ b/include/crypto/gf128hash.h
@@ -34,12 +34,29 @@ struct polyval_elem {
 	};
 };
 
+/* Format of struct ghash_key and struct polyval_key on x86_64 */
+struct gf128hash_key_x86 {
+	/* Powers of the hash key H^8 through H^1, in POLYVAL format */
+	struct polyval_elem h_powers[8];
+	/* Halves of each entry of @h_powers XOR'd together */
+	__le64 h_powers_xored[8];
+	/*
+	 * H^1 * x^-64 mod G(x) in POLYVAL format.  This is used to optimize
+	 * single-block multiplications using 1-step reduction.
+	 */
+	struct polyval_elem h_times_xm64;
+};
+
 /**
  * struct ghash_key - Prepared key for GHASH
  *
  * Use ghash_preparekey() to initialize this.
  */
 struct ghash_key {
+#if defined(CONFIG_CRYPTO_LIB_GF128HASH_ARCH) && defined(CONFIG_X86_64)
+	/** @k: Prepared key in x86_64 format */
+	struct gf128hash_key_x86 k;
+#else
 #if defined(CONFIG_CRYPTO_LIB_GF128HASH_ARCH) && defined(CONFIG_PPC64)
 	/** @htable: GHASH key format used by the POWER8 assembly code */
 	u64 htable[4][2];
@@ -50,6 +67,7 @@ struct ghash_key {
 #endif
 	/** @h: The hash key H, in POLYVAL format */
 	struct polyval_elem h;
+#endif
 };
 
 /**
@@ -63,8 +81,10 @@ struct ghash_key {
  * exponentiation repeats the POLYVAL dot operation, with its "extra" x^-128.
  */
 struct polyval_key {
-#if defined(CONFIG_CRYPTO_LIB_GF128HASH_ARCH) && \
-	(defined(CONFIG_ARM64) || defined(CONFIG_X86))
+#if defined(CONFIG_CRYPTO_LIB_GF128HASH_ARCH) && defined(CONFIG_X86_64)
+	/** @k: Prepared key in x86_64 format */
+	struct gf128hash_key_x86 k;
+#elif defined(CONFIG_CRYPTO_LIB_GF128HASH_ARCH) && defined(CONFIG_ARM64)
 	/** @h_powers: Powers of the hash key H^8 through H^1 */
 	struct polyval_elem h_powers[8];
 #else
diff --git a/lib/crypto/Kconfig b/lib/crypto/Kconfig
index 4644dee78ae3d..1a5ca64097568 100644
--- a/lib/crypto/Kconfig
+++ b/lib/crypto/Kconfig
@@ -150,7 +150,7 @@ config CRYPTO_LIB_GF128HASH
 
 config CRYPTO_LIB_GF128HASH_ARCH
 	bool
-	depends on CRYPTO_LIB_GF128HASH && !UML
+	depends on CRYPTO_LIB_GF128HASH && !UML && !KMSAN
 	default y if ARM && KERNEL_MODE_NEON
 	default y if ARM64
 	default y if PPC64 && VSX
diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile
index 5ddf64ce1d453..5b458b6f20e32 100644
--- a/lib/crypto/Makefile
+++ b/lib/crypto/Makefile
@@ -42,8 +42,7 @@ OBJECT_FILES_NON_STANDARD_powerpc/ghashp8-ppc.o := y
 endif
 
 libgf128hash-$(CONFIG_RISCV) += riscv/ghash-riscv64-zvkg.o
-libgf128hash-$(CONFIG_X86) += x86/ghash-pclmul.o \
-			      x86/polyval-pclmul-avx.o
+libgf128hash-$(CONFIG_X86_64) += x86/gf128hash-pclmul.o
 endif # CONFIG_CRYPTO_LIB_GF128HASH_ARCH
 
 # clean-files must be defined unconditionally
diff --git a/lib/crypto/x86/gf128hash-cpu.h b/lib/crypto/x86/gf128hash-cpu.h
new file mode 100644
index 0000000000000..157da0a49c416
--- /dev/null
+++ b/lib/crypto/x86/gf128hash-cpu.h
@@ -0,0 +1,26 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * This header contains the x86_64 gf128hash CPU feature predicates and some
+ * internal functions, so that the x86_64 AES-GCM code can reuse them.
+ *
+ * Copyright 2026 Google LLC
+ */
+#ifndef _LIB_CRYPTO_X86_GF128HASH_CPU_H
+#define _LIB_CRYPTO_X86_GF128HASH_CPU_H
+
+#include <crypto/gf128hash.h>
+#include <linux/cpufeature.h>
+
+static inline bool gf128hash_use_pclmul(void)
+{
+	return IS_ENABLED(CONFIG_X86_64) &&
+	       cpu_feature_enabled(X86_FEATURE_PCLMULQDQ) &&
+	       cpu_feature_enabled(X86_FEATURE_SSSE3);
+}
+
+static inline bool gf128hash_use_pclmul_avx(void)
+{
+	return gf128hash_use_pclmul() && cpu_feature_enabled(X86_FEATURE_AVX);
+}
+
+#endif /* _LIB_CRYPTO_X86_GF128HASH_CPU_H */
diff --git a/lib/crypto/x86/gf128hash-pclmul.S b/lib/crypto/x86/gf128hash-pclmul.S
new file mode 100644
index 0000000000000..7bb0a25b9df02
--- /dev/null
+++ b/lib/crypto/x86/gf128hash-pclmul.S
@@ -0,0 +1,559 @@
+/* SPDX-License-Identifier: Apache-2.0 OR BSD-2-Clause */
+//
+// Accelerated GHASH and POLYVAL implementation with PCLMULQDQ and AVX
+//
+// Copyright 2024 Google LLC
+//
+// Author: Eric Biggers <ebiggers@google.com>
+//
+//------------------------------------------------------------------------------
+//
+// This file is dual-licensed, meaning that you can use it under your choice of
+// either of the following two licenses:
+//
+// Licensed under the Apache License 2.0 (the "License").  You may obtain a copy
+// of the License at
+//
+//	http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// or
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+//    this list of conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+//
+//------------------------------------------------------------------------------
+//
+// This file implements GHASH and POLYVAL using PCLMULQDQ on 128-bit vectors
+// (xmm registers).  Two variants are generated from the same macros:
+//
+// - *_pclmul: non-VEX instructions (PCLMULQDQ, plus SSSE3 which all real CPUs
+//   with PCLMULQDQ have)
+// - *_pclmul_avx: VEX-coded 128-bit instructions (PCLMULQDQ + AVX + SSSE3),
+//   avoiding extra movdqa instructions and AVX-SSE transition penalties
+//
+// This file also documents the math shared with gf128hash-vpclmul-avx2.S and
+// gf128hash-vpclmul-avx512.S.
+//
+// Mathematical background
+// -----------------------
+//
+// GHASH (NIST SP 800-38D) and POLYVAL (RFC 8452) are polynomial evaluation
+// hashes over GF(2^128).  Each 16-byte block represents a polynomial of degree
+// < 128 over GF(2) (so polynomial addition is XOR), and each message block M_i
+// updates the accumulator by adding M_i and multiplying by the key H.  GHASH
+// and POLYVAL differ only in field representation and multiplication:
+//
+// - POLYVAL uses LSB-first bit order: bit j of byte i (bit 0 = LSB, bit 7 =
+//   MSB) is the coefficient of x^(8i + j).  The modulus is G(x) = x^128 + x^127
+//   + x^126 + x^121 + 1, and multiplication is Montgomery multiplication,
+//   updating acc to dot(acc + M_i, H) where:
+//
+//	dot(A, B) = A * B * x^-128  (mod G(x))
+//
+// - GHASH uses MSB-first bit order: bit j of byte i is the coefficient of
+//   x^(8i + 7 - j).  The modulus is F(x) = x^128 + x^7 + x^2 + x + 1, and
+//   multiplication is ordinary, updating acc to (acc + M_i) * H mod F(x).
+//
+// However, GHASH is difficult to implement in the way it's described above,
+// since the MSB-first bit order is very inconvenient.  Instead, this code
+// implements GHASH via POLYVAL, by re-expressing each GHASH computation as an
+// equivalent POLYVAL computation.
+//
+// Reversing the 16 bytes of a GHASH block A (without reversing bits within each
+// byte) moves byte i to 15 - i.  Read in POLYVAL's representation, bit j of
+// byte 15 - i is the coefficient of x^(8*(15 - i) + j) =
+// x^(127 - (8i + 7 - j)), so the resulting POLYVAL polynomial is:
+//
+//	ByteReverse(A) = x^127 * A(x^-1)
+//
+// Now let A(x) * B(x) = Q(x) * F(x) + R(x), where R = A * B mod F(x) and
+// deg(Q) <= 126.  Since G(x) = x^128 * F(x^-1) and x^126 * Q(x^-1) is a
+// polynomial:
+//
+//	ByteReverse(A) * ByteReverse(B)
+//    = x^254 * A(x^-1) * B(x^-1)
+//    = x^254 * (Q(x^-1) * F(x^-1) + R(x^-1))
+//    = (x^126 * Q(x^-1)) * (x^128 * F(x^-1)) + x^127 * (x^127 * R(x^-1))
+//    = (x^126 * Q(x^-1)) * G(x) + x^127 * ByteReverse(R)
+//    = x^127 * ByteReverse(A * B mod F(x))  (mod G(x))
+//
+// Pre-multiplying ByteReverse(H) by x cancels the x^127 * x^-128 = x^-1 factor
+// when using dot():
+//
+//	dot(ByteReverse(A), x * ByteReverse(H))
+//    = ByteReverse(A) * (x * ByteReverse(H)) * x^-128  (mod G(x))
+//    = ByteReverse(A) * ByteReverse(H) * x^-127        (mod G(x))
+//    = ByteReverse(A * H mod F(x))                     (mod G(x))
+//
+// Since ByteReverse is linear over GF(2), GHASH is computed with POLYVAL
+// arithmetic by keeping the accumulator in POLYVAL form, byte-reversing each
+// message block, replacing H with x * ByteReverse(H) mod G(x), and
+// byte-reversing the final accumulator (done in C by polyval_acc_to_ghash()).
+//
+// Reduction
+// ---------
+//
+// Since G(x) = x^64 * (x^64 + x^63 + x^62 + x^57) + 1, we have
+// x^-64 = x^64 + x^63 + x^62 + x^57 (mod G(x)).  For a 128-bit polynomial
+// P = P_L + P_H * x^64 (with 64-bit halves P_L and P_H):
+//
+//	P * x^-64 = P_H + P_L * x^64 + P_L * (x^63 + x^62 + x^57)  (mod G(x))
+//
+// This is a swap of P's 64-bit halves (pshufd $0x4e) plus one 64x64=>128-bit
+// carryless multiply of P_L by .Lgfpoly, yielding a reduced result (degree <
+// 128).
+//
+// For dot(A, B), the 256-bit product A * B = LO + MI * x^64 + HI * x^128
+// (with overlapping 128-bit parts LO = A_L * B_L, MI = A_L * B_H + A_H * B_L,
+// and HI = A_H * B_H) is multiplied by x^-128 in two steps: MI += LO * x^-64,
+// then HI += MI * x^-64, leaving dot(A, B) in HI.
+//
+// Implementation notes
+// --------------------
+//
+// - Aggregation: To hide multiply-and-reduce latency, key powers H^8..H^1
+//   (H^1 = H in POLYVAL format, H^k = dot(H^(k-1), H^1)) are precomputed, and
+//   8 blocks are processed per reduction:
+//
+//	acc = dot(acc + M_0, H^8) + dot(M_1, H^7) + ... + dot(M_7, H^1)
+//
+//   The 256-bit products are summed and reduced once per 8 blocks.  The inner
+//   loop is kept rolled for code size; out-of-order execution overlaps it.
+//
+// - Karatsuba multiplication: Multi-block strides compute
+//   MI = (A_L + A_H) * (B_L + B_H) + LO + HI, with (H^k)_L + (H^k)_H
+//   precomputed in key->h_powers_xored and "+ LO + HI" deferred to the end of
+//   the stride.  Relative to schoolbook, this saves 1 pclmulqdq per block (plus
+//   2 movdqa in *_pclmul) at the cost of 1 64-bit load, 1 pshufd, and 0.25 pxor
+//   per block in the 8-block loop.  This wins on AMD and older Intel CPUs and
+//   breaks even on newer Intel CPUs.
+//
+// - Reduction uses 2 pclmulqdq instructions (0.25 per block in the 8-block
+//   loop), which is faster than a shift/XOR-only reduction.
+//
+// - 1-step reduction for single-block multiplies and preparekey: Precomputing
+//   A * x^-64 mod G(x) lets dot(A, B) skip one reduction step.  preparekey
+//   precomputes H^1 * x^-64 mod G(x) for computing H^2..H^8 and stores it in
+//   key->h_times_xm64 for gf128hash_mul_pclmul{,_avx} and the 1-block path in
+//   {ghash,polyval}_blocks_pclmul{,_avx}.
+
+#include <linux/linkage.h>
+
+.section .rodata
+	// Keep the 16-byte constants 16-byte aligned for non-VEX SSE memory
+	// operands (pshufb, movdqa, pand).
+.p2align 4
+
+	// pshufb mask that reverses the order of the bytes in a 16-byte block
+.Lbswap_mask:
+	.octa	0x000102030405060708090a0b0c0d0e0f
+
+	// Mask for multiplying by x mod G(x): G(x) - x^128 = x^127 + x^126 +
+	// x^121 + 1 (bits 127, 126, 121, and 0), and bit 64 for the carry from
+	// bit 63 that paddq doesn't propagate
+.Lgfpoly_and_internal_carrybit:
+	.octa	0xc2000000000000010000000000000001
+
+	// (G(x) - x^128 - 1) / x^64 = x^63 + x^62 + x^57, the constant used to
+	// multiply by x^-64 mod G(x)
+.Lgfpoly:
+	.quad	0xc200000000000000
+
+// Offsets in struct gf128hash_key_x86, using the 8-power non-permuted layout.
+// h_powers[0..7] holds H^8..H^1, h_powers_xored[i] holds the XOR of the two
+// 64-bit halves of h_powers[i], and h_times_xm64 holds H^1 * x^-64 mod G(x).
+#define OFFSETOF_H_POWERS	0
+#define OFFSETOFEND_H_POWERS	128
+#define OFFSETOF_H_POWERS_XORED	128
+#define OFFSETOF_H_TIMES_XM64	192
+
+.text
+
+// Do a vpclmulqdq, or fall back to a movdqa and a pclmulqdq.  The fallback
+// assumes that \src1 and \dst are distinct registers.
+.macro	_vpclmulqdq	imm, src1, src2, dst
+.if USE_AVX
+	vpclmulqdq	\imm, \src1, \src2, \dst
+.else
+	movdqa		\src2, \dst
+	pclmulqdq	\imm, \src1, \dst
+.endif
+.endm
+
+// Set \b = dot(\a, \b), given \a_times_xm64 = \a * x^-64 mod G(x).  Letting
+// c = \a_times_xm64, this uses:
+//
+//	a * b * x^-128 = (a * b_H + c * b_L) * x^-64
+//		       = (MI + HI * x^64) * x^-64
+//		       = HI + MI * x^-64  (mod G(x))
+//
+// where MI = a_L * b_H + c_L * b_L and HI = a_H * b_H + c_H * b_L.  So only
+// one reduction step is needed, to fold MI into HI.  \gfpoly must contain
+// .Lgfpoly in its low qword.  Clobbers \t0 and \t1.  All operands must be
+// distinct registers.
+.macro	_gf128hash_mul	a, a_times_xm64, b, gfpoly, t0, t1
+	_vpclmulqdq	$0x01, \a, \b, \t0		// a_L * b_H
+	_vpclmulqdq	$0x00, \a_times_xm64, \b, \t1	// (a*x^-64)_L * b_L
+	pxor		\t1, \t0			// MI
+	_vpclmulqdq	$0x11, \a, \b, \t1		// a_H * b_H
+	pclmulqdq	$0x10, \a_times_xm64, \b	// (a*x^-64)_H * b_L
+	pxor		\t1, \b				// HI
+	pshufd		$0x4e, \t0, \t1			// MI_H + MI_L * x^64
+	pclmulqdq	$0x00, \gfpoly, \t0		// MI_L*(x^63+x^62+x^57)
+	pxor		\t1, \b				// Fold MI into HI (1)
+	pxor		\t0, \b				// Fold MI into HI (2)
+.endm
+
+// Reduce the 256-bit product LO + MI * x^64 + HI * x^128 given in \lo, \mi,
+// and \hi: multiply it by x^-128 mod G(x) and store the 128-bit result in \hi.
+// This is done in two steps, MI += LO * x^-64 then HI += MI * x^-64.  \gfpoly
+// must contain .Lgfpoly in its low qword.  Clobbers \lo, \mi, and \tmp.  All
+// operands must be distinct registers.
+.macro	_gf128hash_reduce	lo, mi, hi, gfpoly, tmp
+	pshufd		$0x4e, \lo, \tmp		// LO_H + LO_L * x^64
+	pclmulqdq	$0x00, \gfpoly, \lo		// LO_L*(x^63+x^62+x^57)
+	pxor		\tmp, \mi			// Fold LO into MI (1)
+	pxor		\lo, \mi			// Fold LO into MI (2)
+	pshufd		$0x4e, \mi, \tmp		// MI_H + MI_L * x^64
+	pclmulqdq	$0x00, \gfpoly, \mi		// MI_L*(x^63+x^62+x^57)
+	pxor		\tmp, \hi			// Fold MI into HI (1)
+	pxor		\mi, \hi			// Fold MI into HI (2)
+.endm
+
+// void {ghash,polyval}_preparekey_pclmul{,_avx}(struct gf128hash_key_x86 *key,
+//						 const u8 raw_key[16]);
+//
+// Given the raw GHASH key (\is_ghash=1) or POLYVAL key (\is_ghash=0), set:
+// - key->h_powers[0..7] to H^8..H^1 in POLYVAL format
+// - key->h_powers_xored[i] to the XOR of the two 64-bit halves of h_powers[i]
+// - key->h_times_xm64 to H^1 * x^-64 mod G(x)
+.macro	_gf128hash_preparekey	is_ghash
+	.set	KEY,		%rdi
+	.set	RAW_KEY,	%rsi
+	// %rax is used as a loop/offset register.
+	.set	TMP0,		%xmm0
+	.set	TMP1,		%xmm1
+	.set	H_CUR,		%xmm2
+	.set	H_POW1,		%xmm3
+	.set	H_POW1_XM64,	%xmm4
+	.set	GFPOLY,		%xmm5
+
+	movdqu		(RAW_KEY), H_POW1
+.if \is_ghash
+	// Convert the GHASH key to POLYVAL format: byte-reverse it, then
+	// multiply it by x mod G(x).  Multiplying by x is a left shift by 1
+	// bit, then an XOR of G(x) - x^128 if bit 127 was set.  However,
+	// there's no instruction that shifts a 128-bit value by 1 bit.
+	// Instead, use paddq to shift each 64-bit half, then add the carry from
+	// bit 63 to bit 64.  'pshufd $0xd3' and 'psrad $31' set dwords 0 and 3
+	// to copies of bit 127 and dword 2 to copies of bit 63; pand then
+	// selects the bits to XOR in from G(x) - x^128 and the carry bit.
+	pshufb		.Lbswap_mask(%rip), H_POW1
+	pshufd		$0xd3, H_POW1, TMP0
+	psrad		$31, TMP0
+	paddq		H_POW1, H_POW1
+	pand		.Lgfpoly_and_internal_carrybit(%rip), TMP0
+	pxor		TMP0, H_POW1
+.endif
+
+	// Store H^1 in h_powers[7].
+	movdqu		H_POW1, OFFSETOF_H_POWERS+7*16(KEY)
+
+	// Compute H_POW1_XM64 = H^1 * x^-64 mod G(x) = (H^1)_H + (H^1)_L * x^64
+	// + (H^1)_L * (x^63 + x^62 + x^57), and store it in h_times_xm64.
+	movq		.Lgfpoly(%rip), GFPOLY
+	pshufd		$0x4e, H_POW1, TMP0
+	_vpclmulqdq	$0x00, GFPOLY, H_POW1, H_POW1_XM64
+	pxor		TMP0, H_POW1_XM64
+	movdqu		H_POW1_XM64, OFFSETOF_H_TIMES_XM64(KEY)
+
+	// Store the XOR of the halves of H^1 in h_powers_xored[7], reusing the
+	// swapped halves of H^1 still in TMP0.
+	pxor		H_POW1, TMP0
+	movq		TMP0, OFFSETOF_H_POWERS_XORED+7*8(KEY)
+
+	// Compute H^2..H^8 and store them in h_powers[6..0], and store the XORs
+	// of their halves in h_powers_xored[6..0].  %eax (zero-extended to
+	// %rax) counts down from 6*8 to 0 by 8; %rax is the offset into
+	// h_powers_xored, and 2*%rax is the offset into h_powers.
+	movdqa		H_POW1, H_CUR
+	mov		$6*8, %eax
+.Lpreparekey_next\@:
+	_gf128hash_mul	H_POW1, H_POW1_XM64, H_CUR, GFPOLY, TMP0, TMP1
+	movdqu		H_CUR, OFFSETOF_H_POWERS(KEY,%rax,2)
+	pshufd		$0x4e, H_CUR, TMP0
+	pxor		H_CUR, TMP0
+	movq		TMP0, OFFSETOF_H_POWERS_XORED(KEY,%rax)
+	sub		$8, %eax
+	jge		.Lpreparekey_next\@
+
+	RET
+.endm
+
+// void gf128hash_mul_pclmul{,_avx}(struct polyval_elem *acc,
+//				    const struct gf128hash_key_x86 *key);
+//
+// Set *acc = dot(*acc, H^1) using the precomputed H^1 and H^1 * x^-64 in @key.
+// The C code uses this to multiply the accumulator by H^1 after XOR'ing in a
+// buffered (possibly partial) block.  Works with both the 8-power and 16-power
+// key layouts, so no separate AVX2 or AVX512 version is needed.
+.macro	_gf128hash_mul_func
+	.set	ACC_PTR,	%rdi
+	.set	KEY,		%rsi
+	.set	TMP0,		%xmm0
+	.set	TMP1,		%xmm1
+	.set	ACC,		%xmm2
+	.set	H_POW1,		%xmm3
+	.set	H_POW1_XM64,	%xmm4
+	.set	GFPOLY,		%xmm5
+
+	movdqu		(ACC_PTR), ACC
+	movdqu		OFFSETOFEND_H_POWERS-16(KEY), H_POW1
+	movdqu		OFFSETOF_H_TIMES_XM64(KEY), H_POW1_XM64
+	movq		.Lgfpoly(%rip), GFPOLY
+	_gf128hash_mul	H_POW1, H_POW1_XM64, ACC, GFPOLY, TMP0, TMP1
+	movdqu		ACC, (ACC_PTR)
+	RET
+.endm
+
+// void
+// {ghash,polyval}_blocks_pclmul{,_avx}(struct polyval_elem *acc,
+//					const struct gf128hash_key_x86 *key,
+//					const u8 *data, size_t nblocks);
+//
+// Update the POLYVAL-format accumulator @acc with @nblocks >= 1 full 16-byte
+// blocks from @data.  If \bswap_data=1 (GHASH), each block is byte-reversed to
+// convert it to POLYVAL format.
+.macro	_gf128hash_blocks	bswap_data
+	.set	ACC_PTR,		%rdi
+	.set	KEY,			%rsi
+	.set	DATA,			%rdx
+	.set	NBLOCKS,		%rcx
+	.set	NBLOCKS_32,		%ecx
+	.set	POWERS_XORED_PTR,	%r8
+
+	// %rax and %r9d are used as loop/temporary registers.
+	.set	TMP0,		%xmm0
+	.set	TMP1,		%xmm1
+	.set	TMP2,		%xmm2
+	.set	LO,		%xmm3
+	.set	MI,		%xmm4
+	.set	ACC,		%xmm5
+	.set	BSWAP_MASK,	%xmm6
+	.set	GFPOLY,		%xmm7
+
+.if \bswap_data
+	movdqa		.Lbswap_mask(%rip), BSWAP_MASK
+.endif
+	movdqu		(ACC_PTR), ACC
+	movq		.Lgfpoly(%rip), GFPOLY
+
+	// Handle nblocks == 1 specially.  This case is common (e.g. for 1-block
+	// associated data, the incremental AES-GCM lengths block, and the HCTR2
+	// length and tweak blocks), and the stride loop below requires at least
+	// 2 blocks.
+	cmp		$1, NBLOCKS
+	je		.Lblocks_1x\@
+
+	// Process the blocks in strides of 8, then process any remaining 2..7
+	// blocks as one final stride (or 1 remaining block via .Lblocks_1x).
+	// For an n-block stride of POLYVAL-format message blocks M_0..M_{n-1},
+	// let B_0 = M_0 + acc, B_i = M_i for 1 <= i < n, and K_i = H^(n-i).
+	// Compute the unreduced sum of the products K_i * B_i using Karatsuba
+	// multiplication:
+	//
+	//	LO = sum (K_i)_L * (B_i)_L
+	//	HI = sum (K_i)_H * (B_i)_H
+	//	MI = sum (K_i)_x * (B_i)_x + LO + HI
+	//
+	// where A_x = A_L + A_H.  HI is accumulated in ACC, and the "+ LO + HI"
+	// term of MI is added just once at the end.  Then (LO, MI, HI) is
+	// reduced into ACC.
+	//
+	// In the loop, %rax = 8*i, so K_i is at OFFSETOF_H_POWERS(KEY,%rax,2),
+	// M_i is at (DATA,%rax,2), and (K_i)_x is at (POWERS_XORED_PTR,%rax).
+	// %r9d = 8*(n-1) is the final value of %rax.  The h_powers_xored
+	// entries are loaded with movq instead of being used as 16-byte
+	// (v)pclmulqdq memory operands, since the entries are 8 bytes wide and
+	// non-VEX pclmulqdq also requires 16-byte alignment (while struct
+	// gf128hash_key_x86 is only 8-byte aligned).
+	lea		OFFSETOF_H_POWERS_XORED(KEY), POWERS_XORED_PTR
+	sub		$8, NBLOCKS
+	jb		.Lblocks_tail\@
+	mov		$7*8, %r9d
+.Lblocks_karatsuba\@:
+	// i = 0: XOR ACC into M_0 to form B_0, and initialize LO, MI, and HI.
+	xor		%eax, %eax
+	movdqu		OFFSETOF_H_POWERS(KEY), TMP0	// K_0 = H^n
+	movdqu		(DATA), TMP1		// M_0 (before bswap)
+.if \bswap_data
+	pshufb		BSWAP_MASK, TMP1
+.endif
+	pxor		TMP1, ACC		// B_0 = M_0 + ACC
+	pshufd		$0x4e, ACC, MI
+	pxor		ACC, MI			// (B_0)_x = (B_0)_L + (B_0)_H
+	_vpclmulqdq	$0x00, TMP0, ACC, LO	// LO = (K_0)_L * (B_0)_L
+	pclmulqdq	$0x11, TMP0, ACC	// HI = (K_0)_H * (B_0)_H
+	movq		(POWERS_XORED_PTR), TMP1 // (K_0)_x = (K_0)_L + (K_0)_H
+	pclmulqdq	$0x00, TMP1, MI		// MI = (K_0)_x * (B_0)_x
+
+	// i = 1..n-1 (B_i = M_i): accumulate into LO, MI, and HI.
+.Lblocks_karatsuba_loop\@:
+	add		$8, %eax
+	movdqu		OFFSETOF_H_POWERS(KEY,%rax,2), TMP0 // K_i = H^(n-i)
+	movdqu		(DATA,%rax,2), TMP1	// M_i (before bswap)
+.if \bswap_data
+	pshufb		BSWAP_MASK, TMP1
+.endif
+	_vpclmulqdq	$0x00, TMP0, TMP1, TMP2
+	pxor		TMP2, LO		// LO += (K_i)_L * (M_i)_L
+	pshufd		$0x4e, TMP1, TMP2
+	pxor		TMP1, TMP2		// (M_i)_x = (M_i)_L + (M_i)_H
+	pclmulqdq	$0x11, TMP0, TMP1
+	pxor		TMP1, ACC		// HI += (K_i)_H * (M_i)_H
+	movq		(POWERS_XORED_PTR,%rax), TMP1 // (K_i)_x
+	pclmulqdq	$0x00, TMP1, TMP2
+	pxor		TMP2, MI		// MI += (K_i)_x * (M_i)_x
+	cmp		%r9d, %eax
+	jne		.Lblocks_karatsuba_loop\@
+
+	// Finish MI, then reduce (LO, MI, HI) into ACC.
+	pxor		LO, MI
+	pxor		ACC, MI
+	_gf128hash_reduce LO, MI, ACC, GFPOLY, TMP2
+
+	sub		$-128, DATA	// DATA += 128 (compact imm8)
+	sub		$8, NBLOCKS
+	jae		.Lblocks_karatsuba\@
+
+.Lblocks_tail\@:
+	add		$8, NBLOCKS
+	jz		.Lblocks_done\@
+	cmp		$1, NBLOCKS
+	je		.Lblocks_1x\@
+
+	// 2 <= n = NBLOCKS <= 7 blocks remain.  Process them as one more stride
+	// that starts with K_0 = H^n = h_powers[8-n]: advance KEY by 16*(8-n)
+	// and POWERS_XORED_PTR by 8*(8-n), and set %r9d = 8*(n-1).  Set
+	// NBLOCKS = 0 so that after the stride, the sub $8 underflows into
+	// .Lblocks_tail, where add $8 yields 0 and jumps to .Lblocks_done
+	// (over-advancing DATA by 128 is harmless since it is no longer used).
+	lea		-8(,NBLOCKS,8), %r9d	// 8*(n-1)
+	mov		$7*8, %eax
+	sub		%r9d, %eax		// 8*(8-n)
+	add		%rax, POWERS_XORED_PTR	// POWERS_XORED_PTR += 8*(8-n)
+	lea		(KEY,%rax,2), KEY	// KEY += 16*(8-n)
+	xor		NBLOCKS_32, NBLOCKS_32
+	jmp		.Lblocks_karatsuba\@
+
+.Lblocks_1x\@:
+	// Process one block: ACC = dot(ACC + M_0, H^1), using H^1 and
+	// H^1 * x^-64 from KEY.
+	movdqu		(DATA), TMP0
+.if \bswap_data
+	pshufb		BSWAP_MASK, TMP0
+.endif
+	pxor		TMP0, ACC
+	movdqu		OFFSETOFEND_H_POWERS-16(KEY), TMP0	// H^1
+	movdqu		OFFSETOF_H_TIMES_XM64(KEY), TMP1	// H^1 * x^-64
+	_gf128hash_mul	TMP0, TMP1, ACC, GFPOLY, TMP2, LO
+
+.Lblocks_done\@:
+	movdqu		ACC, (ACC_PTR)
+	RET
+.endm
+
+.set	USE_AVX, 0
+SYM_FUNC_START(ghash_preparekey_pclmul)
+	_gf128hash_preparekey	1
+SYM_FUNC_END(ghash_preparekey_pclmul)
+SYM_FUNC_START(polyval_preparekey_pclmul)
+	_gf128hash_preparekey	0
+SYM_FUNC_END(polyval_preparekey_pclmul)
+SYM_FUNC_START(gf128hash_mul_pclmul)
+	_gf128hash_mul_func
+SYM_FUNC_END(gf128hash_mul_pclmul)
+SYM_FUNC_START(ghash_blocks_pclmul)
+	_gf128hash_blocks	1
+SYM_FUNC_END(ghash_blocks_pclmul)
+SYM_FUNC_START(polyval_blocks_pclmul)
+	_gf128hash_blocks	0
+SYM_FUNC_END(polyval_blocks_pclmul)
+
+.set	USE_AVX, 1
+
+// Re-encode the remaining SSE mnemonics as VEX.128 so *_pclmul_avx contains no
+// legacy SSE instructions.  Use vararg for instructions whose operand count
+// doesn't change so memory operands containing commas pass through intact.
+// (movq is only used for xmm<->memory transfers above, never for GPR moves.)
+.macro	movdqu args:vararg
+	vmovdqu		\args
+.endm
+.macro	movdqa args:vararg
+	vmovdqa		\args
+.endm
+.macro	movq args:vararg
+	vmovq		\args
+.endm
+.macro	pshufd args:vararg
+	vpshufd		\args
+.endm
+.macro	pxor a, b
+	vpxor		\a, \b, \b
+.endm
+.macro	pand a, b
+	vpand		\a, \b, \b
+.endm
+.macro	paddq a, b
+	vpaddq		\a, \b, \b
+.endm
+.macro	psrad a, b
+	vpsrad		\a, \b, \b
+.endm
+.macro	pshufb a, b
+	vpshufb		\a, \b, \b
+.endm
+.macro	pclmulqdq imm, a, b
+	vpclmulqdq	\imm, \a, \b, \b
+.endm
+
+SYM_FUNC_START(ghash_preparekey_pclmul_avx)
+	_gf128hash_preparekey	1
+SYM_FUNC_END(ghash_preparekey_pclmul_avx)
+SYM_FUNC_START(polyval_preparekey_pclmul_avx)
+	_gf128hash_preparekey	0
+SYM_FUNC_END(polyval_preparekey_pclmul_avx)
+SYM_FUNC_START(gf128hash_mul_pclmul_avx)
+	_gf128hash_mul_func
+SYM_FUNC_END(gf128hash_mul_pclmul_avx)
+SYM_FUNC_START(ghash_blocks_pclmul_avx)
+	_gf128hash_blocks	1
+SYM_FUNC_END(ghash_blocks_pclmul_avx)
+SYM_FUNC_START(polyval_blocks_pclmul_avx)
+	_gf128hash_blocks	0
+SYM_FUNC_END(polyval_blocks_pclmul_avx)
diff --git a/lib/crypto/x86/gf128hash.h b/lib/crypto/x86/gf128hash.h
index 5ef8f2f7b6f3c..9abdea7f9ba86 100644
--- a/lib/crypto/x86/gf128hash.h
+++ b/lib/crypto/x86/gf128hash.h
@@ -5,61 +5,143 @@
  * Copyright 2025 Google LLC
  */
 #include <asm/fpu/api.h>
-#include <linux/cpufeature.h>
+#include "gf128hash-cpu.h"
 
 #define NUM_H_POWERS 8
 
+/* The assembly code assumes the following offsets. */
+static_assert(sizeof_field(struct gf128hash_key_x86, h_powers) ==
+	      NUM_H_POWERS * sizeof(struct polyval_elem));
+static_assert(offsetof(struct gf128hash_key_x86, h_powers) == 0);
+static_assert(offsetof(struct gf128hash_key_x86, h_powers_xored) == 128);
+static_assert(offsetof(struct gf128hash_key_x86, h_times_xm64) == 192);
+static_assert(sizeof(struct gf128hash_key_x86) == 208);
+
 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_pclmul);
 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_pclmul_avx);
 
-asmlinkage void polyval_mul_pclmul(struct polyval_elem *a,
-				   const struct polyval_elem *b);
-asmlinkage void polyval_mul_pclmul_avx(struct polyval_elem *a,
-				       const struct polyval_elem *b);
+void gf128hash_mul_pclmul(struct polyval_elem *acc,
+			  const struct gf128hash_key_x86 *key);
+void gf128hash_mul_pclmul_avx(struct polyval_elem *acc,
+			      const struct gf128hash_key_x86 *key);
 
-asmlinkage void ghash_blocks_pclmul(struct polyval_elem *acc,
-				    const struct polyval_elem *key,
-				    const u8 *data, size_t nblocks);
-asmlinkage void polyval_blocks_pclmul_avx(struct polyval_elem *acc,
-					  const struct polyval_key *key,
-					  const u8 *data, size_t nblocks);
+void ghash_preparekey_pclmul(struct gf128hash_key_x86 *key,
+			     const u8 raw_key[GHASH_BLOCK_SIZE]);
+void ghash_preparekey_pclmul_avx(struct gf128hash_key_x86 *key,
+				 const u8 raw_key[GHASH_BLOCK_SIZE]);
+void polyval_preparekey_pclmul(struct gf128hash_key_x86 *key,
+			       const u8 raw_key[POLYVAL_BLOCK_SIZE]);
+void polyval_preparekey_pclmul_avx(struct gf128hash_key_x86 *key,
+				   const u8 raw_key[POLYVAL_BLOCK_SIZE]);
 
-#define polyval_preparekey_arch polyval_preparekey_arch
-static void polyval_preparekey_arch(struct polyval_key *key,
-				    const u8 raw_key[POLYVAL_BLOCK_SIZE])
+void ghash_blocks_pclmul(struct polyval_elem *acc,
+			 const struct gf128hash_key_x86 *key, const u8 *data,
+			 size_t nblocks);
+void ghash_blocks_pclmul_avx(struct polyval_elem *acc,
+			     const struct gf128hash_key_x86 *key,
+			     const u8 *data, size_t nblocks);
+void polyval_blocks_pclmul(struct polyval_elem *acc,
+			   const struct gf128hash_key_x86 *key, const u8 *data,
+			   size_t nblocks);
+void polyval_blocks_pclmul_avx(struct polyval_elem *acc,
+			       const struct gf128hash_key_x86 *key,
+			       const u8 *data, size_t nblocks);
+
+static __always_inline void
+__gf128hash_mul_x86_fpu(struct polyval_elem *acc,
+			const struct gf128hash_key_x86 *key)
+{
+	if (static_branch_likely(&have_pclmul_avx))
+		gf128hash_mul_pclmul_avx(acc, key);
+	else
+		gf128hash_mul_pclmul(acc, key);
+}
+
+static __always_inline void
+__ghash_blocks_x86_fpu(struct polyval_elem *acc,
+		       const struct gf128hash_key_x86 *key, const u8 *data,
+		       size_t nblocks)
+{
+	if (static_branch_likely(&have_pclmul_avx))
+		ghash_blocks_pclmul_avx(acc, key, data, nblocks);
+	else
+		ghash_blocks_pclmul(acc, key, data, nblocks);
+}
+
+/*
+ * Compute *out = *in * x^-64 mod G(x), where
+ * x^-64 = x^64 + x^63 + x^62 + x^57 (mod G(x)).
+ */
+static void polyval_mul_xm64_generic(struct polyval_elem *out,
+				     const struct polyval_elem *in)
 {
-	static_assert(ARRAY_SIZE(key->h_powers) == NUM_H_POWERS);
-	memcpy(&key->h_powers[NUM_H_POWERS - 1], raw_key, POLYVAL_BLOCK_SIZE);
-	if (static_branch_likely(&have_pclmul_avx) && irq_fpu_usable()) {
+	u64 lo = le64_to_cpu(in->lo);
+	u64 hi = le64_to_cpu(in->hi);
+
+	out->lo = cpu_to_le64(hi ^ (lo << 63) ^ (lo << 62) ^ (lo << 57));
+	out->hi = cpu_to_le64(lo ^ (lo >> 1) ^ (lo >> 2) ^ (lo >> 7));
+}
+
+static __always_inline void
+gf128hash_preparekey_x86(struct gf128hash_key_x86 *key, const u8 raw_key[16],
+			 bool is_ghash)
+{
+	if (static_branch_likely(&have_pclmul) && likely(irq_fpu_usable())) {
 		kernel_fpu_begin_mask(0);
-		for (int i = NUM_H_POWERS - 2; i >= 0; i--) {
-			key->h_powers[i] = key->h_powers[i + 1];
-			polyval_mul_pclmul_avx(
-				&key->h_powers[i],
-				&key->h_powers[NUM_H_POWERS - 1]);
+		if (static_branch_likely(&have_pclmul_avx)) {
+			if (is_ghash)
+				ghash_preparekey_pclmul_avx(key, raw_key);
+			else
+				polyval_preparekey_pclmul_avx(key, raw_key);
+		} else {
+			if (is_ghash)
+				ghash_preparekey_pclmul(key, raw_key);
+			else
+				polyval_preparekey_pclmul(key, raw_key);
 		}
 		kernel_fpu_end();
-	} else {
-		for (int i = NUM_H_POWERS - 2; i >= 0; i--) {
-			key->h_powers[i] = key->h_powers[i + 1];
-			polyval_mul_generic(&key->h_powers[i],
-					    &key->h_powers[NUM_H_POWERS - 1]);
-		}
+		return;
 	}
+	if (is_ghash)
+		ghash_key_to_polyval(raw_key, &key->h_powers[NUM_H_POWERS - 1]);
+	else
+		memcpy(&key->h_powers[NUM_H_POWERS - 1], raw_key,
+		       POLYVAL_BLOCK_SIZE);
+	for (int i = NUM_H_POWERS - 2; i >= 0; i--) {
+		key->h_powers[i] = key->h_powers[i + 1];
+		polyval_mul_generic(&key->h_powers[i],
+				    &key->h_powers[NUM_H_POWERS - 1]);
+	}
+	for (int i = 0; i < NUM_H_POWERS; i++)
+		key->h_powers_xored[i] = key->h_powers[i].lo ^
+					 key->h_powers[i].hi;
+	polyval_mul_xm64_generic(&key->h_times_xm64,
+				 &key->h_powers[NUM_H_POWERS - 1]);
 }
 
-static void polyval_mul_x86(struct polyval_elem *a,
-			    const struct polyval_elem *b)
+#define ghash_preparekey_arch ghash_preparekey_arch
+static void ghash_preparekey_arch(struct ghash_key *key,
+				  const u8 raw_key[GHASH_BLOCK_SIZE])
 {
-	if (static_branch_likely(&have_pclmul) && irq_fpu_usable()) {
+	gf128hash_preparekey_x86(&key->k, raw_key, true);
+}
+
+#define polyval_preparekey_arch polyval_preparekey_arch
+static void polyval_preparekey_arch(struct polyval_key *key,
+				    const u8 raw_key[POLYVAL_BLOCK_SIZE])
+{
+	gf128hash_preparekey_x86(&key->k, raw_key, false);
+}
+
+static void gf128hash_mul_x86(struct polyval_elem *acc,
+			      const struct gf128hash_key_x86 *key)
+{
+	if (static_branch_likely(&have_pclmul) && likely(irq_fpu_usable())) {
 		kernel_fpu_begin_mask(0);
-		if (static_branch_likely(&have_pclmul_avx))
-			polyval_mul_pclmul_avx(a, b);
-		else
-			polyval_mul_pclmul(a, b);
+		__gf128hash_mul_x86_fpu(acc, key);
 		kernel_fpu_end();
 	} else {
-		polyval_mul_generic(a, b);
+		polyval_mul_generic(acc, &key->h_powers[NUM_H_POWERS - 1]);
 	}
 }
 
@@ -67,67 +149,74 @@ static void polyval_mul_x86(struct polyval_elem *a,
 static void ghash_mul_arch(struct polyval_elem *acc,
 			   const struct ghash_key *key)
 {
-	polyval_mul_x86(acc, &key->h);
+	gf128hash_mul_x86(acc, &key->k);
 }
 
 #define polyval_mul_arch polyval_mul_arch
 static void polyval_mul_arch(struct polyval_elem *acc,
 			     const struct polyval_key *key)
 {
-	polyval_mul_x86(acc, &key->h_powers[NUM_H_POWERS - 1]);
+	gf128hash_mul_x86(acc, &key->k);
 }
 
-#define ghash_blocks_arch ghash_blocks_arch
-static void ghash_blocks_arch(struct polyval_elem *acc,
-			      const struct ghash_key *key,
-			      const u8 *data, size_t nblocks)
+static __always_inline void
+gf128hash_blocks_x86(struct polyval_elem *acc,
+		     const struct gf128hash_key_x86 *key, const u8 *data,
+		     size_t nblocks, bool is_ghash)
 {
-	if (static_branch_likely(&have_pclmul) && irq_fpu_usable()) {
+	if (static_branch_likely(&have_pclmul) && likely(irq_fpu_usable())) {
+		static_assert(GHASH_BLOCK_SIZE == POLYVAL_BLOCK_SIZE);
 		do {
-			/* Allow rescheduling every 4 KiB. */
+			/* Allow rescheduling every 32 KiB. */
 			size_t n = min_t(size_t, nblocks,
-					 4096 / GHASH_BLOCK_SIZE);
+					 32768 / GHASH_BLOCK_SIZE);
 
 			kernel_fpu_begin_mask(0);
-			ghash_blocks_pclmul(acc, &key->h, data, n);
+			if (is_ghash)
+				__ghash_blocks_x86_fpu(acc, key, data, n);
+			else if (static_branch_likely(&have_pclmul_avx))
+				polyval_blocks_pclmul_avx(acc, key, data, n);
+			else
+				polyval_blocks_pclmul(acc, key, data, n);
 			kernel_fpu_end();
 			data += n * GHASH_BLOCK_SIZE;
 			nblocks -= n;
 		} while (nblocks);
 	} else {
-		ghash_blocks_generic(acc, &key->h, data, nblocks);
+		if (is_ghash)
+			ghash_blocks_generic(acc,
+					     &key->h_powers[NUM_H_POWERS - 1],
+					     data, nblocks);
+		else
+			polyval_blocks_generic(acc,
+					       &key->h_powers[NUM_H_POWERS - 1],
+					       data, nblocks);
 	}
 }
 
+#define ghash_blocks_arch ghash_blocks_arch
+static void ghash_blocks_arch(struct polyval_elem *acc,
+			      const struct ghash_key *key, const u8 *data,
+			      size_t nblocks)
+{
+	gf128hash_blocks_x86(acc, &key->k, data, nblocks, true);
+}
+
 #define polyval_blocks_arch polyval_blocks_arch
 static void polyval_blocks_arch(struct polyval_elem *acc,
 				const struct polyval_key *key,
 				const u8 *data, size_t nblocks)
 {
-	if (static_branch_likely(&have_pclmul_avx) && irq_fpu_usable()) {
-		do {
-			/* Allow rescheduling every 4 KiB. */
-			size_t n = min_t(size_t, nblocks,
-					 4096 / POLYVAL_BLOCK_SIZE);
-
-			kernel_fpu_begin_mask(0);
-			polyval_blocks_pclmul_avx(acc, key, data, n);
-			kernel_fpu_end();
-			data += n * POLYVAL_BLOCK_SIZE;
-			nblocks -= n;
-		} while (nblocks);
-	} else {
-		polyval_blocks_generic(acc, &key->h_powers[NUM_H_POWERS - 1],
-				       data, nblocks);
-	}
+	gf128hash_blocks_x86(acc, &key->k, data, nblocks, false);
 }
 
 #define gf128hash_mod_init_arch gf128hash_mod_init_arch
 static void gf128hash_mod_init_arch(void)
 {
-	if (boot_cpu_has(X86_FEATURE_PCLMULQDQ)) {
-		static_branch_enable(&have_pclmul);
-		if (boot_cpu_has(X86_FEATURE_AVX))
-			static_branch_enable(&have_pclmul_avx);
-	}
+	if (!gf128hash_use_pclmul())
+		return;
+
+	if (gf128hash_use_pclmul_avx())
+		static_branch_enable(&have_pclmul_avx);
+	static_branch_enable(&have_pclmul);
 }
diff --git a/lib/crypto/x86/ghash-pclmul.S b/lib/crypto/x86/ghash-pclmul.S
deleted file mode 100644
index 6ffb5aea6063d..0000000000000
--- a/lib/crypto/x86/ghash-pclmul.S
+++ /dev/null
@@ -1,127 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0-only */
-/*
- * Accelerated GHASH implementation with Intel PCLMULQDQ-NI
- * instructions. This file contains accelerated part of ghash
- * implementation. More information about PCLMULQDQ can be found at:
- *
- * https://www.intel.com/content/dam/develop/external/us/en/documents/clmul-wp-rev-2-02-2014-04-20.pdf
- *
- * Copyright (c) 2009 Intel Corp.
- *   Author: Huang Ying <ying.huang@intel.com>
- *	     Vinodh Gopal
- *	     Erdinc Ozturk
- *	     Deniz Karakoyunlu
- */
-
-#include <linux/linkage.h>
-#include <asm/frame.h>
-
-.section	.rodata.cst16.bswap_mask, "aM", @progbits, 16
-.align 16
-.Lbswap_mask:
-	.octa 0x000102030405060708090a0b0c0d0e0f
-
-#define ACC	%xmm0
-#define KEY	%xmm1
-#define T1	%xmm2
-#define T2	%xmm3
-#define T3	%xmm4
-#define BSWAP	%xmm5
-#define IN1	%xmm6
-
-.text
-
-/*
- * __clmul_gf128mul_ble:	internal ABI
- * input:
- *	ACC:			operand1
- *	KEY:			operand2, hash_key << 1 mod poly
- * output:
- *	ACC:			operand1 * operand2 mod poly
- * changed:
- *	T1
- *	T2
- *	T3
- */
-SYM_FUNC_START_LOCAL(__clmul_gf128mul_ble)
-	movaps ACC, T1
-	pshufd $0b01001110, ACC, T2
-	pshufd $0b01001110, KEY, T3
-	pxor ACC, T2
-	pxor KEY, T3
-
-	pclmulqdq $0x00, KEY, ACC	# ACC = a0 * b0
-	pclmulqdq $0x11, KEY, T1	# T1 = a1 * b1
-	pclmulqdq $0x00, T3, T2		# T2 = (a1 + a0) * (b1 + b0)
-	pxor ACC, T2
-	pxor T1, T2			# T2 = a0 * b1 + a1 * b0
-
-	movaps T2, T3
-	pslldq $8, T3
-	psrldq $8, T2
-	pxor T3, ACC
-	pxor T2, T1			# <T1:ACC> is result of
-					# carry-less multiplication
-
-	# first phase of the reduction
-	movaps ACC, T3
-	psllq $1, T3
-	pxor ACC, T3
-	psllq $5, T3
-	pxor ACC, T3
-	psllq $57, T3
-	movaps T3, T2
-	pslldq $8, T2
-	psrldq $8, T3
-	pxor T2, ACC
-	pxor T3, T1
-
-	# second phase of the reduction
-	movaps ACC, T2
-	psrlq $5, T2
-	pxor ACC, T2
-	psrlq $1, T2
-	pxor ACC, T2
-	psrlq $1, T2
-	pxor T2, T1
-	pxor T1, ACC
-	RET
-SYM_FUNC_END(__clmul_gf128mul_ble)
-
-/*
- * void polyval_mul_pclmul(struct polyval_elem *a,
- *			   const struct polyval_elem *b)
- */
-SYM_FUNC_START(polyval_mul_pclmul)
-	FRAME_BEGIN
-	movups (%rdi), ACC
-	movups (%rsi), KEY
-	call __clmul_gf128mul_ble
-	movups ACC, (%rdi)
-	FRAME_END
-	RET
-SYM_FUNC_END(polyval_mul_pclmul)
-
-/*
- * void ghash_blocks_pclmul(struct polyval_elem *acc,
- *			    const struct polyval_elem *key,
- *			    const u8 *data, size_t nblocks)
- */
-SYM_FUNC_START(ghash_blocks_pclmul)
-	FRAME_BEGIN
-	movaps .Lbswap_mask(%rip), BSWAP
-	movups (%rdi), ACC
-	movups (%rsi), KEY
-.align 4
-.Lnext_block:
-	movups (%rdx), IN1
-	pshufb BSWAP, IN1
-	pxor IN1, ACC
-	call __clmul_gf128mul_ble
-	add $16, %rdx
-	dec %rcx
-	jnz .Lnext_block
-	movups ACC, (%rdi)
-	FRAME_END
-	RET
-SYM_FUNC_END(ghash_blocks_pclmul)
diff --git a/lib/crypto/x86/polyval-pclmul-avx.S b/lib/crypto/x86/polyval-pclmul-avx.S
deleted file mode 100644
index 7f739465ad35f..0000000000000
--- a/lib/crypto/x86/polyval-pclmul-avx.S
+++ /dev/null
@@ -1,319 +0,0 @@
-/* SPDX-License-Identifier: GPL-2.0 */
-/*
- * Copyright 2021 Google LLC
- */
-/*
- * This is an efficient implementation of POLYVAL using intel PCLMULQDQ-NI
- * instructions. It works on 8 blocks at a time, by precomputing the first 8
- * keys powers h^8, ..., h^1 in the POLYVAL finite field. This precomputation
- * allows us to split finite field multiplication into two steps.
- *
- * In the first step, we consider h^i, m_i as normal polynomials of degree less
- * than 128. We then compute p(x) = h^8m_0 + ... + h^1m_7 where multiplication
- * is simply polynomial multiplication.
- *
- * In the second step, we compute the reduction of p(x) modulo the finite field
- * modulus g(x) = x^128 + x^127 + x^126 + x^121 + 1.
- *
- * This two step process is equivalent to computing h^8m_0 + ... + h^1m_7 where
- * multiplication is finite field multiplication. The advantage is that the
- * two-step process  only requires 1 finite field reduction for every 8
- * polynomial multiplications. Further parallelism is gained by interleaving the
- * multiplications and polynomial reductions.
- */
-
-#include <linux/linkage.h>
-#include <asm/frame.h>
-
-#define STRIDE_BLOCKS 8
-
-#define GSTAR %xmm7
-#define PL %xmm8
-#define PH %xmm9
-#define TMP_XMM %xmm11
-#define LO %xmm12
-#define HI %xmm13
-#define MI %xmm14
-#define SUM %xmm15
-
-#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
-
-.Lgstar:
-	.quad 0xc200000000000000, 0xc200000000000000
-
-.text
-
-/*
- * Performs schoolbook1_iteration on two lists of 128-bit polynomials of length
- * count pointed to by MSG and KEY_POWERS.
- */
-.macro schoolbook1 count
-	.set i, 0
-	.rept (\count)
-		schoolbook1_iteration i 0
-		.set i, (i +1)
-	.endr
-.endm
-
-/*
- * Computes the product of two 128-bit polynomials at the memory locations
- * specified by (MSG + 16*i) and (KEY_POWERS + 16*i) and XORs the components of
- * the 256-bit product into LO, MI, HI.
- *
- * Given:
- *   X = [X_1 : X_0]
- *   Y = [Y_1 : Y_0]
- *
- * We compute:
- *   LO += X_0 * Y_0
- *   MI += X_0 * Y_1 + X_1 * Y_0
- *   HI += X_1 * Y_1
- *
- * Later, the 256-bit result can be extracted as:
- *   [HI_1 : HI_0 + MI_1 : LO_1 + MI_0 : LO_0]
- * This step is done when computing the polynomial reduction for efficiency
- * reasons.
- *
- * If xor_sum == 1, then also XOR the value of SUM into m_0.  This avoids an
- * extra multiplication of SUM and h^8.
- */
-.macro schoolbook1_iteration i xor_sum
-	movups (16*\i)(MSG), %xmm0
-	.if (\i == 0 && \xor_sum == 1)
-		pxor SUM, %xmm0
-	.endif
-	vpclmulqdq $0x01, (16*\i)(KEY_POWERS), %xmm0, %xmm2
-	vpclmulqdq $0x00, (16*\i)(KEY_POWERS), %xmm0, %xmm1
-	vpclmulqdq $0x10, (16*\i)(KEY_POWERS), %xmm0, %xmm3
-	vpclmulqdq $0x11, (16*\i)(KEY_POWERS), %xmm0, %xmm4
-	vpxor %xmm2, MI, MI
-	vpxor %xmm1, LO, LO
-	vpxor %xmm4, HI, HI
-	vpxor %xmm3, MI, MI
-.endm
-
-/*
- * Performs the same computation as schoolbook1_iteration, except we expect the
- * arguments to already be loaded into xmm0 and xmm1 and we set the result
- * registers LO, MI, and HI directly rather than XOR'ing into them.
- */
-.macro schoolbook1_noload
-	vpclmulqdq $0x01, %xmm0, %xmm1, MI
-	vpclmulqdq $0x10, %xmm0, %xmm1, %xmm2
-	vpclmulqdq $0x00, %xmm0, %xmm1, LO
-	vpclmulqdq $0x11, %xmm0, %xmm1, HI
-	vpxor %xmm2, MI, MI
-.endm
-
-/*
- * Computes the 256-bit polynomial represented by LO, HI, MI. Stores
- * the result in PL, PH.
- *   [PH : PL] = [HI_1 : HI_0 + MI_1 : LO_1 + MI_0 : LO_0]
- */
-.macro schoolbook2
-	vpslldq $8, MI, PL
-	vpsrldq $8, MI, PH
-	pxor LO, PL
-	pxor HI, PH
-.endm
-
-/*
- * Computes the 128-bit reduction of PH : PL. Stores the result in dest.
- *
- * This macro computes p(x) mod g(x) where p(x) is in montgomery form and g(x) =
- * x^128 + x^127 + x^126 + x^121 + 1.
- *
- * We have a 256-bit polynomial PH : PL = P_3 : P_2 : P_1 : P_0 that is the
- * product of two 128-bit polynomials in Montgomery form.  We need to reduce it
- * mod g(x).  Also, since polynomials in Montgomery form have an "extra" factor
- * of x^128, this product has two extra factors of x^128.  To get it back into
- * Montgomery form, we need to remove one of these factors by dividing by x^128.
- *
- * To accomplish both of these goals, we add multiples of g(x) that cancel out
- * the low 128 bits P_1 : P_0, leaving just the high 128 bits. Since the low
- * bits are zero, the polynomial division by x^128 can be done by right shifting.
- *
- * Since the only nonzero term in the low 64 bits of g(x) is the constant term,
- * the multiple of g(x) needed to cancel out P_0 is P_0 * g(x).  The CPU can
- * only do 64x64 bit multiplications, so split P_0 * g(x) into x^128 * P_0 +
- * x^64 * g*(x) * P_0 + P_0, where g*(x) is bits 64-127 of g(x).  Adding this to
- * the original polynomial gives P_3 : P_2 + P_0 + T_1 : P_1 + T_0 : 0, where T
- * = T_1 : T_0 = g*(x) * P_0.  Thus, bits 0-63 got "folded" into bits 64-191.
- *
- * Repeating this same process on the next 64 bits "folds" bits 64-127 into bits
- * 128-255, giving the answer in bits 128-255. This time, we need to cancel P_1
- * + T_0 in bits 64-127. The multiple of g(x) required is (P_1 + T_0) * g(x) *
- * x^64. Adding this to our previous computation gives P_3 + P_1 + T_0 + V_1 :
- * P_2 + P_0 + T_1 + V_0 : 0 : 0, where V = V_1 : V_0 = g*(x) * (P_1 + T_0).
- *
- * So our final computation is:
- *   T = T_1 : T_0 = g*(x) * P_0
- *   V = V_1 : V_0 = g*(x) * (P_1 + T_0)
- *   p(x) / x^{128} mod g(x) = P_3 + P_1 + T_0 + V_1 : P_2 + P_0 + T_1 + V_0
- *
- * The implementation below saves a XOR instruction by computing P_1 + T_0 : P_0
- * + T_1 and XORing into dest, rather than separately XORing P_1 : P_0 and T_0 :
- * T_1 into dest.  This allows us to reuse P_1 + T_0 when computing V.
- */
-.macro montgomery_reduction dest
-	vpclmulqdq $0x00, PL, GSTAR, TMP_XMM	# TMP_XMM = T_1 : T_0 = P_0 * g*(x)
-	pshufd $0b01001110, TMP_XMM, TMP_XMM	# TMP_XMM = T_0 : T_1
-	pxor PL, TMP_XMM			# TMP_XMM = P_1 + T_0 : P_0 + T_1
-	pxor TMP_XMM, PH			# PH = P_3 + P_1 + T_0 : P_2 + P_0 + T_1
-	pclmulqdq $0x11, GSTAR, TMP_XMM		# TMP_XMM = V_1 : V_0 = V = [(P_1 + T_0) * g*(x)]
-	vpxor TMP_XMM, PH, \dest
-.endm
-
-/*
- * Compute schoolbook multiplication for 8 blocks
- * m_0h^8 + ... + m_7h^1
- *
- * If reduce is set, also computes the montgomery reduction of the
- * previous full_stride call and XORs with the first message block.
- * (m_0 + REDUCE(PL, PH))h^8 + ... + m_7h^1.
- * I.e., the first multiplication uses m_0 + REDUCE(PL, PH) instead of m_0.
- */
-.macro full_stride reduce
-	pxor LO, LO
-	pxor HI, HI
-	pxor MI, MI
-
-	schoolbook1_iteration 7 0
-	.if \reduce
-		vpclmulqdq $0x00, PL, GSTAR, TMP_XMM
-	.endif
-
-	schoolbook1_iteration 6 0
-	.if \reduce
-		pshufd $0b01001110, TMP_XMM, TMP_XMM
-	.endif
-
-	schoolbook1_iteration 5 0
-	.if \reduce
-		pxor PL, TMP_XMM
-	.endif
-
-	schoolbook1_iteration 4 0
-	.if \reduce
-		pxor TMP_XMM, PH
-	.endif
-
-	schoolbook1_iteration 3 0
-	.if \reduce
-		pclmulqdq $0x11, GSTAR, TMP_XMM
-	.endif
-
-	schoolbook1_iteration 2 0
-	.if \reduce
-		vpxor TMP_XMM, PH, SUM
-	.endif
-
-	schoolbook1_iteration 1 0
-
-	schoolbook1_iteration 0 1
-
-	addq $(8*16), MSG
-	schoolbook2
-.endm
-
-/*
- * Process BLOCKS_LEFT blocks, where 0 < BLOCKS_LEFT < STRIDE_BLOCKS
- */
-.macro partial_stride
-	mov BLOCKS_LEFT, TMP
-	shlq $4, TMP
-	addq $(16*STRIDE_BLOCKS), KEY_POWERS
-	subq TMP, KEY_POWERS
-
-	movups (MSG), %xmm0
-	pxor SUM, %xmm0
-	movups (KEY_POWERS), %xmm1
-	schoolbook1_noload
-	dec BLOCKS_LEFT
-	addq $16, MSG
-	addq $16, KEY_POWERS
-
-	test $4, BLOCKS_LEFT
-	jz .Lpartial4BlocksDone
-	schoolbook1 4
-	addq $(4*16), MSG
-	addq $(4*16), KEY_POWERS
-.Lpartial4BlocksDone:
-	test $2, BLOCKS_LEFT
-	jz .Lpartial2BlocksDone
-	schoolbook1 2
-	addq $(2*16), MSG
-	addq $(2*16), KEY_POWERS
-.Lpartial2BlocksDone:
-	test $1, BLOCKS_LEFT
-	jz .LpartialDone
-	schoolbook1 1
-.LpartialDone:
-	schoolbook2
-	montgomery_reduction SUM
-.endm
-
-/*
- * Computes a = a * b * x^{-128} mod x^128 + x^127 + x^126 + x^121 + 1.
- *
- * void polyval_mul_pclmul_avx(struct polyval_elem *a,
- *			       const struct polyval_elem *b);
- */
-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(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 the accumulator
- * rsi - pointer to precomputed key powers h^8 ... h^1
- * rdx - pointer to message blocks
- * rcx - number of blocks to hash
- *
- * void polyval_blocks_pclmul_avx(struct polyval_elem *acc,
- *				  const struct polyval_key *key,
- *				  const u8 *data, size_t nblocks);
- */
-SYM_FUNC_START(polyval_blocks_pclmul_avx)
-	FRAME_BEGIN
-	vmovdqa .Lgstar(%rip), GSTAR
-	movups (ACCUMULATOR), SUM
-	subq $STRIDE_BLOCKS, BLOCKS_LEFT
-	js .LstrideLoopExit
-	full_stride 0
-	subq $STRIDE_BLOCKS, BLOCKS_LEFT
-	js .LstrideLoopExitReduce
-.LstrideLoop:
-	full_stride 1
-	subq $STRIDE_BLOCKS, BLOCKS_LEFT
-	jns .LstrideLoop
-.LstrideLoopExitReduce:
-	montgomery_reduction SUM
-.LstrideLoopExit:
-	add $STRIDE_BLOCKS, BLOCKS_LEFT
-	jz .LskipPartial
-	partial_stride
-.LskipPartial:
-	movups SUM, (ACCUMULATOR)
-	FRAME_END
-	RET
-SYM_FUNC_END(polyval_blocks_pclmul_avx)
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH 06/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with VPCLMULQDQ and AVX2
  2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
                   ` (4 preceding siblings ...)
  2026-11-29 20:02 ` [PATCH 05/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with PCLMULQDQ and AVX Eric Biggers
@ 2026-11-29 20:02 ` Eric Biggers
  2026-11-29 20:02 ` [PATCH 07/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with VPCLMULQDQ and AVX512 Eric Biggers
                   ` (4 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, Eric Biggers

Add a VPCLMULQDQ + AVX2 implementation of GHASH and POLYVAL for x86_64
in lib/crypto/x86/gf128hash-vpclmul-avx2.S, providing:

- {ghash,polyval}_preparekey_vpclmul_avx2()
- {ghash,polyval}_blocks_vpclmul_avx2()

The file is derived from arch/x86/crypto/aes-gcm-vaes-avx2.S, so it
inherits its copyright and license.  This speeds up both algorithms on
CPUs with VPCLMULQDQ and AVX2 by hashing two 128-bit blocks per YMM
vector (8 blocks per stride), and prepares for migrating the VAES+AVX2
AES-GCM code into lib/crypto/.

Like gf128hash-pclmul.S, the assembly uses macros to share code between
GHASH and POLYVAL and processes trailing 2..7 blocks in parallel with a
single deferred reduction.  Key implementation choices for AVX2:

- The 8-block main loop uses 256-bit Karatsuba multiplication with
  h_powers_xored stored in the permuted order (8,6,7,5,4,2,3,1) so all
  8 XOR'd halves stay resident in two YMM registers without shuffles.
  The 2..7-block tail uses schoolbook multiplication because when the
  number of remaining blocks is odd it needs key-power pairs that the
  permuted table doesn't support.

- Key preparation stores H^1 * x^-64 mod G(x) in key->h_times_xm64,
  squares H^1 to H^2, precomputes H^2 * x^-64 mod G(x), and computes
  [H^4, H^3], [H^6, H^5], and [H^8, H^7] in 2-wide YMM vectors using
  1-step-reduction multiplications by [H^2, H^2].

- Single-block calls (nblocks == 1) use a strictly 128-bit XMM fast path
  to avoid YMM overhead and vzeroupper, using key->h_times_xm64 for a
  1-step reduction (as does the final single-block tail path).

Gate this path on VAES as well as AVX2 and VPCLMULQDQ so that
libgf128hash and libaes (whose VAES+AVX2 AES-GCM code requires VAES)
always agree on the layout of 'struct ghash_key'.

Benchmark results on AMD Ryzen 9 9950X (Zen 5) using ghash_kunit and
polyval_kunit:

    Length   GHASH before  GHASH after   POLYVAL before  POLYVAL after
    ------   ------------  -----------   --------------  -------------
         1       129 MB/s     129 MB/s         131 MB/s       131 MB/s
        16      2105 MB/s    2157 MB/s        2278 MB/s      2232 MB/s
        64      5881 MB/s    7286 MB/s        6015 MB/s      7156 MB/s
       127      6017 MB/s    6615 MB/s        6161 MB/s      6785 MB/s
       128      8796 MB/s   11769 MB/s        8726 MB/s     11663 MB/s
       200      7658 MB/s    9112 MB/s        7728 MB/s      8863 MB/s
       256     10651 MB/s   16585 MB/s       10620 MB/s     16529 MB/s
       511     10212 MB/s   14640 MB/s       10478 MB/s     14630 MB/s
       512     11991 MB/s   17740 MB/s       12082 MB/s     20235 MB/s
      1024     13081 MB/s   20218 MB/s       12857 MB/s     22206 MB/s
      3173     13096 MB/s   20521 MB/s       13118 MB/s     20545 MB/s
      4096     13535 MB/s   21706 MB/s       13351 MB/s     20717 MB/s
     16384     13446 MB/s   21577 MB/s       13233 MB/s     22174 MB/s

Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 include/crypto/gf128hash.h              |   6 +-
 lib/crypto/Makefile                     |   3 +-
 lib/crypto/x86/gf128hash-cpu.h          |  13 +
 lib/crypto/x86/gf128hash-vpclmul-avx2.S | 537 ++++++++++++++++++++++++
 lib/crypto/x86/gf128hash.h              |  50 ++-
 5 files changed, 601 insertions(+), 8 deletions(-)
 create mode 100644 lib/crypto/x86/gf128hash-vpclmul-avx2.S

diff --git a/include/crypto/gf128hash.h b/include/crypto/gf128hash.h
index c8b523a2d33cf..4d2109a3362c0 100644
--- a/include/crypto/gf128hash.h
+++ b/include/crypto/gf128hash.h
@@ -38,7 +38,11 @@ struct polyval_elem {
 struct gf128hash_key_x86 {
 	/* Powers of the hash key H^8 through H^1, in POLYVAL format */
 	struct polyval_elem h_powers[8];
-	/* Halves of each entry of @h_powers XOR'd together */
+	/*
+	 * Halves of each entry of @h_powers XOR'd together.  If
+	 * gf128hash_use_vpclmul_avx2(), they're in the order H^8, H^6, H^7,
+	 * H^5, H^4, H^2, H^3, H^1.  Otherwise they're in the order H^8..H^1.
+	 */
 	__le64 h_powers_xored[8];
 	/*
 	 * H^1 * x^-64 mod G(x) in POLYVAL format.  This is used to optimize
diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile
index 5b458b6f20e32..9d3ecc643a844 100644
--- a/lib/crypto/Makefile
+++ b/lib/crypto/Makefile
@@ -42,7 +42,8 @@ OBJECT_FILES_NON_STANDARD_powerpc/ghashp8-ppc.o := y
 endif
 
 libgf128hash-$(CONFIG_RISCV) += riscv/ghash-riscv64-zvkg.o
-libgf128hash-$(CONFIG_X86_64) += x86/gf128hash-pclmul.o
+libgf128hash-$(CONFIG_X86_64) += x86/gf128hash-pclmul.o \
+				 x86/gf128hash-vpclmul-avx2.o
 endif # CONFIG_CRYPTO_LIB_GF128HASH_ARCH
 
 # clean-files must be defined unconditionally
diff --git a/lib/crypto/x86/gf128hash-cpu.h b/lib/crypto/x86/gf128hash-cpu.h
index 157da0a49c416..5045b41bf8d73 100644
--- a/lib/crypto/x86/gf128hash-cpu.h
+++ b/lib/crypto/x86/gf128hash-cpu.h
@@ -23,4 +23,17 @@ static inline bool gf128hash_use_pclmul_avx(void)
 	return gf128hash_use_pclmul() && cpu_feature_enabled(X86_FEATURE_AVX);
 }
 
+/*
+ * Check VAES too, even though GHASH and POLYVAL don't use VAES instructions, so
+ * that struct ghash_key matches the layout expected by libaes's AES-GCM code
+ * (which falls back to its non-VAES code if VAES is disabled).
+ */
+static inline bool gf128hash_use_vpclmul_avx2(void)
+{
+	return gf128hash_use_pclmul_avx() &&
+	       cpu_feature_enabled(X86_FEATURE_VAES) &&
+	       cpu_feature_enabled(X86_FEATURE_AVX2) &&
+	       cpu_feature_enabled(X86_FEATURE_VPCLMULQDQ);
+}
+
 #endif /* _LIB_CRYPTO_X86_GF128HASH_CPU_H */
diff --git a/lib/crypto/x86/gf128hash-vpclmul-avx2.S b/lib/crypto/x86/gf128hash-vpclmul-avx2.S
new file mode 100644
index 0000000000000..9c38148445aa3
--- /dev/null
+++ b/lib/crypto/x86/gf128hash-vpclmul-avx2.S
@@ -0,0 +1,537 @@
+/* SPDX-License-Identifier: Apache-2.0 OR BSD-2-Clause */
+//
+// Accelerated GHASH and POLYVAL implementation with VPCLMULQDQ and AVX2
+//
+// Copyright 2025 Google LLC
+//
+// Author: Eric Biggers <ebiggers@google.com>
+//
+//------------------------------------------------------------------------------
+//
+// This file is dual-licensed, meaning that you can use it under your choice of
+// either of the following two licenses:
+//
+// Licensed under the Apache License 2.0 (the "License").  You may obtain a copy
+// of the License at
+//
+//	http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// or
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+//    this list of conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+//
+//------------------------------------------------------------------------------
+//
+// This file implements GHASH and POLYVAL using the VPCLMULQDQ instruction on
+// 256-bit vectors (ymm registers), each holding two 128-bit blocks.  It also
+// requires AVX2 (for 256-bit vector integer operations).  The math and the
+// overall design are the same as in gf128hash-pclmul.S, which documents them.
+// The main differences are:
+//
+// - The 8-block stride is processed as 4 vectors.  Lane 0 of each vector holds
+//   the earlier block and lane 1 the later one, so the data vectors are
+//   multiplied by the key power vectors [H^8, H^7], [H^6, H^5], [H^4, H^3], and
+//   [H^2, H^1] (written [lane 0, lane 1]), which stay in registers.  The
+//   unreduced products are summed in each lane, both lanes are reduced at once,
+//   and the two reduced lanes are XOR'd together.  This works because the
+//   reduction is linear.  The accumulator is kept in lane 0 with lane 1 zero,
+//   so XOR'ing it into the first data vector adds it to the first block only.
+//
+// - The 8-block loop uses Karatsuba multiplication like gf128hash-pclmul.S.
+//   To avoid any per-vector loads or shuffles of the precomputed XOR'd halves
+//   of the key powers, h_powers_xored stores them in the order H^8, H^6, H^7,
+//   H^5, H^4, H^2, H^3, H^1.  The loop loads them into two registers:
+//
+//	H_POW43_XORED = [(H^8)_x, (H^6)_x | (H^7)_x, (H^5)_x]
+//	H_POW21_XORED = [(H^4)_x, (H^2)_x | (H^3)_x, (H^1)_x]
+//
+//   where (H^k)_x = (H^k)_L + (H^k)_H, qwords are written low-to-high, and '|'
+//   separates lanes 0 and 1.  vpclmulqdq then selects either the low qword of
+//   each lane (for H_POW4 = [H^8, H^7] and H_POW2 = [H^4, H^3]) or the high
+//   qword (for H_POW3 = [H^6, H^5] and H_POW1 = [H^2, H^1]).  The final 2..7
+//   blocks use schoolbook multiplication instead, since when the number of
+//   remaining blocks is odd they need key power pairs (e.g. [H^5, H^4]) that
+//   this layout doesn't support.
+//
+// - Single-block multiplications (both nblocks == 1 and a single remaining
+//   block after the 8-block loop) use the precomputed H^1 * x^-64 mod G(x) from
+//   key->h_times_xm64 so that only one reduction step is needed, matching
+//   gf128hash-pclmul.S.  When nblocks == 1 at entry, a dedicated xmm-only fast
+//   path is used to avoid ymm setup and vzeroupper; when 1 block remains after
+//   the 8-block loop, ymm registers are already dirty so .Lblocks_1x falls
+//   through to vzeroupper.
+//
+// - preparekey stores H^1 * x^-64 mod G(x) in key->h_times_xm64, squares H^1 to
+//   get H^2, precomputes H^2 * x^-64 mod G(x), and then computes [H^4, H^3],
+//   [H^6, H^5], and [H^8, H^7] by repeatedly multiplying by [H^2, H^2] using
+//   the 1-step reduction.
+
+#include <linux/linkage.h>
+
+.section .rodata
+.p2align 4
+
+	// vpshufb mask that reverses the order of the bytes in a 16-byte block
+.Lbswap_mask:
+	.octa	0x000102030405060708090a0b0c0d0e0f
+
+	// Mask for multiplying by x mod G(x): G(x) - x^128 = x^127 + x^126 +
+	// x^121 + 1 (bits 127, 126, 121, and 0), and bit 64 for the carry from
+	// bit 63 that vpaddq doesn't propagate
+.Lgfpoly_and_internal_carrybit:
+	.octa	0xc2000000000000010000000000000001
+
+	// (G(x) - x^128 - 1) / x^64 = x^63 + x^62 + x^57, the constant used to
+	// multiply by x^-64 mod G(x)
+.Lgfpoly:
+	.quad	0xc200000000000000
+
+// Offsets in struct gf128hash_key_x86, using the 8-power permuted layout.
+// h_powers[0..7] holds H^8..H^1, h_powers_xored[0..7] holds the XORs of the two
+// 64-bit halves of H^8, H^6, H^7, H^5, H^4, H^2, H^3, H^1 (in that order), and
+// h_times_xm64 holds H^1 * x^-64 mod G(x).
+#define OFFSETOF_H_POWERS	0
+#define OFFSETOFEND_H_POWERS	128
+#define OFFSETOF_H_POWERS_XORED	128
+#define OFFSETOF_H_TIMES_XM64	192
+
+.text
+
+// Set each 128-bit lane of \dst to dot(lane of \a, lane of \b), given
+// \a_times_xm64 = \a * x^-64 mod G(x) in each lane (see gf128hash-pclmul.S for
+// the math).  Works on xmm and ymm registers.  \dst may alias \a,
+// \a_times_xm64, or \b.  \gfpoly must contain .Lgfpoly in the low qword of each
+// lane.  Clobbers \t0 and \t1.  \gfpoly, \t0, and \t1 must be distinct from
+// each other and from the other operands.
+.macro	_gf128hash_mul	a, a_times_xm64, b, dst, gfpoly, t0, t1
+	vpclmulqdq	$0x01, \a, \b, \t0		// a_L * b_H
+	vpclmulqdq	$0x00, \a_times_xm64, \b, \t1	// (a*x^-64)_L * b_L
+	vpxor		\t1, \t0, \t0			// MI
+	vpclmulqdq	$0x11, \a, \b, \t1		// a_H * b_H
+	vpclmulqdq	$0x10, \a_times_xm64, \b, \dst	// (a*x^-64)_H * b_L
+	vpxor		\t1, \dst, \dst			// HI
+	vpclmulqdq	$0x00, \gfpoly, \t0, \t1	// MI_L*(x^63+x^62+x^57)
+	vpshufd		$0x4e, \t0, \t0			// MI_H + MI_L * x^64
+	vpxor		\t0, \dst, \dst			// Fold MI into HI (1)
+	vpxor		\t1, \dst, \dst			// Fold MI into HI (2)
+.endm
+
+// Like _gf128hash_mul, but compute dot(\a, \a) in each 128-bit lane.  In
+// GF(2)[x], the cross terms cancel: (a_L + a_H * x^64)^2 = (a_L)^2 +
+// (a_H)^2 * x^128.  So only 2 vpclmulqdq are needed for the product, and the
+// initial MI is 0, so the first reduction step sets MI = LO * x^-64.  \dst may
+// alias \a.  Clobbers \t0 and \t1.  \gfpoly, \t0, and \t1 must be distinct from
+// each other and from \a and \dst.
+.macro	_gf128hash_square	a, dst, gfpoly, t0, t1
+	vpclmulqdq	$0x00, \a, \a, \t0		// LO = (a_L)^2
+	vpclmulqdq	$0x11, \a, \a, \dst		// HI = (a_H)^2
+	vpclmulqdq	$0x00, \gfpoly, \t0, \t1	// LO_L*(x^63+x^62+x^57)
+	vpshufd		$0x4e, \t0, \t0			// LO_H + LO_L * x^64
+	vpxor		\t0, \t1, \t1			// MI = LO * x^-64
+	vpclmulqdq	$0x00, \gfpoly, \t1, \t0	// MI_L*(x^63+x^62+x^57)
+	vpshufd		$0x4e, \t1, \t1			// MI_H + MI_L * x^64
+	vpxor		\t1, \dst, \dst			// Fold MI into HI (1)
+	vpxor		\t0, \dst, \dst			// Fold MI into HI (2)
+.endm
+
+// Reduce the 256-bit products LO + MI * x^64 + HI * x^128 given in each 128-bit
+// lane of \lo, \mi, and \hi: multiply them by x^-128 mod G(x) and store the
+// 128-bit results in \hi.  This is done in two steps, MI += LO * x^-64 then
+// HI += MI * x^-64.  Works on xmm and ymm registers.  \gfpoly must contain
+// .Lgfpoly in the low qword of each lane.  Clobbers \lo, \mi, and \tmp.  All
+// operands must be distinct registers.
+.macro	_gf128hash_reduce	lo, mi, hi, gfpoly, tmp
+	vpclmulqdq	$0x00, \gfpoly, \lo, \tmp	// LO_L*(x^63+x^62+x^57)
+	vpshufd		$0x4e, \lo, \lo			// LO_H + LO_L * x^64
+	vpxor		\lo, \mi, \mi			// Fold LO into MI (1)
+	vpxor		\tmp, \mi, \mi			// Fold LO into MI (2)
+	vpclmulqdq	$0x00, \gfpoly, \mi, \tmp	// MI_L*(x^63+x^62+x^57)
+	vpshufd		$0x4e, \mi, \mi			// MI_H + MI_L * x^64
+	vpxor		\mi, \hi, \hi			// Fold MI into HI (1)
+	vpxor		\tmp, \hi, \hi			// Fold MI into HI (2)
+.endm
+
+// void {ghash,polyval}_preparekey_vpclmul_avx2(struct gf128hash_key_x86 *key,
+//						const u8 raw_key[16]);
+//
+// Given the raw GHASH key (\is_ghash=1) or POLYVAL key (\is_ghash=0), set:
+// - key->h_powers[0..7] to H^8..H^1 in POLYVAL format
+// - key->h_powers_xored[0..7] to the XORs of the two 64-bit halves of H^8, H^6,
+//   H^7, H^5, H^4, H^2, H^3, H^1 (in that order)
+// - key->h_times_xm64 to H^1 * x^-64 mod G(x)
+.macro	_gf128hash_preparekey	is_ghash
+	.set	KEY,		%rdi
+	.set	RAW_KEY,	%rsi
+	.set	TMP0,		%ymm0
+	.set	TMP0_XMM,	%xmm0
+	.set	TMP1,		%ymm1
+	.set	TMP1_XMM,	%xmm1
+	.set	H_CUR,		%ymm2
+	.set	H_CUR_XMM,	%xmm2
+	.set	H_CUR2,		%ymm3
+	.set	H_INC,		%ymm4
+	.set	H_INC_XMM,	%xmm4
+	.set	H_INC_XM64,	%ymm5
+	.set	H_INC_XM64_XMM,	%xmm5
+	.set	GFPOLY,		%ymm6
+	.set	GFPOLY_XMM,	%xmm6
+
+	vmovdqu		(RAW_KEY), H_CUR_XMM
+.if \is_ghash
+	// Convert the GHASH key to POLYVAL format: byte-reverse it, then
+	// multiply it by x mod G(x).  See gf128hash-pclmul.S for details.
+	vpshufb		.Lbswap_mask(%rip), H_CUR_XMM, H_CUR_XMM
+	vpshufd		$0xd3, H_CUR_XMM, TMP0_XMM
+	vpsrad		$31, TMP0_XMM, TMP0_XMM
+	vpaddq		H_CUR_XMM, H_CUR_XMM, H_CUR_XMM
+	vpand		.Lgfpoly_and_internal_carrybit(%rip), TMP0_XMM, TMP0_XMM
+	vpxor		TMP0_XMM, H_CUR_XMM, H_CUR_XMM
+.endif
+
+	vpbroadcastq	.Lgfpoly(%rip), GFPOLY
+
+	// Compute and store H^1 * x^-64 mod G(x) in h_times_xm64.
+	vpclmulqdq	$0x00, GFPOLY_XMM, H_CUR_XMM, TMP1_XMM
+	vpshufd		$0x4e, H_CUR_XMM, TMP0_XMM
+	vpxor		TMP0_XMM, TMP1_XMM, TMP1_XMM
+	vmovdqu		TMP1_XMM, OFFSETOF_H_TIMES_XM64(KEY)
+
+	// Square H^1 to get H^2, and compute H^2 * x^-64 mod G(x).
+	_gf128hash_square H_CUR_XMM, H_INC_XMM, GFPOLY_XMM, TMP0_XMM, TMP1_XMM
+	vpclmulqdq	$0x00, GFPOLY_XMM, H_INC_XMM, H_INC_XM64_XMM
+	vpshufd		$0x4e, H_INC_XMM, TMP0_XMM
+	vpxor		TMP0_XMM, H_INC_XM64_XMM, H_INC_XM64_XMM
+
+	// Create H_CUR = [H^2, H^1], H_INC = [H^2, H^2], and
+	// H_INC_XM64 = [H^2 * x^-64, H^2 * x^-64].
+	vinserti128	$1, H_CUR_XMM, H_INC, H_CUR
+	vinserti128	$1, H_INC_XMM, H_INC, H_INC
+	vinserti128	$1, H_INC_XM64_XMM, H_INC_XM64, H_INC_XM64
+
+	// Compute H_CUR2 = [H^4, H^3].
+	_gf128hash_mul	H_INC, H_INC_XM64, H_CUR, H_CUR2, GFPOLY, TMP0, TMP1
+
+	// Store [H^4, H^3, H^2, H^1] in h_powers[4..7].
+	vmovdqu		H_CUR, OFFSETOF_H_POWERS+3*32(KEY)
+	vmovdqu		H_CUR2, OFFSETOF_H_POWERS+2*32(KEY)
+
+	// Store [(H^4)_x, (H^2)_x | (H^3)_x, (H^1)_x] in h_powers_xored[4..7].
+	// This layout requires only in-lane unpacking (in AT&T syntax, H_CUR2
+	// unpacks into the low qwords and H_CUR into the high qwords).
+	vpunpcklqdq	H_CUR, H_CUR2, TMP0
+	vpunpckhqdq	H_CUR, H_CUR2, TMP1
+	vpxor		TMP1, TMP0, TMP0
+	vmovdqu		TMP0, OFFSETOF_H_POWERS_XORED+1*32(KEY)
+
+	// Compute H_CUR = [H^6, H^5] and H_CUR2 = [H^8, H^7], and store
+	// [H^8, H^7, H^6, H^5] in h_powers[0..3].
+	_gf128hash_mul	H_INC, H_INC_XM64, H_CUR2, H_CUR, GFPOLY, TMP0, TMP1
+	_gf128hash_mul	H_INC, H_INC_XM64, H_CUR, H_CUR2, GFPOLY, TMP0, TMP1
+	vmovdqu		H_CUR, OFFSETOF_H_POWERS+1*32(KEY)
+	vmovdqu		H_CUR2, OFFSETOF_H_POWERS+0*32(KEY)
+
+	// Store [(H^8)_x, (H^6)_x | (H^7)_x, (H^5)_x] in h_powers_xored[0..3].
+	vpunpcklqdq	H_CUR, H_CUR2, TMP0
+	vpunpckhqdq	H_CUR, H_CUR2, TMP1
+	vpxor		TMP1, TMP0, TMP0
+	vmovdqu		TMP0, OFFSETOF_H_POWERS_XORED+0*32(KEY)
+
+	vzeroupper
+	RET
+.endm
+
+// Update ACC with 8 blocks (four 32-byte vectors) of data from DATA, using
+// aggregated Karatsuba multiplication.  ACC must hold the accumulator in lane 0
+// and zero in lane 1, and this property is preserved.
+//
+// For each data vector M, vpunpckhqdq and vpxor compute M_L + M_H in the low
+// qword of each lane, for the Karatsuba middle product.  Vectors 1..3 are
+// processed before vector 0 so that the loop-carried dependency on ACC enters
+// as late as possible.
+.macro	_gf128hash_4x	bswap_data
+	// Vector 1: [M_2, M_3] * [H^6, H^5], with the high qwords of
+	// H_POW43_XORED.  Initialize LO, MI, and HI.
+	vmovdqu		1*32(DATA), TMP1
+.if \bswap_data
+	vpshufb		BSWAP_MASK, TMP1, TMP1
+.endif
+	vpclmulqdq	$0x00, H_POW3, TMP1, LO
+	vpclmulqdq	$0x11, H_POW3, TMP1, HI
+	vpunpckhqdq	TMP1, TMP1, TMP0
+	vpxor		TMP1, TMP0, TMP0
+	vpclmulqdq	$0x10, H_POW43_XORED, TMP0, MI
+
+	// Vector 2: [M_4, M_5] * [H^4, H^3], with the low qwords of
+	// H_POW21_XORED.
+	vmovdqu		2*32(DATA), TMP1
+.if \bswap_data
+	vpshufb		BSWAP_MASK, TMP1, TMP1
+.endif
+	vpclmulqdq	$0x00, H_POW2, TMP1, TMP0
+	vpxor		TMP0, LO, LO
+	vpclmulqdq	$0x11, H_POW2, TMP1, TMP0
+	vpxor		TMP0, HI, HI
+	vpunpckhqdq	TMP1, TMP1, TMP0
+	vpxor		TMP1, TMP0, TMP0
+	vpclmulqdq	$0x00, H_POW21_XORED, TMP0, TMP0
+	vpxor		TMP0, MI, MI
+
+	// Vector 3: [M_6, M_7] * [H^2, H^1], with the high qwords of
+	// H_POW21_XORED.
+	vmovdqu		3*32(DATA), TMP1
+.if \bswap_data
+	vpshufb		BSWAP_MASK, TMP1, TMP1
+.endif
+	vpclmulqdq	$0x00, H_POW1, TMP1, TMP0
+	vpxor		TMP0, LO, LO
+	vpclmulqdq	$0x11, H_POW1, TMP1, TMP0
+	vpxor		TMP0, HI, HI
+	vpunpckhqdq	TMP1, TMP1, TMP0
+	vpxor		TMP1, TMP0, TMP0
+	vpclmulqdq	$0x10, H_POW21_XORED, TMP0, TMP0
+	vpxor		TMP0, MI, MI
+
+	// Vector 0: [M_0 + ACC, M_1] * [H^8, H^7], with the low qwords of
+	// H_POW43_XORED.  Finish MI by adding LO and HI to it (in parallel with
+	// vector 0's middle product), then reduce both lanes and XOR them
+	// together into ACC_XMM.  Writing ACC_XMM zeroes lane 1 of ACC.
+	vmovdqu		0*32(DATA), TMP1
+.if \bswap_data
+	vpshufb		BSWAP_MASK, TMP1, TMP1
+.endif
+	vpxor		ACC, TMP1, TMP1
+	vpclmulqdq	$0x00, H_POW4, TMP1, TMP0
+	vpxor		TMP0, LO, LO
+	vpclmulqdq	$0x11, H_POW4, TMP1, TMP0
+	vpxor		TMP0, HI, HI
+	vpunpckhqdq	TMP1, TMP1, TMP0
+	vpxor		TMP1, TMP0, TMP0
+	vpclmulqdq	$0x00, H_POW43_XORED, TMP0, TMP0
+	vpxor		LO, MI, MI
+	vpxor		HI, MI, MI
+	vpxor		TMP0, MI, MI
+	_gf128hash_reduce LO, MI, HI, GFPOLY, TMP0
+	vextracti128	$1, HI, TMP0_XMM
+	vpxor		TMP0_XMM, HI_XMM, ACC_XMM
+.endm
+
+// void {ghash,polyval}_blocks_vpclmul_avx2(struct polyval_elem *acc,
+//					    const struct gf128hash_key_x86 *key,
+//					    const u8 *data, size_t nblocks);
+//
+// Update the POLYVAL-format accumulator @acc with @nblocks >= 1 full 16-byte
+// blocks from @data.  If \bswap_data=1 (GHASH), each block is byte-reversed to
+// convert it to POLYVAL format.
+.macro	_gf128hash_blocks	bswap_data
+	.set	ACC_PTR,	%rdi
+	.set	KEY,		%rsi
+	.set	DATA,		%rdx
+	.set	NBLOCKS,	%rcx
+	.set	POWERS_PTR,	%rax
+
+	.set	TMP0,		%ymm0
+	.set	TMP0_XMM,	%xmm0
+	.set	TMP1,		%ymm1
+	.set	TMP1_XMM,	%xmm1
+	.set	TMP2,		%ymm2
+	.set	TMP2_XMM,	%xmm2
+	.set	LO,		%ymm3
+	.set	LO_XMM,		%xmm3
+	.set	MI,		%ymm4
+	.set	HI,		%ymm5
+	.set	HI_XMM,		%xmm5
+	.set	ACC,		%ymm6
+	.set	ACC_XMM,	%xmm6
+	.set	GFPOLY,		%ymm7
+	.set	GFPOLY_XMM,	%xmm7
+	.set	H_POW43_XORED,	%ymm8
+	.set	H_POW21_XORED,	%ymm9
+	.set	H_POW4,		%ymm10
+	.set	H_POW3,		%ymm11
+	.set	H_POW2,		%ymm12
+	.set	H_POW1,		%ymm13
+	.set	BSWAP_MASK,	%ymm14
+	.set	BSWAP_MASK_XMM,	%xmm14
+
+	// Load the accumulator into lane 0 of ACC.  This zeroes lane 1.
+	vmovdqu		(ACC_PTR), ACC_XMM
+
+	// Handle nblocks == 1 specially, using only xmm registers.  This case
+	// is common (e.g. for 1-block associated data, the incremental AES-GCM
+	// lengths block, and the HCTR2 length and tweak blocks).
+	cmp		$1, NBLOCKS
+	jne		.Lblocks_more_than_1block\@
+
+	vmovq		.Lgfpoly(%rip), GFPOLY_XMM
+	vmovdqu		(DATA), TMP0_XMM
+.if \bswap_data
+	vpshufb		.Lbswap_mask(%rip), TMP0_XMM, TMP0_XMM
+.endif
+	vpxor		TMP0_XMM, ACC_XMM, ACC_XMM
+	vmovdqu		OFFSETOFEND_H_POWERS-16(KEY), TMP0_XMM	// H^1
+	vmovdqu		OFFSETOF_H_TIMES_XM64(KEY), TMP1_XMM	// H^1 * x^-64
+	_gf128hash_mul	TMP0_XMM, TMP1_XMM, ACC_XMM, ACC_XMM, GFPOLY_XMM, \
+			TMP2_XMM, LO_XMM
+	vmovdqu		ACC_XMM, (ACC_PTR)
+	// No vzeroupper is needed since only xmm registers were used.
+	RET
+
+.Lblocks_more_than_1block\@:
+.if \bswap_data
+	vbroadcasti128	.Lbswap_mask(%rip), BSWAP_MASK
+.endif
+	vpbroadcastq	.Lgfpoly(%rip), GFPOLY
+
+	// Process 8 blocks (128 bytes) at a time.
+	sub		$8, NBLOCKS
+	jb		.Lblocks_tail\@
+	// Load the XOR'd halves (in H^8,H^6|H^7,H^5 and H^4,H^2|H^3,H^1 order)
+	// and key powers.
+	vmovdqu		OFFSETOF_H_POWERS_XORED+0*32(KEY), H_POW43_XORED
+	vmovdqu		OFFSETOF_H_POWERS_XORED+1*32(KEY), H_POW21_XORED
+	vmovdqu		OFFSETOF_H_POWERS+0*32(KEY), H_POW4	// [H^8, H^7]
+	vmovdqu		OFFSETOF_H_POWERS+1*32(KEY), H_POW3	// [H^6, H^5]
+	vmovdqu		OFFSETOF_H_POWERS+2*32(KEY), H_POW2	// [H^4, H^3]
+	vmovdqu		OFFSETOF_H_POWERS+3*32(KEY), H_POW1	// [H^2, H^1]
+.Lblocks_loop_4x\@:
+	_gf128hash_4x	\bswap_data
+	sub		$-128, DATA	// DATA += 128 (compact imm8)
+	sub		$8, NBLOCKS
+	jae		.Lblocks_loop_4x\@
+
+.Lblocks_tail\@:
+	add		$8, NBLOCKS
+	jz		.Lblocks_done\@
+	cmp		$1, NBLOCKS
+	je		.Lblocks_1x\@
+
+	// 2 <= n = NBLOCKS <= 7 blocks remain.  Multiply them by H^n..H^1,
+	// starting at h_powers[8-n], using schoolbook multiplication.  Sum the
+	// unreduced products, and reduce the sum once at the end.
+	mov		NBLOCKS, POWERS_PTR
+	shl		$4, POWERS_PTR
+	neg		POWERS_PTR
+	lea		OFFSETOFEND_H_POWERS(KEY,POWERS_PTR), POWERS_PTR
+
+	// Blocks 0 and 1.  Since lane 1 of ACC is zero, vpxor adds ACC to
+	// block 0 only.
+	vmovdqu		(DATA), TMP0
+.if \bswap_data
+	vpshufb		BSWAP_MASK, TMP0, TMP0
+.endif
+	vpxor		ACC, TMP0, TMP0
+	vmovdqu		(POWERS_PTR), TMP1
+	vpclmulqdq	$0x00, TMP1, TMP0, LO
+	vpclmulqdq	$0x01, TMP1, TMP0, MI
+	vpclmulqdq	$0x10, TMP1, TMP0, TMP2
+	vpclmulqdq	$0x11, TMP1, TMP0, HI
+	vpxor		TMP2, MI, MI
+	add		$32, DATA
+	add		$32, POWERS_PTR
+
+	// Any further pairs of blocks (0, 1, or 2 iterations).  Subtract 4
+	// (2 for blocks 0..1 just processed, plus 2 for the next pair).
+	sub		$4, NBLOCKS
+	jb		.Lblocks_tail_odd\@
+.Lblocks_tail_loop\@:
+	vmovdqu		(DATA), TMP0
+.if \bswap_data
+	vpshufb		BSWAP_MASK, TMP0, TMP0
+.endif
+	vmovdqu		(POWERS_PTR), TMP1
+	vpclmulqdq	$0x00, TMP1, TMP0, TMP2
+	vpxor		TMP2, LO, LO
+	vpclmulqdq	$0x01, TMP1, TMP0, TMP2
+	vpxor		TMP2, MI, MI
+	vpclmulqdq	$0x10, TMP1, TMP0, TMP2
+	vpxor		TMP2, MI, MI
+	vpclmulqdq	$0x11, TMP1, TMP0, TMP2
+	vpxor		TMP2, HI, HI
+	add		$32, DATA
+	add		$32, POWERS_PTR
+	sub		$2, NBLOCKS
+	jae		.Lblocks_tail_loop\@
+.Lblocks_tail_odd\@:
+	add		$2, NBLOCKS
+	jz		.Lblocks_tail_reduce\@
+
+	// Final block, if n is odd: multiply it by H^1 in lane 0.  The 128-bit
+	// vpclmulqdq zeroes lane 1 of TMP2, so lane 1 of LO, MI, and HI is
+	// unchanged.
+	vmovdqu		(DATA), TMP0_XMM
+.if \bswap_data
+	vpshufb		BSWAP_MASK_XMM, TMP0_XMM, TMP0_XMM
+.endif
+	vmovdqu		(POWERS_PTR), TMP1_XMM
+	vpclmulqdq	$0x00, TMP1_XMM, TMP0_XMM, TMP2_XMM
+	vpxor		TMP2, LO, LO
+	vpclmulqdq	$0x01, TMP1_XMM, TMP0_XMM, TMP2_XMM
+	vpxor		TMP2, MI, MI
+	vpclmulqdq	$0x10, TMP1_XMM, TMP0_XMM, TMP2_XMM
+	vpxor		TMP2, MI, MI
+	vpclmulqdq	$0x11, TMP1_XMM, TMP0_XMM, TMP2_XMM
+	vpxor		TMP2, HI, HI
+
+.Lblocks_tail_reduce\@:
+	// Reduce both lanes, and XOR them together into ACC_XMM.
+	_gf128hash_reduce LO, MI, HI, GFPOLY, TMP0
+	vextracti128	$1, HI, TMP0_XMM
+	vpxor		TMP0_XMM, HI_XMM, ACC_XMM
+	jmp		.Lblocks_done\@
+
+.Lblocks_1x\@:
+	// 1 block remains after 8-block stride(s): ACC = dot(ACC + M_0, H^1).
+	vmovdqu		(DATA), TMP0_XMM
+.if \bswap_data
+	vpshufb		BSWAP_MASK_XMM, TMP0_XMM, TMP0_XMM
+.endif
+	vpxor		TMP0_XMM, ACC_XMM, ACC_XMM
+	vmovdqu		OFFSETOFEND_H_POWERS-16(KEY), TMP0_XMM	// H^1
+	vmovdqu		OFFSETOF_H_TIMES_XM64(KEY), TMP1_XMM	// H^1 * x^-64
+	_gf128hash_mul	TMP0_XMM, TMP1_XMM, ACC_XMM, ACC_XMM, GFPOLY_XMM, \
+			TMP2_XMM, LO_XMM
+
+.Lblocks_done\@:
+	vmovdqu		ACC_XMM, (ACC_PTR)
+	vzeroupper
+	RET
+.endm
+
+SYM_FUNC_START(ghash_preparekey_vpclmul_avx2)
+	_gf128hash_preparekey	1
+SYM_FUNC_END(ghash_preparekey_vpclmul_avx2)
+SYM_FUNC_START(polyval_preparekey_vpclmul_avx2)
+	_gf128hash_preparekey	0
+SYM_FUNC_END(polyval_preparekey_vpclmul_avx2)
+SYM_FUNC_START(ghash_blocks_vpclmul_avx2)
+	_gf128hash_blocks	1
+SYM_FUNC_END(ghash_blocks_vpclmul_avx2)
+SYM_FUNC_START(polyval_blocks_vpclmul_avx2)
+	_gf128hash_blocks	0
+SYM_FUNC_END(polyval_blocks_vpclmul_avx2)
diff --git a/lib/crypto/x86/gf128hash.h b/lib/crypto/x86/gf128hash.h
index 9abdea7f9ba86..4470be6dfea2d 100644
--- a/lib/crypto/x86/gf128hash.h
+++ b/lib/crypto/x86/gf128hash.h
@@ -19,6 +19,7 @@ static_assert(sizeof(struct gf128hash_key_x86) == 208);
 
 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_pclmul);
 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_pclmul_avx);
+static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_vpclmul_avx2);
 
 void gf128hash_mul_pclmul(struct polyval_elem *acc,
 			  const struct gf128hash_key_x86 *key);
@@ -29,10 +30,14 @@ void ghash_preparekey_pclmul(struct gf128hash_key_x86 *key,
 			     const u8 raw_key[GHASH_BLOCK_SIZE]);
 void ghash_preparekey_pclmul_avx(struct gf128hash_key_x86 *key,
 				 const u8 raw_key[GHASH_BLOCK_SIZE]);
+void ghash_preparekey_vpclmul_avx2(struct gf128hash_key_x86 *key,
+				   const u8 raw_key[GHASH_BLOCK_SIZE]);
 void polyval_preparekey_pclmul(struct gf128hash_key_x86 *key,
 			       const u8 raw_key[POLYVAL_BLOCK_SIZE]);
 void polyval_preparekey_pclmul_avx(struct gf128hash_key_x86 *key,
 				   const u8 raw_key[POLYVAL_BLOCK_SIZE]);
+void polyval_preparekey_vpclmul_avx2(struct gf128hash_key_x86 *key,
+				     const u8 raw_key[POLYVAL_BLOCK_SIZE]);
 
 void ghash_blocks_pclmul(struct polyval_elem *acc,
 			 const struct gf128hash_key_x86 *key, const u8 *data,
@@ -40,12 +45,18 @@ void ghash_blocks_pclmul(struct polyval_elem *acc,
 void ghash_blocks_pclmul_avx(struct polyval_elem *acc,
 			     const struct gf128hash_key_x86 *key,
 			     const u8 *data, size_t nblocks);
+void ghash_blocks_vpclmul_avx2(struct polyval_elem *acc,
+			       const struct gf128hash_key_x86 *key,
+			       const u8 *data, size_t nblocks);
 void polyval_blocks_pclmul(struct polyval_elem *acc,
 			   const struct gf128hash_key_x86 *key, const u8 *data,
 			   size_t nblocks);
 void polyval_blocks_pclmul_avx(struct polyval_elem *acc,
 			       const struct gf128hash_key_x86 *key,
 			       const u8 *data, size_t nblocks);
+void polyval_blocks_vpclmul_avx2(struct polyval_elem *acc,
+				 const struct gf128hash_key_x86 *key,
+				 const u8 *data, size_t nblocks);
 
 static __always_inline void
 __gf128hash_mul_x86_fpu(struct polyval_elem *acc,
@@ -62,7 +73,9 @@ __ghash_blocks_x86_fpu(struct polyval_elem *acc,
 		       const struct gf128hash_key_x86 *key, const u8 *data,
 		       size_t nblocks)
 {
-	if (static_branch_likely(&have_pclmul_avx))
+	if (static_branch_likely(&have_vpclmul_avx2))
+		ghash_blocks_vpclmul_avx2(acc, key, data, nblocks);
+	else if (static_branch_likely(&have_pclmul_avx))
 		ghash_blocks_pclmul_avx(acc, key, data, nblocks);
 	else
 		ghash_blocks_pclmul(acc, key, data, nblocks);
@@ -88,7 +101,12 @@ gf128hash_preparekey_x86(struct gf128hash_key_x86 *key, const u8 raw_key[16],
 {
 	if (static_branch_likely(&have_pclmul) && likely(irq_fpu_usable())) {
 		kernel_fpu_begin_mask(0);
-		if (static_branch_likely(&have_pclmul_avx)) {
+		if (static_branch_likely(&have_vpclmul_avx2)) {
+			if (is_ghash)
+				ghash_preparekey_vpclmul_avx2(key, raw_key);
+			else
+				polyval_preparekey_vpclmul_avx2(key, raw_key);
+		} else if (static_branch_likely(&have_pclmul_avx)) {
 			if (is_ghash)
 				ghash_preparekey_pclmul_avx(key, raw_key);
 			else
@@ -112,9 +130,24 @@ gf128hash_preparekey_x86(struct gf128hash_key_x86 *key, const u8 raw_key[16],
 		polyval_mul_generic(&key->h_powers[i],
 				    &key->h_powers[NUM_H_POWERS - 1]);
 	}
-	for (int i = 0; i < NUM_H_POWERS; i++)
-		key->h_powers_xored[i] = key->h_powers[i].lo ^
-					 key->h_powers[i].hi;
+	/*
+	 * Decide which key layout to use.  This fallback code is reached when
+	 * the static keys aren't set, which might be because
+	 * gf128hash_mod_init() hasn't run yet.  Check the CPU features directly
+	 * here so that keys prepared before gf128hash_mod_init() have the same
+	 * layout as keys prepared afterwards.
+	 */
+	if (gf128hash_use_vpclmul_avx2()) {
+		static const u8 indices[8] = { 0, 2, 1, 3, 4, 6, 5, 7 };
+
+		for (int i = 0; i < NUM_H_POWERS; i++)
+			key->h_powers_xored[i] = key->h_powers[indices[i]].lo ^
+						 key->h_powers[indices[i]].hi;
+	} else {
+		for (int i = 0; i < NUM_H_POWERS; i++)
+			key->h_powers_xored[i] = key->h_powers[i].lo ^
+						 key->h_powers[i].hi;
+	}
 	polyval_mul_xm64_generic(&key->h_times_xm64,
 				 &key->h_powers[NUM_H_POWERS - 1]);
 }
@@ -174,6 +207,8 @@ gf128hash_blocks_x86(struct polyval_elem *acc,
 			kernel_fpu_begin_mask(0);
 			if (is_ghash)
 				__ghash_blocks_x86_fpu(acc, key, data, n);
+			else if (static_branch_likely(&have_vpclmul_avx2))
+				polyval_blocks_vpclmul_avx2(acc, key, data, n);
 			else if (static_branch_likely(&have_pclmul_avx))
 				polyval_blocks_pclmul_avx(acc, key, data, n);
 			else
@@ -216,7 +251,10 @@ static void gf128hash_mod_init_arch(void)
 	if (!gf128hash_use_pclmul())
 		return;
 
-	if (gf128hash_use_pclmul_avx())
+	if (gf128hash_use_pclmul_avx()) {
 		static_branch_enable(&have_pclmul_avx);
+		if (gf128hash_use_vpclmul_avx2())
+			static_branch_enable(&have_vpclmul_avx2);
+	}
 	static_branch_enable(&have_pclmul);
 }
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH 07/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with VPCLMULQDQ and AVX512
  2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
                   ` (5 preceding siblings ...)
  2026-11-29 20:02 ` [PATCH 06/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with VPCLMULQDQ and AVX2 Eric Biggers
@ 2026-11-29 20:02 ` Eric Biggers
  2026-11-29 20:02 ` [PATCH 08/11] lib/crypto: x86/aes-gcm: Migrate AES-NI optimized code into library Eric Biggers
                   ` (3 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, Eric Biggers

Add a VPCLMULQDQ + AVX512 implementation of GHASH and POLYVAL for x86_64
in lib/crypto/x86/gf128hash-vpclmul-avx512.S, providing:

- {ghash,polyval}_preparekey_vpclmul_avx512()
- {ghash,polyval}_blocks_vpclmul_avx512()

The file is derived from arch/x86/crypto/aes-gcm-vaes-avx512.S, so it
inherits its copyright and license.  This speeds up both algorithms on
AVX512 CPUs by hashing four 128-bit blocks per ZMM vector (16 blocks per
stride), and prepares for migrating the VAES+AVX512 AES-GCM code into
lib/crypto/.

Key implementation choices for AVX512:

- The 16-block main loop uses schoolbook multiplication with 3-input
  vpternlogd rather than Karatsuba (matching aes-gcm-vaes-avx512.S and
  avoiding 128 bytes of extra key-struct storage).

- Key preparation stores H^1 * x^-64 mod G(x) in key->h_times_xm64 and
  computes H^16 through H^1 in parallel via squaring (H^1 -> H^2),
  2-wide YMM multiplication ([H^4, H^3]), and 4-wide ZMM multiplications
  by [H^4, H^4, H^4, H^4], precomputing x^-64 multiples so each
  multiplication needs only a single reduction step.

- Trailing 1..15 blocks are processed in a single masked loop that sums
  unreduced products across all remaining vectors and performs one
  deferred reduction at the end; on the final vector (with 1 <= r <= 4
  blocks), BMI2 bzhi + a zero-masked input load is paired with an
  unmasked 64-byte load of [H^r..H^1, 0..].  Single-block calls (nblocks
  == 1) use a strictly 128-bit XMM fast path with key->h_times_xm64 to
  avoid ZMM overhead and vzeroupper.

To accommodate the 16 precomputed key powers and three trailing zeroized
padding blocks needed for the unmasked 64-byte key-power load on 1..3
trailing blocks, extend 'struct gf128hash_key_x86' into a union of the
8-power and 16-power layouts (growing it from 208 to 320 bytes).

To keep H^1 and H^1 * x^-64 at the same offsets in both layouts, place
h_powers[8] at the end of the union and h_times_xm64 after the padding.
This allows single-block and generic fallback code to access them
unconditionally.

Benchmark results on AMD Ryzen 9 9950X (Zen 5) using ghash_kunit and
polyval_kunit:

    Length   GHASH before  GHASH after   POLYVAL before  POLYVAL after
    ------   ------------  -----------   --------------  -------------
         1       129 MB/s     129 MB/s         131 MB/s       128 MB/s
        16      2157 MB/s    2122 MB/s        2232 MB/s      2298 MB/s
        64      7286 MB/s    6353 MB/s        7156 MB/s      6530 MB/s
       127      6615 MB/s    6896 MB/s        6785 MB/s      6962 MB/s
       128     11769 MB/s   11907 MB/s       11663 MB/s     12245 MB/s
       200      9112 MB/s   11263 MB/s        8863 MB/s     10913 MB/s
       256     16585 MB/s   21921 MB/s       16529 MB/s     22183 MB/s
       511     14640 MB/s   20077 MB/s       14630 MB/s     20459 MB/s
       512     17740 MB/s   28403 MB/s       20235 MB/s     28070 MB/s
      1024     20218 MB/s   33497 MB/s       22206 MB/s     31997 MB/s
      3173     20521 MB/s   34829 MB/s       20545 MB/s     35064 MB/s
      4096     21706 MB/s   37833 MB/s       20717 MB/s     37368 MB/s
     16384     21577 MB/s   39348 MB/s       22174 MB/s     39020 MB/s

Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 include/crypto/gf128hash.h                |  32 +-
 lib/crypto/Makefile                       |   3 +-
 lib/crypto/x86/gf128hash-cpu.h            |   9 +
 lib/crypto/x86/gf128hash-pclmul.S         |   8 +-
 lib/crypto/x86/gf128hash-vpclmul-avx2.S   |   8 +-
 lib/crypto/x86/gf128hash-vpclmul-avx512.S | 516 ++++++++++++++++++++++
 lib/crypto/x86/gf128hash.h                |  90 +++-
 7 files changed, 631 insertions(+), 35 deletions(-)
 create mode 100644 lib/crypto/x86/gf128hash-vpclmul-avx512.S

diff --git a/include/crypto/gf128hash.h b/include/crypto/gf128hash.h
index 4d2109a3362c0..5c38fc38fd9c4 100644
--- a/include/crypto/gf128hash.h
+++ b/include/crypto/gf128hash.h
@@ -36,14 +36,34 @@ struct polyval_elem {
 
 /* Format of struct ghash_key and struct polyval_key on x86_64 */
 struct gf128hash_key_x86 {
-	/* Powers of the hash key H^8 through H^1, in POLYVAL format */
-	struct polyval_elem h_powers[8];
 	/*
-	 * Halves of each entry of @h_powers XOR'd together.  If
-	 * gf128hash_use_vpclmul_avx2(), they're in the order H^8, H^6, H^7,
-	 * H^5, H^4, H^2, H^3, H^1.  Otherwise they're in the order H^8..H^1.
+	 * If gf128hash_use_vpclmul_avx512(), then h_powers16 is used.
+	 * Otherwise the other member of the union is used.  In either case, H^1
+	 * is in the same place (h_powers16[15] or equivalently h_powers[7]).
 	 */
-	__le64 h_powers_xored[8];
+	union {
+		/* Powers of the hash key H^16 through H^1, in POLYVAL format */
+		struct polyval_elem h_powers16[16];
+
+		struct {
+			/*
+			 * Halves of each entry of @h_powers XOR'd together.  If
+			 * gf128hash_use_vpclmul_avx2(), they're in the order
+			 * H^8, H^6, H^7, H^5, H^4, H^2, H^3, H^1.  Otherwise
+			 * they're in the order H^8..H^1.
+			 */
+			__le64 h_powers_xored[8];
+			/* Unused space (set to zero) */
+			u8 unused[64];
+			/*
+			 * Powers of the hash key H^8 through H^1, in POLYVAL
+			 * format
+			 */
+			struct polyval_elem h_powers[8];
+		};
+	};
+	/* Padding for AVX512 loads (set to zero) */
+	struct polyval_elem padding[3];
 	/*
 	 * H^1 * x^-64 mod G(x) in POLYVAL format.  This is used to optimize
 	 * single-block multiplications using 1-step reduction.
diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile
index 9d3ecc643a844..c057c0d896a4f 100644
--- a/lib/crypto/Makefile
+++ b/lib/crypto/Makefile
@@ -43,7 +43,8 @@ endif
 
 libgf128hash-$(CONFIG_RISCV) += riscv/ghash-riscv64-zvkg.o
 libgf128hash-$(CONFIG_X86_64) += x86/gf128hash-pclmul.o \
-				 x86/gf128hash-vpclmul-avx2.o
+				 x86/gf128hash-vpclmul-avx2.o \
+				 x86/gf128hash-vpclmul-avx512.o
 endif # CONFIG_CRYPTO_LIB_GF128HASH_ARCH
 
 # clean-files must be defined unconditionally
diff --git a/lib/crypto/x86/gf128hash-cpu.h b/lib/crypto/x86/gf128hash-cpu.h
index 5045b41bf8d73..ed7500e665d8d 100644
--- a/lib/crypto/x86/gf128hash-cpu.h
+++ b/lib/crypto/x86/gf128hash-cpu.h
@@ -36,4 +36,13 @@ static inline bool gf128hash_use_vpclmul_avx2(void)
 	       cpu_feature_enabled(X86_FEATURE_VPCLMULQDQ);
 }
 
+static inline bool gf128hash_use_vpclmul_avx512(void)
+{
+	return gf128hash_use_vpclmul_avx2() &&
+	       cpu_feature_enabled(X86_FEATURE_AVX512BW) &&
+	       cpu_feature_enabled(X86_FEATURE_AVX512VL) &&
+	       cpu_feature_enabled(X86_FEATURE_BMI2) &&
+	       !cpu_feature_enabled(X86_FEATURE_PREFER_YMM);
+}
+
 #endif /* _LIB_CRYPTO_X86_GF128HASH_CPU_H */
diff --git a/lib/crypto/x86/gf128hash-pclmul.S b/lib/crypto/x86/gf128hash-pclmul.S
index 7bb0a25b9df02..5814a6aa1f1ce 100644
--- a/lib/crypto/x86/gf128hash-pclmul.S
+++ b/lib/crypto/x86/gf128hash-pclmul.S
@@ -187,10 +187,10 @@
 // Offsets in struct gf128hash_key_x86, using the 8-power non-permuted layout.
 // h_powers[0..7] holds H^8..H^1, h_powers_xored[i] holds the XOR of the two
 // 64-bit halves of h_powers[i], and h_times_xm64 holds H^1 * x^-64 mod G(x).
-#define OFFSETOF_H_POWERS	0
-#define OFFSETOFEND_H_POWERS	128
-#define OFFSETOF_H_POWERS_XORED	128
-#define OFFSETOF_H_TIMES_XM64	192
+#define OFFSETOF_H_POWERS_XORED	0
+#define OFFSETOF_H_POWERS	128
+#define OFFSETOFEND_H_POWERS	256
+#define OFFSETOF_H_TIMES_XM64	304
 
 .text
 
diff --git a/lib/crypto/x86/gf128hash-vpclmul-avx2.S b/lib/crypto/x86/gf128hash-vpclmul-avx2.S
index 9c38148445aa3..57585f54a8f64 100644
--- a/lib/crypto/x86/gf128hash-vpclmul-avx2.S
+++ b/lib/crypto/x86/gf128hash-vpclmul-avx2.S
@@ -116,10 +116,10 @@
 // h_powers[0..7] holds H^8..H^1, h_powers_xored[0..7] holds the XORs of the two
 // 64-bit halves of H^8, H^6, H^7, H^5, H^4, H^2, H^3, H^1 (in that order), and
 // h_times_xm64 holds H^1 * x^-64 mod G(x).
-#define OFFSETOF_H_POWERS	0
-#define OFFSETOFEND_H_POWERS	128
-#define OFFSETOF_H_POWERS_XORED	128
-#define OFFSETOF_H_TIMES_XM64	192
+#define OFFSETOF_H_POWERS_XORED	0
+#define OFFSETOF_H_POWERS	128
+#define OFFSETOFEND_H_POWERS	256
+#define OFFSETOF_H_TIMES_XM64	304
 
 .text
 
diff --git a/lib/crypto/x86/gf128hash-vpclmul-avx512.S b/lib/crypto/x86/gf128hash-vpclmul-avx512.S
new file mode 100644
index 0000000000000..af7c2d05ff989
--- /dev/null
+++ b/lib/crypto/x86/gf128hash-vpclmul-avx512.S
@@ -0,0 +1,516 @@
+/* SPDX-License-Identifier: Apache-2.0 OR BSD-2-Clause */
+//
+// Accelerated GHASH and POLYVAL implementation with VPCLMULQDQ and AVX512
+//
+// Copyright 2024 Google LLC
+//
+// Author: Eric Biggers <ebiggers@google.com>
+//
+//------------------------------------------------------------------------------
+//
+// This file is dual-licensed, meaning that you can use it under your choice of
+// either of the following two licenses:
+//
+// Licensed under the Apache License 2.0 (the "License").  You may obtain a copy
+// of the License at
+//
+//	http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// or
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+//    this list of conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in the
+//    documentation and/or other materials provided with the distribution.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+//
+//------------------------------------------------------------------------------
+//
+// This file implements GHASH and POLYVAL using the VPCLMULQDQ instruction on
+// 512-bit vectors (zmm registers), each holding four 128-bit blocks.  It also
+// requires AVX512BW (for vmovdqu8, 512-bit vpshufb, and kmovq), AVX512VL (for
+// EVEX-coded instructions such as vpternlogd on xmm and ymm registers), and
+// BMI2 (for bzhi).  The math is documented in gf128hash-pclmul.S.  The design
+// is similar to gf128hash-vpclmul-avx2.S, with the following differences:
+//
+// - The main loop processes 16 blocks per stride, as 4 vectors.  Lanes 0..3 of
+//   each vector hold 4 consecutive blocks in order, so the data vectors are
+//   multiplied by the key power vectors [H^16..H^13], [H^12..H^9], [H^8..H^5],
+//   and [H^4..H^1] (written [lane 0..lane 3]), which stay in registers.  As in
+//   the AVX2 code, the unreduced products are summed in each lane, all lanes
+//   are reduced at once, and the reduced lanes are XOR'd together.
+//
+// - The main loop uses schoolbook multiplication rather than Karatsuba.  The
+//   3-input XOR provided by vpternlogd ($0x96: dst ^= src1 ^ src2) helps
+//   schoolbook more than Karatsuba, storing the XOR'd halves of all 16 key
+//   powers for Karatsuba would add 128 bytes to struct gf128hash_key_x86, and
+//   using schoolbook also matches aes-gcm-vaes-avx512.S (which shares the key
+//   struct).  As in gf128hash-vpclmul-avx2.S, vectors 1..3 are processed before
+//   vector 0 so the loop-carried dependency on the accumulator enters as late
+//   as possible.
+//
+// - The key uses the 16-power layout of struct gf128hash_key_x86:
+//   h_powers16[0..15] holds H^16..H^1 and is followed by 3 zeroized padding
+//   blocks, and then h_times_xm64 (H^1 * x^-64 mod G(x)).  h_powers16[15] and
+//   h_times_xm64 are at the same offsets as in the 8-power layout.  The padding
+//   allows any remaining 1..15 blocks after the 16-block loop to be processed
+//   in one masked loop (with a single deferred reduction at the end): on the
+//   last vector (with 1 <= r <= 4 blocks), a zero-masked load avoids reading
+//   past the end of the data, and an unmasked load reads [H^r..H^1, 0, ...].
+//
+// - The nblocks == 1 fast path uses only xmm registers (avoiding the overhead
+//   of zmm registers and of vzeroupper) and uses key->h_times_xm64 so that only
+//   one reduction step is needed, matching gf128hash-pclmul.S.
+//
+// - preparekey stores H^1 * x^-64 mod G(x) in key->h_times_xm64, squares H^1 to
+//   get H^2, computes [H^4, H^3] by multiplying [H^2, H^1] by [H^2, H^2], and
+//   then computes [H^8..H^5], [H^12..H^9], and [H^16..H^13] by repeatedly
+//   multiplying by [H^4, H^4, H^4, H^4], precomputing x^-64 multiples so each
+//   multiplication needs only one reduction step.
+//
+// - Only zmm0..zmm15 are used (never zmm16..zmm31), so vzeroupper resets all
+//   dirty upper vector state (avoiding Hi16_ZMM XSAVE overhead) and 128/256-bit
+//   operations can use shorter VEX encodings where applicable.
+
+#include <linux/linkage.h>
+
+.section .rodata
+.p2align 4
+
+	// vpshufb mask that reverses the order of the bytes in a 16-byte block
+.Lbswap_mask:
+	.octa	0x000102030405060708090a0b0c0d0e0f
+
+	// Mask for multiplying by x mod G(x): G(x) - x^128 = x^127 + x^126 +
+	// x^121 + 1 (bits 127, 126, 121, and 0), and bit 64 for the carry from
+	// bit 63 that vpaddq doesn't propagate
+.Lgfpoly_and_internal_carrybit:
+	.octa	0xc2000000000000010000000000000001
+
+	// (G(x) - x^128 - 1) / x^64 = x^63 + x^62 + x^57, the constant used to
+	// multiply by x^-64 mod G(x)
+.Lgfpoly:
+	.quad	0xc200000000000000
+
+// Offsets in struct gf128hash_key_x86, using the 16-power layout.
+// h_powers16[0..15] holds H^16..H^1, followed by 3 zeroized padding blocks at
+// OFFSETOFEND_H_POWERS, and then h_times_xm64 (H^1 * x^-64 mod G(x)).
+#define OFFSETOF_H_POWERS	0
+#define OFFSETOFEND_H_POWERS	256
+#define OFFSETOF_H_TIMES_XM64	304
+
+.text
+
+// Set each 128-bit lane of \dst to dot(lane of \a, lane of \b), given
+// \a_times_xm64 = \a * x^-64 mod G(x) in each lane (see gf128hash-pclmul.S for
+// the math).  Works on xmm, ymm, and zmm registers.  \dst may alias \a,
+// \a_times_xm64, or \b.  \gfpoly must contain .Lgfpoly in the low qword of each
+// lane.  Clobbers \t0 and \t1.  \gfpoly, \t0, and \t1 must be distinct from
+// each other and from the other operands.
+.macro	_gf128hash_mul	a, a_times_xm64, b, dst, gfpoly, t0, t1
+	vpclmulqdq	$0x01, \a, \b, \t0		// a_L * b_H
+	vpclmulqdq	$0x00, \a_times_xm64, \b, \t1	// (a*x^-64)_L * b_L
+	vpxord		\t1, \t0, \t0			// MI
+	vpclmulqdq	$0x11, \a, \b, \t1		// a_H * b_H
+	vpclmulqdq	$0x10, \a_times_xm64, \b, \dst	// (a*x^-64)_H * b_L
+	vpxord		\t1, \dst, \dst			// HI
+	vpclmulqdq	$0x00, \gfpoly, \t0, \t1	// MI_L*(x^63+x^62+x^57)
+	vpshufd		$0x4e, \t0, \t0			// MI_H + MI_L * x^64
+	vpternlogd	$0x96, \t1, \t0, \dst		// Fold MI into HI
+.endm
+
+// Like _gf128hash_mul, but compute dot(\a, \a) in each 128-bit lane.  In
+// GF(2)[x], the cross terms cancel: (a_L + a_H * x^64)^2 = (a_L)^2 +
+// (a_H)^2 * x^128.  So only 2 vpclmulqdq are needed for the product, and the
+// initial MI is 0, so the first reduction step sets MI = LO * x^-64.  \dst may
+// alias \a.  Clobbers \t0 and \t1.  \gfpoly, \t0, and \t1 must be distinct from
+// each other and from \a and \dst.
+.macro	_gf128hash_square	a, dst, gfpoly, t0, t1
+	vpclmulqdq	$0x00, \a, \a, \t0		// LO = (a_L)^2
+	vpclmulqdq	$0x11, \a, \a, \dst		// HI = (a_H)^2
+	vpclmulqdq	$0x00, \gfpoly, \t0, \t1	// LO_L*(x^63+x^62+x^57)
+	vpshufd		$0x4e, \t0, \t0			// LO_H + LO_L * x^64
+	vpxord		\t0, \t1, \t1			// MI = LO * x^-64
+	vpclmulqdq	$0x00, \gfpoly, \t1, \t0	// MI_L*(x^63+x^62+x^57)
+	vpshufd		$0x4e, \t1, \t1			// MI_H + MI_L * x^64
+	vpternlogd	$0x96, \t0, \t1, \dst		// Fold MI into HI
+.endm
+
+// Reduce the 256-bit products LO + MI * x^64 + HI * x^128 given in each 128-bit
+// lane of \lo, \mi, and \hi: multiply them by x^-128 mod G(x) and store the
+// 128-bit results in \hi.  This is done in two steps, MI += LO * x^-64 then
+// HI += MI * x^-64.  Works on xmm, ymm, and zmm registers.  \gfpoly must
+// contain .Lgfpoly in the low qword of each lane.  Clobbers \lo, \mi, and \tmp.
+// All operands must be distinct registers.
+.macro	_gf128hash_reduce	lo, mi, hi, gfpoly, tmp
+	vpclmulqdq	$0x00, \gfpoly, \lo, \tmp	// LO_L*(x^63+x^62+x^57)
+	vpshufd		$0x4e, \lo, \lo			// LO_H + LO_L * x^64
+	vpternlogd	$0x96, \tmp, \lo, \mi		// Fold LO into MI
+	vpclmulqdq	$0x00, \gfpoly, \mi, \tmp	// MI_L*(x^63+x^62+x^57)
+	vpshufd		$0x4e, \mi, \mi			// MI_H + MI_L * x^64
+	vpternlogd	$0x96, \tmp, \mi, \hi		// Fold MI into HI
+.endm
+
+// void {ghash,polyval}_preparekey_vpclmul_avx512(struct gf128hash_key_x86 *key,
+//						  const u8 raw_key[16]);
+//
+// Given the raw GHASH key (\is_ghash=1) or POLYVAL key (\is_ghash=0), set:
+// - key->h_powers16[0..15] to H^16..H^1 in POLYVAL format
+// - key->padding[0..2] to zero
+// - key->h_times_xm64 to H^1 * x^-64 mod G(x)
+.macro	_gf128hash_preparekey	is_ghash
+	.set	KEY,		%rdi
+	.set	RAW_KEY,	%rsi
+	.set	POWERS_PTR,	%rdx
+	// %eax is used as a loop counter.
+	.set	TMP0,		%zmm0
+	.set	TMP0_YMM,	%ymm0
+	.set	TMP0_XMM,	%xmm0
+	.set	TMP1,		%zmm1
+	.set	TMP1_YMM,	%ymm1
+	.set	TMP1_XMM,	%xmm1
+	.set	H_CUR,		%zmm2
+	.set	H_CUR_YMM,	%ymm2
+	.set	H_CUR_XMM,	%xmm2
+	.set	H_INC,		%zmm3
+	.set	H_INC_YMM,	%ymm3
+	.set	H_INC_XMM,	%xmm3
+	.set	H_INC_XM64,	%zmm4
+	.set	H_INC_XM64_YMM,	%ymm4
+	.set	H_INC_XM64_XMM,	%xmm4
+	.set	GFPOLY,		%zmm5
+	.set	GFPOLY_YMM,	%ymm5
+	.set	GFPOLY_XMM,	%xmm5
+
+	vmovdqu		(RAW_KEY), H_CUR_XMM
+.if \is_ghash
+	// Convert the GHASH key to POLYVAL format: byte-reverse it, then
+	// multiply it by x mod G(x).  See gf128hash-pclmul.S for details.  Here
+	// vpternlogd $0x78 does the AND and XOR: dst ^= src1 & src2.
+	vpshufb		.Lbswap_mask(%rip), H_CUR_XMM, H_CUR_XMM
+	vpshufd		$0xd3, H_CUR_XMM, TMP0_XMM
+	vpsrad		$31, TMP0_XMM, TMP0_XMM
+	vpaddq		H_CUR_XMM, H_CUR_XMM, H_CUR_XMM
+	vpternlogd	$0x78, .Lgfpoly_and_internal_carrybit(%rip), \
+			TMP0_XMM, H_CUR_XMM
+.endif
+
+	// Point POWERS_PTR to h_powers16[12], and zeroize the 3 padding blocks
+	// (addressed via POWERS_PTR for compact disp8 encoding).
+	lea		OFFSETOFEND_H_POWERS-64(KEY), POWERS_PTR
+	vpxor		TMP0_XMM, TMP0_XMM, TMP0_XMM
+	vmovdqu		TMP0_YMM, 64(POWERS_PTR)	// padding[0..1]
+	vmovdqu		TMP0_XMM, 64+32(POWERS_PTR)	// padding[2]
+
+	vpbroadcastq	.Lgfpoly(%rip), GFPOLY
+
+	// Compute and store H^1 * x^-64 mod G(x) in h_times_xm64.
+	vpclmulqdq	$0x00, GFPOLY_XMM, H_CUR_XMM, TMP1_XMM
+	vpshufd		$0x4e, H_CUR_XMM, TMP0_XMM
+	vpxor		TMP0_XMM, TMP1_XMM, TMP1_XMM
+	vmovdqu		TMP1_XMM, OFFSETOF_H_TIMES_XM64(KEY)
+
+	// Square H^1 to get H^2, and compute H^2 * x^-64 mod G(x).
+	_gf128hash_square H_CUR_XMM, H_INC_XMM, GFPOLY_XMM, TMP0_XMM, TMP1_XMM
+	vpclmulqdq	$0x00, GFPOLY_XMM, H_INC_XMM, H_INC_XM64_XMM
+	vpshufd		$0x4e, H_INC_XMM, TMP0_XMM
+	vpxor		TMP0_XMM, H_INC_XM64_XMM, H_INC_XM64_XMM
+
+	// Create H_CUR_YMM = [H^2, H^1], H_INC_YMM = [H^2, H^2], and
+	// H_INC_XM64_YMM = [H^2 * x^-64, H^2 * x^-64].
+	vinserti128	$1, H_CUR_XMM, H_INC_YMM, H_CUR_YMM
+	vinserti128	$1, H_INC_XMM, H_INC_YMM, H_INC_YMM
+	vinserti128	$1, H_INC_XM64_XMM, H_INC_XM64_YMM, H_INC_XM64_YMM
+
+	// Compute H_INC_YMM = [H^4, H^3], then create
+	// H_CUR = [H^4, H^3, H^2, H^1], H_INC = [H^4, H^4, H^4, H^4], and
+	// H_INC_XM64 = [H^4 * x^-64, ...].
+	_gf128hash_mul	H_INC_YMM, H_INC_XM64_YMM, H_CUR_YMM, H_INC_YMM, \
+			GFPOLY_YMM, TMP0_YMM, TMP1_YMM
+	vinserti64x4	$1, H_CUR_YMM, H_INC, H_CUR
+	vshufi64x2	$0, H_INC, H_INC, H_INC
+	vpclmulqdq	$0x00, GFPOLY, H_INC, H_INC_XM64
+	vpshufd		$0x4e, H_INC, TMP0
+	vpxord		TMP0, H_INC_XM64, H_INC_XM64
+
+	// Store [H^4, H^3, H^2, H^1] in h_powers16[12..15].
+	vmovdqu8	H_CUR, (POWERS_PTR)
+
+	// Compute [H^8..H^5], [H^12..H^9], and [H^16..H^13], and store them in
+	// h_powers16[8..11], [4..7], and [0..3] respectively.
+	mov		$3, %eax
+.Lpreparekey_next\@:
+	sub		$64, POWERS_PTR
+	_gf128hash_mul	H_INC, H_INC_XM64, H_CUR, H_CUR, GFPOLY, TMP0, TMP1
+	vmovdqu8	H_CUR, (POWERS_PTR)
+	dec		%eax
+	jnz		.Lpreparekey_next\@
+
+	vzeroupper
+	RET
+.endm
+
+// XOR together the four 128-bit lanes of \src (whose low lane is \src_xmm), and
+// store the result in \dst_xmm.  Writing \dst_xmm zeroes the upper lanes of the
+// corresponding zmm register.  \dst_xmm may alias \src_xmm; \t0_xmm, \t1_xmm,
+// and \t2_xmm are temporaries and must be distinct from each other and from
+// \src_xmm and \dst_xmm.  \src_xmm, \dst_xmm, and \t0_xmm must be in
+// %xmm0..%xmm15 (for VEX-encoded vpxor).
+.macro	_horizontal_xor	src, src_xmm, dst_xmm, t0_xmm, t1_xmm, t2_xmm
+	vextracti32x4	$1, \src, \t0_xmm
+	vextracti32x4	$2, \src, \t1_xmm
+	vextracti32x4	$3, \src, \t2_xmm
+	vpxor		\t0_xmm, \src_xmm, \dst_xmm
+	vpternlogd	$0x96, \t1_xmm, \t2_xmm, \dst_xmm
+.endm
+
+// Update ACC with 16 blocks (four 64-byte vectors) of data from DATA, using
+// aggregated schoolbook multiplication.  ACC must hold the accumulator in lane
+// 0 and zero in lanes 1..3, and this property is preserved.  After
+// byte-reversing (if \bswap_data=1) and adding ACC to DATA0, the products are
+// summed per lane for i = 0..3 as:
+//
+//	LO = sum LO_i,            where LO_i  = (H_POW{4-i})_L * (DATAi)_L
+//	MI = sum (MI_ia + MI_ib), where MI_ia = (H_POW{4-i})_L * (DATAi)_H and
+//					MI_ib = (H_POW{4-i})_H * (DATAi)_L
+//	HI = sum HI_i,            where HI_i  = (H_POW{4-i})_H * (DATAi)_H
+//
+// Vectors 1..3 are processed before vector 0 so that the loop-carried
+// dependency on ACC enters as late as possible.
+.macro	_gf128hash_4x	bswap_data
+	vmovdqu8	1*64(DATA), DATA1
+	vmovdqu8	2*64(DATA), DATA2
+	vmovdqu8	3*64(DATA), DATA3
+	vmovdqu8	0*64(DATA), DATA0
+.if \bswap_data
+	vpshufb		BSWAP_MASK, DATA1, DATA1
+	vpshufb		BSWAP_MASK, DATA2, DATA2
+	vpshufb		BSWAP_MASK, DATA3, DATA3
+	vpshufb		BSWAP_MASK, DATA0, DATA0
+.endif
+
+	// Vectors 1..3: [M_4..M_7] * [H^12..H^9], [M_8..M_11] * [H^8..H^5], and
+	// [M_12..M_15] * [H^4..H^1].  Initialize (LO, MI, HI) with their sum.
+	vpclmulqdq	$0x00, H_POW3, DATA1, LO	// LO_1
+	vpclmulqdq	$0x00, H_POW2, DATA2, TMP0	// LO_2
+	vpclmulqdq	$0x00, H_POW1, DATA3, TMP1	// LO_3
+	vpternlogd	$0x96, TMP1, TMP0, LO		// sum(LO_{1..3})
+
+	vpclmulqdq	$0x01, H_POW3, DATA1, MI	// MI_1a
+	vpclmulqdq	$0x01, H_POW2, DATA2, TMP0	// MI_2a
+	vpclmulqdq	$0x01, H_POW1, DATA3, TMP1	// MI_3a
+	vpternlogd	$0x96, TMP1, TMP0, MI		// sum(MI_{1..3}a)
+	vpclmulqdq	$0x10, H_POW3, DATA1, TMP0	// MI_1b
+	vpclmulqdq	$0x10, H_POW2, DATA2, TMP1	// MI_2b
+	vpternlogd	$0x96, TMP1, TMP0, MI		// + MI_1b + MI_2b
+	vpclmulqdq	$0x10, H_POW1, DATA3, TMP0	// MI_3b
+	vpxord		TMP0, MI, MI			// sum(MI_{1..3}{a,b})
+
+	vpclmulqdq	$0x11, H_POW3, DATA1, HI	// HI_1
+	vpclmulqdq	$0x11, H_POW2, DATA2, DATA2	// HI_2
+	vpclmulqdq	$0x11, H_POW1, DATA3, DATA3	// HI_3
+	vpternlogd	$0x96, DATA3, DATA2, HI		// sum(HI_{1..3})
+
+	// Vector 0: [M_0 + ACC, M_1..M_3] * [H^16..H^13].  Add to (LO, MI, HI),
+	// then reduce all 4 lanes and XOR them together into ACC_XMM.  Writing
+	// ACC_XMM zeroes lanes 1..3 of ACC.
+	vpxord		ACC, DATA0, DATA0
+	vpclmulqdq	$0x00, H_POW4, DATA0, TMP0	// LO_0
+	vpclmulqdq	$0x01, H_POW4, DATA0, TMP1	// MI_0a
+	vpclmulqdq	$0x10, H_POW4, DATA0, DATA2	// MI_0b
+	vpclmulqdq	$0x11, H_POW4, DATA0, DATA0	// HI_0
+	vpxord		TMP0, LO, LO		// LO = sum(LO_{0..3})
+	vpternlogd	$0x96, DATA2, TMP1, MI	// MI = sum(MI_{0..3}{a,b})
+	vpxord		DATA0, HI, HI		// HI = sum(HI_{0..3})
+	_gf128hash_reduce LO, MI, HI, GFPOLY, TMP0
+	_horizontal_xor	HI, HI_XMM, ACC_XMM, DATA0_XMM, DATA1_XMM, DATA2_XMM
+.endm
+
+// void
+// {ghash,polyval}_blocks_vpclmul_avx512(struct polyval_elem *acc,
+//					 const struct gf128hash_key_x86 *key,
+//					 const u8 *data, size_t nblocks);
+//
+// Update the POLYVAL-format accumulator @acc with @nblocks >= 1 full 16-byte
+// blocks from @data.  If \bswap_data=1 (GHASH), each block is byte-reversed to
+// convert it to POLYVAL format.
+.macro	_gf128hash_blocks	bswap_data
+	.set	ACC_PTR,	%rdi
+	.set	KEY,		%rsi
+	.set	DATA,		%rdx
+	.set	NBLOCKS,	%rcx
+	.set	NBYTES,		%rcx	// Reused as byte count in the tail loop
+	.set	POWERS_PTR,	%rax
+	.set	ALL_ONES,	%r8
+
+	// %r9 and %k1 are used as temporary registers.
+	.set	DATA0,		%zmm0
+	.set	DATA0_XMM,	%xmm0
+	.set	DATA1,		%zmm1
+	.set	DATA1_XMM,	%xmm1
+	.set	DATA2,		%zmm2
+	.set	DATA2_XMM,	%xmm2
+	.set	DATA3,		%zmm3
+	.set	DATA3_XMM,	%xmm3
+	.set	BSWAP_MASK,	%zmm4
+	.set	ACC,		%zmm5
+	.set	ACC_XMM,	%xmm5
+	.set	H_POW4,		%zmm6
+	.set	H_POW3,		%zmm7
+	.set	H_POW2,		%zmm8
+	.set	H_POW1,		%zmm9
+	.set	GFPOLY,		%zmm10
+	.set	GFPOLY_XMM,	%xmm10
+	.set	TMP0,		%zmm11
+	.set	TMP1,		%zmm12
+	.set	LO,		%zmm13
+	.set	MI,		%zmm14
+	.set	HI,		%zmm15
+	.set	HI_XMM,		%xmm15
+
+	// Load the accumulator into lane 0 of ACC.  This zeroes lanes 1..3.
+	vmovdqu		(ACC_PTR), ACC_XMM
+
+	// Handle nblocks == 1 specially, using only xmm registers.  This case
+	// is common (e.g. for 1-block associated data, the incremental AES-GCM
+	// lengths block, and the HCTR2 length and tweak blocks).
+	cmp		$1, NBLOCKS
+	jne		.Lblocks_more_than_1block\@
+
+	vmovq		.Lgfpoly(%rip), GFPOLY_XMM
+	vmovdqu		(DATA), DATA0_XMM
+.if \bswap_data
+	vpshufb		.Lbswap_mask(%rip), DATA0_XMM, DATA0_XMM
+.endif
+	vpxor		DATA0_XMM, ACC_XMM, ACC_XMM
+	vmovdqu		OFFSETOFEND_H_POWERS-16(KEY), DATA0_XMM	// H^1
+	vmovdqu		OFFSETOF_H_TIMES_XM64(KEY), DATA1_XMM	// H^1 * x^-64
+	_gf128hash_mul	DATA0_XMM, DATA1_XMM, ACC_XMM, ACC_XMM, GFPOLY_XMM, \
+			DATA2_XMM, DATA3_XMM
+	vmovdqu		ACC_XMM, (ACC_PTR)
+	// No vzeroupper is needed since only xmm registers were used.
+	RET
+
+.Lblocks_more_than_1block\@:
+.if \bswap_data
+	vbroadcasti32x4	.Lbswap_mask(%rip), BSWAP_MASK
+.endif
+	vpbroadcastq	.Lgfpoly(%rip), GFPOLY
+
+	// Process 16 blocks (256 bytes) at a time.
+	sub		$16, NBLOCKS
+	jb		.Lblocks_tail\@
+	vmovdqu8	OFFSETOF_H_POWERS+0*64(KEY), H_POW4	// [H^16..H^13]
+	vmovdqu8	OFFSETOF_H_POWERS+1*64(KEY), H_POW3	// [H^12..H^9]
+	vmovdqu8	OFFSETOF_H_POWERS+2*64(KEY), H_POW2	// [H^8..H^5]
+	vmovdqu8	OFFSETOF_H_POWERS+3*64(KEY), H_POW1	// [H^4..H^1]
+.Lblocks_loop_4x\@:
+	_gf128hash_4x	\bswap_data
+	add		$256, DATA
+	sub		$16, NBLOCKS
+	jae		.Lblocks_loop_4x\@
+
+.Lblocks_tail\@:
+	add		$16, NBLOCKS
+	jz		.Lblocks_done\@
+
+	// 1 <= n = NBLOCKS <= 15 blocks remain.  Multiply them by H^n..H^1,
+	// starting at h_powers16[16-n], using schoolbook multiplication.  Sum
+	// the unreduced products across all remaining vectors, and reduce once
+	// at the end.  After converting NBLOCKS to NBYTES (16*n <= 240 <= 255,
+	// so it fits in bzhi's 8-bit index), on each iteration bzhi builds a
+	// byte mask of all 1s if >= 64 bytes remain, or one bit per remaining
+	// data byte otherwise.  When fewer than 4 blocks remain, the
+	// zero-masked load doesn't access masked-out bytes, and the unmasked
+	// key-power load extends into the zeroized padding blocks; unused lanes
+	// of DATA0 are zero (vpshufb keeps them zero) and contribute 0.
+	shl		$4, NBLOCKS			// NBYTES = 16*n
+	mov		NBYTES, POWERS_PTR
+	neg		POWERS_PTR
+	lea		OFFSETOFEND_H_POWERS(KEY,POWERS_PTR), POWERS_PTR
+	mov		$-1, ALL_ONES
+
+	// First vector (up to 4 blocks): XOR ACC into block 0 (lanes 1..3 of
+	// ACC are zero) and initialize LO, MI, and HI.
+	bzhi		NBYTES, ALL_ONES, %r9
+	kmovq		%r9, %k1
+	vmovdqu8	(DATA), DATA0{%k1}{z}
+	vmovdqu8	(POWERS_PTR), H_POW1
+.if \bswap_data
+	vpshufb		BSWAP_MASK, DATA0, DATA0
+.endif
+	vpxord		ACC, DATA0, DATA0
+	vpclmulqdq	$0x00, H_POW1, DATA0, LO
+	vpclmulqdq	$0x01, H_POW1, DATA0, MI
+	vpclmulqdq	$0x10, H_POW1, DATA0, TMP0
+	vpclmulqdq	$0x11, H_POW1, DATA0, HI
+	vpxord		TMP0, MI, MI
+	sub		$64, NBYTES
+	jle		.Lblocks_tail_reduce\@
+
+	// Remaining vectors (1..3 iterations).
+.Lblocks_tail_loop\@:
+	add		$64, DATA
+	add		$64, POWERS_PTR
+	bzhi		NBYTES, ALL_ONES, %r9
+	kmovq		%r9, %k1
+	vmovdqu8	(DATA), DATA0{%k1}{z}
+	vmovdqu8	(POWERS_PTR), H_POW1
+.if \bswap_data
+	vpshufb		BSWAP_MASK, DATA0, DATA0
+.endif
+	vpclmulqdq	$0x00, H_POW1, DATA0, TMP0
+	vpclmulqdq	$0x01, H_POW1, DATA0, TMP1
+	vpclmulqdq	$0x10, H_POW1, DATA0, DATA2
+	vpclmulqdq	$0x11, H_POW1, DATA0, DATA1
+	vpxord		TMP0, LO, LO
+	vpternlogd	$0x96, DATA2, TMP1, MI
+	vpxord		DATA1, HI, HI
+	sub		$64, NBYTES
+	jg		.Lblocks_tail_loop\@
+
+.Lblocks_tail_reduce\@:
+	// Reduce all 4 lanes, and XOR them together into ACC_XMM.
+	_gf128hash_reduce LO, MI, HI, GFPOLY, TMP0
+	_horizontal_xor	HI, HI_XMM, ACC_XMM, DATA0_XMM, DATA1_XMM, DATA2_XMM
+
+.Lblocks_done\@:
+	vmovdqu		ACC_XMM, (ACC_PTR)
+	vzeroupper
+	RET
+.endm
+
+SYM_FUNC_START(ghash_preparekey_vpclmul_avx512)
+	_gf128hash_preparekey	1
+SYM_FUNC_END(ghash_preparekey_vpclmul_avx512)
+SYM_FUNC_START(polyval_preparekey_vpclmul_avx512)
+	_gf128hash_preparekey	0
+SYM_FUNC_END(polyval_preparekey_vpclmul_avx512)
+SYM_FUNC_START(ghash_blocks_vpclmul_avx512)
+	_gf128hash_blocks	1
+SYM_FUNC_END(ghash_blocks_vpclmul_avx512)
+SYM_FUNC_START(polyval_blocks_vpclmul_avx512)
+	_gf128hash_blocks	0
+SYM_FUNC_END(polyval_blocks_vpclmul_avx512)
diff --git a/lib/crypto/x86/gf128hash.h b/lib/crypto/x86/gf128hash.h
index 4470be6dfea2d..9fb826d62e829 100644
--- a/lib/crypto/x86/gf128hash.h
+++ b/lib/crypto/x86/gf128hash.h
@@ -8,18 +8,24 @@
 #include "gf128hash-cpu.h"
 
 #define NUM_H_POWERS 8
+#define NUM_H_POWERS_AVX512 16
 
 /* The assembly code assumes the following offsets. */
 static_assert(sizeof_field(struct gf128hash_key_x86, h_powers) ==
 	      NUM_H_POWERS * sizeof(struct polyval_elem));
-static_assert(offsetof(struct gf128hash_key_x86, h_powers) == 0);
-static_assert(offsetof(struct gf128hash_key_x86, h_powers_xored) == 128);
-static_assert(offsetof(struct gf128hash_key_x86, h_times_xm64) == 192);
-static_assert(sizeof(struct gf128hash_key_x86) == 208);
+static_assert(sizeof_field(struct gf128hash_key_x86, h_powers16) ==
+	      NUM_H_POWERS_AVX512 * sizeof(struct polyval_elem));
+static_assert(offsetof(struct gf128hash_key_x86, h_powers_xored) == 0);
+static_assert(offsetof(struct gf128hash_key_x86, h_powers) == 128);
+static_assert(offsetof(struct gf128hash_key_x86, h_powers16) == 0);
+static_assert(offsetof(struct gf128hash_key_x86, padding) == 256);
+static_assert(offsetof(struct gf128hash_key_x86, h_times_xm64) == 304);
+static_assert(sizeof(struct gf128hash_key_x86) == 320);
 
 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_pclmul);
 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_pclmul_avx);
 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_vpclmul_avx2);
+static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_vpclmul_avx512);
 
 void gf128hash_mul_pclmul(struct polyval_elem *acc,
 			  const struct gf128hash_key_x86 *key);
@@ -32,12 +38,16 @@ void ghash_preparekey_pclmul_avx(struct gf128hash_key_x86 *key,
 				 const u8 raw_key[GHASH_BLOCK_SIZE]);
 void ghash_preparekey_vpclmul_avx2(struct gf128hash_key_x86 *key,
 				   const u8 raw_key[GHASH_BLOCK_SIZE]);
+void ghash_preparekey_vpclmul_avx512(struct gf128hash_key_x86 *key,
+				     const u8 raw_key[GHASH_BLOCK_SIZE]);
 void polyval_preparekey_pclmul(struct gf128hash_key_x86 *key,
 			       const u8 raw_key[POLYVAL_BLOCK_SIZE]);
 void polyval_preparekey_pclmul_avx(struct gf128hash_key_x86 *key,
 				   const u8 raw_key[POLYVAL_BLOCK_SIZE]);
 void polyval_preparekey_vpclmul_avx2(struct gf128hash_key_x86 *key,
 				     const u8 raw_key[POLYVAL_BLOCK_SIZE]);
+void polyval_preparekey_vpclmul_avx512(struct gf128hash_key_x86 *key,
+				       const u8 raw_key[POLYVAL_BLOCK_SIZE]);
 
 void ghash_blocks_pclmul(struct polyval_elem *acc,
 			 const struct gf128hash_key_x86 *key, const u8 *data,
@@ -48,6 +58,9 @@ void ghash_blocks_pclmul_avx(struct polyval_elem *acc,
 void ghash_blocks_vpclmul_avx2(struct polyval_elem *acc,
 			       const struct gf128hash_key_x86 *key,
 			       const u8 *data, size_t nblocks);
+void ghash_blocks_vpclmul_avx512(struct polyval_elem *acc,
+				 const struct gf128hash_key_x86 *key,
+				 const u8 *data, size_t nblocks);
 void polyval_blocks_pclmul(struct polyval_elem *acc,
 			   const struct gf128hash_key_x86 *key, const u8 *data,
 			   size_t nblocks);
@@ -57,6 +70,9 @@ void polyval_blocks_pclmul_avx(struct polyval_elem *acc,
 void polyval_blocks_vpclmul_avx2(struct polyval_elem *acc,
 				 const struct gf128hash_key_x86 *key,
 				 const u8 *data, size_t nblocks);
+void polyval_blocks_vpclmul_avx512(struct polyval_elem *acc,
+				   const struct gf128hash_key_x86 *key,
+				   const u8 *data, size_t nblocks);
 
 static __always_inline void
 __gf128hash_mul_x86_fpu(struct polyval_elem *acc,
@@ -73,7 +89,9 @@ __ghash_blocks_x86_fpu(struct polyval_elem *acc,
 		       const struct gf128hash_key_x86 *key, const u8 *data,
 		       size_t nblocks)
 {
-	if (static_branch_likely(&have_vpclmul_avx2))
+	if (static_branch_likely(&have_vpclmul_avx512))
+		ghash_blocks_vpclmul_avx512(acc, key, data, nblocks);
+	else if (static_branch_likely(&have_vpclmul_avx2))
 		ghash_blocks_vpclmul_avx2(acc, key, data, nblocks);
 	else if (static_branch_likely(&have_pclmul_avx))
 		ghash_blocks_pclmul_avx(acc, key, data, nblocks);
@@ -101,6 +119,14 @@ gf128hash_preparekey_x86(struct gf128hash_key_x86 *key, const u8 raw_key[16],
 {
 	if (static_branch_likely(&have_pclmul) && likely(irq_fpu_usable())) {
 		kernel_fpu_begin_mask(0);
+		if (static_branch_likely(&have_vpclmul_avx512)) {
+			if (is_ghash)
+				ghash_preparekey_vpclmul_avx512(key, raw_key);
+			else
+				polyval_preparekey_vpclmul_avx512(key, raw_key);
+			kernel_fpu_end();
+			return;
+		}
 		if (static_branch_likely(&have_vpclmul_avx2)) {
 			if (is_ghash)
 				ghash_preparekey_vpclmul_avx2(key, raw_key);
@@ -118,6 +144,8 @@ gf128hash_preparekey_x86(struct gf128hash_key_x86 *key, const u8 raw_key[16],
 				polyval_preparekey_pclmul(key, raw_key);
 		}
 		kernel_fpu_end();
+		memset(key->unused, 0, sizeof(key->unused));
+		memset(key->padding, 0, sizeof(key->padding));
 		return;
 	}
 	if (is_ghash)
@@ -125,11 +153,10 @@ gf128hash_preparekey_x86(struct gf128hash_key_x86 *key, const u8 raw_key[16],
 	else
 		memcpy(&key->h_powers[NUM_H_POWERS - 1], raw_key,
 		       POLYVAL_BLOCK_SIZE);
-	for (int i = NUM_H_POWERS - 2; i >= 0; i--) {
-		key->h_powers[i] = key->h_powers[i + 1];
-		polyval_mul_generic(&key->h_powers[i],
-				    &key->h_powers[NUM_H_POWERS - 1]);
-	}
+	static_assert(offsetof(struct gf128hash_key_x86,
+			       h_powers[NUM_H_POWERS - 1]) ==
+		      offsetof(struct gf128hash_key_x86,
+			       h_powers16[NUM_H_POWERS_AVX512 - 1]));
 	/*
 	 * Decide which key layout to use.  This fallback code is reached when
 	 * the static keys aren't set, which might be because
@@ -137,17 +164,34 @@ gf128hash_preparekey_x86(struct gf128hash_key_x86 *key, const u8 raw_key[16],
 	 * here so that keys prepared before gf128hash_mod_init() have the same
 	 * layout as keys prepared afterwards.
 	 */
-	if (gf128hash_use_vpclmul_avx2()) {
-		static const u8 indices[8] = { 0, 2, 1, 3, 4, 6, 5, 7 };
-
-		for (int i = 0; i < NUM_H_POWERS; i++)
-			key->h_powers_xored[i] = key->h_powers[indices[i]].lo ^
-						 key->h_powers[indices[i]].hi;
+	if (gf128hash_use_vpclmul_avx512()) {
+		for (int i = NUM_H_POWERS_AVX512 - 2; i >= 0; i--) {
+			key->h_powers16[i] = key->h_powers16[i + 1];
+			polyval_mul_generic(
+				&key->h_powers16[i],
+				&key->h_powers16[NUM_H_POWERS_AVX512 - 1]);
+		}
 	} else {
-		for (int i = 0; i < NUM_H_POWERS; i++)
-			key->h_powers_xored[i] = key->h_powers[i].lo ^
-						 key->h_powers[i].hi;
+		for (int i = NUM_H_POWERS - 2; i >= 0; i--) {
+			key->h_powers[i] = key->h_powers[i + 1];
+			polyval_mul_generic(&key->h_powers[i],
+					    &key->h_powers[NUM_H_POWERS - 1]);
+		}
+		if (gf128hash_use_vpclmul_avx2()) {
+			static const u8 indices[8] = { 0, 2, 1, 3, 4, 6, 5, 7 };
+
+			for (int i = 0; i < NUM_H_POWERS; i++)
+				key->h_powers_xored[i] =
+					key->h_powers[indices[i]].lo ^
+					key->h_powers[indices[i]].hi;
+		} else {
+			for (int i = 0; i < NUM_H_POWERS; i++)
+				key->h_powers_xored[i] = key->h_powers[i].lo ^
+							 key->h_powers[i].hi;
+		}
+		memset(key->unused, 0, sizeof(key->unused));
 	}
+	memset(key->padding, 0, sizeof(key->padding));
 	polyval_mul_xm64_generic(&key->h_times_xm64,
 				 &key->h_powers[NUM_H_POWERS - 1]);
 }
@@ -207,6 +251,9 @@ gf128hash_blocks_x86(struct polyval_elem *acc,
 			kernel_fpu_begin_mask(0);
 			if (is_ghash)
 				__ghash_blocks_x86_fpu(acc, key, data, n);
+			else if (static_branch_likely(&have_vpclmul_avx512))
+				polyval_blocks_vpclmul_avx512(acc, key, data,
+							      n);
 			else if (static_branch_likely(&have_vpclmul_avx2))
 				polyval_blocks_vpclmul_avx2(acc, key, data, n);
 			else if (static_branch_likely(&have_pclmul_avx))
@@ -253,8 +300,11 @@ static void gf128hash_mod_init_arch(void)
 
 	if (gf128hash_use_pclmul_avx()) {
 		static_branch_enable(&have_pclmul_avx);
-		if (gf128hash_use_vpclmul_avx2())
+		if (gf128hash_use_vpclmul_avx2()) {
 			static_branch_enable(&have_vpclmul_avx2);
+			if (gf128hash_use_vpclmul_avx512())
+				static_branch_enable(&have_vpclmul_avx512);
+		}
 	}
 	static_branch_enable(&have_pclmul);
 }
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH 08/11] lib/crypto: x86/aes-gcm: Migrate AES-NI optimized code into library
  2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
                   ` (6 preceding siblings ...)
  2026-11-29 20:02 ` [PATCH 07/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with VPCLMULQDQ and AVX512 Eric Biggers
@ 2026-11-29 20:02 ` Eric Biggers
  2026-11-29 20:02 ` [PATCH 09/11] lib/crypto: x86/aes-gcm: Migrate VAES+AVX2 " Eric Biggers
                   ` (2 subsequent siblings)
  10 siblings, 0 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, Eric Biggers

Migrate aes-gcm-aesni-x86_64.S into lib/crypto/, and wire it up to the
AES-GCM library functions.  Remove the superseded crypto_aead
implementations from aesni-intel_glue.c.

This makes the AES-GCM library be optimized with AES-NI and AES-NI+AVX,
while the same AES-GCM optimizations still remain accessible via
crypto_aead via gcm-aes-lib and rfc4106-gcm-aes-lib.  It's also simpler,
since it eliminates the crypto_aead boilerplate.

Note: the new code is not yet enabled on CPUs that support VAES, since
the ghash_key format is different in that case.  The following commits
will migrate the VAES+AVX2 and VAES+AVX512 optimized AES-GCM code.

Some changes to the assembly code were required to match what the
library expects:

- Take 'struct aes_gcm_key' instead of 'struct aes_gcm_key_aesni'.

- Don't use 16-byte SSE memory operands from the key, since
  'struct aes_gcm_key' isn't necessarily 16-byte aligned.

- Remove aes_gcm_precompute_aesni*() and aes_gcm_aad_update_aesni*().
  The equivalent functionality is now handled in libgf128hash.

- aes_gcm_{enc,dec}_update_*():

    - Take the counter as big-endian instead of little-endian.

    - Widen datalen from int to size_t.

    - Reorder the arguments to match what the library hooks expect.

- Load and store the exact tag length in aes_gcm_{enc,dec}_final_*().

Note: the assembly code is in need of some further cleanups (such as not
mixing VEX-coded and legacy SSE instructions, updating some names and
comments, and further optimizations).  Those are left for a later
commit, as this one is already quite large.

Benchmark results on AMD Ryzen 9 9950X (Zen 5) with VAES disabled (QEMU
'-cpu host,-vaes') using aes_gcm_kunit (before = uncombined library
AES-CTR + GHASH fallback):

    Length    Enc before   Enc after    Dec before   Dec after
    ------    ----------   ---------    ----------   ---------
        16      291 MB/s    550 MB/s      281 MB/s    710 MB/s
        64     1089 MB/s   1791 MB/s     1092 MB/s   2201 MB/s
       128     2058 MB/s   3336 MB/s     2059 MB/s   3720 MB/s
       256     3302 MB/s   4884 MB/s     3176 MB/s   5365 MB/s
       512     4376 MB/s   6397 MB/s     4291 MB/s   6801 MB/s
      1024     5171 MB/s   7526 MB/s     5251 MB/s   7761 MB/s
      1420     5157 MB/s   7538 MB/s     5092 MB/s   8028 MB/s
      4096     5989 MB/s   8532 MB/s     6126 MB/s   8985 MB/s
     16384     6382 MB/s   8532 MB/s     6288 MB/s   8998 MB/s

Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 arch/x86/crypto/Makefile                      |   1 -
 arch/x86/crypto/aesni-intel_glue.c            | 184 +-------
 lib/crypto/Makefile                           |   3 +
 .../crypto/x86}/aes-gcm-aesni-x86_64.S        | 414 +++++++-----------
 lib/crypto/x86/aes.h                          | 286 ++++++++++--
 lib/crypto/x86/gf128hash-cpu.h                |   6 +
 lib/crypto/x86/gf128hash.h                    |  23 +
 7 files changed, 452 insertions(+), 465 deletions(-)
 rename {arch/x86/crypto => lib/crypto/x86}/aes-gcm-aesni-x86_64.S (75%)

diff --git a/arch/x86/crypto/Makefile b/arch/x86/crypto/Makefile
index 09bdea45bc3e7..2749f765c7724 100644
--- a/arch/x86/crypto/Makefile
+++ b/arch/x86/crypto/Makefile
@@ -41,7 +41,6 @@ aegis128-aesni-y := aegis128-aesni-asm.o aegis128-aesni-glue.o
 
 obj-$(CONFIG_CRYPTO_AES_NI_INTEL) += aesni-intel.o
 aesni-intel-y := aesni-intel_glue.o \
-		 aes-gcm-aesni-x86_64.o \
 		 aes-gcm-vaes-avx2.o \
 		 aes-gcm-vaes-avx512.o
 
diff --git a/arch/x86/crypto/aesni-intel_glue.c b/arch/x86/crypto/aesni-intel_glue.c
index 3b58d77d2f5d3..51aa7b1566b3d 100644
--- a/arch/x86/crypto/aesni-intel_glue.c
+++ b/arch/x86/crypto/aesni-intel_glue.c
@@ -46,39 +46,6 @@ struct aes_gcm_key {
 	u32 rfc4106_nonce;
 };
 
-/* Key struct used by the AES-NI implementations of AES-GCM */
-struct aes_gcm_key_aesni {
-	/*
-	 * Common part of the key.  16-byte alignment is required by the
-	 * assembly code.
-	 */
-	struct aes_gcm_key base __aligned(16);
-
-	/*
-	 * Powers of the hash key H^8 through H^1.  These are 128-bit values.
-	 * They all have an extra factor of x^-1 and are byte-reversed.  16-byte
-	 * alignment is required by the assembly code.
-	 */
-	u64 h_powers[8][2] __aligned(16);
-
-	/*
-	 * h_powers_xored[i] contains the two 64-bit halves of h_powers[i] XOR'd
-	 * together.  It's used for Karatsuba multiplication.  16-byte alignment
-	 * is required by the assembly code.
-	 */
-	u64 h_powers_xored[8] __aligned(16);
-
-	/*
-	 * H^1 times x^64 (and also the usual extra factor of x^-1).  16-byte
-	 * alignment is required by the assembly code.
-	 */
-	u64 h_times_x64[2] __aligned(16);
-};
-#define AES_GCM_KEY_AESNI(key)	\
-	container_of((key), struct aes_gcm_key_aesni, base)
-#define AES_GCM_KEY_AESNI_SIZE	\
-	(sizeof(struct aes_gcm_key_aesni) + (15 & ~(CRYPTO_MINALIGN - 1)))
-
 /* Key struct used by the VAES + AVX2 implementation of AES-GCM */
 struct aes_gcm_key_vaes_avx2 {
 	/*
@@ -142,7 +109,6 @@ struct aes_gcm_key_vaes_avx512 {
  */
 #define FLAG_RFC4106	BIT(0)
 #define FLAG_ENC	BIT(1)
-#define FLAG_AVX	BIT(2)
 #define FLAG_VAES_AVX2	BIT(3)
 #define FLAG_VAES_AVX512 BIT(4)
 
@@ -151,16 +117,10 @@ aes_gcm_key_get(struct crypto_aead *tfm, int flags)
 {
 	if (flags & FLAG_VAES_AVX512)
 		return PTR_ALIGN(crypto_aead_ctx(tfm), 64);
-	else if (flags & FLAG_VAES_AVX2)
-		return PTR_ALIGN(crypto_aead_ctx(tfm), 32);
 	else
-		return PTR_ALIGN(crypto_aead_ctx(tfm), 16);
+		return PTR_ALIGN(crypto_aead_ctx(tfm), 32);
 }
 
-asmlinkage void
-aes_gcm_precompute_aesni(struct aes_gcm_key_aesni *key);
-asmlinkage void
-aes_gcm_precompute_aesni_avx(struct aes_gcm_key_aesni *key);
 asmlinkage void
 aes_gcm_precompute_vaes_avx2(struct aes_gcm_key_vaes_avx2 *key);
 asmlinkage void
@@ -170,20 +130,10 @@ static void aes_gcm_precompute(struct aes_gcm_key *key, int flags)
 {
 	if (flags & FLAG_VAES_AVX512)
 		aes_gcm_precompute_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key));
-	else if (flags & FLAG_VAES_AVX2)
-		aes_gcm_precompute_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key));
-	else if (flags & FLAG_AVX)
-		aes_gcm_precompute_aesni_avx(AES_GCM_KEY_AESNI(key));
 	else
-		aes_gcm_precompute_aesni(AES_GCM_KEY_AESNI(key));
+		aes_gcm_precompute_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key));
 }
 
-asmlinkage void
-aes_gcm_aad_update_aesni(const struct aes_gcm_key_aesni *key,
-			 u8 ghash_acc[16], const u8 *aad, int aadlen);
-asmlinkage void
-aes_gcm_aad_update_aesni_avx(const struct aes_gcm_key_aesni *key,
-			     u8 ghash_acc[16], const u8 *aad, int aadlen);
 asmlinkage void
 aes_gcm_aad_update_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
 			     u8 ghash_acc[16], const u8 *aad, int aadlen);
@@ -197,25 +147,11 @@ static void aes_gcm_aad_update(const struct aes_gcm_key *key, u8 ghash_acc[16],
 	if (flags & FLAG_VAES_AVX512)
 		aes_gcm_aad_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
 					       ghash_acc, aad, aadlen);
-	else if (flags & FLAG_VAES_AVX2)
+	else
 		aes_gcm_aad_update_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key),
 					     ghash_acc, aad, aadlen);
-	else if (flags & FLAG_AVX)
-		aes_gcm_aad_update_aesni_avx(AES_GCM_KEY_AESNI(key), ghash_acc,
-					     aad, aadlen);
-	else
-		aes_gcm_aad_update_aesni(AES_GCM_KEY_AESNI(key), ghash_acc,
-					 aad, aadlen);
 }
 
-asmlinkage void
-aes_gcm_enc_update_aesni(const struct aes_gcm_key_aesni *key,
-			 const u32 le_ctr[4], u8 ghash_acc[16],
-			 const u8 *src, u8 *dst, int datalen);
-asmlinkage void
-aes_gcm_enc_update_aesni_avx(const struct aes_gcm_key_aesni *key,
-			     const u32 le_ctr[4], u8 ghash_acc[16],
-			     const u8 *src, u8 *dst, int datalen);
 asmlinkage void
 aes_gcm_enc_update_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
 			     const u32 le_ctr[4], u8 ghash_acc[16],
@@ -226,14 +162,6 @@ aes_gcm_enc_update_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
 			       const u8 *src, u8 *dst, int datalen);
 
 asmlinkage void
-aes_gcm_dec_update_aesni(const struct aes_gcm_key_aesni *key,
-			 const u32 le_ctr[4], u8 ghash_acc[16],
-			 const u8 *src, u8 *dst, int datalen);
-asmlinkage void
-aes_gcm_dec_update_aesni_avx(const struct aes_gcm_key_aesni *key,
-			     const u32 le_ctr[4], u8 ghash_acc[16],
-			     const u8 *src, u8 *dst, int datalen);
-asmlinkage void
 aes_gcm_dec_update_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
 			     const u32 le_ctr[4], u8 ghash_acc[16],
 			     const u8 *src, u8 *dst, int datalen);
@@ -253,45 +181,22 @@ aes_gcm_update(const struct aes_gcm_key *key,
 			aes_gcm_enc_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
 						       le_ctr, ghash_acc,
 						       src, dst, datalen);
-		else if (flags & FLAG_VAES_AVX2)
+		else
 			aes_gcm_enc_update_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key),
 						     le_ctr, ghash_acc,
 						     src, dst, datalen);
-		else if (flags & FLAG_AVX)
-			aes_gcm_enc_update_aesni_avx(AES_GCM_KEY_AESNI(key),
-						     le_ctr, ghash_acc,
-						     src, dst, datalen);
-		else
-			aes_gcm_enc_update_aesni(AES_GCM_KEY_AESNI(key), le_ctr,
-						 ghash_acc, src, dst, datalen);
 	} else {
 		if (flags & FLAG_VAES_AVX512)
 			aes_gcm_dec_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
 						       le_ctr, ghash_acc,
 						       src, dst, datalen);
-		else if (flags & FLAG_VAES_AVX2)
+		else
 			aes_gcm_dec_update_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key),
 						     le_ctr, ghash_acc,
 						     src, dst, datalen);
-		else if (flags & FLAG_AVX)
-			aes_gcm_dec_update_aesni_avx(AES_GCM_KEY_AESNI(key),
-						     le_ctr, ghash_acc,
-						     src, dst, datalen);
-		else
-			aes_gcm_dec_update_aesni(AES_GCM_KEY_AESNI(key),
-						 le_ctr, ghash_acc,
-						 src, dst, datalen);
 	}
 }
 
-asmlinkage void
-aes_gcm_enc_final_aesni(const struct aes_gcm_key_aesni *key,
-			const u32 le_ctr[4], u8 ghash_acc[16],
-			u64 total_aadlen, u64 total_datalen);
-asmlinkage void
-aes_gcm_enc_final_aesni_avx(const struct aes_gcm_key_aesni *key,
-			    const u32 le_ctr[4], u8 ghash_acc[16],
-			    u64 total_aadlen, u64 total_datalen);
 asmlinkage void
 aes_gcm_enc_final_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
 			    const u32 le_ctr[4], u8 ghash_acc[16],
@@ -311,30 +216,12 @@ aes_gcm_enc_final(const struct aes_gcm_key *key,
 		aes_gcm_enc_final_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
 					      le_ctr, ghash_acc,
 					      total_aadlen, total_datalen);
-	else if (flags & FLAG_VAES_AVX2)
+	else
 		aes_gcm_enc_final_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key),
 					    le_ctr, ghash_acc,
 					    total_aadlen, total_datalen);
-	else if (flags & FLAG_AVX)
-		aes_gcm_enc_final_aesni_avx(AES_GCM_KEY_AESNI(key),
-					    le_ctr, ghash_acc,
-					    total_aadlen, total_datalen);
-	else
-		aes_gcm_enc_final_aesni(AES_GCM_KEY_AESNI(key),
-					le_ctr, ghash_acc,
-					total_aadlen, total_datalen);
 }
 
-asmlinkage bool __must_check
-aes_gcm_dec_final_aesni(const struct aes_gcm_key_aesni *key,
-			const u32 le_ctr[4], const u8 ghash_acc[16],
-			u64 total_aadlen, u64 total_datalen,
-			const u8 tag[16], int taglen);
-asmlinkage bool __must_check
-aes_gcm_dec_final_aesni_avx(const struct aes_gcm_key_aesni *key,
-			    const u32 le_ctr[4], const u8 ghash_acc[16],
-			    u64 total_aadlen, u64 total_datalen,
-			    const u8 tag[16], int taglen);
 asmlinkage bool __must_check
 aes_gcm_dec_final_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
 			    const u32 le_ctr[4], const u8 ghash_acc[16],
@@ -357,21 +244,11 @@ aes_gcm_dec_final(const struct aes_gcm_key *key, const u32 le_ctr[4],
 						     le_ctr, ghash_acc,
 						     total_aadlen, total_datalen,
 						     tag, taglen);
-	else if (flags & FLAG_VAES_AVX2)
+	else
 		return aes_gcm_dec_final_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key),
 						   le_ctr, ghash_acc,
 						   total_aadlen, total_datalen,
 						   tag, taglen);
-	else if (flags & FLAG_AVX)
-		return aes_gcm_dec_final_aesni_avx(AES_GCM_KEY_AESNI(key),
-						   le_ctr, ghash_acc,
-						   total_aadlen, total_datalen,
-						   tag, taglen);
-	else
-		return aes_gcm_dec_final_aesni(AES_GCM_KEY_AESNI(key),
-					       le_ctr, ghash_acc,
-					       total_aadlen, total_datalen,
-					       tag, taglen);
 }
 
 /*
@@ -439,11 +316,6 @@ static int gcm_setkey(struct crypto_aead *tfm, const u8 *raw_key,
 	}
 
 	/* The assembly code assumes the following offsets. */
-	static_assert(offsetof(struct aes_gcm_key_aesni, base.aes_key.len) == 0);
-	static_assert(offsetof(struct aes_gcm_key_aesni, base.aes_key.k.rndkeys) == 16);
-	static_assert(offsetof(struct aes_gcm_key_aesni, h_powers) == 272);
-	static_assert(offsetof(struct aes_gcm_key_aesni, h_powers_xored) == 400);
-	static_assert(offsetof(struct aes_gcm_key_aesni, h_times_x64) == 464);
 	static_assert(offsetof(struct aes_gcm_key_vaes_avx2, base.aes_key.len) == 0);
 	static_assert(offsetof(struct aes_gcm_key_vaes_avx2, base.aes_key.k.rndkeys) == 16);
 	static_assert(offsetof(struct aes_gcm_key_vaes_avx2, h_powers) == 288);
@@ -465,9 +337,6 @@ static int gcm_setkey(struct crypto_aead *tfm, const u8 *raw_key,
 		static const u8 x_to_the_minus1[16] __aligned(__alignof__(be128)) = {
 			[0] = 0xc2, [15] = 1
 		};
-		static const u8 x_to_the_63[16] __aligned(__alignof__(be128)) = {
-			[7] = 1,
-		};
 		be128 h1 = {};
 		be128 h;
 		int i;
@@ -490,7 +359,7 @@ static int gcm_setkey(struct crypto_aead *tfm, const u8 *raw_key,
 				gf128mul_lle(&h, &h1);
 			}
 			memset(k->padding, 0, sizeof(k->padding));
-		} else if (flags & FLAG_VAES_AVX2) {
+		} else {
 			struct aes_gcm_key_vaes_avx2 *k =
 				AES_GCM_KEY_VAES_AVX2(key);
 			static const u8 indices[8] = { 0, 2, 1, 3, 4, 6, 5, 7 };
@@ -506,19 +375,6 @@ static int gcm_setkey(struct crypto_aead *tfm, const u8 *raw_key,
 				k->h_powers_xored[i] = k->h_powers[j][0] ^
 						       k->h_powers[j][1];
 			}
-		} else {
-			struct aes_gcm_key_aesni *k = AES_GCM_KEY_AESNI(key);
-
-			for (i = ARRAY_SIZE(k->h_powers) - 1; i >= 0; i--) {
-				k->h_powers[i][0] = be64_to_cpu(h.b);
-				k->h_powers[i][1] = be64_to_cpu(h.a);
-				k->h_powers_xored[i] = k->h_powers[i][0] ^
-						       k->h_powers[i][1];
-				gf128mul_lle(&h, &h1);
-			}
-			gf128mul_lle(&h1, (const be128 *)x_to_the_63);
-			k->h_times_x64[0] = be64_to_cpu(h1.b);
-			k->h_times_x64[1] = be64_to_cpu(h1.a);
 		}
 	}
 	return 0;
@@ -764,16 +620,6 @@ static struct aead_alg aes_gcm_algs_##suffix[] = { {			       \
 	},								       \
 } }
 
-/* aes_gcm_algs_aesni */
-DEFINE_GCM_ALGS(aesni, /* no flags */ 0,
-		"generic-gcm-aesni", "rfc4106-gcm-aesni",
-		AES_GCM_KEY_AESNI_SIZE, 400);
-
-/* aes_gcm_algs_aesni_avx */
-DEFINE_GCM_ALGS(aesni_avx, FLAG_AVX,
-		"generic-gcm-aesni-avx", "rfc4106-gcm-aesni-avx",
-		AES_GCM_KEY_AESNI_SIZE, 500);
-
 /* aes_gcm_algs_vaes_avx2 */
 DEFINE_GCM_ALGS(vaes_avx2, FLAG_VAES_AVX2,
 		"generic-gcm-vaes-avx2", "rfc4106-gcm-vaes-avx2",
@@ -790,10 +636,6 @@ static int __init register_avx_algs(void)
 
 	if (!boot_cpu_has(X86_FEATURE_AVX))
 		return 0;
-	err = crypto_register_aeads(aes_gcm_algs_aesni_avx,
-				    ARRAY_SIZE(aes_gcm_algs_aesni_avx));
-	if (err)
-		return err;
 	/*
 	 * Note: not all the algorithms registered below actually require
 	 * VPCLMULQDQ.  But in practice every CPU with VAES also has VPCLMULQDQ.
@@ -836,7 +678,6 @@ static int __init register_avx_algs(void)
 
 static void unregister_avx_algs(void)
 {
-	unregister_aeads(aes_gcm_algs_aesni_avx);
 	unregister_aeads(aes_gcm_algs_vaes_avx2);
 	unregister_aeads(aes_gcm_algs_vaes_avx512);
 }
@@ -854,11 +695,6 @@ static int __init aesni_init(void)
 	if (!x86_match_cpu(aesni_cpu_id))
 		return -ENODEV;
 
-	err = crypto_register_aeads(aes_gcm_algs_aesni,
-				    ARRAY_SIZE(aes_gcm_algs_aesni));
-	if (err)
-		return err;
-
 	err = register_avx_algs();
 	if (err)
 		goto unregister_avx;
@@ -867,15 +703,11 @@ static int __init aesni_init(void)
 
 unregister_avx:
 	unregister_avx_algs();
-	crypto_unregister_aeads(aes_gcm_algs_aesni,
-				ARRAY_SIZE(aes_gcm_algs_aesni));
 	return err;
 }
 
 static void __exit aesni_exit(void)
 {
-	crypto_unregister_aeads(aes_gcm_algs_aesni,
-				ARRAY_SIZE(aes_gcm_algs_aesni));
 	unregister_avx_algs();
 }
 
diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile
index c057c0d896a4f..b813c895cc9da 100644
--- a/lib/crypto/Makefile
+++ b/lib/crypto/Makefile
@@ -95,6 +95,9 @@ libaes-$(CONFIG_X86) += x86/aes-aesni.o
 ifneq ($(CONFIG_CRYPTO_LIB_AES_CTR),)
 libaes-$(CONFIG_X86_64) += x86/aes-ctr-avx-x86_64.o
 endif
+ifneq ($(CONFIG_CRYPTO_LIB_AES_GCM),)
+libaes-$(CONFIG_X86_64) += x86/aes-gcm-aesni-x86_64.o
+endif
 ifneq ($(CONFIG_CRYPTO_LIB_AES_XTS),)
 libaes-$(CONFIG_X86_64) += x86/aes-xts-avx-x86_64.o
 endif
diff --git a/arch/x86/crypto/aes-gcm-aesni-x86_64.S b/lib/crypto/x86/aes-gcm-aesni-x86_64.S
similarity index 75%
rename from arch/x86/crypto/aes-gcm-aesni-x86_64.S
rename to lib/crypto/x86/aes-gcm-aesni-x86_64.S
index 6b2abb76827e1..a385ca3372e59 100644
--- a/arch/x86/crypto/aes-gcm-aesni-x86_64.S
+++ b/lib/crypto/x86/aes-gcm-aesni-x86_64.S
@@ -134,20 +134,21 @@
 	.quad	0xc200000000000000
 .Lone:
 	.quad	1
-.Lgfpoly_and_internal_carrybit:
-	.octa	0xc2000000000000010000000000000001
 	// Loading 16 bytes from '.Lzeropad_mask + 16 - len' produces a mask of
 	// 'len' 0xff bytes and the rest zeroes.
 .Lzeropad_mask:
 	.octa	0xffffffffffffffffffffffffffffffff
 	.octa	0
+.Lbe_one:
+	.long	0x01000000
 
-// Offsets in struct aes_gcm_key_aesni
+// Offsets in struct aes_gcm_key
 #define OFFSETOF_AESKEYLEN	0
 #define OFFSETOF_AESROUNDKEYS	16
-#define OFFSETOF_H_POWERS	272
-#define OFFSETOF_H_POWERS_XORED	400
-#define OFFSETOF_H_TIMES_X64	464
+#define OFFSETOF_H_POWERS_XORED	(256 + 0)
+#define OFFSETOF_H_POWERS	(256 + 128)
+#define OFFSETOF_H_TIMES_X64	(256 + 304)
+#define OFFSETOF_AUTHTAG_LEN	(256 + 320)
 
 .text
 
@@ -206,6 +207,26 @@
 .endif
 .endm
 
+// Do one AES round on \dst using the unaligned round key at \round_key_mem.
+.macro	_aesenc_1x	round_key_mem, dst, tmp
+.if USE_AVX
+	vaesenc		\round_key_mem, \dst, \dst
+.else
+	movdqu		\round_key_mem, \tmp
+	aesenc		\tmp, \dst
+.endif
+.endm
+
+// Do the final AES round on \dst using the unaligned round key at \round_key_mem.
+.macro	_aesenclast_1x	round_key_mem, dst, tmp
+.if USE_AVX
+	vaesenclast	\round_key_mem, \dst, \dst
+.else
+	movdqu		\round_key_mem, \tmp
+	aesenclast	\tmp, \dst
+.endif
+.endm
+
 // Load 1 <= %ecx <= 15 bytes from the pointer \src into the xmm register \dst
 // and zeroize any remaining bytes.  Clobbers %rax, %rcx, and \tmp{64,32}.
 .macro	_load_partial_block	src, dst, tmp64, tmp32
@@ -318,14 +339,6 @@
 .endif
 .endm
 
-// GHASH-multiply \a by \b and store the reduced product in \b.
-// See _ghash_mul_step for details.
-.macro	_ghash_mul	a, a_times_x64, b, gfpoly, t0, t1
-.irp i, 0,1,2,3,4,5,6,7,8,9
-	_ghash_mul_step	\i, \a, \a_times_x64, \b, \gfpoly, \t0, \t1
-.endr
-.endm
-
 // GHASH-multiply \a by \b and add the unreduced product to \lo, \mi, and \hi.
 // This does Karatsuba multiplication and must be paired with _ghash_reduce.  On
 // the first call, \lo, \mi, and \hi must be zero.  \a_xored must contain the
@@ -399,7 +412,7 @@
 	xor		%eax, %eax
 
 	// Load the highest hash key power, H^8.
-	movdqa		OFFSETOF_H_POWERS(KEY), TMP0
+	movdqu		OFFSETOF_H_POWERS(KEY), TMP0
 
 	// Load the first ciphertext block and byte-reflect it.
 .if \enc
@@ -424,7 +437,8 @@
 	pclmulqdq	$0x11, TMP0, GHASH_ACC
 
 	// MI = (a_L + a_H) * (b_L + b_H)
-	pclmulqdq	$0x00, OFFSETOF_H_POWERS_XORED(KEY), MI
+	movq		OFFSETOF_H_POWERS_XORED(KEY), TMP1
+	pclmulqdq	$0x00, TMP1, MI
 .endm
 
 // Continue the GHASH update of 8 ciphertext blocks as described above by doing
@@ -434,7 +448,7 @@
 	add		$8, %eax
 
 	// Load the next lowest key power.
-	movdqa		OFFSETOF_H_POWERS(KEY,%rax,2), TMP0
+	movdqu		OFFSETOF_H_POWERS(KEY,%rax,2), TMP0
 
 	// Load the next ciphertext block and byte-reflect it.
 .if \enc
@@ -487,145 +501,12 @@
 .endif
 .endm
 
-// void aes_gcm_precompute_##suffix(struct aes_gcm_key_aesni *key);
-//
-// Given the expanded AES key, derive the GHASH subkey and initialize the GHASH
-// related fields in the key struct.
-.macro	_aes_gcm_precompute
-
-	// Function arguments
-	.set	KEY,		%rdi
-
-	// Additional local variables.
-	// %xmm0-%xmm1 and %rax are used as temporaries.
-	.set	RNDKEYLAST_PTR,	%rsi
-	.set	H_CUR,		%xmm2
-	.set	H_POW1,		%xmm3	// H^1
-	.set	H_POW1_X64,	%xmm4	// H^1 * x^64
-	.set	GFPOLY,		%xmm5
-
-	// Encrypt an all-zeroes block to get the raw hash subkey.
-	movl		OFFSETOF_AESKEYLEN(KEY), %eax
-	lea		OFFSETOF_AESROUNDKEYS+6*16(KEY,%rax,4), RNDKEYLAST_PTR
-	movdqa		OFFSETOF_AESROUNDKEYS(KEY), H_POW1
-	lea		OFFSETOF_AESROUNDKEYS+16(KEY), %rax
-1:
-	aesenc		(%rax), H_POW1
-	add		$16, %rax
-	cmp		%rax, RNDKEYLAST_PTR
-	jne		1b
-	aesenclast	(RNDKEYLAST_PTR), H_POW1
-
-	// Preprocess the raw hash subkey as needed to operate on GHASH's
-	// bit-reflected values directly: reflect its bytes, then multiply it by
-	// x^-1 (using the backwards interpretation of polynomial coefficients
-	// from the GCM spec) or equivalently x^1 (using the alternative,
-	// natural interpretation of polynomial coefficients).
-	pshufb		.Lbswap_mask(%rip), H_POW1
-	movdqa		H_POW1, %xmm0
-	pshufd		$0xd3, %xmm0, %xmm0
-	psrad		$31, %xmm0
-	paddq		H_POW1, H_POW1
-	pand		.Lgfpoly_and_internal_carrybit(%rip), %xmm0
-	pxor		%xmm0, H_POW1
-
-	// Store H^1.
-	movdqa		H_POW1, OFFSETOF_H_POWERS+7*16(KEY)
-
-	// Compute and store H^1 * x^64.
-	movq		.Lgfpoly(%rip), GFPOLY
-	pshufd		$0x4e, H_POW1, %xmm0
-	_vpclmulqdq	$0x00, H_POW1, GFPOLY, H_POW1_X64
-	pxor		%xmm0, H_POW1_X64
-	movdqa		H_POW1_X64, OFFSETOF_H_TIMES_X64(KEY)
-
-	// Compute and store the halves of H^1 XOR'd together.
-	pxor		H_POW1, %xmm0
-	movq		%xmm0, OFFSETOF_H_POWERS_XORED+7*8(KEY)
-
-	// Compute and store the remaining key powers H^2 through H^8.
-	movdqa		H_POW1, H_CUR
-	mov		$6*8, %eax
-.Lprecompute_next\@:
-	// Compute H^i = H^{i-1} * H^1.
-	_ghash_mul	H_POW1, H_POW1_X64, H_CUR, GFPOLY, %xmm0, %xmm1
-	// Store H^i.
-	movdqa		H_CUR, OFFSETOF_H_POWERS(KEY,%rax,2)
-	// Compute and store the halves of H^i XOR'd together.
-	pshufd		$0x4e, H_CUR, %xmm0
-	pxor		H_CUR, %xmm0
-	movq		%xmm0, OFFSETOF_H_POWERS_XORED(KEY,%rax)
-	sub		$8, %eax
-	jge		.Lprecompute_next\@
-
-	RET
-.endm
-
-// void aes_gcm_aad_update_aesni(const struct aes_gcm_key_aesni *key,
-//				 u8 ghash_acc[16], const u8 *aad, int aadlen);
-//
-// This function processes the AAD (Additional Authenticated Data) in GCM.
-// Using the key |key|, it updates the GHASH accumulator |ghash_acc| with the
-// data given by |aad| and |aadlen|.  On the first call, |ghash_acc| must be all
-// zeroes.  |aadlen| must be a multiple of 16, except on the last call where it
-// can be any length.  The caller must do any buffering needed to ensure this.
-.macro	_aes_gcm_aad_update
-
-	// Function arguments
-	.set	KEY,		%rdi
-	.set	GHASH_ACC_PTR,	%rsi
-	.set	AAD,		%rdx
-	.set	AADLEN,		%ecx
-	// Note: _load_partial_block relies on AADLEN being in %ecx.
-
-	// Additional local variables.
-	// %rax, %r10, and %xmm0-%xmm1 are used as temporary registers.
-	.set	BSWAP_MASK,	%xmm2
-	.set	GHASH_ACC,	%xmm3
-	.set	H_POW1,		%xmm4	// H^1
-	.set	H_POW1_X64,	%xmm5	// H^1 * x^64
-	.set	GFPOLY,		%xmm6
-
-	movdqa		.Lbswap_mask(%rip), BSWAP_MASK
-	movdqu		(GHASH_ACC_PTR), GHASH_ACC
-	movdqa		OFFSETOF_H_POWERS+7*16(KEY), H_POW1
-	movdqa		OFFSETOF_H_TIMES_X64(KEY), H_POW1_X64
-	movq		.Lgfpoly(%rip), GFPOLY
-
-	// Process the AAD one full block at a time.
-	sub		$16, AADLEN
-	jl		.Laad_loop_1x_done\@
-.Laad_loop_1x\@:
-	movdqu		(AAD), %xmm0
-	pshufb		BSWAP_MASK, %xmm0
-	pxor		%xmm0, GHASH_ACC
-	_ghash_mul	H_POW1, H_POW1_X64, GHASH_ACC, GFPOLY, %xmm0, %xmm1
-	add		$16, AAD
-	sub		$16, AADLEN
-	jge		.Laad_loop_1x\@
-.Laad_loop_1x_done\@:
-	// Check whether there is a partial block at the end.
-	add		$16, AADLEN
-	jz		.Laad_done\@
-
-	// Process a partial block of length 1 <= AADLEN <= 15.
-	// _load_partial_block assumes that %ecx contains AADLEN.
-	_load_partial_block	AAD, %xmm0, %r10, %r10d
-	pshufb		BSWAP_MASK, %xmm0
-	pxor		%xmm0, GHASH_ACC
-	_ghash_mul	H_POW1, H_POW1_X64, GHASH_ACC, GFPOLY, %xmm0, %xmm1
-
-.Laad_done\@:
-	movdqu		GHASH_ACC, (GHASH_ACC_PTR)
-	RET
-.endm
-
 // Increment LE_CTR eight times to generate eight little-endian counter blocks,
 // swap each to big-endian, and store them in AESDATA[0-7].  Also XOR them with
 // the zero-th AES round key.  Clobbers TMP0 and TMP1.
 .macro	_ctr_begin_8x
 	movq		.Lone(%rip), TMP0
-	movdqa		OFFSETOF_AESROUNDKEYS(KEY), TMP1 // zero-th round key
+	movdqu		OFFSETOF_AESROUNDKEYS(KEY), TMP1 // zero-th round key
 .irp i, 0,1,2,3,4,5,6,7
 	_vpshufb	BSWAP_MASK, LE_CTR, AESDATA\i
 	pxor		TMP1, AESDATA\i
@@ -658,9 +539,11 @@
 .endr
 .endm
 
-// void aes_gcm_{enc,dec}_update_##suffix(const struct aes_gcm_key_aesni *key,
-//					  const u32 le_ctr[4], u8 ghash_acc[16],
-//					  const u8 *src, u8 *dst, int datalen);
+// void aes_gcm_{enc,dec}_update_##suffix(u8 *dst, const u8 *src,
+//					  size_t datalen,
+//					  struct polyval_elem *ghash_acc,
+//					  const __be32 ctr32[4],
+//					  const struct aes_gcm_key *key);
 //
 // This macro generates a GCM encryption or decryption update function with the
 // above prototype (with \enc selecting which one).
@@ -674,32 +557,27 @@
 // any length.  The caller must do any buffering needed to ensure this.  Both
 // in-place and out-of-place en/decryption are supported.
 //
-// |le_ctr| must give the current counter in little-endian format.  For a new
-// message, the low word of the counter must be 2.  This function loads the
-// counter from |le_ctr| and increments the loaded counter as needed, but it
-// does *not* store the updated counter back to |le_ctr|.  The caller must
-// update |le_ctr| if any more data segments follow.  Internally, only the low
+// |ctr32| must give the current counter in big-endian format.  This function
+// loads the counter from |ctr32| and increments the loaded counter as needed,
+// but it does *not* store the updated counter back to |ctr32|.  The caller must
+// update |ctr32| if any more data segments follow.  Internally, only the low
 // 32-bit word of the counter is incremented, following the GCM standard.
 .macro	_aes_gcm_update	enc
 
 	// Function arguments
-	.set	KEY,		%rdi
-	.set	LE_CTR_PTR,	%rsi	// Note: overlaps with usage as temp reg
-	.set	GHASH_ACC_PTR,	%rdx
-	.set	SRC,		%rcx
-	.set	DST,		%r8
-	.set	DATALEN,	%r9d
-	.set	DATALEN64,	%r9	// Zero-extend DATALEN before using!
-	// Note: the code setting up for _load_partial_block assumes that SRC is
-	// in %rcx (and that DATALEN is *not* in %rcx).
+	.set	DST,		%rdi
+	.set	SRC,		%rsi
+	.set	DATALEN,	%rdx
+	.set	DATALEN32,	%edx
+	.set	GHASH_ACC_PTR,	%rcx
+	.set	BE_CTR_PTR,	%r8
+	.set	KEY,		%r9
+	// Note: the code setting up for _load_partial_block and
+	// _store_partial_block assumes that GHASH_ACC_PTR is in %rcx (and that
+	// DATALEN is *not* in %rcx).
 
 	// Additional local variables
-
-	// %rax and %rsi are used as temporary registers.  Note: %rsi overlaps
-	// with LE_CTR_PTR, which is used only at the beginning.
-
-	.set	AESKEYLEN,	%r10d	// AES key length in bytes
-	.set	AESKEYLEN64,	%r10
+	.set	RNDKEY_PTR,	%r10
 	.set	RNDKEYLAST_PTR,	%r11	// Pointer to last AES round key
 
 	// Put the most frequently used values in %xmm0-%xmm7 to reduce code
@@ -724,10 +602,11 @@
 
 	movdqa		.Lbswap_mask(%rip), BSWAP_MASK
 	movdqu		(GHASH_ACC_PTR), GHASH_ACC
-	movdqu		(LE_CTR_PTR), LE_CTR
+	movdqu		(BE_CTR_PTR), LE_CTR
+	pshufb		BSWAP_MASK, LE_CTR
 
-	movl		OFFSETOF_AESKEYLEN(KEY), AESKEYLEN
-	lea		OFFSETOF_AESROUNDKEYS+6*16(KEY,AESKEYLEN64,4), RNDKEYLAST_PTR
+	movl		OFFSETOF_AESKEYLEN(KEY), %eax
+	lea		OFFSETOF_AESROUNDKEYS+6*16(KEY,%rax,4), RNDKEYLAST_PTR
 
 	// If there are at least 8*16 bytes of data, then continue into the main
 	// loop, which processes 8*16 bytes of data per iteration.
@@ -746,15 +625,15 @@
 .if \enc
 	// Encrypt the first 8 plaintext blocks.
 	_ctr_begin_8x
-	lea		OFFSETOF_AESROUNDKEYS+16(KEY), %rsi
+	lea		OFFSETOF_AESROUNDKEYS+16(KEY), RNDKEY_PTR
 	.p2align 4
 1:
-	movdqa		(%rsi), TMP0
+	movdqu		(RNDKEY_PTR), TMP0
 	_aesenc_8x	TMP0
-	add		$16, %rsi
-	cmp		%rsi, RNDKEYLAST_PTR
+	add		$16, RNDKEY_PTR
+	cmp		RNDKEY_PTR, RNDKEYLAST_PTR
 	jne		1b
-	movdqa		(%rsi), TMP0
+	movdqu		(RNDKEY_PTR), TMP0
 	_aesenclast_8x	TMP0
 	_xor_data_8x
 	// Don't increment DST until the ciphertext blocks have been hashed.
@@ -768,12 +647,12 @@
 
 	// Generate the next set of 8 counter blocks and start encrypting them.
 	_ctr_begin_8x
-	lea		OFFSETOF_AESROUNDKEYS+16(KEY), %rsi
+	lea		OFFSETOF_AESROUNDKEYS+16(KEY), RNDKEY_PTR
 
 	// Do a round of AES, and start the GHASH update of 8 ciphertext blocks
 	// by doing the unreduced multiplication for the first ciphertext block.
-	movdqa		(%rsi), TMP0
-	add		$16, %rsi
+	movdqu		(RNDKEY_PTR), TMP0
+	add		$16, RNDKEY_PTR
 	_aesenc_8x	TMP0
 	_ghash_update_begin_8x \enc
 
@@ -781,8 +660,8 @@
 	// unreduced multiplication for the remaining ciphertext blocks.
 	.p2align 4
 1:
-	movdqa		(%rsi), TMP0
-	add		$16, %rsi
+	movdqu		(RNDKEY_PTR), TMP0
+	add		$16, RNDKEY_PTR
 	_aesenc_8x	TMP0
 	_ghash_update_continue_8x \enc
 	cmp		$7*8, %eax
@@ -791,14 +670,14 @@
 	// Do the remaining AES rounds.
 	.p2align 4
 1:
-	movdqa		(%rsi), TMP0
-	add		$16, %rsi
+	movdqu		(RNDKEY_PTR), TMP0
+	add		$16, RNDKEY_PTR
 	_aesenc_8x	TMP0
-	cmp		%rsi, RNDKEYLAST_PTR
+	cmp		RNDKEY_PTR, RNDKEYLAST_PTR
 	jne		1b
 
 	// Do the GHASH reduction and the last round of AES.
-	movdqa		(RNDKEYLAST_PTR), TMP0
+	movdqu		(RNDKEYLAST_PTR), TMP0
 	_ghash_update_end_8x_step	0
 	_aesenclast_8x	TMP0
 	_ghash_update_end_8x_step	1
@@ -855,7 +734,7 @@
 	// Set up a block counter %rax to contain 8*(8-n), where n is the number
 	// of blocks that remain, counting any partial block.  This will be used
 	// to access the key powers H^n through H^1.
-	mov		DATALEN, %eax
+	mov		DATALEN32, %eax
 	neg		%eax
 	and		$~15, %eax
 	sar		$1, %eax
@@ -870,25 +749,25 @@
 	// Encrypt the next counter block.
 	_vpshufb	BSWAP_MASK, LE_CTR, TMP0
 	paddd		ONE, LE_CTR
-	pxor		OFFSETOF_AESROUNDKEYS(KEY), TMP0
-	lea		-6*16(RNDKEYLAST_PTR), %rsi	// Reduce code size
-	cmp		$24, AESKEYLEN
+	_xor_mem_to_reg	OFFSETOF_AESROUNDKEYS(KEY), TMP0, tmp=TMP1
+	lea		-6*16(RNDKEYLAST_PTR), RNDKEY_PTR	// Reduce code size
+	cmpl		$24, OFFSETOF_AESKEYLEN(KEY)
 	jl		128f	// AES-128?
 	je		192f	// AES-192?
 	// AES-256
-	aesenc		-7*16(%rsi), TMP0
-	aesenc		-6*16(%rsi), TMP0
+	_aesenc_1x	-7*16(RNDKEY_PTR), TMP0, TMP1
+	_aesenc_1x	-6*16(RNDKEY_PTR), TMP0, TMP1
 192:
-	aesenc		-5*16(%rsi), TMP0
-	aesenc		-4*16(%rsi), TMP0
+	_aesenc_1x	-5*16(RNDKEY_PTR), TMP0, TMP1
+	_aesenc_1x	-4*16(RNDKEY_PTR), TMP0, TMP1
 128:
 .irp i, -3,-2,-1,0,1,2,3,4,5
-	aesenc		\i*16(%rsi), TMP0
+	_aesenc_1x	\i*16(RNDKEY_PTR), TMP0, TMP1
 .endr
-	aesenclast	(RNDKEYLAST_PTR), TMP0
+	_aesenclast_1x	(RNDKEYLAST_PTR), TMP0, TMP1
 
 	// Load the next key power H^i.
-	movdqa		OFFSETOF_H_POWERS(KEY,%rax,2), H_POW
+	movdqu		OFFSETOF_H_POWERS(KEY,%rax,2), H_POW
 	movq		OFFSETOF_H_POWERS_XORED(KEY,%rax), H_POW_XORED
 
 	// XOR the keystream block that was just generated in TMP0 with the next
@@ -927,37 +806,39 @@
 
 	// Encrypt a counter block for the last time.
 	pshufb		BSWAP_MASK, LE_CTR
-	pxor		OFFSETOF_AESROUNDKEYS(KEY), LE_CTR
-	lea		OFFSETOF_AESROUNDKEYS+16(KEY), %rsi
+	_xor_mem_to_reg	OFFSETOF_AESROUNDKEYS(KEY), LE_CTR, tmp=TMP0
+	lea		OFFSETOF_AESROUNDKEYS+16(KEY), RNDKEY_PTR
 1:
-	aesenc		(%rsi), LE_CTR
-	add		$16, %rsi
-	cmp		%rsi, RNDKEYLAST_PTR
+	_aesenc_1x	(RNDKEY_PTR), LE_CTR, TMP0
+	add		$16, RNDKEY_PTR
+	cmp		RNDKEY_PTR, RNDKEYLAST_PTR
 	jne		1b
-	aesenclast	(RNDKEYLAST_PTR), LE_CTR
+	_aesenclast_1x	(RNDKEYLAST_PTR), LE_CTR, TMP0
 
 	// Load the lowest key power, H^1.
-	movdqa		OFFSETOF_H_POWERS(KEY,%rax,2), H_POW
+	movdqu		OFFSETOF_H_POWERS(KEY,%rax,2), H_POW
 	movq		OFFSETOF_H_POWERS_XORED(KEY,%rax), H_POW_XORED
 
-	// Load and zero-pad 1 <= DATALEN <= 15 bytes of data from SRC.  SRC is
-	// in %rcx, but _load_partial_block needs DATALEN in %rcx instead.
-	// RNDKEYLAST_PTR is no longer needed, so reuse it for SRC.
-	mov		SRC, RNDKEYLAST_PTR
-	mov		DATALEN, %ecx
-	_load_partial_block	RNDKEYLAST_PTR, TMP0, %rsi, %esi
+	// Load and zero-pad 1 <= DATALEN <= 15 bytes of data from SRC.
+	// GHASH_ACC_PTR is in %rcx, but _load_partial_block and
+	// _store_partial_block need DATALEN in %ecx instead.  Save
+	// GHASH_ACC_PTR in RNDKEYLAST_PTR, which is no longer needed.
+	mov		GHASH_ACC_PTR, RNDKEYLAST_PTR
+	mov		DATALEN32, %ecx
+	_load_partial_block	SRC, TMP0, %r10, %r10d
 
 	// XOR the keystream block that was just generated in LE_CTR with the
 	// source data block and store the resulting en/decrypted data to DST.
 	pxor		TMP0, LE_CTR
-	mov		DATALEN, %ecx
+	mov		DATALEN32, %ecx
 	_store_partial_block	LE_CTR, DST
+	mov		RNDKEYLAST_PTR, GHASH_ACC_PTR
 
 	// If encrypting, zero-pad the final ciphertext block for GHASH.  (If
 	// decrypting, this was already done by _load_partial_block.)
 .if \enc
 	lea		.Lzeropad_mask+16(%rip), %rax
-	sub		DATALEN64, %rax
+	sub		DATALEN, %rax
 	_vpand		(%rax), LE_CTR, TMP0
 .endif
 
@@ -977,13 +858,16 @@
 	RET
 .endm
 
-// void aes_gcm_enc_final_##suffix(const struct aes_gcm_key_aesni *key,
-//				   const u32 le_ctr[4], u8 ghash_acc[16],
-//				   u64 total_aadlen, u64 total_datalen);
-// bool aes_gcm_dec_final_##suffix(const struct aes_gcm_key_aesni *key,
-//				   const u32 le_ctr[4], const u8 ghash_acc[16],
+// void aes_gcm_enc_final_##suffix(const struct aes_gcm_key *key,
+//				   const u8 nonce[12],
+//				   const struct polyval_elem *ghash_acc,
+//				   u64 total_aadlen, u64 total_datalen,
+//				   u8 *authtag);
+// bool aes_gcm_dec_final_##suffix(const struct aes_gcm_key *key,
+//				   const u8 nonce[12],
+//				   const struct polyval_elem *ghash_acc,
 //				   u64 total_aadlen, u64 total_datalen,
-//				   const u8 tag[16], int taglen);
+//				   const u8 *authtag);
 //
 // This macro generates one of the above two functions (with \enc selecting
 // which one).  Both functions finish computing the GCM authentication tag by
@@ -991,41 +875,42 @@
 // |total_aadlen| and |total_datalen| must be the total length of the additional
 // authenticated data and the en/decrypted data in bytes, respectively.
 //
-// The encryption function then stores the full-length (16-byte) computed
-// authentication tag to |ghash_acc|.  The decryption function instead loads the
-// expected authentication tag (the one that was transmitted) from the 16-byte
-// buffer |tag|, compares the first 4 <= |taglen| <= 16 bytes of it to the
+// The encryption function then stores the computed authentication tag to
+// |authtag|.  The decryption function instead loads the expected authentication
+// tag (the one that was transmitted) from |authtag|, compares it to the
 // computed tag in constant time, and returns true if and only if they match.
+// In both cases the length of the tag is |key->authtag_len| bytes.
 .macro	_aes_gcm_final	enc
 
 	// Function arguments
 	.set	KEY,		%rdi
-	.set	LE_CTR_PTR,	%rsi
+	.set	NONCE_PTR,	%rsi
 	.set	GHASH_ACC_PTR,	%rdx
 	.set	TOTAL_AADLEN,	%rcx
 	.set	TOTAL_DATALEN,	%r8
 	.set	TAG,		%r9
-	.set	TAGLEN,		%r10d	// Originally at 8(%rsp)
-	.set	TAGLEN64,	%r10
 
 	// Additional local variables.
-	// %rax and %xmm0-%xmm2 are used as temporary registers.
-	.set	AESKEYLEN,	%r11d
-	.set	AESKEYLEN64,	%r11
-	.set	BSWAP_MASK,	%xmm3
+	// %rax and %xmm0-%xmm3 are used as temporary registers.
+	.set	AESKEYLEN,	%r10d
+	.set	AESKEYLEN64,	%r10
+	.set	TAGLEN,		%r11d
+	.set	TAGLEN64,	%r11
 	.set	GHASH_ACC,	%xmm4
 	.set	H_POW1,		%xmm5	// H^1
 	.set	H_POW1_X64,	%xmm6	// H^1 * x^64
 	.set	GFPOLY,		%xmm7
+	.set	BSWAP_MASK,	%xmm8
 
 	movdqa		.Lbswap_mask(%rip), BSWAP_MASK
 	movl		OFFSETOF_AESKEYLEN(KEY), AESKEYLEN
+	// authtag_len is size_t with value in 4..16, so movl suffices here.
+	movl		OFFSETOF_AUTHTAG_LEN(KEY), TAGLEN
 
-	// Set up a counter block with 1 in the low 32-bit word.  This is the
-	// counter that produces the ciphertext needed to encrypt the auth tag.
-	movdqu		(LE_CTR_PTR), %xmm0
-	mov		$1, %eax
-	pinsrd		$0, %eax, %xmm0
+	// Build J_0 = nonce || be32(1).
+	movq		(NONCE_PTR), %xmm0
+	pinsrd		$2, 8(NONCE_PTR), %xmm0
+	pinsrd		$3, .Lbe_one(%rip), %xmm0
 
 	// Build the lengths block and XOR it into the GHASH accumulator.
 	movq		TOTAL_DATALEN, GHASH_ACC
@@ -1033,8 +918,8 @@
 	psllq		$3, GHASH_ACC	// Bytes to bits
 	_xor_mem_to_reg	(GHASH_ACC_PTR), GHASH_ACC, %xmm1
 
-	movdqa		OFFSETOF_H_POWERS+7*16(KEY), H_POW1
-	movdqa		OFFSETOF_H_TIMES_X64(KEY), H_POW1_X64
+	movdqu		OFFSETOF_H_POWERS+7*16(KEY), H_POW1
+	movdqu		OFFSETOF_H_TIMES_X64(KEY), H_POW1_X64
 	movq		.Lgfpoly(%rip), GFPOLY
 
 	// Make %rax point to the 6th from last AES round key.  (Using signed
@@ -1043,23 +928,23 @@
 
 	// AES-encrypt the counter block and also multiply GHASH_ACC by H^1.
 	// Interleave the AES and GHASH instructions to improve performance.
-	pshufb		BSWAP_MASK, %xmm0
-	pxor		OFFSETOF_AESROUNDKEYS(KEY), %xmm0
+	_xor_mem_to_reg	OFFSETOF_AESROUNDKEYS(KEY), %xmm0, tmp=%xmm1
+
 	cmp		$24, AESKEYLEN
 	jl		128f	// AES-128?
 	je		192f	// AES-192?
 	// AES-256
-	aesenc		-7*16(%rax), %xmm0
-	aesenc		-6*16(%rax), %xmm0
+	_aesenc_1x	-7*16(%rax), %xmm0, %xmm3
+	_aesenc_1x	-6*16(%rax), %xmm0, %xmm3
 192:
-	aesenc		-5*16(%rax), %xmm0
-	aesenc		-4*16(%rax), %xmm0
+	_aesenc_1x	-5*16(%rax), %xmm0, %xmm3
+	_aesenc_1x	-4*16(%rax), %xmm0, %xmm3
 128:
 .irp i, 0,1,2,3,4,5,6,7,8
-	aesenc		(\i-3)*16(%rax), %xmm0
+	_aesenc_1x	(\i-3)*16(%rax), %xmm0, %xmm3
 	_ghash_mul_step	\i, H_POW1, H_POW1_X64, GHASH_ACC, GFPOLY, %xmm1, %xmm2
 .endr
-	aesenclast	6*16(%rax), %xmm0
+	_aesenclast_1x	6*16(%rax), %xmm0, %xmm3
 	_ghash_mul_step	9, H_POW1, H_POW1_X64, GHASH_ACC, GFPOLY, %xmm1, %xmm2
 
 	// Undo the byte reflection of the GHASH accumulator.
@@ -1070,15 +955,30 @@
 
 .if \enc
 	// Return the computed auth tag.
-	movdqu		GHASH_ACC, (GHASH_ACC_PTR)
+	cmp		$16, TAGLEN
+	jne		.Lstore_short_tag\@
+	movdqu		GHASH_ACC, (TAG)
+	RET
+.Lstore_short_tag\@:
+	mov		TAGLEN, %ecx
+	_store_partial_block GHASH_ACC, TAG
 .else
 	.set		ZEROPAD_MASK_PTR, TOTAL_AADLEN // Reusing TOTAL_AADLEN!
 
 	// Verify the auth tag in constant time by XOR'ing the transmitted and
 	// computed auth tags together and using the ptest instruction to check
 	// whether the first TAGLEN bytes of the result are zero.
+	cmp		$16, TAGLEN
+	jne		.Lverify_short_tag\@
 	_xor_mem_to_reg	(TAG), GHASH_ACC, tmp=%xmm0
-	movl		8(%rsp), TAGLEN
+	xor		%eax, %eax
+	ptest		GHASH_ACC, GHASH_ACC
+	sete		%al
+	RET
+.Lverify_short_tag\@:
+	mov		TAGLEN, %ecx
+	_load_partial_block TAG, %xmm0, %r8, %r8d
+	pxor		%xmm0, GHASH_ACC
 	lea		.Lzeropad_mask+16(%rip), ZEROPAD_MASK_PTR
 	sub		TAGLEN64, ZEROPAD_MASK_PTR
 	xor		%eax, %eax
@@ -1089,12 +989,6 @@
 .endm
 
 .set	USE_AVX, 0
-SYM_FUNC_START(aes_gcm_precompute_aesni)
-	_aes_gcm_precompute
-SYM_FUNC_END(aes_gcm_precompute_aesni)
-SYM_FUNC_START(aes_gcm_aad_update_aesni)
-	_aes_gcm_aad_update
-SYM_FUNC_END(aes_gcm_aad_update_aesni)
 SYM_FUNC_START(aes_gcm_enc_update_aesni)
 	_aes_gcm_update	1
 SYM_FUNC_END(aes_gcm_enc_update_aesni)
@@ -1109,12 +1003,6 @@ SYM_FUNC_START(aes_gcm_dec_final_aesni)
 SYM_FUNC_END(aes_gcm_dec_final_aesni)
 
 .set	USE_AVX, 1
-SYM_FUNC_START(aes_gcm_precompute_aesni_avx)
-	_aes_gcm_precompute
-SYM_FUNC_END(aes_gcm_precompute_aesni_avx)
-SYM_FUNC_START(aes_gcm_aad_update_aesni_avx)
-	_aes_gcm_aad_update
-SYM_FUNC_END(aes_gcm_aad_update_aesni_avx)
 SYM_FUNC_START(aes_gcm_enc_update_aesni_avx)
 	_aes_gcm_update	1
 SYM_FUNC_END(aes_gcm_enc_update_aesni_avx)
diff --git a/lib/crypto/x86/aes.h b/lib/crypto/x86/aes.h
index 01af1a522b429..72222c2895a4f 100644
--- a/lib/crypto/x86/aes.h
+++ b/lib/crypto/x86/aes.h
@@ -6,8 +6,10 @@
  */
 
 #include <asm/fpu/api.h>
+#include "gf128hash-cpu.h"
 
 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_aesni);
+static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_aesni_pclmul);
 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_aesni_avx);
 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_vaes_avx2);
 static __ro_after_init DEFINE_STATIC_KEY_FALSE(have_vaes_avx512);
@@ -406,35 +408,269 @@ static bool aes_xts_decrypt_arch(u8 *dst, const u8 *src, size_t len,
 }
 #endif /* CONFIG_CRYPTO_LIB_AES_XTS */
 
+#if IS_ENABLED(CONFIG_CRYPTO_LIB_AES_GCM) && IS_ENABLED(CONFIG_X86_64)
+/* The assembly code assumes the following offsets. */
+static_assert(offsetof(struct gf128hash_key_x86, h_powers_xored) == 0);
+static_assert(offsetof(struct gf128hash_key_x86, h_powers) == 128);
+static_assert(offsetof(struct gf128hash_key_x86, h_times_xm64) == 304);
+static_assert(offsetof(struct gf128hash_key_x86, h_powers[7]) == 240);
+static_assert(offsetof(struct aes_gcm_key, aes) == 0);
+static_assert(offsetof(struct aes_gcm_key, ghash) == 256);
+static_assert(offsetof(struct aes_gcm_key, authtag_len) == 576);
+
+/*
+ * Limit the length of non-preemptible contexts.  AES-GCM is fast, so use 32 KiB
+ * as the limit rather than 4 KiB.  It must be a multiple of AES_BLOCK_SIZE.
+ */
+#define GCM_CHUNK_SIZE 32768
+
+void aes_gcm_enc_update_aesni(u8 *dst, const u8 *src, size_t len,
+			      struct polyval_elem *ghash_acc,
+			      const __be32 ctr32[4],
+			      const struct aes_gcm_key *key);
+void aes_gcm_dec_update_aesni(u8 *dst, const u8 *src, size_t len,
+			      struct polyval_elem *ghash_acc,
+			      const __be32 ctr32[4],
+			      const struct aes_gcm_key *key);
+void aes_gcm_enc_update_aesni_avx(u8 *dst, const u8 *src, size_t len,
+				  struct polyval_elem *ghash_acc,
+				  const __be32 ctr32[4],
+				  const struct aes_gcm_key *key);
+void aes_gcm_dec_update_aesni_avx(u8 *dst, const u8 *src, size_t len,
+				  struct polyval_elem *ghash_acc,
+				  const __be32 ctr32[4],
+				  const struct aes_gcm_key *key);
+
+void aes_gcm_enc_final_aesni(const struct aes_gcm_key *key, const u8 nonce[12],
+			     const struct polyval_elem *ghash_acc,
+			     u64 total_aadlen, u64 total_datalen, u8 *authtag);
+bool aes_gcm_dec_final_aesni(const struct aes_gcm_key *key, const u8 nonce[12],
+			     const struct polyval_elem *ghash_acc,
+			     u64 total_aadlen, u64 total_datalen,
+			     const u8 *authtag);
+void aes_gcm_enc_final_aesni_avx(const struct aes_gcm_key *key,
+				 const u8 nonce[12],
+				 const struct polyval_elem *ghash_acc,
+				 u64 total_aadlen, u64 total_datalen,
+				 u8 *authtag);
+bool aes_gcm_dec_final_aesni_avx(const struct aes_gcm_key *key,
+				 const u8 nonce[12],
+				 const struct polyval_elem *ghash_acc,
+				 u64 total_aadlen, u64 total_datalen,
+				 const u8 *authtag);
+
+/*
+ * En/decrypt and GHASH @len bytes inside an active FPU section.  @len must be
+ * nonzero.  @len is a multiple of AES_BLOCK_SIZE for incremental AES-GCM, or
+ * any length for one-shot AES-GCM.
+ */
+static __always_inline void
+aes_gcm_update_x86_fpu(u8 *dst, const u8 *src, size_t len,
+		       struct polyval_elem *ghash_acc, __be32 ctr32[4],
+		       const struct aes_gcm_key *key, bool enc)
+{
+	for (;;) {
+		size_t n = min(len, GCM_CHUNK_SIZE);
+
+		static_assert(GCM_CHUNK_SIZE % AES_BLOCK_SIZE == 0);
+
+		if (static_branch_likely(&have_aesni_avx)) {
+			if (enc)
+				aes_gcm_enc_update_aesni_avx(
+					dst, src, n, ghash_acc, ctr32, key);
+			else
+				aes_gcm_dec_update_aesni_avx(
+					dst, src, n, ghash_acc, ctr32, key);
+		} else {
+			if (enc)
+				aes_gcm_enc_update_aesni(dst, src, n, ghash_acc,
+							 ctr32, key);
+			else
+				aes_gcm_dec_update_aesni(dst, src, n, ghash_acc,
+							 ctr32, key);
+		}
+		len -= n;
+		if (likely(!len))
+			break;
+		kernel_fpu_end();
+		be32_add_cpu(&ctr32[3], GCM_CHUNK_SIZE / AES_BLOCK_SIZE);
+		dst += GCM_CHUNK_SIZE;
+		src += GCM_CHUNK_SIZE;
+		kernel_fpu_begin_mask(0);
+	}
+}
+
+/* len is always a positive multiple of AES_BLOCK_SIZE here. */
+static __always_inline bool
+aes_gcm_crypt_update_x86(u8 *dst, const u8 *src, size_t len,
+			 struct polyval_elem *ghash_acc, const __be32 ctr32[4],
+			 const struct aes_gcm_key *key, bool enc)
+{
+	__be32 ctr[4];
+
+	if (!static_branch_likely(&have_aesni_pclmul) ||
+	    static_branch_likely(&have_vaes_avx2) ||
+	    unlikely(!irq_fpu_usable()))
+		return false;
+
+	memcpy(ctr, ctr32, sizeof(ctr));
+	kernel_fpu_begin_mask(0);
+	aes_gcm_update_x86_fpu(dst, src, len, ghash_acc, ctr, key, enc);
+	kernel_fpu_end();
+	return true;
+}
+
+#define aes_gcm_encrypt_update_arch aes_gcm_encrypt_update_arch
+static bool aes_gcm_encrypt_update_arch(u8 *dst, const u8 *src, size_t len,
+					struct polyval_elem *ghash_acc,
+					const __be32 ctr32[4],
+					const struct aes_gcm_key *key)
+{
+	return aes_gcm_crypt_update_x86(dst, src, len, ghash_acc, ctr32, key,
+					true);
+}
+
+#define aes_gcm_decrypt_update_arch aes_gcm_decrypt_update_arch
+static bool aes_gcm_decrypt_update_arch(u8 *dst, const u8 *src, size_t len,
+					struct polyval_elem *ghash_acc,
+					const __be32 ctr32[4],
+					const struct aes_gcm_key *key)
+{
+	return aes_gcm_crypt_update_x86(dst, src, len, ghash_acc, ctr32, key,
+					false);
+}
+
+static void aes_gcm_process_ad_x86(const struct aes_gcm_key *key,
+				   struct polyval_elem *ghash_acc, const u8 *ad,
+				   size_t ad_len)
+{
+	size_t nblocks = ad_len / GHASH_BLOCK_SIZE;
+	size_t ad_rem = ad_len % GHASH_BLOCK_SIZE;
+
+	while (nblocks) {
+		size_t n = min(nblocks, GCM_CHUNK_SIZE / GHASH_BLOCK_SIZE);
+
+		ghash_blocks_x86_fpu(ghash_acc, &key->ghash.k, ad, n);
+		ad += n * GHASH_BLOCK_SIZE;
+		nblocks -= n;
+		if (likely(!nblocks))
+			break;
+		kernel_fpu_end();
+		kernel_fpu_begin_mask(0);
+	}
+	if (ad_rem) {
+		for (size_t i = 0; i < ad_rem; i++)
+			ghash_acc->bytes[GHASH_BLOCK_SIZE - 1 - i] ^= ad[i];
+		gf128hash_mul_x86_fpu(ghash_acc, &key->ghash.k);
+	}
+}
+
+static __always_inline bool
+aes_gcm_crypt_x86(u8 *dst, const u8 *src, size_t data_len, u8 *authtag,
+		  const u8 *ad, size_t ad_len, const u8 nonce[12],
+		  const struct aes_gcm_key *key, bool enc, int *err)
+{
+	struct polyval_elem ghash_acc = {};
+	__be32 ctr32[4];
+
+	if (!static_branch_likely(&have_aesni_pclmul) ||
+	    static_branch_likely(&have_vaes_avx2) ||
+	    unlikely(!irq_fpu_usable()))
+		return false;
+
+	memcpy(ctr32, nonce, 12);
+	ctr32[3] = cpu_to_be32(2);
+
+	kernel_fpu_begin_mask(0);
+
+	if (ad_len)
+		aes_gcm_process_ad_x86(key, &ghash_acc, ad, ad_len);
+
+	if (likely(data_len))
+		aes_gcm_update_x86_fpu(dst, src, data_len, &ghash_acc, ctr32,
+				       key, enc);
+
+	if (enc) {
+		if (static_branch_likely(&have_aesni_avx))
+			aes_gcm_enc_final_aesni_avx(key, nonce, &ghash_acc,
+						    ad_len, data_len, authtag);
+		else
+			aes_gcm_enc_final_aesni(key, nonce, &ghash_acc, ad_len,
+						data_len, authtag);
+	} else {
+		bool valid;
+
+		if (static_branch_likely(&have_aesni_avx))
+			valid = aes_gcm_dec_final_aesni_avx(key, nonce,
+							    &ghash_acc, ad_len,
+							    data_len, authtag);
+		else
+			valid = aes_gcm_dec_final_aesni(key, nonce, &ghash_acc,
+							ad_len, data_len,
+							authtag);
+		*err = valid ? 0 : -EBADMSG;
+	}
+
+	kernel_fpu_end();
+	memzero_explicit(&ghash_acc, sizeof(ghash_acc));
+	return true;
+}
+
+#define aes_gcm_encrypt_arch aes_gcm_encrypt_arch
+static bool aes_gcm_encrypt_arch(u8 *dst, const u8 *src, size_t data_len,
+				 u8 *authtag, const u8 *ad, size_t ad_len,
+				 const u8 nonce[12],
+				 const struct aes_gcm_key *key)
+{
+	return aes_gcm_crypt_x86(dst, src, data_len, authtag, ad, ad_len, nonce,
+				 key, true, NULL);
+}
+
+#define aes_gcm_decrypt_arch aes_gcm_decrypt_arch
+static bool aes_gcm_decrypt_arch(u8 *dst, const u8 *src, size_t data_len,
+				 const u8 *authtag, const u8 *ad, size_t ad_len,
+				 const u8 nonce[12],
+				 const struct aes_gcm_key *key, int *err)
+{
+	return aes_gcm_crypt_x86(dst, src, data_len, (u8 *)authtag, ad, ad_len,
+				 nonce, key, false, err);
+}
+#endif /* CONFIG_CRYPTO_LIB_AES_GCM && CONFIG_X86_64 */
+
 #define aes_mod_init_arch aes_mod_init_arch
 static void aes_mod_init_arch(void)
 {
-	/* Everything below requires AES-NI. */
-	if (!boot_cpu_has(X86_FEATURE_AES))
+	if (!cpu_feature_enabled(X86_FEATURE_AES))
 		return;
-	static_branch_enable(&have_aesni);
 
-	/* Everything below requires AVX and is also 64-bit only. */
-	if (!boot_cpu_has(X86_FEATURE_AVX) || !IS_ENABLED(CONFIG_X86_64))
-		return;
-	static_branch_enable(&have_aesni_avx);
-
-	/*
-	 * Everything below requires VAES, and also sometimes AVX2, VPCLMULQDQ,
-	 * and PCLMULQDQ.  Use a single static key for all of them, since in
-	 * practice every CPU with VAES also has the others.
-	 */
-	if (!boot_cpu_has(X86_FEATURE_VAES) ||
-	    !boot_cpu_has(X86_FEATURE_AVX2) ||
-	    !boot_cpu_has(X86_FEATURE_VPCLMULQDQ) ||
-	    !boot_cpu_has(X86_FEATURE_PCLMULQDQ))
-		return;
-	static_branch_enable(&have_vaes_avx2);
+	/* All the AVX functions are 64-bit only. */
+	if (IS_ENABLED(CONFIG_X86_64) && cpu_feature_enabled(X86_FEATURE_AVX)) {
+		static_branch_enable(&have_aesni_avx);
 
-	if (!boot_cpu_has(X86_FEATURE_AVX512BW) ||
-	    !boot_cpu_has(X86_FEATURE_AVX512VL) ||
-	    !boot_cpu_has(X86_FEATURE_BMI2) ||
-	    boot_cpu_has(X86_FEATURE_PREFER_YMM))
-		return;
-	static_branch_enable(&have_vaes_avx512);
+		/*
+		 * The *_vaes_avx2 functions additionally require VAES,
+		 * VPCLMULQDQ, and AVX2.  (Not all actually need VPCLMULQDQ, but
+		 * every CPU with VAES has VPCLMULQDQ too.)
+		 *
+		 * The *_vaes_avx512 functions require all of that, plus
+		 * AVX512BW, AVX512VL, BMI2, and !PREFER_YMM.
+		 *
+		 * For AES-GCM, the *_vaes_avx2 and *_vaes_avx512 functions
+		 * assume the *_vpclmul_avx2 and *_vpclmul_avx512 ghash_key
+		 * layouts respectively.  The ghash_key layout is selected by
+		 * libgf128hash.  Therefore, use the gf128hash_*() predicates
+		 * (which check for all of these features including VAES) to
+		 * ensure the two modules match.
+		 */
+		if (gf128hash_use_vpclmul_avx2()) {
+			static_branch_enable(&have_vaes_avx2);
+			if (gf128hash_use_vpclmul_avx512())
+				static_branch_enable(&have_vaes_avx512);
+		}
+	}
+
+	if (gf128hash_use_pclmul() && cpu_feature_enabled(X86_FEATURE_XMM4_1))
+		static_branch_enable(&have_aesni_pclmul);
+
+	static_branch_enable(&have_aesni);
 }
diff --git a/lib/crypto/x86/gf128hash-cpu.h b/lib/crypto/x86/gf128hash-cpu.h
index ed7500e665d8d..bad0a5f653851 100644
--- a/lib/crypto/x86/gf128hash-cpu.h
+++ b/lib/crypto/x86/gf128hash-cpu.h
@@ -45,4 +45,10 @@ static inline bool gf128hash_use_vpclmul_avx512(void)
 	       !cpu_feature_enabled(X86_FEATURE_PREFER_YMM);
 }
 
+void ghash_blocks_x86_fpu(struct polyval_elem *acc,
+			  const struct gf128hash_key_x86 *key, const u8 *data,
+			  size_t nblocks);
+void gf128hash_mul_x86_fpu(struct polyval_elem *acc,
+			   const struct gf128hash_key_x86 *key);
+
 #endif /* _LIB_CRYPTO_X86_GF128HASH_CPU_H */
diff --git a/lib/crypto/x86/gf128hash.h b/lib/crypto/x86/gf128hash.h
index 9fb826d62e829..b97e52a80da1f 100644
--- a/lib/crypto/x86/gf128hash.h
+++ b/lib/crypto/x86/gf128hash.h
@@ -99,6 +99,29 @@ __ghash_blocks_x86_fpu(struct polyval_elem *acc,
 		ghash_blocks_pclmul(acc, key, data, nblocks);
 }
 
+/*
+ * The following two functions are exported to libaes for the x86 one-shot
+ * AES-GCM code to efficiently process the associated data.  They assume that
+ * the caller is already in a kernel-mode FPU section and has already checked
+ * gf128hash_use_pclmul() (e.g., via a static_key).  They also assume that
+ * gf128hash_mod_init_arch() has run already, via the initcall ordering.
+ */
+
+void gf128hash_mul_x86_fpu(struct polyval_elem *acc,
+			   const struct gf128hash_key_x86 *key)
+{
+	__gf128hash_mul_x86_fpu(acc, key);
+}
+EXPORT_SYMBOL_FOR_MODULES(gf128hash_mul_x86_fpu, "libaes");
+
+void ghash_blocks_x86_fpu(struct polyval_elem *acc,
+			  const struct gf128hash_key_x86 *key, const u8 *data,
+			  size_t nblocks)
+{
+	__ghash_blocks_x86_fpu(acc, key, data, nblocks);
+}
+EXPORT_SYMBOL_FOR_MODULES(ghash_blocks_x86_fpu, "libaes");
+
 /*
  * Compute *out = *in * x^-64 mod G(x), where
  * x^-64 = x^64 + x^63 + x^62 + x^57 (mod G(x)).
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH 09/11] lib/crypto: x86/aes-gcm: Migrate VAES+AVX2 optimized code into library
  2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
                   ` (7 preceding siblings ...)
  2026-11-29 20:02 ` [PATCH 08/11] lib/crypto: x86/aes-gcm: Migrate AES-NI optimized code into library Eric Biggers
@ 2026-11-29 20:02 ` Eric Biggers
  2026-11-29 20:02 ` [PATCH 10/11] lib/crypto: x86/aes-gcm: Migrate VAES+AVX512 " Eric Biggers
  2026-11-29 20:02 ` [PATCH 11/11] crypto: x86/aesni-intel - Remove empty module Eric Biggers
  10 siblings, 0 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, Eric Biggers

Migrate aes-gcm-vaes-avx2.S into lib/crypto/, and wire it up to the
AES-GCM library functions.  Remove the superseded crypto_aead
implementations from aesni-intel_glue.c.

This makes the AES-GCM library be optimized with VAES+AVX2, while the
same AES-GCM optimizations still remain accessible via crypto_aead via
gcm-aes-lib and rfc4106-gcm-aes-lib.  It's also simpler, since it
eliminates the crypto_aead boilerplate.

Note: the new code is not yet enabled on CPUs that support VAES+AVX512,
since the ghash_key format is different in that case.  The following
commit will migrate the VAES+AVX512 optimized AES-GCM code.

Some changes to the assembly code were required to match what the
library expects:

- Take 'struct aes_gcm_key' instead of 'struct aes_gcm_key_vaes_avx2'.

- Remove aes_gcm_precompute_vaes_avx2() and
  aes_gcm_aad_update_vaes_avx2().  The equivalent functionality is now
  handled in libgf128hash.

- aes_gcm_{enc,dec}_update_vaes_avx2():

    - Take the counter as big-endian instead of little-endian.

    - Widen datalen from int to size_t.

    - Reorder the arguments to match what the library hooks expect.

- Load and store the exact tag length in
  aes_gcm_{enc,dec}_final_vaes_avx2().

Note: the assembly code is in need of some further cleanups (such as
updating some names and comments, and further optimizations).  Those are
left for a later commit, as this one is already quite large.

Benchmark results on AMD Ryzen 9 9950X (Zen 5) with AVX-512VL disabled
(QEMU '-cpu host,-avx512vl') using aes_gcm_kunit (before = uncombined
library AES-CTR + GHASH fallback):

    Length    Enc before   Enc after    Dec before   Dec after
    ------    ----------   ---------    ----------   ---------
        16      278 MB/s    511 MB/s      274 MB/s    670 MB/s
        64     1101 MB/s   2046 MB/s     1052 MB/s   2633 MB/s
       128     2079 MB/s   3613 MB/s     2088 MB/s   4537 MB/s
       256     3776 MB/s   6121 MB/s     3948 MB/s   6989 MB/s
       512     5949 MB/s   8547 MB/s     6030 MB/s   9715 MB/s
      1024     7847 MB/s  10685 MB/s     8010 MB/s  11668 MB/s
      1420     7876 MB/s  10436 MB/s     7440 MB/s  12326 MB/s
      4096    10393 MB/s  12954 MB/s    10410 MB/s  14075 MB/s
     16384    11251 MB/s  13359 MB/s    11402 MB/s  14488 MB/s

Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 arch/x86/crypto/Makefile                      |   1 -
 arch/x86/crypto/aesni-intel_glue.c            | 176 ++------
 lib/crypto/Makefile                           |   3 +-
 .../crypto/x86}/aes-gcm-vaes-avx2.S           | 419 ++++--------------
 lib/crypto/x86/aes.h                          |  42 +-
 5 files changed, 158 insertions(+), 483 deletions(-)
 rename {arch/x86/crypto => lib/crypto/x86}/aes-gcm-vaes-avx2.S (69%)

diff --git a/arch/x86/crypto/Makefile b/arch/x86/crypto/Makefile
index 2749f765c7724..b0e3660980f2f 100644
--- a/arch/x86/crypto/Makefile
+++ b/arch/x86/crypto/Makefile
@@ -41,7 +41,6 @@ aegis128-aesni-y := aegis128-aesni-asm.o aegis128-aesni-glue.o
 
 obj-$(CONFIG_CRYPTO_AES_NI_INTEL) += aesni-intel.o
 aesni-intel-y := aesni-intel_glue.o \
-		 aes-gcm-vaes-avx2.o \
 		 aes-gcm-vaes-avx512.o
 
 obj-$(CONFIG_CRYPTO_SM4_AESNI_AVX_X86_64) += sm4-aesni-avx-x86_64.o
diff --git a/arch/x86/crypto/aesni-intel_glue.c b/arch/x86/crypto/aesni-intel_glue.c
index 51aa7b1566b3d..8d969dfa8f896 100644
--- a/arch/x86/crypto/aesni-intel_glue.c
+++ b/arch/x86/crypto/aesni-intel_glue.c
@@ -46,35 +46,6 @@ struct aes_gcm_key {
 	u32 rfc4106_nonce;
 };
 
-/* Key struct used by the VAES + AVX2 implementation of AES-GCM */
-struct aes_gcm_key_vaes_avx2 {
-	/*
-	 * Common part of the key.  The assembly code prefers 16-byte alignment
-	 * for this.
-	 */
-	struct aes_gcm_key base __aligned(16);
-
-	/*
-	 * Powers of the hash key H^8 through H^1.  These are 128-bit values.
-	 * They all have an extra factor of x^-1 and are byte-reversed.
-	 * The assembly code prefers 32-byte alignment for this.
-	 */
-	u64 h_powers[8][2] __aligned(32);
-
-	/*
-	 * Each entry in this array contains the two halves of an entry of
-	 * h_powers XOR'd together, in the following order:
-	 * H^8,H^6,H^7,H^5,H^4,H^2,H^3,H^1 i.e. indices 0,2,1,3,4,6,5,7.
-	 * This is used for Karatsuba multiplication.
-	 */
-	u64 h_powers_xored[8];
-};
-
-#define AES_GCM_KEY_VAES_AVX2(key) \
-	container_of((key), struct aes_gcm_key_vaes_avx2, base)
-#define AES_GCM_KEY_VAES_AVX2_SIZE \
-	(sizeof(struct aes_gcm_key_vaes_avx2) + (31 & ~(CRYPTO_MINALIGN - 1)))
-
 /* Key struct used by the VAES + AVX512 implementation of AES-GCM */
 struct aes_gcm_key_vaes_avx512 {
 	/*
@@ -109,34 +80,21 @@ struct aes_gcm_key_vaes_avx512 {
  */
 #define FLAG_RFC4106	BIT(0)
 #define FLAG_ENC	BIT(1)
-#define FLAG_VAES_AVX2	BIT(3)
 #define FLAG_VAES_AVX512 BIT(4)
 
 static inline struct aes_gcm_key *
 aes_gcm_key_get(struct crypto_aead *tfm, int flags)
 {
-	if (flags & FLAG_VAES_AVX512)
-		return PTR_ALIGN(crypto_aead_ctx(tfm), 64);
-	else
-		return PTR_ALIGN(crypto_aead_ctx(tfm), 32);
+	return PTR_ALIGN(crypto_aead_ctx(tfm), 64);
 }
 
-asmlinkage void
-aes_gcm_precompute_vaes_avx2(struct aes_gcm_key_vaes_avx2 *key);
 asmlinkage void
 aes_gcm_precompute_vaes_avx512(struct aes_gcm_key_vaes_avx512 *key);
 
 static void aes_gcm_precompute(struct aes_gcm_key *key, int flags)
 {
-	if (flags & FLAG_VAES_AVX512)
-		aes_gcm_precompute_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key));
-	else
-		aes_gcm_precompute_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key));
+	aes_gcm_precompute_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key));
 }
-
-asmlinkage void
-aes_gcm_aad_update_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
-			     u8 ghash_acc[16], const u8 *aad, int aadlen);
 asmlinkage void
 aes_gcm_aad_update_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
 			       u8 ghash_acc[16], const u8 *aad, int aadlen);
@@ -144,28 +102,15 @@ aes_gcm_aad_update_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
 static void aes_gcm_aad_update(const struct aes_gcm_key *key, u8 ghash_acc[16],
 			       const u8 *aad, int aadlen, int flags)
 {
-	if (flags & FLAG_VAES_AVX512)
-		aes_gcm_aad_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
-					       ghash_acc, aad, aadlen);
-	else
-		aes_gcm_aad_update_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key),
-					     ghash_acc, aad, aadlen);
+	aes_gcm_aad_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key), ghash_acc,
+				       aad, aadlen);
 }
-
-asmlinkage void
-aes_gcm_enc_update_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
-			     const u32 le_ctr[4], u8 ghash_acc[16],
-			     const u8 *src, u8 *dst, int datalen);
 asmlinkage void
 aes_gcm_enc_update_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
 			       const u32 le_ctr[4], u8 ghash_acc[16],
 			       const u8 *src, u8 *dst, int datalen);
 
 asmlinkage void
-aes_gcm_dec_update_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
-			     const u32 le_ctr[4], u8 ghash_acc[16],
-			     const u8 *src, u8 *dst, int datalen);
-asmlinkage void
 aes_gcm_dec_update_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
 			       const u32 le_ctr[4], u8 ghash_acc[16],
 			       const u8 *src, u8 *dst, int datalen);
@@ -177,30 +122,16 @@ aes_gcm_update(const struct aes_gcm_key *key,
 	       const u8 *src, u8 *dst, int datalen, int flags)
 {
 	if (flags & FLAG_ENC) {
-		if (flags & FLAG_VAES_AVX512)
-			aes_gcm_enc_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
-						       le_ctr, ghash_acc,
-						       src, dst, datalen);
-		else
-			aes_gcm_enc_update_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key),
-						     le_ctr, ghash_acc,
-						     src, dst, datalen);
+		aes_gcm_enc_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
+					       le_ctr, ghash_acc, src, dst,
+					       datalen);
 	} else {
-		if (flags & FLAG_VAES_AVX512)
-			aes_gcm_dec_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
-						       le_ctr, ghash_acc,
-						       src, dst, datalen);
-		else
-			aes_gcm_dec_update_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key),
-						     le_ctr, ghash_acc,
-						     src, dst, datalen);
+		aes_gcm_dec_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
+					       le_ctr, ghash_acc, src, dst,
+					       datalen);
 	}
 }
 
-asmlinkage void
-aes_gcm_enc_final_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
-			    const u32 le_ctr[4], u8 ghash_acc[16],
-			    u64 total_aadlen, u64 total_datalen);
 asmlinkage void
 aes_gcm_enc_final_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
 			      const u32 le_ctr[4], u8 ghash_acc[16],
@@ -212,21 +143,9 @@ aes_gcm_enc_final(const struct aes_gcm_key *key,
 		  const u32 le_ctr[4], u8 ghash_acc[16],
 		  u64 total_aadlen, u64 total_datalen, int flags)
 {
-	if (flags & FLAG_VAES_AVX512)
-		aes_gcm_enc_final_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
-					      le_ctr, ghash_acc,
-					      total_aadlen, total_datalen);
-	else
-		aes_gcm_enc_final_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key),
-					    le_ctr, ghash_acc,
-					    total_aadlen, total_datalen);
+	aes_gcm_enc_final_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key), le_ctr,
+				      ghash_acc, total_aadlen, total_datalen);
 }
-
-asmlinkage bool __must_check
-aes_gcm_dec_final_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
-			    const u32 le_ctr[4], const u8 ghash_acc[16],
-			    u64 total_aadlen, u64 total_datalen,
-			    const u8 tag[16], int taglen);
 asmlinkage bool __must_check
 aes_gcm_dec_final_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
 			      const u32 le_ctr[4], const u8 ghash_acc[16],
@@ -239,16 +158,9 @@ aes_gcm_dec_final(const struct aes_gcm_key *key, const u32 le_ctr[4],
 		  u8 ghash_acc[16], u64 total_aadlen, u64 total_datalen,
 		  u8 tag[16], int taglen, int flags)
 {
-	if (flags & FLAG_VAES_AVX512)
-		return aes_gcm_dec_final_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
-						     le_ctr, ghash_acc,
-						     total_aadlen, total_datalen,
-						     tag, taglen);
-	else
-		return aes_gcm_dec_final_vaes_avx2(AES_GCM_KEY_VAES_AVX2(key),
-						   le_ctr, ghash_acc,
-						   total_aadlen, total_datalen,
-						   tag, taglen);
+	return aes_gcm_dec_final_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
+					     le_ctr, ghash_acc, total_aadlen,
+					     total_datalen, tag, taglen);
 }
 
 /*
@@ -316,10 +228,6 @@ static int gcm_setkey(struct crypto_aead *tfm, const u8 *raw_key,
 	}
 
 	/* The assembly code assumes the following offsets. */
-	static_assert(offsetof(struct aes_gcm_key_vaes_avx2, base.aes_key.len) == 0);
-	static_assert(offsetof(struct aes_gcm_key_vaes_avx2, base.aes_key.k.rndkeys) == 16);
-	static_assert(offsetof(struct aes_gcm_key_vaes_avx2, h_powers) == 288);
-	static_assert(offsetof(struct aes_gcm_key_vaes_avx2, h_powers_xored) == 416);
 	static_assert(offsetof(struct aes_gcm_key_vaes_avx512, base.aes_key.len) == 0);
 	static_assert(offsetof(struct aes_gcm_key_vaes_avx512, base.aes_key.k.rndkeys) == 16);
 	static_assert(offsetof(struct aes_gcm_key_vaes_avx512, h_powers) == 320);
@@ -349,33 +257,15 @@ static int gcm_setkey(struct crypto_aead *tfm, const u8 *raw_key,
 		gf128mul_lle(&h, (const be128 *)x_to_the_minus1);
 
 		/* Compute the needed key powers */
-		if (flags & FLAG_VAES_AVX512) {
-			struct aes_gcm_key_vaes_avx512 *k =
-				AES_GCM_KEY_VAES_AVX512(key);
-
-			for (i = ARRAY_SIZE(k->h_powers) - 1; i >= 0; i--) {
-				k->h_powers[i][0] = be64_to_cpu(h.b);
-				k->h_powers[i][1] = be64_to_cpu(h.a);
-				gf128mul_lle(&h, &h1);
-			}
-			memset(k->padding, 0, sizeof(k->padding));
-		} else {
-			struct aes_gcm_key_vaes_avx2 *k =
-				AES_GCM_KEY_VAES_AVX2(key);
-			static const u8 indices[8] = { 0, 2, 1, 3, 4, 6, 5, 7 };
-
-			for (i = ARRAY_SIZE(k->h_powers) - 1; i >= 0; i--) {
-				k->h_powers[i][0] = be64_to_cpu(h.b);
-				k->h_powers[i][1] = be64_to_cpu(h.a);
-				gf128mul_lle(&h, &h1);
-			}
-			for (i = 0; i < ARRAY_SIZE(k->h_powers_xored); i++) {
-				int j = indices[i];
-
-				k->h_powers_xored[i] = k->h_powers[j][0] ^
-						       k->h_powers[j][1];
-			}
+		struct aes_gcm_key_vaes_avx512 *k =
+			AES_GCM_KEY_VAES_AVX512(key);
+
+		for (i = ARRAY_SIZE(k->h_powers) - 1; i >= 0; i--) {
+			k->h_powers[i][0] = be64_to_cpu(h.b);
+			k->h_powers[i][1] = be64_to_cpu(h.a);
+			gf128mul_lle(&h, &h1);
 		}
+		memset(k->padding, 0, sizeof(k->padding));
 	}
 	return 0;
 }
@@ -620,11 +510,6 @@ static struct aead_alg aes_gcm_algs_##suffix[] = { {			       \
 	},								       \
 } }
 
-/* aes_gcm_algs_vaes_avx2 */
-DEFINE_GCM_ALGS(vaes_avx2, FLAG_VAES_AVX2,
-		"generic-gcm-vaes-avx2", "rfc4106-gcm-vaes-avx2",
-		AES_GCM_KEY_VAES_AVX2_SIZE, 600);
-
 /* aes_gcm_algs_vaes_avx512 */
 DEFINE_GCM_ALGS(vaes_avx512, FLAG_VAES_AVX512,
 		"generic-gcm-vaes-avx512", "rfc4106-gcm-vaes-avx512",
@@ -632,8 +517,6 @@ DEFINE_GCM_ALGS(vaes_avx512, FLAG_VAES_AVX512,
 
 static int __init register_avx_algs(void)
 {
-	int err;
-
 	if (!boot_cpu_has(X86_FEATURE_AVX))
 		return 0;
 	/*
@@ -647,10 +530,6 @@ static int __init register_avx_algs(void)
 	    !boot_cpu_has(X86_FEATURE_VPCLMULQDQ) ||
 	    !boot_cpu_has(X86_FEATURE_PCLMULQDQ))
 		return 0;
-	err = crypto_register_aeads(aes_gcm_algs_vaes_avx2,
-				    ARRAY_SIZE(aes_gcm_algs_vaes_avx2));
-	if (err)
-		return err;
 
 	if (!boot_cpu_has(X86_FEATURE_AVX512BW) ||
 	    !boot_cpu_has(X86_FEATURE_AVX512VL) ||
@@ -664,12 +543,8 @@ static int __init register_avx_algs(void)
 			aes_gcm_algs_vaes_avx512[i].base.cra_priority = 1;
 	}
 
-	err = crypto_register_aeads(aes_gcm_algs_vaes_avx512,
-				    ARRAY_SIZE(aes_gcm_algs_vaes_avx512));
-	if (err)
-		return err;
-
-	return 0;
+	return crypto_register_aeads(aes_gcm_algs_vaes_avx512,
+				     ARRAY_SIZE(aes_gcm_algs_vaes_avx512));
 }
 
 #define unregister_aeads(A) \
@@ -678,7 +553,6 @@ static int __init register_avx_algs(void)
 
 static void unregister_avx_algs(void)
 {
-	unregister_aeads(aes_gcm_algs_vaes_avx2);
 	unregister_aeads(aes_gcm_algs_vaes_avx512);
 }
 
diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile
index b813c895cc9da..6e2d264f12492 100644
--- a/lib/crypto/Makefile
+++ b/lib/crypto/Makefile
@@ -96,7 +96,8 @@ ifneq ($(CONFIG_CRYPTO_LIB_AES_CTR),)
 libaes-$(CONFIG_X86_64) += x86/aes-ctr-avx-x86_64.o
 endif
 ifneq ($(CONFIG_CRYPTO_LIB_AES_GCM),)
-libaes-$(CONFIG_X86_64) += x86/aes-gcm-aesni-x86_64.o
+libaes-$(CONFIG_X86_64) += x86/aes-gcm-aesni-x86_64.o \
+			   x86/aes-gcm-vaes-avx2.o
 endif
 ifneq ($(CONFIG_CRYPTO_LIB_AES_XTS),)
 libaes-$(CONFIG_X86_64) += x86/aes-xts-avx-x86_64.o
diff --git a/arch/x86/crypto/aes-gcm-vaes-avx2.S b/lib/crypto/x86/aes-gcm-vaes-avx2.S
similarity index 69%
rename from arch/x86/crypto/aes-gcm-vaes-avx2.S
rename to lib/crypto/x86/aes-gcm-vaes-avx2.S
index 9cc387957fa93..2adcb36c08e37 100644
--- a/arch/x86/crypto/aes-gcm-vaes-avx2.S
+++ b/lib/crypto/x86/aes-gcm-vaes-avx2.S
@@ -108,10 +108,6 @@
 .Lgfpoly:
 	.octa	0xc2000000000000000000000000000001
 
-	// Same as above, but with the (1 << 64) bit set.
-.Lgfpoly_and_internal_carrybit:
-	.octa	0xc2000000000000010000000000000001
-
 	// Values needed to prepare the initial vector of counter blocks.
 .Lctr_pattern:
 	.octa	0
@@ -121,13 +117,17 @@
 .Linc_2blocks:
 	.octa	2
 
-// Offsets in struct aes_gcm_key_vaes_avx2
+.Lbe_one:
+	.long	0x01000000
+
+// Offsets in struct aes_gcm_key
 #define OFFSETOF_AESKEYLEN	0
 #define OFFSETOF_AESROUNDKEYS	16
-#define OFFSETOF_H_POWERS	288
+#define OFFSETOF_H_POWERS_XORED	(256 + 0)
+#define OFFSETOF_H_POWERS	(256 + 128)
 #define NUM_H_POWERS		8
 #define OFFSETOFEND_H_POWERS    (OFFSETOF_H_POWERS + (NUM_H_POWERS * 16))
-#define OFFSETOF_H_POWERS_XORED	OFFSETOFEND_H_POWERS
+#define OFFSETOF_AUTHTAG_LEN	(256 + 320)
 
 .text
 
@@ -161,14 +161,6 @@
 .endif
 .endm
 
-// GHASH-multiply the 128-bit lanes of \a by the 128-bit lanes of \b and store
-// the reduced products in \dst.  See _ghash_mul_step for full explanation.
-.macro	_ghash_mul	a, b, dst, gfpoly, t0, t1, t2
-.irp i, 0,1,2,3,4,5,6,7,8,9
-	_ghash_mul_step	\i, \a, \b, \dst, \gfpoly, \t0, \t1, \t2
-.endr
-.endm
-
 // GHASH-multiply the 128-bit lanes of \a by the 128-bit lanes of \b and add the
 // *unreduced* products to \lo, \mi, and \hi.
 .macro	_ghash_mul_noreduce	a, b, lo, mi, hi, t0
@@ -195,122 +187,12 @@
 	vpxor		\t0, \hi, \hi
 .endm
 
-// This is a specialized version of _ghash_mul that computes \a * \a, i.e. it
-// squares \a.  It skips computing MI = (a_L * a_H) + (a_H * a_L) = 0.
-.macro	_ghash_square	a, dst, gfpoly, t0, t1
-	vpclmulqdq	$0x00, \a, \a, \t0	  // LO = a_L * a_L
-	vpclmulqdq	$0x11, \a, \a, \dst	  // HI = a_H * a_H
-	vpclmulqdq	$0x01, \t0, \gfpoly, \t1  // LO_L*(x^63 + x^62 + x^57)
-	vpshufd		$0x4e, \t0, \t0		  // Swap halves of LO
-	vpxor		\t0, \t1, \t1		  // Fold LO into MI
-	vpclmulqdq	$0x01, \t1, \gfpoly, \t0  // MI_L*(x^63 + x^62 + x^57)
-	vpshufd		$0x4e, \t1, \t1		  // Swap halves of MI
-	vpxor		\t1, \dst, \dst		  // Fold MI into HI (part 1)
-	vpxor		\t0, \dst, \dst		  // Fold MI into HI (part 2)
-.endm
-
-// void aes_gcm_precompute_vaes_avx2(struct aes_gcm_key_vaes_avx2 *key);
-//
-// Given the expanded AES key |key->base.aes_key|, derive the GHASH subkey and
-// initialize |key->h_powers| and |key->h_powers_xored|.
-//
-// We use h_powers[0..7] to store H^8 through H^1, and h_powers_xored[0..7] to
-// store the 64-bit halves of the key powers XOR'd together (for Karatsuba
-// multiplication) in the order 8,6,7,5,4,2,3,1.
-SYM_FUNC_START(aes_gcm_precompute_vaes_avx2)
-
-	// Function arguments
-	.set	KEY,		%rdi
-
-	// Additional local variables
-	.set	POWERS_PTR,	%rsi
-	.set	RNDKEYLAST_PTR,	%rdx
-	.set	TMP0,		%ymm0
-	.set	TMP0_XMM,	%xmm0
-	.set	TMP1,		%ymm1
-	.set	TMP1_XMM,	%xmm1
-	.set	TMP2,		%ymm2
-	.set	TMP2_XMM,	%xmm2
-	.set	H_CUR,		%ymm3
-	.set	H_CUR_XMM,	%xmm3
-	.set	H_CUR2,		%ymm4
-	.set	H_INC,		%ymm5
-	.set	H_INC_XMM,	%xmm5
-	.set	GFPOLY,		%ymm6
-	.set	GFPOLY_XMM,	%xmm6
-
-	// Encrypt an all-zeroes block to get the raw hash subkey.
-	movl		OFFSETOF_AESKEYLEN(KEY), %eax
-	lea		OFFSETOF_AESROUNDKEYS+6*16(KEY,%rax,4), RNDKEYLAST_PTR
-	vmovdqu		OFFSETOF_AESROUNDKEYS(KEY), H_CUR_XMM
-	lea		OFFSETOF_AESROUNDKEYS+16(KEY), %rax
-1:
-	vaesenc		(%rax), H_CUR_XMM, H_CUR_XMM
-	add		$16, %rax
-	cmp		%rax, RNDKEYLAST_PTR
-	jne		1b
-	vaesenclast	(RNDKEYLAST_PTR), H_CUR_XMM, H_CUR_XMM
-
-	// Reflect the bytes of the raw hash subkey.
-	vpshufb		.Lbswap_mask(%rip), H_CUR_XMM, H_CUR_XMM
-
-	// Finish preprocessing the byte-reflected hash subkey by multiplying it
-	// by x^-1 ("standard" interpretation of polynomial coefficients) or
-	// equivalently x^1 (natural interpretation).  This gets the key into a
-	// format that avoids having to bit-reflect the data blocks later.
-	vpshufd		$0xd3, H_CUR_XMM, TMP0_XMM
-	vpsrad		$31, TMP0_XMM, TMP0_XMM
-	vpaddq		H_CUR_XMM, H_CUR_XMM, H_CUR_XMM
-	vpand		.Lgfpoly_and_internal_carrybit(%rip), TMP0_XMM, TMP0_XMM
-	vpxor		TMP0_XMM, H_CUR_XMM, H_CUR_XMM
-
-	// Load the gfpoly constant.
-	vbroadcasti128	.Lgfpoly(%rip), GFPOLY
-
-	// Square H^1 to get H^2.
-	_ghash_square	H_CUR_XMM, H_INC_XMM, GFPOLY_XMM, TMP0_XMM, TMP1_XMM
-
-	// Create H_CUR = [H^2, H^1] and H_INC = [H^2, H^2].
-	vinserti128	$1, H_CUR_XMM, H_INC, H_CUR
-	vinserti128	$1, H_INC_XMM, H_INC, H_INC
-
-	// Compute H_CUR2 = [H^4, H^3].
-	_ghash_mul	H_INC, H_CUR, H_CUR2, GFPOLY, TMP0, TMP1, TMP2
-
-	// Store [H^2, H^1] and [H^4, H^3].
-	vmovdqu		H_CUR, OFFSETOF_H_POWERS+3*32(KEY)
-	vmovdqu		H_CUR2, OFFSETOF_H_POWERS+2*32(KEY)
-
-	// For Karatsuba multiplication: compute and store the two 64-bit halves
-	// of each key power XOR'd together.  Order is 4,2,3,1.
-	vpunpcklqdq	H_CUR, H_CUR2, TMP0
-	vpunpckhqdq	H_CUR, H_CUR2, TMP1
-	vpxor		TMP1, TMP0, TMP0
-	vmovdqu		TMP0, OFFSETOF_H_POWERS_XORED+32(KEY)
-
-	// Compute and store H_CUR = [H^6, H^5] and H_CUR2 = [H^8, H^7].
-	_ghash_mul	H_INC, H_CUR2, H_CUR, GFPOLY, TMP0, TMP1, TMP2
-	_ghash_mul	H_INC, H_CUR, H_CUR2, GFPOLY, TMP0, TMP1, TMP2
-	vmovdqu		H_CUR, OFFSETOF_H_POWERS+1*32(KEY)
-	vmovdqu		H_CUR2, OFFSETOF_H_POWERS+0*32(KEY)
-
-	// Again, compute and store the two 64-bit halves of each key power
-	// XOR'd together.  Order is 8,6,7,5.
-	vpunpcklqdq	H_CUR, H_CUR2, TMP0
-	vpunpckhqdq	H_CUR, H_CUR2, TMP1
-	vpxor		TMP1, TMP0, TMP0
-	vmovdqu		TMP0, OFFSETOF_H_POWERS_XORED(KEY)
-
-	vzeroupper
-	RET
-SYM_FUNC_END(aes_gcm_precompute_vaes_avx2)
-
 // Do one step of the GHASH update of four vectors of data blocks.
 //   \i: the step to do, 0 through 9
-//   \ghashdata_ptr: pointer to the data blocks (ciphertext or AAD)
-//   KEY: pointer to struct aes_gcm_key_vaes_avx2
+//   \ghashdata_ptr: pointer to the data blocks (ciphertext)
+//   KEY: pointer to struct aes_gcm_key
 //   BSWAP_MASK: mask for reflecting the bytes of blocks
-//   H_POW[2-1]_XORED: cached values from KEY->h_powers_xored
+//   H_POW[2-1]_XORED: cached values from KEY->ghash.k.h_powers_xored
 //   TMP[0-2]: temporary registers.  TMP[1-2] must be preserved across steps.
 //   LO, MI: working state for this macro that must be preserved across steps
 //   GHASH_ACC: the GHASH accumulator (input/output)
@@ -480,136 +362,6 @@ SYM_FUNC_END(aes_gcm_precompute_vaes_avx2)
 .Ldone\@:
 .endm
 
-// void aes_gcm_aad_update_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
-//				     u8 ghash_acc[16],
-//				     const u8 *aad, int aadlen);
-//
-// This function processes the AAD (Additional Authenticated Data) in GCM.
-// Using the key |key|, it updates the GHASH accumulator |ghash_acc| with the
-// data given by |aad| and |aadlen|.  On the first call, |ghash_acc| must be all
-// zeroes.  |aadlen| must be a multiple of 16, except on the last call where it
-// can be any length.  The caller must do any buffering needed to ensure this.
-//
-// This handles large amounts of AAD efficiently, while also keeping overhead
-// low for small amounts which is the common case.  TLS and IPsec use less than
-// one block of AAD, but (uncommonly) other use cases may use much more.
-SYM_FUNC_START(aes_gcm_aad_update_vaes_avx2)
-
-	// Function arguments
-	.set	KEY,		%rdi
-	.set	GHASH_ACC_PTR,	%rsi
-	.set	AAD,		%rdx
-	.set	AADLEN,		%ecx	// Must be %ecx for _load_partial_block
-	.set	AADLEN64,	%rcx	// Zero-extend AADLEN before using!
-
-	// Additional local variables.
-	// %rax and %r8 are used as temporary registers.
-	.set	TMP0,		%ymm0
-	.set	TMP0_XMM,	%xmm0
-	.set	TMP1,		%ymm1
-	.set	TMP1_XMM,	%xmm1
-	.set	TMP2,		%ymm2
-	.set	TMP2_XMM,	%xmm2
-	.set	LO,		%ymm3
-	.set	LO_XMM,		%xmm3
-	.set	MI,		%ymm4
-	.set	MI_XMM,		%xmm4
-	.set	GHASH_ACC,	%ymm5
-	.set	GHASH_ACC_XMM,	%xmm5
-	.set	BSWAP_MASK,	%ymm6
-	.set	BSWAP_MASK_XMM,	%xmm6
-	.set	GFPOLY,		%ymm7
-	.set	GFPOLY_XMM,	%xmm7
-	.set	H_POW2_XORED,	%ymm8
-	.set	H_POW1_XORED,	%ymm9
-
-	// Load the bswap_mask and gfpoly constants.  Since AADLEN is usually
-	// small, usually only 128-bit vectors will be used.  So as an
-	// optimization, don't broadcast these constants to both 128-bit lanes
-	// quite yet.
-	vmovdqu		.Lbswap_mask(%rip), BSWAP_MASK_XMM
-	vmovdqu		.Lgfpoly(%rip), GFPOLY_XMM
-
-	// Load the GHASH accumulator.
-	vmovdqu		(GHASH_ACC_PTR), GHASH_ACC_XMM
-
-	// Check for the common case of AADLEN <= 16, as well as AADLEN == 0.
-	test		AADLEN, AADLEN
-	jz		.Laad_done
-	cmp		$16, AADLEN
-	jle		.Laad_lastblock
-
-	// AADLEN > 16, so we'll operate on full vectors.  Broadcast bswap_mask
-	// and gfpoly to both 128-bit lanes.
-	vinserti128	$1, BSWAP_MASK_XMM, BSWAP_MASK, BSWAP_MASK
-	vinserti128	$1, GFPOLY_XMM, GFPOLY, GFPOLY
-
-	// If AADLEN >= 128, update GHASH with 128 bytes of AAD at a time.
-	add		$-128, AADLEN	// 128 is 4 bytes, -128 is 1 byte
-	jl		.Laad_loop_4x_done
-	vmovdqu		OFFSETOF_H_POWERS_XORED(KEY), H_POW2_XORED
-	vmovdqu		OFFSETOF_H_POWERS_XORED+32(KEY), H_POW1_XORED
-.Laad_loop_4x:
-	_ghash_4x	AAD
-	sub		$-128, AAD
-	add		$-128, AADLEN
-	jge		.Laad_loop_4x
-.Laad_loop_4x_done:
-
-	// If AADLEN >= 32, update GHASH with 32 bytes of AAD at a time.
-	add		$96, AADLEN
-	jl		.Laad_loop_1x_done
-.Laad_loop_1x:
-	vmovdqu		(AAD), TMP0
-	vpshufb		BSWAP_MASK, TMP0, TMP0
-	vpxor		TMP0, GHASH_ACC, GHASH_ACC
-	vmovdqu		OFFSETOFEND_H_POWERS-32(KEY), TMP0
-	_ghash_mul	TMP0, GHASH_ACC, GHASH_ACC, GFPOLY, TMP1, TMP2, LO
-	vextracti128	$1, GHASH_ACC, TMP0_XMM
-	vpxor		TMP0_XMM, GHASH_ACC_XMM, GHASH_ACC_XMM
-	add		$32, AAD
-	sub		$32, AADLEN
-	jge		.Laad_loop_1x
-.Laad_loop_1x_done:
-	add		$32, AADLEN
-	// Now 0 <= AADLEN < 32.
-
-	jz		.Laad_done
-	cmp		$16, AADLEN
-	jle		.Laad_lastblock
-
-	// Update GHASH with the remaining 17 <= AADLEN <= 31 bytes of AAD.
-	mov		AADLEN, AADLEN	// Zero-extend AADLEN to AADLEN64.
-	vmovdqu		(AAD), TMP0_XMM
-	vmovdqu		-16(AAD, AADLEN64), TMP1_XMM
-	vpshufb		BSWAP_MASK_XMM, TMP0_XMM, TMP0_XMM
-	vpxor		TMP0_XMM, GHASH_ACC_XMM, GHASH_ACC_XMM
-	lea		.Lrshift_and_bswap_table(%rip), %rax
-	vpshufb		-16(%rax, AADLEN64), TMP1_XMM, TMP1_XMM
-	vinserti128	$1, TMP1_XMM, GHASH_ACC, GHASH_ACC
-	vmovdqu		OFFSETOFEND_H_POWERS-32(KEY), TMP0
-	_ghash_mul	TMP0, GHASH_ACC, GHASH_ACC, GFPOLY, TMP1, TMP2, LO
-	vextracti128	$1, GHASH_ACC, TMP0_XMM
-	vpxor		TMP0_XMM, GHASH_ACC_XMM, GHASH_ACC_XMM
-	jmp		.Laad_done
-
-.Laad_lastblock:
-	// Update GHASH with the remaining 1 <= AADLEN <= 16 bytes of AAD.
-	_load_partial_block	AAD, TMP0_XMM, %r8, %r8d
-	vpshufb		BSWAP_MASK_XMM, TMP0_XMM, TMP0_XMM
-	vpxor		TMP0_XMM, GHASH_ACC_XMM, GHASH_ACC_XMM
-	vmovdqu		OFFSETOFEND_H_POWERS-16(KEY), TMP0_XMM
-	_ghash_mul	TMP0_XMM, GHASH_ACC_XMM, GHASH_ACC_XMM, GFPOLY_XMM, \
-			TMP1_XMM, TMP2_XMM, LO_XMM
-
-.Laad_done:
-	// Store the updated GHASH accumulator back to memory.
-	vmovdqu		GHASH_ACC_XMM, (GHASH_ACC_PTR)
-
-	vzeroupper
-	RET
-SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
-
 // Do one non-last round of AES encryption on the blocks in the given AESDATA
 // vectors using the round key that has been broadcast to all 128-bit lanes of
 // \round_key.
@@ -659,9 +411,11 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 .endr
 .endm
 
-// void aes_gcm_{enc,dec}_update_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
-//					   const u32 le_ctr[4], u8 ghash_acc[16],
-//					   const u8 *src, u8 *dst, int datalen);
+// void aes_gcm_{enc,dec}_update_vaes_avx2(u8 *dst, const u8 *src,
+//					   size_t datalen,
+//					   struct polyval_elem *ghash_acc,
+//					   const __be32 ctr32[4],
+//					   const struct aes_gcm_key *key);
 //
 // This macro generates a GCM encryption or decryption update function with the
 // above prototype (with \enc selecting which one).  The function computes the
@@ -674,28 +428,25 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 // any length.  The caller must do any buffering needed to ensure this.  Both
 // in-place and out-of-place en/decryption are supported.
 //
-// |le_ctr| must give the current counter in little-endian format.  This
-// function loads the counter from |le_ctr| and increments the loaded counter as
-// needed, but it does *not* store the updated counter back to |le_ctr|.  The
-// caller must update |le_ctr| if any more data segments follow.  Internally,
-// only the low 32-bit word of the counter is incremented, following the GCM
-// standard.
+// |ctr32| must give the current counter in big-endian format.  This function
+// loads the counter from |ctr32| and increments the loaded counter as needed,
+// but it does *not* store the updated counter back to |ctr32|.  The caller must
+// update |ctr32| if any more data segments follow.  Internally, only the low
+// 32-bit word of the counter is incremented, following the GCM standard.
 .macro	_aes_gcm_update	enc
 
 	// Function arguments
-	.set	KEY,		%rdi
-	.set	LE_CTR_PTR,	%rsi
-	.set	LE_CTR_PTR32,	%esi
-	.set	GHASH_ACC_PTR,	%rdx
-	.set	SRC,		%rcx	// Assumed to be %rcx.
+	.set	DST,		%rdi
+	.set	SRC,		%rsi
+	.set	DATALEN,	%rdx
+	.set	DATALEN32,	%edx
+	.set	GHASH_ACC_PTR,	%rcx	// Assumed to be %rcx.
 					// See .Ltail_xor_and_ghash_1to16bytes
-	.set	DST,		%r8
-	.set	DATALEN,	%r9d
-	.set	DATALEN64,	%r9	// Zero-extend DATALEN before using!
-
-	// Additional local variables
+	.set	BE_CTR_PTR,	%r8
+	.set	BE_CTR_PTR32,	%r8d
+	.set	KEY,		%r9
 
-	// %rax is used as a temporary register.  LE_CTR_PTR is also available
+	// %rax is used as a temporary register.  BE_CTR_PTR is also available
 	// as a temporary register after the counter is loaded.
 
 	// AES key length in bytes
@@ -730,8 +481,8 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 	.set	MI,		%ymm6
 	.set	MI_XMM,		%xmm6
 
-	// H_POW[2-1]_XORED contain cached values from KEY->h_powers_xored.  The
-	// descending numbering reflects the order of the key powers.
+	// H_POW[2-1]_XORED contain cached values from KEY->ghash.k.h_powers_xored.
+	// The descending numbering reflects the order of the key powers.
 	.set	H_POW2_XORED,	%ymm7
 	.set	H_POW2_XORED_XMM, %xmm7
 	.set	H_POW1_XORED,	%ymm8
@@ -761,7 +512,8 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 
 	// Load the GHASH accumulator and the starting counter.
 	vmovdqu		(GHASH_ACC_PTR), GHASH_ACC_XMM
-	vbroadcasti128	(LE_CTR_PTR), LE_CTR
+	vbroadcasti128	(BE_CTR_PTR), LE_CTR
+	vpshufb		BSWAP_MASK, LE_CTR, LE_CTR
 
 	// Load the AES key length in bytes.
 	movl		OFFSETOF_AESKEYLEN(KEY), AESKEYLEN
@@ -857,9 +609,9 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 
 	// Make POWERS_PTR point to the key powers [H^N, H^(N-1), ...] where N
 	// is the number of blocks that remain.
-	.set		POWERS_PTR, LE_CTR_PTR	// LE_CTR_PTR is free to be reused.
-	.set		POWERS_PTR32, LE_CTR_PTR32
-	mov		DATALEN, %eax
+	.set		POWERS_PTR, BE_CTR_PTR	// BE_CTR_PTR is free to be reused.
+	.set		POWERS_PTR32, BE_CTR_PTR32
+	mov		DATALEN32, %eax
 	neg		%rax
 	and		$~15, %rax  // -round_up(DATALEN, 16)
 	lea		OFFSETOFEND_H_POWERS(KEY,%rax), POWERS_PTR
@@ -924,7 +676,7 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 	// Load a vpshufb mask that will right-shift by '32 - DATALEN' bytes
 	// (shifting in zeroes), then reflect all 16 bytes.
 	lea		.Lrshift_and_bswap_table(%rip), %rax
-	vmovdqu		-16(%rax, DATALEN64), TMP2_XMM
+	vmovdqu		-16(%rax, DATALEN), TMP2_XMM
 
 	// Move the second keystream block to its own register and left-align it
 	vextracti128	$1, AESDATA0, AESDATA1_XMM
@@ -936,18 +688,18 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 	// input data: the full ciphertext block and the zero-padded partial
 	// ciphertext block, both byte-reflected, in AESDATA0.
 .if \enc
-	vpxor		-16(SRC, DATALEN64), AESDATA1_XMM, AESDATA1_XMM
+	vpxor		-16(SRC, DATALEN), AESDATA1_XMM, AESDATA1_XMM
 	vpxor		(SRC), AESDATA0_XMM, AESDATA0_XMM
-	vmovdqu		AESDATA1_XMM, -16(DST, DATALEN64)
+	vmovdqu		AESDATA1_XMM, -16(DST, DATALEN)
 	vmovdqu		AESDATA0_XMM, (DST)
 	vpshufb		TMP2_XMM, AESDATA1_XMM, AESDATA1_XMM
 	vpshufb		BSWAP_MASK_XMM, AESDATA0_XMM, AESDATA0_XMM
 .else
-	vmovdqu		-16(SRC, DATALEN64), TMP1_XMM
+	vmovdqu		-16(SRC, DATALEN), TMP1_XMM
 	vmovdqu		(SRC), TMP0_XMM
 	vpxor		TMP1_XMM, AESDATA1_XMM, AESDATA1_XMM
 	vpxor		TMP0_XMM, AESDATA0_XMM, AESDATA0_XMM
-	vmovdqu		AESDATA1_XMM, -16(DST, DATALEN64)
+	vmovdqu		AESDATA1_XMM, -16(DST, DATALEN)
 	vmovdqu		AESDATA0_XMM, (DST)
 	vpshufb		TMP2_XMM, TMP1_XMM, AESDATA1_XMM
 	vpshufb		BSWAP_MASK_XMM, TMP0_XMM, AESDATA0_XMM
@@ -961,16 +713,19 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 	// Handle 1 <= DATALEN <= 16.  Carefully load and store the
 	// possibly-partial block, which we mustn't access out of bounds.
 	vmovdqu		(POWERS_PTR), TMP2_XMM
-	mov		SRC, KEY	// Free up %rcx, assuming SRC == %rcx
-	mov		DATALEN, %ecx
-	_load_partial_block	KEY, TMP0_XMM, POWERS_PTR, POWERS_PTR32
+	// Free up %rcx (assuming GHASH_ACC_PTR == %rcx) by saving it in KEY,
+	// which is dead after this point; it is restored below.
+	mov		GHASH_ACC_PTR, KEY
+	mov		DATALEN32, %ecx
+	_load_partial_block	SRC, TMP0_XMM, POWERS_PTR, POWERS_PTR32
 	vpxor		TMP0_XMM, AESDATA0_XMM, AESDATA0_XMM
-	mov		DATALEN, %ecx
+	mov		DATALEN32, %ecx
 	_store_partial_block	AESDATA0_XMM, DST, POWERS_PTR, POWERS_PTR32
+	mov		KEY, GHASH_ACC_PTR
 .if \enc
 	lea		.Lselect_high_bytes_table(%rip), %rax
 	vpshufb		BSWAP_MASK_XMM, AESDATA0_XMM, AESDATA0_XMM
-	vpand		(%rax, DATALEN64), AESDATA0_XMM, AESDATA0_XMM
+	vpand		(%rax, DATALEN), AESDATA0_XMM, AESDATA0_XMM
 .else
 	vpshufb		BSWAP_MASK_XMM, TMP0_XMM, AESDATA0_XMM
 .endif
@@ -997,13 +752,16 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 	RET
 .endm
 
-// void aes_gcm_enc_final_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
-//				    const u32 le_ctr[4], u8 ghash_acc[16],
-//				    u64 total_aadlen, u64 total_datalen);
-// bool aes_gcm_dec_final_vaes_avx2(const struct aes_gcm_key_vaes_avx2 *key,
-//				    const u32 le_ctr[4], const u8 ghash_acc[16],
+// void aes_gcm_enc_final_vaes_avx2(const struct aes_gcm_key *key,
+//				    const u8 nonce[12],
+//				    const struct polyval_elem *ghash_acc,
 //				    u64 total_aadlen, u64 total_datalen,
-//				    const u8 tag[16], int taglen);
+//				    u8 *authtag);
+// bool aes_gcm_dec_final_vaes_avx2(const struct aes_gcm_key *key,
+//				    const u8 nonce[12],
+//				    const struct polyval_elem *ghash_acc,
+//				    u64 total_aadlen, u64 total_datalen,
+//				    const u8 *authtag);
 //
 // This macro generates one of the above two functions (with \enc selecting
 // which one).  Both functions finish computing the GCM authentication tag by
@@ -1011,44 +769,40 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 // |total_aadlen| and |total_datalen| must be the total length of the additional
 // authenticated data and the en/decrypted data in bytes, respectively.
 //
-// The encryption function then stores the full-length (16-byte) computed
-// authentication tag to |ghash_acc|.  The decryption function instead loads the
-// expected authentication tag (the one that was transmitted) from the 16-byte
-// buffer |tag|, compares the first 4 <= |taglen| <= 16 bytes of it to the
+// The encryption function then stores the computed authentication tag to
+// |authtag|.  The decryption function instead loads the expected authentication
+// tag (the one that was transmitted) from |authtag|, compares it to the
 // computed tag in constant time, and returns true if and only if they match.
+// In both cases the length of the tag is |key->authtag_len| bytes.
 .macro	_aes_gcm_final	enc
 
 	// Function arguments
 	.set	KEY,		%rdi
-	.set	LE_CTR_PTR,	%rsi
+	.set	NONCE_PTR,	%rsi
 	.set	GHASH_ACC_PTR,	%rdx
 	.set	TOTAL_AADLEN,	%rcx
 	.set	TOTAL_DATALEN,	%r8
 	.set	TAG,		%r9
-	.set	TAGLEN,		%r10d	// Originally at 8(%rsp)
-	.set	TAGLEN64,	%r10
 
 	// Additional local variables.
 	// %rax and %xmm0-%xmm3 are used as temporary registers.
+	.set	TAGLEN,		%r10d
+	.set	TAGLEN64,	%r10
 	.set	AESKEYLEN,	%r11d
 	.set	AESKEYLEN64,	%r11
 	.set	GFPOLY,		%xmm4
 	.set	BSWAP_MASK,	%xmm5
-	.set	LE_CTR,		%xmm6
-	.set	GHASH_ACC,	%xmm7
-	.set	H_POW1,		%xmm8
+	.set	GHASH_ACC,	%xmm6
+	.set	H_POW1,		%xmm7
 
 	// Load some constants.
 	vmovdqa		.Lgfpoly(%rip), GFPOLY
 	vmovdqa		.Lbswap_mask(%rip), BSWAP_MASK
 
-	// Load the AES key length in bytes.
+	// Load the AES key length and auth tag length in bytes.
+	// authtag_len is size_t with value in 4..16, so movl suffices here.
 	movl		OFFSETOF_AESKEYLEN(KEY), AESKEYLEN
-
-	// Set up a counter block with 1 in the low 32-bit word.  This is the
-	// counter that produces the ciphertext needed to encrypt the auth tag.
-	// GFPOLY has 1 in the low word, so grab the 1 from there using a blend.
-	vpblendd	$0xe, (LE_CTR_PTR), GFPOLY, LE_CTR
+	movl		OFFSETOF_AUTHTAG_LEN(KEY), TAGLEN
 
 	// Build the lengths block and XOR it with the GHASH accumulator.
 	// Although the lengths block is defined as the AAD length followed by
@@ -1064,17 +818,14 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 	// Load the first hash key power (H^1), which is stored last.
 	vmovdqu		OFFSETOFEND_H_POWERS-16(KEY), H_POW1
 
-	// Load TAGLEN if decrypting.
-.if !\enc
-	movl		8(%rsp), TAGLEN
-.endif
-
 	// Make %rax point to the last AES round key for the chosen AES variant.
 	lea		OFFSETOF_AESROUNDKEYS+6*16(KEY,AESKEYLEN64,4), %rax
 
-	// Start the AES encryption of the counter block by swapping the counter
-	// block to big-endian and XOR-ing it with the zero-th AES round key.
-	vpshufb		BSWAP_MASK, LE_CTR, %xmm0
+	// Build J_0 = nonce || be32(1) and XOR it with the zero-th AES round
+	// key to start the AES encryption of the counter block.
+	vmovq		(NONCE_PTR), %xmm0
+	vpinsrd		$2, 8(NONCE_PTR), %xmm0, %xmm0
+	vpinsrd		$3, .Lbe_one(%rip), %xmm0, %xmm0
 	vpxor		OFFSETOF_AESROUNDKEYS(KEY), %xmm0, %xmm0
 
 	// Complete the AES encryption and multiply GHASH_ACC by H^1.
@@ -1116,11 +867,29 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx2)
 .if \enc
 	vpxor		(%rax), GHASH_ACC, %xmm1
 	vaesenclast	%xmm1, %xmm0, GHASH_ACC
-	vmovdqu		GHASH_ACC, (GHASH_ACC_PTR)
+	cmp		$16, TAGLEN
+	jne		.Lstore_short_tag\@
+	vmovdqu		GHASH_ACC, (TAG)
+	RET
+.Lstore_short_tag\@:
+	mov		TAGLEN, %ecx
+	_store_partial_block GHASH_ACC, TAG, %r8, %r8d
 .else
+	cmp		$16, TAGLEN
+	jne		.Lverify_short_tag\@
 	vpxor		(TAG), GHASH_ACC, GHASH_ACC
 	vpxor		(%rax), GHASH_ACC, GHASH_ACC
 	vaesenclast	GHASH_ACC, %xmm0, %xmm0
+	xor		%eax, %eax
+	vptest		%xmm0, %xmm0
+	sete		%al
+	RET
+.Lverify_short_tag\@:
+	vpxor		(%rax), GHASH_ACC, GHASH_ACC
+	mov		TAGLEN, %ecx
+	_load_partial_block TAG, %xmm1, %r8, %r8d
+	vpxor		%xmm1, GHASH_ACC, GHASH_ACC
+	vaesenclast	GHASH_ACC, %xmm0, %xmm0
 	lea		.Lselect_high_bytes_table(%rip), %rax
 	vmovdqu		(%rax, TAGLEN64), %xmm1
 	vpshufb		BSWAP_MASK, %xmm1, %xmm1 // select low bytes, not high
diff --git a/lib/crypto/x86/aes.h b/lib/crypto/x86/aes.h
index 72222c2895a4f..97035b783ec4a 100644
--- a/lib/crypto/x86/aes.h
+++ b/lib/crypto/x86/aes.h
@@ -440,6 +440,14 @@ void aes_gcm_dec_update_aesni_avx(u8 *dst, const u8 *src, size_t len,
 				  struct polyval_elem *ghash_acc,
 				  const __be32 ctr32[4],
 				  const struct aes_gcm_key *key);
+void aes_gcm_enc_update_vaes_avx2(u8 *dst, const u8 *src, size_t len,
+				  struct polyval_elem *ghash_acc,
+				  const __be32 ctr32[4],
+				  const struct aes_gcm_key *key);
+void aes_gcm_dec_update_vaes_avx2(u8 *dst, const u8 *src, size_t len,
+				  struct polyval_elem *ghash_acc,
+				  const __be32 ctr32[4],
+				  const struct aes_gcm_key *key);
 
 void aes_gcm_enc_final_aesni(const struct aes_gcm_key *key, const u8 nonce[12],
 			     const struct polyval_elem *ghash_acc,
@@ -458,6 +466,16 @@ bool aes_gcm_dec_final_aesni_avx(const struct aes_gcm_key *key,
 				 const struct polyval_elem *ghash_acc,
 				 u64 total_aadlen, u64 total_datalen,
 				 const u8 *authtag);
+void aes_gcm_enc_final_vaes_avx2(const struct aes_gcm_key *key,
+				 const u8 nonce[12],
+				 const struct polyval_elem *ghash_acc,
+				 u64 total_aadlen, u64 total_datalen,
+				 u8 *authtag);
+bool aes_gcm_dec_final_vaes_avx2(const struct aes_gcm_key *key,
+				 const u8 nonce[12],
+				 const struct polyval_elem *ghash_acc,
+				 u64 total_aadlen, u64 total_datalen,
+				 const u8 *authtag);
 
 /*
  * En/decrypt and GHASH @len bytes inside an active FPU section.  @len must be
@@ -474,7 +492,14 @@ aes_gcm_update_x86_fpu(u8 *dst, const u8 *src, size_t len,
 
 		static_assert(GCM_CHUNK_SIZE % AES_BLOCK_SIZE == 0);
 
-		if (static_branch_likely(&have_aesni_avx)) {
+		if (static_branch_likely(&have_vaes_avx2)) {
+			if (enc)
+				aes_gcm_enc_update_vaes_avx2(
+					dst, src, n, ghash_acc, ctr32, key);
+			else
+				aes_gcm_dec_update_vaes_avx2(
+					dst, src, n, ghash_acc, ctr32, key);
+		} else if (static_branch_likely(&have_aesni_avx)) {
 			if (enc)
 				aes_gcm_enc_update_aesni_avx(
 					dst, src, n, ghash_acc, ctr32, key);
@@ -509,7 +534,7 @@ aes_gcm_crypt_update_x86(u8 *dst, const u8 *src, size_t len,
 	__be32 ctr[4];
 
 	if (!static_branch_likely(&have_aesni_pclmul) ||
-	    static_branch_likely(&have_vaes_avx2) ||
+	    static_branch_likely(&have_vaes_avx512) ||
 	    unlikely(!irq_fpu_usable()))
 		return false;
 
@@ -574,7 +599,7 @@ aes_gcm_crypt_x86(u8 *dst, const u8 *src, size_t data_len, u8 *authtag,
 	__be32 ctr32[4];
 
 	if (!static_branch_likely(&have_aesni_pclmul) ||
-	    static_branch_likely(&have_vaes_avx2) ||
+	    static_branch_likely(&have_vaes_avx512) ||
 	    unlikely(!irq_fpu_usable()))
 		return false;
 
@@ -591,7 +616,10 @@ aes_gcm_crypt_x86(u8 *dst, const u8 *src, size_t data_len, u8 *authtag,
 				       key, enc);
 
 	if (enc) {
-		if (static_branch_likely(&have_aesni_avx))
+		if (static_branch_likely(&have_vaes_avx2))
+			aes_gcm_enc_final_vaes_avx2(key, nonce, &ghash_acc,
+						    ad_len, data_len, authtag);
+		else if (static_branch_likely(&have_aesni_avx))
 			aes_gcm_enc_final_aesni_avx(key, nonce, &ghash_acc,
 						    ad_len, data_len, authtag);
 		else
@@ -600,7 +628,11 @@ aes_gcm_crypt_x86(u8 *dst, const u8 *src, size_t data_len, u8 *authtag,
 	} else {
 		bool valid;
 
-		if (static_branch_likely(&have_aesni_avx))
+		if (static_branch_likely(&have_vaes_avx2))
+			valid = aes_gcm_dec_final_vaes_avx2(key, nonce,
+							    &ghash_acc, ad_len,
+							    data_len, authtag);
+		else if (static_branch_likely(&have_aesni_avx))
 			valid = aes_gcm_dec_final_aesni_avx(key, nonce,
 							    &ghash_acc, ad_len,
 							    data_len, authtag);
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH 10/11] lib/crypto: x86/aes-gcm: Migrate VAES+AVX512 optimized code into library
  2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
                   ` (8 preceding siblings ...)
  2026-11-29 20:02 ` [PATCH 09/11] lib/crypto: x86/aes-gcm: Migrate VAES+AVX2 " Eric Biggers
@ 2026-11-29 20:02 ` Eric Biggers
  2026-11-29 20:02 ` [PATCH 11/11] crypto: x86/aesni-intel - Remove empty module Eric Biggers
  10 siblings, 0 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, Eric Biggers

Migrate aes-gcm-vaes-avx512.S into lib/crypto/, and wire it up to the
AES-GCM library functions.  Remove the superseded crypto_aead
implementations from aesni-intel_glue.c, leaving aesni-intel as an empty
module to be removed in the next commit.

This makes the AES-GCM library be optimized with VAES+AVX512, while the
same AES-GCM optimizations still remain accessible via crypto_aead via
gcm-aes-lib and rfc4106-gcm-aes-lib.  It's also simpler, since it
eliminates the crypto_aead boilerplate.

Some changes to the assembly code were required to match what the
library expects:

- Take 'struct aes_gcm_key' instead of 'struct aes_gcm_key_vaes_avx512'.

- Remove aes_gcm_precompute_vaes_avx512() and
  aes_gcm_aad_update_vaes_avx512().  The equivalent functionality is now
  handled in libgf128hash.

- aes_gcm_{enc,dec}_update_vaes_avx512():

    - Take the counter as big-endian instead of little-endian.

    - Widen datalen from int to size_t.

    - Reorder the arguments to match what the library hooks expect.

- Load and store the exact tag length in
  aes_gcm_{enc,dec}_final_vaes_avx512() using masked vmovdqu8, reading
  key->authtag_len from the key struct.

Note: the assembly code is in need of some further cleanups (such as
updating some names and comments, and further optimizations).  Those are
left for a later commit, as this one is already quite large.

Finally, now that all x86 AES-GCM implementations have been migrated
into the library, increase the priority of "gcm-aes-lib" and
"rfc4106-gcm-aes-lib" to 500 on x86 to match the other x86 AES modes.

Benchmark results on AMD Ryzen 9 9950X (Zen 5) using aes_gcm_kunit
(before = uncombined library AES-CTR + GHASH fallback):

    Length    Enc before   Enc after    Dec before   Dec after
    ------    ----------   ---------    ----------   ---------
        16      276 MB/s    465 MB/s      272 MB/s    614 MB/s
        64     1062 MB/s   1935 MB/s     1094 MB/s   2403 MB/s
       128     2116 MB/s   3866 MB/s     2121 MB/s   4948 MB/s
       256     4226 MB/s   7621 MB/s     4159 MB/s   8977 MB/s
       512     7342 MB/s  12609 MB/s     7849 MB/s  13496 MB/s
      1024    11717 MB/s  17542 MB/s    11675 MB/s  18838 MB/s
      1420    10548 MB/s  17082 MB/s    10360 MB/s  19754 MB/s
      4096    17896 MB/s  24722 MB/s    17626 MB/s  26789 MB/s
     16384    19560 MB/s  26937 MB/s    20104 MB/s  29057 MB/s

Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 arch/x86/crypto/Makefile                      |   3 +-
 arch/x86/crypto/aesni-intel_glue.c            | 548 ------------------
 crypto/aes.c                                  |   4 +-
 lib/crypto/Makefile                           |   3 +-
 .../crypto/x86}/aes-gcm-vaes-avx512.S         | 374 ++----------
 lib/crypto/x86/aes.h                          |  44 +-
 6 files changed, 100 insertions(+), 876 deletions(-)
 rename {arch/x86/crypto => lib/crypto/x86}/aes-gcm-vaes-avx512.S (74%)

diff --git a/arch/x86/crypto/Makefile b/arch/x86/crypto/Makefile
index b0e3660980f2f..7a443aa3ce4d7 100644
--- a/arch/x86/crypto/Makefile
+++ b/arch/x86/crypto/Makefile
@@ -40,8 +40,7 @@ obj-$(CONFIG_CRYPTO_AEGIS128_AESNI_SSE2) += aegis128-aesni.o
 aegis128-aesni-y := aegis128-aesni-asm.o aegis128-aesni-glue.o
 
 obj-$(CONFIG_CRYPTO_AES_NI_INTEL) += aesni-intel.o
-aesni-intel-y := aesni-intel_glue.o \
-		 aes-gcm-vaes-avx512.o
+aesni-intel-y := aesni-intel_glue.o
 
 obj-$(CONFIG_CRYPTO_SM4_AESNI_AVX_X86_64) += sm4-aesni-avx-x86_64.o
 sm4-aesni-avx-x86_64-y := sm4-aesni-avx-asm_64.o sm4_aesni_avx_glue.o
diff --git a/arch/x86/crypto/aesni-intel_glue.c b/arch/x86/crypto/aesni-intel_glue.c
index 8d969dfa8f896..93718bb95092a 100644
--- a/arch/x86/crypto/aesni-intel_glue.c
+++ b/arch/x86/crypto/aesni-intel_glue.c
@@ -17,544 +17,9 @@
  * Copyright 2024 Google LLC
  */
 
-#include <linux/hardirq.h>
-#include <linux/types.h>
 #include <linux/module.h>
 #include <linux/err.h>
-#include <crypto/algapi.h>
-#include <crypto/aes.h>
-#include <crypto/b128ops.h>
-#include <crypto/gcm.h>
-#include <crypto/gf128mul.h>
 #include <asm/cpu_device_id.h>
-#include <asm/simd.h>
-#include <crypto/scatterwalk.h>
-#include <crypto/internal/aead.h>
-#include <crypto/internal/simd.h>
-#include <crypto/internal/skcipher.h>
-#include <linux/jump_label.h>
-#include <linux/workqueue.h>
-#include <linux/spinlock.h>
-#include <linux/static_call.h>
-
-/* The common part of the x86_64 AES-GCM key struct */
-struct aes_gcm_key {
-	/* Expanded AES key and the AES key length in bytes */
-	struct aes_enckey aes_key;
-
-	/* RFC4106 nonce (used only by the rfc4106 algorithms) */
-	u32 rfc4106_nonce;
-};
-
-/* Key struct used by the VAES + AVX512 implementation of AES-GCM */
-struct aes_gcm_key_vaes_avx512 {
-	/*
-	 * Common part of the key.  The assembly code prefers 16-byte alignment
-	 * for this.
-	 */
-	struct aes_gcm_key base __aligned(16);
-
-	/*
-	 * Powers of the hash key H^16 through H^1.  These are 128-bit values.
-	 * They all have an extra factor of x^-1 and are byte-reversed.  This
-	 * array is aligned to a 64-byte boundary to make it naturally aligned
-	 * for 512-bit loads, which can improve performance.  (The assembly code
-	 * doesn't *need* the alignment; this is just an optimization.)
-	 */
-	u64 h_powers[16][2] __aligned(64);
-
-	/* Three padding blocks required by the assembly code */
-	u64 padding[3][2];
-};
-#define AES_GCM_KEY_VAES_AVX512(key) \
-	container_of((key), struct aes_gcm_key_vaes_avx512, base)
-#define AES_GCM_KEY_VAES_AVX512_SIZE \
-	(sizeof(struct aes_gcm_key_vaes_avx512) + (63 & ~(CRYPTO_MINALIGN - 1)))
-
-/*
- * These flags are passed to the AES-GCM helper functions to specify the
- * specific version of AES-GCM (RFC4106 or not), whether it's encryption or
- * decryption, and which assembly functions should be called.  Assembly
- * functions are selected using flags instead of function pointers to avoid
- * indirect calls (which are very expensive on x86) regardless of inlining.
- */
-#define FLAG_RFC4106	BIT(0)
-#define FLAG_ENC	BIT(1)
-#define FLAG_VAES_AVX512 BIT(4)
-
-static inline struct aes_gcm_key *
-aes_gcm_key_get(struct crypto_aead *tfm, int flags)
-{
-	return PTR_ALIGN(crypto_aead_ctx(tfm), 64);
-}
-
-asmlinkage void
-aes_gcm_precompute_vaes_avx512(struct aes_gcm_key_vaes_avx512 *key);
-
-static void aes_gcm_precompute(struct aes_gcm_key *key, int flags)
-{
-	aes_gcm_precompute_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key));
-}
-asmlinkage void
-aes_gcm_aad_update_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
-			       u8 ghash_acc[16], const u8 *aad, int aadlen);
-
-static void aes_gcm_aad_update(const struct aes_gcm_key *key, u8 ghash_acc[16],
-			       const u8 *aad, int aadlen, int flags)
-{
-	aes_gcm_aad_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key), ghash_acc,
-				       aad, aadlen);
-}
-asmlinkage void
-aes_gcm_enc_update_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
-			       const u32 le_ctr[4], u8 ghash_acc[16],
-			       const u8 *src, u8 *dst, int datalen);
-
-asmlinkage void
-aes_gcm_dec_update_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
-			       const u32 le_ctr[4], u8 ghash_acc[16],
-			       const u8 *src, u8 *dst, int datalen);
-
-/* __always_inline to optimize out the branches based on @flags */
-static __always_inline void
-aes_gcm_update(const struct aes_gcm_key *key,
-	       const u32 le_ctr[4], u8 ghash_acc[16],
-	       const u8 *src, u8 *dst, int datalen, int flags)
-{
-	if (flags & FLAG_ENC) {
-		aes_gcm_enc_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
-					       le_ctr, ghash_acc, src, dst,
-					       datalen);
-	} else {
-		aes_gcm_dec_update_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
-					       le_ctr, ghash_acc, src, dst,
-					       datalen);
-	}
-}
-
-asmlinkage void
-aes_gcm_enc_final_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
-			      const u32 le_ctr[4], u8 ghash_acc[16],
-			      u64 total_aadlen, u64 total_datalen);
-
-/* __always_inline to optimize out the branches based on @flags */
-static __always_inline void
-aes_gcm_enc_final(const struct aes_gcm_key *key,
-		  const u32 le_ctr[4], u8 ghash_acc[16],
-		  u64 total_aadlen, u64 total_datalen, int flags)
-{
-	aes_gcm_enc_final_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key), le_ctr,
-				      ghash_acc, total_aadlen, total_datalen);
-}
-asmlinkage bool __must_check
-aes_gcm_dec_final_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
-			      const u32 le_ctr[4], const u8 ghash_acc[16],
-			      u64 total_aadlen, u64 total_datalen,
-			      const u8 tag[16], int taglen);
-
-/* __always_inline to optimize out the branches based on @flags */
-static __always_inline bool __must_check
-aes_gcm_dec_final(const struct aes_gcm_key *key, const u32 le_ctr[4],
-		  u8 ghash_acc[16], u64 total_aadlen, u64 total_datalen,
-		  u8 tag[16], int taglen, int flags)
-{
-	return aes_gcm_dec_final_vaes_avx512(AES_GCM_KEY_VAES_AVX512(key),
-					     le_ctr, ghash_acc, total_aadlen,
-					     total_datalen, tag, taglen);
-}
-
-/*
- * This is the Integrity Check Value (aka the authentication tag) length and can
- * be 8, 12 or 16 bytes long.
- */
-static int common_rfc4106_set_authsize(struct crypto_aead *aead,
-				       unsigned int authsize)
-{
-	switch (authsize) {
-	case 8:
-	case 12:
-	case 16:
-		break;
-	default:
-		return -EINVAL;
-	}
-
-	return 0;
-}
-
-static int generic_gcmaes_set_authsize(struct crypto_aead *tfm,
-				       unsigned int authsize)
-{
-	switch (authsize) {
-	case 4:
-	case 8:
-	case 12:
-	case 13:
-	case 14:
-	case 15:
-	case 16:
-		break;
-	default:
-		return -EINVAL;
-	}
-
-	return 0;
-}
-
-/*
- * This is the setkey function for the x86_64 implementations of AES-GCM.  It
- * saves the RFC4106 nonce if applicable, expands the AES key, and precomputes
- * powers of the hash key.
- *
- * To comply with the crypto_aead API, this has to be usable in no-SIMD context.
- * For that reason, this function includes a portable C implementation of the
- * needed logic.  However, the portable C implementation is very slow, taking
- * about the same time as encrypting 37 KB of data.  To be ready for users that
- * may set a key even somewhat frequently, we therefore also include a SIMD
- * assembly implementation, expanding the AES key using AES-NI and precomputing
- * the hash key powers using PCLMULQDQ or VPCLMULQDQ.
- */
-static int gcm_setkey(struct crypto_aead *tfm, const u8 *raw_key,
-		      unsigned int keylen, int flags)
-{
-	struct aes_gcm_key *key = aes_gcm_key_get(tfm, flags);
-	int err;
-
-	if (flags & FLAG_RFC4106) {
-		if (keylen < 4)
-			return -EINVAL;
-		keylen -= 4;
-		key->rfc4106_nonce = get_unaligned_be32(raw_key + keylen);
-	}
-
-	/* The assembly code assumes the following offsets. */
-	static_assert(offsetof(struct aes_gcm_key_vaes_avx512, base.aes_key.len) == 0);
-	static_assert(offsetof(struct aes_gcm_key_vaes_avx512, base.aes_key.k.rndkeys) == 16);
-	static_assert(offsetof(struct aes_gcm_key_vaes_avx512, h_powers) == 320);
-	static_assert(offsetof(struct aes_gcm_key_vaes_avx512, padding) == 576);
-
-	err = aes_prepareenckey(&key->aes_key, raw_key, keylen);
-	if (err)
-		return err;
-
-	if (likely(crypto_simd_usable())) {
-		kernel_fpu_begin_mask(0);
-		aes_gcm_precompute(key, flags);
-		kernel_fpu_end();
-	} else {
-		static const u8 x_to_the_minus1[16] __aligned(__alignof__(be128)) = {
-			[0] = 0xc2, [15] = 1
-		};
-		be128 h1 = {};
-		be128 h;
-		int i;
-
-		/* Encrypt the all-zeroes block to get the hash key H^1 */
-		aes_encrypt(&key->aes_key, (u8 *)&h1, (u8 *)&h1);
-
-		/* Compute H^1 * x^-1 */
-		h = h1;
-		gf128mul_lle(&h, (const be128 *)x_to_the_minus1);
-
-		/* Compute the needed key powers */
-		struct aes_gcm_key_vaes_avx512 *k =
-			AES_GCM_KEY_VAES_AVX512(key);
-
-		for (i = ARRAY_SIZE(k->h_powers) - 1; i >= 0; i--) {
-			k->h_powers[i][0] = be64_to_cpu(h.b);
-			k->h_powers[i][1] = be64_to_cpu(h.a);
-			gf128mul_lle(&h, &h1);
-		}
-		memset(k->padding, 0, sizeof(k->padding));
-	}
-	return 0;
-}
-
-/*
- * Initialize @ghash_acc, then pass all @assoclen bytes of associated data
- * (a.k.a. additional authenticated data) from @sg_src through the GHASH update
- * assembly function.  The caller must be in a kernel-mode FPU section.
- */
-static void gcm_process_assoc(const struct aes_gcm_key *key, u8 ghash_acc[16],
-			      struct scatterlist *sg_src, unsigned int assoclen,
-			      int flags)
-{
-	struct scatter_walk walk;
-	/*
-	 * The assembly function requires that the length of any non-last
-	 * segment of associated data be a multiple of 16 bytes, so this
-	 * function does the buffering needed to achieve that.
-	 */
-	unsigned int pos = 0;
-	u8 buf[16];
-
-	memset(ghash_acc, 0, 16);
-	scatterwalk_start(&walk, sg_src);
-
-	while (assoclen) {
-		unsigned int orig_len_this_step = scatterwalk_next(
-			&walk, assoclen);
-		unsigned int len_this_step = orig_len_this_step;
-		unsigned int len;
-		const u8 *src = walk.addr;
-
-		assoclen -= orig_len_this_step;
-		if (unlikely(pos)) {
-			len = min(len_this_step, 16 - pos);
-			memcpy(&buf[pos], src, len);
-			pos += len;
-			src += len;
-			len_this_step -= len;
-			if (pos < 16)
-				goto next;
-			aes_gcm_aad_update(key, ghash_acc, buf, 16, flags);
-			pos = 0;
-		}
-		len = len_this_step;
-		if (unlikely(assoclen)) /* Not the last segment yet? */
-			len = round_down(len, 16);
-		aes_gcm_aad_update(key, ghash_acc, src, len, flags);
-		src += len;
-		len_this_step -= len;
-		if (unlikely(len_this_step)) {
-			memcpy(buf, src, len_this_step);
-			pos = len_this_step;
-		}
-next:
-		scatterwalk_done_src(&walk, orig_len_this_step);
-		if (need_resched()) {
-			kernel_fpu_end();
-			kernel_fpu_begin_mask(0);
-		}
-	}
-	if (unlikely(pos))
-		aes_gcm_aad_update(key, ghash_acc, buf, pos, flags);
-}
-
-
-/* __always_inline to optimize out the branches based on @flags */
-static __always_inline int
-gcm_crypt(struct aead_request *req, int flags)
-{
-	struct crypto_aead *tfm = crypto_aead_reqtfm(req);
-	const struct aes_gcm_key *key = aes_gcm_key_get(tfm, flags);
-	unsigned int assoclen = req->assoclen;
-	struct skcipher_walk walk;
-	unsigned int nbytes;
-	u8 ghash_acc[16]; /* GHASH accumulator */
-	u32 le_ctr[4]; /* Counter in little-endian format */
-	int taglen;
-	int err;
-
-	/* Initialize the counter and determine the associated data length. */
-	le_ctr[0] = 2;
-	if (flags & FLAG_RFC4106) {
-		if (unlikely(assoclen != 16 && assoclen != 20))
-			return -EINVAL;
-		assoclen -= 8;
-		le_ctr[1] = get_unaligned_be32(req->iv + 4);
-		le_ctr[2] = get_unaligned_be32(req->iv + 0);
-		le_ctr[3] = key->rfc4106_nonce; /* already byte-swapped */
-	} else {
-		le_ctr[1] = get_unaligned_be32(req->iv + 8);
-		le_ctr[2] = get_unaligned_be32(req->iv + 4);
-		le_ctr[3] = get_unaligned_be32(req->iv + 0);
-	}
-
-	/* Begin walking through the plaintext or ciphertext. */
-	if (flags & FLAG_ENC)
-		err = skcipher_walk_aead_encrypt(&walk, req, false);
-	else
-		err = skcipher_walk_aead_decrypt(&walk, req, false);
-	if (err)
-		return err;
-
-	/*
-	 * Since the AES-GCM assembly code requires that at least three assembly
-	 * functions be called to process any message (this is needed to support
-	 * incremental updates cleanly), to reduce overhead we try to do all
-	 * three calls in the same kernel FPU section if possible.  We close the
-	 * section and start a new one if there are multiple data segments or if
-	 * rescheduling is needed while processing the associated data.
-	 */
-	kernel_fpu_begin_mask(0);
-
-	/* Pass the associated data through GHASH. */
-	gcm_process_assoc(key, ghash_acc, req->src, assoclen, flags);
-
-	/* En/decrypt the data and pass the ciphertext through GHASH. */
-	while (unlikely((nbytes = walk.nbytes) < walk.total)) {
-		/*
-		 * Non-last segment.  In this case, the assembly function
-		 * requires that the length be a multiple of 16 (AES_BLOCK_SIZE)
-		 * bytes.  The needed buffering of up to 16 bytes is handled by
-		 * the skcipher_walk.  Here we just need to round down to a
-		 * multiple of 16.
-		 */
-		nbytes = round_down(nbytes, AES_BLOCK_SIZE);
-		aes_gcm_update(key, le_ctr, ghash_acc, walk.src.virt.addr,
-			       walk.dst.virt.addr, nbytes, flags);
-		le_ctr[0] += nbytes / AES_BLOCK_SIZE;
-		kernel_fpu_end();
-		err = skcipher_walk_done(&walk, walk.nbytes - nbytes);
-		if (err)
-			return err;
-		kernel_fpu_begin_mask(0);
-	}
-	/* Last segment: process all remaining data. */
-	aes_gcm_update(key, le_ctr, ghash_acc, walk.src.virt.addr,
-		       walk.dst.virt.addr, nbytes, flags);
-	/*
-	 * The low word of the counter isn't used by the finalize, so there's no
-	 * need to increment it here.
-	 */
-
-	/* Finalize */
-	taglen = crypto_aead_authsize(tfm);
-	if (flags & FLAG_ENC) {
-		/* Finish computing the auth tag. */
-		aes_gcm_enc_final(key, le_ctr, ghash_acc, assoclen,
-				  req->cryptlen, flags);
-
-		/* Store the computed auth tag in the dst scatterlist. */
-		scatterwalk_map_and_copy(ghash_acc, req->dst, req->assoclen +
-					 req->cryptlen, taglen, 1);
-	} else {
-		unsigned int datalen = req->cryptlen - taglen;
-		u8 tag[16];
-
-		/* Get the transmitted auth tag from the src scatterlist. */
-		scatterwalk_map_and_copy(tag, req->src, req->assoclen + datalen,
-					 taglen, 0);
-		/*
-		 * Finish computing the auth tag and compare it to the
-		 * transmitted one.  The assembly function does the actual tag
-		 * comparison.  Here, just check the boolean result.
-		 */
-		if (!aes_gcm_dec_final(key, le_ctr, ghash_acc, assoclen,
-				       datalen, tag, taglen, flags))
-			err = -EBADMSG;
-	}
-	kernel_fpu_end();
-	if (nbytes)
-		skcipher_walk_done(&walk, 0);
-	return err;
-}
-
-#define DEFINE_GCM_ALGS(suffix, flags, generic_driver_name, rfc_driver_name,   \
-			ctxsize, priority)				       \
-									       \
-static int gcm_setkey_##suffix(struct crypto_aead *tfm, const u8 *raw_key,     \
-			       unsigned int keylen)			       \
-{									       \
-	return gcm_setkey(tfm, raw_key, keylen, (flags));		       \
-}									       \
-									       \
-static int gcm_encrypt_##suffix(struct aead_request *req)		       \
-{									       \
-	return gcm_crypt(req, (flags) | FLAG_ENC);			       \
-}									       \
-									       \
-static int gcm_decrypt_##suffix(struct aead_request *req)		       \
-{									       \
-	return gcm_crypt(req, (flags));					       \
-}									       \
-									       \
-static int rfc4106_setkey_##suffix(struct crypto_aead *tfm, const u8 *raw_key, \
-				   unsigned int keylen)			       \
-{									       \
-	return gcm_setkey(tfm, raw_key, keylen, (flags) | FLAG_RFC4106);       \
-}									       \
-									       \
-static int rfc4106_encrypt_##suffix(struct aead_request *req)		       \
-{									       \
-	return gcm_crypt(req, (flags) | FLAG_RFC4106 | FLAG_ENC);	       \
-}									       \
-									       \
-static int rfc4106_decrypt_##suffix(struct aead_request *req)		       \
-{									       \
-	return gcm_crypt(req, (flags) | FLAG_RFC4106);			       \
-}									       \
-									       \
-static struct aead_alg aes_gcm_algs_##suffix[] = { {			       \
-	.setkey			= gcm_setkey_##suffix,			       \
-	.setauthsize		= generic_gcmaes_set_authsize,		       \
-	.encrypt		= gcm_encrypt_##suffix,			       \
-	.decrypt		= gcm_decrypt_##suffix,			       \
-	.ivsize			= GCM_AES_IV_SIZE,			       \
-	.chunksize		= AES_BLOCK_SIZE,			       \
-	.maxauthsize		= 16,					       \
-	.base = {							       \
-		.cra_name		= "gcm(aes)",			       \
-		.cra_driver_name	= generic_driver_name,		       \
-		.cra_priority		= (priority),			       \
-		.cra_blocksize		= 1,				       \
-		.cra_ctxsize		= (ctxsize),			       \
-		.cra_module		= THIS_MODULE,			       \
-	},								       \
-}, {									       \
-	.setkey			= rfc4106_setkey_##suffix,		       \
-	.setauthsize		= common_rfc4106_set_authsize,		       \
-	.encrypt		= rfc4106_encrypt_##suffix,		       \
-	.decrypt		= rfc4106_decrypt_##suffix,		       \
-	.ivsize			= GCM_RFC4106_IV_SIZE,			       \
-	.chunksize		= AES_BLOCK_SIZE,			       \
-	.maxauthsize		= 16,					       \
-	.base = {							       \
-		.cra_name		= "rfc4106(gcm(aes))",		       \
-		.cra_driver_name	= rfc_driver_name,		       \
-		.cra_priority		= (priority),			       \
-		.cra_blocksize		= 1,				       \
-		.cra_ctxsize		= (ctxsize),			       \
-		.cra_module		= THIS_MODULE,			       \
-	},								       \
-} }
-
-/* aes_gcm_algs_vaes_avx512 */
-DEFINE_GCM_ALGS(vaes_avx512, FLAG_VAES_AVX512,
-		"generic-gcm-vaes-avx512", "rfc4106-gcm-vaes-avx512",
-		AES_GCM_KEY_VAES_AVX512_SIZE, 800);
-
-static int __init register_avx_algs(void)
-{
-	if (!boot_cpu_has(X86_FEATURE_AVX))
-		return 0;
-	/*
-	 * Note: not all the algorithms registered below actually require
-	 * VPCLMULQDQ.  But in practice every CPU with VAES also has VPCLMULQDQ.
-	 * Similarly, the assembler support was added at about the same time.
-	 * For simplicity, just always check for VAES and VPCLMULQDQ together.
-	 */
-	if (!boot_cpu_has(X86_FEATURE_AVX2) ||
-	    !boot_cpu_has(X86_FEATURE_VAES) ||
-	    !boot_cpu_has(X86_FEATURE_VPCLMULQDQ) ||
-	    !boot_cpu_has(X86_FEATURE_PCLMULQDQ))
-		return 0;
-
-	if (!boot_cpu_has(X86_FEATURE_AVX512BW) ||
-	    !boot_cpu_has(X86_FEATURE_AVX512VL) ||
-	    !boot_cpu_has(X86_FEATURE_BMI2))
-		return 0;
-
-	if (boot_cpu_has(X86_FEATURE_PREFER_YMM)) {
-		int i;
-
-		for (i = 0; i < ARRAY_SIZE(aes_gcm_algs_vaes_avx512); i++)
-			aes_gcm_algs_vaes_avx512[i].base.cra_priority = 1;
-	}
-
-	return crypto_register_aeads(aes_gcm_algs_vaes_avx512,
-				     ARRAY_SIZE(aes_gcm_algs_vaes_avx512));
-}
-
-#define unregister_aeads(A) \
-	if (refcount_read(&(A)[0].base.cra_refcnt) != 0) \
-		crypto_unregister_aeads((A), ARRAY_SIZE(A))
-
-static void unregister_avx_algs(void)
-{
-	unregister_aeads(aes_gcm_algs_vaes_avx512);
-}
 
 static const struct x86_cpu_id aesni_cpu_id[] = {
 	X86_MATCH_FEATURE(X86_FEATURE_AES, NULL),
@@ -564,25 +29,14 @@ MODULE_DEVICE_TABLE(x86cpu, aesni_cpu_id);
 
 static int __init aesni_init(void)
 {
-	int err;
-
 	if (!x86_match_cpu(aesni_cpu_id))
 		return -ENODEV;
 
-	err = register_avx_algs();
-	if (err)
-		goto unregister_avx;
-
 	return 0;
-
-unregister_avx:
-	unregister_avx_algs();
-	return err;
 }
 
 static void __exit aesni_exit(void)
 {
-	unregister_avx_algs();
 }
 
 module_init(aesni_init);
@@ -590,5 +44,3 @@ module_exit(aesni_exit);
 
 MODULE_DESCRIPTION("AES-GCM, optimized with AES-NI or VAES instructions");
 MODULE_LICENSE("GPL");
-MODULE_ALIAS_CRYPTO("gcm(aes)");
-MODULE_ALIAS_CRYPTO("rfc4106(gcm(aes))");
diff --git a/crypto/aes.c b/crypto/aes.c
index e360756385cdf..08ac2faa6cb71 100644
--- a/crypto/aes.c
+++ b/crypto/aes.c
@@ -1208,7 +1208,7 @@ static struct aead_alg aead_algs[] = {
 	{
 		.base.cra_name = "gcm(aes)",
 		.base.cra_driver_name = "gcm-aes-lib",
-		.base.cra_priority = 110,
+		.base.cra_priority = IS_ENABLED(CONFIG_X86) ? 500 : 110,
 		.base.cra_blocksize = 1,
 		.base.cra_ctxsize = sizeof(struct aes_gcm_key),
 		.base.cra_module = THIS_MODULE,
@@ -1223,7 +1223,7 @@ static struct aead_alg aead_algs[] = {
 	{
 		.base.cra_name = "rfc4106(gcm(aes))",
 		.base.cra_driver_name = "rfc4106-gcm-aes-lib",
-		.base.cra_priority = 110,
+		.base.cra_priority = IS_ENABLED(CONFIG_X86) ? 500 : 110,
 		.base.cra_blocksize = 1,
 		.base.cra_ctxsize = sizeof(struct aes_rfc4106_key),
 		.base.cra_module = THIS_MODULE,
diff --git a/lib/crypto/Makefile b/lib/crypto/Makefile
index 6e2d264f12492..ccd702f58f3d6 100644
--- a/lib/crypto/Makefile
+++ b/lib/crypto/Makefile
@@ -97,7 +97,8 @@ libaes-$(CONFIG_X86_64) += x86/aes-ctr-avx-x86_64.o
 endif
 ifneq ($(CONFIG_CRYPTO_LIB_AES_GCM),)
 libaes-$(CONFIG_X86_64) += x86/aes-gcm-aesni-x86_64.o \
-			   x86/aes-gcm-vaes-avx2.o
+			   x86/aes-gcm-vaes-avx2.o \
+			   x86/aes-gcm-vaes-avx512.o
 endif
 ifneq ($(CONFIG_CRYPTO_LIB_AES_XTS),)
 libaes-$(CONFIG_X86_64) += x86/aes-xts-avx-x86_64.o
diff --git a/arch/x86/crypto/aes-gcm-vaes-avx512.S b/lib/crypto/x86/aes-gcm-vaes-avx512.S
similarity index 74%
rename from arch/x86/crypto/aes-gcm-vaes-avx512.S
rename to lib/crypto/x86/aes-gcm-vaes-avx512.S
index 516747db46592..70b9adc02b41c 100644
--- a/arch/x86/crypto/aes-gcm-vaes-avx512.S
+++ b/lib/crypto/x86/aes-gcm-vaes-avx512.S
@@ -66,10 +66,6 @@
 .Lgfpoly:
 	.octa	0xc2000000000000000000000000000001
 
-	// Same as above, but with the (1 << 64) bit set.
-.Lgfpoly_and_internal_carrybit:
-	.octa	0xc2000000000000010000000000000001
-
 	// Values needed to prepare the initial vector of counter blocks.
 .Lctr_pattern:
 	.octa	0
@@ -81,6 +77,10 @@
 .Linc_4blocks:
 	.octa	4
 
+	// Big-endian 1, for constructing J_0 = nonce || be32(1).
+.Lbe_one:
+	.long	0x01000000
+
 // Number of powers of the hash key stored in the key struct.  The powers are
 // stored from highest (H^NUM_H_POWERS) to lowest (H^1).
 #define NUM_H_POWERS		16
@@ -92,7 +92,7 @@
 #define OFFSETOF_AESROUNDKEYS	16
 
 // Offset to start of hash key powers array in the key struct
-#define OFFSETOF_H_POWERS	320
+#define OFFSETOF_H_POWERS	256
 
 // Offset to end of hash key powers array in the key struct.
 //
@@ -101,6 +101,7 @@
 // blocks remain, we load the 4 values [H^2, H^1, 0, 0].  The most padding
 // blocks needed is 3, which occurs if [H^1, 0, 0, 0] is loaded.
 #define OFFSETOFEND_H_POWERS	(OFFSETOF_H_POWERS + (NUM_H_POWERS * 16))
+#define OFFSETOF_AUTHTAG_LEN	(OFFSETOF_H_POWERS + 320)
 
 .text
 
@@ -232,14 +233,6 @@
 .endif
 .endm
 
-// GHASH-multiply the 128-bit lanes of \a by the 128-bit lanes of \b and store
-// the reduced products in \dst.  See _ghash_mul_step for full explanation.
-.macro	_ghash_mul	a, b, dst, gfpoly, t0, t1, t2
-.irp i, 0,1,2,3,4,5,6,7,8,9
-	_ghash_mul_step	\i, \a, \b, \dst, \gfpoly, \t0, \t1, \t2
-.endr
-.endm
-
 // GHASH-multiply the 128-bit lanes of \a by the 128-bit lanes of \b and add the
 // *unreduced* products to \lo, \mi, and \hi.
 .macro	_ghash_mul_noreduce	a, b, lo, mi, hi, t0, t1, t2, t3
@@ -263,126 +256,6 @@
 	vpternlogd	$0x96, \t0, \mi, \hi
 .endm
 
-// This is a specialized version of _ghash_mul that computes \a * \a, i.e. it
-// squares \a.  It skips computing MI = (a_L * a_H) + (a_H * a_L) = 0.
-.macro	_ghash_square	a, dst, gfpoly, t0, t1
-	vpclmulqdq	$0x00, \a, \a, \t0	  // LO = a_L * a_L
-	vpclmulqdq	$0x11, \a, \a, \dst	  // HI = a_H * a_H
-	vpclmulqdq	$0x01, \t0, \gfpoly, \t1  // LO_L*(x^63 + x^62 + x^57)
-	vpshufd		$0x4e, \t0, \t0		  // Swap halves of LO
-	vpxord		\t0, \t1, \t1		  // Fold LO into MI
-	vpclmulqdq	$0x01, \t1, \gfpoly, \t0  // MI_L*(x^63 + x^62 + x^57)
-	vpshufd		$0x4e, \t1, \t1		  // Swap halves of MI
-	vpternlogd	$0x96, \t0, \t1, \dst	  // Fold MI into HI
-.endm
-
-// void aes_gcm_precompute_vaes_avx512(struct aes_gcm_key_vaes_avx512 *key);
-//
-// Given the expanded AES key |key->base.aes_key|, derive the GHASH subkey and
-// initialize |key->h_powers| and |key->padding|.
-SYM_FUNC_START(aes_gcm_precompute_vaes_avx512)
-
-	// Function arguments
-	.set	KEY,		%rdi
-
-	// Additional local variables.
-	// %zmm[0-2] and %rax are used as temporaries.
-	.set	POWERS_PTR,	%rsi
-	.set	RNDKEYLAST_PTR,	%rdx
-	.set	H_CUR,		%zmm3
-	.set	H_CUR_YMM,	%ymm3
-	.set	H_CUR_XMM,	%xmm3
-	.set	H_INC,		%zmm4
-	.set	H_INC_YMM,	%ymm4
-	.set	H_INC_XMM,	%xmm4
-	.set	GFPOLY,		%zmm5
-	.set	GFPOLY_YMM,	%ymm5
-	.set	GFPOLY_XMM,	%xmm5
-
-	// Get pointer to lowest set of key powers (located at end of array).
-	lea		OFFSETOFEND_H_POWERS-64(KEY), POWERS_PTR
-
-	// Encrypt an all-zeroes block to get the raw hash subkey.
-	movl		OFFSETOF_AESKEYLEN(KEY), %eax
-	lea		OFFSETOF_AESROUNDKEYS+6*16(KEY,%rax,4), RNDKEYLAST_PTR
-	vmovdqu		OFFSETOF_AESROUNDKEYS(KEY), %xmm0
-	add		$OFFSETOF_AESROUNDKEYS+16, KEY
-1:
-	vaesenc		(KEY), %xmm0, %xmm0
-	add		$16, KEY
-	cmp		KEY, RNDKEYLAST_PTR
-	jne		1b
-	vaesenclast	(RNDKEYLAST_PTR), %xmm0, %xmm0
-
-	// Reflect the bytes of the raw hash subkey.
-	vpshufb		.Lbswap_mask(%rip), %xmm0, H_CUR_XMM
-
-	// Zeroize the padding blocks.
-	vpxor		%xmm0, %xmm0, %xmm0
-	vmovdqu		%ymm0, 64(POWERS_PTR)
-	vmovdqu		%xmm0, 64+2*16(POWERS_PTR)
-
-	// Finish preprocessing the first key power, H^1.  Since this GHASH
-	// implementation operates directly on values with the backwards bit
-	// order specified by the GCM standard, it's necessary to preprocess the
-	// raw key as follows.  First, reflect its bytes.  Second, multiply it
-	// by x^-1 mod x^128 + x^7 + x^2 + x + 1 (if using the backwards
-	// interpretation of polynomial coefficients), which can also be
-	// interpreted as multiplication by x mod x^128 + x^127 + x^126 + x^121
-	// + 1 using the alternative, natural interpretation of polynomial
-	// coefficients.  For details, see the comment above _ghash_mul_step.
-	//
-	// Either way, for the multiplication the concrete operation performed
-	// is a left shift of the 128-bit value by 1 bit, then an XOR with (0xc2
-	// << 120) | 1 if a 1 bit was carried out.  However, there's no 128-bit
-	// wide shift instruction, so instead double each of the two 64-bit
-	// halves and incorporate the internal carry bit into the value XOR'd.
-	vpshufd		$0xd3, H_CUR_XMM, %xmm0
-	vpsrad		$31, %xmm0, %xmm0
-	vpaddq		H_CUR_XMM, H_CUR_XMM, H_CUR_XMM
-	// H_CUR_XMM ^= xmm0 & gfpoly_and_internal_carrybit
-	vpternlogd	$0x78, .Lgfpoly_and_internal_carrybit(%rip), %xmm0, H_CUR_XMM
-
-	// Load the gfpoly constant.
-	vbroadcasti32x4	.Lgfpoly(%rip), GFPOLY
-
-	// Square H^1 to get H^2.
-	//
-	// Note that as with H^1, all higher key powers also need an extra
-	// factor of x^-1 (or x using the natural interpretation).  Nothing
-	// special needs to be done to make this happen, though: H^1 * H^1 would
-	// end up with two factors of x^-1, but the multiplication consumes one.
-	// So the product H^2 ends up with the desired one factor of x^-1.
-	_ghash_square	H_CUR_XMM, H_INC_XMM, GFPOLY_XMM, %xmm0, %xmm1
-
-	// Create H_CUR_YMM = [H^2, H^1] and H_INC_YMM = [H^2, H^2].
-	vinserti128	$1, H_CUR_XMM, H_INC_YMM, H_CUR_YMM
-	vinserti128	$1, H_INC_XMM, H_INC_YMM, H_INC_YMM
-
-	// Create H_CUR = [H^4, H^3, H^2, H^1] and H_INC = [H^4, H^4, H^4, H^4].
-	_ghash_mul	H_INC_YMM, H_CUR_YMM, H_INC_YMM, GFPOLY_YMM, \
-			%ymm0, %ymm1, %ymm2
-	vinserti64x4	$1, H_CUR_YMM, H_INC, H_CUR
-	vshufi64x2	$0, H_INC, H_INC, H_INC
-
-	// Store the lowest set of key powers.
-	vmovdqu8	H_CUR, (POWERS_PTR)
-
-	// Compute and store the remaining key powers.
-	// Repeatedly multiply [H^(i+3), H^(i+2), H^(i+1), H^i] by
-	// [H^4, H^4, H^4, H^4] to get [H^(i+7), H^(i+6), H^(i+5), H^(i+4)].
-	mov		$3, %eax
-.Lprecompute_next:
-	sub		$64, POWERS_PTR
-	_ghash_mul	H_INC, H_CUR, H_CUR, GFPOLY, %zmm0, %zmm1, %zmm2
-	vmovdqu8	H_CUR, (POWERS_PTR)
-	dec		%eax
-	jnz		.Lprecompute_next
-
-	vzeroupper	// This is needed after using ymm or zmm registers.
-	RET
-SYM_FUNC_END(aes_gcm_precompute_vaes_avx512)
-
 // XOR together the 128-bit lanes of \src (whose low lane is \src_xmm) and store
 // the result in \dst_xmm.  This implicitly zeroizes the other lanes of dst.
 .macro	_horizontal_xor	src, src_xmm, dst_xmm, t0_xmm, t1_xmm, t2_xmm
@@ -482,139 +355,6 @@ SYM_FUNC_END(aes_gcm_precompute_vaes_avx512)
 .endr
 .endm
 
-// void aes_gcm_aad_update_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
-//				       u8 ghash_acc[16],
-//				       const u8 *aad, int aadlen);
-//
-// This function processes the AAD (Additional Authenticated Data) in GCM.
-// Using the key |key|, it updates the GHASH accumulator |ghash_acc| with the
-// data given by |aad| and |aadlen|.  On the first call, |ghash_acc| must be all
-// zeroes.  |aadlen| must be a multiple of 16, except on the last call where it
-// can be any length.  The caller must do any buffering needed to ensure this.
-//
-// This handles large amounts of AAD efficiently, while also keeping overhead
-// low for small amounts which is the common case.  TLS and IPsec use less than
-// one block of AAD, but (uncommonly) other use cases may use much more.
-SYM_FUNC_START(aes_gcm_aad_update_vaes_avx512)
-
-	// Function arguments
-	.set	KEY,		%rdi
-	.set	GHASH_ACC_PTR,	%rsi
-	.set	AAD,		%rdx
-	.set	AADLEN,		%ecx
-	.set	AADLEN64,	%rcx	// Zero-extend AADLEN before using!
-
-	// Additional local variables.
-	// %rax and %k1 are used as temporary registers.
-	.set	GHASHDATA0,	%zmm0
-	.set	GHASHDATA0_XMM,	%xmm0
-	.set	GHASHDATA1,	%zmm1
-	.set	GHASHDATA1_XMM,	%xmm1
-	.set	GHASHDATA2,	%zmm2
-	.set	GHASHDATA2_XMM,	%xmm2
-	.set	GHASHDATA3,	%zmm3
-	.set	BSWAP_MASK,	%zmm4
-	.set	BSWAP_MASK_XMM,	%xmm4
-	.set	GHASH_ACC,	%zmm5
-	.set	GHASH_ACC_XMM,	%xmm5
-	.set	H_POW4,		%zmm6
-	.set	H_POW3,		%zmm7
-	.set	H_POW2,		%zmm8
-	.set	H_POW1,		%zmm9
-	.set	H_POW1_XMM,	%xmm9
-	.set	GFPOLY,		%zmm10
-	.set	GFPOLY_XMM,	%xmm10
-	.set	GHASHTMP0,	%zmm11
-	.set	GHASHTMP1,	%zmm12
-	.set	GHASHTMP2,	%zmm13
-
-	// Load the GHASH accumulator.
-	vmovdqu		(GHASH_ACC_PTR), GHASH_ACC_XMM
-
-	// Check for the common case of AADLEN <= 16, as well as AADLEN == 0.
-	cmp		$16, AADLEN
-	jg		.Laad_more_than_16bytes
-	test		AADLEN, AADLEN
-	jz		.Laad_done
-
-	// Fast path: update GHASH with 1 <= AADLEN <= 16 bytes of AAD.
-	vmovdqu		.Lbswap_mask(%rip), BSWAP_MASK_XMM
-	vmovdqu		.Lgfpoly(%rip), GFPOLY_XMM
-	mov		$-1, %eax
-	bzhi		AADLEN, %eax, %eax
-	kmovd		%eax, %k1
-	vmovdqu8	(AAD), GHASHDATA0_XMM{%k1}{z}
-	vmovdqu		OFFSETOFEND_H_POWERS-16(KEY), H_POW1_XMM
-	vpshufb		BSWAP_MASK_XMM, GHASHDATA0_XMM, GHASHDATA0_XMM
-	vpxor		GHASHDATA0_XMM, GHASH_ACC_XMM, GHASH_ACC_XMM
-	_ghash_mul	H_POW1_XMM, GHASH_ACC_XMM, GHASH_ACC_XMM, GFPOLY_XMM, \
-			GHASHDATA0_XMM, GHASHDATA1_XMM, GHASHDATA2_XMM
-	jmp		.Laad_done
-
-.Laad_more_than_16bytes:
-	vbroadcasti32x4	.Lbswap_mask(%rip), BSWAP_MASK
-	vbroadcasti32x4	.Lgfpoly(%rip), GFPOLY
-
-	// If AADLEN >= 256, update GHASH with 256 bytes of AAD at a time.
-	sub		$256, AADLEN
-	jl		.Laad_loop_4x_done
-	vmovdqu8	OFFSETOFEND_H_POWERS-4*64(KEY), H_POW4
-	vmovdqu8	OFFSETOFEND_H_POWERS-3*64(KEY), H_POW3
-	vmovdqu8	OFFSETOFEND_H_POWERS-2*64(KEY), H_POW2
-	vmovdqu8	OFFSETOFEND_H_POWERS-1*64(KEY), H_POW1
-.Laad_loop_4x:
-	vmovdqu8	0*64(AAD), GHASHDATA0
-	vmovdqu8	1*64(AAD), GHASHDATA1
-	vmovdqu8	2*64(AAD), GHASHDATA2
-	vmovdqu8	3*64(AAD), GHASHDATA3
-	_ghash_4x
-	add		$256, AAD
-	sub		$256, AADLEN
-	jge		.Laad_loop_4x
-.Laad_loop_4x_done:
-
-	// If AADLEN >= 64, update GHASH with 64 bytes of AAD at a time.
-	add		$192, AADLEN
-	jl		.Laad_loop_1x_done
-	vmovdqu8	OFFSETOFEND_H_POWERS-1*64(KEY), H_POW1
-.Laad_loop_1x:
-	vmovdqu8	(AAD), GHASHDATA0
-	vpshufb		BSWAP_MASK, GHASHDATA0, GHASHDATA0
-	vpxord		GHASHDATA0, GHASH_ACC, GHASH_ACC
-	_ghash_mul	H_POW1, GHASH_ACC, GHASH_ACC, GFPOLY, \
-			GHASHDATA0, GHASHDATA1, GHASHDATA2
-	_horizontal_xor GHASH_ACC, GHASH_ACC_XMM, GHASH_ACC_XMM, \
-			GHASHDATA0_XMM, GHASHDATA1_XMM, GHASHDATA2_XMM
-	add		$64, AAD
-	sub		$64, AADLEN
-	jge		.Laad_loop_1x
-.Laad_loop_1x_done:
-
-	// Update GHASH with the remaining 0 <= AADLEN < 64 bytes of AAD.
-	add		$64, AADLEN
-	jz		.Laad_done
-	mov		$-1, %rax
-	bzhi		AADLEN64, %rax, %rax
-	kmovq		%rax, %k1
-	vmovdqu8	(AAD), GHASHDATA0{%k1}{z}
-	neg		AADLEN64
-	and		$~15, AADLEN64  // -round_up(AADLEN, 16)
-	vmovdqu8	OFFSETOFEND_H_POWERS(KEY,AADLEN64), H_POW1
-	vpshufb		BSWAP_MASK, GHASHDATA0, GHASHDATA0
-	vpxord		GHASHDATA0, GHASH_ACC, GHASH_ACC
-	_ghash_mul	H_POW1, GHASH_ACC, GHASH_ACC, GFPOLY, \
-			GHASHDATA0, GHASHDATA1, GHASHDATA2
-	_horizontal_xor GHASH_ACC, GHASH_ACC_XMM, GHASH_ACC_XMM, \
-			GHASHDATA0_XMM, GHASHDATA1_XMM, GHASHDATA2_XMM
-
-.Laad_done:
-	// Store the updated GHASH accumulator back to memory.
-	vmovdqu		GHASH_ACC_XMM, (GHASH_ACC_PTR)
-
-	vzeroupper	// This is needed after using ymm or zmm registers.
-	RET
-SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
-
 // Do one non-last round of AES encryption on the blocks in %zmm[0-3] using the
 // round key that has been broadcast to all 128-bit lanes of \round_key.
 .macro	_vaesenc_4x	round_key
@@ -671,9 +411,11 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
 	vmovdqu8	GHASHDATA3, 3*64(DST)
 .endm
 
-// void aes_gcm_{enc,dec}_update_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
-//					     const u32 le_ctr[4], u8 ghash_acc[16],
-//					     const u8 *src, u8 *dst, int datalen);
+// void aes_gcm_{enc,dec}_update_vaes_avx512(u8 *dst, const u8 *src,
+//					     size_t datalen,
+//					     struct polyval_elem *ghash_acc,
+//					     const __be32 ctr32[4],
+//					     const struct aes_gcm_key *key);
 //
 // This macro generates a GCM encryption or decryption update function with the
 // above prototype (with \enc selecting which one).  The function computes the
@@ -686,26 +428,25 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
 // any length.  The caller must do any buffering needed to ensure this.  Both
 // in-place and out-of-place en/decryption are supported.
 //
-// |le_ctr| must give the current counter in little-endian format.  This
-// function loads the counter from |le_ctr| and increments the loaded counter as
-// needed, but it does *not* store the updated counter back to |le_ctr|.  The
-// caller must update |le_ctr| if any more data segments follow.  Internally,
-// only the low 32-bit word of the counter is incremented, following the GCM
-// standard.
+// |ctr32| must give the current counter in big-endian format.  This function
+// loads the counter from |ctr32| and increments the loaded counter as needed,
+// but it does *not* store the updated counter back to |ctr32|.  The caller must
+// update |ctr32| if any more data segments follow.  Internally, only the low
+// 32-bit word of the counter is incremented, following the GCM standard.
 .macro	_aes_gcm_update	enc
 
 	// Function arguments
-	.set	KEY,		%rdi
-	.set	LE_CTR_PTR,	%rsi
-	.set	GHASH_ACC_PTR,	%rdx
-	.set	SRC,		%rcx
-	.set	DST,		%r8
-	.set	DATALEN,	%r9d
-	.set	DATALEN64,	%r9	// Zero-extend DATALEN before using!
+	.set	DST,		%rdi
+	.set	SRC,		%rsi
+	.set	DATALEN,	%rdx
+	.set	DATALEN32,	%edx
+	.set	GHASH_ACC_PTR,	%rcx
+	.set	BE_CTR_PTR,	%r8
+	.set	KEY,		%r9
 
 	// Additional local variables
 
-	// %rax and %k1 are used as temporary registers.  LE_CTR_PTR is also
+	// %rax and %k1 are used as temporary registers.  BE_CTR_PTR is also
 	// available as a temporary register after the counter is loaded.
 
 	// AES key length in bytes
@@ -785,7 +526,8 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
 
 	// Load the GHASH accumulator and the starting counter.
 	vmovdqu		(GHASH_ACC_PTR), GHASH_ACC_XMM
-	vbroadcasti32x4	(LE_CTR_PTR), LE_CTR
+	vbroadcasti32x4	(BE_CTR_PTR), LE_CTR
+	vpshufb		BSWAP_MASK, LE_CTR, LE_CTR
 
 	// Load the AES key length in bytes.
 	movl		OFFSETOF_AESKEYLEN(KEY), AESKEYLEN
@@ -807,8 +549,7 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
 	// that processes 256 bytes of data at a time.  Otherwise skip it.
 	//
 	// Pre-subtracting 256 from DATALEN saves an instruction from the main
-	// loop and also ensures that at least one write always occurs to
-	// DATALEN, zero-extending it and allowing DATALEN64 to be used later.
+	// loop.
 	sub		$256, DATALEN
 	jl		.Lcrypt_loop_4x_done\@
 
@@ -930,8 +671,8 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
 
 	// Make POWERS_PTR point to the key powers [H^N, H^(N-1), ...] where N
 	// is the number of blocks that remain.
-	.set		POWERS_PTR, LE_CTR_PTR	// LE_CTR_PTR is free to be reused.
-	mov		DATALEN, %eax
+	.set		POWERS_PTR, BE_CTR_PTR	// BE_CTR_PTR is free to be reused.
+	mov		DATALEN32, %eax
 	neg		%rax
 	and		$~15, %rax  // -round_up(DATALEN, 16)
 	lea		OFFSETOFEND_H_POWERS(KEY,%rax), POWERS_PTR
@@ -953,7 +694,7 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
 	// DATALEN >= 64, otherwise DATALEN 1's.  Do this branchlessly using the
 	// bzhi instruction from BMI2.  (This relies on DATALEN <= 255.)
 	mov		$-1, %rax
-	bzhi		DATALEN64, %rax, %rax
+	bzhi		DATALEN, %rax, %rax
 	kmovq		%rax, %k1
 
 	// Encrypt a vector of counter blocks.  This does not need to be masked.
@@ -1014,14 +755,16 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
 	RET
 .endm
 
-// void aes_gcm_enc_final_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
-//				      const u32 le_ctr[4], u8 ghash_acc[16],
-//				      u64 total_aadlen, u64 total_datalen);
-// bool aes_gcm_dec_final_vaes_avx512(const struct aes_gcm_key_vaes_avx512 *key,
-//				      const u32 le_ctr[4],
-//				      const u8 ghash_acc[16],
+// void aes_gcm_enc_final_vaes_avx512(const struct aes_gcm_key *key,
+//				      const u8 nonce[12],
+//				      const struct polyval_elem *ghash_acc,
 //				      u64 total_aadlen, u64 total_datalen,
-//				      const u8 tag[16], int taglen);
+//				      u8 *authtag);
+// bool aes_gcm_dec_final_vaes_avx512(const struct aes_gcm_key *key,
+//				      const u8 nonce[12],
+//				      const struct polyval_elem *ghash_acc,
+//				      u64 total_aadlen, u64 total_datalen,
+//				      const u8 *authtag);
 //
 // This macro generates one of the above two functions (with \enc selecting
 // which one).  Both functions finish computing the GCM authentication tag by
@@ -1029,31 +772,30 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
 // |total_aadlen| and |total_datalen| must be the total length of the additional
 // authenticated data and the en/decrypted data in bytes, respectively.
 //
-// The encryption function then stores the full-length (16-byte) computed
-// authentication tag to |ghash_acc|.  The decryption function instead loads the
-// expected authentication tag (the one that was transmitted) from the 16-byte
-// buffer |tag|, compares the first 4 <= |taglen| <= 16 bytes of it to the
+// The encryption function then stores the computed authentication tag to
+// |authtag|.  The decryption function instead loads the expected authentication
+// tag (the one that was transmitted) from |authtag|, compares it to the
 // computed tag in constant time, and returns true if and only if they match.
+// In both cases the length of the tag is |key->authtag_len| bytes.
 .macro	_aes_gcm_final	enc
 
 	// Function arguments
 	.set	KEY,		%rdi
-	.set	LE_CTR_PTR,	%rsi
+	.set	NONCE_PTR,	%rsi
 	.set	GHASH_ACC_PTR,	%rdx
 	.set	TOTAL_AADLEN,	%rcx
 	.set	TOTAL_DATALEN,	%r8
 	.set	TAG,		%r9
-	.set	TAGLEN,		%r10d	// Originally at 8(%rsp)
 
 	// Additional local variables.
 	// %rax, %xmm0-%xmm3, and %k1 are used as temporary registers.
+	.set	TAGLEN,		%r10d
 	.set	AESKEYLEN,	%r11d
 	.set	AESKEYLEN64,	%r11
 	.set	GFPOLY,		%xmm4
 	.set	BSWAP_MASK,	%xmm5
-	.set	LE_CTR,		%xmm6
-	.set	GHASH_ACC,	%xmm7
-	.set	H_POW1,		%xmm8
+	.set	GHASH_ACC,	%xmm6
+	.set	H_POW1,		%xmm7
 
 	// Load some constants.
 	vmovdqa		.Lgfpoly(%rip), GFPOLY
@@ -1062,11 +804,6 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
 	// Load the AES key length in bytes.
 	movl		OFFSETOF_AESKEYLEN(KEY), AESKEYLEN
 
-	// Set up a counter block with 1 in the low 32-bit word.  This is the
-	// counter that produces the ciphertext needed to encrypt the auth tag.
-	// GFPOLY has 1 in the low word, so grab the 1 from there using a blend.
-	vpblendd	$0xe, (LE_CTR_PTR), GFPOLY, LE_CTR
-
 	// Build the lengths block and XOR it with the GHASH accumulator.
 	// Although the lengths block is defined as the AAD length followed by
 	// the en/decrypted data length, both in big-endian byte order, a byte
@@ -1081,20 +818,21 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
 	// Load the first hash key power (H^1), which is stored last.
 	vmovdqu8	OFFSETOFEND_H_POWERS-16(KEY), H_POW1
 
-.if !\enc
 	// Prepare a mask of TAGLEN one bits.
-	movl		8(%rsp), TAGLEN
+	// authtag_len is size_t with value in 4..16, so movl suffices here.
+	movl		OFFSETOF_AUTHTAG_LEN(KEY), TAGLEN
 	mov		$-1, %eax
 	bzhi		TAGLEN, %eax, %eax
 	kmovd		%eax, %k1
-.endif
 
 	// Make %rax point to the last AES round key for the chosen AES variant.
 	lea		OFFSETOF_AESROUNDKEYS+6*16(KEY,AESKEYLEN64,4), %rax
 
-	// Start the AES encryption of the counter block by swapping the counter
-	// block to big-endian and XOR-ing it with the zero-th AES round key.
-	vpshufb		BSWAP_MASK, LE_CTR, %xmm0
+	// Build J_0 = nonce || be32(1) and XOR it with the zero-th AES round
+	// key to start the AES encryption of the counter block.
+	vmovq		(NONCE_PTR), %xmm0
+	vpinsrd		$2, 8(NONCE_PTR), %xmm0, %xmm0
+	vpinsrd		$3, .Lbe_one(%rip), %xmm0, %xmm0
 	vpxor		OFFSETOF_AESROUNDKEYS(KEY), %xmm0, %xmm0
 
 	// Complete the AES encryption and multiply GHASH_ACC by H^1.
@@ -1137,9 +875,9 @@ SYM_FUNC_END(aes_gcm_aad_update_vaes_avx512)
 .if \enc
 	vpxor		(%rax), GHASH_ACC, %xmm1
 	vaesenclast	%xmm1, %xmm0, GHASH_ACC
-	vmovdqu		GHASH_ACC, (GHASH_ACC_PTR)
+	vmovdqu8	GHASH_ACC, (TAG){%k1}
 .else
-	vmovdqu		(TAG), %xmm1
+	vmovdqu8	(TAG), %xmm1{%k1}{z}
 	vpternlogd	$0x96, (%rax), GHASH_ACC, %xmm1
 	vaesenclast	%xmm1, %xmm0, %xmm0
 	xor		%eax, %eax
diff --git a/lib/crypto/x86/aes.h b/lib/crypto/x86/aes.h
index 97035b783ec4a..e0c65904eef09 100644
--- a/lib/crypto/x86/aes.h
+++ b/lib/crypto/x86/aes.h
@@ -412,6 +412,8 @@ static bool aes_xts_decrypt_arch(u8 *dst, const u8 *src, size_t len,
 /* The assembly code assumes the following offsets. */
 static_assert(offsetof(struct gf128hash_key_x86, h_powers_xored) == 0);
 static_assert(offsetof(struct gf128hash_key_x86, h_powers) == 128);
+static_assert(offsetof(struct gf128hash_key_x86, h_powers16) == 0);
+static_assert(offsetof(struct gf128hash_key_x86, padding) == 256);
 static_assert(offsetof(struct gf128hash_key_x86, h_times_xm64) == 304);
 static_assert(offsetof(struct gf128hash_key_x86, h_powers[7]) == 240);
 static_assert(offsetof(struct aes_gcm_key, aes) == 0);
@@ -448,6 +450,14 @@ void aes_gcm_dec_update_vaes_avx2(u8 *dst, const u8 *src, size_t len,
 				  struct polyval_elem *ghash_acc,
 				  const __be32 ctr32[4],
 				  const struct aes_gcm_key *key);
+void aes_gcm_enc_update_vaes_avx512(u8 *dst, const u8 *src, size_t len,
+				    struct polyval_elem *ghash_acc,
+				    const __be32 ctr32[4],
+				    const struct aes_gcm_key *key);
+void aes_gcm_dec_update_vaes_avx512(u8 *dst, const u8 *src, size_t len,
+				    struct polyval_elem *ghash_acc,
+				    const __be32 ctr32[4],
+				    const struct aes_gcm_key *key);
 
 void aes_gcm_enc_final_aesni(const struct aes_gcm_key *key, const u8 nonce[12],
 			     const struct polyval_elem *ghash_acc,
@@ -476,6 +486,16 @@ bool aes_gcm_dec_final_vaes_avx2(const struct aes_gcm_key *key,
 				 const struct polyval_elem *ghash_acc,
 				 u64 total_aadlen, u64 total_datalen,
 				 const u8 *authtag);
+void aes_gcm_enc_final_vaes_avx512(const struct aes_gcm_key *key,
+				   const u8 nonce[12],
+				   const struct polyval_elem *ghash_acc,
+				   u64 total_aadlen, u64 total_datalen,
+				   u8 *authtag);
+bool aes_gcm_dec_final_vaes_avx512(const struct aes_gcm_key *key,
+				   const u8 nonce[12],
+				   const struct polyval_elem *ghash_acc,
+				   u64 total_aadlen, u64 total_datalen,
+				   const u8 *authtag);
 
 /*
  * En/decrypt and GHASH @len bytes inside an active FPU section.  @len must be
@@ -492,7 +512,14 @@ aes_gcm_update_x86_fpu(u8 *dst, const u8 *src, size_t len,
 
 		static_assert(GCM_CHUNK_SIZE % AES_BLOCK_SIZE == 0);
 
-		if (static_branch_likely(&have_vaes_avx2)) {
+		if (static_branch_likely(&have_vaes_avx512)) {
+			if (enc)
+				aes_gcm_enc_update_vaes_avx512(
+					dst, src, n, ghash_acc, ctr32, key);
+			else
+				aes_gcm_dec_update_vaes_avx512(
+					dst, src, n, ghash_acc, ctr32, key);
+		} else if (static_branch_likely(&have_vaes_avx2)) {
 			if (enc)
 				aes_gcm_enc_update_vaes_avx2(
 					dst, src, n, ghash_acc, ctr32, key);
@@ -534,7 +561,6 @@ aes_gcm_crypt_update_x86(u8 *dst, const u8 *src, size_t len,
 	__be32 ctr[4];
 
 	if (!static_branch_likely(&have_aesni_pclmul) ||
-	    static_branch_likely(&have_vaes_avx512) ||
 	    unlikely(!irq_fpu_usable()))
 		return false;
 
@@ -599,7 +625,6 @@ aes_gcm_crypt_x86(u8 *dst, const u8 *src, size_t data_len, u8 *authtag,
 	__be32 ctr32[4];
 
 	if (!static_branch_likely(&have_aesni_pclmul) ||
-	    static_branch_likely(&have_vaes_avx512) ||
 	    unlikely(!irq_fpu_usable()))
 		return false;
 
@@ -616,7 +641,11 @@ aes_gcm_crypt_x86(u8 *dst, const u8 *src, size_t data_len, u8 *authtag,
 				       key, enc);
 
 	if (enc) {
-		if (static_branch_likely(&have_vaes_avx2))
+		if (static_branch_likely(&have_vaes_avx512))
+			aes_gcm_enc_final_vaes_avx512(key, nonce, &ghash_acc,
+						      ad_len, data_len,
+						      authtag);
+		else if (static_branch_likely(&have_vaes_avx2))
 			aes_gcm_enc_final_vaes_avx2(key, nonce, &ghash_acc,
 						    ad_len, data_len, authtag);
 		else if (static_branch_likely(&have_aesni_avx))
@@ -628,7 +657,12 @@ aes_gcm_crypt_x86(u8 *dst, const u8 *src, size_t data_len, u8 *authtag,
 	} else {
 		bool valid;
 
-		if (static_branch_likely(&have_vaes_avx2))
+		if (static_branch_likely(&have_vaes_avx512))
+			valid = aes_gcm_dec_final_vaes_avx512(key, nonce,
+							      &ghash_acc,
+							      ad_len, data_len,
+							      authtag);
+		else if (static_branch_likely(&have_vaes_avx2))
 			valid = aes_gcm_dec_final_vaes_avx2(key, nonce,
 							    &ghash_acc, ad_len,
 							    data_len, authtag);
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

* [PATCH 11/11] crypto: x86/aesni-intel - Remove empty module
  2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
                   ` (9 preceding siblings ...)
  2026-11-29 20:02 ` [PATCH 10/11] lib/crypto: x86/aes-gcm: Migrate VAES+AVX512 " Eric Biggers
@ 2026-11-29 20:02 ` Eric Biggers
  10 siblings, 0 replies; 12+ messages in thread
From: Eric Biggers @ 2026-11-29 20:02 UTC (permalink / raw)
  To: linux-crypto
  Cc: Ard Biesheuvel, Jason A . Donenfeld, Herbert Xu, x86,
	Antonio Quartulli, Eric Biggers

Since all x86 optimized AES code has been migrated into lib/crypto/,
remove the now-empty aesni-intel module.  All its functionality is now
provided by the aes module (CONFIG_CRYPTO_AES) when the mode-specific
kconfigs are enabled (CONFIG_CRYPTO_XTS, etc.).

Make CRYPTO_AES_NI_INTEL a transitional symbol that enables CRYPTO_AES
and CRYPTO_XTS.  This minimizes the chance that systems using LUKS /
dm-crypt with AES-CBC or AES-XTS fail to boot due to enabling
CRYPTO_AES_NI_INTEL only.  (This is a targeted mitigation for an
important case, and thus other options like CRYPTO_GCM intentionally
aren't included in these transitional selections.  CRYPTO_CBC does not
need to be explicitly handled, as DM_CRYPT already selects it.)

Unfortunately, the CRYPTO_AES_NI_INTEL transitional symbol can't just go
in arch/x86/crypto/Kconfig, since transitional symbols can't be enclosed
in 'if'.  Therefore, it has to go in crypto/Kconfig.  Transitional
symbols also can't use 'select'; however, 'select' is nonetheless needed
here, to set CRYPTO_AES and CRYPTO_XTS in existing kconfigs that had
them explicitly set to 'n'.  So the selects go directly on CRYPTO.  It's
a bit ugly, but it can be removed after a few releases.

Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 Documentation/filesystems/fscrypt.rst |  2 --
 arch/x86/crypto/Kconfig               | 25 ---------------
 arch/x86/crypto/Makefile              |  3 --
 arch/x86/crypto/aesni-intel_glue.c    | 46 ---------------------------
 crypto/Kconfig                        |  9 ++++++
 5 files changed, 9 insertions(+), 76 deletions(-)
 delete mode 100644 arch/x86/crypto/aesni-intel_glue.c

diff --git a/Documentation/filesystems/fscrypt.rst b/Documentation/filesystems/fscrypt.rst
index 6e2e511a70bb5..8a21973207b8b 100644
--- a/Documentation/filesystems/fscrypt.rst
+++ b/Documentation/filesystems/fscrypt.rst
@@ -447,14 +447,12 @@ API, but the filenames mode still does.
 - AES-256-XTS and AES-256-CBC-CTS
     - Recommended:
         - arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK
-        - x86: CONFIG_CRYPTO_AES_NI_INTEL
 
 - AES-256-HCTR2
     - Mandatory:
         - CONFIG_CRYPTO_HCTR2
     - Recommended:
         - arm64: CONFIG_CRYPTO_AES_ARM64_CE_BLK
-        - x86: CONFIG_CRYPTO_AES_NI_INTEL
 
 - Adiantum
     - Mandatory:
diff --git a/arch/x86/crypto/Kconfig b/arch/x86/crypto/Kconfig
index 20f5e2a17e45a..ab0c6e6638102 100644
--- a/arch/x86/crypto/Kconfig
+++ b/arch/x86/crypto/Kconfig
@@ -2,31 +2,6 @@
 
 menu "Accelerated Cryptographic Algorithms for CPU (x86)"
 
-config CRYPTO_AES_NI_INTEL
-	tristate "Ciphers: AES, modes: GCM (AES-NI/VAES)"
-	depends on 64BIT
-	select CRYPTO_AEAD
-	select CRYPTO_LIB_AES
-	select CRYPTO_LIB_GF128MUL
-	select CRYPTO_SKCIPHER
-	select CRYPTO_AES
-	select CRYPTO_CBC
-	select CRYPTO_XTS
-	help
-	  AEAD cipher: AES with GCM
-
-	  Architecture: x86_64 using:
-	  - AES-NI (AES new instructions)
-	  - VAES (Vector AES)
-
-	  The module controlled by this option (aesni-intel.ko) no longer
-	  directly provides the accelerated ECB, CBC, CBC-CTS, CTR, XCTR, and
-	  XTS code.  Those are now provided by CRYPTO_AES (aes.ko) when the
-	  corresponding mode option (CRYPTO_XTS, CRYPTO_CBC, etc.) is enabled.
-
-	  To ensure dm-crypt continues to work in kconfigs with only this option
-	  set, this option selects CRYPTO_AES, CRYPTO_CBC, and CRYPTO_XTS.
-
 config CRYPTO_BLOWFISH_X86_64
 	tristate "Ciphers: Blowfish, modes: ECB, CBC"
 	depends on 64BIT
diff --git a/arch/x86/crypto/Makefile b/arch/x86/crypto/Makefile
index 7a443aa3ce4d7..e345342e445d6 100644
--- a/arch/x86/crypto/Makefile
+++ b/arch/x86/crypto/Makefile
@@ -39,9 +39,6 @@ cast6-avx-x86_64-y := cast6-avx-x86_64-asm_64.o cast6_avx_glue.o
 obj-$(CONFIG_CRYPTO_AEGIS128_AESNI_SSE2) += aegis128-aesni.o
 aegis128-aesni-y := aegis128-aesni-asm.o aegis128-aesni-glue.o
 
-obj-$(CONFIG_CRYPTO_AES_NI_INTEL) += aesni-intel.o
-aesni-intel-y := aesni-intel_glue.o
-
 obj-$(CONFIG_CRYPTO_SM4_AESNI_AVX_X86_64) += sm4-aesni-avx-x86_64.o
 sm4-aesni-avx-x86_64-y := sm4-aesni-avx-asm_64.o sm4_aesni_avx_glue.o
 
diff --git a/arch/x86/crypto/aesni-intel_glue.c b/arch/x86/crypto/aesni-intel_glue.c
deleted file mode 100644
index 93718bb95092a..0000000000000
--- a/arch/x86/crypto/aesni-intel_glue.c
+++ /dev/null
@@ -1,46 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0-or-later
-/*
- * Support for AES-NI and VAES instructions.  This file contains glue code.
- * The real AES implementations are in .S files.
- *
- * Copyright (C) 2008, Intel Corp.
- *    Author: Huang Ying <ying.huang@intel.com>
- *
- * Added RFC4106 AES-GCM support for 128-bit keys under the AEAD
- * interface for 64-bit kernels.
- *    Authors: Adrian Hoban <adrian.hoban@intel.com>
- *             Gabriele Paoloni <gabriele.paoloni@intel.com>
- *             Tadeusz Struk (tadeusz.struk@intel.com)
- *             Aidan O'Mahony (aidan.o.mahony@intel.com)
- *    Copyright (c) 2010, Intel Corporation.
- *
- * Copyright 2024 Google LLC
- */
-
-#include <linux/module.h>
-#include <linux/err.h>
-#include <asm/cpu_device_id.h>
-
-static const struct x86_cpu_id aesni_cpu_id[] = {
-	X86_MATCH_FEATURE(X86_FEATURE_AES, NULL),
-	{}
-};
-MODULE_DEVICE_TABLE(x86cpu, aesni_cpu_id);
-
-static int __init aesni_init(void)
-{
-	if (!x86_match_cpu(aesni_cpu_id))
-		return -ENODEV;
-
-	return 0;
-}
-
-static void __exit aesni_exit(void)
-{
-}
-
-module_init(aesni_init);
-module_exit(aesni_exit);
-
-MODULE_DESCRIPTION("AES-GCM, optimized with AES-NI or VAES instructions");
-MODULE_LICENSE("GPL");
diff --git a/crypto/Kconfig b/crypto/Kconfig
index 981d5dc422d4c..b3ff1b88a5ad1 100644
--- a/crypto/Kconfig
+++ b/crypto/Kconfig
@@ -14,6 +14,8 @@ source "crypto/async_tx/Kconfig"
 menuconfig CRYPTO
 	tristate "Cryptographic API"
 	select CRYPTO_LIB_UTILS
+	select CRYPTO_AES if CRYPTO_AES_NI_INTEL && X86_64
+	select CRYPTO_XTS if CRYPTO_AES_NI_INTEL && X86_64
 	help
 	  This option provides the core Cryptographic API.
 
@@ -1377,3 +1379,10 @@ source "certs/Kconfig"
 source "crypto/krb5/Kconfig"
 
 endif	# if CRYPTO
+
+config CRYPTO_AES_NI_INTEL
+	tristate
+	transitional
+	help
+	  This transitional symbol ensures that kconfigs that had aesni-intel
+	  enabled still get AES-XTS support (via CRYPTO_AES and CRYPTO_XTS).
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 12+ messages in thread

end of thread, other threads:[~2026-11-29 20:04 UTC | newest]

Thread overview: 12+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-29 20:02 [PATCH 00/11] Migrate x86_64 AES-GCM code into library Eric Biggers
2026-11-29 20:02 ` [PATCH 01/11] crypto: aes - Flush dcache in CBC-CTS and XTS linear fast paths Eric Biggers
2026-11-29 20:02 ` [PATCH 02/11] lib/crypto: gf128hash: Link libgf128hash before libaes Eric Biggers
2026-11-29 20:02 ` [PATCH 03/11] lib/crypto: aes-gcm: Add one-shot AES-GCM arch hooks Eric Biggers
2026-11-29 20:02 ` [PATCH 04/11] crypto: aes - Add linear fast path for AES-GCM Eric Biggers
2026-11-29 20:02 ` [PATCH 05/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with PCLMULQDQ and AVX Eric Biggers
2026-11-29 20:02 ` [PATCH 06/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with VPCLMULQDQ and AVX2 Eric Biggers
2026-11-29 20:02 ` [PATCH 07/11] lib/crypto: x86/gf128hash: Optimize GHASH and POLYVAL with VPCLMULQDQ and AVX512 Eric Biggers
2026-11-29 20:02 ` [PATCH 08/11] lib/crypto: x86/aes-gcm: Migrate AES-NI optimized code into library Eric Biggers
2026-11-29 20:02 ` [PATCH 09/11] lib/crypto: x86/aes-gcm: Migrate VAES+AVX2 " Eric Biggers
2026-11-29 20:02 ` [PATCH 10/11] lib/crypto: x86/aes-gcm: Migrate VAES+AVX512 " Eric Biggers
2026-11-29 20:02 ` [PATCH 11/11] crypto: x86/aesni-intel - Remove empty module Eric Biggers

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox