Author SHA1 Message Date
cnmcdee 8e40d15470 CUDA BCH remainder (experiments/cuda-bch)
Parallel-CRC chunking of the table-driven LFSR remainder on the GPU:
each BCH block is split into 4096-byte chunks, every chunk partial
remainder is computed by one thread, and partials combine with a
precomputed advance-by-4096-bytes table (built on-device by repeated
squaring from Adv_1). The short chunk goes first in each block, so
every combine step advances by exactly 4096 bytes. Encode is fully
GPU; decode uses the GPU remainder for the clean path and falls back
to the CPU BM+Chien block decoder for dirty blocks, so correction
behaviour is identical.

Measured on RTX 3080 Ti (hot_house), 50 MB blob, median of 5:
  remainder throughput CPU -> GPU: t=8 87 -> 2961 MB/s (34x),
  t=32 22.8 -> 1094 MB/s (48x). WP 3.8 MB: t=8 71.7 -> 881 MB/s,
  t=32 18.5 -> 186 MB/s (in-process).
End-to-end store mode (-0), 50 MB: -e4 0.89 -> 0.53 s, -e7
2.44 -> 0.57 s. A fresh process pays ~0.12 s CUDA first-touch
cost, so dispatch is per-t (t=32: 4 MB, t=16: 8 MB, t<=8: 16 MB)
and is checked BEFORE any CUDA call -- small blobs never pay init
and never regress (WP -0 -e4: 0.078 s vs 0.075 s CPU).

Verification: bch_cuda_test 612 checks, 0 failures (GPU encode
byte-identical to a brute-force-remainder CPU reference, all t,
sizes 1 B..1 MiB incl. chunk/block boundaries; decode agrees with
CPU on clean, <=t-bit and t+1-bit damage); full make test green
(bch 7975, rs 530, run_rs 61, run_tests 149, deep repair 47,
hyper 56); CPU-vs-CUDA CLI archives byte-identical (8/8) with
cross-verify and byte-identical extracts both ways. CPU-only
build (make NVCC=) also verified: no cudart dependency, bch_test
7975/0, pure-CPU speeds.
2026-12-03 12:02:54 -05:00
55 changed files with 1775 additions and 2113 deletions

No files matched your search

-97
View File
@@ -1,97 +0,0 @@
# CUDA Chase-1 (deep repair) — experiments/cuda-chase
GPU port of the Chase-1 scan (`bch_chase1_block`, bch.c) for the
`-e4` case (m=22, t=8): one CUDA thread per trial position runs
Berlekamp-Massey + the lambda-splits test; a second kernel runs the
Chien search in parallel for the few survivors; the host verifies
each by the syndrome-zero check. Candidate order and counts match
the CPU exactly.
## Files
- `chase_cuda.h` / `chase_cuda.cu` — the CUDA implementation
(`chase_cuda_scan1`, `chase_cuda_available`). Only t=8 is
implemented; other t values return -2.
- `chase_bench.c` — benchmark harness: builds one 524,265-byte
block, flips N bits (default 9, seed 12345), checks the standard
decode fails, then times `--cpu` (`bch_chase1_block`) or `--cuda`
(`chase_cuda_scan1`) and prints trials / split_pass / codewords /
candidates / seconds / trials/s / a hash of the candidate set in
order / whether the original is among the candidates.
- `bch_block_syndrome()` (bch.c/bch.h) — new public accessor for
the syndrome S_1..S_2t of a received word (thin wrapper around the
existing static `compute_syndrome`). Returns 0 with S filled,
1 if the remainder is zero (clean word), -1 on bad input.
## Why the GPU version is exactly equivalent
1. **Splits test.** The CPU test is gcd(lambda, x^(2^m)-x) of
degree L. x^(2^m)-x is squarefree, so that gcd has degree L iff
lambda divides x^(2^m)-x iff x^(2^m) mod lambda == x. The kernel
computes h = x^(2^m) mod lambda by m repeated squarings and
passes iff h == x — no gcd at all. L <= 1 always splits,
matching the CPU.
2. **BM early exit.** BM's L is non-decreasing, so a trial whose L
exceeds t at any point is doomed; the kernel exits early and
never writes C beyond index t. Exactly equivalent: any such
write would only raise the degree past t (deg(C) after an
update equals the new L).
3. **Verification.** The corrected word's syndrome is
S ^ col(trial) ^ XOR col(root), and syndrome zero iff remainder
zero: the syndrome's roots close under conjugation to the
generator, so a degree-<r binary remainder with all 2t syndrome
roots is 0. The host checks this with the host exp table
(no per-candidate decode needed).
4. **Order.** The kernel's atomic-append order is nondeterministic,
so the host sorts survivors by position ascending before
verification; candidate order then reproduces the CPU's
(suspects first in order, then ascending).
## Measured (hot_house, RTX 3080 Ti, Dec 3 2026)
One 524,265-byte block, m=22, t=8, 9 errors, 4,194,296 trials.
| case | CPU | CUDA | hash |
|---|---|---|---|
| seed 12345, 9 errors | 171.571 s (24,446 trials/s) | 0.335–0.379 s (11.1–12.5M trials/s) | 0xca5f43bdeb9d8c96 (both) |
| seed 999, 10 errors | 158.573 s (26,450 trials/s) | 0.328 s (12.8M trials/s) | 0x5003477cf2b5970d (both) |
- seed 12345: trials 4,194,296, split_pass 135, codewords 135,
candidates 15, original among candidates YES (both).
- seed 999 (10 errors): split_pass 72, codewords 72, candidates 8,
original NO on both — Chase-1 cannot fix t+2 errors (one trial
flip leaves 9 > t=8); the 8 candidates are other codewords.
That is the algorithm's limit, not an implementation difference.
- Seeds 2/3/4 (suspect-path cases, 6/6/9 suspects) validated
against the CPU the same way (hash match) — see
/root/chase-cpu-seed{2,3,4}.log and the CUDA runs.
Speedup on the timed scan: **171.571 / 0.335 ≈ 512×** (worst
repeat 171.571 / 0.379 ≈ 453×). End-to-end wall clock including
process start + CUDA context init: ~0.9 s vs ~172 s (~190×).
## Build
```
# CPU-only bench
gcc -O2 -Wall -Wextra -o chase_bench_cpu chase_bench.c bch.c
# CUDA bench (nvcc pattern from the cuda-bch job)
/usr/local/cuda/bin/nvcc -O3 -arch=sm_86 -Xcompiler -O2 -c -o chase_cuda.o chase_cuda.cu
gcc -O2 -Wall -Wextra -DHAVE_CUDA -c -o chase_bench.o chase_bench.c
gcc -O2 -Wall -Wextra -c -o bch.o bch.c
/usr/local/cuda/bin/nvcc -arch=sm_86 -o chase_bench_cuda chase_bench.o bch.o chase_cuda.o
```
## Limits / not done
- t=8 only. Other t values need a template instantiation per t
(the kernel is written with CT=8; the BM/splits code is
t-generic in structure).
- Chase-2 is not ported (pair scan; the same per-trial kernel
applies, but the pair enumeration and candidate ordering need
their own pass).
- Counts are full-scan counts: if max_cands is hit, the CPU stops
the scan early (partial stats) while the GPU runs the whole scan
and then truncates. The candidate set still matches (first
max_cands in CPU order). Not an issue for the benchmark
(15 < 64 candidates).
+61 -57
View File
@@ -3,15 +3,23 @@ CFLAGS = -O2 -Wall -Wextra
LDLIBS = -llz
PREFIX = /usr/local
# CUDA Chase-1 (optional): nvcc lives here on hot_house (not on PATH
# by default). When it exists, chase_cuda.o is built and linked into
# lzply and lzply_deep_repair; otherwise deep_repair.c falls back to
# the CPU Chase via its weak references and the build is unchanged.
NVCC ?= /usr/local/cuda/bin/nvcc
NVCCFLAGS = -O3 -arch=sm_86 -Xcompiler -O2
CHASE_CUDA_OBJ =
ifneq ($(wildcard $(NVCC)),)
CHASE_CUDA_OBJ = chase_cuda.o
# CUDA BCH remainder (optional): if nvcc is on PATH, bch_cuda.o is
# built and linked into liblzply.a and the tools; bch.c dispatches
# to it via weak symbols for large blobs. Without nvcc the build is
# unchanged (CPU-only). These definitions MUST stay above every rule
# that references $(CUDA_OBJ): make expands prerequisites when the
# rule is read, so a definition below the liblzply.a rule would
# silently leave bch_cuda.o out of the archive. NOTE: bch_cuda.o is
# still listed explicitly on each tool link line below, because the
# weak references from bch.o do not make the linker pull it out of
# the archive on their own.
NVCC ?= $(shell command -v nvcc 2>/dev/null)
CUDA_ARCH ?= sm_86
CUDA_OBJ =
CUDA_LIBS =
ifneq ($(NVCC),)
CUDA_OBJ = bch_cuda.o
CUDA_LIBS = -L$(dir $(NVCC))../lib64 -lcudart -lstdc++
endif
all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
@@ -21,7 +29,7 @@ all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyp
# command-line tool (lzply), the FUSE filesystem (lzply_mount),
# the statistics tool (lzply_stat) and the heal tool (lzply_heal)
# all link it.
liblzply.a: lzply_lib.o bch.o sha256.o
liblzply.a: lzply_lib.o bch.o sha256.o $(CUDA_OBJ)
ar rcs $@ $^
lzply_lib.o: lzply_lib.c lzply_lib.h bch.h bch_polys.h sha256.h
@@ -33,15 +41,35 @@ sha256.o: sha256.c sha256.h
bch.o: bch.c bch.h bch_polys.h
$(CC) $(CFLAGS) -c -o $@ bch.c
lzply.o: lzply.c lzply_lib.h bch.h bch_polys.h deep_repair.h repair_cmd.h
# CUDA BCH remainder rules (variables are defined at the top).
ifneq ($(NVCC),)
bch_cuda.o: bch_cuda.cu bch_cuda.h bch.h bch_polys.h
$(NVCC) -O3 -arch=$(CUDA_ARCH) -Xcompiler -O2 -c -o $@ bch_cuda.cu
bch_cuda_test.o: bch_cuda_test.c bch_cuda.h bch.h
$(CC) $(CFLAGS) -c -o $@ bch_cuda_test.c
bch_cuda_test: bch_cuda_test.o bch_cuda.o bch.o
$(NVCC) -arch=$(CUDA_ARCH) -o $@ bch_cuda_test.o bch_cuda.o bch.o
bch_bench.o: bch_bench.c bch.h
$(CC) $(CFLAGS) -c -o $@ bch_bench.c
bch_bench: bch_bench.o bch.o bch_cuda.o
$(NVCC) -arch=$(CUDA_ARCH) -o $@ bch_bench.o bch.o bch_cuda.o
else
bch_bench.o: bch_bench.c bch.h
$(CC) $(CFLAGS) -c -o $@ bch_bench.c
bch_bench: bch_bench.o bch.o
$(CC) $(CFLAGS) -o $@ bch_bench.o bch.o
endif
lzply.o: lzply.c lzply_lib.h bch.h bch_polys.h
$(CC) $(CFLAGS) -c -o $@ lzply.c
lzply: lzply.o deep_repair.o repair_cmd.o liblzrs.a liblzply.a $(CHASE_CUDA_OBJ)
ifeq ($(CHASE_CUDA_OBJ),)
$(CC) $(CFLAGS) -o $@ lzply.o deep_repair.o repair_cmd.o liblzrs.a liblzply.a $(LDLIBS)
else
$(NVCC) -arch=sm_86 -o $@ lzply.o deep_repair.o repair_cmd.o liblzrs.a liblzply.a $(CHASE_CUDA_OBJ) $(LDLIBS)
endif
lzply: lzply.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply.o $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
# FUSE filesystem. Needs libfuse3-dev; no pkg-config on the server, so
# the flags are explicit (-D_FILE_OFFSET_BITS=64 is required by FUSE).
@@ -51,8 +79,8 @@ FUSE_LIBS = -lfuse3
lzply_mount.o: lzply_mount.c lzply_lib.h bch.h bch_polys.h
$(CC) $(CFLAGS) $(FUSE_CFLAGS) -c -o $@ lzply_mount.c
lzply_mount: lzply_mount.o liblzply.a
$(CC) $(CFLAGS) $(FUSE_CFLAGS) -o $@ lzply_mount.o liblzply.a $(LDLIBS) $(FUSE_LIBS)
lzply_mount: lzply_mount.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) $(FUSE_CFLAGS) -o $@ lzply_mount.o $(CUDA_OBJ) liblzply.a $(LDLIBS) $(FUSE_LIBS) $(CUDA_LIBS)
# Shared helpers for lzply_stat and lzply_heal (mount resolution via
# /proc, human-size formatting). No FUSE needed.
@@ -62,14 +90,14 @@ lzply_util.o: lzply_util.c lzply_lib.h lzply_util.h
lzply_stat.o: lzply_stat.c lzply_lib.h lzply_util.h
$(CC) $(CFLAGS) -c -o $@ lzply_stat.c
lzply_stat: lzply_stat.o lzply_util.o liblzply.a
$(CC) $(CFLAGS) -o $@ lzply_stat.o lzply_util.o liblzply.a $(LDLIBS)
lzply_stat: lzply_stat.o lzply_util.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply_stat.o lzply_util.o $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
lzply_heal.o: lzply_heal.c lzply_lib.h lzply_util.h
$(CC) $(CFLAGS) -c -o $@ lzply_heal.c
lzply_heal: lzply_heal.o lzply_util.o liblzply.a
$(CC) $(CFLAGS) -o $@ lzply_heal.o lzply_util.o liblzply.a $(LDLIBS)
lzply_heal: lzply_heal.o lzply_util.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply_heal.o lzply_util.o $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
# Bit error rate detector. Read-only: decodes each BCH entry's stored
# bytes in memory and counts the corrected bit errors. Links the same
@@ -77,8 +105,8 @@ lzply_heal: lzply_heal.o lzply_util.o liblzply.a
lzply_check.o: lzply_check.c lzply_lib.h lzply_util.h
$(CC) $(CFLAGS) -c -o $@ lzply_check.c
lzply_check: lzply_check.o lzply_util.o liblzply.a
$(CC) $(CFLAGS) -o $@ lzply_check.o lzply_util.o liblzply.a $(LDLIBS) -lm
lzply_check: lzply_check.o lzply_util.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply_check.o lzply_util.o $(CUDA_OBJ) liblzply.a $(LDLIBS) -lm $(CUDA_LIBS)
# In-place platter refresher. Reads a file (or every regular file
# under a directory / mount point) and rewrites it over itself, with
@@ -87,8 +115,8 @@ lzply_check: lzply_check.o lzply_util.o liblzply.a
lzply_refresh.o: lzply_refresh.c lzply_lib.h lzply_util.h
$(CC) $(CFLAGS) -c -o $@ lzply_refresh.c
lzply_refresh: lzply_refresh.o lzply_util.o liblzply.a
$(CC) $(CFLAGS) -o $@ lzply_refresh.o lzply_util.o liblzply.a $(LDLIBS)
lzply_refresh: lzply_refresh.o lzply_util.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply_refresh.o lzply_util.o $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
# Striped volume (bit-plane, 8 data stripes + 1-3 XOR/GF parity stripes
# + BCH). No compression, so it links only bch.o + sha256.o — no
@@ -102,23 +130,6 @@ lzply_hyper: lzply_hyper.o bch.o sha256.o
bch_test: bch.c bch_test.c bch.h bch_polys.h
$(CC) $(CFLAGS) -o $@ bch.c bch_test.c
# CUDA Chase-1 bench (experiments/cuda-chase): GPU port of the
# deep-repair Chase-1 scan (t=8 only). Needs CUDA 13.x; NVCC is
# /usr/local/cuda/bin/nvcc on hot_house (not on PATH by default).
# NVCC / NVCCFLAGS are defined at the top of this file.
chase_bench_cpu: chase_bench.c bch.c bch.h bch_polys.h
$(CC) $(CFLAGS) -o $@ chase_bench.c bch.c
chase_bench.o: chase_bench.c bch.h chase_cuda.h
$(CC) $(CFLAGS) -DHAVE_CUDA -c -o $@ chase_bench.c
chase_cuda.o: chase_cuda.cu chase_cuda.h bch.h bch_polys.h
$(NVCC) $(NVCCFLAGS) -c -o $@ chase_cuda.cu
chase_bench_cuda: chase_bench.o bch.o chase_cuda.o
$(NVCC) -arch=sm_86 -o $@ chase_bench.o bch.o chase_cuda.o
# Reed-Solomon codec (rs.c) and the LZRS v1 archive layer
# (lzrs_lib.c: LZRS entry encode/decode + header I/O + scan).
# lz_rs links both plus the shared v4 core (liblzply.a).
@@ -134,8 +145,8 @@ liblzrs.a: lzrs_lib.o rs.o
lz_rs.o: lz_rs.c lzrs_lib.h lzply_lib.h bch.h bch_polys.h
$(CC) $(CFLAGS) -c -o $@ lz_rs.c
lz_rs: lz_rs.o liblzrs.a liblzply.a
$(CC) $(CFLAGS) -o $@ lz_rs.o liblzrs.a liblzply.a $(LDLIBS)
lz_rs: lz_rs.o liblzrs.a liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lz_rs.o liblzrs.a $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
rs_test: rs.c rs_test.c rs.h
$(CC) $(CFLAGS) -o $@ rs.c rs_test.c
@@ -151,18 +162,11 @@ crc16_test: crc16_test.c liblzply.a
deep_repair.o: deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h rs.h sha256.h
$(CC) $(CFLAGS) -c -o $@ deep_repair.c
lzply_deep_repair.o: lzply_deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h repair_cmd.h
lzply_deep_repair.o: lzply_deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h
$(CC) $(CFLAGS) -c -o $@ lzply_deep_repair.c
repair_cmd.o: repair_cmd.c repair_cmd.h deep_repair.h lzply_lib.h lzrs_lib.h bch.h
$(CC) $(CFLAGS) -c -o $@ repair_cmd.c
lzply_deep_repair: lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a liblzply.a $(CHASE_CUDA_OBJ)
ifeq ($(CHASE_CUDA_OBJ),)
$(CC) $(CFLAGS) -o $@ lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a liblzply.a $(LDLIBS)
else
$(NVCC) -arch=sm_86 -o $@ lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a liblzply.a $(CHASE_CUDA_OBJ) $(LDLIBS)
endif
lzply_deep_repair: lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply_deep_repair.o deep_repair.o liblzrs.a $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
# bch_polys.h is generated by gen_bch_polys.py from the rssearch data
# (~/workspace/rssearch/polys.txt + finds.txt) and checked in; it is
@@ -223,6 +227,6 @@ install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply
install -m 755 mount.lzply /sbin/mount.lzply
clean:
rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair bch_test rs_test crc16_test chase_bench_cpu chase_bench_cuda *.o liblzply.a liblzrs.a
rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair bch_test rs_test crc16_test bch_cuda_test bch_bench *.o liblzply.a liblzrs.a
.PHONY: all test install clean
+3 -8
View File
@@ -191,8 +191,7 @@ is the only LZRS format.
## Deep repair — past the BCH limit
`lzply_deep_repair` -- also built into the main tool as `lzply -r` --
recovers entries whose bit errors exceed the
`lzply_deep_repair` recovers entries whose bit errors exceed the
BCH correction limit t, in escalating levels, reporting per-level
timing ("time of arrival": how long each level took and at which
level the repair landed):
@@ -228,9 +227,7 @@ CRC-checked, 1,024 rejected by CRC, 0 false accepts.
Limits, measured honestly: Chase scans are O(nbits) trials at
~7,800 trials/s on m=22 blocks (a full scan of a 524 KiB block
takes ~9 minutes on the CPU; ~0.35 s on a CUDA build -- the L1
scan runs on the GPU when a device is present, with CPU fallback),
so beyond-t repair of large blocks is bounded
takes ~9 minutes), so beyond-t repair of large blocks is bounded
by the time budget (default 120 s per entry) and reports partial
coverage rather than pretending. Two bugs found by measurement
and fixed: the trial flip was not applied to the reconstructed
@@ -239,9 +236,7 @@ candidates before trying them, truncating the list before the
genuine candidate arrived (a 600 KiB file with 9 errors in one
block failed at a 60 s budget before the fix; it recovers after
it). Full design, bounds, and measured numbers:
`docs/deep-repair.md`. CUDA Chase write-up:
https://www.lzply.com/cuda-chase-500x-deep-repair/ . Tests:
`tests/run_deep_repair_tests.sh`
`docs/deep-repair.md`. Tests: `tests/run_deep_repair_tests.sh`
(round-trips, old-format rejection, corruption matrix,
false-accept measurement).
+44 -22
View File
@@ -42,6 +42,36 @@
#include <time.h>
#include "bch.h"
/* CUDA fast path (bch_cuda.cu, linked only when built with nvcc).
* Weak symbols: a CPU-only build leaves them NULL and always takes
* the CPU path below. bch_cuda_encode returns the stored length or 0
* on failure; bch_cuda_decode returns 0, -1 (uncorrectable) or -2
* (internal error). Any CUDA failure falls through to the CPU path,
* which re-verifies, so results are identical with or without a GPU. */
extern size_t bch_cuda_encode(const uint8_t *, size_t, const bch_poly_t *,
uint8_t *) __attribute__((weak));
extern int bch_cuda_decode(const uint8_t *, size_t, size_t,
const bch_poly_t *, uint8_t *,
int *) __attribute__((weak));
extern int bch_cuda_available(void) __attribute__((weak));
/* Minimum blob size for the GPU path, by t. A fresh process pays
* ~0.12 s of CUDA first-touch cost (context creation + first
* cudaMalloc, measured on hot_house) before any kernel runs, so the
* GPU only wins once the CPU remainder time exceeds that: t=8 runs
* ~87 MB/s on the CPU (break-even ~12 MB), t=32 ~23 MB/s
* (break-even ~3 MB). The thresholds are deliberately conservative
* and, critically, are checked BEFORE any CUDA call, so small blobs
* never pay the init cost at all. */
static size_t bch_cuda_min_len(int t)
{
if (t >= 32)
return 4u << 20;
if (t >= 16)
return 8u << 20;
return 16u << 20;
}
/* ------------------------------------------------------------------ */
/* polynomial lookup */
/* ------------------------------------------------------------------ */
@@ -614,6 +644,13 @@ size_t bch_encode(const uint8_t *data, size_t len, const bch_poly_t *p,
bch_encode_block(data, 0, p, out);
return bch_block_stored_len(0, p);
}
if (len >= bch_cuda_min_len(p->t) && bch_cuda_available &&
bch_cuda_available()) {
size_t n = bch_cuda_encode(data, len, p, out);
if (n != 0)
return n;
/* fall through to the CPU path on any CUDA failure */
}
while (off < len) {
size_t chunk = len - off;
if (chunk > maxd)
@@ -643,6 +680,13 @@ int bch_decode(const uint8_t *in, size_t len, size_t orig_len,
*corrected = c1;
return 0;
}
if (orig_len >= bch_cuda_min_len(p->t) && bch_cuda_available &&
bch_cuda_available()) {
if (bch_cuda_decode(in, len, orig_len, p, out, corrected) == 0)
return 0;
/* fall through to the CPU path on any CUDA failure or
* uncorrectable result (the CPU path re-verifies) */
}
while (off < orig_len) {
size_t chunk = orig_len - off;
if (chunk > maxd)
@@ -1290,28 +1334,6 @@ static int compute_syndrome(const uint8_t *in, size_t in_len, size_t data_len,
return 0;
}
/* Public syndrome accessor, for the CUDA Chase scan (and any other
* caller that needs S without a full decode). Same return codes as
* compute_syndrome: 0 with S filled, 1 if the remainder is zero
* (clean word), -1 on bad input. */
int bch_block_syndrome(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint32_t *S)
{
if (!in || !p || !S)
return -1;
bch_ctx_t *ctx = bch_ctx_new(p);
if (!ctx)
return -1;
const gf_tables_t *tab = gf_tables_for(p->m);
if (!tab) {
bch_ctx_free(ctx);
return -1;
}
int rc = compute_syndrome(in, in_len, data_len, p, ctx, tab, S);
bch_ctx_free(ctx);
return rc;
}
/* Column of the parity-check matrix for bit position pos:
* col_j = alpha^(j*(nbits-1-pos)), j = 1..2t. Fills col[0..2t-1]. */
static void col_at(size_t pos, size_t nbits, int t, const gf_tables_t *tab,
-6
View File
@@ -157,12 +157,6 @@ int bch_remainder_bruteforce(const uint8_t *data, size_t data_len,
/* weight-(t+2) pattern. The list is what buys the rate. */
/* ------------------------------------------------------------------ */
/* Syndrome S_1..S_2t of the received word (for the CUDA Chase scan).
* Returns 0 with S filled, 1 if the remainder is zero (clean word),
* -1 on bad input. S must hold 2*t uint32_t. */
int bch_block_syndrome(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint32_t *S);
/* Maximum distinct candidate blocks returned per chase call. */
#define BCH_CHASE_MAX_CANDS 64
/* Maximum suspect positions considered by chase2. */
+165
View File
@@ -0,0 +1,165 @@
/* bch_bench.c - micro-benchmark for the BCH layer (encode/decode).
*
* Times bch_encode / bch_decode on an in-memory blob (no LZMA, SHA or
* I/O), so the numbers isolate the remainder + memcpy cost. Also times
* a plain memcpy of the same size for reference, and verifies the
* round-trip plus 1-bit-flip correction. The same binary measures the
* CUDA path when linked with bch_cuda.o (dispatch lives inside
* bch_encode/bch_decode); without it, it measures the CPU path.
*
* Usage: bch_bench [file] [reps]
* file: input blob (default: deterministic 50 MiB generated in RAM)
* reps: timed repetitions per case (default 5, median reported)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "bch.h"
static double now_s(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;
}
static int cmp_dbl(const void *a, const void *b)
{
double x = *(const double *)a, y = *(const double *)b;
return (x > y) - (x < y);
}
static double median(double *v, int n)
{
qsort(v, (size_t)n, sizeof(double), cmp_dbl);
return v[n / 2];
}
/* Deterministic filler: xorshift64, fast and incompressible-ish. */
static void fill_pattern(uint8_t *buf, size_t len)
{
uint64_t s = 0x9e3779b97f4a7c15ULL;
size_t i = 0;
while (i + 8 <= len) {
s ^= s << 13; s ^= s >> 7; s ^= s << 17;
memcpy(buf + i, &s, 8);
i += 8;
}
while (i < len) {
s ^= s << 13; s ^= s >> 7; s ^= s << 17;
buf[i++] = (uint8_t)s;
}
}
static const bch_poly_t *poly_for(size_t len, int t)
{
/* bch_poly_for_data(524000, t) returns the m=22 poly for that t:
* 8*524000 + t*22 < 2^22-1, while m=21 (N=2^21-1) is too small. */
const bch_poly_t *p = bch_poly_for_data(524000, t);
(void)len;
return p;
}
int main(int argc, char **argv)
{
const char *path = argc > 1 ? argv[1] : NULL;
int reps = argc > 2 ? atoi(argv[2]) : 5;
if (reps < 1) reps = 1;
if (reps > 21) reps = 21;
uint8_t *data = NULL;
size_t len = 0;
if (path) {
FILE *f = fopen(path, "rb");
if (!f) { perror("fopen"); return 1; }
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
if (n < 0) { fprintf(stderr, "ftell failed\n"); return 1; }
len = (size_t)n;
data = malloc(len ? len : 1);
if (fread(data, 1, len, f) != len) { fprintf(stderr, "short read\n"); return 1; }
fclose(f);
} else {
len = 50u << 20;
data = malloc(len);
fill_pattern(data, len);
}
printf("blob %zu bytes (%.3f MiB), reps %d\n", len,
(double)len / 1048576.0, reps);
double *ts = malloc(sizeof(double) * (size_t)reps);
double s, e;
/* memcpy reference */
uint8_t *tmp = malloc(len ? len : 1);
for (int i = 0; i < reps; i++) {
s = now_s();
memcpy(tmp, data, len);
e = now_s();
ts[i] = e - s;
}
printf("memcpy : median %.4f s %8.1f MB/s\n", median(ts, reps),
(double)len / 1048576.0 / median(ts, reps));
for (int ti = 0; ti < 2; ti++) {
int t = ti == 0 ? 8 : 32;
const bch_poly_t *p = poly_for(len, t);
if (!p) { printf("t=%d: no poly\n", t); continue; }
size_t maxd = bch_max_data(p);
size_t blocks = (len + maxd - 1) / maxd;
size_t eclen = bch_encoded_len(len, p);
uint8_t *enc = malloc(eclen ? eclen : 1);
uint8_t *dec = malloc(len ? len : 1);
printf("t=%-2d poly id 0x%04x m=%d r=%d maxdata=%zu blocks=%zu stored=%zu (+%.2f%%)\n",
t, p->id, p->m, p->r, maxd, blocks, eclen,
100.0 * (double)(eclen - len) / (double)len);
/* warmup + verify round-trip once */
if (bch_encode(data, len, p, enc) != eclen) {
printf("t=%d: encode failed\n", t); return 1;
}
int corr = 0;
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0 ||
memcmp(dec, data, len) != 0) {
printf("t=%d: round-trip FAILED\n", t); return 1;
}
/* 1-bit flip in the first block must still decode. */
enc[0] ^= 0x01;
corr = 0;
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0 ||
memcmp(dec, data, len) != 0 || corr != 1) {
printf("t=%d: 1-bit-flip decode FAILED (corr=%d)\n", t, corr);
return 1;
}
enc[0] ^= 0x01;
printf("t=%d: round-trip ok, 1-bit flip corrected (corr=1)\n", t);
for (int i = 0; i < reps; i++) {
s = now_s();
if (bch_encode(data, len, p, enc) != eclen) { printf("encode fail\n"); return 1; }
e = now_s();
ts[i] = e - s;
}
double med = median(ts, reps);
printf("t=%-2d encode : median %.4f s %8.1f MB/s\n", t, med,
(double)len / 1048576.0 / med);
for (int i = 0; i < reps; i++) {
s = now_s();
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0) { printf("decode fail\n"); return 1; }
e = now_s();
ts[i] = e - s;
}
med = median(ts, reps);
printf("t=%-2d decode : median %.4f s %8.1f MB/s (corr=%d)\n", t, med,
(double)len / 1048576.0 / med, corr);
free(enc);
free(dec);
}
free(tmp);
free(data);
free(ts);
printf("ALL OK\n");
return 0;
}
+735
View File
@@ -0,0 +1,735 @@
/* bch_cuda.cu - CUDA BCH remainder for lzply.
*
* See bch_cuda.h for the design. Remainder recap (bch.c): the state
* is an r-bit value, left-aligned in nb = (r+7)/8 bytes; feeding a
* byte is rem = shift8(rem) XOR T[rem[0] XOR b], where T is the
* 256*nb table built from the generator. That step is GF(2)-linear
* in (rem, b), so feeding a chunk from zero state gives a partial
* remainder, and concatenating chunks is partial-combining with an
* advance-by-k-bytes map Adv_k (itself linear, so it is a table:
* Adv_k(S) = XOR over bytes j of Adv_k[j][S[j]]).
*
* Host-side table building duplicates bch.c exactly (glow, T, and
* Adv_1); the 12 squarings Adv_1 -> Adv_4096 run on the device.
* Bit-identity vs the CPU remainder is verified by bch_cuda_test
* (GPU encode output byte-identical to CPU encode, all 82 polys
* via the (t, size) grid, plus decode agreement on dirty blocks).
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <cuda_runtime.h>
extern "C" {
#include "bch.h"
}
#include "bch_cuda.h"
/* Debug prints on failure paths, enabled by BCH_CUDA_DEBUG=1. */
static int cu_debug(void)
{
static int d = -1;
if (d < 0)
d = getenv("BCH_CUDA_DEBUG") ? 1 : 0;
return d;
}
#define CU_DBG(...) do { if (cu_debug()) { fprintf(stderr, "bch_cuda %s:%d: ", __func__, __LINE__); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); } } while (0)
#define BCH_CUDA_CHUNK 4096
#define BCH_CUDA_MAX_NB 88 /* r max = 32*22 = 704 bits -> nb = 88 */
#define BCH_CUDA_MAX_POLYS 8
/* ------------------------------------------------------------------ */
/* host-side LFSR helpers: bit-identical copies of bch.c */
/* ------------------------------------------------------------------ */
static void cu_rem_set_bit(uint8_t *rem, int r, int i)
{
int byte = (r - 1 - i) / 8;
int bit = 7 - ((r - 1 - i) % 8);
rem[byte] |= (uint8_t)(1u << bit);
}
static void cu_rem_shl1(uint8_t *rem, int nb)
{
for (int i = 0; i < nb; i++)
rem[i] = (uint8_t)((rem[i] << 1) | (i + 1 < nb ? (rem[i + 1] >> 7) : 0));
}
static void cu_rem_bitstep(uint8_t *rem, int m, const uint8_t *glow, int nb)
{
int fb = ((rem[0] >> 7) & 1) ^ (m & 1);
cu_rem_shl1(rem, nb);
if (fb)
for (int i = 0; i < nb; i++)
rem[i] ^= glow[i];
}
/* One table-driven byte step, given an explicit table. */
static void cu_rem_feed_byte(uint8_t *rem, uint8_t b,
const uint8_t *table, int nb)
{
int idx = rem[0] ^ b;
const uint8_t *t = table + (size_t)idx * nb;
for (int i = 0; i < nb - 1; i++)
rem[i] = rem[i + 1] ^ t[i];
rem[nb - 1] = t[nb - 1];
}
static int cu_rem_is_zero(const uint8_t *rem, int nb)
{
for (int i = 0; i < nb; i++)
if (rem[i])
return 0;
return 1;
}
/* ------------------------------------------------------------------ */
/* device availability */
/* ------------------------------------------------------------------ */
extern "C" int bch_cuda_available(void)
{
static int cached = -1;
if (cached < 0) {
int n = 0;
cudaError_t err = cudaGetDeviceCount(&n);
cached = (err == cudaSuccess && n > 0) ? 1 : 0;
}
return cached;
}
/* ------------------------------------------------------------------ */
/* kernels */
/* ------------------------------------------------------------------ */
/* One thread per chunk: serial table LFSR over the chunk, zero state.
* Templated on NB so the remainder stays in registers; the generic
* version covers any other nb (local-memory remainder). */
template <int NB>
__global__ void partial_kernel_t(const uint8_t *__restrict__ in,
const int *__restrict__ chunk_off,
const int *__restrict__ chunk_len,
const uint8_t *__restrict__ table,
uint8_t *__restrict__ part, int nchunks)
{
int c = blockIdx.x * blockDim.x + threadIdx.x;
if (c >= nchunks)
return;
const uint8_t *src = in + chunk_off[c];
int len = chunk_len[c];
uint8_t rem[NB];
#pragma unroll
for (int i = 0; i < NB; i++)
rem[i] = 0;
for (int k = 0; k < len; k++) {
int idx = rem[0] ^ src[k];
const uint8_t *t = table + (size_t)idx * NB;
#pragma unroll
for (int i = 0; i < NB - 1; i++)
rem[i] = rem[i + 1] ^ t[i];
rem[NB - 1] = t[NB - 1];
}
uint8_t *dst = part + (size_t)c * NB;
#pragma unroll
for (int i = 0; i < NB; i++)
dst[i] = rem[i];
}
__global__ void partial_kernel_g(const uint8_t *__restrict__ in,
const int *__restrict__ chunk_off,
const int *__restrict__ chunk_len,
const uint8_t *__restrict__ table,
uint8_t *__restrict__ part, int nchunks,
int nb)
{
int c = blockIdx.x * blockDim.x + threadIdx.x;
if (c >= nchunks)
return;
const uint8_t *src = in + chunk_off[c];
int len = chunk_len[c];
uint8_t rem[BCH_CUDA_MAX_NB];
for (int i = 0; i < nb; i++)
rem[i] = 0;
for (int k = 0; k < len; k++) {
int idx = rem[0] ^ src[k];
const uint8_t *t = table + (size_t)idx * nb;
for (int i = 0; i < nb - 1; i++)
rem[i] = rem[i + 1] ^ t[i];
rem[nb - 1] = t[nb - 1];
}
uint8_t *dst = part + (size_t)c * nb;
for (int i = 0; i < nb; i++)
dst[i] = rem[i];
}
/* One thread per block: combine that block's chunk partials.
* acc = P_first; then acc = Adv_CHUNK(acc) XOR P_k for each later
* (full) chunk. adv is the nb*256*nb advance table. */
template <int NB>
__global__ void combine_kernel_t(const uint8_t *__restrict__ part,
const int *__restrict__ block_first,
const int *__restrict__ block_nchunk,
const uint8_t *__restrict__ adv,
uint8_t *__restrict__ rem_out, int nblocks)
{
int b = blockIdx.x * blockDim.x + threadIdx.x;
if (b >= nblocks)
return;
uint8_t acc[NB];
const uint8_t *p0 = part + (size_t)block_first[b] * NB;
#pragma unroll
for (int i = 0; i < NB; i++)
acc[i] = p0[i];
for (int k = 1; k < block_nchunk[b]; k++) {
uint8_t nxt[NB];
#pragma unroll
for (int i = 0; i < NB; i++)
nxt[i] = 0;
#pragma unroll
for (int j = 0; j < NB; j++) {
const uint8_t *a = adv + ((size_t)j * 256 + acc[j]) * NB;
#pragma unroll
for (int i = 0; i < NB; i++)
nxt[i] ^= a[i];
}
const uint8_t *pk = part + (size_t)(block_first[b] + k) * NB;
#pragma unroll
for (int i = 0; i < NB; i++)
acc[i] = nxt[i] ^ pk[i];
}
uint8_t *dst = rem_out + (size_t)b * NB;
#pragma unroll
for (int i = 0; i < NB; i++)
dst[i] = acc[i];
}
__global__ void combine_kernel_g(const uint8_t *__restrict__ part,
const int *__restrict__ block_first,
const int *__restrict__ block_nchunk,
const uint8_t *__restrict__ adv,
uint8_t *__restrict__ rem_out, int nblocks,
int nb)
{
int b = blockIdx.x * blockDim.x + threadIdx.x;
if (b >= nblocks)
return;
uint8_t acc[BCH_CUDA_MAX_NB];
const uint8_t *p0 = part + (size_t)block_first[b] * nb;
for (int i = 0; i < nb; i++)
acc[i] = p0[i];
for (int k = 1; k < block_nchunk[b]; k++) {
uint8_t nxt[BCH_CUDA_MAX_NB];
for (int i = 0; i < nb; i++)
nxt[i] = 0;
for (int j = 0; j < nb; j++) {
const uint8_t *a = adv + ((size_t)j * 256 + acc[j]) * nb;
for (int i = 0; i < nb; i++)
nxt[i] ^= a[i];
}
const uint8_t *pk = part + (size_t)(block_first[b] + k) * nb;
for (int i = 0; i < nb; i++)
acc[i] = nxt[i] ^ pk[i];
}
uint8_t *dst = rem_out + (size_t)b * nb;
for (int i = 0; i < nb; i++)
dst[i] = acc[i];
}
/* Advance-table squaring: one thread per (byte j, value v) entry.
* out[j][v] = Adv(Adv[j][v]), i.e. Adv_{2k} from Adv_k. */
__global__ void adv_square_kernel(const uint8_t *__restrict__ adv_in,
uint8_t *__restrict__ adv_out, int nb)
{
int e = blockIdx.x * blockDim.x + threadIdx.x;
if (e >= nb * 256)
return;
uint8_t v[BCH_CUDA_MAX_NB];
const uint8_t *src = adv_in + (size_t)e * nb;
for (int i = 0; i < nb; i++)
v[i] = src[i];
uint8_t out[BCH_CUDA_MAX_NB];
for (int i = 0; i < nb; i++)
out[i] = 0;
for (int j = 0; j < nb; j++) {
const uint8_t *row = adv_in + ((size_t)j * 256 + v[j]) * nb;
for (int i = 0; i < nb; i++)
out[i] ^= row[i];
}
uint8_t *dst = adv_out + (size_t)e * nb;
for (int i = 0; i < nb; i++)
dst[i] = out[i];
}
/* ------------------------------------------------------------------ */
/* per-poly cached device state */
/* ------------------------------------------------------------------ */
typedef struct {
uint16_t id;
int nb;
int r;
uint8_t glow[BCH_CUDA_MAX_NB];
uint8_t *d_table; /* 256*nb */
uint8_t *d_adv; /* nb*256*nb, advance by BCH_CUDA_CHUNK */
uint8_t *d_adv2; /* scratch for squaring */
} cu_poly_t;
static cu_poly_t g_polys[BCH_CUDA_MAX_POLYS];
static int g_npolys = 0;
static void cu_poly_cleanup_partial(cu_poly_t *cp)
{
if (cp->d_table) { cudaFree(cp->d_table); cp->d_table = NULL; }
if (cp->d_adv) { cudaFree(cp->d_adv); cp->d_adv = NULL; }
if (cp->d_adv2) { cudaFree(cp->d_adv2); cp->d_adv2 = NULL; }
}
static cu_poly_t *cu_poly_get(const bch_poly_t *p)
{
for (int i = 0; i < g_npolys; i++)
if (g_polys[i].id == p->id && g_polys[i].d_table)
return &g_polys[i];
if (g_npolys >= BCH_CUDA_MAX_POLYS) {
/* Evict everything (rebuilds are ~ms: the squaring runs on
* the device). One lzply process normally uses 1-2 polys. */
for (int i = 0; i < g_npolys; i++)
cu_poly_cleanup_partial(&g_polys[i]);
memset(g_polys, 0, sizeof(g_polys));
g_npolys = 0;
CU_DBG("poly cache evicted");
}
cu_poly_t *cp = &g_polys[g_npolys];
memset(cp, 0, sizeof(*cp));
cp->id = p->id;
cp->r = p->r;
cp->nb = (p->r + 7) / 8;
int nb = cp->nb;
uint8_t *table = NULL;
uint8_t *adv1 = NULL;
/* glow + T on the host (same construction as bch_ctx_new). */
const uint8_t *gen = bch_poly_bytes + p->off;
for (int i = 0; i < p->r; i++)
if ((gen[i / 8] >> (i % 8)) & 1)
cu_rem_set_bit(cp->glow, p->r, i);
table = (uint8_t *)malloc((size_t)256 * nb);
if (!table)
goto fail;
for (int u = 0; u < 256; u++) {
uint8_t *t = table + (size_t)u * nb;
memset(t, 0, nb);
for (int b = 7; b >= 0; b--)
cu_rem_bitstep(t, (u >> b) & 1, cp->glow, nb);
}
/* Adv_1 on the host: one zero byte fed from each single-byte state. */
adv1 = (uint8_t *)malloc((size_t)nb * 256 * nb);
if (!adv1) {
free(table);
goto fail;
}
for (int j = 0; j < nb; j++) {
for (int v = 0; v < 256; v++) {
uint8_t *s = adv1 + ((size_t)j * 256 + v) * nb;
memset(s, 0, nb);
s[j] = (uint8_t)v;
cu_rem_feed_byte(s, 0, table, nb);
}
}
{
cudaError_t err;
err = cudaMalloc(&cp->d_table, (size_t)256 * nb);
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_table malloc: %s", p->id, cudaGetErrorString(err)); goto fail; }
err = cudaMemcpy(cp->d_table, table, (size_t)256 * nb,
cudaMemcpyHostToDevice);
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_table copy: %s", p->id, cudaGetErrorString(err)); goto fail; }
err = cudaMalloc(&cp->d_adv, (size_t)nb * 256 * nb);
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_adv malloc: %s", p->id, cudaGetErrorString(err)); goto fail; }
err = cudaMalloc(&cp->d_adv2, (size_t)nb * 256 * nb);
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_adv2 malloc: %s", p->id, cudaGetErrorString(err)); goto fail; }
err = cudaMemcpy(cp->d_adv, adv1, (size_t)nb * 256 * nb,
cudaMemcpyHostToDevice);
free(table);
free(adv1);
if (err != cudaSuccess) { CU_DBG("poly 0x%04x d_adv copy: %s", p->id, cudaGetErrorString(err)); goto fail; }
/* Square on the device: Adv_1 -> Adv_CHUNK (CHUNK is a power of 2). */
int steps = 0;
while ((1 << steps) < BCH_CUDA_CHUNK)
steps++;
uint8_t *cur = cp->d_adv, *nxt = cp->d_adv2;
int nentries = nb * 256;
for (int s = 0; s < steps; s++) {
adv_square_kernel<<<(nentries + 255) / 256, 256>>>(cur, nxt, nb);
err = cudaGetLastError();
if (err != cudaSuccess) { CU_DBG("poly 0x%04x square %d launch: %s", p->id, s, cudaGetErrorString(err)); goto fail; }
err = cudaDeviceSynchronize();
if (err != cudaSuccess) { CU_DBG("poly 0x%04x square %d sync: %s", p->id, s, cudaGetErrorString(err)); goto fail; }
uint8_t *tmp = cur;
cur = nxt;
nxt = tmp;
}
if (cur != cp->d_adv) {
err = cudaMemcpy(cp->d_adv, cur, (size_t)nb * 256 * nb,
cudaMemcpyDeviceToDevice);
if (err != cudaSuccess) { CU_DBG("poly 0x%04x adv copyback: %s", p->id, cudaGetErrorString(err)); goto fail; }
}
}
g_npolys++;
return cp;
fail:
/* Leave no poisoned slot behind: a retry rebuilds from scratch. */
cu_poly_cleanup_partial(cp);
memset(cp, 0, sizeof(*cp));
return NULL;
}
/* ------------------------------------------------------------------ */
/* cached device scratch buffers */
/* ------------------------------------------------------------------ */
static uint8_t *g_d_in = NULL;
static size_t g_d_in_cap = 0;
static uint8_t *g_d_part = NULL;
static size_t g_d_part_cap = 0;
static uint8_t *g_d_rem = NULL;
static size_t g_d_rem_cap = 0;
static int *g_d_coff = NULL, *g_d_clen = NULL;
static int *g_d_bfirst = NULL, *g_d_bnc = NULL;
static size_t g_d_coff_cap = 0;
static size_t g_d_clen_cap = 0;
static size_t g_d_bfirst_cap = 0;
static size_t g_d_bnc_cap = 0;
static int cu_ensure_u8(uint8_t **ptr, size_t *cap, size_t need)
{
if (*cap >= need)
return 0;
if (*ptr)
cudaFree(*ptr);
size_t ncap = *cap ? *cap : (1u << 20);
while (ncap < need)
ncap *= 2;
if (cudaMalloc(ptr, ncap) != cudaSuccess) {
*ptr = NULL;
*cap = 0;
return -1;
}
*cap = ncap;
return 0;
}
static int cu_ensure_int(int **ptr, size_t *cap, size_t need)
{
if (*cap >= need)
return 0;
if (*ptr)
cudaFree(*ptr);
size_t ncap = *cap ? *cap : 4096;
while (ncap < need)
ncap *= 2;
if (cudaMalloc((void **)ptr, ncap * sizeof(int)) != cudaSuccess) {
*ptr = NULL;
*cap = 0;
return -1;
}
*cap = ncap;
return 0;
}
/* ------------------------------------------------------------------ */
/* chunk plan + remainder runner */
/* ------------------------------------------------------------------ */
/* Blocks are byte strings [bstart[b], bstart[b]+blen[b]).
* Chunk 0 of each block is short (len - (n-1)*CHUNK), the rest are
* full CHUNK bytes, so every combine step advances by exactly CHUNK. */
static int cu_plan(const size_t *bstart, const size_t *blen, int nblocks,
int *coff, int *clen, int *bfirst, int *bnc)
{
int nc = 0;
for (int b = 0; b < nblocks; b++) {
size_t L = blen[b];
int n = (int)((L + BCH_CUDA_CHUNK - 1) / BCH_CUDA_CHUNK);
if (n < 1)
n = 1;
bfirst[b] = nc;
bnc[b] = n;
size_t first = L - (size_t)(n - 1) * BCH_CUDA_CHUNK;
for (int k = 0; k < n; k++) {
coff[nc] = (int)(bstart[b] +
(k == 0 ? 0 : first + (size_t)(k - 1) * BCH_CUDA_CHUNK));
clen[nc] = (int)(k == 0 ? first : BCH_CUDA_CHUNK);
nc++;
}
}
return nc;
}
static int cu_remainders(cu_poly_t *cp, int nchunks, int nblocks)
{
int nb = cp->nb;
dim3 pb(256);
dim3 pg((unsigned)((nchunks + 255) / 256));
switch (nb) {
case 3: partial_kernel_t<3><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
case 6: partial_kernel_t<6><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
case 11: partial_kernel_t<11><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
case 22: partial_kernel_t<22><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
case 44: partial_kernel_t<44><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
case 88: partial_kernel_t<88><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
default: partial_kernel_g<<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks, nb); break;
}
{
cudaError_t err = cudaGetLastError();
if (err != cudaSuccess) {
CU_DBG("partial kernel: %s", cudaGetErrorString(err));
return -1;
}
}
dim3 cb(256);
dim3 cg((unsigned)((nblocks + 255) / 256));
switch (nb) {
case 3: combine_kernel_t<3><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
case 6: combine_kernel_t<6><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
case 11: combine_kernel_t<11><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
case 22: combine_kernel_t<22><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
case 44: combine_kernel_t<44><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
case 88: combine_kernel_t<88><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
default: combine_kernel_g<<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks, nb); break;
}
{
cudaError_t err = cudaGetLastError();
if (err != cudaSuccess) {
CU_DBG("combine kernel: %s", cudaGetErrorString(err));
return -1;
}
err = cudaDeviceSynchronize();
if (err != cudaSuccess) {
CU_DBG("remainders sync: %s", cudaGetErrorString(err));
return -1;
}
}
return 0;
}
/* Upload the chunk plan; returns 0 or -1. */
static int cu_upload_plan(const int *coff, const int *clen,
const int *bfirst, const int *bnc,
int nchunks, int nblocks)
{
if (cu_ensure_int(&g_d_coff, &g_d_coff_cap, (size_t)nchunks) != 0)
return -1;
if (cu_ensure_int(&g_d_clen, &g_d_clen_cap, (size_t)nchunks) != 0)
return -1;
if (cu_ensure_int(&g_d_bfirst, &g_d_bfirst_cap, (size_t)nblocks) != 0)
return -1;
if (cu_ensure_int(&g_d_bnc, &g_d_bnc_cap, (size_t)nblocks) != 0)
return -1;
if (cudaMemcpy(g_d_coff, coff, (size_t)nchunks * sizeof(int),
cudaMemcpyHostToDevice) != cudaSuccess)
return -1;
if (cudaMemcpy(g_d_clen, clen, (size_t)nchunks * sizeof(int),
cudaMemcpyHostToDevice) != cudaSuccess)
return -1;
if (cudaMemcpy(g_d_bfirst, bfirst, (size_t)nblocks * sizeof(int),
cudaMemcpyHostToDevice) != cudaSuccess)
return -1;
if (cudaMemcpy(g_d_bnc, bnc, (size_t)nblocks * sizeof(int),
cudaMemcpyHostToDevice) != cudaSuccess)
return -1;
return 0;
}
/* ------------------------------------------------------------------ */
/* public API */
/* ------------------------------------------------------------------ */
extern "C" size_t bch_cuda_encode(const uint8_t *data, size_t len,
const bch_poly_t *p, uint8_t *out)
{
if (!data || !out || !p || len == 0)
return 0;
if (!bch_cuda_available())
return 0;
cu_poly_t *cp = cu_poly_get(p);
if (!cp)
return 0;
int nb = cp->nb;
size_t maxd = bch_max_data(p);
int nblocks = (int)((len + maxd - 1) / maxd);
size_t *bstart = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
size_t *blen = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
int *coff = NULL, *clen = NULL, *bfirst = NULL, *bnc = NULL;
uint8_t *rem = NULL;
size_t ret = 0;
if (!bstart || !blen)
goto done;
{
size_t off = 0;
for (int b = 0; b < nblocks; b++) {
size_t chunk = len - off;
if (chunk > maxd)
chunk = maxd;
bstart[b] = off;
blen[b] = chunk;
off += chunk;
}
}
/* Worst-case chunk count: every block split at CHUNK + 1. */
coff = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
clen = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
bfirst = (int *)malloc(sizeof(int) * (size_t)nblocks);
bnc = (int *)malloc(sizeof(int) * (size_t)nblocks);
if (!coff || !clen || !bfirst || !bnc)
goto done;
{
int nchunks = cu_plan(bstart, blen, nblocks, coff, clen, bfirst, bnc);
if (cu_ensure_u8(&g_d_in, &g_d_in_cap, len) != 0)
goto done;
if (cu_ensure_u8(&g_d_part, &g_d_part_cap, (size_t)nchunks * nb) != 0)
goto done;
if (cu_ensure_u8(&g_d_rem, &g_d_rem_cap, (size_t)nblocks * nb) != 0)
goto done;
if (cudaMemcpy(g_d_in, data, len, cudaMemcpyHostToDevice) != cudaSuccess)
goto done;
if (cu_upload_plan(coff, clen, bfirst, bnc, nchunks, nblocks) != 0)
goto done;
if (cu_remainders(cp, nchunks, nblocks) != 0)
goto done;
rem = (uint8_t *)malloc((size_t)nblocks * nb);
if (!rem)
goto done;
if (cudaMemcpy(rem, g_d_rem, (size_t)nblocks * nb,
cudaMemcpyDeviceToHost) != cudaSuccess)
goto done;
size_t woff = 0;
for (int b = 0; b < nblocks; b++) {
memcpy(out + woff, data + bstart[b], blen[b]);
memcpy(out + woff + blen[b], rem + (size_t)b * nb, nb);
woff += blen[b] + nb;
}
ret = woff;
}
done:
free(bstart);
free(blen);
free(coff);
free(clen);
free(bfirst);
free(bnc);
free(rem);
return ret;
}
extern "C" int bch_cuda_decode(const uint8_t *in, size_t len, size_t orig_len,
const bch_poly_t *p, uint8_t *out,
int *corrected)
{
if (corrected)
*corrected = 0;
if (!in || !out || !p)
return -2;
if (orig_len == 0)
return -2; /* CPU handles the empty-blob block */
if (len != bch_encoded_len(orig_len, p))
return -2; /* malformed length: let the CPU path report it */
if (!bch_cuda_available())
return -2;
cu_poly_t *cp = cu_poly_get(p);
if (!cp)
return -2;
int nb = cp->nb;
int r = cp->r;
size_t maxd = bch_max_data(p);
int nblocks = (int)((orig_len + maxd - 1) / maxd);
size_t *bstart = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
size_t *blen = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
size_t *dlen = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
size_t *doff = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
int *coff = NULL, *clen = NULL, *bfirst = NULL, *bnc = NULL;
uint8_t *rem = NULL;
int ret = -2;
if (!bstart || !blen || !dlen || !doff)
goto done;
{
size_t off = 0, roff = 0;
for (int b = 0; b < nblocks; b++) {
size_t chunk = orig_len - off;
if (chunk > maxd)
chunk = maxd;
dlen[b] = chunk;
doff[b] = off;
bstart[b] = roff; /* stored offset */
blen[b] = chunk + (size_t)(r / 8); /* data + whole parity bytes */
off += chunk;
roff += chunk + nb;
}
}
coff = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
clen = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
bfirst = (int *)malloc(sizeof(int) * (size_t)nblocks);
bnc = (int *)malloc(sizeof(int) * (size_t)nblocks);
if (!coff || !clen || !bfirst || !bnc)
goto done;
{
int nchunks = cu_plan(bstart, blen, nblocks, coff, clen, bfirst, bnc);
if (cu_ensure_u8(&g_d_in, &g_d_in_cap, len) != 0)
goto done;
if (cu_ensure_u8(&g_d_part, &g_d_part_cap, (size_t)nchunks * nb) != 0)
goto done;
if (cu_ensure_u8(&g_d_rem, &g_d_rem_cap, (size_t)nblocks * nb) != 0)
goto done;
if (cudaMemcpy(g_d_in, in, len, cudaMemcpyHostToDevice) != cudaSuccess)
goto done;
if (cu_upload_plan(coff, clen, bfirst, bnc, nchunks, nblocks) != 0)
goto done;
if (cu_remainders(cp, nchunks, nblocks) != 0)
goto done;
rem = (uint8_t *)malloc((size_t)nblocks * nb);
if (!rem)
goto done;
if (cudaMemcpy(rem, g_d_rem, (size_t)nblocks * nb,
cudaMemcpyDeviceToHost) != cudaSuccess)
goto done;
int whole = r / 8;
int total_corr = 0;
for (int b = 0; b < nblocks; b++) {
uint8_t *rb = rem + (size_t)b * nb;
/* Feed the remaining (r%8) parity bits, MSB first, from
* the final parity byte -- the same tail rem_of_codeword
* feeds bit-by-bit. */
const uint8_t *par = in + bstart[b] + dlen[b];
for (int bit = 7; bit >= 8 - (r % 8) && (r % 8); bit--)
cu_rem_bitstep(rb, (par[whole] >> bit) & 1, cp->glow, nb);
if (cu_rem_is_zero(rb, nb)) {
memcpy(out + doff[b], in + bstart[b], dlen[b]);
continue;
}
/* Dirty block: CPU BM + Chien, identical to the CPU path. */
int c1 = 0;
if (bch_decode_block(in + bstart[b], dlen[b] + nb, dlen[b], p,
out + doff[b], &c1) != 0) {
ret = -1;
goto done;
}
total_corr += c1;
}
if (corrected)
*corrected = total_corr;
ret = 0;
}
done:
free(bstart);
free(blen);
free(dlen);
free(doff);
free(coff);
free(clen);
free(bfirst);
free(bnc);
free(rem);
return ret;
}
+56
View File
@@ -0,0 +1,56 @@
/* bch_cuda.h - CUDA BCH remainder for lzply.
*
* GPU fast path for the BCH remainder (bch_encode / bch_decode).
* The remainder is GF(2)-linear, so parallel-CRC-style chunking
* applies: split each block into 4096-byte chunks, compute each
* chunk's partial remainder (zero initial state) on the GPU, then
* combine with a precomputed advance-by-4096-bytes table
* (Adv(S) = the state S advanced by 4096 zero bytes; built on the
* device by repeated squaring from Adv_1).
*
* Chunking puts the short chunk FIRST in each block, so every combine
* step advances by exactly 4096 bytes -- no arbitrary-length advance
* table is ever needed.
*
* Encode is fully GPU (remainder per block -> parity bytes). Decode
* uses the GPU remainder for the clean path (remainder zero -> copy
* the data out); a block with a nonzero remainder falls back to the
* CPU bch_decode_block (Berlekamp-Massey + Chien), so correction
* behaviour is identical to the CPU path.
*
* All functions fall back gracefully: bch_cuda_encode returns 0 and
* bch_cuda_decode returns -2 on any CUDA problem, and bch.c treats
* those as "use the CPU path". bch_cuda_available() is 0 when no
* CUDA device is present. The symbols are referenced weakly from
* bch.c, so a CPU-only build (no bch_cuda.o linked) works unchanged.
*/
#ifndef LZPLY_BCH_CUDA_H
#define LZPLY_BCH_CUDA_H
#include <stddef.h>
#include <stdint.h>
#include "bch.h"
#ifdef __cplusplus
extern "C" {
#endif
/* 1 if a CUDA device is present and usable, 0 otherwise. */
int bch_cuda_available(void);
/* Encode a whole blob on the GPU (same contract as bch_encode).
* Returns the stored length, or 0 on any failure (caller: use CPU). */
size_t bch_cuda_encode(const uint8_t *data, size_t len,
const bch_poly_t *p, uint8_t *out);
/* Decode a whole blob on the GPU (same contract as bch_decode).
* Returns 0 on success, -1 if any block is uncorrectable, -2 on an
* internal/CUDA error (caller: fall back to the CPU path). */
int bch_cuda_decode(const uint8_t *in, size_t len, size_t orig_len,
const bch_poly_t *p, uint8_t *out, int *corrected);
#ifdef __cplusplus
}
#endif
#endif /* LZPLY_BCH_CUDA_H */
+388
View File
@@ -0,0 +1,388 @@
/* bch_cuda_test.c - verification + benchmark for the CUDA BCH path.
*
* 1. Correctness: for t in {1,2,4,8,16,32} and a spread of blob sizes
* (1 B .. 1 MiB, incl. chunk and block boundaries), GPU encode must
* be byte-identical to a CPU reference encode built block-by-block
* from the INDEPENDENT brute-force remainder (bit-by-bit long
* division -- no table LFSR, no dispatch, so the comparison cannot
* be circular: for len >= 1MB bch_encode itself dispatches to the
* GPU). GPU decode of a CPU-encoded blob (clean, and with up to t
* flipped bits in one block) must match a per-block CPU decode via
* bch_decode_block; a t+1-bit flip must make GPU and CPU decode
* agree.
* 2. Benchmark: GPU encode/decode MB/s at 1/4/50 MB for t=8/32
* (median of 5), via the direct CUDA entry points and via the
* bch_encode/bch_decode dispatch (they must agree -- dispatch
* overhead ~0). The first CUDA call (table build + context init)
* is timed separately from steady state. True CPU numbers come
* from bch_bench_cpu (built without bch_cuda.o); compare against
* those in the report.
*
* Usage: bch_cuda_test [datafile]
* datafile: blob for the benchmark (default: generated 50 MiB).
* Exit 0 only if every check passes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "bch.h"
#include "bch_cuda.h"
static int fails = 0;
static int checks = 0;
#define CHECK(cond, ...) do { \
checks++; \
if (!(cond)) { fails++; printf("FAIL: " __VA_ARGS__); printf("\n"); } \
} while (0)
static uint64_t rng_state = 0x12345678abcdefULL;
static uint64_t xr(void)
{
rng_state ^= rng_state << 13;
rng_state ^= rng_state >> 7;
rng_state ^= rng_state << 17;
return rng_state;
}
static void rand_bytes(uint8_t *buf, size_t n)
{
for (size_t i = 0; i < n; i++)
buf[i] = (uint8_t)(xr() & 0xff);
}
static void flip_bits(uint8_t *buf, size_t nbits, int k)
{
size_t *pos = malloc(sizeof(size_t) * (size_t)(k > 0 ? k : 1));
int got = 0;
while (got < k) {
size_t p = (size_t)(xr() % nbits);
int dup = 0;
for (int i = 0; i < got; i++)
if (pos[i] == p)
dup = 1;
if (!dup)
pos[got++] = p;
}
for (int i = 0; i < k; i++)
buf[pos[i] / 8] ^= (uint8_t)(1u << (7 - (pos[i] % 8)));
free(pos);
}
static double now_s(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;
}
static int cmp_dbl(const void *a, const void *b)
{
double x = *(const double *)a, y = *(const double *)b;
return (x > y) - (x < y);
}
static double median(double *v, int n)
{
qsort(v, (size_t)n, sizeof(double), cmp_dbl);
return v[n / 2];
}
static int t_index(int t)
{
switch (t) {
case 1: return 0;
case 2: return 1;
case 4: return 2;
case 8: return 3;
case 16: return 4;
case 32: return 5;
default: return -1;
}
}
/* Same selection as lzply_lib: auto-pick, else largest m for the t. */
static const bch_poly_t *test_poly(size_t len, int t)
{
const bch_poly_t *p = bch_poly_for_data(len, t);
if (p)
return p;
int ti = t_index(t);
if (ti < 0)
return NULL;
for (int m = BCH_MAX_M; m >= BCH_MIN_M; m--) {
uint16_t id = bch_poly_by_mt[m - BCH_MIN_M][ti];
if (id)
return bch_poly_by_id(id);
}
return NULL;
}
/* CPU reference encode: block-by-block, brute-force remainder. */
static void ref_encode(const uint8_t *data, size_t len,
const bch_poly_t *p, uint8_t *out)
{
size_t maxd = bch_max_data(p);
size_t off = 0, woff = 0;
if (len == 0) {
if (bch_remainder_bruteforce(data, 0, p, out) != 0) {
printf("ref_encode: bruteforce failed\n");
exit(1);
}
return;
}
while (off < len) {
size_t chunk = len - off;
if (chunk > maxd)
chunk = maxd;
size_t nb = bch_block_stored_len(chunk, p) - chunk;
uint8_t *rem = malloc(nb);
if (bch_remainder_bruteforce(data + off, chunk, p, rem) != 0) {
printf("ref_encode: bruteforce failed\n");
exit(1);
}
memcpy(out + woff, data + off, chunk);
memcpy(out + woff + chunk, rem, nb);
free(rem);
woff += bch_block_stored_len(chunk, p);
off += chunk;
}
}
/* CPU reference decode: block-by-block via bch_decode_block.
* Returns 0 ok, -1 uncorrectable. */
static int ref_decode(const uint8_t *in, size_t len, size_t orig_len,
const bch_poly_t *p, uint8_t *out, int *corrected)
{
if (corrected)
*corrected = 0;
size_t maxd = bch_max_data(p);
size_t off = 0, roff = 0;
int total = 0;
if (orig_len == 0) {
if (len != bch_block_stored_len(0, p))
return -1;
int c1 = 0;
if (bch_decode_block(in, len, 0, p, out, &c1) != 0)
return -1;
if (corrected)
*corrected = c1;
return 0;
}
while (off < orig_len) {
size_t chunk = orig_len - off;
if (chunk > maxd)
chunk = maxd;
size_t slen = bch_block_stored_len(chunk, p);
if (roff + slen > len)
return -1;
int c1 = 0;
if (bch_decode_block(in + roff, slen, chunk, p, out + off, &c1) != 0)
return -1;
total += c1;
roff += slen;
off += chunk;
}
if (corrected)
*corrected = total;
return 0;
}
static void correctness_case(const uint8_t *data, size_t len, int t)
{
const bch_poly_t *p = test_poly(len, t);
if (!p) {
printf("SKIP t=%d len=%zu: no poly\n", t, len);
return;
}
size_t eclen = bch_encoded_len(len, p);
uint8_t *enc_cpu = malloc(eclen ? eclen : 1);
uint8_t *enc_gpu = malloc(eclen ? eclen : 1);
uint8_t *dec = malloc(len ? len : 1);
uint8_t *dec2 = malloc(len ? len : 1);
uint8_t *work = malloc(eclen ? eclen : 1);
if (!enc_cpu || !enc_gpu || !dec || !dec2 || !work) {
printf("OOM\n");
exit(1);
}
ref_encode(data, len, p, enc_cpu);
size_t gn = bch_cuda_encode(data, len, p, enc_gpu);
CHECK(gn == eclen, "t=%d len=%zu gpu encode len %zu != %zu",
t, len, gn, eclen);
CHECK(gn == eclen && memcmp(enc_cpu, enc_gpu, eclen) == 0,
"t=%d len=%zu poly 0x%04x m=%d gpu encode != cpu(bruteforce) encode",
t, len, p->id, p->m);
/* clean decode both ways */
int cc = -1, gc = -1;
CHECK(ref_decode(enc_cpu, eclen, len, p, dec, &cc) == 0 &&
memcmp(dec, data, len) == 0,
"t=%d len=%zu cpu decode of cpu encode", t, len);
CHECK(bch_cuda_decode(enc_cpu, eclen, len, p, dec2, &gc) == 0 &&
memcmp(dec2, data, len) == 0 && gc == 0,
"t=%d len=%zu gpu decode of cpu encode (gc=%d)", t, len, gc);
CHECK(ref_decode(enc_gpu, eclen, len, p, dec, &cc) == 0 &&
memcmp(dec, data, len) == 0,
"t=%d len=%zu cpu decode of gpu encode", t, len);
CHECK(bch_cuda_decode(enc_gpu, eclen, len, p, dec2, &gc) == 0 &&
memcmp(dec2, data, len) == 0 && gc == 0,
"t=%d len=%zu gpu decode of gpu encode", t, len);
/* dirty decode: flip k<=t bits in the first block. */
if (len > 0) {
size_t first = len < bch_max_data(p) ? len : bch_max_data(p);
size_t nbits = (size_t)8 * first + p->r;
int k = t < 3 ? t : 3;
memcpy(work, enc_cpu, eclen);
flip_bits(work, nbits, k);
int rc_cpu = ref_decode(work, eclen, len, p, dec, &cc);
int rc_gpu = bch_cuda_decode(work, eclen, len, p, dec2, &gc);
CHECK(rc_cpu == rc_gpu,
"t=%d len=%zu %d-bit flip: cpu rc=%d gpu rc=%d",
t, len, k, rc_cpu, rc_gpu);
if (rc_cpu == 0)
CHECK(memcmp(dec, dec2, len) == 0 && cc == gc,
"t=%d len=%zu %d-bit flip: decoded bytes/corr differ (cc=%d gc=%d)",
t, len, k, cc, gc);
/* t+1 bits in one block: GPU and CPU decode must agree. */
memcpy(work, enc_cpu, eclen);
flip_bits(work, nbits, t + 1);
rc_cpu = ref_decode(work, eclen, len, p, dec, &cc);
rc_gpu = bch_cuda_decode(work, eclen, len, p, dec2, &gc);
CHECK(rc_cpu == rc_gpu,
"t=%d len=%zu %d-bit flip: cpu rc=%d gpu rc=%d (must agree)",
t, len, t + 1, rc_cpu, rc_gpu);
if (rc_cpu == 0)
CHECK(memcmp(dec, dec2, len) == 0,
"t=%d len=%zu %d-bit flip: both decoded but differ",
t, len, t + 1);
}
free(enc_cpu);
free(enc_gpu);
free(dec);
free(dec2);
free(work);
}
static void bench_case(const uint8_t *data, size_t len, int t)
{
const bch_poly_t *p = test_poly(len, t);
if (!p) {
printf("SKIP bench t=%d len=%zu: no poly\n", t, len);
return;
}
size_t eclen = bch_encoded_len(len, p);
uint8_t *enc = malloc(eclen);
uint8_t *enc2 = malloc(eclen);
uint8_t *dec = malloc(len);
double ts[5];
double s, e;
int corr = 0;
/* first-call timing (table build + context init) */
s = now_s();
size_t gn = bch_cuda_encode(data, len, p, enc2);
e = now_s();
printf("t=%-2d len=%8zu first-gpu-encode %7.4f s (%7.1f MB/s, incl table build)\n",
t, len, e - s, (double)len / 1048576.0 / (e - s));
if (gn != eclen) { printf("gpu enc fail\n"); exit(1); }
/* steady-state GPU direct */
for (int i = 0; i < 5; i++) {
s = now_s();
gn = bch_cuda_encode(data, len, p, enc2);
e = now_s();
ts[i] = e - s;
if (gn != eclen) { printf("gpu enc fail\n"); exit(1); }
}
double gpu_enc = median(ts, 5);
/* dispatch path (bch_encode): must match GPU direct */
for (int i = 0; i < 5; i++) {
s = now_s();
if (bch_encode(data, len, p, enc) != eclen) { printf("disp enc fail\n"); exit(1); }
e = now_s();
ts[i] = e - s;
}
double disp_enc = median(ts, 5);
printf("t=%-2d len=%8zu ENCODE gpu-direct %7.4f s %8.1f MB/s | dispatch %7.4f s %8.1f MB/s | equal=%d\n",
t, len, gpu_enc, (double)len / 1048576.0 / gpu_enc,
disp_enc, (double)len / 1048576.0 / disp_enc,
memcmp(enc, enc2, eclen) == 0);
for (int i = 0; i < 5; i++) {
s = now_s();
if (bch_cuda_decode(enc, eclen, len, p, dec, &corr) != 0) { printf("gpu dec fail\n"); exit(1); }
e = now_s();
ts[i] = e - s;
}
double gpu_dec = median(ts, 5);
for (int i = 0; i < 5; i++) {
s = now_s();
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0) { printf("disp dec fail\n"); exit(1); }
e = now_s();
ts[i] = e - s;
}
double disp_dec = median(ts, 5);
printf("t=%-2d len=%8zu DECODE gpu-direct %7.4f s %8.1f MB/s | dispatch %7.4f s %8.1f MB/s\n",
t, len, gpu_dec, (double)len / 1048576.0 / gpu_dec,
disp_dec, (double)len / 1048576.0 / disp_dec);
CHECK(memcmp(dec, data, len) == 0, "t=%d len=%zu bench round-trip", t, len);
free(enc);
free(enc2);
free(dec);
}
int main(int argc, char **argv)
{
printf("CUDA available: %d\n", bch_cuda_available());
if (!bch_cuda_available()) {
printf("NO CUDA DEVICE -- cannot test\n");
return 1;
}
/* correctness grid */
static const size_t sizes[] = { 1, 2, 100, 4095, 4096, 4097, 8192,
65536, 524265, 524266, 1048576 };
static const int ts_[] = { 1, 2, 4, 8, 16, 32 };
size_t maxlen = 1048576;
uint8_t *buf = malloc(maxlen);
if (!buf) return 1;
rand_bytes(buf, maxlen);
for (size_t si = 0; si < sizeof(sizes) / sizeof(sizes[0]); si++) {
for (size_t ti = 0; ti < sizeof(ts_) / sizeof(ts_[0]); ti++) {
correctness_case(buf, sizes[si], ts_[ti]);
}
}
printf("correctness: %d checks, %d failures\n", checks, fails);
if (fails) {
printf("CORRECTNESS FAILED\n");
return 1;
}
/* benchmark data */
uint8_t *big = NULL;
size_t biglen = 0;
if (argc > 1) {
FILE *f = fopen(argv[1], "rb");
if (!f) { perror("fopen"); return 1; }
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
biglen = (size_t)n;
big = malloc(biglen);
if (fread(big, 1, biglen, f) != biglen) { printf("short read\n"); return 1; }
fclose(f);
} else {
biglen = 50u << 20;
big = malloc(biglen);
rand_bytes(big, biglen);
}
printf("bench blob %zu bytes (%.1f MiB)\n", biglen,
(double)biglen / 1048576.0);
for (size_t bi = 0; bi < 3; bi++) {
size_t L = bi == 0 ? (1u << 20) : bi == 1 ? (4u << 20) : biglen;
if (L > biglen)
L = biglen;
bench_case(big, L, 8);
bench_case(big, L, 32);
}
free(buf);
free(big);
printf("checks=%d fails=%d %s\n", checks, fails,
fails ? "FAILED" : "ALL OK");
return fails ? 1 : 0;
}
-181
View File
@@ -1,181 +0,0 @@
/* chase_bench.c - CPU vs CUDA Chase-1 benchmark for deep repair.
*
* Reproduces the GPU-day baseline: Chase-1 exhaustive scan of one
* 524265-byte BCH block (m=22, t=8, -e4), 9 errors, nbits=4,194,296
* trials, ~181 s single-core (~23,200 trials/s).
*
* Usage: chase_bench --cpu | --cuda [--nerr N] [--seed S]
* --cpu : time bch_chase1_block (CPU reference)
* --cuda : time the CUDA Chase-1 scan (chase_cuda.cu)
* Prints: trials, split_pass, codewords, candidates, seconds,
* trials/s, and whether the original data is among the candidates.
* Exit 0 iff the original data is among the candidates.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#include "bch.h"
#ifdef HAVE_CUDA
#include "chase_cuda.h"
#endif
#define DFLT_D 524265
#define DFLT_T 8
#define DFLT_NERR 9
static uint64_t rng_state;
static uint64_t xr(void)
{
uint64_t x = rng_state;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
rng_state = x;
return x * 0x2545F4914F6CDD1DULL;
}
static double now_s(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
}
static void flip_bit(uint8_t *buf, size_t pos)
{
buf[pos >> 3] ^= (uint8_t)(1u << (7 - (pos & 7)));
}
/* FNV-1a hash over the candidate set, in order, for CPU/CUDA comparison. */
static uint64_t cands_hash(const uint8_t *cands, int nc, size_t D)
{
uint64_t h = 0xcbf29ce484222325ULL;
for (int i = 0; i < nc; i++) {
const uint8_t *c = cands + (size_t)i * D;
for (size_t j = 0; j < D; j++) {
h ^= c[j];
h *= 0x100000001b3ULL;
}
}
return h;
}
int main(int argc, char **argv)
{
int use_cuda = 0;
int nerr = DFLT_NERR;
uint64_t seed = 12345;
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--cuda"))
use_cuda = 1;
else if (!strcmp(argv[i], "--cpu"))
use_cuda = 0;
else if (!strcmp(argv[i], "--nerr") && i + 1 < argc)
nerr = atoi(argv[++i]);
else if (!strcmp(argv[i], "--seed") && i + 1 < argc)
seed = strtoull(argv[++i], NULL, 10);
else {
fprintf(stderr, "usage: %s [--cpu|--cuda] [--nerr N] [--seed S]\n",
argv[0]);
return 2;
}
}
size_t D = DFLT_D;
int t = DFLT_T;
const bch_poly_t *p = bch_poly_for_data(D, t);
if (!p) {
fprintf(stderr, "no poly for D=%zu t=%d\n", D, t);
return 1;
}
size_t slen = bch_block_stored_len(D, p);
size_t nbits = (size_t)8 * D + (size_t)p->r;
printf("poly: m=%d t=%d r=%d id=%04x D=%zu stored=%zu nbits=%zu\n",
p->m, p->t, p->r, p->id, D, slen, nbits);
fflush(stdout);
uint8_t *data = malloc(D), *enc = malloc(slen), *dec = malloc(D);
uint8_t *cands = malloc((size_t)BCH_CHASE_MAX_CANDS * D);
if (!data || !enc || !dec || !cands)
return 1;
rng_state = seed;
for (size_t i = 0; i < D; i++)
data[i] = (uint8_t)xr();
if (bch_encode_block(data, D, p, enc) != 0) {
fprintf(stderr, "encode failed\n");
return 1;
}
/* flip nerr distinct bit positions, deterministic */
rng_state = seed ^ 0x9e3779b97f4a7c15ULL;
size_t *errpos = malloc(sizeof(size_t) * (size_t)nerr);
for (int i = 0; i < nerr; i++) {
size_t pos;
int dup;
do {
pos = (size_t)(xr() % nbits);
dup = 0;
for (int j = 0; j < i; j++)
if (errpos[j] == pos)
dup = 1;
} while (dup);
errpos[i] = pos;
flip_bit(enc, pos);
}
printf("flipped %d bits at:", nerr);
for (int i = 0; i < nerr; i++)
printf(" %zu", errpos[i]);
printf("\n");
fflush(stdout);
/* control: standard decode must fail */
if (bch_decode_block(enc, slen, D, p, dec, NULL) == 0) {
fprintf(stderr,
"control FAILED: standard decode succeeded on %d-error word\n",
nerr);
return 1;
}
printf("control: standard decode fails as expected\n");
fflush(stdout);
size_t *susp = malloc(sizeof(size_t) * BCH_CHASE_MAX_SUSPECTS);
int ns = bch_suspect_positions(enc, slen, D, p, susp, BCH_CHASE_MAX_SUSPECTS);
printf("suspects: %d\n", ns);
fflush(stdout);
double t0 = now_s();
long trials = 0, split_pass = 0, codewords = 0;
int nc = 0;
if (!use_cuda) {
bch_chase_stats_t cs;
nc = bch_chase1_block(enc, slen, D, p, cands, BCH_CHASE_MAX_CANDS,
susp, ns, &cs, -1);
trials = cs.trials;
split_pass = cs.split_pass;
codewords = cs.codewords;
printf("cpu: nc=%d partial=%d\n", nc, cs.partial);
} else {
#ifdef HAVE_CUDA
nc = chase_cuda_scan1(enc, slen, D, p, cands, BCH_CHASE_MAX_CANDS,
susp, ns, &trials, &split_pass, &codewords);
printf("cuda: nc=%d\n", nc);
#else
fprintf(stderr, "built without CUDA support\n");
return 1;
#endif
}
double dt = now_s() - t0;
if (nc < 0) {
fprintf(stderr, "scan failed\n");
return 1;
}
printf("trials=%ld split_pass=%ld codewords=%ld candidates=%d\n",
trials, split_pass, codewords, nc);
printf("time=%.3f s rate=%.0f trials/s\n", dt, trials / dt);
printf("cands_hash=0x%016llx\n",
(unsigned long long)cands_hash(cands, nc, D));
int found = 0;
for (int i = 0; i < nc; i++)
if (memcmp(cands + (size_t)i * D, data, D) == 0)
found = 1;
printf("original among candidates: %s\n", found ? "YES" : "NO");
return found ? 0 : 1;
}
-611
View File
@@ -1,611 +0,0 @@
/* chase_cuda.cu - CUDA Chase-1 scan for deep repair (t=8, -e4).
*
* GPU mirror of bch_chase1_block (bch.c). One thread per trial
* position runs Berlekamp-Massey + the lambda-splits test. Two
* facts make the GPU version exactly equivalent to the CPU:
*
* 1. The CPU splits test is gcd(lambda, x^(2^m)-x) of degree L.
* x^(2^m)-x is squarefree, so that gcd has degree L iff lambda
* divides x^(2^m)-x iff x^(2^m) mod lambda == x. The kernel
* therefore computes h = x^(2^m) mod lambda by m repeated
* squarings and passes iff h == x, with no gcd at all.
* L <= 1 always splits, matching the CPU.
* 2. BM's L is non-decreasing, so a trial whose L exceeds t at any
* point is doomed; the kernel exits early, and never writes C
* beyond index t. That is exactly equivalent: any such write
* would only raise the degree past t, and the final L would
* still exceed t (deg(C) after an update equals the new L).
*
* After the scan, a second kernel runs the Chien search in parallel
* for the (few) positions that passed: one thread per (position,
* codeword bit) evaluates lambda at that bit by Horner. The host
* then verifies each survivor by the syndrome-zero check: the
* syndrome of the corrected word is S ^ col(trial) ^
* XOR col(root), and syndrome zero iff remainder zero (the
* syndrome's roots close under conjugation to the generator, so a
* degree-<r binary remainder with all 2t syndrome roots is 0).
*
* GF arithmetic on the device is shift-and-XOR in registers (like
* gf_mul_slow); division uses log/exp tables (only ~12 divs per
* trial, and the BM early exit usually fires before many).
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <cuda_runtime.h>
extern "C" {
#include "bch.h"
}
#include "chase_cuda.h"
/* Only t=8 (-e4) is implemented: the benchmark case. */
#define CT 8
#define CT2 (2 * CT)
#define CHASE_CUDA_MAX_PASS 1048576u /* 1M passing positions (expect ~135) */
/* ---- GF(2^m) device helpers ---- */
/* Shift-and-XOR multiply (identical to gf_mul_slow in bch.c). */
__device__ __forceinline__ uint32_t cu_gf_mul(uint32_t a, uint32_t b, uint32_t P, int m)
{
uint32_t r = 0;
while (b) {
if (b & 1)
r ^= a;
b >>= 1;
a <<= 1;
if (a & (1u << m))
a ^= P;
}
return r;
}
/* Division via log/exp tables (identical to gf_div_tab; b != 0 by
* construction - a previous discrepancy). */
__device__ __forceinline__ uint32_t cu_gf_div_tab(uint32_t a, uint32_t b,
const uint32_t *d_log,
const uint32_t *d_exp,
uint32_t N)
{
if (!a)
return 0;
int d = (int)d_log[a] - (int)d_log[b];
if (d < 0)
d += (int)N;
return d_exp[d];
}
/* Berlekamp-Massey on 2*CT syndromes. Returns L (0..CT) with
* lambda[0..L] filled, or -1 if L exceeds CT at any point (trial
* doomed: L never decreases, so the CPU would reject it too). */
__device__ int cu_bm(const uint32_t *S, const uint32_t *d_log,
const uint32_t *d_exp, uint32_t N, uint32_t P, int m,
uint32_t *lambda)
{
uint32_t C[CT + 1], B[CT + 1], Tm[CT + 1];
#pragma unroll
for (int i = 0; i <= CT; i++)
C[i] = B[i] = 0;
C[0] = B[0] = 1;
int L = 0, shift = 1;
uint32_t b = 1;
for (int n = 0; n < CT2; n++) {
uint32_t d = S[n];
#pragma unroll
for (int i = 1; i <= CT; i++)
if (i <= L && C[i] && n - i >= 0)
d ^= cu_gf_mul(C[i], S[n - i], P, m);
if (d == 0) {
shift++;
continue;
}
#pragma unroll
for (int i = 0; i <= CT; i++)
Tm[i] = C[i];
uint32_t coef = cu_gf_div_tab(d, b, d_log, d_exp, N);
int lim = CT - shift;
#pragma unroll
for (int i = 0; i <= CT; i++)
if (i <= lim && B[i])
C[i + shift] ^= cu_gf_mul(coef, B[i], P, m);
if (2 * L <= n) {
L = n + 1 - L;
if (L > CT)
return -1;
#pragma unroll
for (int i = 0; i <= CT; i++)
B[i] = Tm[i];
b = d;
shift = 1;
} else {
shift++;
}
}
#pragma unroll
for (int i = 0; i <= L; i++)
lambda[i] = C[i];
return L;
}
/* out = a^2 mod mod (mod monic of degree L, 1 <= L <= CT). */
__device__ void cu_square_mod(const uint32_t *a, int L, const uint32_t *mod,
uint32_t P, int m, uint32_t *out)
{
uint32_t prod[2 * CT + 1];
#pragma unroll
for (int i = 0; i <= 2 * CT; i++)
prod[i] = 0;
#pragma unroll
for (int i = 0; i < CT; i++)
if (i < L && a[i])
prod[2 * i] ^= cu_gf_mul(a[i], a[i], P, m);
for (int k = 2 * L - 2; k >= L; k--) {
uint32_t c = prod[k];
if (!c)
continue;
prod[k] = 0;
#pragma unroll
for (int j = 0; j < CT; j++)
if (j < L && mod[j])
prod[k - L + j] ^= cu_gf_mul(c, mod[j], P, m);
}
#pragma unroll
for (int i = 0; i <= CT; i++)
out[i] = (i < L) ? prod[i] : 0;
}
/* Splits test: h = x^(2^m) mod lambda; splits iff h == x (see the
* header comment for why this is exactly the CPU's gcd test). */
__device__ int cu_lambda_splits(const uint32_t *lambda, int L, int m, uint32_t P)
{
if (L <= 1)
return 1;
uint32_t cur[CT + 1], nxt[CT + 1];
#pragma unroll
for (int i = 0; i <= CT; i++)
cur[i] = nxt[i] = 0;
cur[1] = 1;
for (int i = 0; i < m; i++) {
cu_square_mod(cur, L, lambda, P, m, nxt);
#pragma unroll
for (int j = 0; j <= CT; j++)
cur[j] = nxt[j];
}
cur[1] ^= 1; /* h = cur - x */
#pragma unroll
for (int j = 0; j < CT; j++)
if (j < L && cur[j])
return 0;
return 1;
}
/* ---- kernel 1: BM + splits scan, one thread per trial position ---- */
__global__ void chase1_scan_kernel(const uint32_t *d_S, const uint32_t *d_exp,
const uint32_t *d_log, uint32_t N, uint32_t P,
int m, size_t nbits, uint32_t *d_pass,
uint32_t *d_pass_lambda, uint32_t *d_pass_L,
unsigned int *d_npass, unsigned long long *d_split_pass)
{
size_t pp = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
if (pp >= nbits)
return;
uint32_t K = (uint32_t)(nbits - 1 - pp);
uint32_t Sp[CT2];
#pragma unroll
for (int j = 1; j <= CT2; j++) {
uint32_t e = (uint32_t)(((uint64_t)j * K) % N);
Sp[j - 1] = d_S[j - 1] ^ d_exp[e];
}
uint32_t lambda[CT + 1];
int L = cu_bm(Sp, d_log, d_exp, N, P, m, lambda);
if (L < 0)
return;
uint32_t inv = cu_gf_div_tab(1, lambda[L], d_log, d_exp, N);
uint32_t mono[CT + 1];
#pragma unroll
for (int i = 0; i <= L; i++)
mono[i] = cu_gf_mul(lambda[i], inv, P, m);
if (!cu_lambda_splits(mono, L, m, P))
return;
atomicAdd(d_split_pass, 1ULL);
unsigned int idx = atomicAdd(d_npass, 1u);
if (idx >= CHASE_CUDA_MAX_PASS)
return;
d_pass[idx] = (uint32_t)pp;
d_pass_L[idx] = (uint32_t)L;
#pragma unroll
for (int i = 0; i <= CT; i++)
d_pass_lambda[(size_t)idx * (CT + 1) + i] = (i <= L) ? mono[i] : 0;
}
/* ---- kernel 2: parallel Chien search for the survivors ----
* One thread per (survivor, codeword bit): evaluates lambda at
* x_p = alpha^(p-(n-1)) by Horner and records p if it is a root. */
__global__ void chase1_chien_kernel(const uint32_t *d_pass_lambda,
const uint32_t *d_pass_L,
const uint32_t *d_exp, uint32_t N,
uint32_t P, int m, size_t nbits,
unsigned int npass, uint32_t *d_roots,
uint32_t *d_nroots)
{
size_t tid = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
size_t total = (size_t)npass * nbits;
if (tid >= total)
return;
unsigned int pi = (unsigned int)(tid / nbits);
size_t p = tid % nbits;
uint32_t L = d_pass_L[pi];
const uint32_t *lam = d_pass_lambda + (size_t)pi * (CT + 1);
long long off = (long long)p - (long long)(nbits - 1);
long long em = off % (long long)N;
if (em < 0)
em += (long long)N;
uint32_t x = d_exp[em];
uint32_t v = lam[L];
for (int j = (int)L - 1; j >= 0; j--)
v = cu_gf_mul(v, x, P, m) ^ lam[j];
if (v == 0) {
unsigned int idx = atomicAdd(&d_nroots[pi], 1u);
if (idx < (unsigned int)CT)
d_roots[(size_t)pi * CT + idx] = (uint32_t)p;
}
}
/* ---- host side ---- */
int chase_cuda_available(void)
{
int n = 0;
if (cudaGetDeviceCount(&n) != cudaSuccess)
return 0;
return n > 0;
}
/* GF(2^m) exp/log tables, built once per m and cached (host + device). */
typedef struct {
int m;
uint32_t N, P;
uint32_t *h_exp; /* host copy, for the syndrome-zero check */
uint32_t *d_exp, *d_log;
} cu_tables_t;
static cu_tables_t g_tab;
static uint32_t gf_mul_alpha_h(uint32_t x, uint32_t P, int m)
{
uint32_t top = (x >> (m - 1)) & 1u;
x <<= 1;
if (top)
x ^= P;
return x & ((1u << m) - 1);
}
static int cu_tables_for(int m)
{
if (g_tab.m == m && g_tab.d_exp)
return 0;
uint32_t P = bch_prim_poly[m];
uint32_t N = (1u << m) - 1;
uint32_t *exp = (uint32_t *)malloc((size_t)(N + 1) * sizeof(uint32_t));
uint32_t *log = (uint32_t *)malloc((size_t)(N + 1) * sizeof(uint32_t));
if (!exp || !log) {
free(exp);
free(log);
return -1;
}
uint32_t x = 1;
for (uint32_t i = 0; i <= N; i++) {
exp[i] = x;
log[x] = i;
x = gf_mul_alpha_h(x, P, m);
}
log[0] = 0;
uint32_t *d_exp = NULL, *d_log = NULL;
if (cudaMalloc(&d_exp, (size_t)(N + 1) * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_log, (size_t)(N + 1) * sizeof(uint32_t)) != cudaSuccess ||
cudaMemcpy(d_exp, exp, (size_t)(N + 1) * sizeof(uint32_t),
cudaMemcpyHostToDevice) != cudaSuccess ||
cudaMemcpy(d_log, log, (size_t)(N + 1) * sizeof(uint32_t),
cudaMemcpyHostToDevice) != cudaSuccess) {
cudaFree(d_exp);
cudaFree(d_log);
free(exp);
free(log);
return -1;
}
free(g_tab.h_exp);
g_tab.m = m;
g_tab.N = N;
g_tab.P = P;
g_tab.h_exp = exp;
g_tab.d_exp = d_exp;
g_tab.d_log = d_log;
free(log); /* device copy kept; host log not needed */
return 0;
}
static void flip_bit(uint8_t *buf, size_t pos)
{
buf[pos >> 3] ^= (uint8_t)(1u << (7 - (pos & 7)));
}
int chase_cuda_scan1(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint8_t *cands, int max_cands,
const size_t *suspects, int nsuspects,
long *trials_out, long *split_pass_out,
long *codewords_out)
{
if (!in || !p || !cands || max_cands <= 0 || !trials_out ||
!split_pass_out || !codewords_out)
return -1;
if (p->t != CT)
return -2; /* only t=8 implemented */
if (!chase_cuda_available())
return -2;
size_t stored = bch_block_stored_len(data_len, p);
if (in_len != stored)
return -1;
int r = p->r, m = p->m;
uint32_t N = (1u << m) - 1;
uint32_t P = bch_prim_poly[m];
size_t nbits = (size_t)8 * data_len + (size_t)r;
/* syndrome; also the clean-word early out (same as chase_setup) */
uint32_t S[CT2];
int src = bch_block_syndrome(in, in_len, data_len, p, S);
if (src < 0)
return -1;
if (src == 1) {
*trials_out = 0;
*split_pass_out = 0;
*codewords_out = 0;
return 0;
}
if (cu_tables_for(m) != 0)
return -2;
uint32_t *d_S = NULL, *d_pass = NULL, *d_pass_lambda = NULL,
*d_pass_L = NULL, *d_roots = NULL, *d_nroots = NULL;
unsigned int *d_npass = NULL;
unsigned long long *d_split_pass = NULL;
unsigned int npass = 0;
unsigned long long split_pass = 0;
int rc = -2;
long codewords = 0;
int nc = 0;
uint32_t *h_pass = NULL, *h_pass_L = NULL, *h_roots = NULL, *h_nroots = NULL;
if (cudaMalloc(&d_S, CT2 * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_pass, CHASE_CUDA_MAX_PASS * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_pass_lambda, (size_t)CHASE_CUDA_MAX_PASS * (CT + 1) * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_pass_L, CHASE_CUDA_MAX_PASS * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_npass, sizeof(unsigned int)) != cudaSuccess ||
cudaMalloc(&d_split_pass, sizeof(unsigned long long)) != cudaSuccess)
goto out;
if (cudaMemcpy(d_S, S, CT2 * sizeof(uint32_t), cudaMemcpyHostToDevice) != cudaSuccess)
goto out;
if (cudaMemset(d_npass, 0, sizeof(unsigned int)) != cudaSuccess ||
cudaMemset(d_split_pass, 0, sizeof(unsigned long long)) != cudaSuccess)
goto out;
/* kernel 1: BM + splits scan */
{
int block = 256;
size_t grid = (nbits + (size_t)block - 1) / (size_t)block;
chase1_scan_kernel<<<grid, block>>>(d_S, g_tab.d_exp, g_tab.d_log, N, P, m,
nbits, d_pass, d_pass_lambda, d_pass_L,
d_npass, d_split_pass);
if (cudaDeviceSynchronize() != cudaSuccess)
goto out;
}
if (cudaMemcpy(&npass, d_npass, sizeof(unsigned int), cudaMemcpyDeviceToHost) != cudaSuccess ||
cudaMemcpy(&split_pass, d_split_pass, sizeof(unsigned long long), cudaMemcpyDeviceToHost) != cudaSuccess)
goto out;
*split_pass_out = (long)split_pass;
*trials_out = (long)nbits;
if (npass > CHASE_CUDA_MAX_PASS)
npass = CHASE_CUDA_MAX_PASS; /* truncated; not expected (~135) */
if (npass > 0) {
h_pass = (uint32_t *)malloc((size_t)npass * sizeof(uint32_t));
h_pass_L = (uint32_t *)malloc((size_t)npass * sizeof(uint32_t));
h_roots = (uint32_t *)malloc((size_t)npass * CT * sizeof(uint32_t));
h_nroots = (uint32_t *)malloc((size_t)npass * sizeof(uint32_t));
if (!h_pass || !h_pass_L || !h_roots || !h_nroots)
goto out;
if (cudaMemcpy(h_pass, d_pass, (size_t)npass * sizeof(uint32_t),
cudaMemcpyDeviceToHost) != cudaSuccess ||
cudaMemcpy(h_pass_L, d_pass_L, (size_t)npass * sizeof(uint32_t),
cudaMemcpyDeviceToHost) != cudaSuccess)
goto out;
if (cudaMalloc(&d_roots, (size_t)npass * CT * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_nroots, (size_t)npass * sizeof(uint32_t)) != cudaSuccess)
goto out;
if (cudaMemset(d_nroots, 0, (size_t)npass * sizeof(uint32_t)) != cudaSuccess)
goto out;
/* kernel 2: parallel Chien search for the survivors */
{
int block = 256;
size_t total = (size_t)npass * nbits;
size_t grid = (total + (size_t)block - 1) / (size_t)block;
chase1_chien_kernel<<<grid, block>>>(d_pass_lambda, d_pass_L,
g_tab.d_exp, N, P, m, nbits,
npass, d_roots, d_nroots);
if (cudaDeviceSynchronize() != cudaSuccess)
goto out;
}
if (cudaMemcpy(h_roots, d_roots, (size_t)npass * CT * sizeof(uint32_t),
cudaMemcpyDeviceToHost) != cudaSuccess ||
cudaMemcpy(h_nroots, d_nroots, (size_t)npass * sizeof(uint32_t),
cudaMemcpyDeviceToHost) != cudaSuccess)
goto out;
/* sort survivors by position ascending: the kernel's
* atomic-append order is nondeterministic, but the CPU
* scans ascending, so candidate order must be sorted. */
for (unsigned int i = 0; i < npass; i++) {
for (unsigned int j = i + 1; j < npass; j++) {
if (h_pass[j] < h_pass[i]) {
uint32_t t;
t = h_pass[i]; h_pass[i] = h_pass[j]; h_pass[j] = t;
t = h_pass_L[i]; h_pass_L[i] = h_pass_L[j]; h_pass_L[j] = t;
t = h_nroots[i]; h_nroots[i] = h_nroots[j]; h_nroots[j] = t;
for (int k = 0; k < CT; k++) {
t = h_roots[(size_t)i * CT + k];
h_roots[(size_t)i * CT + k] = h_roots[(size_t)j * CT + k];
h_roots[(size_t)j * CT + k] = t;
}
}
}
}
}
/* host verification, in CPU order: suspects first in order, then
* ascending positions skipping suspects. For each survivor with
* a full root set, the corrected word's syndrome is
* S ^ col(trial) ^ XOR col(root); it is a codeword iff that is
* zero. Identical to the CPU's zero-remainder check. */
{
uint8_t *seen = (uint8_t *)malloc((size_t)max_cands * data_len);
uint32_t *syn = (uint32_t *)malloc(CT2 * sizeof(uint32_t));
if (!seen || !syn) {
free(seen);
free(syn);
goto out;
}
/* order: suspects (that passed) first, then the rest ascending */
unsigned char *is_susp = (unsigned char *)calloc(npass, 1);
if (!is_susp) {
free(seen);
free(syn);
goto out;
}
for (int s = 0; s < nsuspects && nc < max_cands; s++) {
for (unsigned int pi = 0; pi < npass; pi++) {
if (is_susp[pi] || h_pass[pi] != (uint32_t)suspects[s])
continue;
is_susp[pi] = 1;
/* verify survivor pi */
if (h_nroots[pi] != h_pass_L[pi])
break;
uint32_t K = (uint32_t)(nbits - 1 - h_pass[pi]);
for (int j = 1; j <= CT2; j++) {
uint32_t e = (uint32_t)(((uint64_t)j * K) % N);
syn[j - 1] = S[j - 1] ^ g_tab.h_exp[e];
}
for (uint32_t ri = 0; ri < h_nroots[pi]; ri++) {
uint32_t Kr = (uint32_t)(nbits - 1 - h_roots[(size_t)pi * CT + ri]);
for (int j = 1; j <= CT2; j++) {
uint32_t e = (uint32_t)(((uint64_t)j * Kr) % N);
syn[j - 1] ^= g_tab.h_exp[e];
}
}
int zero = 1;
for (int j = 0; j < CT2; j++)
if (syn[j]) {
zero = 0;
break;
}
if (!zero)
break;
codewords++;
/* build the candidate data bytes and dedup */
uint8_t *work = (uint8_t *)malloc(in_len);
if (!work) {
free(seen);
free(syn);
free(is_susp);
goto out;
}
memcpy(work, in, in_len);
flip_bit(work, h_pass[pi]);
for (uint32_t ri = 0; ri < h_nroots[pi]; ri++)
flip_bit(work, h_roots[(size_t)pi * CT + ri]);
int dup = 0;
for (int c = 0; c < nc; c++)
if (memcmp(seen + (size_t)c * data_len, work, data_len) == 0) {
dup = 1;
break;
}
if (!dup) {
memcpy(cands + (size_t)nc * data_len, work, data_len);
memcpy(seen + (size_t)nc * data_len, work, data_len);
nc++;
}
free(work);
break;
}
}
for (unsigned int pi = 0; pi < npass && nc < max_cands; pi++) {
if (is_susp[pi])
continue;
/* verify survivor pi (same as above, ascending order) */
if (h_nroots[pi] != h_pass_L[pi])
continue;
uint32_t K = (uint32_t)(nbits - 1 - h_pass[pi]);
for (int j = 1; j <= CT2; j++) {
uint32_t e = (uint32_t)(((uint64_t)j * K) % N);
syn[j - 1] = S[j - 1] ^ g_tab.h_exp[e];
}
for (uint32_t ri = 0; ri < h_nroots[pi]; ri++) {
uint32_t Kr = (uint32_t)(nbits - 1 - h_roots[(size_t)pi * CT + ri]);
for (int j = 1; j <= CT2; j++) {
uint32_t e = (uint32_t)(((uint64_t)j * Kr) % N);
syn[j - 1] ^= g_tab.h_exp[e];
}
}
int zero = 1;
for (int j = 0; j < CT2; j++)
if (syn[j]) {
zero = 0;
break;
}
if (!zero)
continue;
codewords++;
uint8_t *work = (uint8_t *)malloc(in_len);
if (!work) {
free(seen);
free(syn);
free(is_susp);
goto out;
}
memcpy(work, in, in_len);
flip_bit(work, h_pass[pi]);
for (uint32_t ri = 0; ri < h_nroots[pi]; ri++)
flip_bit(work, h_roots[(size_t)pi * CT + ri]);
int dup = 0;
for (int c = 0; c < nc; c++)
if (memcmp(seen + (size_t)c * data_len, work, data_len) == 0) {
dup = 1;
break;
}
if (!dup) {
memcpy(cands + (size_t)nc * data_len, work, data_len);
memcpy(seen + (size_t)nc * data_len, work, data_len);
nc++;
}
free(work);
}
free(seen);
free(syn);
free(is_susp);
}
*codewords_out = codewords;
rc = nc;
out:
cudaFree(d_S);
cudaFree(d_pass);
cudaFree(d_pass_lambda);
cudaFree(d_pass_L);
cudaFree(d_npass);
cudaFree(d_split_pass);
cudaFree(d_roots);
cudaFree(d_nroots);
free(h_pass);
free(h_pass_L);
free(h_roots);
free(h_nroots);
return rc;
}
-46
View File
@@ -1,46 +0,0 @@
/* chase_cuda.h - CUDA Chase-1 scan for deep repair (t=8, -e4).
*
* GPU mirror of bch_chase1_block (bch.c) for one block: one CUDA
* thread per trial position runs Berlekamp-Massey + the
* lambda-splits test; a second kernel runs the Chien search in
* parallel for the few survivors; the host verifies each by the
* syndrome-zero check (exactly equivalent to the CPU's
* zero-remainder check: syndrome zero iff remainder zero, since
* the syndrome's roots close under conjugation to the generator).
*
* Candidate order reproduces the CPU's: suspects first in order,
* then ascending positions skipping suspects. Counts (trials,
* split_pass, codewords) use the same definitions as
* bch_chase_stats_t, so results are directly comparable.
*/
#ifndef LZPLY_CHASE_CUDA_H
#define LZPLY_CHASE_CUDA_H
#include <stddef.h>
#include <stdint.h>
#include "bch.h"
#ifdef __cplusplus
extern "C" {
#endif
/* 1 if a CUDA device is present, 0 otherwise. */
int chase_cuda_available(void);
/* Chase-1 for one block on the GPU (t=8 only; returns -2 for other t
* or when CUDA is unavailable/fails). Same candidate contract as
* bch_chase1_block: returns the number of distinct candidate blocks
* in `cands` (each data_len bytes, 0..max_cands), or -1 on bad
* input. `suspects` may be NULL (with nsuspects 0). Stats are the
* same counts as bch_chase_stats_t. */
int chase_cuda_scan1(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint8_t *cands, int max_cands,
const size_t *suspects, int nsuspects,
long *trials_out, long *split_pass_out,
long *codewords_out);
#ifdef __cplusplus
}
#endif
#endif /* LZPLY_CHASE_CUDA_H */
+3 -56
View File
@@ -23,16 +23,6 @@
#include "rs.h"
#include "sha256.h"
/* CUDA Chase-1 (chase_cuda.cu), linked only when nvcc is available
* at build time; weak so a CPU-only build links and runs unchanged
* (same pattern as bch_cuda in bch.c on main). */
extern int chase_cuda_available(void) __attribute__((weak));
extern int chase_cuda_scan1(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint8_t *cands, int max_cands,
const size_t *suspects, int nsuspects,
long *trials_out, long *split_pass_out,
long *codewords_out) __attribute__((weak));
/* Decompress a blob and verify its SHA-256. Returns a malloc'd raw
* buffer (caller frees) or NULL on failure. Level 0 means stored
* uncompressed (the blob is the raw bytes). */
@@ -149,42 +139,6 @@ static void pool_free(block_pool_t *pool, size_t *pool_bytes)
pool->dlen = 0;
}
/* Chase-1 for one block: the CUDA scan when a device is present,
* the CPU scan otherwise. Same candidate contract as
* bch_chase1_block (suspects first, then ascending positions;
* candidates in scan order, so the L1 direct-try order is
* unchanged). *used_cuda is set to 1 when the GPU scan ran.
* The GPU scan has no deadline (it runs the full scan in ~0.35 s
* on a 524 KiB block); when the deadline is already past, the CPU
* scan runs instead and reports partial as usual. A -2 from the
* GPU scan (not t=8, or CUDA failed) also falls back to CPU. */
static int chase1_block(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint8_t *cands, int max_cands,
const size_t *suspects, int nsuspects,
bch_chase_stats_t *stats, double deadline,
int *used_cuda)
{
*used_cuda = 0;
if (chase_cuda_available && chase_cuda_available() &&
(deadline < 0 || bch_now() < deadline)) {
long trials = 0, split_pass = 0, codewords = 0;
int ncc = chase_cuda_scan1(in, in_len, data_len, p, cands,
max_cands, suspects, nsuspects,
&trials, &split_pass, &codewords);
if (ncc >= 0) {
stats->trials = trials;
stats->split_pass = split_pass;
stats->codewords = codewords;
stats->candidates = ncc;
stats->partial = 0;
*used_cuda = 1;
return ncc;
}
}
return bch_chase1_block(in, in_len, data_len, p, cands, max_cands,
suspects, nsuspects, stats, deadline);
}
int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
int is_bch, uint16_t poly_id, int rs_level,
const uint8_t want_sha[32], size_t blob_size,
@@ -418,8 +372,7 @@ int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
free(bc);
}
added1 = pools[bi].n; /* pool size after pass-2 */
/* Chase-1 candidates (suspects first, then scan) --
* GPU when a device is present, else CPU. */
/* Chase-1 candidates (suspects first, then scan). */
{
size_t *susp = malloc(sizeof(size_t) *
BCH_CHASE_MAX_SUSPECTS);
@@ -436,16 +389,10 @@ int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
bslen[bi], bdlen[bi],
poly, susp,
BCH_CHASE_MAX_SUSPECTS);
{
int used_cuda = 0;
ncc = chase1_block(bch_stored + s_off,
ncc = bch_chase1_block(bch_stored + s_off,
bslen[bi], bdlen[bi], poly,
cc, BCH_CHASE_MAX_CANDS,
susp, ns, &cs, deadline,
&used_cuda);
if (used_cuda)
stats->chase_cuda_used = 1;
}
susp, ns, &cs, deadline);
stats->trials[1] += cs.trials;
stats->split_pass[1] += cs.split_pass;
stats->codewords[1] += cs.codewords;
-1
View File
@@ -67,7 +67,6 @@ typedef struct {
long blocks_total; /* BCH blocks in the blob */
long blocks_failed; /* blocks failing standard decode */
int partial; /* a level stopped early on its budget */
int chase_cuda_used; /* L1 ran on the GPU (CUDA Chase-1 scan) */
char fail_stage[24]; /* "ok", "rs", "len", "crc", "sha",
"budget", "noecc", "nocand" */
} deep_stats_t;
+5 -56
View File
@@ -1,13 +1,11 @@
# Deep repair — past the BCH limit t
Deep repair recovers archive entries whose bit errors exceed
`lzply_deep_repair` recovers archive entries whose bit errors exceed
the BCH correction limit t, in escalating levels, reporting
per-level timing ("time of arrival": how long each level took and
at which level the repair landed). It is built into the main tool
(`lzply -r archive`, same levels and options as the standalone
`lzply_deep_repair` binary, which is still shipped). The CRC16
is the oracle: every beyond-t candidate is CRC-verified before
acceptance, then decompressed and SHA-256-checked.
at which level the repair landed). The CRC16 is the oracle: every
beyond-t candidate is CRC-verified before acceptance, then
decompressed and SHA-256-checked.
## The levels
@@ -39,43 +37,6 @@ acceptance, then decompressed and SHA-256-checked.
holds its true data in the pool but neither single-block
variation passes the CRC.
## The CUDA Chase-1 scan (L1 on the GPU)
On a CUDA build (nvcc present at build time -- `make` links
`chase_cuda.o` into `lzply` and `lzply_deep_repair` automatically;
without nvcc the build is CPU-only and nothing changes), the L1
Chase-1 scan runs on the GPU when a CUDA device is present. The
dispatch is automatic: there is no flag. The scan is the same
algorithm as the CPU one (one thread per trial position:
Berlekamp-Massey + the lambda-splits test, Chien search in
parallel for survivors, host syndrome-zero verification), and
produces the same candidates in the same order -- verified
bit-identical across the 5-pattern validation and a 24-pattern
sweep (10/10 CPU/CUDA hash agreements, zero mismatches).
Measured on hot_house (RTX 3080 Ti), one 524 KiB block (m=22,
t=8, -e4), 4,194,296 trials: **171.571 s CPU -> 0.335-0.379 s
CUDA (453-512x on the timed scan, ~190x end to end)**; the
extended sweep runs 453-562x. A beyond-t repair of a 524 KiB
block that took ~8 minutes at L1 now lands in under a second.
`-v` marks the L1 line `(CUDA)` when the GPU scan ran.
Fallback: the CPU scan runs whenever the GPU scan cannot -- no
CUDA device, a CPU-only build, a non-t=8 poly (the kernel is
t=8 only), a CUDA failure, or a deadline already past when the
scan would start. The symbols are referenced weakly, so a
CPU-only build links and runs unchanged.
Limits: the kernel is t=8 only; Chase-2 is not ported (L2 stays
on the CPU). The GPU scan has no deadline -- it runs the full
scan, then truncates at `BCH_CHASE_MAX_CANDS` (the CPU scan
stops early at the cap when the budget hits); the candidate set
still matches. On small blocks the ~0.115 s CUDA first-touch
cost dominates -- a 512-byte block repairs in ~0.11 s on the GPU
vs ~0.04 s on the CPU -- so the win is on large blocks.
Full write-up: https://www.lzply.com/cuda-chase-500x-deep-repair/
## Why the suspect set does not help Chase-2 (much)
With hard-decision input there is no channel reliability, so
@@ -137,16 +98,6 @@ lzply_deep_repair [-l max-level 0..3] [--time-budget seconds] [-v]
[-o outdir] [--entry name] archive
```
The same repair is built into the main tool:
```
lzply -r [--level 0..3] [--time-budget seconds] [-v]
[-o outdir] [--entry name] archive [outdir]
```
`-r` takes the same levels, budget, and output options
(`--level` in place of `-l`, which is the list mode in `lzply`).
Per-entry output:
```
@@ -217,9 +168,7 @@ wrong-but-valid candidates per trial and the CRC rejects all
`bch_test` 7,975 checks still pass). A full Chase-1 scan of a
524 KiB block (4,194,296 trials) takes **471.9 s** (measured,
probe5: RECOVERED at L1 in 471.918 s, trials 4,194,296,
split 126, codewords 126). On a CUDA build the same scan runs
on the GPU in ~0.35 s (see the CUDA section above); 471.9 s is
the CPU scan. The tool scans fully before trying
split 126, codewords 126). The tool scans fully before trying
candidates (the chase layer has no oracle), so the landing time
is the full-scan time, not the time to the lowest true error.
At the default 120 s budget a beyond-t repair of a 524 KiB
+3 -95
View File
@@ -105,9 +105,7 @@
#include <unistd.h>
#include "bch.h"
#include "deep_repair.h"
#include "lzply_lib.h"
#include "repair_cmd.h"
@@ -1573,7 +1571,7 @@ static int cmd_tree(const char *archive, const char **selectors,
static void usage(FILE *out)
{
fprintf(out,
"Usage: %s -c|-d|-l|-t|-a|-i|-tr|-r [options] <input> [output] [selectors...]\n"
"Usage: %s -c|-d|-l|-t|-a|-i|-tr [options] <input> [output] [selectors...]\n"
"\n"
" -c compress a file or directory into one .lzply archive\n"
" -a append files/dirs to an archive (creates it if\n"
@@ -1596,15 +1594,6 @@ static void usage(FILE *out)
" -tr print an archive as a tree, like the Linux\n"
" `tree` command, with a directory/file count.\n"
" Selectors filter it.\n"
" -r repair an archive: recover entries whose bit\n"
" errors exceed the BCH limit t, in escalating\n"
" levels L0-L3 (standard decode, Chase-1,\n"
" Chase-2, cross-block). Recovered files go to\n"
" [output] dir (default ./repaired). --level N\n"
" caps the level (default 3), --time-budget S\n"
" the seconds per entry (default 120). On a\n"
" CUDA build the L1 Chase-1 scan runs on the\n"
" GPU when a device is present, else CPU.\n"
" -datestart <date> only entries with mtime on or after this date\n"
" -dateend <date> only entries with mtime on or before this date\n"
" Dates are YYYY-MM-DD (whole day, inclusive) or\n"
@@ -1659,18 +1648,16 @@ static void usage(FILE *out)
" %s -i backup.lzply -datestart 2024-01-01 -dateend 2024-06-30\n"
" inspect only Jan-Jun 2024 entries\n"
" %s -tr backup.lzply photos/ -year 2025 tree of 2025 photos only\n"
" %s -r backup.lzply repair into ./repaired\n"
" %s -r -o fixed/ backup.lzply repair into fixed/\n"
"\n"
"Exit codes: 0 ok, 1 usage, 2 I/O error, 3 corrupt/unrecoverable.\n",
lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname,
lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname,
lzply_progname, lzply_progname, lzply_progname, lzply_progname,
lzply_progname, lzply_progname, lzply_progname);
lzply_progname);
}
enum { MODE_NONE, MODE_COMPRESS, MODE_DECOMPRESS, MODE_LIST, MODE_TEST,
MODE_APPEND, MODE_INSPECT, MODE_TREE, MODE_REPAIR };
MODE_APPEND, MODE_INSPECT, MODE_TREE };
/* Parse a poly=NN value: hex if it has a 0x prefix or any a-f/A-F
* letter, else decimal. Returns the poly, or NULL if it is not a
@@ -1709,11 +1696,6 @@ int main(int argc, char **argv)
int ecc_level = 4; /* default -e 4 -> BCH t=8 */
const bch_poly_t *pinned_poly = NULL;
int ow_mode = OW_ASK;
const char *repair_outdir = "./repaired";
int repair_verbose = 0;
int repair_max_level = DEEP_MAX_LEVEL;
double repair_budget = DEEP_DEFAULT_BUDGET_SEC;
const char *repair_only_entry = NULL;
date_filter_t dfilter;
const char **args = NULL; /* positional arguments after the options */
int nargs = 0;
@@ -1762,64 +1744,6 @@ int main(int argc, char **argv)
mode = MODE_INSPECT;
} else if (strcmp(a, "-tr") == 0 || strcmp(a, "--tree") == 0) {
mode = MODE_TREE;
} else if (strcmp(a, "-r") == 0 || strcmp(a, "--repair") == 0) {
mode = MODE_REPAIR;
} else if (strcmp(a, "-o") == 0 || strcmp(a, "--output") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: -o needs a directory\n",
lzply_progname);
return EXIT_USAGE;
}
repair_outdir = argv[++i];
} else if (strcmp(a, "-v") == 0 || strcmp(a, "--verbose") == 0) {
repair_verbose = 1;
} else if (strcmp(a, "--level") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: --level needs 0..3\n",
lzply_progname);
return EXIT_USAGE;
}
repair_max_level = atoi(argv[++i]);
if (repair_max_level < 0 || repair_max_level > DEEP_MAX_LEVEL) {
fprintf(stderr, "%s: --level must be 0..3\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strncmp(a, "--level=", 8) == 0) {
repair_max_level = atoi(a + 8);
if (repair_max_level < 0 || repair_max_level > DEEP_MAX_LEVEL) {
fprintf(stderr, "%s: --level must be 0..3\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strcmp(a, "--time-budget") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: --time-budget needs seconds\n",
lzply_progname);
return EXIT_USAGE;
}
repair_budget = atof(argv[++i]);
if (repair_budget <= 0) {
fprintf(stderr, "%s: --time-budget must be > 0\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strncmp(a, "--time-budget=", 14) == 0) {
repair_budget = atof(a + 14);
if (repair_budget <= 0) {
fprintf(stderr, "%s: --time-budget must be > 0\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strcmp(a, "--entry") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: --entry needs a stored path\n",
lzply_progname);
return EXIT_USAGE;
}
repair_only_entry = argv[++i];
} else if (strncmp(a, "--entry=", 8) == 0) {
repair_only_entry = a + 8;
} else if (strcmp(a, "-datestart") == 0 ||
strcmp(a, "--datestart") == 0) {
if (i + 1 >= argc) {
@@ -2007,22 +1931,6 @@ int main(int argc, char **argv)
nargs >= 2 ? nargs - 1 : 0,
&dfilter);
break;
case MODE_REPAIR:
/* archive, optional outdir. */
if (nargs < 1 || nargs > 2) {
fprintf(stderr,
"%s: -r needs an archive and an optional output directory\n",
lzply_progname);
usage(stderr);
rc = EXIT_USAGE;
break;
}
if (nargs == 2)
repair_outdir = args[1];
rc = repair_archive(lzply_progname, args[0], repair_outdir,
repair_max_level, repair_budget,
repair_only_entry, repair_verbose);
break;
default:
rc = EXIT_USAGE;
break;
+312 -6
View File
@@ -18,23 +18,27 @@
* and how many bits were corrected. -v adds the per-level trial
* counts (BM trials, splitting-filter passes, valid codewords).
*
* The archive-walking driver lives in repair_cmd.c (shared with
* the lzply -r mode); this file is only the option parsing.
*
* Exit codes: 0 all entries recovered, 1 usage, 2 I/O error,
* 3 any entry unrecoverable (matching lzply's EXIT_CORRUPT).
*/
#define _FILE_OFFSET_BITS 64
#define _DEFAULT_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "bch.h"
#include "deep_repair.h"
#include "lzply_lib.h"
#include "repair_cmd.h"
#include "lzrs_lib.h"
static const char *prog = "lzply_deep_repair";
@@ -53,6 +57,56 @@ static void usage(void)
prog, DEEP_DEFAULT_BUDGET_SEC);
}
/* mkdir -p (mode 0755 for created parents). Returns 0 on success. */
static int mkdir_p(const char *path, mode_t mode)
{
char *tmp = xstrdup(path);
size_t n = strlen(tmp);
size_t i;
if (n == 0) {
free(tmp);
return 0;
}
while (n > 1 && tmp[n - 1] == '/')
tmp[--n] = '\0';
for (i = 1; i <= n; i++) {
if (tmp[i] == '/' || tmp[i] == '\0') {
char save = tmp[i];
struct stat st;
tmp[i] = '\0';
if (stat(tmp, &st) != 0) {
if (mkdir(tmp, mode) != 0 && errno != EEXIST) {
free(tmp);
return -1;
}
} else if (!S_ISDIR(st.st_mode)) {
free(tmp);
return -1;
}
tmp[i] = save;
}
}
free(tmp);
return 0;
}
static int write_out_file(const char *path, const uint8_t *data, size_t len,
uint32_t mode)
{
FILE *f = fopen(path, "wb");
if (!f)
return -1;
if (len > 0 && fwrite(data, 1, len, f) != len) {
fclose(f);
return -1;
}
if (fclose(f) != 0)
return -1;
if (mode)
chmod(path, (mode_t)(mode & 07777));
return 0;
}
int main(int argc, char **argv)
{
int max_level = DEEP_MAX_LEVEL;
@@ -61,6 +115,9 @@ int main(int argc, char **argv)
const char *outdir = "./repaired";
const char *only_entry = NULL;
const char *archive = NULL;
int is_lzrs = 0;
FILE *f = NULL;
uint8_t magic[4];
int opt;
static struct option long_opts[] = {
{ "time-budget", required_argument, NULL, 1000 },
@@ -110,6 +167,255 @@ int main(int argc, char **argv)
}
archive = argv[optind];
return repair_archive(prog, archive, outdir, max_level, budget,
only_entry, verbose);
f = fopen(archive, "rb");
if (!f) {
fprintf(stderr, "%s: cannot open %s: %s\n", prog, archive,
strerror(errno));
return EXIT_IO;
}
if (fread(magic, 1, 4, f) != 4) {
fprintf(stderr, "%s: %s is too short to be an archive\n",
prog, archive);
fclose(f);
return EXIT_CORRUPT;
}
if (memcmp(magic, "LZRS", 4) == 0)
is_lzrs = 1;
else if (memcmp(magic, "LZPL", 4) != 0) {
fprintf(stderr, "%s: %s is not an LZPL or LZRS archive\n",
prog, archive);
fclose(f);
return EXIT_CORRUPT;
}
/* Validate the archive up front (version, headers, end marker),
* so a structurally broken archive fails before any repair is
* attempted. The scan also gives the clear v4 message for old
* LZPL archives. */
{
int version = 0;
uint32_t count = 0;
off_t size = 0, end_off = 0;
scan_list_t entries;
int s;
rewind(f);
if (is_lzrs)
s = lzrs_scan_archive(archive, &version, &count, &size,
&entries, &end_off);
else
s = scan_archive(archive, &version, &count, &size,
&entries, &end_off);
if (s != 0) {
fclose(f);
return EXIT_CORRUPT;
}
scan_list_free(&entries);
rewind(f);
}
if (mkdir_p(outdir, 0755) != 0) {
fprintf(stderr, "%s: cannot create output directory %s: %s\n",
prog, outdir, strerror(errno));
fclose(f);
return EXIT_IO;
}
/* Skip the 16-byte global header; then walk the entries. */
if (fseeko(f, 16, SEEK_SET) != 0) {
fprintf(stderr, "%s: cannot seek in %s\n", prog, archive);
fclose(f);
return EXIT_IO;
}
{
int worst = 0;
long n_ok = 0, n_fail = 0, n_dir = 0;
long landed[4] = { 0, 0, 0, 0 };
double t_start = bch_now();
for (;;) {
char *path = NULL;
int level = 0, is_bch = 0, rs_level = 0, is_dir = 0;
uint16_t poly_id = 0, want_crc16 = 0;
uint64_t stored_size = 0, blob_size = 0, orig_size = 0;
uint32_t mode = 0;
uint8_t sha[32];
uint8_t *stored = NULL;
int r;
if (is_lzrs) {
lzrs_ehdr_t h;
r = lzrs_read_entry_header(f, &h);
if (r == 1)
break;
if (r < 0) {
fprintf(stderr, "%s: truncated or corrupt entry header\n",
prog);
worst = EXIT_CORRUPT;
break;
}
path = h.path;
level = h.level;
is_bch = (h.flags & FLAG_BCH) != 0;
rs_level = h.rs_level;
is_dir = (h.flags & FLAG_ISDIR) != 0;
poly_id = h.bch_poly_id;
want_crc16 = h.crc16;
stored_size = h.stored_size;
blob_size = h.blob_size;
orig_size = h.orig_size;
mode = h.mode;
memcpy(sha, h.sha, 32);
} else {
ehdr_t h;
r = read_entry_header(f, &h);
if (r == 1)
break;
if (r < 0) {
fprintf(stderr, "%s: truncated or corrupt entry header\n",
prog);
worst = EXIT_CORRUPT;
break;
}
path = h.path;
level = h.level;
is_bch = (h.flags & FLAG_BCH) != 0;
rs_level = 0;
is_dir = (h.flags & FLAG_ISDIR) != 0;
poly_id = (uint16_t)(h.rs_level |
((uint16_t)h.reserved << 8));
want_crc16 = h.crc16;
stored_size = h.stored_size;
blob_size = h.blob_size;
orig_size = h.orig_size;
mode = h.mode;
memcpy(sha, h.sha, 32);
}
stored = xmalloc(stored_size ? (size_t)stored_size : 1);
if (stored_size > 0 &&
fread(stored, 1, (size_t)stored_size, f) !=
(size_t)stored_size) {
fprintf(stderr, "%s: truncated data for %s\n", prog, path);
free(stored);
free(path);
worst = EXIT_CORRUPT;
break;
}
if (only_entry && strcmp(path, only_entry) != 0) {
free(stored);
free(path);
continue;
}
if (is_dir) {
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
sprintf(dp, "%s/%s", outdir, path);
if (mkdir_p(dp, mode ? (mode_t)(mode & 07777) : 0755) != 0)
fprintf(stderr, "%s: cannot create directory %s: %s\n",
prog, dp, strerror(errno));
free(dp);
free(stored);
free(path);
n_dir++;
continue;
}
{
uint8_t *raw = NULL;
size_t raw_len = 0;
deep_stats_t st;
int drc = deep_repair_entry(stored, (size_t)stored_size,
level, is_bch, poly_id,
rs_level, sha,
(size_t)blob_size, want_crc16,
max_level, budget,
&raw, &raw_len, &st);
free(stored);
if (drc != 0) {
printf("%s: FAILED (stage %s) after %.3fs, "
"cands %ld crc-rejects %ld sha-rejects %ld\n",
path, st.fail_stage, st.t_total,
st.cands_tried, st.crc_rejects, st.sha_rejects);
if (verbose) {
int lv;
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
printf(" L%d: %.3fs trials %ld split %ld "
"codewords %ld\n", lv, st.t_level[lv],
st.trials[lv], st.split_pass[lv],
st.codewords[lv]);
printf(" blocks %ld/%ld failed%s\n",
st.blocks_failed, st.blocks_total,
st.partial ? " (partial: budget hit)" : "");
}
n_fail++;
if (EXIT_CORRUPT > worst)
worst = EXIT_CORRUPT;
free(path);
continue;
}
if (raw_len != orig_size) {
fprintf(stderr, "%s: %s: size mismatch after repair "
"(got %zu, expected %llu)\n", prog, path,
raw_len, (unsigned long long)orig_size);
free(raw);
free(path);
n_fail++;
if (EXIT_CORRUPT > worst)
worst = EXIT_CORRUPT;
continue;
}
{
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
char *pd;
sprintf(dp, "%s/%s", outdir, path);
pd = parent_dir(dp);
if (mkdir_p(pd, 0755) != 0)
fprintf(stderr, "%s: cannot create %s: %s\n",
prog, pd, strerror(errno));
free(pd);
if (write_out_file(dp, raw, raw_len, mode) != 0) {
fprintf(stderr, "%s: cannot write %s: %s\n",
prog, dp, strerror(errno));
if (EXIT_IO > worst)
worst = EXIT_IO;
free(dp);
free(raw);
free(path);
continue;
}
free(dp);
}
{
char rssuf[48];
rssuf[0] = '\0';
if (st.rs_corrected > 0)
snprintf(rssuf, sizeof rssuf,
" (RS corrected %d symbols)",
st.rs_corrected);
printf("%s: RECOVERED at L%d in %.3fs "
"(L0 %.3fs, L1 %.3fs, L2 %.3fs, L3 %.3fs) "
"cands %ld crc-rejects %ld sha-rejects %ld "
"bch-corrected %d%s\n",
path, st.level_landed, st.t_total,
st.t_level[0], st.t_level[1], st.t_level[2],
st.t_level[3], st.cands_tried, st.crc_rejects,
st.sha_rejects, st.bch_corrected, rssuf);
}
if (verbose) {
int lv;
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
printf(" L%d: %.3fs trials %ld split %ld "
"codewords %ld\n", lv, st.t_level[lv],
st.trials[lv], st.split_pass[lv],
st.codewords[lv]);
printf(" blocks %ld/%ld failed%s\n",
st.blocks_failed, st.blocks_total,
st.partial ? " (partial: budget hit)" : "");
}
landed[st.level_landed]++;
n_ok++;
free(raw);
free(path);
}
}
printf("deep repair: %ld recovered (L0 %ld, L1 %ld, L2 %ld, "
"L3 %ld), %ld failed, %ld directories, %.3fs total\n",
n_ok, landed[0], landed[1], landed[2], landed[3],
n_fail, n_dir, bch_now() - t_start);
fclose(f);
return worst;
}
}
-354
View File
@@ -1,354 +0,0 @@
/* repair_cmd.c - shared archive repair driver for `lzply -r` and
* `lzply_deep_repair`.
*
* repair_archive() validates an LZPL v5 or LZRS v1 archive, then
* attempts the escalating deep-repair ladder (L0 standard decode
* to t, L1 Chase-1 flips, L2 Chase-2 flips, L3 cross-block list
* decoding) per entry, writing recovered files under outdir with
* their stored paths preserved. Nothing is ever written unless it
* passes both oracles (CRC16, then decompress + SHA-256).
*
* Per entry it reports the level the repair landed at and the
* per-level timing -- the "time of arrival": how long each level
* took, how many candidates were tried, how many the CRC rejected,
* and how many bits were corrected. -v adds the per-level trial
* counts (BM trials, splitting-filter passes, valid codewords);
* the L1 line carries a (CUDA) marker when the Chase-1 scan ran
* on the GPU.
*
* Returns the worst exit code: 0 all entries recovered, 2 I/O
* error, 3 any entry unrecoverable (matching lzply's EXIT_*).
*/
#define _FILE_OFFSET_BITS 64
#define _DEFAULT_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "bch.h"
#include "deep_repair.h"
#include "lzply_lib.h"
#include "lzrs_lib.h"
#include "repair_cmd.h"
/* mkdir -p (mode 0755 for created parents). Returns 0 on success. */
static int mkdir_p(const char *path, mode_t mode)
{
char *tmp = xstrdup(path);
size_t n = strlen(tmp);
size_t i;
if (n == 0) {
free(tmp);
return 0;
}
while (n > 1 && tmp[n - 1] == '/')
tmp[--n] = '\0';
for (i = 1; i <= n; i++) {
if (tmp[i] == '/' || tmp[i] == '\0') {
char save = tmp[i];
struct stat st;
tmp[i] = '\0';
if (stat(tmp, &st) != 0) {
if (mkdir(tmp, mode) != 0 && errno != EEXIST) {
free(tmp);
return -1;
}
} else if (!S_ISDIR(st.st_mode)) {
free(tmp);
return -1;
}
tmp[i] = save;
}
}
free(tmp);
return 0;
}
static int write_out_file(const char *path, const uint8_t *data, size_t len,
uint32_t mode)
{
FILE *f = fopen(path, "wb");
if (!f)
return -1;
if (len > 0 && fwrite(data, 1, len, f) != len) {
fclose(f);
return -1;
}
if (fclose(f) != 0)
return -1;
if (mode)
chmod(path, (mode_t)(mode & 07777));
return 0;
}
int repair_archive(const char *prog, const char *archive,
const char *outdir, int max_level, double budget,
const char *only_entry, int verbose)
{
int is_lzrs = 0;
FILE *f = NULL;
uint8_t magic[4];
lzply_set_progname(prog);
f = fopen(archive, "rb");
if (!f) {
fprintf(stderr, "%s: cannot open %s: %s\n", prog, archive,
strerror(errno));
return EXIT_IO;
}
if (fread(magic, 1, 4, f) != 4) {
fprintf(stderr, "%s: %s is too short to be an archive\n", prog, archive);
fclose(f);
return EXIT_CORRUPT;
}
if (memcmp(magic, "LZRS", 4) == 0)
is_lzrs = 1;
else if (memcmp(magic, "LZPL", 4) != 0) {
fprintf(stderr, "%s: %s is not an LZPL or LZRS archive\n", prog, archive);
fclose(f);
return EXIT_CORRUPT;
}
/* Validate the archive up front (version, headers, end marker),
* so a structurally broken archive fails before any repair is
* attempted. The scan also gives the clear v4 message for old
* LZPL archives. */
{
int version = 0;
uint32_t count = 0;
off_t size = 0, end_off = 0;
scan_list_t entries;
int s;
rewind(f);
if (is_lzrs)
s = lzrs_scan_archive(archive, &version, &count, &size,
&entries, &end_off);
else
s = scan_archive(archive, &version, &count, &size,
&entries, &end_off);
if (s != 0) {
fclose(f);
return EXIT_CORRUPT;
}
scan_list_free(&entries);
rewind(f);
}
if (mkdir_p(outdir, 0755) != 0) {
fprintf(stderr, "%s: cannot create output directory %s: %s\n",
prog, outdir, strerror(errno));
fclose(f);
return EXIT_IO;
}
/* Skip the 16-byte global header; then walk the entries. */
if (fseeko(f, 16, SEEK_SET) != 0) {
fprintf(stderr, "%s: cannot seek in %s: %s\n", prog, archive,
strerror(errno));
fclose(f);
return EXIT_IO;
}
{
int worst = 0;
long n_ok = 0, n_fail = 0, n_dir = 0;
long landed[4] = { 0, 0, 0, 0 };
double t_start = bch_now();
for (;;) {
char *path = NULL;
int level = 0, is_bch = 0, rs_level = 0, is_dir = 0;
uint16_t poly_id = 0, want_crc16 = 0;
uint64_t stored_size = 0, blob_size = 0, orig_size = 0;
uint32_t mode = 0;
uint8_t sha[32];
uint8_t *stored = NULL;
int r;
if (is_lzrs) {
lzrs_ehdr_t h;
r = lzrs_read_entry_header(f, &h);
if (r == 1)
break;
if (r < 0) {
fprintf(stderr, "%s: truncated or corrupt entry header\n",
prog);
worst = EXIT_CORRUPT;
break;
}
path = h.path;
level = h.level;
is_bch = (h.flags & FLAG_BCH) != 0;
rs_level = h.rs_level;
is_dir = (h.flags & FLAG_ISDIR) != 0;
poly_id = h.bch_poly_id;
want_crc16 = h.crc16;
stored_size = h.stored_size;
blob_size = h.blob_size;
orig_size = h.orig_size;
mode = h.mode;
memcpy(sha, h.sha, 32);
} else {
ehdr_t h;
r = read_entry_header(f, &h);
if (r == 1)
break;
if (r < 0) {
fprintf(stderr, "%s: truncated or corrupt entry header\n",
prog);
worst = EXIT_CORRUPT;
break;
}
path = h.path;
level = h.level;
is_bch = (h.flags & FLAG_BCH) != 0;
rs_level = 0;
is_dir = (h.flags & FLAG_ISDIR) != 0;
poly_id = (uint16_t)(h.rs_level |
((uint16_t)h.reserved << 8));
want_crc16 = h.crc16;
stored_size = h.stored_size;
blob_size = h.blob_size;
orig_size = h.orig_size;
mode = h.mode;
memcpy(sha, h.sha, 32);
}
stored = xmalloc(stored_size ? (size_t)stored_size : 1);
if (stored_size > 0 &&
fread(stored, 1, (size_t)stored_size, f) !=
(size_t)stored_size) {
fprintf(stderr, "%s: truncated data for %s\n", prog, path);
free(stored);
free(path);
worst = EXIT_CORRUPT;
break;
}
if (only_entry && strcmp(path, only_entry) != 0) {
free(stored);
free(path);
continue;
}
if (is_dir) {
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
sprintf(dp, "%s/%s", outdir, path);
if (mkdir_p(dp, mode ? (mode_t)(mode & 07777) : 0755) != 0)
fprintf(stderr, "%s: cannot create directory %s: %s\n",
prog, dp, strerror(errno));
free(dp);
free(stored);
free(path);
n_dir++;
continue;
}
{
uint8_t *raw = NULL;
size_t raw_len = 0;
deep_stats_t st;
int drc = deep_repair_entry(stored, (size_t)stored_size,
level, is_bch, poly_id,
rs_level, sha,
(size_t)blob_size, want_crc16,
max_level, budget,
&raw, &raw_len, &st);
free(stored);
if (drc != 0) {
printf("%s: FAILED (stage %s) after %.3fs, "
"cands %ld crc-rejects %ld sha-rejects %ld\n",
path, st.fail_stage, st.t_total,
st.cands_tried, st.crc_rejects, st.sha_rejects);
if (verbose) {
int lv;
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
printf(" L%d: %.3fs trials %ld split %ld "
"codewords %ld%s\n", lv, st.t_level[lv],
st.trials[lv], st.split_pass[lv],
st.codewords[lv],
(lv == 1 && st.chase_cuda_used) ?
" (CUDA)" : "");
printf(" blocks %ld/%ld failed%s\n",
st.blocks_failed, st.blocks_total,
st.partial ? " (partial: budget hit)" : "");
}
n_fail++;
if (EXIT_CORRUPT > worst)
worst = EXIT_CORRUPT;
free(path);
continue;
}
if (raw_len != orig_size) {
fprintf(stderr, "%s: %s: size mismatch after repair "
"(got %zu, expected %llu)\n", prog, path,
raw_len, (unsigned long long)orig_size);
free(raw);
free(path);
n_fail++;
if (EXIT_CORRUPT > worst)
worst = EXIT_CORRUPT;
continue;
}
{
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
char *pd;
sprintf(dp, "%s/%s", outdir, path);
pd = parent_dir(dp);
if (mkdir_p(pd, 0755) != 0)
fprintf(stderr, "%s: cannot create %s: %s\n",
prog, pd, strerror(errno));
free(pd);
if (write_out_file(dp, raw, raw_len, mode) != 0) {
fprintf(stderr, "%s: cannot write %s: %s\n",
prog, dp, strerror(errno));
if (EXIT_IO > worst)
worst = EXIT_IO;
free(dp);
free(raw);
free(path);
continue;
}
free(dp);
}
{
char rssuf[48];
rssuf[0] = '\0';
if (st.rs_corrected > 0)
snprintf(rssuf, sizeof rssuf,
" (RS corrected %d symbols)",
st.rs_corrected);
printf("%s: RECOVERED at L%d in %.3fs "
"(L0 %.3fs, L1 %.3fs, L2 %.3fs, L3 %.3fs) "
"cands %ld crc-rejects %ld sha-rejects %ld "
"bch-corrected %d%s\n",
path, st.level_landed, st.t_total,
st.t_level[0], st.t_level[1], st.t_level[2],
st.t_level[3], st.cands_tried, st.crc_rejects,
st.sha_rejects, st.bch_corrected, rssuf);
}
if (verbose) {
int lv;
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
printf(" L%d: %.3fs trials %ld split %ld "
"codewords %ld%s\n", lv, st.t_level[lv],
st.trials[lv], st.split_pass[lv],
st.codewords[lv],
(lv == 1 && st.chase_cuda_used) ?
" (CUDA)" : "");
printf(" blocks %ld/%ld failed%s\n",
st.blocks_failed, st.blocks_total,
st.partial ? " (partial: budget hit)" : "");
}
landed[st.level_landed]++;
n_ok++;
free(raw);
free(path);
}
}
printf("deep repair: %ld recovered (L0 %ld, L1 %ld, L2 %ld, "
"L3 %ld), %ld failed, %ld directories, %.3fs total\n",
n_ok, landed[0], landed[1], landed[2], landed[3],
n_fail, n_dir, bch_now() - t_start);
fclose(f);
return worst;
}
}
-17
View File
@@ -1,17 +0,0 @@
/* repair_cmd.h - shared archive repair driver.
*
* repair_archive() is the archive-walking repair loop used by both
* the lzply -r mode and the lzply_deep_repair binary: it validates
* the archive, then attempts the escalating deep-repair ladder
* (L0-L3) per entry, writing recovered files under outdir.
* Returns the worst exit code: 0 all entries recovered, 2 I/O
* error, 3 any entry unrecoverable (matching lzply's EXIT_*).
*/
#ifndef LZPLY_REPAIR_CMD_H
#define LZPLY_REPAIR_CMD_H
int repair_archive(const char *prog, const char *archive,
const char *outdir, int max_level, double budget,
const char *only_entry, int verbose);
#endif /* LZPLY_REPAIR_CMD_H */
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 9 bits at: 3498895 1877890 867125 251131 3784195 2342946 1354710 492520 135908
control: standard decode fails as expected
suspects: 6
cpu: nc=13 partial=0
trials=4194296 split_pass=117 codewords=117 candidates=13
time=166.680 s rate=25164 trials/s
cands_hash=0x5c7f589a39df28b8
original among candidates: YES
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 11 bits at: 7480 711379 3153510 1270250 3083353 1772972 938922 807275 94692 1349411 2303948
control: standard decode fails as expected
suspects: 0
cpu: nc=7 partial=0
trials=4194296 split_pass=63 codewords=63 candidates=7
time=159.671 s rate=26268 trials/s
cands_hash=0x64657c5daf8fe7bd
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 10 bits at: 1752901 3737741 3059447 2051162 317292 620740 979055 1373300 3126232 2196530
control: standard decode fails as expected
suspects: 12
cpu: nc=11 partial=0
trials=4194296 split_pass=99 codewords=99 candidates=11
time=164.670 s rate=25471 trials/s
cands_hash=0x56c63d470502aee8
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 9 bits at: 2917275 1921054 4031549 1001171 2122060 1902685 3634746 522053 2462819
control: standard decode fails as expected
suspects: 0
cpu: nc=13 partial=0
trials=4194296 split_pass=117 codewords=117 candidates=13
time=168.330 s rate=24917 trials/s
cands_hash=0x67fdae628952aa68
original among candidates: YES
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 12 bits at: 890570 2616517 4117318 731678 2468035 436493 204399 1066127 205524 3172107 3730223 2267138
control: standard decode fails as expected
suspects: 6
cpu: nc=13 partial=0
trials=4194296 split_pass=117 codewords=117 candidates=13
time=166.697 s rate=25161 trials/s
cands_hash=0x7e36640193d2f371
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 10 bits at: 2573515 3309936 1817927 223125 3836982 2344499 4025415 1674867 2505759 2533574
control: standard decode fails as expected
suspects: 3
cuda: nc=10
trials=4194296 split_pass=90 codewords=90 candidates=10
time=0.305 s rate=13738008 trials/s
cands_hash=0xf0ac78a5c0db6077
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 12 bits at: 3172352 1071835 3926998 3247870 3251552 3325465 155676 3753442 1626860 3680006 2968890 315944
control: standard decode fails as expected
suspects: 6
cuda: nc=13
trials=4194296 split_pass=117 codewords=117 candidates=13
time=0.316 s rate=13258809 trials/s
cands_hash=0xff1b6acdbcda946e
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 9 bits at: 1139622 1583101 138872 3986032 4059758 2290546 1200718 4107582 2213207
control: standard decode fails as expected
suspects: 6
cuda: nc=9
trials=4194296 split_pass=81 codewords=81 candidates=9
time=0.292 s rate=14373237 trials/s
cands_hash=0xc3dc7b7528027f2c
original among candidates: YES
-3
View File
@@ -1,3 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 7 bits at: 3498895 1877890 867125 251131 3784195 2342946 1354710
control FAILED: standard decode succeeded on 7-error word
-3
View File
@@ -1,3 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 8 bits at: 3498895 1877890 867125 251131 3784195 2342946 1354710 492520
control FAILED: standard decode succeeded on 8-error word
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 9 bits at: 3498895 1877890 867125 251131 3784195 2342946 1354710 492520 135908
control: standard decode fails as expected
suspects: 6
cuda: nc=13
trials=4194296 split_pass=117 codewords=117 candidates=13
time=0.362 s rate=11601794 trials/s
cands_hash=0x5c7f589a39df28b8
original among candidates: YES
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 11 bits at: 3933902 465327 3816380 801717 1488751 2770697 1474470 2075870 803263 2125553 3564454
control: standard decode fails as expected
suspects: 0
cuda: nc=10
trials=4194296 split_pass=90 codewords=90 candidates=10
time=0.309 s rate=13562801 trials/s
cands_hash=0x0828e3f1a1de3768
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 10 bits at: 1826361 717892 152487 785237 531434 2695038 3847765 1073156 1449180 1378323
control: standard decode fails as expected
suspects: 0
cuda: nc=14
trials=4194296 split_pass=126 codewords=126 candidates=14
time=0.332 s rate=12630048 trials/s
cands_hash=0x2478043cdde3ae3e
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 10 bits at: 2607436 1927552 988006 2269250 396460 3929804 123706 24069 746876 2808087
control: standard decode fails as expected
suspects: 3
cuda: nc=12
trials=4194296 split_pass=108 codewords=108 candidates=12
time=0.322 s rate=13016562 trials/s
cands_hash=0x06acc3a69443d342
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 11 bits at: 392468 3185225 2667856 3078904 524650 2513743 2343604 3018313 3280212 3273574 3523990
control: standard decode fails as expected
suspects: 0
cuda: nc=11
trials=4194296 split_pass=99 codewords=99 candidates=11
time=0.315 s rate=13299619 trials/s
cands_hash=0xd0e203ae5074c351
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 12 bits at: 38571 3843158 2832380 2172314 3143789 732683 2822399 477706 1732523 3284823 1535823 1770581
control: standard decode fails as expected
suspects: 0
cuda: nc=9
trials=4194296 split_pass=81 codewords=81 candidates=9
time=0.285 s rate=14727206 trials/s
cands_hash=0xa817ea75c23a4634
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 11 bits at: 7480 711379 3153510 1270250 3083353 1772972 938922 807275 94692 1349411 2303948
control: standard decode fails as expected
suspects: 0
cuda: nc=7
trials=4194296 split_pass=63 codewords=63 candidates=7
time=0.284 s rate=14768929 trials/s
cands_hash=0x64657c5daf8fe7bd
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 9 bits at: 3186922 2673650 95755 3163968 1448843 1728624 3938100 3106615 3246295
control: standard decode fails as expected
suspects: 3
cuda: nc=18
trials=4194296 split_pass=162 codewords=162 candidates=18
time=0.352 s rate=11929751 trials/s
cands_hash=0x9fbf8f81ead3e086
original among candidates: YES
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 10 bits at: 1752901 3737741 3059447 2051162 317292 620740 979055 1373300 3126232 2196530
control: standard decode fails as expected
suspects: 12
cuda: nc=11
trials=4194296 split_pass=99 codewords=99 candidates=11
time=0.311 s rate=13481690 trials/s
cands_hash=0x56c63d470502aee8
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 11 bits at: 2942199 3813690 55970 3322604 1721331 1106782 2795398 3273601 2978575 590496 1883743
control: standard decode fails as expected
suspects: 3
cuda: nc=16
trials=4194296 split_pass=144 codewords=144 candidates=16
time=0.334 s rate=12569297 trials/s
cands_hash=0xab869c50c89764d7
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 11 bits at: 4193586 3139026 1537929 3333519 4177005 3421389 1477710 2478458 3490487 446536 2834840
control: standard decode fails as expected
suspects: 0
cuda: nc=12
trials=4194296 split_pass=108 codewords=108 candidates=12
time=0.318 s rate=13172288 trials/s
cands_hash=0xc2ce80d884c0de3a
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 9 bits at: 2917275 1921054 4031549 1001171 2122060 1902685 3634746 522053 2462819
control: standard decode fails as expected
suspects: 0
cuda: nc=13
trials=4194296 split_pass=117 codewords=117 candidates=13
time=0.321 s rate=13079187 trials/s
cands_hash=0x67fdae628952aa68
original among candidates: YES
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 12 bits at: 890570 2616517 4117318 731678 2468035 436493 204399 1066127 205524 3172107 3730223 2267138
control: standard decode fails as expected
suspects: 6
cuda: nc=13
trials=4194296 split_pass=117 codewords=117 candidates=13
time=0.315 s rate=13309357 trials/s
cands_hash=0x7e36640193d2f371
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 10 bits at: 1565866 3522582 366564 1232519 2738835 229635 1819150 3469645 3127283 2389929
control: standard decode fails as expected
suspects: 3
cuda: nc=13
trials=4194296 split_pass=117 codewords=117 candidates=13
time=0.326 s rate=12848095 trials/s
cands_hash=0x69622442a318139d
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 12 bits at: 829773 1707577 251473 1166989 1877618 570817 1417188 517337 600769 4129883 74702 301529
control: standard decode fails as expected
suspects: 3
cuda: nc=15
trials=4194296 split_pass=135 codewords=135 candidates=15
time=0.332 s rate=12614960 trials/s
cands_hash=0xf6dc42abffaa291f
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 10 bits at: 1126595 647008 1758360 1802814 1984026 2375369 1613697 336812 4049402 191539
control: standard decode fails as expected
suspects: 3
cuda: nc=8
trials=4194296 split_pass=72 codewords=72 candidates=8
time=0.290 s rate=14475440 trials/s
cands_hash=0x41d95f8afa6ba1ce
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 9 bits at: 3397325 2439328 2357346 3286739 3189071 982899 1409094 3266818 3890431
control: standard decode fails as expected
suspects: 3
cuda: nc=11
trials=4194296 split_pass=99 codewords=99 candidates=11
time=0.303 s rate=13840509 trials/s
cands_hash=0x3f83e1d877fff106
original among candidates: YES
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 12 bits at: 1213157 78591 1181322 103384 1872122 2087522 3012246 3571933 208726 2725019 1244306 726765
control: standard decode fails as expected
suspects: 0
cuda: nc=13
trials=4194296 split_pass=117 codewords=117 candidates=13
time=0.321 s rate=13085423 trials/s
cands_hash=0xaa142dccd701c52f
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 9 bits at: 3522960 2484215 2732983 881566 254204 1579905 254093 3743235 1848401
control: standard decode fails as expected
suspects: 0
cuda: nc=17
trials=4194296 split_pass=153 codewords=153 candidates=17
time=0.340 s rate=12347934 trials/s
cands_hash=0xdca91931a24c5d24
original among candidates: YES
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 11 bits at: 3292058 983773 450541 316762 2999583 1512213 3313778 3882320 2021991 1212694 1933913
control: standard decode fails as expected
suspects: 0
cuda: nc=12
trials=4194296 split_pass=108 codewords=108 candidates=12
time=0.317 s rate=13216590 trials/s
cands_hash=0x42fd41c1b975b1f5
original among candidates: NO
-9
View File
@@ -1,9 +0,0 @@
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
flipped 12 bits at: 2923071 2946792 2830609 3426044 2307790 3343130 3761171 3197071 889853 557680 1404485 682587
control: standard decode fails as expected
suspects: 9
cuda: nc=12
trials=4194296 split_pass=108 codewords=108 candidates=12
time=0.312 s rate=13429427 trials/s
cands_hash=0x1aff72716b878008
original among candidates: NO
-64
View File
@@ -1,64 +0,0 @@
control probe nerr=7 rc=1 : control FAILED: standard decode succeeded on 7-error word
control probe nerr=8 rc=1 : control FAILED: standard decode succeeded on 8-error word
=== cuda seed=11 nerr=9 2026-12-04T01:22:42Z ===
done cuda seed=11 nerr=9 susp=6 cands=13 time=0.362s hash=0x5c7f589a39df28b8 orig=YES
=== cuda seed=21 nerr=9 2026-12-04T01:22:43Z ===
done cuda seed=21 nerr=9 susp=3 cands=18 time=0.352s hash=0x9fbf8f81ead3e086 orig=YES
=== cuda seed=101 nerr=9 2026-12-04T01:22:44Z ===
done cuda seed=101 nerr=9 susp=6 cands=9 time=0.292s hash=0xc3dc7b7528027f2c orig=YES
=== cuda seed=777 nerr=9 2026-12-04T01:22:45Z ===
done cuda seed=777 nerr=9 susp=3 cands=11 time=0.303s hash=0x3f83e1d877fff106 orig=YES
=== cuda seed=31337 nerr=9 2026-12-04T01:22:46Z ===
done cuda seed=31337 nerr=9 susp=0 cands=13 time=0.321s hash=0x67fdae628952aa68 orig=YES
=== cuda seed=8675309 nerr=9 2026-12-04T01:22:47Z ===
done cuda seed=8675309 nerr=9 susp=0 cands=17 time=0.340s hash=0xdca91931a24c5d24 orig=YES
=== cuda seed=12 nerr=10 2026-12-04T01:22:48Z ===
FAILED rc=1 seed=12 nerr=10 impl=cuda (see sweep2/cuda-seed12-nerr10.log)
=== cuda seed=22 nerr=10 2026-12-04T01:22:48Z ===
FAILED rc=1 seed=22 nerr=10 impl=cuda (see sweep2/cuda-seed22-nerr10.log)
=== cuda seed=100 nerr=10 2026-12-04T01:22:49Z ===
FAILED rc=1 seed=100 nerr=10 impl=cuda (see sweep2/cuda-seed100-nerr10.log)
=== cuda seed=1234 nerr=10 2026-12-04T01:22:50Z ===
FAILED rc=1 seed=1234 nerr=10 impl=cuda (see sweep2/cuda-seed1234-nerr10.log)
=== cuda seed=55555 nerr=10 2026-12-04T01:22:51Z ===
FAILED rc=1 seed=55555 nerr=10 impl=cuda (see sweep2/cuda-seed55555-nerr10.log)
=== cuda seed=424242 nerr=10 2026-12-04T01:22:53Z ===
FAILED rc=1 seed=424242 nerr=10 impl=cuda (see sweep2/cuda-seed424242-nerr10.log)
=== cuda seed=13 nerr=11 2026-12-04T01:22:54Z ===
FAILED rc=1 seed=13 nerr=11 impl=cuda (see sweep2/cuda-seed13-nerr11.log)
=== cuda seed=31 nerr=11 2026-12-04T01:22:54Z ===
FAILED rc=1 seed=31 nerr=11 impl=cuda (see sweep2/cuda-seed31-nerr11.log)
=== cuda seed=2024 nerr=11 2026-12-04T01:22:55Z ===
FAILED rc=1 seed=2024 nerr=11 impl=cuda (see sweep2/cuda-seed2024-nerr11.log)
=== cuda seed=11111 nerr=11 2026-12-04T01:22:56Z ===
FAILED rc=1 seed=11111 nerr=11 impl=cuda (see sweep2/cuda-seed11111-nerr11.log)
=== cuda seed=98765 nerr=11 2026-12-04T01:22:57Z ===
FAILED rc=1 seed=98765 nerr=11 impl=cuda (see sweep2/cuda-seed98765-nerr11.log)
=== cuda seed=22222 nerr=11 2026-12-04T01:22:58Z ===
FAILED rc=1 seed=22222 nerr=11 impl=cuda (see sweep2/cuda-seed22222-nerr11.log)
=== cuda seed=14 nerr=12 2026-12-04T01:22:59Z ===
FAILED rc=1 seed=14 nerr=12 impl=cuda (see sweep2/cuda-seed14-nerr12.log)
=== cuda seed=42 nerr=12 2026-12-04T01:23:00Z ===
FAILED rc=1 seed=42 nerr=12 impl=cuda (see sweep2/cuda-seed42-nerr12.log)
=== cuda seed=1000 nerr=12 2026-12-04T01:23:01Z ===
FAILED rc=1 seed=1000 nerr=12 impl=cuda (see sweep2/cuda-seed1000-nerr12.log)
=== cuda seed=54321 nerr=12 2026-12-04T01:23:02Z ===
FAILED rc=1 seed=54321 nerr=12 impl=cuda (see sweep2/cuda-seed54321-nerr12.log)
=== cuda seed=77777 nerr=12 2026-12-04T01:23:03Z ===
FAILED rc=1 seed=77777 nerr=12 impl=cuda (see sweep2/cuda-seed77777-nerr12.log)
=== cuda seed=999999 nerr=12 2026-12-04T01:23:04Z ===
FAILED rc=1 seed=999999 nerr=12 impl=cuda (see sweep2/cuda-seed999999-nerr12.log)
=== cpu seed=11 nerr=9 2026-12-04T01:23:05Z ===
done cpu seed=11 nerr=9 susp=6 cands=13 time=166.680s hash=0x5c7f589a39df28b8 orig=YES
=== cpu seed=22 nerr=10 2026-12-04T01:25:52Z ===
FAILED rc=1 seed=22 nerr=10 impl=cpu (see sweep2/cpu-seed22-nerr10.log)
=== cpu seed=2024 nerr=11 2026-12-04T01:28:37Z ===
FAILED rc=1 seed=2024 nerr=11 impl=cpu (see sweep2/cpu-seed2024-nerr11.log)
=== cpu seed=42 nerr=12 2026-12-04T01:31:17Z ===
FAILED rc=1 seed=42 nerr=12 impl=cpu (see sweep2/cpu-seed42-nerr12.log)
=== cpu seed=31337 nerr=9 2026-12-04T01:34:04Z ===
done cpu seed=31337 nerr=9 susp=0 cands=13 time=168.330s hash=0x67fdae628952aa68 orig=YES
match column filled
SWEEP DONE 2026-12-04T01:36:53Z
.330s hash=0x67fdae628952aa68 orig=YES
SWEEP DONE 2026-12-04T01:36:53Z
-46
View File
@@ -1,46 +0,0 @@
import glob, os, re, csv
rows = []
for path in sorted(glob.glob("sweep2/*-seed*-nerr*.log")):
m = re.match(r"sweep2/(cpu|cuda)-seed(\d+)-nerr(\d+)\.log", path)
if not m: continue
impl, seed, nerr = m.group(1), int(m.group(2)), int(m.group(3))
txt = open(path).read()
def g(pat):
mm = re.search(pat, txt, re.M)
return mm.group(1) if mm else ""
ctrl_fail = "control FAILED" in txt
rows.append(dict(seed=seed, nerr=nerr, impl=impl,
suspects=g(r"^suspects: (\d+)") or ("CTRL-FAIL" if ctrl_fail else ""),
trials=g(r"^trials=(\d+)"),
split_pass=g(r"split_pass=(\d+)"),
codewords=g(r"codewords=(\d+)"),
candidates=g(r"candidates=(\d+)"),
time_s=g(r"^time=([0-9.]+)"), rate=g(r"rate=(\d+)"),
hash=g(r"^cands_hash=(0x[0-9a-f]+)"),
original=g(r"^original among candidates: ([A-Z]+)"),
partial=g(r"partial=(\d+)"),
note="control-fail: std decode succeeds (nerr<=t)" if ctrl_fail else ""))
cuda = {(r["seed"], r["nerr"]): r["hash"] for r in rows if r["impl"]=="cuda" and r["hash"]}
for r in rows:
if r["impl"]=="cpu" and r["hash"]:
k=(r["seed"], r["nerr"])
r["match"] = "Y" if k in cuda and cuda[k]==r["hash"] else ("N" if k in cuda else "?")
else:
r["match"] = ""
rows.sort(key=lambda r:(r["nerr"], r["seed"], r["impl"]))
with open("sweep2/summary.csv","w",newline="") as f:
w=csv.DictWriter(f, fieldnames=["seed","nerr","impl","suspects","trials","split_pass","codewords","candidates","time_s","rate_trials_s","hash","original","partial","match","note"])
w.writeheader()
for r in rows:
w.writerow({"seed":r["seed"],"nerr":r["nerr"],"impl":r["impl"],"suspects":r["suspects"],"trials":r["trials"],"split_pass":r["split_pass"],"codewords":r["codewords"],"candidates":r["candidates"],"time_s":r["time_s"],"rate_trials_s":r["rate"],"hash":r["hash"],"original":r["original"],"partial":r["partial"],"match":r["match"],"note":r["note"]})
print("rows:", len(rows))
# speedup stats for cpu-verified pairs
pairs=[]
for r in rows:
if r["impl"]=="cpu" and r["hash"]:
c=[x for x in rows if x["impl"]=="cuda" and x["seed"]==r["seed"] and x["nerr"]==r["nerr"]]
if c: pairs.append((r["seed"],r["nerr"],float(r["time_s"]),float(c[0]["time_s"])))
for s,n,ct,gt in pairs:
print(f"seed {s} nerr {n}: cpu {ct:.3f}s / cuda {gt:.3f}s = {ct/gt:.1f}x")
print("max_cands hits (partial=1 or candidates>=64):", [ (r["seed"],r["nerr"],r["impl"],r["candidates"],r["partial"]) for r in rows if r["partial"]=="1" or (r["candidates"].isdigit() and int(r["candidates"])>=64) ])
print("mismatches:", [ (r["seed"],r["nerr"]) for r in rows if r["match"]=="N" ])
-78
View File
@@ -1,78 +0,0 @@
#!/bin/bash
# Chase-1 extended benchmark sweep #2 — hot_house (parrot), RTX 3080 Ti
# Branch experiments/cuda-chase @ 368644a. Read-only benchmarking; no commits/pushes.
# CUDA on all patterns; CPU on 5 spread across nerr values.
# NOTE: nerr 7/8 cannot run the Chase scan: t=8 standard decode corrects
# them, so the harness control check fails by design. Valid nerr: 9-12.
set -u
cd /root/cuda-chase/lzply || exit 1
mkdir -p sweep2
SUM=sweep2/summary.csv
echo "seed,nerr,impl,suspects,trials,split_pass,codewords,candidates,time_s,rate_trials_s,hash,original,match" > "$SUM"
run_one() { # $1=impl(cpu|cuda) $2=seed $3=nerr
local impl="$1" seed="$2" nerr="$3"
local bin="./chase_bench_cpu" flag="--cpu"
[ "$impl" = "cuda" ] && { bin="./chase_bench_cuda"; flag="--cuda"; }
local log="sweep2/${impl}-seed${seed}-nerr${nerr}.log"
echo "=== $impl seed=$seed nerr=$nerr $(date -u +%FT%TZ) ===" | tee -a sweep2/driver.log
"$bin" $flag --seed "$seed" --nerr "$nerr" > "$log" 2>&1
local rc=$?
if [ $rc -ne 0 ]; then
echo "FAILED rc=$rc seed=$seed nerr=$nerr impl=$impl (see $log)" | tee -a sweep2/driver.log
echo "$seed,$nerr,$impl,,,,,,,,,,rc=$rc" >> "$SUM"
return 1
fi
local susp trials sp cw nc t rate hash orig
susp=$(grep -oP '^suspects: \K[0-9]+' "$log" || echo "?")
trials=$(grep -oP '^trials=\K[0-9]+' "$log" || echo "?")
sp=$(grep -oP 'split_pass=\K[0-9]+' "$log" || echo "?")
cw=$(grep -oP 'codewords=\K[0-9]+' "$log" || echo "?")
nc=$(grep -oP 'candidates=\K[0-9]+' "$log" || echo "?")
t=$(grep -oP '^time=\K[0-9.]+' "$log" || echo "?")
rate=$(grep -oP 'rate=\K[0-9]+' "$log" || echo "?")
hash=$(grep -oP '^cands_hash=\K0x[0-9a-f]+' "$log" || echo "?")
orig=$(grep -oP '^original among candidates: \K[A-Z]+' "$log" || echo "?")
echo "$seed,$nerr,$impl,$susp,$trials,$sp,$cw,$nc,$t,$rate,$hash,$orig," >> "$SUM"
echo "done $impl seed=$seed nerr=$nerr susp=$susp cands=$nc time=${t}s hash=$hash orig=$orig" | tee -a sweep2/driver.log
return 0
}
# Control probes: nerr 7/8 expected to fail (standard decode succeeds)
for n in 7 8; do
./chase_bench_cuda --cuda --seed 11 --nerr "$n" > "sweep2/cuda-seed11-nerr${n}.log" 2>&1
echo "control probe nerr=$n rc=$? : $(tail -1 sweep2/cuda-seed11-nerr${n}.log)" | tee -a sweep2/driver.log
done
# CUDA sweep: 24 new patterns, 6 seeds x nerr 9/10/11/12
for n in 9 10 11 12; do
case $n in
9) seeds="11 21 101 777 31337 8675309" ;;
10) seeds="12 22 100 1234 55555 424242" ;;
11) seeds="13 31 2024 11111 98765 22222" ;;
12) seeds="14 42 1000 54321 77777 999999" ;;
esac
for s in $seeds; do run_one cuda "$s" "$n"; done
done
# CPU verification on 5 patterns spread across nerr/suspects (~170 s each)
for spec in "11 9" "22 10" "2024 11" "42 12" "31337 9"; do
set -- $spec; run_one cpu "$1" "$2"
done
# Hash-match check: append match=Y/N to CPU rows by comparing with CUDA rows
python3 - <<'PYEOF'
import csv
rows = list(csv.DictReader(open('sweep2/summary.csv')))
cuda = {(r['seed'], r['nerr']): r['hash'] for r in rows if r['impl'] == 'cuda' and r['hash']}
for r in rows:
if r['impl'] == 'cpu' and r['hash']:
k = (r['seed'], r['nerr'])
r['match'] = 'Y' if k in cuda and cuda[k] == r['hash'] else ('N' if k in cuda else '?')
with open('sweep2/summary.csv', 'w', newline='') as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
w.writeheader(); w.writerows(rows)
print("match column filled")
PYEOF
echo "SWEEP DONE $(date -u +%FT%TZ)" | tee -a sweep2/driver.log
-32
View File
@@ -1,32 +0,0 @@
seed,nerr,impl,suspects,trials,split_pass,codewords,candidates,time_s,rate_trials_s,hash,original,partial,match,note
11,7,cuda,CTRL-FAIL,,,,,,,,,,,control-fail: std decode succeeds (nerr<=t)
11,8,cuda,CTRL-FAIL,,,,,,,,,,,control-fail: std decode succeeds (nerr<=t)
11,9,cpu,6,4194296,117,117,13,166.680,25164,0x5c7f589a39df28b8,YES,0,Y,
11,9,cuda,6,4194296,117,117,13,0.362,11601794,0x5c7f589a39df28b8,YES,,,
21,9,cuda,3,4194296,162,162,18,0.352,11929751,0x9fbf8f81ead3e086,YES,,,
101,9,cuda,6,4194296,81,81,9,0.292,14373237,0xc3dc7b7528027f2c,YES,,,
777,9,cuda,3,4194296,99,99,11,0.303,13840509,0x3f83e1d877fff106,YES,,,
31337,9,cpu,0,4194296,117,117,13,168.330,24917,0x67fdae628952aa68,YES,0,Y,
31337,9,cuda,0,4194296,117,117,13,0.321,13079187,0x67fdae628952aa68,YES,,,
8675309,9,cuda,0,4194296,153,153,17,0.340,12347934,0xdca91931a24c5d24,YES,,,
12,10,cuda,0,4194296,126,126,14,0.332,12630048,0x2478043cdde3ae3e,NO,,,
22,10,cpu,12,4194296,99,99,11,164.670,25471,0x56c63d470502aee8,NO,0,Y,
22,10,cuda,12,4194296,99,99,11,0.311,13481690,0x56c63d470502aee8,NO,,,
100,10,cuda,3,4194296,90,90,10,0.305,13738008,0xf0ac78a5c0db6077,NO,,,
1234,10,cuda,3,4194296,108,108,12,0.322,13016562,0x06acc3a69443d342,NO,,,
55555,10,cuda,3,4194296,72,72,8,0.290,14475440,0x41d95f8afa6ba1ce,NO,,,
424242,10,cuda,3,4194296,117,117,13,0.326,12848095,0x69622442a318139d,NO,,,
13,11,cuda,0,4194296,99,99,11,0.315,13299619,0xd0e203ae5074c351,NO,,,
31,11,cuda,0,4194296,108,108,12,0.318,13172288,0xc2ce80d884c0de3a,NO,,,
2024,11,cpu,0,4194296,63,63,7,159.671,26268,0x64657c5daf8fe7bd,NO,0,Y,
2024,11,cuda,0,4194296,63,63,7,0.284,14768929,0x64657c5daf8fe7bd,NO,,,
11111,11,cuda,0,4194296,90,90,10,0.309,13562801,0x0828e3f1a1de3768,NO,,,
22222,11,cuda,3,4194296,144,144,16,0.334,12569297,0xab869c50c89764d7,NO,,,
98765,11,cuda,0,4194296,108,108,12,0.317,13216590,0x42fd41c1b975b1f5,NO,,,
14,12,cuda,0,4194296,81,81,9,0.285,14727206,0xa817ea75c23a4634,NO,,,
42,12,cpu,6,4194296,117,117,13,166.697,25161,0x7e36640193d2f371,NO,0,Y,
42,12,cuda,6,4194296,117,117,13,0.315,13309357,0x7e36640193d2f371,NO,,,
1000,12,cuda,6,4194296,117,117,13,0.316,13258809,0xff1b6acdbcda946e,NO,,,
54321,12,cuda,3,4194296,135,135,15,0.332,12614960,0xf6dc42abffaa291f,NO,,,
77777,12,cuda,0,4194296,117,117,13,0.321,13085423,0xaa142dccd701c52f,NO,,,
999999,12,cuda,9,4194296,108,108,12,0.312,13429427,0x1aff72716b878008,NO,,,
1 seed nerr impl suspects trials split_pass codewords candidates time_s rate_trials_s hash original partial match note
2 11 7 cuda CTRL-FAIL control-fail: std decode succeeds (nerr<=t)
3 11 8 cuda CTRL-FAIL control-fail: std decode succeeds (nerr<=t)
4 11 9 cpu 6 4194296 117 117 13 166.680 25164 0x5c7f589a39df28b8 YES 0 Y
5 11 9 cuda 6 4194296 117 117 13 0.362 11601794 0x5c7f589a39df28b8 YES
6 21 9 cuda 3 4194296 162 162 18 0.352 11929751 0x9fbf8f81ead3e086 YES
7 101 9 cuda 6 4194296 81 81 9 0.292 14373237 0xc3dc7b7528027f2c YES
8 777 9 cuda 3 4194296 99 99 11 0.303 13840509 0x3f83e1d877fff106 YES
9 31337 9 cpu 0 4194296 117 117 13 168.330 24917 0x67fdae628952aa68 YES 0 Y
10 31337 9 cuda 0 4194296 117 117 13 0.321 13079187 0x67fdae628952aa68 YES
11 8675309 9 cuda 0 4194296 153 153 17 0.340 12347934 0xdca91931a24c5d24 YES
12 12 10 cuda 0 4194296 126 126 14 0.332 12630048 0x2478043cdde3ae3e NO
13 22 10 cpu 12 4194296 99 99 11 164.670 25471 0x56c63d470502aee8 NO 0 Y
14 22 10 cuda 12 4194296 99 99 11 0.311 13481690 0x56c63d470502aee8 NO
15 100 10 cuda 3 4194296 90 90 10 0.305 13738008 0xf0ac78a5c0db6077 NO
16 1234 10 cuda 3 4194296 108 108 12 0.322 13016562 0x06acc3a69443d342 NO
17 55555 10 cuda 3 4194296 72 72 8 0.290 14475440 0x41d95f8afa6ba1ce NO
18 424242 10 cuda 3 4194296 117 117 13 0.326 12848095 0x69622442a318139d NO
19 13 11 cuda 0 4194296 99 99 11 0.315 13299619 0xd0e203ae5074c351 NO
20 31 11 cuda 0 4194296 108 108 12 0.318 13172288 0xc2ce80d884c0de3a NO
21 2024 11 cpu 0 4194296 63 63 7 159.671 26268 0x64657c5daf8fe7bd NO 0 Y
22 2024 11 cuda 0 4194296 63 63 7 0.284 14768929 0x64657c5daf8fe7bd NO
23 11111 11 cuda 0 4194296 90 90 10 0.309 13562801 0x0828e3f1a1de3768 NO
24 22222 11 cuda 3 4194296 144 144 16 0.334 12569297 0xab869c50c89764d7 NO
25 98765 11 cuda 0 4194296 108 108 12 0.317 13216590 0x42fd41c1b975b1f5 NO
26 14 12 cuda 0 4194296 81 81 9 0.285 14727206 0xa817ea75c23a4634 NO
27 42 12 cpu 6 4194296 117 117 13 166.697 25161 0x7e36640193d2f371 NO 0 Y
28 42 12 cuda 6 4194296 117 117 13 0.315 13309357 0x7e36640193d2f371 NO
29 1000 12 cuda 6 4194296 117 117 13 0.316 13258809 0xff1b6acdbcda946e NO
30 54321 12 cuda 3 4194296 135 135 15 0.332 12614960 0xf6dc42abffaa291f NO
31 77777 12 cuda 0 4194296 117 117 13 0.321 13085423 0xaa142dccd701c52f NO
32 999999 12 cuda 9 4194296 108 108 12 0.312 13429427 0x1aff72716b878008 NO
-13
View File
@@ -186,19 +186,6 @@ sys.exit(1 if fails else 0)
PYEOF
if [ $? -ne 0 ]; then FAIL=$((FAIL+1)); echo "FAIL: old-format rejection section (see above)"; else PASS=$((PASS+1)); echo "PASS: old-format rejection section"; fi
# --- 2b. lzply -r smoke test (repair built into the main CLI) -----------
"$LZPLY" -c -e 4 "$WORK/r512.bin" "$WORK/r-smoke.lzpl" >/dev/null
SMOKESZ=$(stat -c %s "$WORK/r-smoke.lzpl")
cp "$WORK/r-smoke.lzpl" "$WORK/r-smoke-corr.lzpl"
"$CORRUPT_BITS" "$WORK/r-smoke-corr.lzpl" 4242 9 104 $((SMOKESZ - 2)) >/dev/null
rm -rf "$WORK/r-smoke-out"
if "$LZPLY" -r -o "$WORK/r-smoke-out" "$WORK/r-smoke-corr.lzpl" >/dev/null 2>&1 \
&& cmp -s "$WORK/r512.bin" "$WORK/r-smoke-out/r512.bin"; then
ok "lzply -r repairs 9-bit corruption (L1)"
else
bad "lzply -r repairs 9-bit corruption (L1)"
fi
# --- 3. Corruption matrix -------------------------------------------------
# repair_trial ARCHIVE ORIG DATA_OFF BLOB_END SEED NERR MODE BUDGET TRIALNO
# MODE: scatter | burst1 | burst2 | conc1 (9 in block 1) | conc2 (9+9)