Linux cryptographic layer development
 help / color / mirror / Atom feed
From: Eric Biggers <ebiggers@kernel.org>
To: linux-crypto@vger.kernel.org
Cc: Ard Biesheuvel <ardb@kernel.org>,
	"Jason A . Donenfeld" <Jason@zx2c4.com>,
	Herbert Xu <herbert@gondor.apana.org.au>,
	Eric Biggers <ebiggers@kernel.org>
Subject: [PATCH 1/2] crypto: lrw - Implement field multiplication without gf128mul_64k
Date: Thu,  3 Dec 2026 12:11:51 -0800	[thread overview]
Message-ID: <20261203201152.76224-2-ebiggers@kernel.org> (raw)
In-Reply-To: <20261203201152.76224-1-ebiggers@kernel.org>

The lrw template is one of the only remaining users of the gf128mul
module, since GHASH and POLYVAL no longer use it.  It's also the only
user of the "bbe" and "64k" functions in it.

The 64 KiB multiplication table, of which a separate instance is created
for each LRW key, is quite enormous.  It's very bad on the CPU's dcache
for anyone still using this legacy disk encryption mode.  Moreover,
initializing it requires key-dependent table lookups.

The 64 KiB table is used to do GF(2^128) multiplications (using the
"bbe" convention) by the field element 'Key2' in two places:

1. When setting a new key, compute and cache
   'mulinc[i] = Key2 * (x^i + ... + 1)' for i in 0..127.
   This creates a 2 KiB table (different from the big 64 KiB table).

2. When en/decrypting each message, compute the initial tweak
   T = Key2 * IV.

The mulinc initialization is easy to do differently, using the formula:

    mulinc[i] = mulinc[i - 1] + (Key2 * x^i)

Maintain Key2 * x^i as a loop variable that's multiplied by x once per
iteration using gf128mul_x_bbe().  That doesn't require a table.

'T = Key2 * IV' is a bit harder to reimplement.  The naive solution of
iterating over all 128 coefficients would be slow.

Instead, we can use the 'mulinc' table, which contains prefix sums.
mulinc[i] is Key2 times a contiguous run of 1 bits starting at the
low-order bit -- used by lrw_next_index() to compute Key2 * (T + 1) from
Key2 * T.  However, by adding two entries we can compute Key2 times
*any* contiguous run of 1 bits.  E.g., considering 0b1100:

      Key2 * 0b1100
    = Key2 * (x^3 + x^2)
    = (Key2 * (x^3 + x^2 + x + 1)) + (Key2 * (x + 1))
    = mulinc[3] + mulinc[1]

If there are other runs of 1 bits, we add those entries too.  The
indices of the mulinc entries to add are the bit positions in IV where
the next higher bit is different: equal to IV ^ (IV >> 1).

Adding (XOR'ing) all such mulinc entries gives Key2 * IV, in linear time
with respect to the number of runs of 1 bits in the IV.

The IV is public, so the IV-dependent execution time is tolerable.

For dm-crypt use, the average number of loop iterations,
popcount(IV ^ (IV >> 1)), also tends to be no more than the number of
iterations (16) done with the gf128mul_64k table.  It also eliminates
the massive 64 KiB table.  So in practice it is faster, despite the
branches being less predictable.  E.g., a benchmark with en/decrypting
512-byte messages and an incrementing IV starting at 4 random bytes and
12 zero bytes showed about 5% better performance.

Setting a key is now much faster too.

Signed-off-by: Eric Biggers <ebiggers@kernel.org>
---
 crypto/Kconfig |  1 -
 crypto/lrw.c   | 90 ++++++++++++++++++++++++--------------------------
 2 files changed, 44 insertions(+), 47 deletions(-)

diff --git a/crypto/Kconfig b/crypto/Kconfig
index 981d5dc422d4c..b203f20b7ca42 100644
--- a/crypto/Kconfig
+++ b/crypto/Kconfig
@@ -699,7 +699,6 @@ config CRYPTO_HCTR2
 
 config CRYPTO_LRW
 	tristate "LRW (Liskov Rivest Wagner)"
-	select CRYPTO_LIB_GF128MUL
 	select CRYPTO_SKCIPHER
 	select CRYPTO_MANAGER
 	select CRYPTO_ECB
diff --git a/crypto/lrw.c b/crypto/lrw.c
index e306e85d7cedc..6baae2971e432 100644
--- a/crypto/lrw.c
+++ b/crypto/lrw.c
@@ -15,12 +15,14 @@
 
 #include <crypto/internal/skcipher.h>
 #include <crypto/scatterwalk.h>
+#include <linux/bitops.h>
 #include <linux/err.h>
 #include <linux/init.h>
 #include <linux/kernel.h>
 #include <linux/module.h>
 #include <linux/scatterlist.h>
 #include <linux/slab.h>
+#include <linux/unaligned.h>
 
 #include <crypto/b128ops.h>
 #include <crypto/gf128mul.h>
@@ -31,20 +33,9 @@ struct lrw_tfm_ctx {
 	struct crypto_skcipher *child;
 
 	/*
-	 * optimizes multiplying a random (non incrementing, as at the
-	 * start of a new sector) value with key2, we could also have
-	 * used 4k optimization tables or no optimization at all. In the
-	 * latter case we would have to store key2 here
-	 */
-	struct gf128mul_64k *table;
-
-	/*
-	 * stores:
-	 *  key2*{ 0,0,...0,0,0,0,1 }, key2*{ 0,0,...0,0,0,1,1 },
-	 *  key2*{ 0,0,...0,0,1,1,1 }, key2*{ 0,0,...0,1,1,1,1 }
-	 *  key2*{ 0,0,...1,1,1,1,1 }, etc
-	 * needed for optimized multiplication of incrementing values
-	 * with key2
+	 * mulinc[i] = Key2 * (x^i + ... + 1) in GF(2^128), i.e. the prefix XOR
+	 * sums of Key2 * x^j.  Used to compute the initial tweak Key2 * IV and
+	 * to update the tweak when incrementing the block counter.
 	 */
 	be128 mulinc[128];
 };
@@ -54,15 +45,34 @@ struct lrw_request_ctx {
 	struct skcipher_request subreq;
 };
 
-static inline void lrw_setbit128_bbe(void *b, int bit)
+/*
+ * Compute T = Key2 * IV in GF(2^128) using mulinc[].
+ *
+ * Because mulinc[i] stores the prefix XOR sums of Key2 * x^0 through
+ * Key2 * x^i, any contiguous run of 1 bits in IV from bit a through bit b
+ * contributes mulinc[b] ^ mulinc[a - 1] (or just mulinc[b] if a == 0).
+ * Those endpoints are the bit positions in IV where the next higher bit is
+ * different, i.e. the set bits of IV ^ (IV >> 1).
+ *
+ * This has IV-dependent execution time, which is fine since the IV is public.
+ */
+static void lrw_mul_tweak(be128 *t, const u8 *iv, const be128 mulinc[128])
 {
-	__set_bit(bit ^ (0x80 -
-#ifdef __BIG_ENDIAN
-			 BITS_PER_LONG
-#else
-			 BITS_PER_BYTE
-#endif
-			), b);
+	u64 hi = get_unaligned_be64(&iv[0]);
+	u64 lo = get_unaligned_be64(&iv[8]);
+	u64 diff_hi = hi ^ (hi >> 1);
+	u64 diff_lo = lo ^ (lo >> 1) ^ (hi << 63);
+	be128 res = { 0 };
+
+	while (diff_lo) {
+		be128_xor(&res, &res, &mulinc[__ffs64(diff_lo)]);
+		diff_lo &= diff_lo - 1;
+	}
+	while (diff_hi) {
+		be128_xor(&res, &res, &mulinc[64 + __ffs64(diff_hi)]);
+		diff_hi &= diff_hi - 1;
+	}
+	*t = res;
 }
 
 static int lrw_setkey(struct crypto_skcipher *parent, const u8 *key,
@@ -72,7 +82,7 @@ static int lrw_setkey(struct crypto_skcipher *parent, const u8 *key,
 	struct crypto_skcipher *child = ctx->child;
 	int err, bsize = LRW_BLOCK_SIZE;
 	const u8 *tweak = key + keylen - bsize;
-	be128 tmp = { 0 };
+	be128 power;
 	int i;
 
 	crypto_skcipher_clear_flags(child, CRYPTO_TFM_REQ_MASK);
@@ -82,21 +92,14 @@ static int lrw_setkey(struct crypto_skcipher *parent, const u8 *key,
 	if (err)
 		return err;
 
-	if (ctx->table)
-		gf128mul_free_64k(ctx->table);
-
-	/* initialize multiplication table for Key2 */
-	ctx->table = gf128mul_init_64k_bbe((be128 *)tweak);
-	if (!ctx->table)
-		return -ENOMEM;
-
-	/* initialize optimization table */
-	for (i = 0; i < 128; i++) {
-		lrw_setbit128_bbe(&tmp, i);
-		ctx->mulinc[i] = tmp;
-		gf128mul_64k_bbe(&ctx->mulinc[i], ctx->table);
+	/* Initialize mulinc[i] = Key2 * (x^i + ... + 1) */
+	memcpy(&power, tweak, sizeof(power));
+	ctx->mulinc[0] = power;
+	for (i = 1; i < 128; i++) {
+		gf128mul_x_bbe(&power, &power);
+		be128_xor(&ctx->mulinc[i], &ctx->mulinc[i - 1], &power);
 	}
-
+	memzero_explicit(&power, sizeof(power));
 	return 0;
 }
 
@@ -124,9 +127,9 @@ static int lrw_next_index(u32 *counter)
 	}
 
 	/*
-	 * If we get here, then x == 128 and we are incrementing the counter
+	 * If we get here, then res == 128 and we are incrementing the counter
 	 * from all ones to all zeros. This means we must return index 127, i.e.
-	 * the one corresponding to key2*{ 1,...,1 }.
+	 * the index of mulinc[] that contains Key2 * (x^127 + ... + 1).
 	 */
 	return 127;
 }
@@ -233,11 +236,8 @@ static void lrw_init_crypt(struct skcipher_request *req)
 	skcipher_request_set_crypt(subreq, req->dst, req->dst,
 				   req->cryptlen, req->iv);
 
-	/* calculate first value of T */
-	memcpy(&rctx->t, req->iv, sizeof(rctx->t));
-
-	/* T <- I*Key2 */
-	gf128mul_64k_bbe(&rctx->t, ctx->table);
+	/* Calculate initial tweak: T = Key2 * IV */
+	lrw_mul_tweak(&rctx->t, req->iv, ctx->mulinc);
 }
 
 static int lrw_encrypt(struct skcipher_request *req)
@@ -285,8 +285,6 @@ static void lrw_exit_tfm(struct crypto_skcipher *tfm)
 {
 	struct lrw_tfm_ctx *ctx = crypto_skcipher_ctx(tfm);
 
-	if (ctx->table)
-		gf128mul_free_64k(ctx->table);
 	crypto_free_skcipher(ctx->child);
 }
 
-- 
2.56.1


  reply	other threads:[~2026-12-03 20:12 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-03 20:11 [PATCH 0/2] lib/crypto: gf128mul: Remove 64 KiB table support Eric Biggers
2026-12-03 20:11 ` Eric Biggers [this message]
2026-12-03 20:11 ` [PATCH 2/2] lib/crypto: gf128mul: Remove unused 64k bbe table functions Eric Biggers

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261203201152.76224-2-ebiggers@kernel.org \
    --to=ebiggers@kernel.org \
    --cc=Jason@zx2c4.com \
    --cc=ardb@kernel.org \
    --cc=herbert@gondor.apana.org.au \
    --cc=linux-crypto@vger.kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox