Skip to contentSkip to conversation

faster SHA-1 collision detection

PATCH In review Scott Chacon 8 participants 24 messages Sep 29 – Oct 11

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

cover faster SHA-1 collision detection

So, spoiler alert, the code in this patch series is mainly AI generated. I would try to fool you, but too many of you are far too aware of my actual C skills. That being said, I thought maybe someone here (especially those of you working on server optimization stuff) would be interested in the speed increases for both the server and client in making sha1dc quite a bit faster.

This series ports the approach of Sam Reis's sha1dc Rust crate [1], which gitoxide recently switched to [2], to C.

The end result hashes roughly 2.7x faster on the Xeon and 2.85x faster on the M5 Max. Single-threaded index-pack of git.git goes from 24.3s to 12.7s on the Xeon, and from 16.1s to 8.7s on the M5 Max.

Hashing throughput on the Xeon, in MiB/s:

16KiB 1MiB vs OpenSSL

  OpenSSL SHA-1 (no detection)   1234    1129      1.00x
  sha1dc/ (today)                 435     450      2.67x
  shani+avx2 (default here)      1002     901      1.24x
  shani+sse2                     1075    1008      1.13x
  portable+avx2                   553     654      1.96x
  portable+sse2                   603     681      1.84x
  portable                        466     565      2.29x

In other words, currently collision detection costs about 1.5–2.5x on top of the hashing itself today, but only about 0.2x with the series.

The patches are:

[1/4]: sha1dc-accel: add a block loop for sha1dc's SHA1_CTX

Just groundwork: our own block loop around sha1dc's context and DV table, with the same results and a few percent slower, plus tests that compare against sha1dc/ directly, including on real collisions in every mode.

[2/4]: sha1dc-accel: vectorize the unavoidable-bitconditions check

The UBC filter rewritten as SSE2, AVX2, NEON, and new scalar forms, using the conditions the crate's solver picks for each. They're carried as tables, with a short loop per form to run them. 1.29x on the Xeon, 1.27x on the M5 Max.

[3/4]: sha1dc-accel: compress with SHA-NI on x86-64

Hardware compression, with the schedule spilled, and recompression of flagged blocks in hardware, too. Another 2.07x on the Xeon.

[4/4]: sha1dc-accel: compress with the ARMv8 SHA-1 instructions

The same for arm64. Another 2.4x on the M5 Max.

The x86 numbers are from a 4-vCPU Xeon VM with SHA-NI and AVX2 (GCC 13, Linux), which is unfortunately rather noisy; the per-patch hyperfine output has the spread. The arm64 numbers are medians of 9 runs on an Apple M5 Max (Apple clang, macOS). The full test suite passes on both.

[1] https://sam.dev/blog/faster-sha1-collision-detection
[2] https://github.com/GitoxideLabs/gitoxide/pull/3008

Scott Chacon (4):
sha1dc-accel: add a block loop for sha1dc's SHA1_CTX
sha1dc-accel: vectorize the unavoidable-bitconditions check
sha1dc-accel: compress with SHA-NI on x86-64
sha1dc-accel: compress with the ARMv8 SHA-1 instructions

 Makefile                            |   14 +
 contrib/buildsystems/CMakeLists.txt |    2 +-
 meson.build                         |    4 +
 sha1dc-accel/arm.c                  |  274 ++++
 sha1dc-accel/internal.h             |  126 ++
 sha1dc-accel/sha1.c                 |  498 ++++++++
 sha1dc-accel/sha1.h                 |   31 +
 sha1dc-accel/ubc_check.c            | 1789 +++++++++++++++++++++++++++
 sha1dc-accel/x86.c                  |  260 ++++
 sha1dc_git.c                        |   18 +
 t/.gitattributes                    |    1 +
 t/helper/test-sha1.c                |   95 ++
 t/helper/test-tool.c                |    2 +
 t/helper/test-tool.h                |    2 +
 t/meson.build                       |    1 +
 t/t0013-sha1dc.sh                   |   47 +
 t/t0013/sha-mbles-1.bin             |  Bin 0 -> 640 bytes
 t/t0013/sha1-reduced-round.bin      |  Bin 0 -> 128 bytes
 t/unit-tests/u-sha1dc.c             |  366 ++++++
 19 files changed, 3529 insertions(+), 1 deletion(-)
 create mode 100644 sha1dc-accel/arm.c
 create mode 100644 sha1dc-accel/internal.h
 create mode 100644 sha1dc-accel/sha1.c
 create mode 100644 sha1dc-accel/sha1.h
 create mode 100644 sha1dc-accel/ubc_check.c
 create mode 100644 sha1dc-accel/x86.c
 create mode 100644 t/t0013/sha-mbles-1.bin
 create mode 100644 t/t0013/sha1-reduced-round.bin
 create mode 100644 t/unit-tests/u-sha1dc.c

base-commit: a018953688f1b10bddf91bff8747068f5f4746a4

Signature · 1 line
2.50.1 (Apple Git-155)
#1 lore raw

PATCH 1/4 sha1dc-accel: add a block loop for sha1dc's SHA1_CTX

Unless you build with some other SHA-1 implementation, every object we hash goes through sha1collisiondetection. That's what we want for safety, but it's not free. On the machine I'm testing with (a 4-vCPU Xeon VM, which has SHA-NI and AVX2), sha1dc hashes at about 400 MiB/s, while OpenSSL's SHA-1 (which does no detection) does about 1100 MiB/s. On an Apple M5 Max, sha1dc manages about 700 MiB/s.
That matters for anything that hashes a lot of data we don't trust, like index-pack.

Sam Reis recently wrote about closing that gap for gitoxide [1], with a from-scratch rewrite of the detection code as a Rust crate [2]. There are really three separate tricks in there:

1. Compress with the CPU's SHA-1 instructions, and spill the expanded message schedule as we go. That's all the detection needs from the vast majority of blocks.

2. The "unavoidable bitconditions" (UBC) filter, which rules out ~95% of blocks before we get to the expensive part, is most of what detection costs. Its conditions can be rewritten into an equivalent set that lines up in vector lanes, and the crate has a solver that does that for each instruction set.

3. Recompress the few blocks the filter can't rule out with the SHA-1 instructions, too.

We could in theory use the crate itself through our Rust support. But that support is optional, the crate needs a much newer Rust than we allow, and none of the three is all that much code once you know what it's doing. So let's do it in C, which helps every build.

We can't really do any of that inside sha1dc/ itself. It's third-party code (optionally a submodule), and its block loop is built around its scalar compression, which stores intermediate states as it goes. So this patch adds sha1dc-accel/, which has its own block loop but works on sha1dc's SHA1_CTX and uses its table of disturbance vectors (DVs). For each block it asks a "backend" to compress it (spilling the schedule and the two states that recompression starts from), runs the UBC filter, and then recompresses the block for each DV the filter didn't rule out.

For now there's only one backend: a portable C compression, plus sha1dc's own ubc_check(). So this is just a reshuffling of what sha1dc/ already does, and the speedups come in the following patches. It comes out a little slower. With 256MB of random data on the Xeon (GCC 13, pinned to one CPU):

Benchmark 1: test-tool.base sha1

    Time (mean ± σ):     727.3 ms ±  60.8 ms    [User: 677.2 ms, System: 40.7 ms]
    Range (min … max):   607.5 ms … 837.0 ms    30 runs

Benchmark 2: test-tool.new sha1

    Time (mean ± σ):     797.2 ms ± 115.5 ms    [User: 745.4 ms, System: 41.8 ms]
    Range (min … max):   630.5 ms … 1078.0 ms    30 runs

Summary
test-tool.base sha1 ran
1.10 ± 0.18 times faster than test-tool.new sha1

That's within the noise of this machine (which is quite noisy, sadly), but callgrind counts 2.3% more instructions for the new code, and on the M5 Max (Apple clang), hashing 1GiB goes from 1.49s to 1.55s (median of 9 runs), about 4% slower. That's a price I'm willing to pay for what comes next.

A few other notes:

- The results must be identical to sha1dc/'s: the same digest, and the same verdict on collisions. That includes the modes that Git itself doesn't use (the "safe hash" mitigation, disabling the UBC filter, and detecting reduced-round collisions). The new unit test checks exactly that against sha1dc/ for every backend the machine can run, on random data. There's only one so far, but there will be more. It also checks that sha1dc/'s table of DVs is laid out the way we expect, so that a change there fails loudly.

- Likewise, "test-tool sha1dc-backends" lists the backends, and GIT_TEST_SHA1DC_BACKEND picks one for "test-tool sha1", which lets t0013 run its collision test against each of them. While I was there I added a second collision, the SHA-mbles chosen-prefix one [3]. It trips the same disturbance vector as SHAttered, II(52,0), but it's a different kind of attack, and gets detected in the tenth block rather than the fifth.

- "test-tool sha1dc-compare" hashes a file both ways, in every combination of those modes and with the input split around each block, and dies if the two ever disagree. t0013 runs it for each backend on SHAttered, SHA-mbles and a reduced-round collision (from the crate's tests), which is the only way to exercise what happens after a collision is found. The last has no NUL byte, so t/.gitattributes marks t0013's .bin files as binary.

- The backend is picked once, on first use. Threads can race to pick it, but they'd all store the same value; with GCC and clang we use relaxed atomics for that. Other compilers only get the portable backend, so they have nothing to pick, and no shared state.

- DC_SHA1_EXTERNAL builds are left alone, since we don't know what their context looks like. For everybody else, DC_SHA1_NO_ACCEL goes back to using sha1dc/ on its own.

[1] https://sam.dev/blog/faster-sha1-collision-detection
[2] https://github.com/srijs/sha1dc
[3] https://sha-mbles.github.io/

Assisted-by Claude Opus 5.5 <[email protected]>
---
 Makefile                            |  10 +
 contrib/buildsystems/CMakeLists.txt |   2 +-
 meson.build                         |   1 +
 sha1dc-accel/internal.h             |  25 ++
 sha1dc-accel/sha1.c                 | 434 ++++++++++++++++++++++++++++
 sha1dc-accel/sha1.h                 |  31 ++
 sha1dc_git.c                        |  18 ++
 t/.gitattributes                    |   1 +
 t/helper/test-sha1.c                |  95 ++++++
 t/helper/test-tool.c                |   2 +
 t/helper/test-tool.h                |   2 +
 t/meson.build                       |   1 +
 t/t0013-sha1dc.sh                   |  47 +++
 t/t0013/sha-mbles-1.bin             | Bin 0 -> 640 bytes
 t/t0013/sha1-reduced-round.bin      | Bin 0 -> 128 bytes
 t/unit-tests/u-sha1dc.c             | 145 ++++++++++
 16 files changed, 813 insertions(+), 1 deletion(-)
 create mode 100644 sha1dc-accel/internal.h
 create mode 100644 sha1dc-accel/sha1.c
 create mode 100644 sha1dc-accel/sha1.h
 create mode 100644 t/t0013/sha-mbles-1.bin
 create mode 100644 t/t0013/sha1-reduced-round.bin
 create mode 100644 t/unit-tests/u-sha1dc.c
Makefile +10 -0
index c649c93c51..9ab13ca2ab 100644
@@ -567,6 +567,10 @@ include shared.mak
 # by the git project to migrate to using sha1collisiondetection as a
 # submodule.
 #
+# Unless DC_SHA1_EXTERNAL is defined, the built-in code is driven by the
+# block loop in sha1dc-accel/, which gives the same results.
+# Define DC_SHA1_NO_ACCEL to use the sha1collisiondetection code alone.
+#
 # === SHA-256 backend ===
 #
 # ==== Security ====
@@ -1555,6 +1559,7 @@ CLAR_TEST_SUITES += u-reftable-readwrite
 CLAR_TEST_SUITES += u-reftable-stack
 CLAR_TEST_SUITES += u-reftable-table
 CLAR_TEST_SUITES += u-reftable-tree
+CLAR_TEST_SUITES += u-sha1dc
 CLAR_TEST_SUITES += u-strbuf
 CLAR_TEST_SUITES += u-strcmp-offset
 CLAR_TEST_SUITES += u-string-list
@@ -2167,6 +2172,11 @@ ifdef DC_SHA1_SUBMODULE
 else
 	LIB_OBJS += sha1dc/sha1.o
 	LIB_OBJS += sha1dc/ubc_check.o
+endif
+ifdef DC_SHA1_NO_ACCEL
+	BASIC_CFLAGS += -DDC_SHA1_NO_ACCEL
+else
+	LIB_OBJS += sha1dc-accel/sha1.o
 endif
 	BASIC_CFLAGS += \
 		-DSHA1DC_NO_STANDARD_INCLUDES \
contrib/buildsystems/CMakeLists.txt +1 -1
index 7874e5a326..3c0ea2a27c 100644
@@ -218,7 +218,7 @@ add_compile_definitions(NO_OPENSSL SHA1_DC SHA1DC_NO_STANDARD_INCLUDES
 			SHA1DC_INIT_SAFE_HASH_DEFAULT=0
 			SHA1DC_CUSTOM_INCLUDE_SHA1_C="git-compat-util.h"
 			SHA1DC_CUSTOM_INCLUDE_UBC_CHECK_C="git-compat-util.h" )
-list(APPEND compat_SOURCES sha1dc_git.c sha1dc/sha1.c sha1dc/ubc_check.c block-sha1/sha1.c sha256/block/sha256.c compat/qsort_s.c)
+list(APPEND compat_SOURCES sha1dc_git.c sha1dc/sha1.c sha1dc/ubc_check.c sha1dc-accel/sha1.c block-sha1/sha1.c sha256/block/sha256.c compat/qsort_s.c)
 
 
 add_compile_definitions(PAGER_ENV="LESS=FRX LV=-c"
meson.build +1 -0
index 0a95d90d21..a821b85f30 100644
@@ -1631,6 +1631,7 @@ if sha1_backend == 'sha1dc'
     'sha1dc_git.c',
     'sha1dc/sha1.c',
     'sha1dc/ubc_check.c',
+    'sha1dc-accel/sha1.c',
   ]
 endif
 if sha1_backend == 'CommonCrypto' or sha1_unsafe_backend == 'CommonCrypto'
sha1dc-accel/internal.h new file +25 -0
new file mode 100644
index 0000000000..bf3513a1e3
@@ -0,0 +1,25 @@
+#ifndef SHA1DC_ACCEL_INTERNAL_H
+#define SHA1DC_ACCEL_INTERNAL_H
+
+/*
+ * Shared between the files of sha1dc-accel/. See sha1.c for an overview.
+ *
+ * The schedule `w` is always the 80 expanded message words in step order,
+ * w[t] at index t, which is also what sha1dc/ keeps in SHA1_CTX.m1.
+ *
+ * A "state" is the five working words [a, b, c, d, e] before a step.
+ */
+
+#if defined(__GNUC__)
+# define SHA1DC_NOINLINE __attribute__((noinline))
+#else
+# define SHA1DC_NOINLINE
+#endif
+
+/* The step a DV's recompression starts from. */
+enum sha1dc_from {
+	SHA1DC_FROM_58 = 58,
+	SHA1DC_FROM_65 = 65
+};
+
+#endif /* SHA1DC_ACCEL_INTERNAL_H */
sha1dc-accel/sha1.c new file +434 -0

434 lines not on this page · raw message

sha1dc-accel/sha1.h new file +31 -0
new file mode 100644
index 0000000000..53dda518f0
@@ -0,0 +1,31 @@
+#ifndef SHA1DC_ACCEL_SHA1_H
+#define SHA1DC_ACCEL_SHA1_H
+
+#if defined(DC_SHA1_SUBMODULE)
+#include "../sha1collisiondetection/lib/sha1.h"
+#else
+#include "../sha1dc/sha1.h"
+#endif
+
+/*
+ * A faster implementation of SHA-1 with collision detection, working on
+ * the SHA1_CTX of sha1dc/ (or of the sha1collisiondetection submodule).
+ * SHA1DCInit() and the SHA1DCSet*() functions set it up as usual; these
+ * then take the place of SHA1DCUpdate() and SHA1DCFinal(), with the same
+ * results. See sha1.c.
+ */
+
+void sha1dc_accel_update(SHA1_CTX *ctx, const void *data, size_t len);
+int sha1dc_accel_final(unsigned char hash[20], SHA1_CTX *ctx);
+
+/*
+ * The implementation in use, such as "shani+avx2" or "portable". For tests,
+ * sha1dc_accel_select() switches to another one by that name; it returns -1
+ * if this build or CPU does not have it. Neither is thread-safe.
+ */
+const char *sha1dc_accel_backend(void);
+int sha1dc_accel_select(const char *name);
+/* The names this build and CPU can use, NULL-terminated. */
+const char *const *sha1dc_accel_backends(void);
+
+#endif /* SHA1DC_ACCEL_SHA1_H */
sha1dc_git.c +18 -0
index fe58d7962a..03958762cf 100644
@@ -2,6 +2,15 @@
 #include "sha1dc_git.h"
 #include "hex.h"
 
+/*
+ * Unless told otherwise, hash with sha1dc-accel/, which gives the same
+ * results as sha1dc/ on the same SHA1_CTX.
+ */
+#if !defined(DC_SHA1_EXTERNAL) && !defined(DC_SHA1_NO_ACCEL)
+#include "sha1dc-accel/sha1.h"
+#define USE_SHA1DC_ACCEL
+#endif
+
 #ifdef DC_SHA1_EXTERNAL
 /*
  * Same as SHA1DCInit, but with default save_hash=0
@@ -18,8 +27,13 @@ void git_SHA1DCInit(SHA1_CTX *ctx)
  */
 void git_SHA1DCFinal(unsigned char hash[20], SHA1_CTX *ctx)
 {
+#ifdef USE_SHA1DC_ACCEL
+	if (!sha1dc_accel_final(hash, ctx))
+		return;
+#else
 	if (!SHA1DCFinal(hash, ctx))
 		return;
+#endif
 	die("SHA-1 appears to be part of a collision attack: %s",
 	    hash_to_hex_algop(hash, &hash_algos[GIT_HASH_SHA1]));
 }
@@ -29,6 +43,9 @@ void git_SHA1DCFinal(unsigned char hash[20], SHA1_CTX *ctx)
  */
 void git_SHA1DCUpdate(SHA1_CTX *ctx, const void *vdata, size_t len)
 {
+#ifdef USE_SHA1DC_ACCEL
+	sha1dc_accel_update(ctx, vdata, len);
+#else
 	const char *data = vdata;
 	while (len > INT_MAX) {
 		SHA1DCUpdate(ctx, data, INT_MAX);
@@ -36,4 +53,5 @@ void git_SHA1DCUpdate(SHA1_CTX *ctx, const void *vdata, size_t len)
 		len -= INT_MAX;
 	}
 	SHA1DCUpdate(ctx, data, len);
+#endif
 }
t/.gitattributes +1 -0
index e867f38c71..f9437159ae 100644
@@ -2,6 +2,7 @@ t[0-9][0-9][0-9][0-9]/* -whitespace
 /chainlint/*.expect eol=lf -whitespace
 /greplint/*.expect eol=lf -whitespace
 /greplint/*.test eol=lf -whitespace
+/t0013/*.bin binary
 /t0110/url-* binary
 /t3206/* eol=lf
 /t3900/*.txt eol=lf
t/helper/test-sha1.c +95 -0

109 lines not on this page · raw message

t/helper/test-tool.c +2 -0
index b71a22b43b..c459218f0b 100644
@@ -73,6 +73,8 @@ static struct test_cmd cmds[] = {
 	{ "serve-v2", cmd__serve_v2 },
 	{ "sha1", cmd__sha1 },
 	{ "sha1-is-sha1dc", cmd__sha1_is_sha1dc },
+	{ "sha1dc-backends", cmd__sha1dc_backends },
+	{ "sha1dc-compare", cmd__sha1dc_compare },
 	{ "sha1-unsafe", cmd__sha1_unsafe },
 	{ "sha256", cmd__sha256 },
 	{ "sigchain", cmd__sigchain },
t/helper/test-tool.h +2 -0
index f2885b33d5..f0cdbddcdf 100644
@@ -66,6 +66,8 @@ int cmd__scrap_cache_tree(int argc, const char **argv);
 int cmd__serve_v2(int argc, const char **argv);
 int cmd__sha1(int argc, const char **argv);
 int cmd__sha1_is_sha1dc(int argc, const char **argv);
+int cmd__sha1dc_backends(int argc, const char **argv);
+int cmd__sha1dc_compare(int argc, const char **argv);
 int cmd__sha1_unsafe(int argc, const char **argv);
 int cmd__sha256(int argc, const char **argv);
 int cmd__sigchain(int argc, const char **argv);
t/meson.build +1 -0
index 3ca7b27104..ec25f0de40 100644
@@ -20,6 +20,7 @@ clar_test_suites = [
   'unit-tests/u-reftable-stack.c',
   'unit-tests/u-reftable-table.c',
   'unit-tests/u-reftable-tree.c',
+  'unit-tests/u-sha1dc.c',
   'unit-tests/u-strbuf.c',
   'unit-tests/u-strcmp-offset.c',
   'unit-tests/u-string-list.c',
t/t0013-sha1dc.sh +47 -0

51 lines not on this page · raw message

t/t0013/sha-mbles-1.bin new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..5a7c30e97646c66422abe0a9793a5fcb9f1cf8d6
GIT binary patch
t/t0013/sha1-reduced-round.bin new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..4623336222bd5c9e7b1b0e244a5897430c1b5c12
GIT binary patch
t/unit-tests/u-sha1dc.c new file +145 -0

145 lines not on this page · raw message

Signature · 1 line
2.50.1 (Apple Git-155)
#3 lore raw

PATCH 2/4 sha1dc-accel: vectorize the unavoidable-bitconditions check

In reply to Scott Chacon

After compressing a block, sha1dc checks its expanded message schedule against the "unavoidable bitconditions" (UBCs) of each of its 32 disturbance vectors (DVs). Each condition says that one bit of W[i] XORed with one bit of W[j] must have a particular value if an attack along that DV is in progress. A failed condition rules out its DVs, and if all 32 are ruled out, which happens for about 95% of blocks, we can skip the expensive recompression.

That makes the check a cheap filter, but it's cheap only compared to recompressing. It's 111 scalar statements, of which 47 run for every block, and the rest sit behind tests of whether their DVs are still alive. On this machine it takes about half as long as the compression itself.

The conditions for any one DV aren't a fixed list, though. They're equations over the bits of the schedule, and equations chain: if bit A must equal bit B, and B must equal C, then A must equal C. So each DV really has a whole space of equivalent condition sets. The generator that wrote sha1dc's ubc_check.c picked conditions that are shared by many DVs, which is the right thing for scalar code. But a vector unit can check 4 (or 8) conditions in a single pair of loads if they have the same shape: the same distance between the two words, the same bit positions, at consecutive values of i. That wants a different choice.

The sha1dc Rust crate has a solver that makes that choice for each instruction set. It picks a "prefix" of vector groups that runs on every block, sized so that it rules out as many blocks as possible for what it costs, and leaves the remaining conditions to a scalar "tail" that only runs for DVs the prefix left alive. Its plans work out roughly like this (the last column is the solver's estimate for random blocks):

  form    prefix               tail   blocks reaching tail
  scalar  70 statements        86     21%
  sse2    26 groups of 4       58      9%
  avx2    16 groups of 8       44      7%
  neon    20 groups of 4       77     17%

The crate only emits Rust, so ubc_check.c carries its plans over as
tables: for each form, the conditions of its prefix (as one entry per vector group, giving the two words, their shifts, and the bit and DVs of each lane), and the remaining conditions of each DV for its tail. The code that runs them is a short loop per form. We ask the compiler to unroll the prefix loops fully, so that each table entry turns back into immediates; without that, the forms are 2.2x to 2.4x slower with GCC and 1.3x to 3.6x slower with clang. With it, GCC's build of the tables runs the same number of instructions as the crate's plans written out as straight-line code, at the same speed. The exception so far is clang 18 on x86-64, where the scalar form runs at half that speed (68ns a block instead of 34ns), since it spills partial masks to the stack. That form is only the fallback for CPUs without SSE2 or NEON, and Apple clang 21 does not do this.

The tables come from the crate as of commit 426b4afd. The crate is MIT or Apache-2.0 at your option (sha1collisiondetection itself is MIT); we use the tables under the MIT license, and the file carries its notice. Note that the crate stores its schedule backwards on x86 (to save a shuffle in its SHA-NI code), where we keep it in step order everywhere, so our SSE2 and AVX2 tables list their lanes in the opposite order from the crate's.

We now have these backends, in order of preference:

- portable+avx2: if the CPU has AVX2 (and the OS saves the YMM registers, which we check with xgetbv)

- portable+sse2: always on x86-64, where SSE2 is part of the ABI

- portable+neon: always on arm64

- portable: everywhere else, which still gets the new scalar form

The vector forms need target attributes and intrinsics, so for now they're only built with GCC 5 or newer and clang. Other compilers (and 32-bit x86, where SSE2 isn't a given) get only the portable one.

With 256MB of random data again, the Xeon picks portable+avx2:

Benchmark 1: test-tool.old sha1

    Time (mean ± σ):     801.1 ms ±  82.9 ms    [User: 750.1 ms, System: 40.3 ms]
    Range (min … max):   673.1 ms … 1006.1 ms    30 runs

Benchmark 2: test-tool.new sha1

    Time (mean ± σ):     620.4 ms ± 111.2 ms    [User: 571.0 ms, System: 41.9 ms]
    Range (min … max):   486.4 ms … 857.2 ms    30 runs

Summary
test-tool.new sha1 ran
1.29 ± 0.27 times faster than test-tool.old sha1

and callgrind counts 16% fewer instructions than before this patch. The M5 Max picks portable+neon, and hashes 1GiB in 1.22s instead of 1.55s (median of 9 runs), 1.27x faster.

For testing, the unit test compares every form against sha1dc's own ubc_check(). Random schedules aren't enough, though: the prefix rules out most of them, so the tail checks for any one DV would hardly ever run. So for each DV, the test also generates random schedules until one keeps that DV alive, and then compares all forms on it with each of its 2560 bits flipped in turn. That's the same approach the crate takes (and sha1collisiondetection's own tools before it).

Outside of the test suite, I also checked every form against ubc_check() on a million random schedules and 256 of those witnesses: built with GCC 13 and clang 18 on x86-64, with Apple clang on arm64 (and with it targeting x86-64, running the SSE2 form under Rosetta and the AVX2 one translated to NEON by SIMDe), and with GCC and clang for aarch64 under qemu.

Assisted-by Claude Opus 5.5 <[email protected]>
---
 Makefile                            |    5 +-
 contrib/buildsystems/CMakeLists.txt |    2 +-
 meson.build                         |    2 +
 sha1dc-accel/internal.h             |   49 +
 sha1dc-accel/sha1.c                 |   47 +-
 sha1dc-accel/ubc_check.c            | 1789 +++++++++++++++++++++++++++
 sha1dc-accel/x86.c                  |   38 +
 t/unit-tests/u-sha1dc.c             |   75 ++
 8 files changed, 1985 insertions(+), 22 deletions(-)
 create mode 100644 sha1dc-accel/ubc_check.c
 create mode 100644 sha1dc-accel/x86.c
Makefile +4 -1
index 9ab13ca2ab..3ad8a7fc92 100644
@@ -568,7 +568,8 @@ include shared.mak
 # submodule.
 #
 # Unless DC_SHA1_EXTERNAL is defined, the built-in code is driven by the
-# block loop in sha1dc-accel/, which gives the same results.
+# faster implementation in sha1dc-accel/, which gives the same results
+# using the CPU's vector units where it has them.
 # Define DC_SHA1_NO_ACCEL to use the sha1collisiondetection code alone.
 #
 # === SHA-256 backend ===
@@ -2177,6 +2178,8 @@ ifdef DC_SHA1_NO_ACCEL
 	BASIC_CFLAGS += -DDC_SHA1_NO_ACCEL
 else
 	LIB_OBJS += sha1dc-accel/sha1.o
+	LIB_OBJS += sha1dc-accel/ubc_check.o
+	LIB_OBJS += sha1dc-accel/x86.o
 endif
 	BASIC_CFLAGS += \
 		-DSHA1DC_NO_STANDARD_INCLUDES \
contrib/buildsystems/CMakeLists.txt +1 -1
index 3c0ea2a27c..67b96d601b 100644
@@ -218,7 +218,7 @@ add_compile_definitions(NO_OPENSSL SHA1_DC SHA1DC_NO_STANDARD_INCLUDES
 			SHA1DC_INIT_SAFE_HASH_DEFAULT=0
 			SHA1DC_CUSTOM_INCLUDE_SHA1_C="git-compat-util.h"
 			SHA1DC_CUSTOM_INCLUDE_UBC_CHECK_C="git-compat-util.h" )
-list(APPEND compat_SOURCES sha1dc_git.c sha1dc/sha1.c sha1dc/ubc_check.c sha1dc-accel/sha1.c block-sha1/sha1.c sha256/block/sha256.c compat/qsort_s.c)
+list(APPEND compat_SOURCES sha1dc_git.c sha1dc/sha1.c sha1dc/ubc_check.c sha1dc-accel/sha1.c sha1dc-accel/ubc_check.c sha1dc-accel/x86.c block-sha1/sha1.c sha256/block/sha256.c compat/qsort_s.c)
 
 
 add_compile_definitions(PAGER_ENV="LESS=FRX LV=-c"
meson.build +2 -0
index a821b85f30..47a60526e9 100644
@@ -1632,6 +1632,8 @@ if sha1_backend == 'sha1dc'
     'sha1dc/sha1.c',
     'sha1dc/ubc_check.c',
     'sha1dc-accel/sha1.c',
+    'sha1dc-accel/ubc_check.c',
+    'sha1dc-accel/x86.c',
   ]
 endif
 if sha1_backend == 'CommonCrypto' or sha1_unsafe_backend == 'CommonCrypto'
sha1dc-accel/internal.h +49 -0

63 lines not on this page · raw message

sha1dc-accel/sha1.c +27 -20

64 lines not on this page · raw message

sha1dc-accel/ubc_check.c new file +1789 -0

1,789 lines not on this page · raw message

sha1dc-accel/x86.c new file +38 -0
new file mode 100644
index 0000000000..7c942fe4de
@@ -0,0 +1,38 @@
+/*
+ * The x86-64 parts of sha1.c: detecting what the CPU has.
+ */
+
+#include "../git-compat-util.h"
+#include "internal.h"
+
+#ifdef SHA1DC_HAVE_SSE2
+
+#include <cpuid.h>
+
+/* Leaf 7 of CPUID, subleaf 0, if the CPU has it. */
+static int cpuid_7(unsigned int *ebx)
+{
+	unsigned int eax, ecx, edx;
+
+	if (__get_cpuid_max(0, NULL) < 7)
+		return 0;
+	__cpuid_count(7, 0, eax, *ebx, ecx, edx);
+	return 1;
+}
+
+int sha1dc_avx2_available(void)
+{
+	unsigned int eax, ebx, ecx, edx, xcr0_lo, xcr0_hi;
+
+	if (!__get_cpuid(1, &eax, &ebx, &ecx, &edx))
+		return 0;
+	/* OSXSAVE and AVX, then whether the OS saves the YMM registers. */
+	if ((ecx & (1u << 27 | 1u << 28)) != (1u << 27 | 1u << 28))
+		return 0;
+	__asm__("xgetbv" : "=a"(xcr0_lo), "=d"(xcr0_hi) : "c"(0));
+	if ((xcr0_lo & 6) != 6)
+		return 0;
+	return cpuid_7(&ebx) && (ebx & (1u << 5));
+}
+
+#endif /* SHA1DC_HAVE_SSE2 */
t/unit-tests/u-sha1dc.c +75 -0

84 lines not on this page · raw message

Signature · 1 line
2.50.1 (Apple Git-155)
#6 lore raw

PATCH 3/4 sha1dc-accel: compress with SHA-NI on x86-64

In reply to Scott Chacon

With the UBC check out of the way, most of what's left is the SHA-1 compression itself, which we still do in portable C. Most x86-64 CPUs from the last several years (Intel since Ice Lake and some Atoms, AMD since Zen) have instructions for that: sha1rnds4 does four rounds at a time, and sha1msg1/sha1msg2 do the message expansion.

There are two catches. The first is that the detection needs the expanded schedule, which the instructions keep to themselves. That's easy enough: as each group of four words is used, we store it (with a shuffle, since SHA-NI holds them in reverse order). Words 16 to 31 come from sha1msg1/sha1msg2, and the rest from the recurrence

W[t] = (W[t-6] ^ W[t-16] ^ W[t-28] ^ W[t-32]) <<< 2

in plain SSE, in which no word of a group depends on another. That's what the crate does, too; it notes that sha1msg2 is microcoded on Sapphire Rapids, where this runs about 10% faster.

The second catch is that the recompression starts from the working state before step 58 or step 65, and the instructions only let us see the state between groups of four steps. But the state at step 60 is just two steps away from 58, and 64 is one step from 65. So we save those two for every block, and only for a block that the filter flags (about one in twenty) do we walk them the rest of the way.

While we're here, we can do the recompression of those flagged blocks with the SHA-1 instructions, too. The portable code runs the partner block backwards from its state at 58 or 65 to find the chaining value it started from, then forwards to find the one it ends on, and compares that with ours. But the instructions only go forwards. So instead we run the partner forwards from step 60 or 64 to step 80, which tells us the only input chaining value that could produce our output (it's the output minus the state at 80, since the feed-forward is just addition). Then we run forwards from that input to step 60 or 64 and see if we arrive back where we started. Since each step is a bijection, that's the same test.

The exception is reduced-round detection, which also wants to know the partner's input chaining value for its own sake. Git never turns that on, so it just keeps using the portable recompression.

We check for SHA-NI (plus SSSE3 and SSE4.1, which the code also needs) with cpuid when we pick a backend, and compile with target attributes, so there's nothing to configure. That gives two new backends in front of the others, shani+avx2 and shani+sse2, which differ only in the UBC check.

The unit test gains a check of the compression against SHA-1 steps written out in the test itself, and of the recompression, which must accept the partner's real output and reject any other.

With the usual 256MB of random data (the Xeon picks shani+avx2):

Benchmark 1: test-tool.old sha1

    Time (mean ± σ):     590.3 ms ±  83.8 ms    [User: 541.0 ms, System: 42.6 ms]
    Range (min … max):   440.2 ms … 750.7 ms    30 runs

Benchmark 2: test-tool.new sha1

    Time (mean ± σ):     285.2 ms ±  26.0 ms    [User: 238.9 ms, System: 42.1 ms]
    Range (min … max):   223.9 ms … 341.5 ms    30 runs

Summary
test-tool.new sha1 ran
2.07 ± 0.35 times faster than test-tool.old sha1

That makes the whole series so far 2.70 ± 0.35 times faster than plain sha1dc/ on this machine. Or, for index-pack on the 208MB pack of a clone of git.git, single-threaded:

  Benchmark 1: git.old index-pack --threads=1
    Time (mean ± σ):     24.301 s ±  1.102 s    [User: 23.739 s, System: 0.219 s]
    Range (min … max):   23.557 s … 26.215 s    5 runs

  Benchmark 2: git.new index-pack --threads=1
    Time (mean ± σ):     12.689 s ±  0.385 s    [User: 12.293 s, System: 0.197 s]
    Range (min … max):   12.274 s … 13.226 s    5 runs

  Summary
    git.new index-pack --threads=1 ran
      1.92 ± 0.10 times faster than git.old index-pack --threads=1

and with 4 threads:

  Benchmark 1: git.old index-pack --threads=4
    Time (mean ± σ):     10.450 s ±  0.445 s    [User: 27.147 s, System: 0.497 s]
    Range (min … max):    9.853 s … 10.782 s    5 runs

  Benchmark 2: git.new index-pack --threads=4
    Time (mean ± σ):      5.924 s ±  0.214 s    [User: 12.693 s, System: 0.527 s]
    Range (min … max):    5.591 s …  6.185 s    5 runs

  Summary
    git.new index-pack --threads=4 ran
      1.76 ± 0.10 times faster than git.old index-pack --threads=4

Hashing in-process, shani+avx2 runs at 900 to 1050 MiB/s for messages of 1KiB and up, against 1130 to 1230 MiB/s for OpenSSL's SHA-1 (which doesn't detect collisions at all) and 420 to 450 MiB/s for sha1dc/. The full test suite passes on this machine, as do t0013 and the unit tests for each of its five backends.

Assisted-by Claude Opus 5.5 <[email protected]>
---
 Makefile                |   2 +-
 sha1dc-accel/internal.h |  28 +++++
 sha1dc-accel/sha1.c     | 105 ++++++++++++++-----
 sha1dc-accel/x86.c      | 224 +++++++++++++++++++++++++++++++++++++++-
 t/unit-tests/u-sha1dc.c | 141 ++++++++++++++++++++++++-
 5 files changed, 471 insertions(+), 29 deletions(-)
Makefile +1 -1
index 3ad8a7fc92..8181ea5692 100644
@@ -569,7 +569,7 @@ include shared.mak
 #
 # Unless DC_SHA1_EXTERNAL is defined, the built-in code is driven by the
 # faster implementation in sha1dc-accel/, which gives the same results
-# using the CPU's vector units where it has them.
+# using the CPU's SHA-1 instructions and vector units where it has them.
 # Define DC_SHA1_NO_ACCEL to use the sha1collisiondetection code alone.
 #
 # === SHA-256 backend ===
sha1dc-accel/internal.h +28 -0
index 03427224da..a27fda19d1 100644
@@ -19,9 +19,11 @@
 # if defined(__x86_64__) && (defined(__clang__) || __GNUC__ >= 5)
 #  define SHA1DC_HAVE_SSE2 1
 #  define SHA1DC_HAVE_AVX2 1
+#  define SHA1DC_HAVE_SHANI 1
 #  include <immintrin.h>
 #  define SHA1DC_TARGET_SSE2
 #  define SHA1DC_TARGET_AVX2 __attribute__((target("avx2")))
+#  define SHA1DC_TARGET_SHANI __attribute__((target("sha,sse4.1,ssse3")))
 # elif defined(__aarch64__) && defined(__ARM_NEON)
 #  define SHA1DC_HAVE_NEON 1
 #  include <arm_neon.h>
@@ -71,4 +73,30 @@ uint32_t sha1dc_ubc_check_neon(const uint32_t w[80]);
 int sha1dc_avx2_available(void);
 #endif
 
+/*
+ * The state the partner block of a DV reaches at the group boundary next to
+ * where its recompression starts: step 60 from step 58, step 64 from step
+ * 65. `state` is this block's state at `from`. In sha1.c.
+ */
+void sha1dc_partner_boundary(enum sha1dc_from from, const uint32_t m1[80],
+			     const uint32_t dm[80], const uint32_t state[5],
+			     uint32_t out[5]);
+
+/*
+ * The hardware compression. It compresses one 64-byte block into `ihv`,
+ * writes the expanded schedule to `w`, and this block's own states at
+ * steps 60 and 64 to `at_60` and `at_64`.
+ *
+ * Its recompression answers whether a DV candidate is really an attack,
+ * running the partner block forwards from `state` (this block's state at
+ * `from`) with the SHA-1 instructions.
+ */
+#ifdef SHA1DC_HAVE_SHANI
+int sha1dc_shani_available(void);
+void sha1dc_compress_shani(uint32_t ihv[5], const unsigned char *block,
+			   uint32_t w[80], uint32_t at_60[5], uint32_t at_64[5]);
+int sha1dc_recompress_shani(enum sha1dc_from from, const uint32_t m1[80],
+			    const uint32_t dm[80], const uint32_t state[5],
+			    const uint32_t ihv_out[5]);
+#endif
 #endif /* SHA1DC_ACCEL_INTERNAL_H */
sha1dc-accel/sha1.c +79 -26

181 lines not on this page · raw message

sha1dc-accel/x86.c +223 -1

232 lines not on this page · raw message

t/unit-tests/u-sha1dc.c +140 -1

156 lines not on this page · raw message

Signature · 1 line
2.50.1 (Apple Git-155)
#7 lore raw

PATCH 4/4 sha1dc-accel: compress with the ARMv8 SHA-1 instructions

In reply to Scott Chacon

Most arm64 CPUs, including Apple's and the Graviton line, have SHA-1 instructions, too, and we can use them the same way as SHA-NI in the previous patch. It's a little simpler here: the instructions keep the working state in the natural order, and vsha1h gives us the fifth word directly, so there's no shuffling to be done.

Knowing whether we can use them is a little trickier:

- If the compiler targets them already (__ARM_FEATURE_SHA2 or __ARM_FEATURE_CRYPTO, which is the case with Apple's clang on macOS), we just use them.

- Otherwise we build the two functions that need them with a target attribute, and check at run time. On Linux that's getauxval(); on other platforms we don't know how to ask yet, and so don't use them.

- Older compilers only declare the intrinsics when the whole file targets the instructions, so a target attribute doesn't help there. We only try the attribute with GCC 9+ and clang 17+.

The one new backend, armv8+neon, goes to the front of the list.

On an Apple M5 Max (macOS, Apple clang), which picks armv8+neon, hashing 1GiB of random data with "test-tool sha1" (median of 9 runs) goes:

  sha1dc, before this series        1.46s   (~700 MiB/s)
  block loop, after 1/4             1.55s
  portable+neon, after 2/4          1.22s
  armv8+neon, this patch            0.51s   (~2 GiB/s)

which is 2.85x overall. For index-pack of the 319MB pack of a clone of git.git, it goes from 16.1s to 8.7s single-threaded (1.86x), and from 6.7s to 5.9s with all 18 threads. The full test suite passes there, too. For comparison, the crate reports 81% of plain SHA-1's throughput on an Apple M4 and 80% on a Graviton4, up from 29% [1].

The run-time check on Linux is only tested under qemu-user so far, built with GCC 13 and clang 18, in a harness that compares every backend and UBC form against sha1dc/ (the same comparisons as the unit tests). I'd be happy to see numbers from anybody with a Graviton or similar machine.

[1] https://sam.dev/blog/faster-sha1-collision-detection

Assisted-by Claude Opus 5.5 <[email protected]>
---
 Makefile                            |   1 +
 contrib/buildsystems/CMakeLists.txt |   2 +-
 meson.build                         |   1 +
 sha1dc-accel/arm.c                  | 274 ++++++++++++++++++++++++++++
 sha1dc-accel/internal.h             |  28 ++-
 sha1dc-accel/sha1.c                 |   6 +-
 t/unit-tests/u-sha1dc.c             |   9 +-
 7 files changed, 316 insertions(+), 5 deletions(-)
 create mode 100644 sha1dc-accel/arm.c
Makefile +1 -0
index 8181ea5692..731a5f60e8 100644
@@ -2177,6 +2177,7 @@ endif
 ifdef DC_SHA1_NO_ACCEL
 	BASIC_CFLAGS += -DDC_SHA1_NO_ACCEL
 else
+	LIB_OBJS += sha1dc-accel/arm.o
 	LIB_OBJS += sha1dc-accel/sha1.o
 	LIB_OBJS += sha1dc-accel/ubc_check.o
 	LIB_OBJS += sha1dc-accel/x86.o
contrib/buildsystems/CMakeLists.txt +1 -1
index 67b96d601b..37ebb67a8d 100644
@@ -218,7 +218,7 @@ add_compile_definitions(NO_OPENSSL SHA1_DC SHA1DC_NO_STANDARD_INCLUDES
 			SHA1DC_INIT_SAFE_HASH_DEFAULT=0
 			SHA1DC_CUSTOM_INCLUDE_SHA1_C="git-compat-util.h"
 			SHA1DC_CUSTOM_INCLUDE_UBC_CHECK_C="git-compat-util.h" )
-list(APPEND compat_SOURCES sha1dc_git.c sha1dc/sha1.c sha1dc/ubc_check.c sha1dc-accel/sha1.c sha1dc-accel/ubc_check.c sha1dc-accel/x86.c block-sha1/sha1.c sha256/block/sha256.c compat/qsort_s.c)
+list(APPEND compat_SOURCES sha1dc_git.c sha1dc/sha1.c sha1dc/ubc_check.c sha1dc-accel/arm.c sha1dc-accel/sha1.c sha1dc-accel/ubc_check.c sha1dc-accel/x86.c block-sha1/sha1.c sha256/block/sha256.c compat/qsort_s.c)
 
 
 add_compile_definitions(PAGER_ENV="LESS=FRX LV=-c"
meson.build +1 -0
index 47a60526e9..7aed4db1ba 100644
@@ -1631,6 +1631,7 @@ if sha1_backend == 'sha1dc'
     'sha1dc_git.c',
     'sha1dc/sha1.c',
     'sha1dc/ubc_check.c',
+    'sha1dc-accel/arm.c',
     'sha1dc-accel/sha1.c',
     'sha1dc-accel/ubc_check.c',
     'sha1dc-accel/x86.c',
sha1dc-accel/arm.c new file +274 -0

274 lines not on this page · raw message

sha1dc-accel/internal.h +26 -2
index a27fda19d1..a50b294b96 100644
@@ -27,6 +27,21 @@
 # elif defined(__aarch64__) && defined(__ARM_NEON)
 #  define SHA1DC_HAVE_NEON 1
 #  include <arm_neon.h>
+/*
+ * The SHA-1 instructions, where the compiler targets them already or can
+ * enable them for one function: older compilers declare their intrinsics
+ * only when the whole file targets them.
+ */
+#  if defined(__ARM_FEATURE_SHA2) || defined(__ARM_FEATURE_CRYPTO)
+#   define SHA1DC_HAVE_ARMV8 1
+#   define SHA1DC_TARGET_ARMV8
+#  elif defined(__clang__) && __clang_major__ >= 17
+#   define SHA1DC_HAVE_ARMV8 1
+#   define SHA1DC_TARGET_ARMV8 __attribute__((target("sha2")))
+#  elif !defined(__clang__) && __GNUC__ >= 9
+#   define SHA1DC_HAVE_ARMV8 1
+#   define SHA1DC_TARGET_ARMV8 __attribute__((target("+crypto")))
+#  endif
 # endif
 #endif
 
@@ -83,11 +98,11 @@ void sha1dc_partner_boundary(enum sha1dc_from from, const uint32_t m1[80],
 			     uint32_t out[5]);
 
 /*
- * The hardware compression. It compresses one 64-byte block into `ihv`,
+ * The hardware compressions. Each compresses one 64-byte block into `ihv`,
  * writes the expanded schedule to `w`, and this block's own states at
  * steps 60 and 64 to `at_60` and `at_64`.
  *
- * Its recompression answers whether a DV candidate is really an attack,
+ * Their recompressions answer whether a DV candidate is really an attack,
  * running the partner block forwards from `state` (this block's state at
  * `from`) with the SHA-1 instructions.
  */
@@ -99,4 +114,13 @@ int sha1dc_recompress_shani(enum sha1dc_from from, const uint32_t m1[80],
 			    const uint32_t dm[80], const uint32_t state[5],
 			    const uint32_t ihv_out[5]);
 #endif
+#ifdef SHA1DC_HAVE_ARMV8
+int sha1dc_armv8_available(void);
+void sha1dc_compress_armv8(uint32_t ihv[5], const unsigned char *block,
+			   uint32_t w[80], uint32_t at_60[5], uint32_t at_64[5]);
+int sha1dc_recompress_armv8(enum sha1dc_from from, const uint32_t m1[80],
+			    const uint32_t dm[80], const uint32_t state[5],
+			    const uint32_t ihv_out[5]);
+#endif
+
 #endif /* SHA1DC_ACCEL_INTERNAL_H */
sha1dc-accel/sha1.c +5 -1
index 2f30b207db..1f1133169b 100644
@@ -8,7 +8,7 @@
  * Sam Reis (https://github.com/srijs/sha1dc), which gitoxide uses:
  *
  *  - The compression runs on the CPU's SHA-1 instructions where it has them
- *    (SHA-NI on x86-64), and
+ *    (SHA-NI on x86-64, the ARMv8 cryptography extension on arm64), and
  *    spills the expanded message schedule as it goes, which is all that
  *    detection needs from an ordinary block. The hardware keeps no
  *    intermediate states around, so the two states that recompression
@@ -264,6 +264,10 @@ static const struct backend backends[] = {
 	{ "shani+sse2", sha1dc_compress_shani, 1, sha1dc_ubc_check_sse2,
 	  sha1dc_recompress_shani, sha1dc_shani_available },
 #endif
+#ifdef SHA1DC_HAVE_ARMV8
+	{ "armv8+neon", sha1dc_compress_armv8, 1, sha1dc_ubc_check_neon,
+	  sha1dc_recompress_armv8, sha1dc_armv8_available },
+#endif
 #ifdef SHA1DC_HAVE_AVX2
 	{ "portable+avx2", compress_portable, 0, sha1dc_ubc_check_avx2, NULL,
 	  sha1dc_avx2_available },
t/unit-tests/u-sha1dc.c +8 -1
index 5948466cb9..f629f59d1d 100644
@@ -197,7 +197,7 @@ static void ubc_forms_agree_with_sha1dc(void)
 	}
 }
 
-#ifdef SHA1DC_HAVE_SHANI
+#if defined(SHA1DC_HAVE_SHANI) || defined(SHA1DC_HAVE_ARMV8)
 
 static uint32_t rol(uint32_t x, int n)
 {
@@ -325,6 +325,13 @@ static void hardware_compression(void)
 		check_recompress(sha1dc_recompress_shani);
 		tested = 1;
 	}
+#endif
+#ifdef SHA1DC_HAVE_ARMV8
+	if (sha1dc_armv8_available()) {
+		check_compress(sha1dc_compress_armv8);
+		check_recompress(sha1dc_recompress_armv8);
+		tested = 1;
+	}
 #endif
 	if (!tested)
 		cl_skip();
Signature · 1 line
2.50.1 (Apple Git-155)
#2 lore raw

Re: [PATCH 1/4] sha1dc-accel: add a block loop for sha1dc's SHA1_CTX

In reply to Scott Chacon

Hi Scott,

Quoted 35 lines · Scott Chacon
sha1dc-accel/sha1.c new file +29 -0
new file mode 100644
index 0000000000..fd75289997
@@ -0,0 +1,434 @@
+/*
+ * SHA-1 with collision detection.
+ *
+ * This computes exactly what sha1dc/ computes: the SHA-1 digest of the
+ * input, and whether any block of it looks like one half of a collision
+ * made by one of the 32 known disturbance vectors (DVs) of Stevens and
+ * Shumow. It works on sha1dc's SHA1_CTX, and uses its table of DVs, but
+ * has its own block loop, which gives the following patches room to
+ * follow the approach of the "sha1dc" Rust crate by Sam Reis
+ * (https://github.com/srijs/sha1dc), which gitoxide uses.
+ *
+ * Each block is compressed by a "backend", which also spills the expanded
+ * message schedule, and the two intermediate states that recompression
+ * starts from (at steps 58 and 65). The unavoidable-bitconditions (UBC)
+ * filter then rules out about 95% of blocks; the rest are recompressed,
+ * once for each DV the filter could not rule out.
+ */
+
+#include "../git-compat-util.h"
+#include "../sha1dc_git.h"
+#if defined(DC_SHA1_SUBMODULE)
+#include "../sha1collisiondetection/lib/ubc_check.h"
+#else
+#include "../sha1dc/ubc_check.h"
+#endif
+#include "sha1.h"
+#include "internal.h"
+
+#define ROL(x, n) (((x) << (n)) | ((x) >> (32 - (n))))

sha1dc-accel/sha1.c line 39

Quoted 10 lines
sha1dc-accel/sha1.c new file +10 -0
+
+#define F_CH(b, c, d) ((d) ^ ((b) & ((c) ^ (d))))
+#define F_PARITY(b, c, d) ((b) ^ (c) ^ (d))
+#define F_MAJ(b, c, d) (((b) & (c)) | ((d) & ((b) | (c))))
+
+#define K0 0x5A827999
+#define K1 0x6ED9EBA1
+#define K2 0x8F1BBCDC
+#define K3 0xCA62C1D6
+

The following lines, including the definition of compress_portable(), duplicate the functionality implemented in sha1_compression_states() in sha1dc/. Maybe we could use that latter function here, too, to make the code DRYer?

Quoted 75 lines
sha1dc-accel/sha1.c new file +75 -0
+/*
+ * One step, on names that rotate: after it, (e, a, b, c, d) are the new
+ * (a, b, c, d, e).
+ */
+#define STEP(f, k, a, b, c, d, e, x) \
+	do { \
+		e += ROL(a, 5) + f(b, c, d) + (k) + (x); \
+		b = ROL(b, 30); \
+	} while (0)
+
+#define LOAD(t) (w[t] = get_be32(block + 4 * (t)))
+#define EXPAND(t) (w[t] = ROL(w[(t) - 3] ^ w[(t) - 8] ^ w[(t) - 14] ^ w[(t) - 16], 1))
+
+#define FIVE_LOAD(f, k, a, b, c, d, e, t) \
+	do { \
+		STEP(f, k, a, b, c, d, e, LOAD(t)); \
+		STEP(f, k, e, a, b, c, d, LOAD((t) + 1)); \
+		STEP(f, k, d, e, a, b, c, LOAD((t) + 2)); \
+		STEP(f, k, c, d, e, a, b, LOAD((t) + 3)); \
+		STEP(f, k, b, c, d, e, a, LOAD((t) + 4)); \
+	} while (0)
+
+#define FIVE_EXPAND(f, k, a, b, c, d, e, t) \
+	do { \
+		STEP(f, k, a, b, c, d, e, EXPAND(t)); \
+		STEP(f, k, e, a, b, c, d, EXPAND((t) + 1)); \
+		STEP(f, k, d, e, a, b, c, EXPAND((t) + 2)); \
+		STEP(f, k, c, d, e, a, b, EXPAND((t) + 3)); \
+		STEP(f, k, b, c, d, e, a, EXPAND((t) + 4)); \
+	} while (0)
+
+/*
+ * The portable compression. Like the hardware ones it spills the schedule,
+ * but it writes the states at steps 58 and 65 directly, on the way past.
+ */
+static void compress_portable(uint32_t ihv[5], const unsigned char *block,
+			      uint32_t w[80], uint32_t state_58[5],
+			      uint32_t state_65[5])
+{
+	uint32_t a = ihv[0], b = ihv[1], c = ihv[2], d = ihv[3], e = ihv[4];
+
+	FIVE_LOAD(F_CH, K0, a, b, c, d, e, 0);
+	FIVE_LOAD(F_CH, K0, a, b, c, d, e, 5);
+	FIVE_LOAD(F_CH, K0, a, b, c, d, e, 10);
+	STEP(F_CH, K0, a, b, c, d, e, LOAD(15));
+	STEP(F_CH, K0, e, a, b, c, d, EXPAND(16));
+	STEP(F_CH, K0, d, e, a, b, c, EXPAND(17));
+	STEP(F_CH, K0, c, d, e, a, b, EXPAND(18));
+	STEP(F_CH, K0, b, c, d, e, a, EXPAND(19));
+
+	FIVE_EXPAND(F_PARITY, K1, a, b, c, d, e, 20);
+	FIVE_EXPAND(F_PARITY, K1, a, b, c, d, e, 25);
+	FIVE_EXPAND(F_PARITY, K1, a, b, c, d, e, 30);
+	FIVE_EXPAND(F_PARITY, K1, a, b, c, d, e, 35);
+
+	FIVE_EXPAND(F_MAJ, K2, a, b, c, d, e, 40);
+	FIVE_EXPAND(F_MAJ, K2, a, b, c, d, e, 45);
+	FIVE_EXPAND(F_MAJ, K2, a, b, c, d, e, 50);
+	STEP(F_MAJ, K2, a, b, c, d, e, EXPAND(55));
+	STEP(F_MAJ, K2, e, a, b, c, d, EXPAND(56));
+	STEP(F_MAJ, K2, d, e, a, b, c, EXPAND(57));
+	state_58[0] = c;
+	state_58[1] = d;
+	state_58[2] = e;
+	state_58[3] = a;
+	state_58[4] = b;
+	STEP(F_MAJ, K2, c, d, e, a, b, EXPAND(58));
+	STEP(F_MAJ, K2, b, c, d, e, a, EXPAND(59));
+
+	FIVE_EXPAND(F_PARITY, K3, a, b, c, d, e, 60);
+	state_65[0] = a;
+	state_65[1] = b;
+	state_65[2] = c;
+	state_65[3] = d;
+	state_65[4] = e;

sha1dc-accel/sha1.c line 124

Quoted 10 lines
sha1dc-accel/sha1.c new file +10 -0
+	FIVE_EXPAND(F_PARITY, K3, a, b, c, d, e, 65);
+	FIVE_EXPAND(F_PARITY, K3, a, b, c, d, e, 70);
+	FIVE_EXPAND(F_PARITY, K3, a, b, c, d, e, 75);
+
+	ihv[0] += a;
+	ihv[1] += b;
+	ihv[2] += c;
+	ihv[3] += d;
+	ihv[4] += e;
+}

Ciao,
Johannes

#4 lore raw

Re: [PATCH 2/4] sha1dc-accel: vectorize the unavoidable-bitconditions check

In reply to Scott Chacon

Hi Scott,

Quoted 1 line · Scott Chacon
 sha1dc-accel/ubc_check.c            | 1789 +++++++++++++++++++++++++++

This is quite large. And of course it's essentially a machine-assisted translation of the Rust code, which itself is the output of the solver.

Assuming that we will not only want to be able to confirm the translation easily, but also be able to adapt to future improvements in the Rust code (e.g. if Sam finds another neat trick to dismiss even more candidates even earlier), here is a Perl script to do precisely that:

-- snip --
#!/usr/bin/perl
# Convert the generated src/ubc_check/{scalar,sse2,avx2,neon}.rs files at # https://github.com/srijs/sha1dc/tree/426b4afd to C table definitions. # Usage: perl sha1dc-accel/generate-ubc-tables.pl sse2 < path/to/sse2.rs # Output is tables only; retain ubc_check.c's declarations and MIT notice. use strict;
use warnings;

my $form = shift // die "usage: $0 scalar|sse2|avx2|neon < form.rs\n"; my %prefix_count = (scalar => 70, sse2 => 26, avx2 => 16, neon => 20); my %tail_count = (scalar => 151, sse2 => 97, avx2 => 77, neon => 137); exists $prefix_count{$form} && !@ARGV or die "unknown form: $form\n"; local $/;
my $src = <STDIN> // die "empty input\n";
my ($prefix) = $src =~ /^fn prefix\([^\n]*\) -> u32 \{(.*?)^\}/ms; defined $prefix or die "missing prefix()\n";
$prefix =~ s/\(([^()]*)\)\s+as\s+i32/$1/g;
$prefix =~ s/\b(\d+)u32\b/$1/g;
my (@out, @rows);

sub table {
	my ($type, $name, $rows) = @_;
	push @out, "static const struct $type ${form}_$name\[\] = {\n",
		map("\t{ $_ },\n", @$rows), "};\n\n";
}
sub condition {
	my ($expr) = @_;
	$expr =~ s/[\s()]//g;
	$expr =~ s/&1$//;
	$expr =~ /\Aw\[(\d+)\](?:>>(\d+))?\^w\[(\d+)\]
		(?:>>(\d+))?(?:\^([01]))?\z/x
		or die "unknown condition: $expr\n";
	return [$1, $2 // 0, $3, $4 // 0, $5 // 0];
}
sub vector {
	my ($expr, $width) = @_;
	my @v;
	if ($expr =~ /(?:_mm(?:256)?_set1_epi32|vdupq_n_u32)\(([^()]*)\)/) {
		@v = ($1) x $width;
	} elsif ($expr =~ /(?:_mm(?:256)?_set_epi32)\(([^()]*)\)/
		|| $expr =~ /splat\(\[([^\]]*)\]\)/s) {
		@v = split /\s*,\s*/, $1;
	} else {
		die "unknown vector: $expr\n";
	}
	@v == $width or die "wrong lane count: $expr\n";
	for (@v) {
		s/^\s+|\s+$//g;
		/\A(?:0|1\s*<<\s*\d+|DV_I{1,2}_\d+_\d+_BIT
			(?:\s*\|\s*DV_I{1,2}_\d+_\d+_BIT)*)\z/x
			or die "unknown lane: $_\n";
		s/\b1\s*<</1u <</;
	}
	# The pinned x86 source lists logical step order, despite set_epi32.
	return "{ " . join(", ", @v) . " }";
}
if ($form eq "scalar") {
	while ($prefix =~ /mask\s*&=\s*(.*?);/sg) {
		my ($expr, $dvs) = $1 =~ /\A(.*?)\s*\|\s*!\(([^()]*)\)\s*\z/s;
		defined $dvs or die "unknown scalar prefix\n";
		$expr =~ s/\s//g;
		my ($bits, $want);
		if ($expr =~ /\A(.*)\.wrapping_sub\(1\)\z/s) {
			($bits, $want) = ($1, 0);
		} elsif ($expr =~ /\A\(0\)\.wrapping_sub\((.*)\)\z/s) {
			($bits, $want) = ($1, 1);
		} else {
			die "unknown scalar mask: $expr\n";
		}
		my $c = condition($bits);
		$c->[4] = $want;
		$dvs =~ s/\s+/ /g;
		push @rows, "{ " . join(", ", @$c) . " }, $dvs";
	}
	table("ubc_prefix_cond", "prefix_conds", \@rows);
} else {
	my $width = $form eq "avx2" ? 8 : 4;
	my %want = (
		"_mm_and_si128(miss,bits)" => 1,
		"_mm_andnot_si128(miss,bits)" => 0,
		"_mm256_and_si256(miss,bits)" => 1,
		"_mm256_andnot_si256(miss,bits)" => 0,
		"vqsubq_u32(bits,set)" => 1,
		"vminq_u32(set,bits)" => 0,
	);
	while ($prefix =~ /\{\s*(let near =.*?)\}/sg) {
		my $g = $1;
		$g =~ s/\s//g;
		my ($lo, $hi, $x, $test, $dvs, $acc) = $g =~
			/\Alet near = load::<(\d+)>\(w\);\s*
			let far = load::<(\d+)>\(w\);\s*let x = (.*?);\s*
			let (?:tested|set) = (.*?);\s*
			(?:let miss = [^;]*;\s*)?let bits = (.*?);\s*
			acc[01] = \w+\(acc[01],\s*(.*?)\);\s*\z/sx;
		defined $acc or die "unknown vector group: $g\n";
		$x =~ s/(?:_mm(?:256)?_xor_si(?:128|256)|veorq_u32)/xor/g;
		$x =~ s/(?:_mm(?:256)?_srli_epi32|vshrq_n_u32)/shr/g;
		$x =~ s/\s//g;
		$x =~ /\Axor\((?:shr\(near,(\d+)\)|near),
			(?:shr\(far,(\d+)\)|far)\)\z/x
			or die "unknown vector XOR: $x\n";
		my ($ls, $hs) = ($1 // 0, $2 // 0);
		$acc =~ s/\s//g;
		exists $want{$acc} or die "unknown predicate: $acc\n";
		push @rows, join(", ", $lo, $ls // 0, $hi, $hs // 0,
			$want{$acc}, vector($test, $width),
			vector($dvs, $width));
	}
	table("ubc_group$width", "groups", \@rows);
}

@rows == $prefix_count{$form} or die "wrong prefix count\n";

if ($form ne "neon") {
	for my $key ("CHECKS", "SPANS") {
		my ($n, $body) = $src =~ /static\s+TAIL_$key:[^\n]*;
			\s*(\d+)\]\s*=\s*\[(.*?)^\];/msx;
		defined $body or die "missing TAIL_$key\n";
		my @tuples = $body =~ /\((\d+(?:\s*,\s*\d+)*)\)/g;
		@tuples == $n && $n == ($key eq "CHECKS" ?
			$tail_count{$form} : 32) or die "wrong tail count\n";
		table($key eq "CHECKS" ? "ubc_cond" : "tail_span",
			"tail_" . lc($key), \@tuples);
	}
} else {
	my @dv;
	my ($tail) = $src =~ /^fn tail\([^\n]*\) -> u32 \{(.*?)^\}/ms;
	defined $tail or die "missing tail()\n";
	$tail =~ s/\s//g;
	while ($tail =~ /if mask & DV_I{1,2}_\d+_\d+_BIT != 0 \{\s*
		let fail = (.*?);\s*out &= !(?:fail|\(fail << (\d+)\));/sgx) {
		my ($expr, $d) = ($1, $2 // 0);
		$d < 32 && !defined $dv[$d] or die "duplicate/invalid DV\n";
		$expr =~ s/[\s()]//g;
		$expr =~ s/&1$// or die "unknown tail mask\n";
		$dv[$d] = [map { join(", ", @{condition($_)}) }
			split /\|/, $expr];
	}
	my (@checks, @spans);
	for my $d (0 .. 31) {
		my $c = $dv[$d] // [];
		push @spans, scalar(@checks) . ", " . scalar(@$c);
		push @checks, @$c;
	}
	@checks == $tail_count{$form} or die "wrong NEON tail count\n";
	table("ubc_cond", "tail_checks", \@checks);
	table("tail_span", "tail_spans", \@spans);
}

print @out;
-- snap --

This Perl script reproduces the tables (although with different formatting, and without the inline comments, I verified it with --patience --color-words="[A-Za-z0-9_]+|.").

As is my rule, I only offer code that I wrote with AI assistance if the output is close enough to what I would have written myself if I had the time (and wouldn't need to take care of my arm muscles' health), and this Perl script is no exception. My first draft would probably have used less informative (or no) error messages, and I only learned about that // operator during this session.

With all that out of the way, I would like to ask to include this script in the patch (or in a follow-up patch) so that the lengthy ubc_check.c file's tables can be validated/regenerated independently.

Quoted 20 lines
sha1dc-accel/ubc_check.c new file +13 -0
new file mode 100644
index 0000000000..f95b799f9d
@@ -0,0 +1,1789 @@
[...]
+static uint32_t neon_prefix(const uint32_t *w)
+{
+	uint32x4_t acc = vdupq_n_u32(0);
+	uint32x2_t folded;
+	size_t i;
+
+	UNROLL_TABLE
+	for (i = 0; i < ARRAY_SIZE(neon_groups); i++) {
+		const struct ubc_group4 *g = &neon_groups[i];
+		uint32x4_t lo = vld1q_u32(w + g->lo);
+		uint32x4_t hi = vld1q_u32(w + g->hi);
+		uint32x4_t dvs = vld1q_u32(g->dvs);
+		uint32x4_t set, fail;

sha1dc-accel/ubc_check.c line 969

Quoted 10 lines
sha1dc-accel/ubc_check.c new file +10 -0
+
+		lo = vshlq_u32(lo, vdupq_n_s32(-(int32_t)g->lo_shift));
+		hi = vshlq_u32(hi, vdupq_n_s32(-(int32_t)g->hi_shift));
+		set = vtstq_u32(veorq_u32(lo, hi), vld1q_u32(g->test));
+		/*
+		 * The DVs of the lanes where the bit is not g->want. Each lane
+		 * of set is all ones or zero, so a saturating subtraction keeps
+		 * dvs where the bit is clear, and min keeps it where it is set.
+		 */
+		fail = g->want ? vqsubq_u32(dvs, set) : vminq_u32(set, dvs);

While this code is correct, I think it is slightly misleading: depending on want, it either subtracts set from dvs, or takes the minimum. But that only happens to be what is desired because each lane of set is all ones or all zero. What we actually want is to mask either those lanes or everything but those lanes, i.e. dvs & ~set or dvs & set, respectively. That would be:

		fail = g->want ? vbicq_u32(dvs, set) : vandq_u32(dvs, set);

This has no speed impact nor does it produce a "more correct" result, but it might improve readability a bit.

I haven't looked very closely whether there are similar issues elsewhere (it is relatively tedious for me to learn all this NEON stuff on the go, this is all new to me). If you're familiar with NEON, it might be worthwhile looking for similarly "correct but misleading" statements.

But then, the proof lies in the pudding, as they say, and the code is probably good enough as-is.

Ciao,
Johannes

#8 lore raw
In reply to Scott Chacon

Hi Scott,

Quoted 6 lines · Scott Chacon

So, spoiler alert, the code in this patch series is mainly AI generated. I would try to fool you, but too many of you are far too aware of my actual C skills. That being said, I thought maybe someone here (especially those of you working on server optimization stuff) would be interested in the speed increases for both the server and client in making sha1dc quite a bit faster.

Hah, I beat you by almost a full day with my "competing" series at
https://lore.kernel.org/git/[email protected]/.
I put the "competing" in double quotes because I think that both patch series have merit, and I would love to see both merged.

Performance-wise, in my tests the Rust sha1dc was a tad faster that this C-accell code on my Ryzen, something like 3.3% for my favorite index-pack benchmark with 30 randomized pairings. Naturally, I tried to figure out where that difference comes from, but I haven't been able to finish that analysis to my satisfaction, although I would like to offer this patch to avoid reordering the message schedule, which closes the gap from 3.3% to 1%:

-- snip --
From: Johannes Schindelin <[email protected]>
Date: Sun, 4 Oct 2026 12:53:56 +0200
Subject: [PATCH] sha1dc-accel: bring SHA-NI performance closer to Rust

The C SHA-NI path spends instructions reordering the message schedule, while Rust uses a mirrored schedule. Avoid that overhead without changing the collision checks.

Across 30 randomized, AC-powered triplets on the same pack, C's mean fell from 8.201s to 8.053s. The paired mean improvement was 0.147s (95% CI: 0.083-0.211s), leaving C about 1% behind Rust.

Assisted-by GPT-6 Sol
---
 sha1dc-accel/internal.h  |  7 +++-
 sha1dc-accel/sha1.c      | 22 +++++++++--
 sha1dc-accel/ubc_check.c | 82 ++++++++++++++++++++++++++++++----------
 sha1dc-accel/x86.c       |  4 +-
 t/unit-tests/u-sha1dc.c  | 34 +++++++++++++----
 5 files changed, 112 insertions(+), 37 deletions(-)
sha1dc-accel/internal.h +5 -2
index a50b294b96b..bcb60811a8f 100644
@@ -4,8 +4,9 @@
 /*
  * Shared between the files of sha1dc-accel/. See sha1.c for an overview.
  *
- * The schedule `w` is always the 80 expanded message words in step order,
- * w[t] at index t, which is also what sha1dc/ keeps in SHA1_CTX.m1.
+ * The schedule `w` has 80 expanded message words. Normally w[t] is at
+ * index t, as in sha1dc/. SHA-NI spills w[t] at index 79 - t; a candidate
+ * is put back in step order before recompression.
  *
  * A "state" is the five working words [a, b, c, d, e] before a step.
  */
@@ -75,9 +76,11 @@ enum sha1dc_from {
 uint32_t sha1dc_ubc_check_scalar(const uint32_t w[80]);
 #ifdef SHA1DC_HAVE_SSE2
 uint32_t sha1dc_ubc_check_sse2(const uint32_t w[80]);
+uint32_t sha1dc_ubc_check_sse2_mirrored(const uint32_t w[80]);
 #endif
 #ifdef SHA1DC_HAVE_AVX2
 uint32_t sha1dc_ubc_check_avx2(const uint32_t w[80]);
+uint32_t sha1dc_ubc_check_avx2_mirrored(const uint32_t w[80]);
 #endif
 #ifdef SHA1DC_HAVE_NEON
 uint32_t sha1dc_ubc_check_neon(const uint32_t w[80]);
sha1dc-accel/sha1.c +18 -4
index 1f1133169b5..bddc3bcdf2d 100644
@@ -259,9 +259,11 @@ static int shani_avx2_available(void)
 /* In order of preference. */
 static const struct backend backends[] = {
 #ifdef SHA1DC_HAVE_SHANI
-	{ "shani+avx2", sha1dc_compress_shani, 1, sha1dc_ubc_check_avx2,
+	{ "shani+avx2", sha1dc_compress_shani, 1,
+	  sha1dc_ubc_check_avx2_mirrored,
 	  sha1dc_recompress_shani, shani_avx2_available },
-	{ "shani+sse2", sha1dc_compress_shani, 1, sha1dc_ubc_check_sse2,
+	{ "shani+sse2", sha1dc_compress_shani, 1,
+	  sha1dc_ubc_check_sse2_mirrored,
 	  sha1dc_recompress_shani, sha1dc_shani_available },
 #endif
 #ifdef SHA1DC_HAVE_ARMV8
@@ -432,8 +434,20 @@ static inline void process(const struct backend *be, SHA1_CTX *ctx,
 		return;
 
 	candidates = ctx->ubc_check ? be->ubc_check(w) : 0xFFFFFFFF;
-	if (candidates &&
-	    attacked(be, ctx, candidates, w, s1, s2, ihv_in, ctx->ihv)) {
+	if (!candidates)
+		return;
+#ifdef SHA1DC_HAVE_SHANI
+	if (be->compress == sha1dc_compress_shani) {
+		int i;
+
+		for (i = 0; i < 40; i++) {
+			uint32_t tmp = w[i];
+			w[i] = w[79 - i];
+			w[79 - i] = tmp;
+		}
+	}
+#endif
+	if (attacked(be, ctx, candidates, w, s1, s2, ihv_in, ctx->ihv)) {
 		ctx->found_collision = 1;
 		/*
 		 * Two more compressions of this block give a digest that the
sha1dc-accel/ubc_check.c +61 -21

161 lines not on this page · raw message

sha1dc-accel/x86.c +2 -2
index c2a0c71f17f..dfdc1fc3b62 100644
@@ -66,8 +66,8 @@ int sha1dc_shani_available(void)
 #define LOADU(p) _mm_loadu_si128((const __m128i *)(const void *)(p))
 #define STOREU(p, v) _mm_storeu_si128((__m128i *)(void *)(p), (v))
 
-/* Writes group `v` (steps t..t+3, held reversed) to w[t..t+3]. */
-#define SPILL(t, v) STOREU(w + (t), _mm_shuffle_epi32((v), REVERSE))
+/* The group is already reversed; store it in the mirrored schedule. */
+#define SPILL(t, v) STOREU(w + 76 - (t), (v))
 
 /* Schedule words 4k..4k+3 for k from 8 on, from groups k-8, k-7, k-4, k-2, k-1. */
 SHA1DC_TARGET_SHANI
t/unit-tests/u-sha1dc.c +26 -8
index f629f59d1d6..c658c219a3a 100644
@@ -151,6 +151,21 @@ static void check_ubc_forms(uint32_t w[80], int flip, int avx2)
 		check_form(sha1dc_ubc_check_scalar(w), want);
 #ifdef SHA1DC_HAVE_SSE2
 		check_form(sha1dc_ubc_check_sse2(w), want);
+		{
+			uint32_t mirrored[80];
+			int t;
+
+			for (t = 0; t < 80; t++)
+				mirrored[t] = w[79 - t];
+			check_form(sha1dc_ubc_check_sse2_mirrored(mirrored),
+				   want);
+#ifdef SHA1DC_HAVE_AVX2
+			if (avx2)
+				check_form(
+					sha1dc_ubc_check_avx2_mirrored(
+						mirrored), want);
+#endif
+		}
 #endif
 #ifdef SHA1DC_HAVE_AVX2
 		if (avx2)
@@ -243,14 +258,15 @@ typedef int (*recompress_fn)(enum sha1dc_from from, const uint32_t m1[80],
 			     const uint32_t dm[80], const uint32_t state[5],
 			     const uint32_t ihv_out[5]);
 
-static void check_compress(compress_fn compress)
+static void check_compress(compress_fn compress, int mirrored)
 {
 	int i, t;
 
 	rng_seed(3);
 	for (i = 0; i < 2000; i++) {
 		unsigned char block[64];
-		uint32_t ihv[5], got[5], w[80], at_60[5], at_64[5], s[5];
+		uint32_t ihv[5], got[5], w[80], expected[80];
+		uint32_t at_60[5], at_64[5], s[5];
 
 		for (t = 0; t < 64; t++)
 			block[t] = rng();
@@ -260,14 +276,16 @@ static void check_compress(compress_fn compress)
 
 		memcpy(s, ihv, sizeof(s));
 		for (t = 0; t < 80; t++) {
-			uint32_t want_w = t < 16 ? get_be32(block + 4 * t) :
-				rol(w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16], 1);
-			cl_assert_equal_i(w[t], want_w);
+			expected[t] = t < 16 ? get_be32(block + 4 * t) :
+				rol(expected[t - 3] ^ expected[t - 8] ^
+				    expected[t - 14] ^ expected[t - 16], 1);
+			cl_assert_equal_i(w[mirrored ? 79 - t : t],
+					  expected[t]);
 			if (t == 60)
 				cl_assert(!memcmp(at_60, s, sizeof(s)));
 			if (t == 64)
 				cl_assert(!memcmp(at_64, s, sizeof(s)));
-			step(s, t, w[t]);
+			step(s, t, expected[t]);
 		}
 		for (t = 0; t < 5; t++)
 			cl_assert_equal_i(got[t], ihv[t] + s[t]);
@@ -321,14 +339,14 @@ static void hardware_compression(void)
 
 #ifdef SHA1DC_HAVE_SHANI
 	if (sha1dc_shani_available()) {
-		check_compress(sha1dc_compress_shani);
+		check_compress(sha1dc_compress_shani, 1);
 		check_recompress(sha1dc_recompress_shani);
 		tested = 1;
 	}
 #endif
 #ifdef SHA1DC_HAVE_ARMV8
 	if (sha1dc_armv8_available()) {
-		check_compress(sha1dc_compress_armv8);
+		check_compress(sha1dc_compress_armv8, 0);
 		check_recompress(sha1dc_recompress_armv8);
 		tested = 1;
 	}

-- snap --

This is admittedly a bit gnarly, and really, really hard to understand unless you immersed yourself in Sam's work. But it _does_ accelerate SHA-1 computation with my Ryzen 7, and I'd be interested to hear whether it has an equivalent effect with your Xeon.

Quoted 37 lines

This series ports the approach of Sam Reis's sha1dc Rust crate [1], which gitoxide recently switched to [2], to C.

The end result hashes roughly 2.7x faster on the Xeon and 2.85x faster on the M5 Max. Single-threaded index-pack of git.git goes from 24.3s to 12.7s on the Xeon, and from 16.1s to 8.7s on the M5 Max.

Hashing throughput on the Xeon, in MiB/s:

16KiB 1MiB vs OpenSSL

  OpenSSL SHA-1 (no detection)   1234    1129      1.00x
  sha1dc/ (today)                 435     450      2.67x
  shani+avx2 (default here)      1002     901      1.24x
  shani+sse2                     1075    1008      1.13x
  portable+avx2                   553     654      1.96x
  portable+sse2                   603     681      1.84x
  portable                        466     565      2.29x

In other words, currently collision detection costs about 1.5–2.5x on top of the hashing itself today, but only about 0.2x with the series.

The patches are:

[1/4]: sha1dc-accel: add a block loop for sha1dc's SHA1_CTX

Just groundwork: our own block loop around sha1dc's context and DV table, with the same results and a few percent slower, plus tests that compare against sha1dc/ directly, including on real collisions in every mode.

[2/4]: sha1dc-accel: vectorize the unavoidable-bitconditions check

The UBC filter rewritten as SSE2, AVX2, NEON, and new scalar forms, using the conditions the crate's solver picks for each. They're carried as tables, with a short loop per form to run them. 1.29x on the Xeon, 1.27x on the M5 Max.

Quoted 8 lines

[3/4]: sha1dc-accel: compress with SHA-NI on x86-64

Hardware compression, with the schedule spilled, and recompression of flagged blocks in hardware, too. Another 2.07x on the Xeon.

[4/4]: sha1dc-accel: compress with the ARMv8 SHA-1 instructions

The same for arm64. Another 2.4x on the M5 Max.

I really like this structure.

BTW I have run the entire test suite both on a Ryzen 7 (using WSL) and on a Windows/ARM64 Cloud PC (using straight Windows because that Cloud PC does not support WSL), with a slightly patched version: running the original (slow) sha1dc, the sha1dc-accel and the Rust sha1dc. There were 0 discrepancies, which meshes with the Sol-assisted analysis of the code, comparing it against the paper and Sam's detailed blog post.

I also wanted to compare the speed, but unfortunately, my tests always suffer the noisy neighbor problem (working on a laptop with parallel work going on, or Cloud PC that is of course a VM in a rack somewhere in Virginia). So all I can really claim is that in my tests, the speed was comparable (with the patch above).

All that said, I am very much in favor of accepting your patch series into Git, with or without my suggested changes.

Thanks!
Johannes

Quoted 53 lines

The x86 numbers are from a 4-vCPU Xeon VM with SHA-NI and AVX2 (GCC 13, Linux), which is unfortunately rather noisy; the per-patch hyperfine output has the spread. The arm64 numbers are medians of 9 runs on an Apple M5 Max (Apple clang, macOS). The full test suite passes on both.

[1] https://sam.dev/blog/faster-sha1-collision-detection
[2] https://github.com/GitoxideLabs/gitoxide/pull/3008

Scott Chacon (4):
sha1dc-accel: add a block loop for sha1dc's SHA1_CTX
sha1dc-accel: vectorize the unavoidable-bitconditions check
sha1dc-accel: compress with SHA-NI on x86-64
sha1dc-accel: compress with the ARMv8 SHA-1 instructions

 Makefile                            |   14 +
 contrib/buildsystems/CMakeLists.txt |    2 +-
 meson.build                         |    4 +
 sha1dc-accel/arm.c                  |  274 ++++
 sha1dc-accel/internal.h             |  126 ++
 sha1dc-accel/sha1.c                 |  498 ++++++++
 sha1dc-accel/sha1.h                 |   31 +
 sha1dc-accel/ubc_check.c            | 1789 +++++++++++++++++++++++++++
 sha1dc-accel/x86.c                  |  260 ++++
 sha1dc_git.c                        |   18 +
 t/.gitattributes                    |    1 +
 t/helper/test-sha1.c                |   95 ++
 t/helper/test-tool.c                |    2 +
 t/helper/test-tool.h                |    2 +
 t/meson.build                       |    1 +
 t/t0013-sha1dc.sh                   |   47 +
 t/t0013/sha-mbles-1.bin             |  Bin 0 -> 640 bytes
 t/t0013/sha1-reduced-round.bin      |  Bin 0 -> 128 bytes
 t/unit-tests/u-sha1dc.c             |  366 ++++++
 19 files changed, 3529 insertions(+), 1 deletion(-)
 create mode 100644 sha1dc-accel/arm.c
 create mode 100644 sha1dc-accel/internal.h
 create mode 100644 sha1dc-accel/sha1.c
 create mode 100644 sha1dc-accel/sha1.h
 create mode 100644 sha1dc-accel/ubc_check.c
 create mode 100644 sha1dc-accel/x86.c
 create mode 100644 t/t0013/sha-mbles-1.bin
 create mode 100644 t/t0013/sha1-reduced-round.bin
 create mode 100644 t/unit-tests/u-sha1dc.c

base-commit: a018953688f1b10bddf91bff8747068f5f4746a4

Signature · 1 line
2.50.1 (Apple Git-155)
#9 lore raw
In reply to Scott Chacon
Quoted 9 lines · Scott Chacon

So, spoiler alert, the code in this patch series is mainly AI generated. I would try to fool you, but too many of you are far too aware of my actual C skills. That being said, I thought maybe someone here (especially those of you working on server optimization stuff) would be interested in the speed increases for both the server and client in making sha1dc quite a bit faster.

This series ports the approach of Sam Reis's sha1dc Rust crate [1], which gitoxide recently switched to [2], to C.

Which means license-wise the original is compatible with us, I presume, as they are "Apache2 or MIT, your choice".

How can you/we be sure, with respect to the current AI policy in SubmittingPatches (which by the way was vetted by SFC lawyers), that your "AI generated" code did not "borrow" from places that gets you/us into trouble?

Quoted 15 lines

The end result hashes roughly 2.7x faster on the Xeon and 2.85x faster on the M5 Max. Single-threaded index-pack of git.git goes from 24.3s to 12.7s on the Xeon, and from 16.1s to 8.7s on the M5 Max.

Hashing throughput on the Xeon, in MiB/s:

16KiB 1MiB vs OpenSSL

  OpenSSL SHA-1 (no detection)   1234    1129      1.00x
  sha1dc/ (today)                 435     450      2.67x
  shani+avx2 (default here)      1002     901      1.24x
  shani+sse2                     1075    1008      1.13x
  portable+avx2                   553     654      1.96x
  portable+sse2                   603     681      1.84x
  portable                        466     565      2.29x
Quoted 2 lines

In other words, currently collision detection costs about 1.5–2.5x on top of the hashing itself today, but only about 0.2x with the series.

Thanks for these numbers.

Quoted 2 lines

[1] https://sam.dev/blog/faster-sha1-collision-detection
[2] https://github.com/GitoxideLabs/gitoxide/pull/3008

And the pointers to the original sources.

#10 lore raw

Hey,

Quoted 10 lines · Junio C Hamano
Quoted 2 lines

This series ports the approach of Sam Reis's sha1dc Rust crate [1], which gitoxide recently switched to [2], to C.

Which means license-wise the original is compatible with us, I presume, as they are "Apache2 or MIT, your choice".

How can you/we be sure, with respect to the current AI policy in SubmittingPatches (which by the way was vetted by SFC lawyers), that your "AI generated" code did not "borrow" from places that gets you/us into trouble?

It's a good question. I actually just submitted a proposed update to that policy based on SFC's updated guidelines, but either way, I learned about this from Sam and have talked to him about the port and he seemed excited about it. I can triple check, but I'm fairly confident that he's fine with this and I am fine signing off on it under the terms of the DCO language.

Of course, he in turn used AI tooling to produce _his_ library, but within the guidelines of the updated SFC guidelines. Johannes's alternative series is the original Rust code of Sam that my agent looked at to produce this (in addition to his blog post explaining it), so I'm not sure how that might be materially different.

Quoted 15 lines
Quoted 15 lines

The end result hashes roughly 2.7x faster on the Xeon and 2.85x faster on the M5 Max. Single-threaded index-pack of git.git goes from 24.3s to 12.7s on the Xeon, and from 16.1s to 8.7s on the M5 Max.

Hashing throughput on the Xeon, in MiB/s:

16KiB 1MiB vs OpenSSL

  OpenSSL SHA-1 (no detection)   1234    1129      1.00x
  sha1dc/ (today)                 435     450      2.67x
  shani+avx2 (default here)      1002     901      1.24x
  shani+sse2                     1075    1008      1.13x
  portable+avx2                   553     654      1.96x
  portable+sse2                   603     681      1.84x
  portable                        466     565      2.29x
Quoted 4 lines
Quoted 2 lines

In other words, currently collision detection costs about 1.5–2.5x on top of the hashing itself today, but only about 0.2x with the series.

Thanks for these numbers.

It would have been better had I provided the same relative scale (it should be 1.5-2.5x vs 1.2x, but whatever, you probably get it. It's 20% overhead here vs 50%-150% overhead previously).

Quoted 4 lines
Quoted 2 lines

[1] https://sam.dev/blog/faster-sha1-collision-detection
[2] https://github.com/GitoxideLabs/gitoxide/pull/3008

And the pointers to the original sources.

CC'ing Sam (sha1dc rust guy) and Sebastian (Gitoxide) on this, just in case they have an opinion but I'm pretty sure they would be more than happy for this to be integrated.

Scott

#5 lore raw

Re: [PATCH 2/4] sha1dc-accel: vectorize the unavoidable-bitconditions check

In reply to Johannes Schindelin
Quoted 17 lines · Johannes Schindelin

This Perl script reproduces the tables (although with different formatting, and without the inline comments, I verified it with --patience --color-words="[A-Za-z0-9_]+|.").
...
With all that out of the way, I would like to ask to include this script in the patch (or in a follow-up patch) so that the lengthy ubc_check.c file's tables can be validated/regenerated independently.
...
While this code is correct, I think it is slightly misleading: depending on want, it either subtracts set from dvs, or takes the minimum. But that only happens to be what is desired because each lane of set is all ones or all zero. What we actually want is to mask either those lanes or everything but those lanes, i.e. dvs & ~set or dvs & set, respectively. That would be:

		fail = g->want ? vbicq_u32(dvs, set) : vandq_u32(dvs, set);
Quoted 7 lines

This has no speed impact nor does it produce a "more correct" result, but it might improve readability a bit.

I haven't looked very closely whether there are similar issues elsewhere (it is relatively tedious for me to learn all this NEON stuff on the go, this is all new to me). If you're familiar with NEON, it might be worthwhile looking for similarly "correct but misleading" statements.

Thanks for offering a very thoughtful help and offering to work well together.

#11 lore raw
In reply to Scott Chacon

Thanks for reeling me in, Scott!

First of all, I am very happy to see that overall, everyone here is making an effort to find a way to speed up SHA-1dc again. It's so impactful!

It really did hurt when I finally had to add SHA-1dc to Gitoxide and see the performance of clones plummet. And it still hurts me knowing that an incredible amount of CPU time is wasted doing something that we now
know can be done much faster. At GitHub scale, this must be more than
a blip.

While it's my dream to one day have a GitHub action that uses gix to clone and safe even more power, I think Git is in a far better spot to achieve significant savings much sooner.

Quoted 61 lines · Scott Chacon

Hey,

Quoted 10 lines · Junio C Hamano
Quoted 2 lines

This series ports the approach of Sam Reis's sha1dc Rust crate [1], which gitoxide recently switched to [2], to C.

Which means license-wise the original is compatible with us, I presume, as they are "Apache2 or MIT, your choice".

How can you/we be sure, with respect to the current AI policy in SubmittingPatches (which by the way was vetted by SFC lawyers), that your "AI generated" code did not "borrow" from places that gets you/us into trouble?

It's a good question. I actually just submitted a proposed update to that policy based on SFC's updated guidelines, but either way, I learned about this from Sam and have talked to him about the port and he seemed excited about it. I can triple check, but I'm fairly confident that he's fine with this and I am fine signing off on it under the terms of the DCO language.

Of course, he in turn used AI tooling to produce _his_ library, but within the guidelines of the updated SFC guidelines. Johannes's alternative series is the original Rust code of Sam that my agent looked at to produce this (in addition to his blog post explaining it), so I'm not sure how that might be materially different.

Quoted 15 lines
Quoted 15 lines

The end result hashes roughly 2.7x faster on the Xeon and 2.85x faster on the M5 Max. Single-threaded index-pack of git.git goes from 24.3s to 12.7s on the Xeon, and from 16.1s to 8.7s on the M5 Max.

Hashing throughput on the Xeon, in MiB/s:

16KiB 1MiB vs OpenSSL

   OpenSSL SHA-1 (no detection)   1234    1129      1.00x
   sha1dc/ (today)                 435     450      2.67x
   shani+avx2 (default here)      1002     901      1.24x
   shani+sse2                     1075    1008      1.13x
   portable+avx2                   553     654      1.96x
   portable+sse2                   603     681      1.84x
   portable                        466     565      2.29x
Quoted 4 lines
Quoted 2 lines

In other words, currently collision detection costs about 1.5–2.5x on top of the hashing itself today, but only about 0.2x with the series.

Thanks for these numbers.

It would have been better had I provided the same relative scale (it should be 1.5-2.5x vs 1.2x, but whatever, you probably get it. It's 20% overhead here vs 50%-150% overhead previously).

Quoted 4 lines
Quoted 2 lines

[1] https://sam.dev/blog/faster-sha1-collision-detection
[2] https://github.com/GitoxideLabs/gitoxide/pull/3008

And the pointers to the original sources.

CC'ing Sam (sha1dc rust guy) and Sebastian (Gitoxide) on this, just in case they have an opinion but I'm pretty sure they would be more than happy for this to be integrated.

Scott

#12 lore raw

Hey everyone. Just for the avoidance of doubt, very happy to see Scott's patch here land and for git to benefit from faster sha1dc hashing. Let me know if I can do anything to support!

Quoted 81 lines · Sebastian Thiel

Thanks for reeling me in, Scott!

First of all, I am very happy to see that overall, everyone here is making an effort to find a way to speed up SHA-1dc again. It's so impactful!

It really did hurt when I finally had to add SHA-1dc to Gitoxide and see the performance of clones plummet. And it still hurts me knowing that an incredible amount of CPU time is wasted doing something that we now know can be done much faster. At GitHub scale, this must be more than a blip.

While it's my dream to one day have a GitHub action that uses gix to clone and safe even more power, I think Git is in a far better spot to achieve significant savings much sooner.

Quoted 61 lines · Scott Chacon

Hey,

Quoted 10 lines · Junio C Hamano
Quoted 2 lines

This series ports the approach of Sam Reis's sha1dc Rust crate [1], which gitoxide recently switched to [2], to C.

Which means license-wise the original is compatible with us, I presume, as they are "Apache2 or MIT, your choice".

How can you/we be sure, with respect to the current AI policy in SubmittingPatches (which by the way was vetted by SFC lawyers), that your "AI generated" code did not "borrow" from places that gets you/us into trouble?

It's a good question. I actually just submitted a proposed update to that policy based on SFC's updated guidelines, but either way, I learned about this from Sam and have talked to him about the port and he seemed excited about it. I can triple check, but I'm fairly confident that he's fine with this and I am fine signing off on it under the terms of the DCO language.

Of course, he in turn used AI tooling to produce _his_ library, but within the guidelines of the updated SFC guidelines. Johannes's alternative series is the original Rust code of Sam that my agent looked at to produce this (in addition to his blog post explaining it), so I'm not sure how that might be materially different.

Quoted 15 lines
Quoted 15 lines

The end result hashes roughly 2.7x faster on the Xeon and 2.85x faster on the M5 Max. Single-threaded index-pack of git.git goes from 24.3s to 12.7s on the Xeon, and from 16.1s to 8.7s on the M5 Max.

Hashing throughput on the Xeon, in MiB/s:

16KiB 1MiB vs OpenSSL

   OpenSSL SHA-1 (no detection)   1234    1129      1.00x
   sha1dc/ (today)                 435     450      2.67x
   shani+avx2 (default here)      1002     901      1.24x
   shani+sse2                     1075    1008      1.13x
   portable+avx2                   553     654      1.96x
   portable+sse2                   603     681      1.84x
   portable                        466     565      2.29x
Quoted 4 lines
Quoted 2 lines

In other words, currently collision detection costs about 1.5–2.5x on top of the hashing itself today, but only about 0.2x with the series.

Thanks for these numbers.

It would have been better had I provided the same relative scale (it should be 1.5-2.5x vs 1.2x, but whatever, you probably get it. It's 20% overhead here vs 50%-150% overhead previously).

Quoted 4 lines
Quoted 2 lines

[1] https://sam.dev/blog/faster-sha1-collision-detection
[2] https://github.com/GitoxideLabs/gitoxide/pull/3008

And the pointers to the original sources.

CC'ing Sam (sha1dc rust guy) and Sebastian (Gitoxide) on this, just in case they have an opinion but I'm pretty sure they would be more than happy for this to be integrated.

Scott

#13 lore raw

Hi Sam,

Quoted 4 lines · Sam Reis

Hey everyone. Just for the avoidance of doubt, very happy to see Scott's patch here land and for git to benefit from faster sha1dc hashing. Let me know if I can do anything to support!

[We bottom-post here]

Quoted 9 lines
Quoted 9 lines · Scott Chacon
Quoted 8 lines

Hey,

Quoted 5 lines · Junio C Hamano
Quoted 2 lines

This series ports the approach of Sam Reis's sha1dc Rust crate [1], which gitoxide recently switched to [2], to C.

Which means license-wise the original is compatible with us, I presume, as they are "Apache2 or MIT, your choice".

Leaving aside the question below about AI policy, I think the important question for Sam and Sebastien is license compatibility?

The sha1collisiondetection submodule and the sha1dc code (extracted from that submodule's upstream, if I'm reading 28dc98e343 (sha1dc: add collision-detecting sha1 implementation, 2017-03-16) correctly?) are MIT licensed, too, so there is some precedent for Git here. I skimmed what I could find of the original threads:

- https://lore.kernel.org/git/[email protected]/
- https://lore.kernel.org/git/?q=sha1dc%3A+add+collision-detecting+sha1+implementation

but I didn't see a discussion of licensing at that time. Perhaps the idea is that we are clear that such code carries a different license from Git?

Anyway, I suppose the fair thing would then be for Scott's code to be MIT (and/or Apache2), in which case it would need similar clarifications? (Or are we prepared to take the stance that de nouveau code based on existing code can be license-washed, in this case to GPL-2?)

Interestingly, Gentoo claims Git's license is only GPL-2, but I think they compile in the sha1dc code since it's the default in meson. Should we be claiming the Git package (with sha1dc) is actually GPL-2 and MIT?

(This is complex territory and I'm sure to have gotten it wrong; pointers to past discussions, esp. those by copyright and licensing professionals, welcome.)

Quoted 17 lines
Quoted 17 lines
Quoted 17 lines
Quoted 4 lines

How can you/we be sure, with respect to the current AI policy in SubmittingPatches (which by the way was vetted by SFC lawyers), that your "AI generated" code did not "borrow" from places that gets you/us into trouble?

It's a good question. I actually just submitted a proposed update to that policy based on SFC's updated guidelines, but either way, I learned about this from Sam and have talked to him about the port and he seemed excited about it. I can triple check, but I'm fairly confident that he's fine with this and I am fine signing off on it under the terms of the DCO language.

Of course, he in turn used AI tooling to produce _his_ library, but within the guidelines of the updated SFC guidelines. Johannes's alternative series is the original Rust code of Sam that my agent looked at to produce this (in addition to his blog post explaining it), so I'm not sure how that might be materially different.

[snip]

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

[1] https://sam.dev/blog/faster-sha1-collision-detection
[2] https://github.com/GitoxideLabs/gitoxide/pull/3008

Signature · 1 line
D. Ben Knoble
#14 lore raw

Hi Ben,

Quoted 10 lines · D. Ben Knoble

Hi Sam,

Quoted 4 lines · Sam Reis

Hey everyone. Just for the avoidance of doubt, very happy to see Scott's patch here land and for git to benefit from faster sha1dc hashing. Let me know if I can do anything to support!

[We bottom-post here]

No problem!

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines · Scott Chacon
Quoted 3 lines

Hey,

On Wed, Oct 7, 2026 at 7:23 PM Junio C Hamano <[email protected]> wrote:

Quoted 8 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 2 lines

This series ports the approach of Sam Reis's sha1dc Rust crate [1], which gitoxide recently switched to [2], to C.

Which means license-wise the original is compatible with us, I presume, as they are "Apache2 or MIT, your choice".

Leaving aside the question below about AI policy, I think the important question for Sam and Sebastien is license compatibility?

I can try answering as best as possible from my perspective. I think it's important
to note, insofar this wasn't clear before, that the actual code for the ubc checks is
fully autogenerated rather than written by hand.

The generator for it was written from scratch by me with LLM assistance, and based
on the methodology described in the 2017 paper from Marc Stevens and Dan Shumow. Nonetheless I ended up crediting Stevens and Shumow in the copyright notice to be on the safe side.

Quoted 20 lines

The sha1collisiondetection submodule and the sha1dc code (extracted from that submodule's upstream, if I'm reading 28dc98e343 (sha1dc: add collision-detecting sha1 implementation, 2017-03-16) correctly?) are MIT licensed, too, so there is some precedent for Git here. I skimmed what I could find of the original threads:

- https://lore.kernel.org/git/[email protected]/
- https://lore.kernel.org/git/?q=sha1dc%3A+add+collision-detecting+sha1+implementation

but I didn't see a discussion of licensing at that time. Perhaps the idea is that we are clear that such code carries a different license from Git?

Anyway, I suppose the fair thing would then be for Scott's code to be MIT (and/or Apache2), in which case it would need similar clarifications? (Or are we prepared to take the stance that de nouveau code based on existing code can be license-washed, in this case to GPL-2?)

Quoted 4 lines

Interestingly, Gentoo claims Git's license is only GPL-2, but I think they compile in the sha1dc code since it's the default in meson. Should we be claiming the Git package (with sha1dc) is actually GPL-2 and MIT?

Again IANAL, but my understanding was always that MIT is GPL-compatible. From https://en.wikipedia.org/wiki/License_compatibility#GPL_compatibility:

"Many of the most common free-software licenses [...] are GPL-compatible. That is, their code can be combined with a program under the GPL without conflict, and the new combination would have the GPL applied to the whole (but the other license would not so apply)."

So as long as it's correctly attributed, that might not be an issue?

Quoted 31 lines

(This is complex territory and I'm sure to have gotten it wrong; pointers to past discussions, esp. those by copyright and licensing professionals, welcome.)

Quoted 17 lines
Quoted 17 lines
Quoted 17 lines
Quoted 4 lines

How can you/we be sure, with respect to the current AI policy in SubmittingPatches (which by the way was vetted by SFC lawyers), that your "AI generated" code did not "borrow" from places that gets you/us into trouble?

It's a good question. I actually just submitted a proposed update to that policy based on SFC's updated guidelines, but either way, I learned about this from Sam and have talked to him about the port and he seemed excited about it. I can triple check, but I'm fairly confident that he's fine with this and I am fine signing off on it under the terms of the DCO language.

Of course, he in turn used AI tooling to produce _his_ library, but within the guidelines of the updated SFC guidelines. Johannes's alternative series is the original Rust code of Sam that my agent looked at to produce this (in addition to his blog post explaining it), so I'm not sure how that might be materially different.

[snip]

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

[1] https://sam.dev/blog/faster-sha1-collision-detection
[2] https://github.com/GitoxideLabs/gitoxide/pull/3008

--
D. Ben Knoble

#23 lore raw
In reply to Sam Reis
Quoted 3 lines · Sam Reis

Hey everyone. Just for the avoidance of doubt, very happy to see Scott's patch here land and for git to benefit from faster sha1dc hashing. Let me know if I can do anything to support!

Thanks. Just to make sure I understand, are you endorsing the idea of your work geting ported to help Git, or are you also happy with the actual code Scott submitted?

#15 lore raw
In reply to D. Ben Knoble
Quoted 3 lines · D. Ben Knoble

but I didn't see a discussion of licensing at that time. Perhaps the idea is that we are clear that such code carries a different license from Git?

We are GPL-2 only, which means we can incorporate BSD-licensed software as long as we satisfy its license and copyright notice requirements.

The above is not an AI-bot-supplied answer, but what one learns when talking to copyright lawyers or reading books on software licensing.

But sometimes asking LLM gives sufficiently useful answer. I typed

"Is GPLv2 compatible with BSD?"

in the search bar of a browser, and here is the early part of what I got, which is not too bad.

* AI summary

Yes, GPLv2 is generally compatible with modern BSD (2-clause and 3-clause) licenses, though the direction of the combination matters.

Compatibility Details

• BSD inside GPLv2: You can include a 2-clause or 3-clause BSD-licensed library or code snippet inside a GPLv2-licensed project. The resulting combined work must be distributed under the terms of the GPLv2.

• GPLv2 inside BSD: You cannot take GPLv2-licensed code and place it into a purely BSD-licensed project. Because the GPLv2 is a strong copyleft license, it forces the entire combined work to be covered by the GPLv2.

#16 lore raw
Quoted 7 lines · Junio C Hamano
Quoted 3 lines · D. Ben Knoble

but I didn't see a discussion of licensing at that time. Perhaps the idea is that we are clear that such code carries a different license from Git?

Quoted 6 lines

We are GPL-2 only, which means we can incorporate BSD-licensed software as long as we satisfy its license and copyright notice requirements.

The above is not an AI-bot-supplied answer, but what one learns when talking to copyright lawyers or reading books on software licensing.

Thanks, that's good to know---but in this case I thought we were talking about the MIT license?

Assuming a similar analysis applies (not clear to me, but not implausible either), that might also answer my question about Gentoo's license descriptor. The product is GPL-2 even if one input was MIT (though it feels strange to effectively "re-license" someone else's code this way).

Signature · 1 line
D. Ben Knoble
#17 lore raw
Quoted 9 lines · D. Ben Knoble
Quoted 6 lines

We are GPL-2 only, which means we can incorporate BSD-licensed software as long as we satisfy its license and copyright notice requirements.

The above is not an AI-bot-supplied answer, but what one learns when talking to copyright lawyers or reading books on software licensing.

Thanks, that's good to know---but in this case I thought we were talking about the MIT license?

Yup, the story is the same. Also BSD and MIT also fully compatible in either direction.

#18 lore raw
In reply to D. Ben Knoble
Quoted 4 lines · D. Ben Knoble

Interestingly, Gentoo claims Git's license is only GPL-2, but I think they compile in the sha1dc code since it's the default in meson. Should we be claiming the Git package (with sha1dc) is actually GPL-2 and MIT?

I _think_ that that depends on whether Gentoo's license tag is meant to be the "effective" license they are distributing their Git package or attempting to encompass the license of all of the code which goes into the Git package.

Fedora's Git package has:

BSD-3-Clause AND GPL-2.0-only AND GPL-2.0-or-later AND LGPL-2.1-or-later AND MIT

I think I was the last to touch that, in ef75bcd (update license data and convert to SPDX format, 2022-11-07). I attempted to capture all of the licensing, but I most certainly could have missed some things. And things may have changed since then too.

Fedora's guidelines have a lengthy page on the License tag². It includes a 'No "effective license" analysis' section discussing this.

I don't know if any of that helps. :)

¹ https://src.fedoraproject.org/rpms/git/c/ef75bcd
² https://docs.fedoraproject.org/en-US/legal/license-field/

Signature · 1 line
Todd
#22 lore raw
In reply to D. Ben Knoble
Quoted 19 lines · D. Ben Knoble

The sha1collisiondetection submodule and the sha1dc code (extracted from that submodule's upstream, if I'm reading 28dc98e343 (sha1dc: add collision-detecting sha1 implementation, 2017-03-16) correctly?) are MIT licensed, too, so there is some precedent for Git here. I skimmed what I could find of the original threads:

- https://lore.kernel.org/git/[email protected]/
- https://lore.kernel.org/git/?q=sha1dc%3A+add+collision-detecting+sha1+implementation

but I didn't see a discussion of licensing at that time. Perhaps the idea is that we are clear that such code carries a different license from Git?

Anyway, I suppose the fair thing would then be for Scott's code to be MIT (and/or Apache2), in which case it would need similar clarifications? (Or are we prepared to take the stance that de nouveau code based on existing code can be license-washed, in this case to GPL-2?)

Quoted 4 lines

Interestingly, Gentoo claims Git's license is only GPL-2, but I think they compile in the sha1dc code since it's the default in meson. Should we be claiming the Git package (with sha1dc) is actually GPL-2 and MIT?

In the abov, Gentoo's mention is about "Git package" as a whole. Git package as a whole can be distributed under GPLv2 only.

MIT, BSD-2 or BSD-3 are permissive and essentially says "you can do whatever you want with the code (including combining with other code or making it proprietary), as long as you keep our copyright notice, keep our disclaimer, and (in the case of BSD-3) do not use our names for endorsement". Specifically, they do not forbid us from incorporating their ware into our project that is licensed differently, as long as we honor their licensing terms on the source files we got from them.

Because we have mixed "permissive" code into GPLv2 code to form a single "work based on the Program", GPLv2 Section 2(b) dictates that the entire combined work must be distributed under the terms of the GPLv2 (and again, the permissiveness of "other" licenses is what allows us to do so). You cannot distribute the finished binary or the combined sources under a permissive license, because doing so would violate the GPLv2's copyleft requirement.

The original "permissively licensed" files (and any modifications made purely to those files) still maintain their original copyright headers and original "permissive" license text. This is because the original copyright holder of the code granted a license to use their files under the original "permissive" licensing terms, which requires us to keep their copyright notice. We do not own the copyright to the original "permissive" code. We are only licensed to use them. So we have no legal authority to strip these "permissive" licenses or unilaterally "relicense" those files into GPLv2.

So to answer your question in the last sentence, we should say "Git package as a whole is GPLv2 only, but parts are borrowed from copyright holders who licensed them under different terms, and these parts can be used under these different parts. For example, sha1dc can be copied from our source tree to your non GPLv2 project as long as you honor their MIT license".

#19 lore raw
In reply to Todd Zullinger
Quoted 7 lines · Todd Zullinger
Quoted 4 lines · D. Ben Knoble

Interestingly, Gentoo claims Git's license is only GPL-2, but I think they compile in the sha1dc code since it's the default in meson. Should we be claiming the Git package (with sha1dc) is actually GPL-2 and MIT?

Quoted 8 lines

I _think_ that that depends on whether Gentoo's license tag is meant to be the "effective" license they are distributing their Git package or attempting to encompass the license of all of the code which goes into the Git package.

Fedora's Git package has:

BSD-3-Clause AND GPL-2.0-only AND GPL-2.0-or-later AND LGPL-2.1-or-later AND MIT

Oh, curious! Where are the (using Gentoo identifiers for the moment) BSD and LGPL-2.1+ sources? I guess I assume by looking at our COPYING that the GPL-2+ came from contributions that said they were willing to be 2+?

Quoted 6 lines

I think I was the last to touch that, in ef75bcd (update license data and convert to SPDX format, 2022-11-07). I attempted to capture all of the licensing, but I most certainly could have missed some things. And things may have changed since then too.

Quoted 8 lines

Fedora's guidelines have a lengthy page on the License tag². It includes a 'No "effective license" analysis' section discussing this.

I don't know if any of that helps. :)

¹ https://src.fedoraproject.org/rpms/git/c/ef75bcd
² https://docs.fedoraproject.org/en-US/legal/license-field/

From Gentoo's packaging guide [1], I think we might want to list all the license, except it really does depend on the license of the (installed) *output* files. We build from source but don't install the source, so maybe Junio's cousin reply that indicates the built product is covered under GPL-2 is sufficient ;)

[1]: https://devmanual.gentoo.org/general-concepts/licenses/index.html#determining-the-correct-license

In the case of other packages [2], it seems we try to handle multi-license cases, but I think there (it's been a while since that particular linked PR stalled) we might be installed both a shared library under one license and a binary under another.

[2]: https://codeberg.org/gentoo/gentoo/pulls/1340#issuecomment-18812828

Anyway, thanks all! I'll assume the Gentoo maintainers knew what they were doing :)

Signature · 1 line
D. Ben Knoble
#20 lore raw
Quoted 9 lines · D. Ben Knoble
Quoted 3 lines · Todd Zullinger

Fedora's Git package has:

BSD-3-Clause AND GPL-2.0-only AND GPL-2.0-or-later AND LGPL-2.1-or-later AND MIT

Oh, curious! Where are the (using Gentoo identifiers for the moment) BSD and LGPL-2.1+ sources? I guess I assume by looking at our COPYING that the GPL-2+ came from contributions that said they were willing to be 2+?

There are various bits of code imported that are under difference licenses, among other things. The code in reftable/ is BSD-3-Clause (using the SPDX naming), for example, while xdiff/xhistogram.c is BSD-3-Clause and/or EDL-1.0 while most of the rest of it is LGPL-2.1-or-later; ewah/ is GPL-2.0-or-later; compat/obstack.[ch] and compat/regex/ are also LGPL-2.1-or-later.

I used the perl licensecheck tool¹ to generate the initial list, then reviewed it and filtered out some bits from the test suite which are not shipped in the binary packages for Fedora.

The command to do that is (without the filtering of any code):

find -type f -exec licensecheck --shortname-scheme spdx {} + | grep -v 'UNKNOWN$' | LANG=C sort >licensecheck

A more complete analysis would require reviewing all of the files which are UNKNOWN to ensure none have a copyright that licensecheck simply didn't find (or isn't in the file but can be found from the git history). I was a bit lazy and didn't do all of that work. :)

Quoted 2 lines

Anyway, thanks all! I'll assume the Gentoo maintainers knew what they were doing :)

Yeah, I've found most distribution packagers try to be diligent about this. Though it can be a somewhat tedious tasks and can change if the distribution switches from expecting packages to list the "effective" license to some other method.

Fedora used to do (or allow) that license simplification, e.g.: boiling down our distributing Git to GPL-2-only, but clarified things a number of years ago to not do so. It ends up slightly easier to just enumerate all the licenses of the code which goes into the binary packages we ship.

¹ https://metacpan.org/release/App-Licensecheck

Signature · 1 line
Todd
#21 lore raw
Quoted 52 lines · Todd Zullinger
Quoted 9 lines · D. Ben Knoble
Quoted 3 lines · Todd Zullinger

Fedora's Git package has:

BSD-3-Clause AND GPL-2.0-only AND GPL-2.0-or-later AND LGPL-2.1-or-later AND MIT

Oh, curious! Where are the (using Gentoo identifiers for the moment) BSD and LGPL-2.1+ sources? I guess I assume by looking at our COPYING that the GPL-2+ came from contributions that said they were willing to be 2+?

There are various bits of code imported that are under difference licenses, among other things. The code in reftable/ is BSD-3-Clause (using the SPDX naming), for example, while xdiff/xhistogram.c is BSD-3-Clause and/or EDL-1.0 while most of the rest of it is LGPL-2.1-or-later; ewah/ is GPL-2.0-or-later; compat/obstack.[ch] and compat/regex/ are also LGPL-2.1-or-later.

I used the perl licensecheck tool¹ to generate the initial list, then reviewed it and filtered out some bits from the test suite which are not shipped in the binary packages for Fedora.

The command to do that is (without the filtering of any code):

find -type f -exec licensecheck --shortname-scheme spdx {} + | grep -v 'UNKNOWN$' | LANG=C sort >licensecheck

A more complete analysis would require reviewing all of the files which are UNKNOWN to ensure none have a copyright that licensecheck simply didn't find (or isn't in the file but can be found from the git history). I was a bit lazy and didn't do all of that work. :)

Quoted 2 lines

Anyway, thanks all! I'll assume the Gentoo maintainers knew what they were doing :)

Yeah, I've found most distribution packagers try to be diligent about this. Though it can be a somewhat tedious tasks and can change if the distribution switches from expecting packages to list the "effective" license to some other method.

Fedora used to do (or allow) that license simplification, e.g.: boiling down our distributing Git to GPL-2-only, but clarified things a number of years ago to not do so. It ends up slightly easier to just enumerate all the licenses of the code which goes into the binary packages we ship.

Quoted 4 lines

¹ https://metacpan.org/release/App-Licensecheck

--
Todd

Thanks, very insightful. I should have thought of xdiff, but many of the others with their own licenses were new(s) to me!

Best,

Signature · 1 line
D. Ben Knoble