RAID 0 EATS YOUR DATA?! I Built a Striped Volume That Rebuilds 3 Dead Stripes — 8 Bit-Planes, P/Q/R Parity + BCH, Reads at 35 MiB/s!

lzply_hyper: a striped volume that splits every file bit-plane across 8 data stripes and rebuilds 1, 2 or 3 dead stripes from independent P/Q/R parity plus BCH. 56/56 tests, real 100 MiB demos, full source.

RAID 0 EATS YOUR DATA?! I Built a Striped Volume That Rebuilds 3 Dead Stripes — 8 Bit-Planes, P/Q/R Parity + BCH, Reads at 35 MiB/s!
lzply_hyper hero: a file split into 8 glowing bit-plane stripes with three parity stripes P, Q, R rebuilding a cracked stripe

RAID 0 is fast and RAID 0 eats your data. That is the deal it has always offered: stripe for speed, and when one disk dies, the volume dies with it. lzply_hyper refuses the deal. It stripes a file across 8 data stripes for read speed — one bit per stripe, a bit-plane split — and then bolts on three independent parity stripes (P, Q, R) plus BCH, so losing one, two, or three stripes is a repair job, not a funeral. Write speed is not a design goal and nobody pretends otherwise. Read speed is. A 100 MiB file reads back at ~35 MiB/s with full verification, and a 3-stripe loss reads back byte-identical. It is built, compiled, and tested on a real server — 56 out of 56 hyper tests passing, plus a 7,406-check BCH harness and the 147-test lzply archive suite it shares a codec with.

This is the full write-up: the bit-plane layout, the P/Q/R parity scheme and why BCH alone cannot rebuild a stripe, the config and the six commands, the index and the one failure mode it cannot hide, the measured read speed and the two BCH speedups that bought it, the 1/2/3-stripe loss demos on a real 100 MiB file, the test results, the bugs I found while building it, and the complete source code.

WHAT IT IS IN ONE PICTURE

WRITE: file -> 8 bit-plane stripes + parityfile bytesbit j -> stripe j→8x8 transposeSWAR, involution→8 data stripesceil(len/8) each+P + Q + R + BCHper-file recordREAD: stripes -> file (exact reverse, verified)surviving stripesdead ones rebuilt→8x8 transposesame function→BCH check/correctsyndrome, then fix→verify SHA-256byte-identical or errorDEAD STRIPE: rebuild from parity (P, Q, R as needed)solve k×k GF(256) system, per byte position1 parity → 1 loss · 2 parities → 2 losses · 3 parities → 3 losses

The order matters and it is not arbitrary. The parity protects the stripes, the BCH protects the reassembled file, and the SHA-256 at the end is the final judge: if anything survived both layers wrong, the file is rejected, never silently returned damaged.

THE BIT-PLANE LAYOUT: ONE BIT PER STRIPE

A file is split byte by byte, bit by bit. Byte i splits into its 8 bits; bit j goes to stripe j. Stripe j holds one bit of every byte, packed. Each data stripe is ceil(file_len / 8) bytes, and the 8 stripes together hold exactly the file — no more, no less. No compression anywhere: an incompressible file costs the same as a compressible one.

file bytes:  b0 b1 b2 b3 b4 b5 b6 b7 b8 ...
stripe 0:    bit0(b0) bit0(b1) ... bit0(b7) | bit0(b8) ...
stripe 1:    bit1(b0) bit1(b1) ... bit1(b7) | bit1(b8) ...
...
stripe 7:    bit7(b0) bit7(b1) ... bit7(b7) | bit7(b8) ...

Reassembly uses an 8x8 bit-matrix transpose (SWAR — three shift/mask/xor stages on a uint64), not per-bit extraction. The transpose is an involution, so the same function splits on write and merges on read. And the on-disk layout is checked against hand-computed values, because a roundtrip alone cannot validate a transpose (an involution roundtrips correctly even if it is the wrong involution — the layout test is what catches it):

bytes 01 02 04 08 10 20 40 80  -> stripes are themselves
bytes FF 00 00 00 00 00 00 00  -> every stripe byte is 01
bytes 80 40 20 10 08 04 02 01  -> stripes are themselves
bytes 00..0F, second group    -> AA CC F0 FF 00 00 00 00

Why 8 stripes and not 5, or 16? Because a byte has 8 bits. The bit-plane split is the most even split there is: every stripe is exactly the same size (up to the last partial group), every byte of the file touches every stripe equally, and losing any one stripe loses exactly one bit of every byte — which is precisely what an XOR parity stripe can rebuild. A 5-stripe split would have to cut bytes unevenly and the parity math would be messier for no benefit.

WHY BCH ALONE CANNOT REBUILD A STRIPE (THE FORK, RESOLVED)

The original sketch was BCH parity over the file, stored on the parity stripe. That recovers bit rot only. It cannot rebuild a dead stripe, and the numbers say so plainly. Poly 0044 (m=20, t=8) holds 131,051 data bytes per block with 160 parity bits (20 bytes) of erasure capacity — while one dead stripe of 8 loses 131,051 / 8 = 16,381 bytes per block, ~800x over capacity. BCH alone is the wrong tool for stripe loss. Stripe loss needs parity computed across the stripes, which is a different scheme from the BCH poly in the config.

So each file's parity record stores two things: stripe-loss parity (P/Q/R) and BCH parity over the file. The BCH layer corrects bit rot in the reassembled file — including a bit error that propagated through a stripe rebuild, since that lands as a single-bit error in the reassembled file. Cost is tiny: a 1 MiB file with poly 0044 is 8 BCH blocks x 20 bytes = 160 bytes total; a 100 MiB file is 16,020 bytes.

THE PARITY LAYERS: P, Q, R — INDEPENDENT, NOT MIRRORS

Three independent parity stripes, not mirrors of each other. (An early draft proposed mirrored copies as the default; that was superseded — mirrors protect against losing the parity file itself, but they add zero tolerance for a second dead data stripe, and the user approved the 2- and 3-stripe loss options instead.)

RowDefinitionRecovers
PXOR across the 8 data stripesany 1 lost stripe
QGF(256) weighted sum, sum g^j * s_ja 2nd lost stripe (RAID-6 style)
RGF(256) weighted sum, sum g^(2j) * s_ja 3rd lost stripe

Here g = 2 is the field generator and the field is GF(256) with primitive polynomial 0x11d. The number of parity stripes in the config sets the tolerance: 1 parity → 1 loss, 2 parities → 2 losses, 3 parities → 3 losses. Recovery solves the small (k×k, k ≤ 3) coefficient system over GF(256) by Gauss-Jordan inversion, per byte position. It uses whichever parity rows survive — Q alone rebuilds 1 lost stripe if P is dead. A 4th lost stripe is beyond tolerance: read and -rebuild fail clearly and never return wrong data.

Each file gets one parity record per parity stripe. The record header (96 bytes) holds the name, original length, poly id and t, the stripe offset and length, the parity and BCH lengths, and a SHA-256 of the original file. After the header come the parity bytes (stripe_len bytes) and the BCH parity bytes. The record is appended to each parity stripe when the file is written; the stripes are written first, then the records, so a crash leaves orphaned stripe data, never a dangling record.

parity record (per parity stripe, per file):
  header (96 bytes):
    magic "HYPR", version u8 (1), parity_idx u8 (0=P, 1=Q, 2=R),
    flags u16, name_len u16 @8, poly_id u16 @10, t u8 @12, npar u8 @13,
    orig_len u64 @16, stripe_off u64 @24, stripe_len u64 @32,
    parity_len u64 @40 (= stripe_len), bch_len u64 @48,
    sha256[32] @56, header_crc32 u32 @88, reserved @92
  name[name_len]
  parity[parity_len]
  bch[bch_len]

The BCH parity is the same on every parity stripe (it is a function of the file, not of the parity row). The poly is taken from the first parity line; all parity lines must agree on poly + error level or the config is rejected. SHA-256 over the original file is the final guard: a BCH miscorrection (a damage pattern beyond t landing on a different valid codeword) is caught by the hash and reported as corruption, never as silent damage.

CONFIG

stripe:<label>:<file>:<rw|ro>:<size>
parity:<label>:<file>:<rw|ro>:<poly>:<error_level>
  • stripe lines: exactly 8 (the bit-plane layout fixes the count; any other number is an error).
  • parity lines: 1–3 (more than 3 is an error for v1).
  • rw = read-write, ro = read-only (never written; usable for reads and recovery). A write requires every stripe and parity to be rw.
  • size = capacity with K/M/G suffixes (10G). A write that would exceed a stripe's remaining capacity fails instead of silently wrapping. -init checks that the filesystem actually has room for the configured sizes.
  • poly is a hex id, as in the polynomial tables: 0044 is m=20, t=8; 003a is m=18, t=32. It is authoritative; error_level must agree with it (bch_t_for_level: 1→1, 2→2, 3→4, 4→8, 5→16, 6→32, 7→32) or the config is rejected. The parser reads the poly as hex — 0044 is 0x0044, m=20, not decimal 44 (which would be m=16). That distinction is a real bug I fixed; see the bugs section.
  • A stripe or parity file can live anywhere — the config is just paths. Labels must be unique across all entries.
stripe:s0:/mnt/disk0/s0.hyper:rw:1G
stripe:s1:/mnt/disk1/s1.hyper:rw:1G
stripe:s2:/mnt/disk2/s2.hyper:rw:1G
stripe:s3:/mnt/disk3/s3.hyper:rw:1G
stripe:s4:/mnt/disk4/s4.hyper:rw:1G
stripe:s5:/mnt/disk5/s5.hyper:rw:1G
stripe:s6:/mnt/disk6/s6.hyper:rw:1G
stripe:s7:/mnt/disk7/s7.hyper:rw:1G
parity:p0:/mnt/disk8/p0.hyper:rw:0044:4
parity:p1:/mnt/disk9/p1.hyper:rw:0044:4
parity:p2:/mnt/diska/p2.hyper:rw:0044:4

COMMANDS

lzply_hyper -c config.txt <command> [args]
  • -init [--force] — validate the config; check each parent directory exists and is writable (if rw) and that the filesystem has room for the configured stripe sizes; create the empty stripe and parity files. Refuses to overwrite existing files without --force. An ro file must already exist (it is verified, never created).
  • write <file> [name] — stripe a file into the volume. The name defaults to the file's basename. Refuses to overwrite an existing name (no overwrite in v1). Requires all stripes and parities rw, all stripe files present and the same size, and enough remaining capacity.
  • read <name> <out> — read a file back out. Rebuilds a dead stripe via parity if needed, corrects bit rot via BCH, verifies SHA-256. Reports rebuilds and corrections.
  • list — list the files in the volume (scans the parity-stripe index; uses the parity stripe with the most records).
  • check <name> — verify a file (stripe parity + BCH + SHA-256), no output file.
  • -rebuild — rebuild lost/corrupt stripes. Detects missing or wrong-size data stripes and parity stripes; reconstructs the data stripes from the surviving stripes + parity (P/Q/R as needed for 1/2/3 losses); reconstructs a missing parity stripe from the data stripes. Rebuilt data goes to temp files and is renamed into place only on success, so a failed rebuild leaves the damaged files untouched. Reports what was rebuilt and what could not be rebuilt. Fails clearly, never silently returns wrong data.

THE INDEX, AND THE ONE FAILURE MODE IT CANNOT HIDE

The index lives in the parity stripes: each file's record is appended to every parity stripe, so list (and read, check, -rebuild) scan the parity stripe with the most records. A truncated parity stripe yields a short index; a crashed write may leave one parity stripe one record ahead, and that record's stripe data is already on disk, so the longest index is the right one.

If every parity stripe is dead but the data stripes are intact, the files are still readable in principle — just unverifiable and unrecoverable, because there is no record of their names, lengths, or hashes. That failure mode is worth knowing, not hiding: keep at least one parity stripe alive, and it does not matter which one.

-rebuild only detects missing or wrong-size stripes. Bit rot inside a stripe file (right size, wrong bytes) is corrected on read by BCH, but -rebuild does not rewrite a stripe file for bit rot alone — it rebuilds a stripe from parity only when the stripe is missing or the wrong size, and then only from parity, never from the stripe's own possibly-corrupt old bytes.

READ SPEED — MEASURED, AND THE TWO SPEEDUPS THAT BOUGHT IT

Measured on the server (Debian 12, 4 vCPU, 3.8 GiB RAM), reading a 100 MiB random file, poly 0044 (m=20, t=8), 3 parity stripes:

OperationThroughput
raw cat of the 8 stripe files (I/O floor)2,424 MiB/s
SHA-256 alone (sha256sum, 100 MiB)178 MiB/s
BCH syndrome alone (clean, 100 MiB)50.8 MiB/s
lzply_hyper read (100 MiB, 3 runs)35.2 / 34.0 / 35.4 MiB/s
lzply_hyper check (100 MiB, 3 runs, no output)37.2 / 33.4 / 37.1 MiB/s

The BCH syndrome is the bottleneck, and profiling proved it: I/O does 2,424 MiB/s, SHA-256 does 178 MiB/s, but the syndrome is a serial LFSR remainder, O(n·r/8), and it cannot be vectorised — each byte depends on the previous remainder, so -O3 -march=native buys nothing (measured: 50.6 vs 50.4 MiB/s). Two targeted speedups in bch.c helped:

1. Fusing the shift and the table XOR into a single pass. The remainder update was two loops over the register per input byte — shift left by one byte, then XOR the table entry. They fuse: new rem[i] = old rem[i+1] ^ T[idx][i], reading rem[i+1] before it is overwritten (sweeping i upward keeps this exact). Syndrome speed went 37 → 50.8 MiB/s. The BCH unit harness (7,406 checks) still passes, and so does the full 147-test archive suite that shares this codec.

2. Syndrome-first, no-copy decode. bch_decode_block used to copy the whole block into a working buffer before even checking the syndrome. Now it computes the syndrome straight from the input, and only allocates the working copy if the remainder is non-zero (i.e. only when Berlekamp-Massey / Chien search actually has to run). The common clean case does no copy at all.

Together they took the read from ~22 MiB/s (first build) to ~35 MiB/s. The remaining cost is the syndrome plus SHA-256; the transpose and the I/O are negligible by comparison. A tiny poly is a trap, by the way: poly 0001 (m=7, t=1) reads a 100 MiB file at 1.4 MiB/s — not because the syndrome per byte is slower, but because the blocks are tiny (~100 bytes), so a 100 MiB file is ~1,000,000 blocks and the per-block overhead dominates. Poly 0044 (m=20) has 131 KiB blocks, so 100 MiB is 801 blocks.

THE DEMO — 100 MiB, THREE STRIPES DELETED, BYTE-IDENTICAL

Real output from the server, Nov 25, 2026. A 100 MiB random file, 8 stripes + 3 parities, poly 0044:

$ lzply_hyper -c cfg.txt -init
stripe s0: /tmp/hyper-demo/vol/s0.bin (created, capacity 1073741824 bytes)
... (8 stripes, 3 parities) ...
volume initialized: 8 data stripes, 3 parity stripe(s), poly 0x0044 t=8
$ lzply_hyper -c cfg.txt write big.bin big
wrote 'big': 104857600 bytes, stripe_off 0, stripe_len 13107200,
  bch 16020 bytes, sha256 a89cc4d7bcd5621d0b0fee033380628861aab5c48c0e2bab2218e211a3cb76bd
$ lzply_hyper -c cfg.txt list
index from parity stripe 0 (p0): 1 file(s)
  big  104857600 bytes  poly 0x0044 t=8  stripe_off 0  stripe_len 13107200
1 file(s), 104857600 bytes total
$ rm vol/s0.bin vol/s4.bin vol/s7.bin        # delete 3 data stripes
$ lzply_hyper -c cfg.txt read big big.out
read 'big': 104857600 bytes -> big.out (rebuilt 3 dead stripes)
$ cmp big.bin big.out                          # byte-identical
$ lzply_hyper -c cfg.txt -rebuild
rebuilt data stripe s0 (vol/s0.bin)
rebuilt data stripe s4 (vol/s4.bin)
rebuilt data stripe s7 (vol/s7.bin)
rebuild complete
$ lzply_hyper -c cfg.txt check big
check 'big': OK (104857600 bytes, sha256 verified)

The same demo also covered 1-stripe loss (delete s3 → read rebuilds via P, -rebuild restores it) and 2-stripe loss (delete s1 s6 → read rebuilds via P+Q), and parity loss (delete p1 → data still readable, -rebuild restores the parity stripe). Per-stripe files for the 100 MiB file: each data stripe 13,107,200 bytes; each parity stripe 13,123,319 bytes. Overhead for 3 parities: 3 × 12.5% + 16,020 BCH bytes ≈ 37.5%.

TESTS — 56 OUT OF 56

tests/run_hyper_tests.sh, run on the server and locally (no FUSE needed — it is a plain CLI). make test also runs the bch_test unit suite (7,406 checks) and the lzply archive suite (147 tests).

  • Config parsing (10): valid 8+3; mismatched poly/error_level (0044 + level 5); 7 data stripes; bad size (10X); parity lines disagreeing on poly; 4 parity stripes; 0 parity stripes; unknown poly (00ff); missing config file; ro stripe (write refused, read works).
  • -init (5): creates 8+3 files, all empty; missing parent directory; insufficient space (8 × 100T); refuses to overwrite without --force; --force replaces.
  • Roundtrips (8): empty, 1 byte, small text, 1 MiB random, 8 MiB random — all byte-identical; list shows all 5 files; check passes clean; duplicate write refused.
  • Bit-plane layout (4): the four hand-computed cases above.
  • 1-stripe loss (4): delete → read via P; -rebuild restores; truncate to half → read via P; -rebuild restores a truncated stripe.
  • 2-stripe loss (3): delete 2 → read via P+Q; -rebuild restores both; the same loss with only 1 parity must fail.
  • 3-stripe loss (4): delete 3 → read via P+Q+R; -rebuild restores all three; the same loss with only 2 parities must fail; Q alone rebuilds 1 lost stripe when P is dead.
  • 4-stripe loss (3): read must fail; no byte-identical output may be produced; -rebuild must fail.
  • Bit-flip correction (4): 3 flipped bits in a data stripe → read corrects via BCH and reports it; check reports it; 3 flipped bits in a parity stripe → data still readable.
  • Parity-stripe loss (3): delete 1 → readable, -rebuild restores; delete all → read fails (no index).
  • Capacity (3): an 8 KiB file exactly fills 1 KiB stripes; a further write fails; the failed write leaves the volume intact.
  • SHA-256 tamper (3): 12 flipped bits in one BCH block → check fails, read fails, no byte-identical output.
  • Read-speed benchmark (1): 32 MiB read timed and reported (36.0 MiB/s on the server).

BUGS FOUND WHILE BUILDING IT

1. The poly id parsed as decimal, not hex — silently the wrong polynomial. The config parser read 0044 as decimal 44 (0x002c, m=16, t=8) because it had no a–f digits and no 0x prefix. The design says 0044 is m=20, t=8. Both are valid t=8 polys, so the error-level check passed and nothing complained — the tool would have quietly used a different polynomial than the one in the config. Fixed by parsing the poly field as hex always (an optional 0x prefix is accepted). The test suite now pins it: a volume initialised with 0044 reports poly 0x0044.

2. hyper_recover read out of bounds when fewer than 3 stripes were lost. The first version skipped lost stripes by comparing j == lost[0]/lost[1]/lost[2] — an out-of-bounds read when k < 3, and the allocated buffers defeated the NULL check that was supposed to catch it. Fixed with an explicit is_lost[8] boolean array. The 1- and 2-stripe loss tests cover the k=1 and k=2 paths.

3. -rebuild would have left a gap in a rebuilt stripe. A damaged stripe file that is truncated (wrong total size) can still read fine for a file near the front — the truncation only cut off the tail. The first rebuild loop only wrote recovered data for stripes that were dead for that file, so a stripe that read fine for an early file got nothing written for it, and the rebuilt file's offsets drifted. Fixed by writing every damaged stripe's data (read or recovered) for every file, in index order.

4. -rebuild trusted the old bytes of a wrong-size stripe. Same root as bug 3, the other direction: a wrong-size stripe file can hold corrupt bytes in the part that survived. The rebuild now forces every damaged stripe dead for every file, so the rebuilt stripe is derived purely from parity, never from its own old bytes.

5. index_build took the first readable parity stripe — which could be a truncated one. A parity stripe cut short yields a short index (fewer files, no error), and the first readable stripe might be that short one. Fixed by scanning all parity stripes and keeping the one with the most records; a crashed write can leave one parity stripe one record ahead, and that record's stripe data is already on disk, so the longest index is the right one.

6. The read path was slow because of the BCH syndrome — and the fix was in the shared codec, so it had to be verified against everything that shares it. First build read at ~22 MiB/s. The two bch.c speedups (fused shift+XOR, syndrome-first no-copy decode) took it to ~35 MiB/s. Because bch.c is shared with the lzply archive tool, the change was verified by the BCH unit harness (7,406 checks, 0 fails), the full archive suite (147 tests), and the hyper suite (56 tests) — all green on the server and locally.

7. My own hand-computed layout values were wrong — and the tool was right. For the 16-byte 00..0F layout case I wrote stripe 1 = 0x66 and stripe 2 = 0x3C. The tool produced 0xCC and 0xF0. Recomputing by hand (and cross-checking with an independent Python transpose) showed the tool was correct and my arithmetic was wrong. The test now asserts the correct values. The lesson is the same as the transpose warning above: hand-computed expectations are only as good as the hand that computed them, so cross-check them independently.

LIMITATIONS (v1, STATED PLAINLY)

  • Whole files are buffered in memory. A 100 MiB file is fine; multi-gigabyte files need a streaming rewrite.
  • write refuses to overwrite an existing name — there is no delete or overwrite command in v1.
  • -rebuild detects missing or wrong-size stripes only. Bit rot inside a stripe file (right size, wrong bytes) is corrected on read by BCH, but does not trigger a stripe rewrite.
  • If every parity stripe is dead, the index is gone: files are unreadable by name even though the data stripes are intact.
  • BCH is a bit-error code: it corrects scattered bit flips, not whole lost bytes. A burst that wipes many consecutive bits in one block can exceed t even when the byte count is small.
  • The BCH decoder builds GF(2m) log/exp tables (up to 32 MiB transient for m=22) the first time it has to correct an error in a block; the no-error path needs no tables and stays fast.
  • A crash mid-write (stripes written, parity records not yet appended) leaves orphaned stripe data — wasted space, not corruption, and the file is simply not in the index.
  • Read speed is bounded by the BCH syndrome (~50 MiB/s) plus SHA-256 (~178 MiB/s). The syndrome is a serial LFSR remainder and cannot be vectorised; making it fundamentally faster needs a different syndrome algorithm, not a faster loop.

FULL SOURCE CODE

Everything below is the exact code on the server at /opt/lzply/src, installed as /usr/local/bin/lzply_hyper. Copy it, build it with make lzply_hyper, run make test. The BCH codec and SHA-256 are shared with the lzply archive tool (see the companion article); bch_polys.h holds the 82 generator polynomials from the rssearch exhaustive search.

lzply_hyper.c

The whole tool — config parser, bit-plane stripe engine (SWAR 8x8 transpose), GF(256) P/Q/R parity, recovery by Gauss-Jordan inversion, BCH + SHA-256 verify, -init / write / read / list / check / -rebuild

/* lzply_hyper.c - striped volume with bit-plane striping and multi-stripe-loss recovery.
 *
 * A user-space striped volume, RAID-0 style but recoverable:
 *   - 8 data stripes, bit-plane: byte i splits into its 8 bits, bit j
 *     goes to stripe j. Stripe j holds one bit of every byte, packed.
 *     No compression anywhere. Write speed is not a constraint;
 *     read speed is the priority.
 *   - Stripe-loss layer (required): independent parity stripes P, Q, R.
 *     P = XOR across the 8 data stripes (recovers 1 lost stripe).
 *     Q = GF(256) weighted parity (recovers a 2nd lost stripe, RAID-6 style).
 *     R = GF(256) weighted parity with different coefficients (recovers
 *     a 3rd lost stripe). 1 parity -> 1 loss, 2 parities -> 2 losses,
 *     3 parities -> 3 losses. The parities are INDEPENDENT, not mirrors.
 *   - Bit-rot layer: BCH parity over the whole file, using the config's
 *     poly + error level (reuses bch.c). SHA-256 over the file for
 *     verification (reuses sha256.c).
 *
 * Config file (-c config.txt), one entry per line:
 *   stripe:<label>:<file>:<rw>:<size>
 *   parity:<label>:<file>:<rw>:<poly>:<error_level>
 *   rw = read-write, ro = read-only. size = capacity, K/M/G suffixes.
 *   poly is authoritative; error_level must agree with it
 *   (bch_t_for_level). 8 data stripes (bit-plane fixes the count),
 *   1..3 parity stripes.
 *
 * Commands (lzply_hyper -c config.txt <command>):
 *   -init [--force]   create the stripe/parity files (checks dirs,
 *                     writability, free space; refuses to overwrite
 *                     existing files without --force)
 *   write <file> [name]  stripe a file into the volume
 *   read <name> <out>    read a file back (fast path; rebuilds a dead
 *                     stripe via parity if needed; verifies SHA-256)
 *   list              list files in the volume
 *   check <name>      verify a file (XOR + BCH + SHA-256, no output)
 *   -rebuild          rebuild lost/corrupt stripes from parity
 *
 * Exit codes: 0 ok, 1 usage, 2 I/O error, 3 corrupt/unrecoverable.
 * (Matches the lzply family convention.)
 */
#define _FILE_OFFSET_BITS 64
#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdarg.h>
#include <errno.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/types.h>

#include "bch.h"
#include "sha256.h"

#define HYPER_NSTRIPES 8
#define HYPER_MAXPAR 3
#define HYPER_BURST (64u * 1024u)   /* I/O burst size */
#define HYPER_MAXNAME 255

#define EXIT_OK 0
#define EXIT_USAGE 1
#define EXIT_IO 2
#define EXIT_CORRUPT 3

static const char *prog = "lzply_hyper";

/* ------------------------------------------------------------------ */
/* small helpers                                                       */
/* ------------------------------------------------------------------ */

static void die(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    fprintf(stderr, "%s: ", prog);
    vfprintf(stderr, fmt, ap);
    fputc('\n', stderr);
    va_end(ap);
    exit(EXIT_IO);
}

static void *xmalloc(size_t n)
{
    void *p = malloc(n ? n : 1);
    if (!p)
        die("out of memory");
    return p;
}

static void *xcalloc(size_t n, size_t sz)
{
    void *p = calloc(n ? n : 1, sz ? sz : 1);
    if (!p)
        die("out of memory");
    return p;
}

static void *xrealloc(void *p, size_t n)
{
    void *q = realloc(p, n ? n : 1);
    if (!q)
        die("out of memory");
    return q;
}

static char *xstrdup(const char *s)
{
    char *p = strdup(s);
    if (!p)
        die("out of memory");
    return p;
}

/* CRC-32 (IEEE, poly 0xEDB88320), table built on first use. */
static uint32_t crc32_table[256];
static int crc32_ready = 0;

static void crc32_init(void)
{
    if (crc32_ready)
        return;
    for (uint32_t i = 0; i < 256; i++) {
        uint32_t c = i;
        for (int k = 0; k < 8; k++)
            c = (c & 1) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
        crc32_table[i] = c;
    }
    crc32_ready = 1;
}

static uint32_t hyper_crc32(const uint8_t *buf, size_t len)
{
    crc32_init();
    uint32_t c = 0xFFFFFFFFu;
    for (size_t i = 0; i < len; i++)
        c = crc32_table[(c ^ buf[i]) & 0xFF] ^ (c >> 8);
    return c ^ 0xFFFFFFFFu;
}

/* little-endian helpers */
static void put_u16(uint8_t *p, uint16_t v)
{
    p[0] = (uint8_t)(v & 0xFF);
    p[1] = (uint8_t)((v >> 8) & 0xFF);
}

static void put_u32(uint8_t *p, uint32_t v)
{
    p[0] = (uint8_t)(v & 0xFF);
    p[1] = (uint8_t)((v >> 8) & 0xFF);
    p[2] = (uint8_t)((v >> 16) & 0xFF);
    p[3] = (uint8_t)((v >> 24) & 0xFF);
}

static void put_u64(uint8_t *p, uint64_t v)
{
    for (int i = 0; i < 8; i++)
        p[i] = (uint8_t)((v >> (8 * i)) & 0xFF);
}

static uint16_t get_u16(const uint8_t *p)
{
    return (uint16_t)(p[0] | ((uint16_t)p[1] << 8));
}

static uint32_t get_u32(const uint8_t *p)
{
    return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
           ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}

static uint64_t get_u64(const uint8_t *p)
{
    uint64_t v = 0;
    for (int i = 0; i < 8; i++)
        v |= (uint64_t)p[i] << (8 * i);
    return v;
}

/* Parse a size with optional K/M/G suffix (1024-based). Returns 0 on error. */
static int parse_size(const char *s, uint64_t *out)
{
    if (!s || !*s)
        return 0;
    char *end;
    errno = 0;
    unsigned long long v = strtoull(s, &end, 10);
    if (errno || end == s)
        return 0;
    uint64_t mult = 1;
    if (*end) {
        char c = (char)toupper((unsigned char)*end);
        if (c == 'K')
            mult = 1024ULL;
        else if (c == 'M')
            mult = 1024ULL * 1024ULL;
        else if (c == 'G')
            mult = 1024ULL * 1024ULL * 1024ULL;
        else
            return 0;
        end++;
        if (*end == 'B' || *end == 'b')
            end++;
        if (*end)
            return 0;
    }
    if (v > UINT64_MAX / mult)
        return 0;
    *out = v * mult;
    return *out > 0;
}

/* Parse a poly id like lzply's poly= : hex if it has a-f digits or a
 * 0x prefix, else decimal. Returns 0 on error. */
/* Poly ids in the config are hex, as written in the design and the
 * polynomial tables (0044 = m=20, t=8; 003a = m=18, t=32). An
 * optional 0x prefix is accepted. */
static int parse_poly_id(const char *s, uint16_t *out)
{
    if (!s || !*s)
        return 0;
    if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
        s += 2;
    if (!*s)
        return 0;
    char *end;
    errno = 0;
    unsigned long v = strtoul(s, &end, 16);
    if (errno || end == s || *end || v > 0xFFFF)
        return 0;
    *out = (uint16_t)v;
    return 1;
}

static void hex32(const uint8_t *b, char *out)
{
    static const char *h = "0123456789abcdef";
    for (int i = 0; i < 32; i++) {
        out[2 * i] = h[b[i] >> 4];
        out[2 * i + 1] = h[b[i] & 0xF];
    }
    out[64] = '\0';
}

/* ------------------------------------------------------------------ */
/* GF(256) arithmetic (primitive poly 0x11d, generator 2)               */
/* ------------------------------------------------------------------ */

static uint8_t gf256_exp[512];
static uint8_t gf256_log[256];
static int gf256_ready = 0;

static void gf256_init(void)
{
    if (gf256_ready)
        return;
    int x = 1;
    for (int i = 0; i < 255; i++) {
        gf256_exp[i] = (uint8_t)x;
        gf256_log[x] = (uint8_t)i;
        x <<= 1;
        if (x & 0x100)
            x ^= 0x11D;
    }
    for (int i = 255; i < 512; i++)
        gf256_exp[i] = gf256_exp[i - 255];
    gf256_ready = 1;
}

static uint8_t gf256_mul(uint8_t a, uint8_t b)
{
    if (a == 0 || b == 0)
        return 0;
    gf256_init();
    return gf256_exp[gf256_log[a] + gf256_log[b]];
}

static uint8_t gf256_inv(uint8_t a)
{
    if (a == 0)
        return 0;
    gf256_init();
    return gf256_exp[255 - gf256_log[a]];
}

/* g^e in GF(256), e any integer (reduced mod 255). */
static uint8_t gf256_pow2(int e)
{
    gf256_init();
    e %= 255;
    if (e < 0)
        e += 255;
    return gf256_exp[e];
}

/* ------------------------------------------------------------------ */
/* 8x8 bit-matrix transpose (SWAR).                                    */
/*                                                                     */
/* Input: 8 bytes a[0..7] packed little-endian into a uint64 (a[0] in */
/* the lowest byte). Output: 8 bytes b[0..7] where b[j] bit p =       */
/* a[p] bit j. The transpose is an involution, so the same function    */
/* converts file bytes -> stripe bytes (write) and stripe bytes ->     */
/* file bytes (read). The test suite checks the on-disk layout      */
/* against hand-computed values (tests/run_hyper_tests.sh).           */
/* ------------------------------------------------------------------ */

static uint64_t transpose8x8(uint64_t x)
{
    uint64_t t;
    t = (x ^ (x >> 7)) & 0x00AA00AA00AA00AAULL;
    x = x ^ t ^ (t << 7);
    t = (x ^ (x >> 14)) & 0x0000CCCC0000CCCCULL;
    x = x ^ t ^ (t << 14);
    t = (x ^ (x >> 28)) & 0x00000000F0F0F0F0ULL;
    x = x ^ t ^ (t << 28);
    return x;
}

/* ------------------------------------------------------------------ */
/* Config                                                              */
/* ------------------------------------------------------------------ */

typedef struct {
    char label[64];
    char path[1024];
    int rw; /* 1 = rw, 0 = ro */
    uint64_t size; /* capacity bytes (stripes only) */
} hyper_stripe_t;

typedef struct {
    char label[64];
    char path[1024];
    int rw; /* 1 = rw, 0 = ro */
    uint16_t poly_id;
    int level; /* error_level 0..7 */
    const bch_poly_t *poly;
} hyper_parity_t;

typedef struct {
    hyper_stripe_t stripes[HYPER_NSTRIPES];
    int nstripes;
    hyper_parity_t parities[HYPER_MAXPAR];
    int nparities;
    const bch_poly_t *poly; /* from the first parity line */
    int t;
    char path[1024]; /* config file path (for messages) */
} hyper_cfg_t;

static void cfg_error(hyper_cfg_t *cfg, const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    fprintf(stderr, "%s: %s: ", prog, cfg->path);
    vfprintf(stderr, fmt, ap);
    fputc('\n', stderr);
    va_end(ap);
    exit(EXIT_USAGE);
}

/* Split a line on ':' into fields. Returns field count, or -1 on error.
 * fields[] gets pointers into a copy of the line. */
static int split_fields(char *line, char **fields, int maxf)
{
    int n = 0;
    char *p = line;
    while (1) {
        if (n >= maxf)
            return -1;
        fields[n++] = p;
        char *c = strchr(p, ':');
        if (!c)
            break;
        *c = '\0';
        p = c + 1;
    }
    return n;
}

static int parse_cfg(const char *path, hyper_cfg_t *cfg)
{
    memset(cfg, 0, sizeof(*cfg));
    snprintf(cfg->path, sizeof(cfg->path), "%s", path);
    FILE *f = fopen(path, "r");
    if (!f) {
        fprintf(stderr, "%s: cannot open config %s: %s\n", prog, path,
                strerror(errno));
        return -1;
    }
    char line[4096];
    int lineno = 0;
    while (fgets(line, sizeof(line), f)) {
        lineno++;
        /* strip trailing newline / CR */
        size_t L = strlen(line);
        while (L && (line[L - 1] == '\n' || line[L - 1] == '\r'))
            line[--L] = '\0';
        /* skip blank lines and comments */
        char *s = line;
        while (*s == ' ' || *s == '\t')
            s++;
        if (!*s || *s == '#')
            continue;
        char *fields[8];
        int nf = split_fields(s, fields, 8);
        if (nf < 0) {
            fclose(f);
            cfg_error(cfg, "line %d: too many fields", lineno);
        }
        if (strcmp(fields[0], "stripe") == 0) {
            if (nf != 5) {
                fclose(f);
                cfg_error(cfg, "line %d: stripe needs 5 fields "
                               "(stripe:label:file:rw:size)", lineno);
            }
            if (cfg->nstripes >= HYPER_NSTRIPES) {
                fclose(f);
                cfg_error(cfg, "line %d: too many data stripes "
                               "(bit-plane layout fixes the count at 8)",
                          lineno);
            }
            hyper_stripe_t *st = &cfg->stripes[cfg->nstripes];
            if (strlen(fields[1]) == 0 || strlen(fields[1]) >= sizeof(st->label)) {
                fclose(f);
                cfg_error(cfg, "line %d: bad stripe label", lineno);
            }
            snprintf(st->label, sizeof(st->label), "%s", fields[1]);
            if (strlen(fields[2]) == 0 || strlen(fields[2]) >= sizeof(st->path)) {
                fclose(f);
                cfg_error(cfg, "line %d: bad stripe file path", lineno);
            }
            snprintf(st->path, sizeof(st->path), "%s", fields[2]);
            if (strcmp(fields[3], "rw") == 0)
                st->rw = 1;
            else if (strcmp(fields[3], "ro") == 0)
                st->rw = 0;
            else {
                fclose(f);
                cfg_error(cfg, "line %d: rw field must be rw or ro", lineno);
            }
            if (!parse_size(fields[4], &st->size)) {
                fclose(f);
                cfg_error(cfg, "line %d: bad stripe size '%s'", lineno, fields[4]);
            }
            cfg->nstripes++;
        } else if (strcmp(fields[0], "parity") == 0) {
            if (nf != 6) {
                fclose(f);
                cfg_error(cfg, "line %d: parity needs 6 fields "
                               "(parity:label:file:rw:poly:error_level)", lineno);
            }
            if (cfg->nparities >= HYPER_MAXPAR) {
                fclose(f);
                cfg_error(cfg, "line %d: too many parity stripes "
                               "(v1 supports at most 3)", lineno);
            }
            hyper_parity_t *pa = &cfg->parities[cfg->nparities];
            if (strlen(fields[1]) == 0 || strlen(fields[1]) >= sizeof(pa->label)) {
                fclose(f);
                cfg_error(cfg, "line %d: bad parity label", lineno);
            }
            snprintf(pa->label, sizeof(pa->label), "%s", fields[1]);
            if (strlen(fields[2]) == 0 || strlen(fields[2]) >= sizeof(pa->path)) {
                fclose(f);
                cfg_error(cfg, "line %d: bad parity file path", lineno);
            }
            snprintf(pa->path, sizeof(pa->path), "%s", fields[2]);
            if (strcmp(fields[3], "rw") == 0)
                pa->rw = 1;
            else if (strcmp(fields[3], "ro") == 0)
                pa->rw = 0;
            else {
                fclose(f);
                cfg_error(cfg, "line %d: rw field must be rw or ro", lineno);
            }
            uint16_t pid;
            if (!parse_poly_id(fields[4], &pid)) {
                fclose(f);
                cfg_error(cfg, "line %d: bad polynomial id '%s'", lineno, fields[4]);
            }
            const bch_poly_t *poly = bch_poly_by_id(pid);
            if (!poly) {
                fclose(f);
                cfg_error(cfg, "line %d: unknown polynomial id 0x%04x", lineno, pid);
            }
            char *end;
            errno = 0;
            long lvl = strtol(fields[5], &end, 10);
            if (errno || end == fields[5] || *end || lvl < 0 || lvl > 7) {
                fclose(f);
                cfg_error(cfg, "line %d: bad error_level '%s' (0..7)", lineno, fields[5]);
            }
            int t = bch_t_for_level((int)lvl);
            if (t < 0 || t != poly->t) {
                fclose(f);
                cfg_error(cfg, "line %d: error_level %ld (t=%d) does not "
                               "agree with poly 0x%04x (t=%d)", lineno, lvl, t,
                          pid, poly->t);
            }
            pa->poly_id = pid;
            pa->level = (int)lvl;
            pa->poly = poly;
            cfg->nparities++;
        } else {
            fclose(f);
            cfg_error(cfg, "line %d: unknown entry type '%s' (stripe or parity)",
                      lineno, fields[0]);
        }
    }
    fclose(f);
    if (cfg->nstripes != HYPER_NSTRIPES) {
        cfg_error(cfg, "need exactly 8 data stripes (bit-plane layout), "
                       "config has %d", cfg->nstripes);
    }
    if (cfg->nparities < 1) {
        cfg_error(cfg, "need at least 1 parity stripe");
    }
    /* labels must be unique across all entries */
    for (int i = 0; i < cfg->nstripes; i++) {
        for (int j = i + 1; j < cfg->nstripes; j++) {
            if (strcmp(cfg->stripes[i].label, cfg->stripes[j].label) == 0)
                cfg_error(cfg, "duplicate label '%s'", cfg->stripes[i].label);
        }
        for (int j = 0; j < cfg->nparities; j++) {
            if (strcmp(cfg->stripes[i].label, cfg->parities[j].label) == 0)
                cfg_error(cfg, "duplicate label '%s'", cfg->stripes[i].label);
        }
    }
    for (int i = 0; i < cfg->nparities; i++) {
        for (int j = i + 1; j < cfg->nparities; j++) {
            if (strcmp(cfg->parities[i].label, cfg->parities[j].label) == 0)
                cfg_error(cfg, "duplicate label '%s'", cfg->parities[i].label);
        }
    }
    /* all parity lines must agree on poly + error level; the first
     * parity line is authoritative */
    cfg->poly = cfg->parities[0].poly;
    cfg->t = cfg->parities[0].poly->t;
    for (int i = 1; i < cfg->nparities; i++) {
        if (cfg->parities[i].poly_id != cfg->parities[0].poly_id ||
            cfg->parities[i].level != cfg->parities[0].level) {
            cfg_error(cfg, "parity lines disagree on poly/error_level "
                           "(%s has 0x%04x:%d, %s has 0x%04x:%d)",
                      cfg->parities[0].label, cfg->parities[0].poly_id,
                      cfg->parities[0].level, cfg->parities[i].label,
                      cfg->parities[i].poly_id, cfg->parities[i].level);
        }
    }
    return 0;
}

/* ------------------------------------------------------------------ */
/* Parity record format                                                */
/*                                                                     */
/* Each parity stripe file is a sequence of records, one per file in  */
/* the volume, appended in write order. Each record holds: a fixed    */
/* 96-byte header, the file name, that parity stripe's parity bytes   */
/* (P, Q or R for this record), and the BCH parity bytes (same on    */
/* every parity stripe). The header carries everything needed to     */
/* find and verify the file: name, original length, stripe offset    */
/* and length, poly, t, parity lengths, SHA-256 of the original.     */
/*                                                                     */
/* Header (96 bytes, little-endian):                                   */
/*   0  magic[4] "HYPR"                                               */
/*   4  version u8 = 1                                                */
/*   5  parity_idx u8 (0=P, 1=Q, 2=R)                                 */
/*   6  flags u8 (0)                                                  */
/*   7  reserved u8                                                   */
/*   8  name_len u16                                                  */
/*  10  poly_id u16                                                   */
/*  12  t u8                                                          */
/*  13  npar u8 (parity stripes in the volume)                        */
/*  14  reserved u16                                                  */
/*  16  orig_len u64                                                  */
/*  24  stripe_off u64 (offset in stripe files)                       */
/*  32  stripe_len u64 (bytes per stripe = ceil(orig_len/8))          */
/*  40  parity_len u64 (= stripe_len)                                 */
/*  48  bch_len u64                                                   */
/*  56  sha256[32]                                                    */
/*  88  header_crc32 u32 (covers bytes 0..87)                         */
/*  92  reserved u32                                                  */
/* Then: name[name_len], parity[parity_len], bch[bch_len].             */
/* ------------------------------------------------------------------ */

#define HYPER_HDR_LEN 96
#define HYPER_MAGIC "HYPR"

typedef struct {
    uint8_t parity_idx;
    uint16_t name_len;
    uint16_t poly_id;
    uint8_t t;
    uint8_t npar;
    uint64_t orig_len;
    uint64_t stripe_off;
    uint64_t stripe_len;
    uint64_t parity_len;
    uint64_t bch_len;
    uint8_t sha256[32];
    char name[HYPER_MAXNAME + 1];
    uint64_t rec_off; /* file offset of this record in its parity stripe */
} hyper_rec_t;

static void hyper_rec_pack(const hyper_rec_t *r, uint8_t *h)
{
    memset(h, 0, HYPER_HDR_LEN);
    memcpy(h, HYPER_MAGIC, 4);
    h[4] = 1;
    h[5] = r->parity_idx;
    h[6] = 0;
    h[7] = 0;
    put_u16(h + 8, r->name_len);
    put_u16(h + 10, r->poly_id);
    h[12] = r->t;
    h[13] = r->npar;
    put_u16(h + 14, 0);
    put_u64(h + 16, r->orig_len);
    put_u64(h + 24, r->stripe_off);
    put_u64(h + 32, r->stripe_len);
    put_u64(h + 40, r->parity_len);
    put_u64(h + 48, r->bch_len);
    memcpy(h + 56, r->sha256, 32);
    put_u32(h + 88, hyper_crc32(h, 88));
    put_u32(h + 92, 0);
}

/* Returns 0 ok, -1 bad magic/version/CRC. */
static int hyper_rec_unpack(const uint8_t *h, hyper_rec_t *r)
{
    if (memcmp(h, HYPER_MAGIC, 4) != 0)
        return -1;
    if (h[4] != 1)
        return -1;
    if (get_u32(h + 88) != hyper_crc32(h, 88))
        return -1;
    memset(r, 0, sizeof(*r));
    r->parity_idx = h[5];
    r->name_len = get_u16(h + 8);
    r->poly_id = get_u16(h + 10);
    r->t = h[12];
    r->npar = h[13];
    r->orig_len = get_u64(h + 16);
    r->stripe_off = get_u64(h + 24);
    r->stripe_len = get_u64(h + 32);
    r->parity_len = get_u64(h + 40);
    r->bch_len = get_u64(h + 48);
    memcpy(r->sha256, h + 56, 32);
    if (r->parity_idx > 2 || r->name_len == 0 || r->name_len > HYPER_MAXNAME)
        return -1;
    if (r->parity_len != r->stripe_len)
        return -1;
    return 0;
}

/* Stripe bytes for a file of orig_len bytes. */
static uint64_t hyper_stripe_len(uint64_t orig_len)
{
    return (orig_len + 7) / 8;
}

/* ------------------------------------------------------------------ */
/* BCH parity helpers (block API: parity bytes extracted per block)    */
/* ------------------------------------------------------------------ */

/* Total BCH parity bytes for a file of len bytes with poly p. */
static size_t hyper_bch_parity_len(size_t len, const bch_poly_t *p)
{
    if (len == 0)
        return 0;
    return bch_encoded_len(len, p) - len;
}

/* Extract the BCH parity bytes for data[0..len) into out
 * (must hold hyper_bch_parity_len(len, p) bytes). */
static void hyper_bch_parity(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, ooff = 0;
    while (off < len) {
        size_t d = len - off;
        if (d > maxd)
            d = maxd;
        size_t slen = bch_block_stored_len(d, p);
        uint8_t *stored = xmalloc(slen);
        bch_encode_block(data + off, d, p, stored);
        size_t plen = slen - d;
        if (plen)
            memcpy(out + ooff, stored + d, plen);
        ooff += plen;
        free(stored);
        off += d;
    }
}

/* Correct data[0..len) in place using parity[0..hyper_bch_parity_len).
 * Returns 0 ok, -1 uncorrectable. *corrected (if non-NULL) = bits fixed. */
static int hyper_bch_correct(uint8_t *data, size_t len, const uint8_t *parity,
                             const bch_poly_t *p, int *corrected)
{
    if (corrected)
        *corrected = 0;
    if (len == 0)
        return 0;
    size_t maxd = bch_max_data(p);
    size_t off = 0, poff = 0;
    int total = 0;
    while (off < len) {
        size_t d = len - off;
        if (d > maxd)
            d = maxd;
        size_t slen = bch_block_stored_len(d, p);
        size_t plen = slen - d;
        uint8_t *stored = xmalloc(slen);
        uint8_t *outb = xmalloc(d);
        memcpy(stored, data + off, d);
        if (plen)
            memcpy(stored + d, parity + poff, plen);
        int c = 0;
        int rc = bch_decode_block(stored, slen, d, p, outb, &c);
        free(stored);
        if (rc != 0) {
            free(outb);
            return -1;
        }
        memcpy(data + off, outb, d);
        free(outb);
        total += c;
        poff += plen;
        off += d;
    }
    if (corrected)
        *corrected = total;
    return 0;
}

/* ------------------------------------------------------------------ */
/* File I/O helpers                                                    */
/* ------------------------------------------------------------------ */

/* Read a whole file into memory. Returns buffer (caller frees) and
 * sets *len. Dies on error. */
static uint8_t *read_whole_file(const char *path, size_t *len)
{
    FILE *f = fopen(path, "rb");
    if (!f)
        die("cannot open %s: %s", path, strerror(errno));
    if (fseek(f, 0, SEEK_END) != 0)
        die("cannot seek %s: %s", path, strerror(errno));
    long sz = ftell(f);
    if (sz < 0)
        die("cannot stat %s: %s", path, strerror(errno));
    if (fseek(f, 0, SEEK_SET) != 0)
        die("cannot seek %s: %s", path, strerror(errno));
    uint8_t *buf = xmalloc((size_t)sz);
    if (sz > 0 && fread(buf, 1, (size_t)sz, f) != (size_t)sz)
        die("cannot read %s: %s", path, strerror(errno));
    fclose(f);
    *len = (size_t)sz;
    return buf;
}

/* Write len bytes from buf to path (truncate/create). Dies on error. */
static void write_whole_file(const char *path, const uint8_t *buf, size_t len)
{
    FILE *f = fopen(path, "wb");
    if (!f)
        die("cannot open %s for writing: %s", path, strerror(errno));
    if (len > 0 && fwrite(buf, 1, len, f) != len)
        die("cannot write %s: %s", path, strerror(errno));
    if (fclose(f) != 0)
        die("cannot close %s: %s", path, strerror(errno));
}

/* File size, or -1 if it does not exist / cannot be statted. */
static int64_t file_size(const char *path)
{
    struct stat st;
    if (stat(path, &st) != 0)
        return -1;
    return (int64_t)st.st_size;
}

/* Parent directory of path (everything before the last '/'), or "."
 * if there is none. Returns a malloc'd string. */
static char *parent_dir(const char *path)
{
    const char *slash = strrchr(path, '/');
    if (!slash)
        return xstrdup(".");
    if (slash == path)
        return xstrdup("/");
    return strndup(path, (size_t)(slash - path));
}

/* ------------------------------------------------------------------ */
/* Index: scan a parity stripe file into an in-memory list of records  */
/* ------------------------------------------------------------------ */

typedef struct {
    hyper_rec_t *recs;
    size_t n, cap;
    int bad; /* set if scanning stopped on a bad record */
} hyper_index_t;

static void index_add(hyper_index_t *idx, const hyper_rec_t *r)
{
    if (idx->n == idx->cap) {
        idx->cap = idx->cap ? idx->cap * 2 : 16;
        idx->recs = xrealloc(idx->recs, idx->cap * sizeof(hyper_rec_t));
    }
    idx->recs[idx->n++] = *r;
}

/* Scan parity stripe file `path` for records. Returns 0 on success
 * (even if the file is empty), -1 if the file cannot be opened.
 * Records are appended to idx in file order. Stops (sets idx->bad)
 * at the first bad record. */
static int index_scan(const char *path, hyper_index_t *idx)
{
    FILE *f = fopen(path, "rb");
    if (!f)
        return -1;
    uint64_t off = 0;
    while (1) {
        uint8_t h[HYPER_HDR_LEN];
        if (fseek(f, (long)off, SEEK_SET) != 0)
            break;
        size_t n = fread(h, 1, HYPER_HDR_LEN, f);
        if (n == 0)
            break; /* clean EOF */
        if (n < HYPER_HDR_LEN) {
            idx->bad = 1;
            break;
        }
        hyper_rec_t r;
        if (hyper_rec_unpack(h, &r) != 0) {
            idx->bad = 1;
            break;
        }
        /* read the name */
        if (fseek(f, (long)(off + HYPER_HDR_LEN), SEEK_SET) != 0) {
            idx->bad = 1;
            break;
        }
        if (fread(r.name, 1, r.name_len, f) != r.name_len) {
            idx->bad = 1;
            break;
        }
        r.name[r.name_len] = '\0';
        r.rec_off = off;
        index_add(idx, &r);
        uint64_t recsize = HYPER_HDR_LEN + r.name_len + r.parity_len + r.bch_len;
        off += recsize;
    }
    fclose(f);
    return 0;
}

static const hyper_rec_t *index_find(const hyper_index_t *idx, const char *name)
{
    for (size_t i = 0; i < idx->n; i++) {
        if (strcmp(idx->recs[i].name, name) == 0)
            return &idx->recs[i];
    }
    return NULL;
}

/* Build the index from the best surviving parity stripe. Scans all
 * parity stripes and keeps the one with the most records: a truncated
 * parity stripe yields a short index, and a crashed write may leave
 * one parity stripe one record ahead (that record's stripe data is
 * already on disk, so the longest index is the right one). Ties break
 * to the first (lowest parity index). Returns 0 on success, -1 if no
 * parity stripe can be read. Sets *used to the stripe used. */
static int index_build(hyper_cfg_t *cfg, hyper_index_t *idx, int *used)
{
    hyper_index_t best;
    memset(&best, 0, sizeof(best));
    int best_pi = -1;
    for (int i = 0; i < cfg->nparities; i++) {
        hyper_index_t cur;
        memset(&cur, 0, sizeof(cur));
        if (index_scan(cfg->parities[i].path, &cur) != 0) {
            free(cur.recs);
            continue;
        }
        if (cur.n == 0 && cur.bad) {
            free(cur.recs);
            continue;
        }
        if (best_pi < 0 || cur.n > best.n) {
            free(best.recs);
            best = cur;
            best_pi = i;
        } else {
            free(cur.recs);
        }
    }
    if (best_pi < 0) {
        free(best.recs);
        return -1;
    }
    *idx = best;
    *used = best_pi;
    return 0;
}

/* Read one record's parity + BCH bytes from parity stripe `pi` at
 * rec_off. The caller provides buffers of parity_len and bch_len.
 * Either buffer may be NULL, in which case those bytes are skipped
 * (seeked past) rather than read. Returns 0 ok, -1 on error. */
static int rec_read_parity(hyper_cfg_t *cfg, int pi, const hyper_rec_t *r,
                           uint8_t *parity, uint8_t *bch)
{
    FILE *f = fopen(cfg->parities[pi].path, "rb");
    if (!f)
        return -1;
    uint64_t base = r->rec_off + HYPER_HDR_LEN + r->name_len;
    if (fseek(f, (long)base, SEEK_SET) != 0) {
        fclose(f);
        return -1;
    }
    if (r->parity_len > 0) {
        if (parity) {
            if (fread(parity, 1, r->parity_len, f) != r->parity_len) {
                fclose(f);
                return -1;
            }
        } else if (fseek(f, (long)r->parity_len, SEEK_CUR) != 0) {
            fclose(f);
            return -1;
        }
    }
    if (r->bch_len > 0) {
        if (bch) {
            if (fread(bch, 1, r->bch_len, f) != r->bch_len) {
                fclose(f);
                return -1;
            }
        } else if (fseek(f, (long)r->bch_len, SEEK_CUR) != 0) {
            fclose(f);
            return -1;
        }
    }
    fclose(f);
    return 0;
}

/* ------------------------------------------------------------------ */
/* Stripe engine: bit-plane split / merge                              */
/*                                                                     */
/* File bytes d[0..F) -> 8 stripe buffers s_j[0..ceil(F/8)), where    */
/* s_j[k] bit p = d[8k+p] bit j. The 8 bytes of one group are one     */
/* 8x8 bit-matrix transpose. Write uses the same transpose as read    */
/* (it is an involution). Work is done in 64 KiB bursts.               */
/* ------------------------------------------------------------------ */

/* Split file data[0..len) into 8 stripe buffers (each stripe_len
 * bytes, zero-padded). stripes[j] must hold stripe_len bytes. */
static void hyper_split(const uint8_t *data, size_t len,
                        uint8_t *stripes[HYPER_NSTRIPES])
{
    size_t slen = (len + 7) / 8;
    size_t groups = len / 8;
    size_t rem = len % 8;
    /* full groups of 8 bytes -> 8 stripe bytes each */
    for (size_t g = 0; g < groups; g++) {
        uint64_t x;
        memcpy(&x, data + 8 * g, 8);
        x = transpose8x8(x);
        for (int j = 0; j < HYPER_NSTRIPES; j++)
            stripes[j][g] = (uint8_t)((x >> (8 * j)) & 0xFF);
    }
    /* partial last group: pad with zero bytes, transpose, keep only
     * the stripe bytes that exist (slen may be groups or groups+1) */
    if (rem) {
        uint8_t tmp[8] = {0, 0, 0, 0, 0, 0, 0, 0};
        memcpy(tmp, data + 8 * groups, rem);
        uint64_t x;
        memcpy(&x, tmp, 8);
        x = transpose8x8(x);
        for (int j = 0; j < HYPER_NSTRIPES; j++)
            stripes[j][groups] = (uint8_t)((x >> (8 * j)) & 0xFF);
    }
    (void)slen;
}

/* Merge 8 stripe buffers back into file data[0..len). The inverse of
 * hyper_split (same transpose). */
static void hyper_merge(uint8_t *stripes[HYPER_NSTRIPES], size_t len,
                        uint8_t *data)
{
    size_t groups = len / 8;
    size_t rem = len % 8;
    for (size_t g = 0; g < groups; g++) {
        uint64_t x = 0;
        for (int j = 0; j < HYPER_NSTRIPES; j++)
            x |= (uint64_t)stripes[j][g] << (8 * j);
        x = transpose8x8(x);
        memcpy(data + 8 * g, &x, 8);
    }
    if (rem) {
        uint64_t x = 0;
        for (int j = 0; j < HYPER_NSTRIPES; j++)
            x |= (uint64_t)stripes[j][groups] << (8 * j);
        x = transpose8x8(x);
        uint8_t tmp[8];
        memcpy(tmp, &x, 8);
        memcpy(data + 8 * groups, tmp, rem);
    }
}

/* ------------------------------------------------------------------ */
/* Parity: P = XOR, Q = sum g^j * s_j, R = sum g^(2j) * s_j (GF(256)) */
/* All three are computed over the stripe bytes (length stripe_len).   */
/* ------------------------------------------------------------------ */

/* Compute parity row `idx` (0=P, 1=Q, 2=R) over the 8 stripe buffers
 * into out (stripe_len bytes). */
static void hyper_parity_row(int idx, uint8_t *stripes[HYPER_NSTRIPES],
                             size_t stripe_len, uint8_t *out)
{
    if (idx == 0) {
        for (size_t k = 0; k < stripe_len; k++) {
            uint8_t v = 0;
            for (int j = 0; j < HYPER_NSTRIPES; j++)
                v ^= stripes[j][k];
            out[k] = v;
        }
    } else if (idx == 1) {
        for (size_t k = 0; k < stripe_len; k++) {
            uint8_t v = 0;
            for (int j = 0; j < HYPER_NSTRIPES; j++)
                v ^= gf256_mul(gf256_pow2(j), stripes[j][k]);
            out[k] = v;
        }
    } else {
        for (size_t k = 0; k < stripe_len; k++) {
            uint8_t v = 0;
            for (int j = 0; j < HYPER_NSTRIPES; j++)
                v ^= gf256_mul(gf256_pow2(2 * j), stripes[j][k]);
            out[k] = v;
        }
    }
}

/* Coefficient of parity row idx for data stripe j. */
static uint8_t hyper_coeff(int idx, int j)
{
    if (idx == 0)
        return 1;
    if (idx == 1)
        return gf256_pow2(j);
    return gf256_pow2(2 * j);
}

/* ------------------------------------------------------------------ */
/* Recovery: solve for lost stripes over GF(256)                       */
/*                                                                     */
/* lost[0..k) are the lost stripe indices (sorted, k = 1..3).         */
/* par_bufs[0..2] are the P/Q/R parity buffers for this file          */
/* (stripe_len bytes each), indexed by parity row — NULL where that   */
/* row is unavailable. Recovery uses whichever rows survive (at      */
/* least k of them); e.g. Q alone rebuilds 1 lost stripe if P is     */
/* dead. stripes[j] is NULL for a lost stripe, else a stripe_len     */
/* buffer of that stripe's bytes. On success the lost stripe buffers */
/* are allocated and filled. Returns 0 ok, -1 if fewer than k parity */
/* rows survive or the system is singular (should not happen for the */
/* P/Q/R coefficient scheme).                                         */
/* ------------------------------------------------------------------ */

/* Invert a kxk matrix over GF(256) by Gauss-Jordan. A is row-major
 * k*k; inv gets the inverse. Returns 0 ok, -1 singular. */
static int gf256_invert(const uint8_t *A, int k, uint8_t *inv)
{
    /* augmented matrix [A | I], 2k columns */
    uint8_t m[3][6];
    for (int i = 0; i < k; i++) {
        for (int j = 0; j < k; j++)
            m[i][j] = A[i * k + j];
        for (int j = 0; j < k; j++)
            m[i][k + j] = (i == j) ? 1 : 0;
    }
    for (int col = 0; col < k; col++) {
        int piv = -1;
        for (int r = col; r < k; r++) {
            if (m[r][col] != 0) {
                piv = r;
                break;
            }
        }
        if (piv < 0)
            return -1;
        if (piv != col) {
            for (int j = 0; j < 2 * k; j++) {
                uint8_t t = m[col][j];
                m[col][j] = m[piv][j];
                m[piv][j] = t;
            }
        }
        uint8_t invp = gf256_inv(m[col][col]);
        for (int j = 0; j < 2 * k; j++)
            m[col][j] = gf256_mul(m[col][j], invp);
        for (int r = 0; r < k; r++) {
            if (r == col || m[r][col] == 0)
                continue;
            uint8_t f = m[r][col];
            for (int j = 0; j < 2 * k; j++)
                m[r][j] ^= gf256_mul(f, m[col][j]);
        }
    }
    for (int i = 0; i < k; i++)
        for (int j = 0; j < k; j++)
            inv[i * k + j] = m[i][k + j];
    return 0;
}

static int hyper_recover(const int *lost, int k, uint8_t *par_bufs[3],
                         uint8_t *stripes[HYPER_NSTRIPES],
                         size_t stripe_len)
{
    if (k < 1 || k > HYPER_MAXPAR)
        return -1;
    /* which parity rows survive; need at least k of them */
    int rows[3], nrows = 0;
    for (int i = 0; i < 3; i++)
        if (par_bufs[i])
            rows[nrows++] = i;
    if (nrows < k)
        return -1;
    /* coefficient matrix A[i][m] = coeff of parity rows[i] for stripe lost[m] */
    uint8_t A[9];
    for (int i = 0; i < k; i++)
        for (int m = 0; m < k; m++)
            A[i * k + m] = hyper_coeff(rows[i], lost[m]);
    uint8_t Ainv[9];
    if (gf256_invert(A, k, Ainv) != 0)
        return -1;
    /* Which stripes are lost (the caller leaves their buffers NULL;
     * surviving stripes must already be loaded). */
    int is_lost[HYPER_NSTRIPES] = {0};
    for (int m = 0; m < k; m++)
        is_lost[lost[m]] = 1;
    /* allocate the lost stripe buffers */
    for (int m = 0; m < k; m++)
        stripes[lost[m]] = xcalloc(stripe_len ? stripe_len : 1, 1);
    /* per byte position: syndromes, then x = Ainv * syn */
    for (size_t pos = 0; pos < stripe_len; pos++) {
        uint8_t syn[3] = {0, 0, 0};
        for (int i = 0; i < k; i++) {
            uint8_t v = par_bufs[rows[i]][pos];
            for (int j = 0; j < HYPER_NSTRIPES; j++) {
                if (is_lost[j])
                    continue;
                v ^= gf256_mul(hyper_coeff(rows[i], j), stripes[j][pos]);
            }
            syn[i] = v;
        }
        for (int m = 0; m < k; m++) {
            uint8_t v = 0;
            for (int i = 0; i < k; i++)
                v ^= gf256_mul(Ainv[m * k + i], syn[i]);
            stripes[lost[m]][pos] = v;
        }
    }
    return 0;
}

/* ------------------------------------------------------------------ */
/* Core file operations                                                */
/* ------------------------------------------------------------------ */

/* Write len bytes in 64 KiB bursts. Returns 0 ok, -1 on error. */
static int write_bursts(FILE *f, const uint8_t *buf, size_t len)
{
    size_t off = 0;
    while (off < len) {
        size_t n = len - off;
        if (n > HYPER_BURST)
            n = HYPER_BURST;
        if (fwrite(buf + off, 1, n, f) != n)
            return -1;
        off += n;
    }
    return 0;
}

/* Read a file's stripe data. stripes[j] gets a stripe_len buffer, or
 * NULL if stripe j is dead (missing file, too short, unreadable).
 * Returns the number of dead stripes; lost[] gets their indices. */
static int load_stripes(hyper_cfg_t *cfg, const hyper_rec_t *r,
                        uint8_t *stripes[HYPER_NSTRIPES], int *lost)
{
    int ndead = 0;
    for (int j = 0; j < HYPER_NSTRIPES; j++) {
        stripes[j] = NULL;
        FILE *f = fopen(cfg->stripes[j].path, "rb");
        if (!f) {
            lost[ndead++] = j;
            continue;
        }
        if (fseek(f, (long)r->stripe_off, SEEK_SET) != 0) {
            fclose(f);
            lost[ndead++] = j;
            continue;
        }
        uint8_t *buf = xmalloc(r->stripe_len ? r->stripe_len : 1);
        if (r->stripe_len > 0 &&
            fread(buf, 1, r->stripe_len, f) != r->stripe_len) {
            free(buf);
            fclose(f);
            lost[ndead++] = j;
            continue;
        }
        fclose(f);
        stripes[j] = buf;
    }
    return ndead;
}

/* Append one parity record to parity stripe pi. The record holds
 * parity bytes `parity` (parity_len bytes) and BCH bytes `bch`
 * (bch_len bytes) for file `name`. Returns 0 ok, -1 on error. */
static int append_record(hyper_cfg_t *cfg, int pi, const hyper_rec_t *tmpl,
                         const char *name, const uint8_t *parity,
                         const uint8_t *bch)
{
    FILE *f = fopen(cfg->parities[pi].path, "ab");
    if (!f)
        return -1;
    hyper_rec_t r = *tmpl;
    r.parity_idx = (uint8_t)pi;
    r.name_len = (uint16_t)strlen(name);
    uint8_t h[HYPER_HDR_LEN];
    hyper_rec_pack(&r, h);
    int rc = 0;
    if (fwrite(h, 1, HYPER_HDR_LEN, f) != HYPER_HDR_LEN)
        rc = -1;
    if (rc == 0 && fwrite(name, 1, r.name_len, f) != r.name_len)
        rc = -1;
    if (rc == 0 && r.parity_len > 0 &&
        write_bursts(f, parity, r.parity_len) != 0)
        rc = -1;
    if (rc == 0 && r.bch_len > 0 &&
        write_bursts(f, bch, r.bch_len) != 0)
        rc = -1;
    if (fclose(f) != 0)
        rc = -1;
    return rc;
}

/* Load a file by name from the volume.
 * On success returns a malloc'd buffer of the file data (caller frees),
 * sets *len, *corrected (BCH bits fixed, 0 if clean), *rebuilt (dead
 * stripes rebuilt via parity, 0 if none). On failure returns NULL and
 * writes a message into errmsg. */
static uint8_t *hyper_load_file(hyper_cfg_t *cfg, const char *name,
                                size_t *len, int *corrected, int *rebuilt,
                                char *errmsg, size_t errmsg_len)
{
    *corrected = 0;
    *rebuilt = 0;
    /* indexes, one per parity stripe (a stripe that cannot be read
     * simply has an empty index) */
    hyper_index_t pidx[HYPER_MAXPAR];
    for (int i = 0; i < HYPER_MAXPAR; i++)
        memset(&pidx[i], 0, sizeof(pidx[i]));
    for (int i = 0; i < cfg->nparities; i++)
        index_scan(cfg->parities[i].path, &pidx[i]);
    /* find the record (first parity stripe that has it) */
    const hyper_rec_t *rec = NULL;
    int rec_pi = -1;
    for (int i = 0; i < cfg->nparities; i++) {
        rec = index_find(&pidx[i], name);
        if (rec) {
            rec_pi = i;
            break;
        }
    }
    if (!rec) {
        snprintf(errmsg, errmsg_len, "no such file '%s' in the volume", name);
        goto fail;
    }
    /* the record's poly must be the config's poly */
    if (rec->poly_id != cfg->poly->id || rec->t != (uint8_t)cfg->t) {
        snprintf(errmsg, errmsg_len,
                 "file '%s' uses poly 0x%04x (t=%d), config uses 0x%04x (t=%d)",
                 name, rec->poly_id, rec->t, cfg->poly->id, cfg->t);
        goto fail;
    }
    /* BCH bytes: read from the parity stripe that had the record
     * (parity bytes skipped here; they are read only if a rebuild
     * is needed) */
    uint8_t *bch = NULL;
    if (rec->bch_len > 0) {
        bch = xmalloc(rec->bch_len);
        if (rec_read_parity(cfg, rec_pi, rec, NULL, bch) != 0) {
            snprintf(errmsg, errmsg_len, "cannot read parity record for '%s'",
                     name);
            free(bch);
            goto fail;
        }
    }
    /* load the stripe data */
    uint8_t *stripes[HYPER_NSTRIPES];
    int lost[HYPER_NSTRIPES];
    int ndead = load_stripes(cfg, rec, stripes, lost);
    if (ndead > cfg->nparities) {
        snprintf(errmsg, errmsg_len,
                 "%d data stripes dead for '%s', only %d parity stripes "
                 "can rebuild that many",
                 ndead, name, cfg->nparities);
        goto fail_stripes;
    }
    if (ndead > 0) {
        /* parity bytes for each row, from that row's parity stripe */
        uint8_t *par_bufs[3] = {NULL, NULL, NULL};
        for (int pi = 0; pi < cfg->nparities; pi++) {
            const hyper_rec_t *pr = index_find(&pidx[pi], name);
            if (!pr)
                continue;
            uint8_t *pb = xmalloc(rec->parity_len ? rec->parity_len : 1);
            uint8_t *bb = xmalloc(rec->bch_len ? rec->bch_len : 1);
            if (rec_read_parity(cfg, pi, pr, pb, bb) == 0)
                par_bufs[pi] = pb;
            else
                free(pb);
            free(bb);
        }
        if (hyper_recover(lost, ndead, par_bufs, stripes, rec->stripe_len) != 0) {
            snprintf(errmsg, errmsg_len,
                     "cannot rebuild %d dead stripe(s) for '%s' "
                     "(not enough surviving parity)", ndead, name);
            for (int i = 0; i < 3; i++)
                free(par_bufs[i]);
            goto fail_stripes;
        }
        for (int i = 0; i < 3; i++)
            free(par_bufs[i]);
        *rebuilt = ndead;
    }
    /* reassemble the file */
    uint8_t *data = xmalloc(rec->orig_len ? rec->orig_len : 1);
    hyper_merge(stripes, rec->orig_len, data);
    for (int j = 0; j < HYPER_NSTRIPES; j++)
        free(stripes[j]);
    /* BCH correct (syndrome is cheap when clean; full correction
     * only runs if the syndrome is non-zero) */
    if (rec->orig_len > 0) {
        int corr = 0;
        if (hyper_bch_correct(data, rec->orig_len, bch, cfg->poly, &corr) != 0) {
            snprintf(errmsg, errmsg_len,
                     "file '%s': BCH uncorrectable (too many bit errors)",
                     name);
            free(data);
            free(bch);
            goto fail;
        }
        *corrected = corr;
    }
    free(bch);
    /* SHA-256 verify: the final judge */
    uint8_t digest[32];
    lzply_sha256(data, rec->orig_len, digest);
    if (memcmp(digest, rec->sha256, 32) != 0) {
        snprintf(errmsg, errmsg_len,
                 "file '%s': SHA-256 mismatch (data corrupt)", name);
        free(data);
        goto fail;
    }
    *len = rec->orig_len;
    for (int i = 0; i < HYPER_MAXPAR; i++)
        free(pidx[i].recs);
    return data;

fail_stripes:
    for (int j = 0; j < HYPER_NSTRIPES; j++)
        free(stripes[j]);
    free(bch);
fail:
    for (int i = 0; i < HYPER_MAXPAR; i++)
        free(pidx[i].recs);
    return NULL;
}

/* ------------------------------------------------------------------ */
/* Commands                                                            */
/* ------------------------------------------------------------------ */

/* Load the parity buffers for a file, one per parity row.
 * pidx[] are the per-parity-stripe indexes (built by the caller).
 * par_bufs[pi] gets a malloc'd parity_len buffer for each parity
 * stripe that has the file's record, else NULL. Returns the number
 * of parity rows loaded. */
static int load_file_parity(hyper_cfg_t *cfg, hyper_index_t *pidx,
                            const char *name, const hyper_rec_t *rec,
                            uint8_t *par_bufs[3])
{
    int n = 0;
    for (int pi = 0; pi < 3; pi++)
        par_bufs[pi] = NULL;
    for (int pi = 0; pi < cfg->nparities; pi++) {
        const hyper_rec_t *pr = index_find(&pidx[pi], name);
        if (!pr)
            continue;
        uint8_t *pb = xmalloc(rec->parity_len ? rec->parity_len : 1);
        uint8_t *bb = xmalloc(rec->bch_len ? rec->bch_len : 1);
        if (rec_read_parity(cfg, pi, pr, pb, bb) == 0) {
            par_bufs[pi] = pb;
            n++;
        } else {
            free(pb);
        }
        free(bb);
    }
    return n;
}

static void free_par_bufs(uint8_t *par_bufs[3])
{
    for (int i = 0; i < 3; i++) {
        free(par_bufs[i]);
        par_bufs[i] = NULL;
    }
}

/* --- -init ------------------------------------------------------- */

static int cmd_init(hyper_cfg_t *cfg, int force)
{
    /* 1. parent dirs exist, are directories, writable for rw files;
     *    ro files must already exist and be readable. */
    for (int j = 0; j < HYPER_NSTRIPES; j++) {
        hyper_stripe_t *st = &cfg->stripes[j];
        char *dir = parent_dir(st->path);
        struct stat dst;
        if (stat(dir, &dst) != 0 || !S_ISDIR(dst.st_mode)) {
            fprintf(stderr, "%s: stripe %s: parent directory %s missing\n",
                    prog, st->label, dir);
            free(dir);
            return EXIT_IO;
        }
        if (st->rw) {
            if (access(dir, W_OK) != 0) {
                fprintf(stderr, "%s: stripe %s: directory %s not writable\n",
                        prog, st->label, dir);
                free(dir);
                return EXIT_IO;
            }
        } else {
            if (access(st->path, R_OK) != 0) {
                fprintf(stderr,
                        "%s: stripe %s: read-only file %s does not exist "
                        "(cannot create a read-only stripe)\n",
                        prog, st->label, st->path);
                free(dir);
                return EXIT_IO;
            }
        }
        free(dir);
    }
    for (int i = 0; i < cfg->nparities; i++) {
        hyper_parity_t *pa = &cfg->parities[i];
        char *dir = parent_dir(pa->path);
        struct stat dst;
        if (stat(dir, &dst) != 0 || !S_ISDIR(dst.st_mode)) {
            fprintf(stderr, "%s: parity %s: parent directory %s missing\n",
                    prog, pa->label, dir);
            free(dir);
            return EXIT_IO;
        }
        if (pa->rw) {
            if (access(dir, W_OK) != 0) {
                fprintf(stderr, "%s: parity %s: directory %s not writable\n",
                        prog, pa->label, dir);
                free(dir);
                return EXIT_IO;
            }
        } else {
            if (access(pa->path, R_OK) != 0) {
                fprintf(stderr,
                        "%s: parity %s: read-only file %s does not exist\n",
                        prog, pa->label, pa->path);
                free(dir);
                return EXIT_IO;
            }
        }
        free(dir);
    }
    /* 2. free-space check, grouped by filesystem (st_dev of the
     *    parent dir). Only rw stripe sizes are reserved; parity
     *    files grow with the file count and have no configured size. */
    {
        struct { dev_t dev; uint64_t need; char *dir; } fs[HYPER_NSTRIPES];
        int nfs = 0;
        for (int j = 0; j < HYPER_NSTRIPES; j++) {
            hyper_stripe_t *st = &cfg->stripes[j];
            if (!st->rw)
                continue;
            char *dir = parent_dir(st->path);
            struct stat dst;
            stat(dir, &dst);
            int k;
            for (k = 0; k < nfs; k++) {
                if (fs[k].dev == dst.st_dev)
                    break;
            }
            if (k == nfs) {
                fs[nfs].dev = dst.st_dev;
                fs[nfs].need = 0;
                fs[nfs].dir = dir;
                nfs++;
            } else {
                free(dir);
            }
            fs[k].need += st->size;
        }
        for (int k = 0; k < nfs; k++) {
            struct statvfs vfs;
            if (statvfs(fs[k].dir, &vfs) != 0) {
                fprintf(stderr, "%s: cannot stat filesystem %s: %s\n",
                        prog, fs[k].dir, strerror(errno));
                for (int m = 0; m < nfs; m++)
                    free(fs[m].dir);
                return EXIT_IO;
            }
            uint64_t freeb = (uint64_t)vfs.f_bavail * (uint64_t)vfs.f_frsize;
            if (freeb < fs[k].need) {
                fprintf(stderr,
                        "%s: filesystem %s has %llu bytes free, needs %llu "
                        "for the configured stripe sizes\n",
                        prog, fs[k].dir,
                        (unsigned long long)freeb,
                        (unsigned long long)fs[k].need);
                for (int m = 0; m < nfs; m++)
                    free(fs[m].dir);
                return EXIT_IO;
            }
            free(fs[k].dir);
        }
    }
    /* 3. create (or verify) the files */
    for (int j = 0; j < HYPER_NSTRIPES; j++) {
        hyper_stripe_t *st = &cfg->stripes[j];
        if (!st->rw) {
            printf("stripe %s: %s (read-only, verified)\n", st->label, st->path);
            continue;
        }
        int64_t sz = file_size(st->path);
        if (sz >= 0 && !force) {
            fprintf(stderr,
                    "%s: stripe %s: %s already exists (%lld bytes); "
                    "refusing to overwrite (use --force)\n",
                    prog, st->label, st->path, (long long)sz);
            return EXIT_IO;
        }
        FILE *f = fopen(st->path, "wb");
        if (!f) {
            fprintf(stderr, "%s: cannot create %s: %s\n", prog, st->path,
                    strerror(errno));
            return EXIT_IO;
        }
        fclose(f);
        printf("stripe %s: %s (%s, capacity %llu bytes)\n", st->label, st->path,
               sz >= 0 ? "replaced" : "created",
               (unsigned long long)st->size);
    }
    for (int i = 0; i < cfg->nparities; i++) {
        hyper_parity_t *pa = &cfg->parities[i];
        if (!pa->rw) {
            printf("parity %s: %s (read-only, verified)\n", pa->label, pa->path);
            continue;
        }
        int64_t sz = file_size(pa->path);
        if (sz >= 0 && !force) {
            fprintf(stderr,
                    "%s: parity %s: %s already exists (%lld bytes); "
                    "refusing to overwrite (use --force)\n",
                    prog, pa->label, pa->path, (long long)sz);
            return EXIT_IO;
        }
        FILE *f = fopen(pa->path, "wb");
        if (!f) {
            fprintf(stderr, "%s: cannot create %s: %s\n", prog, pa->path,
                    strerror(errno));
            return EXIT_IO;
        }
        fclose(f);
        printf("parity %s: %s (%s, poly 0x%04x t=%d)\n", pa->label, pa->path,
               sz >= 0 ? "replaced" : "created", pa->poly_id, pa->poly->t);
    }
    printf("volume initialized: 8 data stripes, %d parity stripe(s), "
           "poly 0x%04x t=%d\n",
           cfg->nparities, cfg->poly->id, cfg->t);
    return EXIT_OK;
}

/* --- write -------------------------------------------------------- */

static int cmd_write(hyper_cfg_t *cfg, const char *srcpath, const char *name)
{
    /* name defaults to the basename of the source file */
    char defname[HYPER_MAXNAME + 1];
    if (!name) {
        const char *base = strrchr(srcpath, '/');
        base = base ? base + 1 : srcpath;
        if (!*base || strlen(base) > HYPER_MAXNAME) {
            fprintf(stderr, "%s: bad file name '%s'\n", prog, base);
            return EXIT_USAGE;
        }
        snprintf(defname, sizeof(defname), "%s", base);
        name = defname;
    }
    if (!*name || strlen(name) > HYPER_MAXNAME || strchr(name, '/') ||
        strchr(name, ':')) {
        fprintf(stderr, "%s: bad file name '%s' (1..%d chars, no '/' or ':')\n",
                prog, name, HYPER_MAXNAME);
        return EXIT_USAGE;
    }
    /* all stripes and parities must be writable for a write */
    for (int j = 0; j < HYPER_NSTRIPES; j++) {
        if (!cfg->stripes[j].rw) {
            fprintf(stderr, "%s: stripe %s is read-only; cannot write\n",
                    prog, cfg->stripes[j].label);
            return EXIT_IO;
        }
    }
    for (int i = 0; i < cfg->nparities; i++) {
        if (!cfg->parities[i].rw) {
            fprintf(stderr, "%s: parity %s is read-only; cannot write\n",
                    prog, cfg->parities[i].label);
            return EXIT_IO;
        }
    }
    /* refuse to overwrite an existing file (no overwrite in v1) */
    {
        hyper_index_t idx;
        memset(&idx, 0, sizeof(idx));
        int used = -1;
        if (index_build(cfg, &idx, &used) == 0) {
            if (index_find(&idx, name)) {
                fprintf(stderr, "%s: file '%s' already exists in the volume "
                                "(no overwrite in v1)\n", prog, name);
                free(idx.recs);
                return EXIT_IO;
            }
            free(idx.recs);
        }
    }
    size_t len;
    uint8_t *data = read_whole_file(srcpath, &len);
    uint64_t slen = hyper_stripe_len(len);
    /* stripe files must all exist and be the same size; that size is
     * where this file's data goes */
    int64_t base_off = -1;
    for (int j = 0; j < HYPER_NSTRIPES; j++) {
        int64_t sz = file_size(cfg->stripes[j].path);
        if (sz < 0) {
            fprintf(stderr, "%s: stripe %s: %s missing (run -init or -rebuild)\n",
                    prog, cfg->stripes[j].label, cfg->stripes[j].path);
            free(data);
            return EXIT_IO;
        }
        if (base_off < 0)
            base_off = sz;
        else if (sz != base_off) {
            fprintf(stderr,
                    "%s: stripe files out of sync (%s is %lld bytes, %s is %lld); "
                    "run -rebuild\n",
                    prog, cfg->stripes[0].label, (long long)base_off,
                    cfg->stripes[j].label, (long long)sz);
            free(data);
            return EXIT_IO;
        }
        if ((uint64_t)base_off + slen > cfg->stripes[j].size) {
            fprintf(stderr,
                    "%s: stripe %s would exceed capacity (%llu + %llu > %llu)\n",
                    prog, cfg->stripes[j].label,
                    (unsigned long long)base_off,
                    (unsigned long long)slen,
                    (unsigned long long)cfg->stripes[j].size);
            free(data);
            return EXIT_IO;
        }
    }
    /* SHA-256 of the original */
    uint8_t digest[32];
    lzply_sha256(data, len, digest);
    /* BCH parity */
    size_t bch_len = hyper_bch_parity_len(len, cfg->poly);
    uint8_t *bch = xmalloc(bch_len ? bch_len : 1);
    if (bch_len > 0)
        hyper_bch_parity(data, len, cfg->poly, bch);
    /* bit-plane split */
    uint8_t *stripes[HYPER_NSTRIPES];
    for (int j = 0; j < HYPER_NSTRIPES; j++)
        stripes[j] = xmalloc(slen ? slen : 1);
    hyper_split(data, len, stripes);
    /* parity rows */
    uint8_t *par[HYPER_MAXPAR];
    for (int i = 0; i < cfg->nparities; i++) {
        par[i] = xmalloc(slen ? slen : 1);
        hyper_parity_row(i, stripes, slen, par[i]);
    }
    /* append stripe data (64 KiB bursts) */
    for (int j = 0; j < HYPER_NSTRIPES; j++) {
        FILE *f = fopen(cfg->stripes[j].path, "ab");
        if (!f) {
            fprintf(stderr, "%s: cannot append to %s: %s\n", prog,
                    cfg->stripes[j].path, strerror(errno));
            goto fail_write;
        }
        if (slen > 0 && write_bursts(f, stripes[j], slen) != 0) {
            fprintf(stderr, "%s: cannot write %s: %s\n", prog,
                    cfg->stripes[j].path, strerror(errno));
            fclose(f);
            goto fail_write;
        }
        if (fclose(f) != 0) {
            fprintf(stderr, "%s: cannot close %s: %s\n", prog,
                    cfg->stripes[j].path, strerror(errno));
            goto fail_write;
        }
    }
    /* append a parity record to each parity stripe */
    {
        hyper_rec_t tmpl;
        memset(&tmpl, 0, sizeof(tmpl));
        tmpl.name_len = (uint16_t)strlen(name);
        tmpl.poly_id = cfg->poly->id;
        tmpl.t = (uint8_t)cfg->t;
        tmpl.npar = (uint8_t)cfg->nparities;
        tmpl.orig_len = len;
        tmpl.stripe_off = (uint64_t)base_off;
        tmpl.stripe_len = slen;
        tmpl.parity_len = slen;
        tmpl.bch_len = bch_len;
        memcpy(tmpl.sha256, digest, 32);
        for (int i = 0; i < cfg->nparities; i++) {
            if (append_record(cfg, i, &tmpl, name, par[i], bch) != 0) {
                fprintf(stderr, "%s: cannot append parity record to %s: %s\n",
                        prog, cfg->parities[i].path, strerror(errno));
                goto fail_write;
            }
        }
    }
    {
        char hex[65];
        hex32(digest, hex);
        printf("wrote '%s': %zu bytes, stripe_off %lld, stripe_len %llu, "
               "bch %zu bytes, sha256 %s\n",
               name, len, (long long)base_off,
               (unsigned long long)slen, bch_len, hex);
    }
    for (int j = 0; j < HYPER_NSTRIPES; j++)
        free(stripes[j]);
    for (int i = 0; i < cfg->nparities; i++)
        free(par[i]);
    free(bch);
    free(data);
    return EXIT_OK;

fail_write:
    for (int j = 0; j < HYPER_NSTRIPES; j++)
        free(stripes[j]);
    for (int i = 0; i < cfg->nparities; i++)
        free(par[i]);
    free(bch);
    free(data);
    return EXIT_IO;
}

/* --- read --------------------------------------------------------- */

static int cmd_read(hyper_cfg_t *cfg, const char *name, const char *outpath)
{
    char errmsg[256];
    size_t len;
    int corrected, rebuilt;
    uint8_t *data = hyper_load_file(cfg, name, &len, &corrected, &rebuilt,
                                    errmsg, sizeof(errmsg));
    if (!data) {
        fprintf(stderr, "%s: %s\n", prog, errmsg);
        return EXIT_CORRUPT;
    }
    write_whole_file(outpath, data, len); /* dies on error */
    printf("read '%s': %zu bytes -> %s", name, len, outpath);
    if (rebuilt > 0)
        printf(" (rebuilt %d dead stripe%s)", rebuilt, rebuilt == 1 ? "" : "s");
    if (corrected > 0)
        printf(" (BCH corrected %d bit%s)", corrected, corrected == 1 ? "" : "s");
    printf("\n");
    free(data);
    return EXIT_OK;
}

/* --- list --------------------------------------------------------- */

static int cmd_list(hyper_cfg_t *cfg)
{
    hyper_index_t idx;
    memset(&idx, 0, sizeof(idx));
    int used;
    if (index_build(cfg, &idx, &used) != 0) {
        fprintf(stderr, "%s: no readable parity stripe; cannot list "
                        "(index lives in the parity stripes)\n", prog);
        return EXIT_CORRUPT;
    }
    printf("index from parity stripe %d (%s): %zu file(s)\n", used,
           cfg->parities[used].label, idx.n);
    if (idx.bad)
        fprintf(stderr, "%s: warning: index ends in a bad record\n", prog);
    uint64_t total = 0;
    for (size_t i = 0; i < idx.n; i++) {
        hyper_rec_t *r = &idx.recs[i];
        total += r->orig_len;
        printf("  %-24s %10llu bytes  poly 0x%04x t=%-2d  stripe_off %lld  "
               "stripe_len %llu\n",
               r->name, (unsigned long long)r->orig_len, r->poly_id, r->t,
               (long long)r->stripe_off, (unsigned long long)r->stripe_len);
    }
    printf("%zu file(s), %llu bytes total\n", idx.n,
           (unsigned long long)total);
    free(idx.recs);
    return EXIT_OK;
}

/* --- check -------------------------------------------------------- */

static int cmd_check(hyper_cfg_t *cfg, const char *name)
{
    char errmsg[256];
    size_t len;
    int corrected, rebuilt;
    uint8_t *data = hyper_load_file(cfg, name, &len, &corrected, &rebuilt,
                                    errmsg, sizeof(errmsg));
    if (!data) {
        fprintf(stderr, "%s: check '%s' FAILED: %s\n", prog, name, errmsg);
        return EXIT_CORRUPT;
    }
    printf("check '%s': OK (%zu bytes, sha256 verified)", name, len);
    if (rebuilt > 0)
        printf(", rebuilt %d dead stripe%s", rebuilt, rebuilt == 1 ? "" : "s");
    if (corrected > 0)
        printf(", BCH corrected %d bit%s", corrected, corrected == 1 ? "" : "s");
    printf("\n");
    free(data);
    return EXIT_OK;
}

/* --- -rebuild ----------------------------------------------------- */

/* Expected total size of the data stripes for this index. */
static uint64_t index_total_stripe_len(const hyper_index_t *idx)
{
    uint64_t total = 0;
    for (size_t i = 0; i < idx->n; i++)
        total += idx->recs[i].stripe_len;
    return total;
}

/* Expected size of a parity stripe holding exactly this index. */
static uint64_t index_parity_size(const hyper_index_t *idx)
{
    uint64_t total = 0;
    for (size_t i = 0; i < idx->n; i++) {
        hyper_rec_t *r = &idx->recs[i];
        total += HYPER_HDR_LEN + r->name_len + r->parity_len + r->bch_len;
    }
    return total;
}

static int cmd_rebuild(hyper_cfg_t *cfg)
{
    hyper_index_t idx;
    memset(&idx, 0, sizeof(idx));
    int used;
    if (index_build(cfg, &idx, &used) != 0) {
        fprintf(stderr,
                "%s: no readable parity stripe; cannot rebuild without the "
                "index (if every parity stripe is dead but the data stripes "
                "are intact, the files are still readable via read, just "
                "unverifiable and unrecoverable)\n", prog);
        return EXIT_CORRUPT;
    }
    if (idx.bad)
        fprintf(stderr, "%s: warning: index ends in a bad record\n", prog);
    uint64_t exp_stripe = index_total_stripe_len(&idx);
    uint64_t exp_parity = index_parity_size(&idx);
    /* which data stripes are damaged (missing or wrong size) */
    int damaged_data[HYPER_NSTRIPES];
    int lost[HYPER_NSTRIPES];
    int k = 0;
    for (int j = 0; j < HYPER_NSTRIPES; j++) {
        int64_t sz = file_size(cfg->stripes[j].path);
        damaged_data[j] = (sz < 0 || (uint64_t)sz != exp_stripe);
        if (damaged_data[j])
            lost[k++] = j;
    }
    /* which parity stripes are damaged */
    int damaged_par[HYPER_MAXPAR];
    int npar_ok = 0;
    for (int i = 0; i < cfg->nparities; i++) {
        int64_t sz = file_size(cfg->parities[i].path);
        damaged_par[i] = (sz < 0 || (uint64_t)sz != exp_parity);
        if (!damaged_par[i])
            npar_ok++;
    }
    if (k == 0) {
        int any_par = 0;
        for (int i = 0; i < cfg->nparities; i++)
            if (damaged_par[i])
                any_par++;
        if (!any_par) {
            printf("rebuild: nothing to rebuild (all stripes intact)\n");
            free(idx.recs);
            return EXIT_OK;
        }
    }
    /* data-stripe rebuild needs at least k surviving parity rows */
    if (k > 0 && k > npar_ok) {
        fprintf(stderr,
                "%s: rebuild FAILED: %d data stripe(s) lost (%s) but only %d "
                "parity stripe(s) survive; %d parity row(s) can rebuild at most "
                "%d lost stripe(s)\n",
                prog, k, k == 1 ? "" : "", npar_ok, npar_ok, npar_ok);
        fprintf(stderr, "%s: damaged stripes are left as they are; "
                        "no data was silently returned\n", prog);
        for (int j = 0; j < HYPER_NSTRIPES; j++)
            if (damaged_data[j])
                fprintf(stderr, "  lost data stripe: %s (%s)\n",
                        cfg->stripes[j].label, cfg->stripes[j].path);
        free(idx.recs);
        return EXIT_CORRUPT;
    }
    /* phase A: rebuild the damaged data stripes. Rebuilt data goes
     * to temp files first and is renamed into place only on success,
     * so a failed rebuild leaves the damaged files untouched. */
    FILE *dout[HYPER_NSTRIPES];
    char *tmpath[HYPER_NSTRIPES];
    for (int j = 0; j < HYPER_NSTRIPES; j++) {
        dout[j] = NULL;
        tmpath[j] = NULL;
    }
    if (k > 0) {
        for (int m = 0; m < k; m++) {
            int j = lost[m];
            if (!cfg->stripes[j].rw) {
                fprintf(stderr, "%s: rebuild FAILED: data stripe %s is "
                                "read-only and damaged; cannot rebuild it\n",
                        prog, cfg->stripes[j].label);
                for (int mm = 0; mm < m; mm++) {
                    fclose(dout[lost[mm]]);
                    remove(tmpath[lost[mm]]);
                    free(tmpath[lost[mm]]);
                }
                free(idx.recs);
                return EXIT_CORRUPT;
            }
            tmpath[j] = xmalloc(strlen(cfg->stripes[j].path) + 16);
            sprintf(tmpath[j], "%s.rebuild-tmp", cfg->stripes[j].path);
            dout[j] = fopen(tmpath[j], "wb");
            if (!dout[j]) {
                fprintf(stderr, "%s: cannot create %s: %s\n", prog,
                        tmpath[j], strerror(errno));
                for (int mm = 0; mm < m; mm++) {
                    fclose(dout[lost[mm]]);
                    remove(tmpath[lost[mm]]);
                    free(tmpath[lost[mm]]);
                }
                free(tmpath[j]);
                free(idx.recs);
                return EXIT_IO;
            }
        }
        /* per-file recovery: load the surviving stripes + parity
         * rows, recover the dead ones, and append each damaged
         * stripe's data (read or recovered) to its rebuilt file.
         * Every damaged stripe gets exactly stripe_len bytes per
         * file, in index order, so the rebuilt files stay aligned
         * even when a damaged stripe happens to read fine for a
         * file near the front of a truncated stripe file. */
        hyper_index_t pidx[HYPER_MAXPAR];
        memset(pidx, 0, sizeof(pidx));
        for (int i = 0; i < cfg->nparities; i++)
            index_scan(cfg->parities[i].path, &pidx[i]);
        int ok = 1;
        for (int fi = 0; fi < (int)idx.n && ok; fi++) {
            hyper_rec_t *rec = &idx.recs[fi];
            uint8_t *stripes[HYPER_NSTRIPES];
            int dlost[HYPER_NSTRIPES];
            int ndead = load_stripes(cfg, rec, stripes, dlost);
            /* Force every damaged stripe dead for this file, even if
             * the old file still has bytes at this offset: a stripe
             * whose file is missing or the wrong size is rebuilt
             * purely from parity, never from its old (possibly
             * corrupt) bytes. */
            for (int m = 0; m < k; m++) {
                int j = lost[m];
                int already = 0;
                for (int d = 0; d < ndead; d++)
                    if (dlost[d] == j) {
                        already = 1;
                        break;
                    }
                if (!already) {
                    free(stripes[j]);
                    stripes[j] = NULL;
                    dlost[ndead++] = j;
                }
            }
            if (ndead > 0) {
                uint8_t *par_bufs[3];
                load_file_parity(cfg, pidx, rec->name, rec, par_bufs);
                if (hyper_recover(dlost, ndead, par_bufs, stripes,
                                  (size_t)rec->stripe_len) != 0) {
                    fprintf(stderr, "%s: rebuild FAILED: file '%s' could not "
                                    "be recovered (%d dead stripe(s))\n",
                            prog, rec->name, ndead);
                    ok = 0;
                }
                free_par_bufs(par_bufs);
            }
            if (ok) {
                for (int m = 0; m < k; m++) {
                    int j = lost[m];
                    if (rec->stripe_len > 0 &&
                        fwrite(stripes[j], 1, rec->stripe_len, dout[j]) !=
                            rec->stripe_len) {
                        fprintf(stderr, "%s: cannot write %s: %s\n", prog,
                                cfg->stripes[j].path, strerror(errno));
                        ok = 0;
                        break;
                    }
                }
            }
            for (int j = 0; j < HYPER_NSTRIPES; j++)
                free(stripes[j]);
        }
        for (int i = 0; i < cfg->nparities; i++)
            free(pidx[i].recs);
        for (int m = 0; m < k; m++)
            fclose(dout[lost[m]]);
        if (!ok) {
            for (int m = 0; m < k; m++) {
                remove(tmpath[lost[m]]);
                free(tmpath[lost[m]]);
            }
            free(idx.recs);
            return EXIT_CORRUPT;
        }
        for (int m = 0; m < k; m++) {
            int j = lost[m];
            if (rename(tmpath[j], cfg->stripes[j].path) != 0) {
                fprintf(stderr, "%s: cannot install rebuilt %s: %s\n", prog,
                        cfg->stripes[j].path, strerror(errno));
                for (int mm = m; mm < k; mm++) {
                    remove(tmpath[lost[mm]]);
                    free(tmpath[lost[mm]]);
                }
                free(idx.recs);
                return EXIT_IO;
            }
            free(tmpath[j]);
        }
        for (int m = 0; m < k; m++)
            printf("rebuilt data stripe %s (%s)\n", cfg->stripes[lost[m]].label,
                   cfg->stripes[lost[m]].path);
    }
    /* phase B: rebuild the damaged parity stripes from the (now
     * complete) data stripes. Each damaged parity file is truncated
     * first, then rebuilt record by record with append_record. */
    {
        hyper_index_t pidx[HYPER_MAXPAR];
        memset(pidx, 0, sizeof(pidx));
        for (int i = 0; i < cfg->nparities; i++)
            index_scan(cfg->parities[i].path, &pidx[i]);
        int src_pi = used; /* a surviving parity stripe to copy BCH from */
        for (int i = 0; i < cfg->nparities; i++) {
            if (!damaged_par[i])
                continue;
            if (!cfg->parities[i].rw) {
                fprintf(stderr, "%s: parity stripe %s is read-only and "
                                "damaged; cannot rebuild it\n",
                        prog, cfg->parities[i].label);
                for (int m = 0; m < cfg->nparities; m++)
                    free(pidx[m].recs);
                free(idx.recs);
                return EXIT_CORRUPT;
            }
            FILE *pf = fopen(cfg->parities[i].path, "wb");
            if (!pf) {
                fprintf(stderr, "%s: cannot rewrite %s: %s\n", prog,
                        cfg->parities[i].path, strerror(errno));
                for (int m = 0; m < cfg->nparities; m++)
                    free(pidx[m].recs);
                free(idx.recs);
                return EXIT_IO;
            }
            fclose(pf); /* truncate; append_record reopens to append */
            int ok = 1;
            for (int fi = 0; fi < (int)idx.n && ok; fi++) {
                hyper_rec_t *rec = &idx.recs[fi];
                uint8_t *stripes[HYPER_NSTRIPES];
                int dlost[HYPER_NSTRIPES];
                int ndead = load_stripes(cfg, rec, stripes, dlost);
                if (ndead > 0) {
                    fprintf(stderr, "%s: rebuild FAILED: file '%s' still has "
                                    "%d dead stripe(s); cannot recompute parity\n",
                            prog, rec->name, ndead);
                    ok = 0;
                } else {
                    uint8_t *prow = xmalloc(rec->parity_len ? rec->parity_len : 1);
                    hyper_parity_row(i, stripes, (size_t)rec->stripe_len, prow);
                    /* BCH bytes are identical on every parity stripe;
                     * copy them from the surviving index stripe */
                    const hyper_rec_t *sr = index_find(&pidx[src_pi], rec->name);
                    uint8_t *bch = xmalloc(rec->bch_len ? rec->bch_len : 1);
                    if (!sr || rec_read_parity(cfg, src_pi, sr, NULL, bch) != 0) {
                        fprintf(stderr, "%s: rebuild FAILED: cannot read BCH "
                                        "for '%s' from parity stripe %d\n",
                                prog, rec->name, src_pi);
                        free(prow);
                        free(bch);
                        ok = 0;
                    } else if (append_record(cfg, i, rec, rec->name, prow,
                                             bch) != 0) {
                        fprintf(stderr, "%s: cannot write parity record to %s: %s\n",
                                prog, cfg->parities[i].path, strerror(errno));
                        free(prow);
                        free(bch);
                        ok = 0;
                    } else {
                        free(prow);
                        free(bch);
                    }
                }
                for (int j = 0; j < HYPER_NSTRIPES; j++)
                    free(stripes[j]);
            }
            if (!ok) {
                for (int m = 0; m < cfg->nparities; m++)
                    free(pidx[m].recs);
                free(idx.recs);
                return EXIT_CORRUPT;
            }
            printf("rebuilt parity stripe %s (%s)\n", cfg->parities[i].label,
                   cfg->parities[i].path);
        }
        for (int m = 0; m < cfg->nparities; m++)
            free(pidx[m].recs);
    }
    free(idx.recs);
    printf("rebuild complete\n");
    return EXIT_OK;
}

/* --- usage / main ------------------------------------------------- */

static void usage(FILE *f)
{
    fprintf(f,
            "usage: %s -c config.txt <command> [args]\n"
            "\n"
            "commands:\n"
            "  -init [--force]     initialize the volume (create stripe and\n"
            "                      parity files; --force replaces existing files)\n"
            "  write <file> [name] write a file into the volume (name defaults\n"
            "                      to the file's basename)\n"
            "  read <name> <out>   read a file back out (rebuilds a dead stripe\n"
            "                      via parity if needed; verifies sha256)\n"
            "  list                list the files in the volume\n"
            "  check <name>        verify a file (stripe parity + BCH + sha256)\n"
            "  -rebuild            rebuild lost/corrupt stripes from parity\n"
            "\n"
            "config lines:\n"
            "  stripe:<label>:<file>:<rw|ro>:<size>   (8 required, size K/M/G)\n"
            "  parity:<label>:<file>:<rw|ro>:<poly>:<error_level>\n"
            "                      (1-3 required; poly + error level must agree\n"
            "                      and match across all parity lines)\n",
            prog);
}

int main(int argc, char **argv)
{
    prog = argv[0];
    const char *cfgpath = NULL;
    int argi = 1;
    /* -c config.txt may come before or after the command */
    if (argi < argc && strcmp(argv[argi], "-c") == 0) {
        if (argi + 1 >= argc) {
            usage(stderr);
            return EXIT_USAGE;
        }
        cfgpath = argv[argi + 1];
        argi += 2;
    }
    if (argi >= argc) {
        usage(stderr);
        return EXIT_USAGE;
    }
    const char *cmd = argv[argi++];
    if (argi < argc && strcmp(argv[argi], "-c") == 0) {
        if (argi + 1 >= argc) {
            usage(stderr);
            return EXIT_USAGE;
        }
        cfgpath = argv[argi + 1];
        argi += 2;
    }
    if (!cfgpath) {
        fprintf(stderr, "%s: no config file given (use -c config.txt)\n", prog);
        usage(stderr);
        return EXIT_USAGE;
    }
    hyper_cfg_t cfg;
    parse_cfg(cfgpath, &cfg); /* exits with a message on bad config */
    int rc;
    if (strcmp(cmd, "-init") == 0) {
        int force = 0;
        if (argi < argc && strcmp(argv[argi], "--force") == 0) {
            force = 1;
            argi++;
        }
        if (argi < argc) {
            fprintf(stderr, "%s: -init takes no further arguments\n", prog);
            return EXIT_USAGE;
        }
        rc = cmd_init(&cfg, force);
    } else if (strcmp(cmd, "write") == 0) {
        if (argi >= argc) {
            fprintf(stderr, "%s: write needs a file\n", prog);
            return EXIT_USAGE;
        }
        const char *name = (argi + 1 < argc) ? argv[argi + 1] : NULL;
        rc = cmd_write(&cfg, argv[argi], name);
    } else if (strcmp(cmd, "read") == 0) {
        if (argi + 1 >= argc) {
            fprintf(stderr, "%s: read needs <name> <out>\n", prog);
            return EXIT_USAGE;
        }
        rc = cmd_read(&cfg, argv[argi], argv[argi + 1]);
    } else if (strcmp(cmd, "list") == 0) {
        rc = cmd_list(&cfg);
    } else if (strcmp(cmd, "check") == 0) {
        if (argi >= argc) {
            fprintf(stderr, "%s: check needs <name>\n", prog);
            return EXIT_USAGE;
        }
        rc = cmd_check(&cfg, argv[argi]);
    } else if (strcmp(cmd, "-rebuild") == 0) {
        rc = cmd_rebuild(&cfg);
    } else {
        fprintf(stderr, "%s: unknown command '%s'\n", prog, cmd);
        usage(stderr);
        return EXIT_USAGE;
    }
    return rc;
}

bch.c

Binary BCH codec — table-driven remainder (fused shift+XOR, syndrome-first no-copy decode), GF(2^m), syndromes, Berlekamp-Massey, Chien search, block splitting

/* bch.c - binary BCH error correction for lzply.
 *
 * Systematic shortened primitive BCH over GF(2), using the 82
 * narrow-sense generators in bch_polys.h (m=7..22, t=1,2,4,8,16,32).
 *
 * ENCODER (remainder / CRC style). A block is D data bytes (k=8D bits)
 * plus r parity bits. The codeword polynomial C(x) = M(x)*x^r + P(x),
 * P(x) = (M(x)*x^r) mod g(x), so C(x) is divisible by g(x). The
 * remainder is computed by a table-driven LFSR (CRC-style): the register
 * is an r-bit value stored LEFT-ALIGNED in a byte array (top bit =
 * bit 7 of rem[0]); for each data byte b,
 *   rem = byteshift(rem) XOR T[rem[0] XOR b],
 * where T[u] = (u(x)*x^r) mod g(x). Feeding the data bytes alone yields
 * P(x) -- the LFSR inherently multiplies by x^r, so NO augmentation
 * (extra zero bits) is fed. The parity bytes ARE the remainder bytes
 * (the last byte's low bits are the zero padding).
 *
 * DECODER. Feed the received codeword (data bytes + r parity bits;
 * the final partial parity byte is fed bit-by-bit so the padding
 * bits are never fed) into the same LFSR, giving R = (E*x^r) mod g,
 * E = error polynomial. R==0 means no error. Otherwise the syndromes
 * are S_j = R(alpha^j) * alpha^(-j*r) for j=1..2t (valid because
 * g(alpha^j)=0, so R(alpha^j) = E(alpha^j)*alpha^(j*r)).
 * Berlekamp-Massey on S_1..S_2t gives the error-locator
 * Lambda(x) = prod (1 + X_p*x), X_p = alpha^(n-1-p) for an error at
 * bit position p (p=0 is the first stored bit, coefficient of
 * x^(n-1)). Chien search evaluates Lambda(alpha^(p-(n-1))) for
 * p=0..n-1; a zero means an error at p, and that bit is flipped.
 * After flipping, the LFSR remainder must be 0 again, else the block
 * is declared uncorrectable. The per-entry SHA-256 in lzply is the
 * final guard against any miscorrection.
 *
 * GF(2^m) arithmetic: elements are uint32_t (< 2^m). The primitive
 * polynomial P_m is the t=1 generator for that m (bch_prim_poly).
 * Multiply-by-alpha is a shift + conditional XOR with the low m bits
 * of P_m. General multiplication is shift-and-xor (used for the
 * syndrome/BM, which need few mults). Chien search needs many mults,
 * so it uses log/exp tables built on demand and cached per m.
 */
#include <stdlib.h>
#include <string.h>
#include "bch.h"

/* ------------------------------------------------------------------ */
/* polynomial lookup                                                   */
/* ------------------------------------------------------------------ */

const bch_poly_t *bch_poly_by_id(uint16_t id)
{
    for (int i = 0; i < BCH_NPOLYS; i++)
        if (bch_polys[i].id == id)
            return &bch_polys[i];
    return NULL;
}

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;
    }
}

const bch_poly_t *bch_poly_for_data(size_t data_bytes, int t)
{
    int ti = t_index(t);
    if (ti < 0)
        return NULL;
    /* smallest m with a poly for (m,t) whose codeword can hold the data:
     * N >= 8*data_bytes + t*m. */
    for (int m = BCH_MIN_M; m <= BCH_MAX_M; m++) {
        uint16_t id = bch_poly_by_mt[m - BCH_MIN_M][ti];
        if (!id)
            continue;
        const bch_poly_t *p = bch_poly_by_id(id);
        uint64_t need = (uint64_t)8 * data_bytes + (uint64_t)t * m;
        if ((uint64_t)p->parent >= need)
            return p;
    }
    return NULL;
}

size_t bch_max_data(const bch_poly_t *p)
{
    /* floor((N - r)/8) data bytes fit in one codeword of this parent. */
    return (size_t)((p->parent - p->r) / 8);
}

size_t bch_block_stored_len(size_t data_len, const bch_poly_t *p)
{
    return data_len + (size_t)((p->r + 7) / 8);
}

size_t bch_encoded_len(size_t len, const bch_poly_t *p)
{
    size_t maxd = bch_max_data(p);
    if (len == 0)
        return bch_block_stored_len(0, p);
    size_t blocks = (len + maxd - 1) / maxd;
    size_t full = blocks - 1;
    size_t last = len - full * maxd;
    return full * bch_block_stored_len(maxd, p) + bch_block_stored_len(last, p);
}

int bch_t_for_level(int level)
{
    switch (level) {
    case 0: return 0;
    case 1: return 1;
    case 2: return 2;
    case 3: return 4;
    case 4: return 8;
    case 5: return 16;
    case 6: return 32;
    case 7: return 32;
    default: return -1;
    }
}

/* ------------------------------------------------------------------ */
/* remainder (table-driven LFSR)                                       */
/*                                                                     */
/* The remainder is an r-bit value stored LEFT-ALIGNED in rem[0..nb-1]:
 * bit (r-1) (coefficient of x^(r-1)) is bit 7 of rem[0]; bit i is at
 * byte (r-1-i)/8, bit 7-((r-1-i)%8). The low (nb*8-r) bits of the
 * last byte are always zero.                                          */
/* ------------------------------------------------------------------ */

typedef struct {
    const bch_poly_t *p;
    int r;              /* parity bits */
    int nb;             /* remainder bytes = (r+7)/8 */
    uint8_t glow[89];   /* low r bits of g(x), left-aligned */
    uint8_t *table;     /* 256 * nb bytes: T[u] = (u(x)*x^r) mod g(x) */
} bch_ctx_t;

static void 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);
}

/* (rem_get_bit removed: rem_eval iterates the bytes directly.) */

/* shift the left-aligned remainder left by one bit (top bit dropped). */
static void 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));
}

/* one bit-step of the LFSR: feed input bit m. */
static void rem_bitstep(uint8_t *rem, int m, const uint8_t *glow, int nb)
{
    int fb = ((rem[0] >> 7) & 1) ^ (m & 1);
    rem_shl1(rem, nb);
    if (fb)
        for (int i = 0; i < nb; i++)
            rem[i] ^= glow[i];
}

static bch_ctx_t *bch_ctx_new(const bch_poly_t *p)
{
    bch_ctx_t *c = calloc(1, sizeof(*c));
    if (!c)
        return NULL;
    c->p = p;
    c->r = p->r;
    c->nb = (p->r + 7) / 8;
    c->table = malloc((size_t)256 * c->nb);
    if (!c->table) {
        free(c);
        return NULL;
    }
    /* glow: low r bits of g(x). Generator bytes are LSB-first:
     * gen[j] holds bits 8j..8j+7, so g_i = (gen[i/8] >> (i%8)) & 1. */
    const uint8_t *gen = bch_poly_bytes + p->off;
    for (int i = 0; i < p->r; i++) {
        if ((gen[i / 8] >> (i % 8)) & 1)
            rem_set_bit(c->glow, p->r, i);
    }
    /* T[u]: feed u's 8 bits (MSB first) into the LFSR from rem=0. */
    for (int u = 0; u < 256; u++) {
        uint8_t *t = c->table + (size_t)u * c->nb;
        memset(t, 0, c->nb);
        for (int b = 7; b >= 0; b--)
            rem_bitstep(t, (u >> b) & 1, c->glow, c->nb);
    }
    return c;
}

static void bch_ctx_free(bch_ctx_t *c)
{
    if (!c)
        return;
    free(c->table);
    free(c);
}

/* table-driven update: feed one whole byte into the remainder.
 * The shift-left-by-one-byte and the table XOR fuse into a single
 * pass: new rem[i] = old rem[i+1] ^ T[idx][i]. Reading rem[i+1]
 * before it is overwritten (we sweep i upward) keeps this exact. */
static void rem_feed_byte(uint8_t *rem, uint8_t b, const bch_ctx_t *c)
{
    int idx = rem[0] ^ b;
    const uint8_t *t = c->table + (size_t)idx * c->nb;
    for (int i = 0; i < c->nb - 1; i++)
        rem[i] = rem[i + 1] ^ t[i];
    rem[c->nb - 1] = t[c->nb - 1];
}

/* remainder of the data bytes alone (== parity P(x)). */
static void rem_of_data(const uint8_t *data, size_t len, const bch_ctx_t *c,
                        uint8_t *rem)
{
    memset(rem, 0, c->nb);
    for (size_t i = 0; i < len; i++)
        rem_feed_byte(rem, data[i], c);
}

/* remainder of a codeword: data bytes (whole) + parity bits (r bits).
 * The parity bits are the first r bits of the parity bytes (MSB first);
 * the padding bits in the final byte are never fed. */
static void rem_of_codeword(const uint8_t *data, size_t data_len,
                            const uint8_t *par, const bch_ctx_t *c,
                            uint8_t *rem)
{
    memset(rem, 0, c->nb);
    for (size_t i = 0; i < data_len; i++)
        rem_feed_byte(rem, data[i], c);
    int r = c->r;
    int whole = r / 8;
    for (int i = 0; i < whole; i++)
        rem_feed_byte(rem, par[i], c);
    for (int b = 7; b >= 8 - (r % 8) && (r % 8); b--)
        rem_bitstep(rem, (par[whole] >> b) & 1, c->glow, c->nb);
}

static int rem_is_zero(const uint8_t *rem, int nb)
{
    for (int i = 0; i < nb; i++)
        if (rem[i])
            return 0;
    return 1;
}

/* brute-force remainder: bit-by-bit long division of the data polynomial
 * (MSB first) by g(x). Used by the unit test to cross-check the table. */
int bch_remainder_bruteforce(const uint8_t *data, size_t data_len,
                             const bch_poly_t *p, uint8_t *rem_out)
{
    bch_ctx_t *c = bch_ctx_new(p);
    if (!c)
        return -1;
    uint8_t *rem = calloc(1, c->nb);
    if (!rem) {
        bch_ctx_free(c);
        return -1;
    }
    for (size_t i = 0; i < data_len; i++)
        for (int b = 7; b >= 0; b--)
            rem_bitstep(rem, (data[i] >> b) & 1, c->glow, c->nb);
    memcpy(rem_out, rem, c->nb);
    free(rem);
    bch_ctx_free(c);
    return 0;
}

/* ------------------------------------------------------------------ */
/* GF(2^m) arithmetic                                                  */
/* ------------------------------------------------------------------ */

static uint32_t gf_mul_slow(uint32_t a, uint32_t b, uint32_t P, int m)
{
    uint32_t mask = (m >= 32) ? 0xffffffffu : ((1u << m) - 1);
    uint32_t plow = P & mask;
    uint32_t r = 0;
    while (b) {
        if (b & 1)
            r ^= a;
        b >>= 1;
        uint32_t top = (a >> (m - 1)) & 1u;
        a = (a << 1) & mask;
        if (top)
            a ^= plow;
    }
    return r;
}

static uint32_t gf_mul_alpha(uint32_t a, uint32_t P, int m)
{
    uint32_t mask = (m >= 32) ? 0xffffffffu : ((1u << m) - 1);
    uint32_t top = (a >> (m - 1)) & 1u;
    a = (a << 1) & mask;
    if (top)
        a ^= (P & mask);
    return a;
}

static uint32_t gf_pow_slow(uint32_t a, uint32_t e, uint32_t P, int m)
{
    uint32_t r = 1;
    while (e) {
        if (e & 1)
            r = gf_mul_slow(r, a, P, m);
        a = gf_mul_slow(a, a, P, m);
        e >>= 1;
    }
    return r;
}

/* (gf_inv via the log/exp tables is used instead; see gf_div_tab.) */

/* log/exp tables, cached per m (single slot; lzply is single-threaded). */
typedef struct {
    int m;
    uint32_t N;         /* 2^m - 1 */
    uint32_t *exp;      /* exp[i] = alpha^i, i = 0..N-1 */
    uint32_t *log;      /* log[v] = i with alpha^i = v, v = 1..N-1 */
} gf_tables_t;

static gf_tables_t gf_cache = { 0, 0, NULL, NULL };

static const gf_tables_t *gf_tables_for(int m)
{
    if (gf_cache.m == m && gf_cache.exp)
        return &gf_cache;
    free(gf_cache.exp);
    free(gf_cache.log);
    gf_cache.m = 0;
    gf_cache.exp = NULL;
    gf_cache.log = NULL;
    uint32_t P = bch_prim_poly[m];
    uint32_t N = (1u << m) - 1;
    size_t sz = (size_t)1 << m;
    uint32_t *exp = malloc(sz * sizeof(uint32_t));
    uint32_t *log = malloc(sz * sizeof(uint32_t));
    if (!exp || !log) {
        free(exp);
        free(log);
        return NULL;
    }
    uint32_t x = 1;
    for (uint32_t i = 0; i < N; i++) {
        exp[i] = x;
        log[x] = i;
        x = gf_mul_alpha(x, P, m);
    }
    exp[N] = 1;
    log[0] = 0;
    gf_cache.m = m;
    gf_cache.N = N;
    gf_cache.exp = exp;
    gf_cache.log = log;
    return &gf_cache;
}

static uint32_t gf_mul_tab(uint32_t a, uint32_t b, const gf_tables_t *t)
{
    if (!a || !b)
        return 0;
    uint32_t s = t->log[a] + t->log[b];
    if (s >= t->N)
        s -= t->N;
    return t->exp[s];
}

static uint32_t gf_div_tab(uint32_t a, uint32_t b, const gf_tables_t *t)
{
    if (!a)
        return 0;
    int d = (int)t->log[a] - (int)t->log[b];
    if (d < 0)
        d += (int)t->N;
    return t->exp[d];
}

/* evaluate the remainder polynomial R(x) (left-aligned bytes, r bits)
 * at x = a, by Horner from the top coefficient down. */
static uint32_t rem_eval(const uint8_t *rem, int r, uint32_t a,
                         uint32_t P, int m)
{
    uint32_t res = 0;
    int seen = 0;
    for (int by = 0; by < (r + 7) / 8 && seen < r; by++) {
        for (int bi = 7; bi >= 0 && seen < r; bi--, seen++) {
            int coeff = (rem[by] >> bi) & 1;
            res = gf_mul_slow(res, a, P, m) ^ (uint32_t)coeff;
        }
    }
    return res;
}

/* ------------------------------------------------------------------ */
/* decoder                                                             */
/* ------------------------------------------------------------------ */

/* Berlekamp-Massey on S_1..S_2t. Returns the degree L and fills
 * lambda[0..L] (lambda[0]=1). Uses slow GF arithmetic. */
static int berlekamp_massey(const uint32_t *S, int t, uint32_t P, int m,
                            uint32_t *lambda)
{
    uint32_t C[33], B[33], T[33];
    for (int i = 0; i <= 32; 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 < 2 * t; n++) {
        /* discrepancy d = S_{n+1} + sum_{i=1..L} C_i * S_{n+1-i} */
        uint32_t d = S[n];
        for (int i = 1; i <= L; i++) {
            if (C[i] && n - i >= 0)
                d ^= gf_mul_slow(C[i], S[n - i], P, m);
        }
        if (d == 0) {
            shift++;
            continue;
        }
        memcpy(T, C, sizeof(T));
        uint32_t coef = gf_div_tab(d, b, gf_tables_for(m));
        /* C = C + coef * x^shift * B */
        for (int i = 0; i <= 32 - shift; i++) {
            if (B[i])
                C[i + shift] ^= gf_mul_slow(coef, B[i], P, m);
        }
        if (2 * L <= n) {
            L = n + 1 - L;
            memcpy(B, T, sizeof(B));
            b = d;
            shift = 1;
        } else {
            shift++;
        }
    }
    for (int i = 0; i <= L; i++)
        lambda[i] = C[i];
    return L;
}

int bch_encode_block(const uint8_t *data, size_t data_len,
                     const bch_poly_t *p, uint8_t *out)
{
    bch_ctx_t *c = bch_ctx_new(p);
    if (!c)
        return -1;
    uint8_t *rem = malloc(c->nb);
    if (!rem) {
        bch_ctx_free(c);
        return -1;
    }
    rem_of_data(data, data_len, c, rem);
    memcpy(out, data, data_len);
    memcpy(out + data_len, rem, c->nb);
    free(rem);
    bch_ctx_free(c);
    return 0;
}

int bch_decode_block(const uint8_t *in, size_t in_len, size_t data_len,
                     const bch_poly_t *p, uint8_t *out, int *corrected)
{
    if (corrected)
        *corrected = 0;
    size_t stored = bch_block_stored_len(data_len, p);
    if (in_len != stored)
        return -1;
    int r = p->r, m = p->m, t = p->t;
    uint32_t P = bch_prim_poly[m];
    uint32_t N = (1u << m) - 1;
    size_t nbits = (size_t)8 * data_len + (size_t)r;
    int nb = (r + 7) / 8;

    bch_ctx_t *c = bch_ctx_new(p);
    if (!c)
        return -1;
    uint8_t *rem = malloc(nb);
    if (!rem) {
        bch_ctx_free(c);
        return -1;
    }
    /* Syndrome first, straight from the input: the common clean case
     * needs no working copy at all. Only if the remainder is non-zero
     * do we copy the block into `work` for Berlekamp-Massey / Chien. */
    rem_of_codeword(in, data_len, in + data_len, c, rem);
    if (rem_is_zero(rem, nb)) {
        /* no errors */
        memcpy(out, in, data_len);
        free(rem);
        bch_ctx_free(c);
        return 0;
    }
    uint8_t *work = malloc(in_len);
    if (!work) {
        free(rem);
        bch_ctx_free(c);
        return -1;
    }
    memcpy(work, in, in_len);

    /* syndromes S_j = R(alpha^j) * alpha^(-j*r), j = 1..2t */
    const gf_tables_t *tab = gf_tables_for(m);
    if (!tab) {
        free(rem);
        free(work);
        bch_ctx_free(c);
        return -1;
    }
    uint32_t S[64];
    for (int j = 1; j <= 2 * t; j++) {
        uint32_t aj = tab->exp[j % N];
        uint32_t v = rem_eval(rem, r, aj, P, m);
        /* multiply by alpha^(-j*r) */
        uint32_t e = (uint32_t)(((uint64_t)j * (uint64_t)r) % N);
        uint32_t inv = (e == 0) ? 1 : tab->exp[N - e];
        S[j - 1] = gf_mul_tab(v, inv, tab);
    }

    uint32_t lambda[33];
    int L = berlekamp_massey(S, t, P, m, lambda);
    if (L <= 0 || L > t) {
        free(rem);
        free(work);
        bch_ctx_free(c);
        return -1;
    }

    /* Chien search, incremental: x_p = alpha^(p-(n-1)), p = 0..n-1.
     * Maintain v[j] = lambda[j] * x_p^j; lambda(x_p) = sum v[j].
     * Stop once L roots are found. */
    uint32_t x0 = tab->exp[(N - (nbits - 1) % N) % N]; /* alpha^-(n-1) */
    uint32_t v[33];
    for (int j = 0; j <= L; j++) {
        /* v[j] = lambda[j] * x0^j */
        v[j] = lambda[j] ? gf_mul_tab(lambda[j], gf_pow_slow(x0, (uint32_t)j, P, m), tab) : 0;
    }
    /* alpha^j for the per-step update */
    uint32_t ajpow[33];
    for (int j = 0; j <= L; j++)
        ajpow[j] = tab->exp[j % N];

    int found = 0;
    for (size_t p = 0; p < nbits && found < L; p++) {
        uint32_t sum = 0;
        for (int j = 0; j <= L; j++)
            sum ^= v[j];
        if (sum == 0) {
            /* error at bit position p: flip it in work */
            size_t byte = p / 8;
            int bit = 7 - (int)(p % 8);
            work[byte] ^= (uint8_t)(1u << bit);
            found++;
        }
        /* advance to p+1: v[j] *= alpha^j */
        for (int j = 1; j <= L; j++)
            if (v[j])
                v[j] = gf_mul_tab(v[j], ajpow[j], tab);
    }
    if (found != L) {
        free(rem);
        free(work);
        bch_ctx_free(c);
        return -1;
    }
    if (corrected)
        *corrected = found;

    /* verify: the corrected codeword must have zero remainder */
    rem_of_codeword(work, data_len, work + data_len, c, rem);
    if (!rem_is_zero(rem, nb)) {
        free(rem);
        free(work);
        bch_ctx_free(c);
        return -1;
    }
    memcpy(out, work, data_len);
    free(rem);
    free(work);
    bch_ctx_free(c);
    return 0;
}

/* ------------------------------------------------------------------ */
/* whole-blob encode / decode                                          */
/* ------------------------------------------------------------------ */

size_t bch_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) {
        bch_encode_block(data, 0, p, out);
        return bch_block_stored_len(0, p);
    }
    while (off < len) {
        size_t chunk = len - off;
        if (chunk > maxd)
            chunk = maxd;
        bch_encode_block(data + off, chunk, p, out + woff);
        woff += bch_block_stored_len(chunk, p);
        off += chunk;
    }
    return woff;
}

int bch_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 (roff != len)
        return -1;
    if (corrected)
        *corrected = total;
    return 0;
}

bch.h

BCH header — poly lookup, auto-pick, block encode/decode

/* bch.h - binary BCH error correction for lzply.
 *
 * Systematic shortened primitive BCH codes over GF(2), using the
 * 82 narrow-sense generator polynomials embedded in bch_polys.h
 * (parents N = 2^m - 1, m = 7..22, t in {1,2,4,8,16,32}).
 *
 * Bit convention (shared by encoder and decoder):
 *   A block holds D data bytes (k = 8*D data bits) and r parity bits.
 *   The codeword is n = k + r bits, stored data-first then parity,
 *   each byte MSB-first, with zero-bit padding to a byte boundary.
 *   The codeword polynomial c(x) has the first stored bit as the
 *   coefficient of x^(n-1) and the last as the coefficient of x^0.
 *   The encoder makes c(x) divisible by g(x): parity =
 *   (data_poly * x^r) mod g(x), i.e. the standard cyclic (CRC-style)
 *   remainder. The decoder recomputes that remainder (the syndrome);
 *   nonzero means errors, which Berlekamp-Massey + Chien search
 *   locate as bit flips. Binary BCH needs no magnitude step.
 *
 * The data capacity of one block is floor((N - r)/8) bytes; a blob
 * longer than that is split into blocks of that size. The decoder
 * reconstructs block boundaries from blob_size + the poly, so no
 * per-block length is stored.
 */
#ifndef LZPLY_BCH_H
#define LZPLY_BCH_H

#include <stddef.h>
#include <stdint.h>
#include "bch_polys.h"

/* Look up a polynomial by id (0x0001..0x0052). NULL if unknown. */
const bch_poly_t *bch_poly_by_id(uint16_t id);

/* Auto-pick: smallest parent m with a poly for (m,t) whose codeword can
 * hold `data_bytes` of data, i.e. N >= 8*data_bytes + t*m. Returns NULL
 * if no parent covers it (data too large for m=22 at this t). */
const bch_poly_t *bch_poly_for_data(size_t data_bytes, int t);

/* Max data bytes one block of this poly can hold: floor((N - r)/8). */
size_t bch_max_data(const bch_poly_t *p);

/* Stored (codeword) bytes for a block holding data_len data bytes:
 * ceil((8*data_len + r)/8). */
size_t bch_block_stored_len(size_t data_len, const bch_poly_t *p);

/* Total stored bytes for a whole blob of len data bytes (all blocks). */
size_t bch_encoded_len(size_t len, const bch_poly_t *p);

/* -e level -> t. 0 -> 0 (no ECC), 1 -> 1, 2 -> 2, 3 -> 4, 4 -> 8,
 * 5 -> 16, 6 -> 32, 7 -> 32. Returns -1 for an invalid level. */
int bch_t_for_level(int level);

/* Encode one block: data_len <= bch_max_data(p). out must hold
 * bch_block_stored_len(data_len, p) bytes. Returns 0 on success. */
int bch_encode_block(const uint8_t *data, size_t data_len,
                     const bch_poly_t *p, uint8_t *out);

/* Decode one block: in_len must equal bch_block_stored_len(data_len, p).
 * out must hold data_len bytes. Returns 0 on success, -1 if
 * uncorrectable. *corrected (if non-NULL) = number of bits corrected. */
int bch_decode_block(const uint8_t *in, size_t in_len, size_t data_len,
                     const bch_poly_t *p, uint8_t *out, int *corrected);

/* Encode a whole blob (splits into blocks of bch_max_data). out must
 * hold bch_encoded_len(len, p) bytes. Returns the stored length. */
size_t bch_encode(const uint8_t *data, size_t len, const bch_poly_t *p,
                  uint8_t *out);

/* Decode a whole blob: orig_len is the data length (blob_size). Returns
 * 0 on success, -1 if any block is uncorrectable. *corrected (if
 * non-NULL) = total bits corrected across blocks. */
int bch_decode(const uint8_t *in, size_t len, size_t orig_len,
               const bch_poly_t *p, uint8_t *out, int *corrected);

/* Brute-force remainder (bit-by-bit long division), used by the unit
 * test to cross-check the table-driven encoder. rem_out must hold
 * (r+7)/8 bytes; returns 0 on success. */
int bch_remainder_bruteforce(const uint8_t *data, size_t data_len,
                             const bch_poly_t *p, uint8_t *rem_out);

#endif /* LZPLY_BCH_H */

bch_polys.h

The 82 embedded generator polynomials (generated by gen_bch_polys.py from the rssearch exhaustive search)

/* bch_polys.h - embedded BCH generator polynomials for lzply.
 *
 * Generated by gen_bch_polys.py from the rssearch results
 * (polys.txt / finds.txt). DO NOT EDIT BY HAND -- regenerate:
 *   python3 gen_bch_polys.py
 *
 * 82 narrow-sense primitive BCH generators, parents N=2^m-1 for
 * m=7..22, t in {1,2,4,8,16,32}. Generator bytes are LSB-first
 * (byte i holds bits 8i..8i+7), exactly as in polys.txt / finds.h.
 * The t=1 polynomial for each m is the primitive polynomial P_m
 * defining GF(2^m) (verified primitive by the generator).
 *
 * Every polynomial was independently recomputed orbit-only from
 * its P_m and checked byte-identical to polys.txt, so this table
 * is the narrow-sense generator for (m,t) under that P_m.
 */
#ifndef LZPLY_BCH_POLYS_H
#define LZPLY_BCH_POLYS_H

#include <stdint.h>

typedef struct {
    uint16_t id;       /* 2-byte polynomial id, e.g. 0x003a */
    uint8_t  m;        /* parent exponent: N = 2^m - 1 */
    uint8_t  t;        /* correctable bit errors */
    uint16_t r;        /* degree = parity bits = t*m */
    uint32_t parent;   /* N = 2^m - 1 */
    uint16_t nbytes;   /* generator length in bytes */
    uint16_t off;      /* offset into bch_poly_bytes[] */
} bch_poly_t;

#define BCH_NPOLYS 82
#define BCH_MIN_M 7
#define BCH_MAX_M 22

static const uint8_t bch_poly_bytes[] = {
    0xef,0xed,0x68,0x2b,0x01,0xe3,0xcb,0x01,0xe3,0x03,0x2d,0x75,0x05,0x1d,0xfe,0x9b,
    0x6d,0x1e,0x4d,0x07,0x03,0x57,0x1b,0x43,0xb7,0xae,0x4c,0x15,0x01,0x83,0x91,0xa1,
    0xeb,0x3a,0x6a,0x1c,0x94,0x9d,0xd1,0x01,0x27,0x0e,0x17,0x4e,0x75,0x5d,0x36,0x3d,
    0xec,0xb4,0x14,0x37,0x23,0x0e,0xa5,0x53,0x73,0x74,0x69,0x47,0xa7,0xf8,0x01,0xb5,
    0xa3,0x29,0xb5,0xa2,0xdb,0x00,0xc4,0xdb,0xec,0xc3,0xd0,0xce,0xca,0x75,0xf7,0xa9,
    0x77,0x6f,0x05,0xa9,0xf6,0x01,0x45,0x17,0x2d,0x04,0xcb,0x01,0x39,0x6a,0x7d,0x41,
    0xb5,0x37,0x01,0xf7,0xc3,0xd1,0x9d,0x41,0xa6,0x30,0x00,0x2e,0xb7,0x24,0xf3,0x01,
    0x3d,0xa1,0x44,0x26,0x84,0x77,0x22,0x9a,0x09,0xca,0xb5,0x67,0x34,0x01,0xdd,0xda,
    0xac,0x5d,0x62,0x74,0xc6,0x10,0x52,0xf6,0x01,0xf7,0x69,0x14,0x32,0x62,0x69,0xd6,
    0xb7,0xac,0xc6,0x0e,0x29,0x05,0x07,0x31,0x65,0xcd,0x33,0x3c,0xd8,0x1d,0xac,0x60,
    0x24,0xa2,0x5c,0xaf,0x3d,0xa9,0xa8,0x40,0xb0,0xa2,0x64,0x8d,0x93,0xd1,0xbf,0x20,
    0x12,0xdc,0x0d,0xc3,0xf8,0x8d,0x4c,0x23,0x57,0x01,0x4b,0x29,0xcb,0xff,0x5e,0x04,
    0xc3,0xdf,0x8e,0xd4,0x44,0x2b,0x1d,0x87,0xd6,0x9f,0x6d,0x66,0xea,0xa8,0xe8,0xea,
    0xda,0x2a,0x96,0x9e,0x01,0x4d,0xee,0xfd,0x7f,0x69,0x08,0xf0,0xd3,0x70,0x2d,0x8c,
    0xcf,0x32,0xd5,0x28,0xb6,0x75,0xc2,0x53,0x5f,0x29,0x4b,0x44,0x5b,0x2c,0xa9,0x01,
    0x57,0x19,0x9b,0xb2,0x6e,0x55,0xcc,0xaa,0x58,0x22,0xd4,0x8f,0x4f,0x23,0x74,0xd9,
    0xe3,0xaf,0x10,0x2b,0xc7,0xdb,0xf8,0xc3,0xba,0x29,0xce,0x56,0x74,0x83,0xf8,0xd3,
    0xac,0x0b,0x54,0xf8,0xfb,0x99,0x2d,0xaf,0xf4,0x79,0xd6,0x5f,0x7b,0x38,0x17,0x2c,
    0x6e,0x09,0x8d,0x01,0x01,0x27,0x46,0x27,0xc8,0x05,0x11,0x25,0xfc,0x12,0x3b,0x81,
    0x91,0xec,0x01,0xb9,0x2e,0xab,0xb2,0xd2,0xbb,0xf8,0xa0,0x47,0xfd,0x7d,0x2a,0x00,
    0xcb,0x01,0xfd,0x04,0x9e,0x66,0xed,0xff,0x49,0x93,0x97,0x12,0xf4,0x8f,0x9e,0x39,
    0x4d,0x26,0x64,0x65,0xfd,0xa1,0x28,0x04,0xcb,0xc2,0xaf,0xb6,0x62,0x62,0x01,0xc9,
    0x81,0x12,0xc4,0xcd,0x44,0xd0,0x80,0xca,0x90,0x10,0x5e,0x80,0xd9,0xb9,0xf5,0xe8,
    0x20,0xd7,0x29,0xbc,0x9a,0x86,0xbe,0x45,0x85,0x28,0x9c,0x4d,0xb9,0xf1,0x43,0x4b,
    0xe0,0x12,0xa8,0x28,0x45,0xf1,0x92,0xf0,0x52,0xbc,0x67,0xd7,0xea,0x3a,0x6a,0xfe,
    0xcc,0x8c,0x04,0xe5,0x3c,0xfc,0x92,0x01,0xd7,0xb3,0x67,0x20,0x02,0x6a,0xe7,0x93,
    0x2b,0x84,0xaf,0xba,0x26,0x10,0x05,0x1f,0xd1,0xf8,0x12,0xe5,0xd6,0xad,0x3c,0xd1,
    0x54,0xa3,0x97,0xfc,0xb3,0x01,0x45,0xcb,0x06,0xb3,0x39,0x6a,0x99,0xb4,0x46,0x84,
    0x40,0x55,0x88,0x93,0x1d,0x21,0x5e,0x37,0x7f,0x23,0xf9,0x11,0xb7,0x1b,0xbd,0x80,
    0x61,0x45,0x9c,0xe2,0x01,0xb5,0x55,0xf0,0x74,0xf3,0xf5,0xd1,0x49,0x77,0x89,0xe2,
    0xf3,0x4c,0x70,0x44,0x41,0xb9,0xe6,0x76,0xd6,0x3b,0xe8,0x90,0x02,0xa2,0x1a,0x7a,
    0x07,0xa7,0xff,0x28,0xb9,0x08,0xe8,0xde,0x6d,0xda,0x6e,0x93,0x52,0x3e,0x23,0x1b,
    0xb8,0x8e,0x50,0xea,0x49,0x3d,0x1d,0x54,0x88,0x04,0xbe,0x26,0x3b,0x7f,0x63,0xfd,
    0x91,0x01,0xbd,0x5f,0x01,0x03,0x5b,0x01,0x05,0x01,0x83,0x50,0x5c,0xac,0xd5,0xfe,
    0xc9,0xe9,0x01,0x91,0xd9,0x40,0x2a,0x4a,0xf3,0xc4,0x38,0xad,0xd2,0x08,0x56,0x5c,
    0x52,0x43,0x4f,0x01,0x29,0x84,0x72,0x1b,0xe7,0xdb,0x80,0x57,0xe1,0xd5,0xc2,0x34,
    0x1a,0x8d,0x5f,0xed,0xa7,0xf7,0x03,0xde,0x8f,0x59,0x60,0x63,0xc3,0x7d,0x3b,0x22,
    0xdf,0x53,0x5e,0x70,0x01,0x09,0x0b,0xa0,0x4c,0xcc,0x65,0x76,0x27,0x03,0x44,0xd7,
    0x60,0x81,0x97,0xd9,0x04,0x84,0x9f,0xf5,0x2a,0x86,0x84,0x7f,0xd3,0x03,0x85,0x77,
    0x31,0x2f,0x14,0xbb,0x58,0xd9,0x1d,0x84,0xdd,0xfe,0x27,0xf6,0x81,0x52,0xff,0x4d,
    0xd3,0xab,0x06,0x27,0x1d,0xfc,0x39,0x8c,0xcd,0xff,0x99,0xc2,0x35,0xe3,0x4e,0xca,
    0xde,0xfa,0xf0,0x9d,0x24,0x01,0xad,0x11,0x03,0xaf,0xd9,0x74,0x51,0x04,0xf5,0xf7,
    0xb2,0xc4,0x4b,0x42,0xcb,0xba,0x10,0x87,0xe0,0x08,0x99,0x03,0xfe,0x48,0xdb,0x80,
    0xb4,0x52,0x64,0xa1,0x7a,0xbf,0x95,0xd9,0x01,0x23,0xd0,0x3f,0x79,0x57,0x7a,0xf3,
    0xfe,0x09,0xf5,0x6e,0xf5,0x61,0x62,0x57,0xe3,0xd0,0x97,0xe4,0x47,0xd9,0x19,0xe6,
    0x96,0x01,0x6f,0x50,0x51,0x31,0xb1,0x8f,0xc3,0x8b,0xaf,0x01,0xd9,0xda,0x54,0xe6,
    0x5f,0x0a,0x25,0xb9,0x03,0x54,0x14,0x0f,0xc2,0xe8,0x96,0x99,0xfd,0xd7,0xab,0x75,
    0xec,0x1d,0xdb,0xdc,0x05,0x71,0x98,0x77,0x3a,0xf8,0xf5,0x2e,0x40,0x40,0xca,0x7c,
    0xe4,0x7c,0x97,0x27,0x2d,0x44,0xf6,0x28,0x7d,0x2d,0x98,0x93,0x54,0x5f,0xde,0x29,
    0x8f,0x56,0x7d,0x53,0x75,0x40,0xb4,0x6d,0x66,0x3b,0x98,0xaf,0x53,0x2d,0x84,0xd3,
    0x01,0xcf,0xf0,0x04,0x11,0x08,0x13,0x9d,0x1b,0x91,0x78,0x32,0x47,0x36,0x00,0x2d,
    0xfd,0xc1,0x01,0x41,0xb8,0xcf,0x7f,0xa2,0xc8,0xb9,0x59,0x84,0x8b,0x3f,0xb0,0x6b,
    0x3c,0xb7,0xd2,0x47,0x5f,0x01,0x7d,0xa9,0x9e,0xf8,0x44,0xc1,0xcc,0x28,0xa8,0x6c,
    0x18,0xa0,0x0e,0x35,0xab,0x8c,0xbf,0x38,0x7d,0x42,0x18,0x22,0xbf,0x1c,0x17,0xa4,
    0xc6,0x79,0x79,0xac,0xcd,0x59,0x91,0xce,0xc2,0xbd,0x01,0xbd,0x11,0x53,0xc4,0x8f,
    0x5e,0xa8,0x8e,0x8f,0xd7,0x9d,0x3f,0xa0,0x51,0x24,0x06,0xe2,0xef,0x28,0x95,0x1a,
    0xdd,0x2d,0x3f,0x7f,0x7f,0x32,0x9a,0xfd,0xca,0x7a,0x84,0x20,0x14,0xe5,0x4e,0xd7,
    0xa5,0x5b,0x18,0x4d,0x50,0x46,0xf7,0x12,0xfa,0x89,0x42,0x9b,0xad,0x6e,0xdb,0xa5,
    0x43,0xc0,0x59,0xbe,0xe5,0x59,0x58,0x6e,0xac,0xcb,0xc7,0xee,0x10,0x31,0x24,0x80,
    0xba,0xd4,0xb3,0x01,0xd5,0x4d,0x0a,0x89,0x55,0xec,0x41,0x43,0x03,0x37,0x27,0x86,
    0x17,0x42,0x42,0xed,0xec,0x17,0x79,0x39,0x2f,0x72,0xa4,0xe4,0x46,0xa9,0x26,0xf5,
    0x19,0xe3,0xe5,0x7b,0xe7,0xb9,0xef,0x45,0x79,0x01,0x71,0x44,0xcb,0x3a,0xeb,0xc8,
    0x50,0x3a,0x21,0x2e,0x9c,0x14,0x55,0x2b,0x60,0xe3,0xae,0xe2,0x1a,0xff,0x31,0x22,
    0x5a,0xe3,0xc0,0x05,0xfe,0x3b,0x00,0xa6,0xb0,0x32,0x82,0xb2,0x4a,0xe4,0xed,0x93,
    0x01,0x61,0x42,0xc5,0x22,0xbe,0x8c,0x20,0xef,0xfc,0x04,0x08,0x78,0xde,0x86,0xd5,
    0x90,0xa9,0x25,0x99,0x4a,0x09,0x58,0x38,0xed,0x78,0xd2,0xe4,0xa7,0x9a,0x6a,0x82,
    0xb8,0xb7,0xb1,0x78,0x1b,0x0b,0xe4,0x4a,0xdd,0xb9,0x04,0x6a,0x1e,0x32,0x51,0x08,
    0x67,0x1f,0xed,0x3f,0x05,0x02,0xba,0x76,0x89,0xb2,0x99,0x99,0xa5,0x1a,0xa5,0x7b,
    0xa8,0x3d,0x74,0x06,0xe8,0x6a,0xf6,0x9f,0x42,0xc6,0x9b,0x5c,0xc9,0x01,0x57,0x0a,
    0x17,0x3f,0x02,0x37,0x86,0xad,0x01,0x85,0x40,0x01,0x77,0x57,0x65,0xe8,0x92,0x5d,
    0x28,0x01,0xc5,0x47,0xab,0xa3,0x7f,0xd8,0x88,0x39,0xff,0xb1,0xcf,0x8a,0x35,0x54,
    0xf2,0xa9,0xb9,0x4d,0x7c,0xb0,0x01,0x7b,0x0e,0xb6,0x1f,0xa2,0xd1,0x10,0x3b,0x4f,
    0x4b,0x67,0x0a,0x5e,0x57,0x30,0x27,0x32,0x7c,0x9d,0x05,0x82,0x45,0x68,0x11,0xed,
    0x60,0xd9,0xb3,0x4d,0xc3,0x59,0x54,0x3c,0x2c,0x46,0xae,0xa7,0x1f,0x57,0x4b,0x01,
    0xf5,0xe6,0x41,0x92,0x9e,0xa9,0x70,0x33,0x0f,0x06,0xdf,0xb1,0xf1,0x63,0x18,0xb6,
    0x76,0xf3,0x85,0x0c,0xb5,0x13,0x4f,0xa2,0xba,0xba,0xc8,0x70,0x15,0xa9,0x3c,0xce,
    0x49,0x1a,0x91,0xd6,0xbf,0x38,0xd9,0xa3,0x6c,0x1a,0x82,0x44,0x33,0x13,0x8f,0xf1,
    0x73,0x36,0x03,0xe7,0x3b,0xd9,0x12,0xfa,0xde,0x0e,0x8d,0x20,0x64,0xa1,0xbd,0x73,
    0xd5,0xbe,0x0c,0x1b,0x22,0xd6,0x4c,0x69,0xdf,0x3a,0xc3,0x8b,0x84,0x22,0xcc,0x88,
    0x01,0xd9,0x4f,0x3d,0x2b,0xc2,0xa1,0xfb,0xec,0x04,0x43,0x6b,0x64,0x05,0x27,0x53,
    0x6a,0xdb,0xf7,0x40,0x14,0x81,0xc4,0x5a,0xc2,0x40,0x75,0x95,0x16,0xff,0x35,0x39,
    0xe0,0x47,0x57,0x31,0x14,0xef,0x67,0x15,0x9b,0x47,0x01,0x35,0xc3,0xac,0x76,0x72,
    0x38,0xb3,0xdd,0x13,0x7b,0xaf,0x03,0xf2,0x16,0xc4,0x41,0xbc,0x91,0x00,0xbe,0xe2,
    0x25,0x5b,0x41,0xe3,0xe9,0x73,0xd9,0xd5,0xa5,0xfb,0xe5,0x79,0x2c,0xe9,0x91,0x71,
    0x30,0x7f,0x9c,0x73,0x28,0x01,0xab,0xee,0x1b,0x0d,0x0a,0x8e,0xfc,0x2d,0x39,0x57,
    0xca,0xfe,0xa7,0x51,0x5c,0x86,0x11,0xcd,0x64,0x52,0xc0,0x45,0xa5,0x58,0x40,0xd7,
    0xc0,0xd3,0x63,0x3f,0xce,0xd6,0x16,0xf1,0x54,0xf4,0x77,0x85,0xf7,0x0b,0x15,0xd8,
    0x8c,0xa7,0xeb,0xca,0x90,0x4c,0xfc,0xaf,0x40,0x58,0x20,0x36,0x1d,0xae,0xa3,0xaf,
    0x93,0xca,0xf9,0x62,0xfe,0xfa,0x52,0x4f,0xcf,0xc5,0x9f,0x6b,0x3b,0x26,0xb9,0xf3,
    0x1f,0xac,0xdd,0xe1,0xd2,0x0e,0xbb,0x4c,0x21,0xdb,0x01,0x9d,0xdf,0x45,0xb3,0x0a,
    0x65,0x57,0x09,0x15,0x4b,0x41,0x57,0xf0,0x8e,0xa2,0x1c,0xf6,0xaf,0xcb,0x96,0x01,
    0x8f,0x6e,0xb6,0x20,0xef,0x52,0x4f,0x7e,0x17,0xe8,0xea,0x65,0xbd,0x9c,0x8f,0x6b,
    0x6a,0x56,0xe6,0x3a,0x80,0xd1,0x01,0x69,0x31,0x2b,0x7e,0xfb,0x02,0x9c,0x17,0x81,
    0x86,0x71,0x3c,0x7d,0x00,0x9f,0xe7,0xc3,0x2b,0x6e,0x7f,0x61,0x72,0xa4,0xfd,0xe2,
    0x51,0x1f,0x28,0x1a,0xa0,0xaf,0x35,0x50,0xe1,0xe9,0x52,0x69,0xf2,0x97,0x3a,0x34,
    0x04,0x8b,0x71,0x01,0x79,0x95,0x98,0x6f,0x3f,0xd2,0x3e,0x6f,0xd8,0xf6,0xfe,0x54,
    0x23,0xa8,0x6e,0x4c,0x92,0x27,0x0f,0x3e,0xd8,0x14,0x94,0x55,0x52,0xcd,0x0e,0x97,
    0x1c,0x17,0xf9,0x5c,0x3f,0x9d,0x96,0x13,0x9d,0xfa,0x95,0x0d,0x79,0xec,0xeb,0x41,
    0x3f,0xb6,0x77,0x52,0x7e,0x96,0x36,0x1a,0xf6,0xc8,0xa3,0xb1,0xcb,0xc3,0x0b,0x8a,
    0x0e,0xc3,0x9d,0xca,0x02,0xfd,0xa4,0x3d,0xb6,0xb9,0x78,0x08,0xa4,0xf4,0xd7,0xd0,
    0x75,0x4d,0xe2,0xb0,0x7f,0x80,0x83,0xd7,0xa4,0x79,0xd9,0x60,0x01,
};

static const bch_poly_t bch_polys[] = {
    { 0x0001, 7, 1, 7, 127, 1, 0 },
    { 0x0002, 7, 2, 14, 127, 2, 1 },
    { 0x0003, 8, 1, 8, 255, 2, 3 },
    { 0x0004, 8, 2, 16, 255, 3, 5 },
    { 0x0005, 9, 1, 9, 511, 2, 8 },
    { 0x0006, 9, 2, 18, 511, 3, 10 },
    { 0x0007, 9, 4, 36, 511, 5, 13 },
    { 0x0008, 10, 1, 10, 1023, 2, 18 },
    { 0x0009, 10, 2, 20, 1023, 3, 20 },
    { 0x000a, 10, 4, 40, 1023, 6, 23 },
    { 0x000b, 10, 8, 80, 1023, 11, 29 },
    { 0x000c, 11, 1, 11, 2047, 2, 40 },
    { 0x000d, 11, 2, 22, 2047, 3, 42 },
    { 0x000e, 11, 4, 44, 2047, 6, 45 },
    { 0x000f, 11, 8, 88, 2047, 12, 51 },
    { 0x0010, 11, 16, 176, 2047, 23, 63 },
    { 0x0011, 12, 1, 12, 4095, 2, 86 },
    { 0x0012, 12, 2, 24, 4095, 4, 88 },
    { 0x0013, 12, 4, 48, 4095, 7, 92 },
    { 0x0014, 12, 8, 96, 4095, 13, 99 },
    { 0x0015, 12, 16, 192, 4095, 25, 112 },
    { 0x0016, 12, 32, 384, 4095, 49, 137 },
    { 0x0017, 13, 1, 13, 8191, 2, 186 },
    { 0x0018, 13, 2, 26, 8191, 4, 188 },
    { 0x0019, 13, 4, 52, 8191, 7, 192 },
    { 0x001a, 13, 8, 104, 8191, 14, 199 },
    { 0x001b, 13, 16, 208, 8191, 27, 213 },
    { 0x001c, 13, 32, 416, 8191, 53, 240 },
    { 0x001d, 14, 1, 14, 16383, 2, 293 },
    { 0x001e, 14, 2, 28, 16383, 4, 295 },
    { 0x001f, 14, 4, 56, 16383, 8, 299 },
    { 0x0020, 14, 8, 112, 16383, 15, 307 },
    { 0x0021, 14, 16, 224, 16383, 29, 322 },
    { 0x0022, 14, 32, 448, 16383, 57, 351 },
    { 0x0023, 15, 1, 15, 32767, 2, 408 },
    { 0x0024, 15, 2, 30, 32767, 4, 410 },
    { 0x0025, 15, 4, 60, 32767, 8, 414 },
    { 0x0026, 15, 8, 120, 32767, 16, 422 },
    { 0x0027, 15, 16, 240, 32767, 31, 438 },
    { 0x0028, 15, 32, 480, 32767, 61, 469 },
    { 0x0029, 16, 1, 16, 65535, 3, 530 },
    { 0x002a, 16, 2, 32, 65535, 5, 533 },
    { 0x002b, 16, 4, 64, 65535, 9, 538 },
    { 0x002c, 16, 8, 128, 65535, 17, 547 },
    { 0x002d, 16, 16, 256, 65535, 33, 564 },
    { 0x002e, 16, 32, 512, 65535, 65, 597 },
    { 0x002f, 17, 1, 17, 131071, 3, 662 },
    { 0x0030, 17, 2, 34, 131071, 5, 665 },
    { 0x0031, 17, 4, 68, 131071, 9, 670 },
    { 0x0032, 17, 8, 136, 131071, 18, 679 },
    { 0x0033, 17, 16, 272, 131071, 35, 697 },
    { 0x0034, 17, 32, 544, 131071, 69, 732 },
    { 0x0035, 18, 1, 18, 262143, 3, 801 },
    { 0x0036, 18, 2, 36, 262143, 5, 804 },
    { 0x0037, 18, 4, 72, 262143, 10, 809 },
    { 0x0038, 18, 8, 144, 262143, 19, 819 },
    { 0x0039, 18, 16, 288, 262143, 37, 838 },
    { 0x003a, 18, 32, 576, 262143, 73, 875 },
    { 0x003b, 19, 1, 19, 524287, 3, 948 },
    { 0x003c, 19, 2, 38, 524287, 5, 951 },
    { 0x003d, 19, 4, 76, 524287, 10, 956 },
    { 0x003e, 19, 8, 152, 524287, 20, 966 },
    { 0x003f, 19, 16, 304, 524287, 39, 986 },
    { 0x0040, 19, 32, 608, 524287, 77, 1025 },
    { 0x0041, 20, 1, 20, 1048575, 3, 1102 },
    { 0x0042, 20, 2, 40, 1048575, 6, 1105 },
    { 0x0043, 20, 4, 80, 1048575, 11, 1111 },
    { 0x0044, 20, 8, 160, 1048575, 21, 1122 },
    { 0x0045, 20, 16, 320, 1048575, 41, 1143 },
    { 0x0046, 20, 32, 640, 1048575, 81, 1184 },
    { 0x0047, 21, 1, 21, 2097151, 3, 1265 },
    { 0x0048, 21, 2, 42, 2097151, 6, 1268 },
    { 0x0049, 21, 4, 84, 2097151, 11, 1274 },
    { 0x004a, 21, 8, 168, 2097151, 22, 1285 },
    { 0x004b, 21, 16, 336, 2097151, 43, 1307 },
    { 0x004c, 21, 32, 672, 2097151, 85, 1350 },
    { 0x004d, 22, 1, 22, 4194303, 3, 1435 },
    { 0x004e, 22, 2, 44, 4194303, 6, 1438 },
    { 0x004f, 22, 4, 88, 4194303, 12, 1444 },
    { 0x0050, 22, 8, 176, 4194303, 23, 1456 },
    { 0x0051, 22, 16, 352, 4194303, 45, 1479 },
    { 0x0052, 22, 32, 704, 4194303, 89, 1524 },
};

/* (m,t) -> poly id, rows m=7..22, cols t = 1,2,4,8,16,32; 0 = none. */
static const uint16_t bch_poly_by_mt[16][6] = {
    { 0x0001, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000 },  /* m=7 */
    { 0x0003, 0x0004, 0x0000, 0x0000, 0x0000, 0x0000 },  /* m=8 */
    { 0x0005, 0x0006, 0x0007, 0x0000, 0x0000, 0x0000 },  /* m=9 */
    { 0x0008, 0x0009, 0x000a, 0x000b, 0x0000, 0x0000 },  /* m=10 */
    { 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0000 },  /* m=11 */
    { 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016 },  /* m=12 */
    { 0x0017, 0x0018, 0x0019, 0x001a, 0x001b, 0x001c },  /* m=13 */
    { 0x001d, 0x001e, 0x001f, 0x0020, 0x0021, 0x0022 },  /* m=14 */
    { 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, 0x0028 },  /* m=15 */
    { 0x0029, 0x002a, 0x002b, 0x002c, 0x002d, 0x002e },  /* m=16 */
    { 0x002f, 0x0030, 0x0031, 0x0032, 0x0033, 0x0034 },  /* m=17 */
    { 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x003a },  /* m=18 */
    { 0x003b, 0x003c, 0x003d, 0x003e, 0x003f, 0x0040 },  /* m=19 */
    { 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046 },  /* m=20 */
    { 0x0047, 0x0048, 0x0049, 0x004a, 0x004b, 0x004c },  /* m=21 */
    { 0x004d, 0x004e, 0x004f, 0x0050, 0x0051, 0x0052 },  /* m=22 */
};

/* Primitive polynomial P_m for GF(2^m), as a uint32 (bit i = coeff of x^i).
 * This is the t=1 generator for that parent. */
static const uint32_t bch_prim_poly[23] = {
    0u,  /* m=0 (unused) */
    0u,  /* m=1 (unused) */
    0u,  /* m=2 (unused) */
    0u,  /* m=3 (unused) */
    0u,  /* m=4 (unused) */
    0u,  /* m=5 (unused) */
    0u,  /* m=6 (unused) */
    0x000000efu,  /* m=7 */
    0x0000012bu,  /* m=8 */
    0x000003e3u,  /* m=9 */
    0x0000074du,  /* m=10 */
    0x00000e27u,  /* m=11 */
    0x00001745u,  /* m=12 */
    0x0000294bu,  /* m=13 */
    0x00004627u,  /* m=14 */
    0x0000b3d7u,  /* m=15 */
    0x00015fbdu,  /* m=16 */
    0x000311adu,  /* m=17 */
    0x0004f0cfu,  /* m=18 */
    0x000a4dd5u,  /* m=19 */
    0x00170a57u,  /* m=20 */
    0x003d4fd9u,  /* m=21 */
    0x0045df9du,  /* m=22 */
};

#endif /* LZPLY_BCH_POLYS_H */

sha256.c

In-tree FIPS 180-4 SHA-256 (no OpenSSL dependency)

/* sha256.c - self-contained SHA-256 (FIPS 180-4); no external crypto library.
 * Standard implementation: initial hash values, K constants,
 * message schedule, compression function, padding. */
#include "sha256.h"

#include <string.h>

#define ROTR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
#define CH(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
#define MAJ(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define EP0(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))
#define EP1(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))
#define SIG0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ ((x) >> 3))
#define SIG1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ ((x) >> 10))

static const uint32_t k[64] = {
    0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, 0x3956c25bu,
    0x59f111f1u, 0x923f82a4u, 0xab1c5ed5u, 0xd807aa98u, 0x12835b01u,
    0x243185beu, 0x550c7dc3u, 0x72be5d74u, 0x80deb1feu, 0x9bdc06a7u,
    0xc19bf174u, 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu,
    0x2de92c6fu, 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, 0x983e5152u,
    0xa831c66du, 0xb00327c8u, 0xbf597fc7u, 0xc6e00bf3u, 0xd5a79147u,
    0x06ca6351u, 0x14292967u, 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu,
    0x53380d13u, 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u,
    0xa2bfe8a1u, 0xa81a664bu, 0xc24b8b70u, 0xc76c51a3u, 0xd192e819u,
    0xd6990624u, 0xf40e3585u, 0x106aa070u, 0x19a4c116u, 0x1e376c08u,
    0x2748774cu, 0x34b0bcb5u, 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu,
    0x682e6ff3u, 0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u,
    0x90befffau, 0xa4506cebu, 0xbef9a3f7u, 0xc67178f2u
};

void lzply_sha256_init(lzply_sha256_ctx_t *ctx)
{
    ctx->datalen = 0;
    ctx->bitlen = 0;
    ctx->state[0] = 0x6a09e667u;
    ctx->state[1] = 0xbb67ae85u;
    ctx->state[2] = 0x3c6ef372u;
    ctx->state[3] = 0xa54ff53au;
    ctx->state[4] = 0x510e527fu;
    ctx->state[5] = 0x9b05688cu;
    ctx->state[6] = 0x1f83d9abu;
    ctx->state[7] = 0x5be0cd19u;
}

static void sha256_transform(lzply_sha256_ctx_t *ctx, const uint8_t data[])
{
    uint32_t a, b, c, d, e, f, g, h, t1, t2, m[64];
    int i;
    for (i = 0; i < 16; i++)
        m[i] = ((uint32_t)data[i * 4] << 24) |
               ((uint32_t)data[i * 4 + 1] << 16) |
               ((uint32_t)data[i * 4 + 2] << 8) |
               ((uint32_t)data[i * 4 + 3]);
    for (i = 16; i < 64; i++)
        m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];
    a = ctx->state[0]; b = ctx->state[1]; c = ctx->state[2]; d = ctx->state[3];
    e = ctx->state[4]; f = ctx->state[5]; g = ctx->state[6]; h = ctx->state[7];
    for (i = 0; i < 64; i++) {
        t1 = h + EP1(e) + CH(e, f, g) + k[i] + m[i];
        t2 = EP0(a) + MAJ(a, b, c);
        h = g; g = f; f = e; e = d + t1;
        d = c; c = b; b = a; a = t1 + t2;
    }
    ctx->state[0] += a; ctx->state[1] += b; ctx->state[2] += c;
    ctx->state[3] += d; ctx->state[4] += e; ctx->state[5] += f;
    ctx->state[6] += g; ctx->state[7] += h;
}

void lzply_sha256_update(lzply_sha256_ctx_t *ctx, const uint8_t *data,
                         size_t len)
{
    size_t i;
    for (i = 0; i < len; i++) {
        ctx->data[ctx->datalen] = data[i];
        ctx->datalen++;
        if (ctx->datalen == 64) {
            sha256_transform(ctx, ctx->data);
            ctx->bitlen += 512;
            ctx->datalen = 0;
        }
    }
}

void lzply_sha256_final(lzply_sha256_ctx_t *ctx, uint8_t out[32])
{
    uint32_t i = ctx->datalen;
    /* Pad: 0x80, zeros, then 64-bit big-endian bit length. */
    if (ctx->datalen < 56) {
        ctx->data[i++] = 0x80;
        while (i < 56)
            ctx->data[i++] = 0x00;
    } else {
        ctx->data[i++] = 0x80;
        while (i < 64)
            ctx->data[i++] = 0x00;
        sha256_transform(ctx, ctx->data);
        memset(ctx->data, 0, 56);
    }
    ctx->bitlen += ctx->datalen * 8;
    ctx->data[63] = (uint8_t)(ctx->bitlen);
    ctx->data[62] = (uint8_t)(ctx->bitlen >> 8);
    ctx->data[61] = (uint8_t)(ctx->bitlen >> 16);
    ctx->data[60] = (uint8_t)(ctx->bitlen >> 24);
    ctx->data[59] = (uint8_t)(ctx->bitlen >> 32);
    ctx->data[58] = (uint8_t)(ctx->bitlen >> 40);
    ctx->data[57] = (uint8_t)(ctx->bitlen >> 48);
    ctx->data[56] = (uint8_t)(ctx->bitlen >> 56);
    sha256_transform(ctx, ctx->data);
    for (i = 0; i < 4; i++) {
        uint32_t j;
        for (j = 0; j < 8; j++) {
            out[i + (j * 4)] = (uint8_t)((ctx->state[j] >> (24 - i * 8)) & 0xff);
        }
    }
}

void lzply_sha256(const uint8_t *data, size_t len, uint8_t out[32])
{
    lzply_sha256_ctx_t ctx;
    lzply_sha256_init(&ctx);
    lzply_sha256_update(&ctx, data, len);
    lzply_sha256_final(&ctx, out);
}

sha256.h

SHA-256 header

/* sha256.h - self-contained SHA-256 (FIPS 180-4); no external crypto library.
 *
 * One-shot: lzply_sha256(data, len, out32). Incremental:
 * lzply_sha256_init / _update / _final. Used by the lzply family
 * for the per-entry SHA-256 (the BCH miscorrection guard) and by
 * lzply_refresh for its before/after verification. */
#ifndef LZPLY_SHA256_H
#define LZPLY_SHA256_H

#include <stddef.h>
#include <stdint.h>

typedef struct {
    uint32_t state[8];
    uint64_t bitlen;
    uint8_t data[64];
    uint32_t datalen;
} lzply_sha256_ctx_t;

void lzply_sha256_init(lzply_sha256_ctx_t *ctx);
void lzply_sha256_update(lzply_sha256_ctx_t *ctx, const uint8_t *data,
                         size_t len);
void lzply_sha256_final(lzply_sha256_ctx_t *ctx, uint8_t out[32]);
void lzply_sha256(const uint8_t *data, size_t len, uint8_t out[32]);

#endif /* LZPLY_SHA256_H */

README-hyper.md

The lzply_hyper README — config, commands, parity scheme, read-speed notes, demo

# lzply_hyper — a striped volume that heals itself

`lzply_hyper` is the striped-volume sibling of `lzply`. It is **not**
an archive and it does not compress. It takes a file, splits it
bit-plane across 8 data stripes, and stores independent parity
stripes plus BCH parity so a dead stripe — or three — can be rebuilt
and bit rot can be corrected on read. Write speed is not a design
goal (bit-packing costs). **Read speed is.** A read reassembles the
file from the surviving stripes, checks it, and verifies it, and the
parity stripes are only touched when a stripe is actually dead.

The name is a pun that stuck: the archiver went `lzrs` → `lzbch` →
`lzply`, and this one stripes *hyper* — many stripes, many parities.

## Layout: 8 bit-plane data stripes

A file is split byte by byte, bit by bit. Byte `i` splits into its 8
bits; bit `j` goes to stripe `j`. Stripe `j` holds one bit of every
byte, packed. So each data stripe is `ceil(file_len / 8)` bytes, and
the 8 stripes together hold exactly the file, no more, no less. No
compression: an incompressible file costs the same as a compressible
one.

Reassembly uses an 8x8 bit-matrix transpose (SWAR — three
shift/mask/xor stages on a `uint64`), not per-bit extraction. The
transpose is an involution, so the same function splits on write and
merges on read. The on-disk layout is checked against hand-computed
values in the test suite (e.g. bytes `01 02 04 08 10 20 40 80`
transpose to themselves; `FF 00 00 00 00 00 00 00` gives every stripe
byte `01`).

```
file bytes:  b0 b1 b2 b3 b4 b5 b6 b7 b8 ...
stripe 0:    bit0(b0) bit0(b1) ... bit0(b7) | bit0(b8) ...
stripe 1:    bit1(b0) bit1(b1) ... bit1(b7) | bit1(b8) ...
...
stripe 7:    bit7(b0) bit7(b1) ... bit7(b7) | bit7(b8) ...
```

## Two parity layers, both in each file's parity record

Every file gets one parity record per parity stripe. The record
header (96 bytes) holds the name, original length, poly id and `t`,
the stripe offset and length, the parity and BCH lengths, and a
SHA-256 of the original file. After the header come the parity bytes
(`stripe_len` bytes) and the BCH parity bytes. The record is appended
to each parity stripe when the file is written; the stripes are
written first, then the records, so a crash leaves orphaned stripe
data, never a dangling record.

### Layer 1 — stripe loss (P, Q, R)

Three **independent** parity stripes, not mirrors of each other:

* **P** = XOR across the 8 data stripes. Recovers any **1** lost stripe.
* **Q** = GF(256) weighted sum, `sum g^j * s_j` (g = 2, the field
  generator, primitive polynomial `0x11d`). Recovers a **2nd** lost
  stripe, RAID-6 style.
* **R** = GF(256) weighted sum with different coefficients,
  `sum g^(2j) * s_j`. Recovers a **3rd** lost stripe.

The number of parity stripes in the config sets the tolerance:
1 parity → 1 loss, 2 parities → 2 losses, 3 parities → 3 losses.
Recovery solves the small (k×k, k ≤ 3) coefficient system over
GF(256) by Gauss-Jordan inversion, per byte position. It uses
whichever parity rows survive — Q alone rebuilds 1 lost stripe if P
is dead. A 4th lost stripe is beyond tolerance: `read` and
`-rebuild` fail clearly and never return wrong data.

BCH alone cannot do this. Poly `0044` (m=20, t=8) holds 131,051 data
bytes per block with 160 parity bits (20 bytes) of erasure capacity,
while one dead stripe of 5 loses 26,210 bytes per block — ~1,300x
over capacity. Stripe loss needs parity *across* the stripes.

### Layer 2 — bit rot (BCH + SHA-256)

BCH parity over the whole file, using the config's poly and error
level, stored after the parity bytes. It corrects bit rot in the
reassembled file — including a bit error that propagated through a
stripe rebuild, since that lands as a single-bit error in the
reassembled file. The poly is taken from the **first** parity line;
all parity lines must agree on poly + error level or the config is
rejected. The BCH parity is the same on every parity stripe.
SHA-256 over the original file is the final guard: a BCH
miscorrection (a damage pattern beyond `t` landing on a different
valid codeword) is caught by the hash and reported as corruption,
never as silent damage.

Read order: reassemble surviving stripes → rebuild any dead stripe
via parity → BCH check/correct → SHA-256 verify. The BCH syndrome
is computed streaming on read (a cheap linear pass); full correction
only runs if the syndrome is non-zero. XOR/Q/R parity is read only
when a stripe is dead. I/O works in 64 KiB bursts.

## Config

```
stripe:<label>:<file>:<rw|ro>:<size>
parity:<label>:<file>:<rw|ro>:<poly>:<error_level>
```

* `stripe` lines: exactly **8** (the bit-plane layout fixes the
  count; any other number is an error).
* `parity` lines: **1–3** (more than 3 is an error for v1).
* `rw` = read-write, `ro` = read-only (never written; usable for
  reads and recovery). A write requires every stripe and parity to
  be `rw`.
* `size` = capacity with K/M/G suffixes (`10G`). A write that would
  exceed a stripe's remaining capacity fails instead of silently
  wrapping. `-init` checks that the filesystem actually has room for
  the configured sizes.
* `poly` is a hex id (as in the polynomial tables: `0044` is m=20,
  t=8; `003a` is m=18, t=32). It is authoritative; `error_level`
  must agree with it (`bch_t_for_level`: 1→1, 2→2, 3→4, 4→8, 5→16,
  6→32, 7→32) or the config is rejected.
* A stripe or parity file can live anywhere — the config is just
  paths. Labels must be unique across all entries.

Example (8 stripes + 3 parities, poly `0044`, level 4):

```
stripe:s0:/mnt/disk0/s0.hyper:rw:1G
stripe:s1:/mnt/disk1/s1.hyper:rw:1G
stripe:s2:/mnt/disk2/s2.hyper:rw:1G
stripe:s3:/mnt/disk3/s3.hyper:rw:1G
stripe:s4:/mnt/disk4/s4.hyper:rw:1G
stripe:s5:/mnt/disk5/s5.hyper:rw:1G
stripe:s6:/mnt/disk6/s6.hyper:rw:1G
stripe:s7:/mnt/disk7/s7.hyper:rw:1G
parity:p0:/mnt/disk8/p0.hyper:rw:0044:4
parity:p1:/mnt/disk9/p1.hyper:rw:0044:4
parity:p2:/mnt/diska/p2.hyper:rw:0044:4
```

## Commands

```
lzply_hyper -c config.txt <command> [args]
```

* `-init [--force]` — validate the config; check each parent
  directory exists and is writable (if `rw`) and that the filesystem
  has room for the configured stripe sizes; create the empty stripe
  and parity files. Refuses to overwrite existing files without
  `--force`. An `ro` file must already exist (it is verified, never
  created).
* `write <file> [name]` — stripe a file into the volume. The name
  defaults to the file's basename. Refuses to overwrite an existing
  name (no overwrite in v1). Requires all stripes and parities `rw`,
  all stripe files present and the same size, and enough remaining
  capacity.
* `read <name> <out>` — read a file back out. Rebuilds a dead stripe
  via parity if needed, corrects bit rot via BCH, verifies SHA-256.
  Reports rebuilds and corrections.
* `list` — list the files in the volume (scans the parity-stripe
  index; uses the parity stripe with the most records).
* `check <name>` — verify a file (stripe parity + BCH + SHA-256),
  no output file.
* `-rebuild` — rebuild lost/corrupt stripes. Detects missing or
  wrong-size data stripes and parity stripes; reconstructs the data
  stripes from the surviving stripes + parity (P/Q/R as needed for
  1/2/3 losses); reconstructs a missing parity stripe from the data
  stripes. Rebuilt data goes to temp files and is renamed into place
  only on success, so a failed rebuild leaves the damaged files
  untouched. Reports what was rebuilt and what could **not** be
  rebuilt. Fails clearly, never silently returns wrong data.

## The index, and its failure mode

The index lives in the parity stripes: each file's record is appended
to every parity stripe, so `list` (and `read`, `check`, `-rebuild`)
scan the parity stripe with the most records. If **every** parity
stripe is dead but the data stripes are intact, the files are still
readable in principle — just unverifiable and unrecoverable, because
there is no record of their names, lengths, or hashes. That failure
mode is worth knowing, not hiding: keep at least one parity stripe
alive, and it does not matter which one.

`-rebuild` only detects missing or wrong-size stripes. Bit rot
*inside* a stripe file (right size, wrong bytes) is corrected on read
by BCH, but `-rebuild` does not rewrite a stripe file for bit rot
alone — it rebuilds a stripe from parity only when the stripe is
missing or the wrong size, and then only from parity, never from the
stripe's own possibly-corrupt old bytes.

## Read speed (measured)

Measured on the server (107.152.42.152, 4 vCPU, 3.8 GiB RAM) reading
a 100 MiB random file, poly `0044` (m=20, t=8), 3 parity stripes:

| operation | throughput |
|---|---|
| raw `cat` of the 8 stripe files (I/O floor) | 2,424 MiB/s |
| SHA-256 alone (`sha256sum`, 100 MiB) | 178 MiB/s |
| BCH syndrome alone (clean, 100 MiB) | 50.8 MiB/s |
| `lzply_hyper read` (100 MiB, 3 runs) | **35.2 / 34.0 / 35.4 MiB/s** |
| `lzply_hyper check` (100 MiB, 3 runs, no output) | **37.2 / 33.4 / 37.1 MiB/s** |

The BCH syndrome is the bottleneck: it is a serial LFSR remainder,
O(n·r/8), and it cannot be vectorised (each byte depends on the
previous remainder). Two targeted speedups in `bch.c` helped: fusing
the shift-left-by-one-byte and the table XOR into a single pass
(37 → 50.8 MiB/s for the syndrome), and computing the syndrome
straight from the input instead of copying the block first. The
read path is ~1.6x faster than the first build (22 → 35 MiB/s).
The remaining cost is the syndrome plus SHA-256; the transpose and
the I/O are negligible by comparison.

## Tests

`tests/run_hyper_tests.sh` — 56 tests, all passing on the server and
locally (no FUSE needed; it is a plain CLI). Run via `make test`
(which also runs the `bch_test` unit suite, 7,406 checks, and the
`lzply` archive suite, 147 tests).

Covered: config parsing (valid, mismatched poly/level, wrong stripe
count, bad size, 0/4 parities, unknown poly, missing config, `ro`
behaviour); `-init` (creates files, missing dir, insufficient space,
refuses overwrite, `--force`); write/read roundtrips (empty, 1 byte,
small, 1 MiB, 8 MiB random); bit-plane layout against hand-computed
values (4 cases); 1-stripe loss (delete + truncate, P); 2-stripe loss
(P+Q, and must-fail with only 1 parity); 3-stripe loss (P+Q+R, and
must-fail with only 2 parities); Q-alone rebuild when P is dead;
4-stripe loss (read and `-rebuild` must fail, never silently return
wrong data); bit-flip correction (3 bits in a data stripe → BCH
corrects, `read` and `check` report it; 3 bits in a parity stripe →
data still readable); parity-stripe loss (delete 1 → readable,
`-rebuild` restores; delete all → read fails, no index); capacity
overflow (exact fill, then a further write fails and the volume is
intact); SHA-256 tamper (12 bits in one BCH block → `check` and
`read` fail, no byte-identical output); read-speed benchmark.

## Demo (server, measured)

```
$ lzply_hyper -c cfg.txt -init
volume initialized: 8 data stripes, 3 parity stripe(s), poly 0x0044 t=8
$ lzply_hyper -c cfg.txt write big.bin big
wrote 'big': 104857600 bytes, stripe_off 0, stripe_len 13107200,
  bch 16020 bytes, sha256 a89cc4d7bcd5621d0b0fee033380628861aab5c48c0e2bab2218e211a3cb76bd
$ rm vol/s0.bin vol/s4.bin vol/s7.bin        # delete 3 data stripes
$ lzply_hyper -c cfg.txt read big big.out
read 'big': 104857600 bytes -> big.out (rebuilt 3 dead stripes)
$ cmp big.bin big.out                          # byte-identical
$ lzply_hyper -c cfg.txt -rebuild
rebuilt data stripe s0 (vol/s0.bin)
rebuilt data stripe s4 (vol/s4.bin)
rebuilt data stripe s7 (vol/s7.bin)
rebuild complete
$ lzply_hyper -c cfg.txt check big
check 'big': OK (104857600 bytes, sha256 verified)
```

Per-stripe files for the 100 MiB file: each data stripe 13,107,200
bytes; each parity stripe 13,123,319 bytes (record header + name +
parity + BCH). Overhead for 3 parities: 3 × 12.5% + 16,020 BCH bytes
+ 3 × 113-byte headers ≈ 37.5%.

## Build / install

```sh
make lzply_hyper        # links bch.o + sha256.o only (no liblz, no FUSE)
make install            # installs /usr/local/bin/lzply_hyper
make test               # bch_test + lzply suite + hyper suite
```

Sources: `lzply_hyper.c` (the whole tool), `bch.c`/`bch.h`/
`bch_polys.h` (BCH codec + the 82 polys), `sha256.c`/`sha256.h`
(in-tree SHA-256). Design draft: `lzply_hyper-design.md`.

lzply_hyper-design.md

The as-built design document (P/Q/R, measured read speed, resolved decisions)

# lzply_hyper — as-built design

Status: **BUILT, Nov 25, 2026.** CLI v1 complete, 56/56 tests pass on
the server and locally, installed at `/usr/local/bin/lzply_hyper`.
This document is the as-built record; the DRAFT it replaces is
superseded. Deviations from the draft are marked.

## The fork, resolved: both — two layers, not one

The user's design as sketched (BCH parity over the file, stored on the
parity stripe) recovers **bit rot only**. It cannot rebuild a dead stripe,
and the numbers say so plainly:

- BCH block, poly `0044` (m=20, t=8): max 131,051 data bytes per block,
  r = 160 parity bits = 20 bytes. Erasure capacity per block is 20 bytes.
- If one of 8 data stripes dies, a 131,051-byte block loses
  131,051 / 8 = 16,381 bytes — ~800x the erasure capacity.
- So BCH alone is the wrong tool for stripe loss. Stripe loss needs
  parity computed **across the stripes**, which is a different scheme
  from the BCH poly in the config.

As built, each file's parity record stores **two things**:

1. **Stripe-loss parity (REQUIRED — user: recover a lost stripe).**
   Independent parity stripes P, Q, R (see below). P alone rebuilds
   any ONE dead data stripe. Overhead is 1/8 (12.5%) per parity stripe.
2. **BCH parity over the file (bit-rot layer).** Computed over the whole
   original file with the config's poly, stored after the parity bytes.
   It corrects bit rot in the reassembled file — including a bit error
   that propagated through a stripe rebuild, since that lands as a
   single-bit error in the reassembled file. Cost is tiny: a 1 MiB file
   with poly `0044` is 8 BCH blocks x 20 bytes = 160 bytes total.
   A 100 MiB file is 16,020 BCH bytes.

Read order: reassemble surviving stripes -> rebuild any dead stripe
via parity -> BCH check/correct -> SHA-256 verify (reuse `sha256.c`).

## Config (user's format, as built)

```
stripe:<label>:<file>:<rw>:<size>
parity:<label>:<file>:<rw>:<poly>:<error_level>
```

- `rw`: `rw` = read-write, `ro` = read-only (never written; usable for
  reads/recovery). Anything else is a config error. A write requires
  every stripe and parity to be `rw`.
- `size`: capacity in bytes, K/M/G suffixes allowed (`10G`). A write
  that would exceed a stripe's remaining capacity fails instead of
  silently wrapping. `-init` checks the filesystem has room.
- `poly` is a **hex** id, authoritative; `error_level` must agree with
  it or the config is rejected. Poly id already fixes (m, t) — e.g.
  `0044` is m=20, t=8 (`bch_polys.h`), and `-e` level 4 also means t=8
  (`bch_t_for_level`: 1->1, 2->2, 3->4, 4->8, 5->16, 6->32). Example:
  `parity:p0:/mnt/disk6/parity.hyper:rw:0044:4`. (The parser reads the
  poly as hex — `0044` is 0x0044, m=20 — not decimal 44, which would be
  m=16. An optional `0x` prefix is accepted.)
- 8 data stripes (one per bit — the bit-plane layout fixes the count
  at 8). **1–3 parity stripes** (more than 3 is an error for v1).
  Poly lookup reuses `bch_poly_by_id()`; BCH encoding reuses
  `bch_encode_block` from `bch.c`. The poly is taken from the **first**
  parity line; all parity lines must agree on poly + error level.

## Striping: 8 bit-plane stripes

- Layout: 8 data stripes, one per bit. Byte i splits into its 8 bits,
  bit j goes to stripe j. Stripe j holds one bit of every byte, packed.
  For a 1 MiB file each stripe is 131,072 bytes, all eight exactly the
  same size. No compression anywhere.
- Write speed is not a constraint (user: write can be super slow), so
  bit-packing cost on write is acceptable.
- Read speed is the priority (user: read must be super fast). Read
  reassembles with an efficient 8x8 bit-matrix transpose (SWAR), not
  per-bit extraction. BCH syndrome is computed streaming on read
  (cheap linear pass); full correction runs only if the syndrome is
  non-zero. XOR/Q/R parity is read only when a stripe is dead. Full
  verify (parity + BCH + SHA-256) is the separate `check` command.
- I/O is 64 KiB bursts in memory, then one sequential write per stripe
  per burst.

## Parity stripes: independent P, Q, R (mirrors superseded)

DEVIATION from the draft: the draft proposed mirrored parity copies
as the v1 default, with Q as a later option. The user instead approved
2-stripe and 3-stripe loss options, which require **independent**
parities. So v1 has no mirrors — each parity stripe is a different
function of the data stripes:

- **P** (parity row 0) = XOR across the 8 data stripes. Recovers 1.
- **Q** (parity row 1) = GF(256) weighted sum, `sum g^j * s_j`, g = 2
  (field generator, primitive polynomial `0x11d`). Recovers a 2nd.
- **R** (parity row 2) = GF(256) weighted sum, `sum g^(2j) * s_j`.
  Recovers a 3rd.

Recovery solves the k×k coefficient system over GF(256) by
Gauss-Jordan inversion, per byte position, using whichever parity rows
survive (at least k of them). Q alone rebuilds 1 lost stripe if P is
dead. 4 lost stripes is beyond tolerance: `read` and `-rebuild` fail
clearly, never silently return wrong data.

## Where files live: index in the parity stripe

- `lzply_hyper` is a CLI in v1, not a mount:
  `lzply_hyper -c config.txt <command>`, with `-init [--force]`,
  `write <file> [name]`, `read <name> <out>`, `list`, `check <name>`,
  `-rebuild`.
- Each file's parity record, appended to each parity stripe: a 96-byte
  header (magic `HYPR`, version 1, parity_idx 0=P/1=Q/2=R, name_len,
  poly_id, t, npar, orig_len, stripe_off, stripe_len, parity_len,
  bch_len, sha256[32], header_crc32) + name + parity bytes
  (`stripe_len`) + BCH parity bytes. The record's `stripe_off` is the
  offset of this file's data in the stripe files (all 8 stripes hold
  the same offset for a given file).
- `list` scans the parity stripe with the most records (a truncated
  parity stripe yields a short index; a crashed write may leave one
  parity stripe one record ahead, and that record's stripe data is
  already on disk, so the longest index is the right one).
  If every parity stripe is dead but the data stripes are intact,
  files are still readable in principle — just unverifiable and
  unrecoverable. That failure mode is worth knowing, not hiding.
- `write` refuses to overwrite an existing name (no overwrite in v1).
  `-rebuild` writes rebuilt data stripes to temp files and renames
  them into place only on success; a failed rebuild leaves the damaged
  files untouched. A damaged stripe is rebuilt purely from parity,
  never from its own possibly-corrupt old bytes.
- `-rebuild` detects missing or wrong-size stripes only. Bit rot
  *inside* a stripe file (right size, wrong bytes) is corrected on
  read by BCH, but does not trigger a stripe rewrite.

## Worked example (8 data + 3 parities, 100 MiB file, poly 0044)

Measured on the server, Nov 25, 2026 (demo file sha256
`a89cc4d7bcd5621d0b0fee033380628861aab5c48c0e2bab2218e211a3cb76bd`):

- Each data stripe: 13,107,200 bytes. Each parity stripe:
  13,123,319 bytes (record header + name + parity + BCH).
- BCH parity: 16,020 bytes. SHA-256: 32 bytes in the header.
- Overhead for 3 parities: 3 × 12.5% + 16,020 BCH bytes ≈ 37.5%.
- Survives: any 1, 2, or 3 dead data stripes (via P, P+Q, P+Q+R),
  a dead parity stripe (data still readable, `-rebuild` restores it),
  or scattered bit errors up to t=8 per 131 KiB BCH block.
- Does not survive: 4 dead data stripes, or all parity stripes dead
  (no index — files unreadable by name, though the data stripes are
  intact), or more than t bit errors in the same BCH block (detected
  by SHA-256, reported, never silently returned).

## Read speed (measured, server)

100 MiB random file, poly `0044`, 3 parities:

| operation | throughput |
|---|---|
| raw `cat` of the 8 stripe files | 2,424 MiB/s |
| SHA-256 alone | 178 MiB/s |
| BCH syndrome alone (clean) | 50.8 MiB/s |
| `lzply_hyper read` | 35.2 / 34.0 / 35.4 MiB/s |
| `lzply_hyper check` | 37.2 / 33.4 / 37.1 MiB/s |

First build read at ~22 MiB/s. Two `bch.c` speedups raised it to
~35 MiB/s: fusing the remainder shift-left-by-one-byte and the table
XOR into a single pass (syndrome 37 → 50.8 MiB/s), and computing the
syndrome straight from the input instead of copying the block first.
The BCH syndrome is the bottleneck — a serial LFSR remainder,
O(n·r/8), not vectorisable (each byte depends on the previous
remainder). The transpose and the I/O are negligible by comparison.

## Decisions (all resolved)

1. Recovery scope: 1/2/3 dead stripes via P/Q/R (user approved the
   2- and 3-stripe loss options).
2. Extra parity stripes: independent P/Q/R, not mirrors (mirrors
   superseded — they cannot add tolerance for a 2nd dead stripe).
3. CLI v1, not a mount.
4. Burst size 64 KiB.
5. No overwrite on `write` in v1; no legacy format concerns (the
   format is new and can change freely).

tests/run_hyper_tests.sh

The 56-test hyper test suite

#!/bin/bash
# run_hyper_tests.sh - lzply_hyper test suite.
# Usage: run_hyper_tests.sh [path-to-lzply_hyper]
# ROOT is the lzply tree root (testdata/, testwork/, tests/ live under
# it): taken from $LZPLY_TEST_ROOT, else the parent of this script's
# directory (works for ~/workspace/lzply and for /opt/lzply/src).
# No FUSE needed (lzply_hyper is a plain CLI), so this runs locally
# and on the server.
set -u
HYPER="${1:-/opt/lzply/src/lzply_hyper}"
case "$HYPER" in
    /*) ;;
    *) HYPER="$(cd "$(dirname "$HYPER")" && pwd)/$(basename "$HYPER")" ;;
esac
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="${LZPLY_TEST_ROOT:-$(dirname "$SCRIPT_DIR")}"
WORK=$ROOT/testwork-hyper
CORRUPT_BITS=/tmp/corrupt_bits_hyper
PASS=0
FAIL=0

ok()  { PASS=$((PASS+1)); echo "PASS: $1"; }
bad() { FAIL=$((FAIL+1)); echo "FAIL: $1"; }

rm -rf "$WORK"
mkdir -p "$WORK"
gcc -O2 -Wall -o "$CORRUPT_BITS" "$ROOT/tests/corrupt_bits.c" || { echo "cannot build corrupt_bits helper"; exit 1; }
[ -x "$HYPER" ] || { echo "lzply_hyper binary not found: $HYPER"; exit 1; }

# mkcfg <dir> <npar> [poly] [level] [stripe-size]
# Writes $dir/cfg.txt (8 stripes + npar parities) and $dir/vol/.
# Defaults: poly 0044 (m=20 t=8), level 4, stripe size 64M.
mkcfg() {
    local dir=$1 npar=${2:-3} poly=${3:-0044} lvl=${4:-4} sz=${5:-64M}
    mkdir -p "$dir/vol"
    : > "$dir/cfg.txt"
    for j in 0 1 2 3 4 5 6 7; do
        echo "stripe:s$j:$dir/vol/s$j.bin:rw:$sz" >> "$dir/cfg.txt"
    done
    for ((p = 0; p < npar; p++)); do
        echo "parity:p$p:$dir/vol/p$p.bin:rw:$poly:$lvl" >> "$dir/cfg.txt"
    done
}

# mkvol <dir> [npar] [poly] [level] [stripe-size]
# mkcfg + -init. Returns non-zero if -init fails.
mkvol() {
    mkcfg "$@"
    "$HYPER" -c "$1/cfg.txt" -init >/dev/null 2>&1
}

# randfile <path> <bytes> : deterministic pseudo-random file.
randfile() {
    python3 -c "
import random,sys
random.seed(12345)
n=$2
with open('$1','wb') as f:
    while n > 0:
        chunk = min(n, 65536)
        f.write(bytes(random.getrandbits(8) for _ in range(chunk)))
        n -= chunk
"
}

# byte_at <file> <offset> : 2-digit hex of the byte at offset (via od).
byte_at() { od -An -tx1 -v -j "$2" -N 1 "$1" | tr -d ' \n'; }

# --- 1. Config parsing -----------------------------------------------
T=$WORK/cfg
mkdir -p "$T"
# 1a. valid config loads (init succeeds)
mkvol "$T/valid" 3 >/dev/null 2>&1 && [ -f "$T/valid/vol/s0.bin" ] && \
    ok "config: valid 8+3 parses and -init creates files" || bad "config: valid 8+3 parses and -init creates files"
# 1b. mismatched poly/error_level (0044 is t=8, level 5 is t=16)
mkcfg "$T/badlevel" 1 0044 5
"$HYPER" -c "$T/badlevel/cfg.txt" -init >/dev/null 2>&1 && \
    bad "config: poly 0044 + level 5 (t=16) rejected" || ok "config: poly 0044 + level 5 (t=16) rejected"
# 1c. wrong data-stripe count (7 stripes)
mkdir -p "$T/seven/vol"
: > "$T/seven/cfg.txt"
for j in 0 1 2 3 4 5 6; do echo "stripe:s$j:$T/seven/vol/s$j.bin:rw:10M" >> "$T/seven/cfg.txt"; done
echo "parity:p0:$T/seven/vol/p0.bin:rw:0044:4" >> "$T/seven/cfg.txt"
"$HYPER" -c "$T/seven/cfg.txt" -init >/dev/null 2>&1 && \
    bad "config: 7 data stripes rejected" || ok "config: 7 data stripes rejected"
# 1d. bad size
mkdir -p "$T/badsize/vol"
: > "$T/badsize/cfg.txt"
for j in 0 1 2 3 4 5 6 7; do echo "stripe:s$j:$T/badsize/vol/s$j.bin:rw:10X" >> "$T/badsize/cfg.txt"; done
echo "parity:p0:$T/badsize/vol/p0.bin:rw:0044:4" >> "$T/badsize/cfg.txt"
"$HYPER" -c "$T/badsize/cfg.txt" -init >/dev/null 2>&1 && \
    bad "config: bad size '10X' rejected" || ok "config: bad size '10X' rejected"
# 1e. mismatched poly across parity lines
mkdir -p "$T/mismatch/vol"
: > "$T/mismatch/cfg.txt"
for j in 0 1 2 3 4 5 6 7; do echo "stripe:s$j:$T/mismatch/vol/s$j.bin:rw:10M" >> "$T/mismatch/cfg.txt"; done
echo "parity:p0:$T/mismatch/vol/p0.bin:rw:0044:4" >> "$T/mismatch/cfg.txt"
echo "parity:p1:$T/mismatch/vol/p1.bin:rw:003a:4" >> "$T/mismatch/cfg.txt"
"$HYPER" -c "$T/mismatch/cfg.txt" -init >/dev/null 2>&1 && \
    bad "config: parity lines disagreeing on poly rejected" || ok "config: parity lines disagreeing on poly rejected"
# 1f. 4 parity stripes (more than 3 is an error for v1)
mkcfg "$T/fourpar" 4
"$HYPER" -c "$T/fourpar/cfg.txt" -init >/dev/null 2>&1 && \
    bad "config: 4 parity stripes rejected" || ok "config: 4 parity stripes rejected"
# 1g. 0 parity stripes
mkdir -p "$T/nopar/vol"
: > "$T/nopar/cfg.txt"
for j in 0 1 2 3 4 5 6 7; do echo "stripe:s$j:$T/nopar/vol/s$j.bin:rw:10M" >> "$T/nopar/cfg.txt"; done
"$HYPER" -c "$T/nopar/cfg.txt" -init >/dev/null 2>&1 && \
    bad "config: 0 parity stripes rejected" || ok "config: 0 parity stripes rejected"
# 1h. unknown poly id
mkcfg "$T/badpoly" 1 00ff 4
"$HYPER" -c "$T/badpoly/cfg.txt" -init >/dev/null 2>&1 && \
    bad "config: unknown poly 00ff rejected" || ok "config: unknown poly 00ff rejected"
# 1i. missing config file
"$HYPER" -c "$T/does-not-exist.txt" -init >/dev/null 2>&1 && \
    bad "config: missing config file rejected" || ok "config: missing config file rejected"
# 1j. ro stripe: write must fail, read must work after a rw write
# (build the volume rw, write a file, then flip one stripe to ro)
mkvol "$T/rotest" 1 >/dev/null 2>&1
echo "ro test content" > "$T/rotest/f.txt"
"$HYPER" -c "$T/rotest/cfg.txt" write "$T/rotest/f.txt" f.txt >/dev/null 2>&1
sed -i 's|/vol/s0.bin:rw:|/vol/s0.bin:ro:|' "$T/rotest/cfg.txt"
"$HYPER" -c "$T/rotest/cfg.txt" write "$T/rotest/f.txt" f2.txt >/dev/null 2>&1 && \
    bad "config: write with an ro stripe rejected" || ok "config: write with an ro stripe rejected"
"$HYPER" -c "$T/rotest/cfg.txt" read f.txt "$T/rotest/f.out" >/dev/null 2>&1 && \
    cmp -s "$T/rotest/f.txt" "$T/rotest/f.out" && \
    ok "config: read works with an ro stripe" || bad "config: read works with an ro stripe"

# --- 2. -init ----------------------------------------------------------
T=$WORK/init
mkdir -p "$T"
# 2a. creates all 11 files, empty
mkvol "$T/a" 3 >/dev/null 2>&1
n=$(ls "$T/a/vol" | wc -l)
[ "$n" = 11 ] && [ ! -s "$T/a/vol/s0.bin" ] && [ ! -s "$T/a/vol/p0.bin" ] && \
    ok "-init: creates 8 stripes + 3 parities, all empty" || bad "-init: creates 8 stripes + 3 parities, all empty (n=$n)"
# 2b. missing parent directory
mkdir -p "$T/missing"
: > "$T/missing/cfg.txt"
for j in 0 1 2 3 4 5 6 7; do echo "stripe:s$j:$T/missing/nodir/s$j.bin:rw:10M" >> "$T/missing/cfg.txt"; done
echo "parity:p0:$T/missing/nodir/p0.bin:rw:0044:4" >> "$T/missing/cfg.txt"
"$HYPER" -c "$T/missing/cfg.txt" -init >/dev/null 2>&1 && \
    bad "-init: missing parent directory rejected" || ok "-init: missing parent directory rejected"
# 2c. insufficient space (8 x 100T can never fit)
mkcfg "$T/nospace" 1 0044 4 100T
"$HYPER" -c "$T/nospace/cfg.txt" -init >/dev/null 2>&1 && \
    bad "-init: insufficient space rejected" || ok "-init: insufficient space rejected"
# 2d. refuses to overwrite without --force
mkvol "$T/ow" 1 >/dev/null 2>&1
"$HYPER" -c "$T/ow/cfg.txt" -init >/dev/null 2>&1 && \
    bad "-init: refuses to overwrite existing files" || ok "-init: refuses to overwrite existing files"
# 2e. --force replaces
"$HYPER" -c "$T/ow/cfg.txt" -init --force >/dev/null 2>&1 && \
    [ ! -s "$T/ow/vol/s0.bin" ] && \
    ok "-init --force: replaces existing files" || bad "-init --force: replaces existing files"

# --- 3. Write/read roundtrip ------------------------------------------
T=$WORK/rt
mkdir -p "$T"
mkvol "$T/v" 3 >/dev/null 2>&1
: > "$T/empty.bin"
"$HYPER" -c "$T/v/cfg.txt" write "$T/empty.bin" empty >/dev/null 2>&1 && \
"$HYPER" -c "$T/v/cfg.txt" read empty "$T/empty.out" >/dev/null 2>&1 && \
cmp -s "$T/empty.bin" "$T/empty.out" && \
    ok "roundtrip: empty file" || bad "roundtrip: empty file"
printf 'x' > "$T/one.bin"
"$HYPER" -c "$T/v/cfg.txt" write "$T/one.bin" one >/dev/null 2>&1 && \
"$HYPER" -c "$T/v/cfg.txt" read one "$T/one.out" >/dev/null 2>&1 && \
cmp -s "$T/one.bin" "$T/one.out" && \
    ok "roundtrip: 1-byte file" || bad "roundtrip: 1-byte file"
printf 'hello hyper world, striped across 8 bit-planes.' > "$T/small.txt"
"$HYPER" -c "$T/v/cfg.txt" write "$T/small.txt" small >/dev/null 2>&1 && \
"$HYPER" -c "$T/v/cfg.txt" read small "$T/small.out" >/dev/null 2>&1 && \
cmp -s "$T/small.txt" "$T/small.out" && \
    ok "roundtrip: small text file" || bad "roundtrip: small text file"
randfile "$T/rand1m.bin" 1048576
"$HYPER" -c "$T/v/cfg.txt" write "$T/rand1m.bin" rand1m >/dev/null 2>&1 && \
"$HYPER" -c "$T/v/cfg.txt" read rand1m "$T/rand1m.out" >/dev/null 2>&1 && \
cmp -s "$T/rand1m.bin" "$T/rand1m.out" && \
    ok "roundtrip: 1 MiB random file" || bad "roundtrip: 1 MiB random file"
randfile "$T/rand8m.bin" 8388608
"$HYPER" -c "$T/v/cfg.txt" write "$T/rand8m.bin" rand8m >/dev/null 2>&1 && \
"$HYPER" -c "$T/v/cfg.txt" read rand8m "$T/rand8m.out" >/dev/null 2>&1 && \
cmp -s "$T/rand8m.bin" "$T/rand8m.out" && \
    ok "roundtrip: 8 MiB random file" || bad "roundtrip: 8 MiB random file"
# list shows all 5 files
"$HYPER" -c "$T/v/cfg.txt" list 2>/dev/null | grep -c "^  " | grep -q "^5$" && \
    ok "list: shows all 5 files" || bad "list: shows all 5 files"
# check passes on a clean file
"$HYPER" -c "$T/v/cfg.txt" check rand1m >/dev/null 2>&1 && \
    ok "check: clean file passes" || bad "check: clean file passes"
# duplicate write refused (no overwrite in v1)
"$HYPER" -c "$T/v/cfg.txt" write "$T/small.txt" small >/dev/null 2>&1 && \
    bad "write: duplicate name refused" || ok "write: duplicate name refused"

# --- 4. Bit-plane layout (hand-computed) -------------------------------
# A fresh volume per case so each stripe file holds only this file.
# Case A: bytes 01 02 04 08 10 20 40 80 -> stripes are themselves.
T=$WORK/layout
mkdir -p "$T"
mkvol "$T/a" 1 >/dev/null 2>&1
python3 -c "open('$T/a/in.bin','wb').write(bytes([0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80]))"
"$HYPER" -c "$T/a/cfg.txt" write "$T/a/in.bin" in >/dev/null 2>&1
la_ok=1
for j in 0 1 2 3 4 5 6 7; do
    want=$(printf '%02x' $((1 << j)))
    got=$(byte_at "$T/a/vol/s$j.bin" 0)
    [ "$got" = "$want" ] || la_ok=0
done
[ $la_ok = 1 ] && ok "layout: 01 02 04 08 10 20 40 80 -> stripes are themselves" || bad "layout: 01 02 04 08 10 20 40 80 -> stripes are themselves"
# Case B: bytes FF 00 00 00 00 00 00 00 -> every stripe is 01.
mkvol "$T/b" 1 >/dev/null 2>&1
python3 -c "open('$T/b/in.bin','wb').write(bytes([0xFF,0,0,0,0,0,0,0]))"
"$HYPER" -c "$T/b/cfg.txt" write "$T/b/in.bin" in >/dev/null 2>&1
lb_ok=1
for j in 0 1 2 3 4 5 6 7; do
    got=$(byte_at "$T/b/vol/s$j.bin" 0)
    [ "$got" = "01" ] || lb_ok=0
done
[ $lb_ok = 1 ] && ok "layout: FF 00..00 -> every stripe is 01" || bad "layout: FF 00..00 -> every stripe is 01"
# Case C: bytes 80 40 20 10 08 04 02 01 -> stripes are themselves (anti-diagonal).
mkvol "$T/c" 1 >/dev/null 2>&1
python3 -c "open('$T/c/in.bin','wb').write(bytes([0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01]))"
"$HYPER" -c "$T/c/cfg.txt" write "$T/c/in.bin" in >/dev/null 2>&1
lc_ok=1
for j in 0 1 2 3 4 5 6 7; do
    want=$(printf '%02x' $((0x80 >> j)))
    got=$(byte_at "$T/c/vol/s$j.bin" 0)
    [ "$got" = "$want" ] || lc_ok=0
done
[ $lc_ok = 1 ] && ok "layout: 80 40 20 10 08 04 02 01 -> stripes are themselves" || bad "layout: 80 40 20 10 08 04 02 01 -> stripes are themselves"
# Case D: 16 bytes 00..0F. First group is 00..07 (all zero -> stripes 00);
# second group 08..0F: stripe j byte = bit j of 08..0F packed.
# byte 08=00001000 ... 0F=00001111. stripe0: bits0 of 08..0F = 0,1,0,1,0,1,0,1
#   (byte p of the group sits at bit p) = 0b10101010 = 0xAA. stripe1: bits1 =
#   0,0,1,1,0,0,1,1 -> 0b11001100 = 0xCC. stripe2: 0,0,0,0,1,1,1,1 -> 0xF0.
#   stripe3: 1,1,1,1,1,1,1,1 -> 0xFF. stripes 4-7: all zero.
mkvol "$T/d" 1 >/dev/null 2>&1
python3 -c "open('$T/d/in.bin','wb').write(bytes(range(16)))"
"$HYPER" -c "$T/d/cfg.txt" write "$T/d/in.bin" in >/dev/null 2>&1
ld_ok=1
for j in 0 1 2 3 4 5 6 7; do :; done
[ "$(byte_at "$T/d/vol/s0.bin" 1)" = "aa" ] || ld_ok=0
[ "$(byte_at "$T/d/vol/s1.bin" 1)" = "cc" ] || ld_ok=0
[ "$(byte_at "$T/d/vol/s2.bin" 1)" = "f0" ] || ld_ok=0
[ "$(byte_at "$T/d/vol/s3.bin" 1)" = "ff" ] || ld_ok=0
[ "$(byte_at "$T/d/vol/s4.bin" 1)" = "00" ] || ld_ok=0
[ "$(byte_at "$T/d/vol/s7.bin" 1)" = "00" ] || ld_ok=0
[ $ld_ok = 1 ] && ok "layout: bytes 00..0F second group -> AA CC F0 FF 00.." || bad "layout: bytes 00..0F second group -> AA CC F0 FF 00.."

# --- 5. 1-stripe loss (1 parity) ---------------------------------------
T=$WORK/loss1
mkdir -p "$T"
mkvol "$T/v" 1 >/dev/null 2>&1
randfile "$T/f.bin" 1048576
"$HYPER" -c "$T/v/cfg.txt" write "$T/f.bin" f >/dev/null 2>&1
rm "$T/v/vol/s3.bin"
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out" >/dev/null 2>&1 && \
cmp -s "$T/f.bin" "$T/f.out" && \
    ok "1-stripe loss: read rebuilds via P, byte-identical" || bad "1-stripe loss: read rebuilds via P, byte-identical"
"$HYPER" -c "$T/v/cfg.txt" -rebuild >/dev/null 2>&1 && \
[ -f "$T/v/vol/s3.bin" ] && \
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out2" >/dev/null 2>&1 && \
cmp -s "$T/f.bin" "$T/f.out2" && \
    ok "1-stripe loss: -rebuild restores the stripe" || bad "1-stripe loss: -rebuild restores the stripe"
# corrupt (not just delete) 1 stripe: truncate it to half
python3 -c "
p='$T/v/vol/s5.bin'
d=open(p,'rb').read()
open(p,'wb').write(d[:len(d)//2])
"
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out3" >/dev/null 2>&1 && \
cmp -s "$T/f.bin" "$T/f.out3" && \
    ok "1-stripe loss: truncated stripe reads back via P" || bad "1-stripe loss: truncated stripe reads back via P"
"$HYPER" -c "$T/v/cfg.txt" -rebuild >/dev/null 2>&1 && \
"$HYPER" -c "$T/v/cfg.txt" check f >/dev/null 2>&1 && \
    ok "1-stripe loss: -rebuild restores a truncated stripe" || bad "1-stripe loss: -rebuild restores a truncated stripe"

# --- 6. 2-stripe loss (2 parities, P+Q) --------------------------------
T=$WORK/loss2
mkdir -p "$T"
mkvol "$T/v" 2 >/dev/null 2>&1
randfile "$T/f.bin" 1048576
"$HYPER" -c "$T/v/cfg.txt" write "$T/f.bin" f >/dev/null 2>&1
rm "$T/v/vol/s1.bin" "$T/v/vol/s6.bin"
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out" >/dev/null 2>&1 && \
cmp -s "$T/f.bin" "$T/f.out" && \
    ok "2-stripe loss: read rebuilds via P+Q, byte-identical" || bad "2-stripe loss: read rebuilds via P+Q, byte-identical"
"$HYPER" -c "$T/v/cfg.txt" -rebuild >/dev/null 2>&1 && \
[ -f "$T/v/vol/s1.bin" ] && [ -f "$T/v/vol/s6.bin" ] && \
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out2" >/dev/null 2>&1 && \
cmp -s "$T/f.bin" "$T/f.out2" && \
    ok "2-stripe loss: -rebuild restores both stripes" || bad "2-stripe loss: -rebuild restores both stripes"
# 2-stripe loss must FAIL with only 1 parity stripe
mkvol "$T/v1" 1 >/dev/null 2>&1
"$HYPER" -c "$T/v1/cfg.txt" write "$T/f.bin" f >/dev/null 2>&1
rm "$T/v1/vol/s1.bin" "$T/v1/vol/s6.bin"
"$HYPER" -c "$T/v1/cfg.txt" read f "$T/f.out" >/dev/null 2>&1 && \
    bad "2-stripe loss: read with only 1 parity must FAIL" || ok "2-stripe loss: read with only 1 parity must FAIL"

# --- 7. 3-stripe loss (3 parities, P+Q+R) ------------------------------
T=$WORK/loss3
mkdir -p "$T"
mkvol "$T/v" 3 >/dev/null 2>&1
randfile "$T/f.bin" 1048576
"$HYPER" -c "$T/v/cfg.txt" write "$T/f.bin" f >/dev/null 2>&1
rm "$T/v/vol/s0.bin" "$T/v/vol/s4.bin" "$T/v/vol/s7.bin"
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out" >/dev/null 2>&1 && \
cmp -s "$T/f.bin" "$T/f.out" && \
    ok "3-stripe loss: read rebuilds via P+Q+R, byte-identical" || bad "3-stripe loss: read rebuilds via P+Q+R, byte-identical"
"$HYPER" -c "$T/v/cfg.txt" -rebuild >/dev/null 2>&1 && \
[ -f "$T/v/vol/s0.bin" ] && [ -f "$T/v/vol/s4.bin" ] && [ -f "$T/v/vol/s7.bin" ] && \
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out2" >/dev/null 2>&1 && \
cmp -s "$T/f.bin" "$T/f.out2" && \
    ok "3-stripe loss: -rebuild restores all three stripes" || bad "3-stripe loss: -rebuild restores all three stripes"
# 3-stripe loss must FAIL with only 2 parity stripes
mkvol "$T/v2" 2 >/dev/null 2>&1
"$HYPER" -c "$T/v2/cfg.txt" write "$T/f.bin" f >/dev/null 2>&1
rm "$T/v2/vol/s0.bin" "$T/v2/vol/s4.bin" "$T/v2/vol/s7.bin"
"$HYPER" -c "$T/v2/cfg.txt" read f "$T/f.out" >/dev/null 2>&1 && \
    bad "3-stripe loss: read with only 2 parities must FAIL" || ok "3-stripe loss: read with only 2 parities must FAIL"
# Q alone rebuilds 1 lost stripe when P is dead (parity-row independence)
mkvol "$T/vq" 3 >/dev/null 2>&1
"$HYPER" -c "$T/vq/cfg.txt" write "$T/f.bin" f >/dev/null 2>&1
rm "$T/vq/vol/s2.bin" "$T/vq/vol/p0.bin"
"$HYPER" -c "$T/vq/cfg.txt" read f "$T/f.out" >/dev/null 2>&1 && \
cmp -s "$T/f.bin" "$T/f.out" && \
    ok "recovery: Q alone rebuilds 1 lost stripe when P is dead" || bad "recovery: Q alone rebuilds 1 lost stripe when P is dead"

# --- 8. 4-stripe loss (beyond tolerance) -------------------------------
T=$WORK/loss4
mkdir -p "$T"
mkvol "$T/v" 3 >/dev/null 2>&1
randfile "$T/f.bin" 1048576
"$HYPER" -c "$T/v/cfg.txt" write "$T/f.bin" f >/dev/null 2>&1
rm "$T/v/vol/s0.bin" "$T/v/vol/s2.bin" "$T/v/vol/s5.bin" "$T/v/vol/s7.bin"
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out" >/dev/null 2>&1 && \
    bad "4-stripe loss: read must FAIL, never silently return wrong data" || ok "4-stripe loss: read must FAIL, never silently return wrong data"
[ -f "$T/f.out" ] && cmp -s "$T/f.bin" "$T/f.out" && \
    bad "4-stripe loss: no output file may be byte-identical" || ok "4-stripe loss: no byte-identical output produced"
"$HYPER" -c "$T/v/cfg.txt" -rebuild >/dev/null 2>&1 && \
    bad "4-stripe loss: -rebuild must FAIL" || ok "4-stripe loss: -rebuild must FAIL"

# --- 9. Bit-flip correction (BCH) ---------------------------------------
T=$WORK/bitflip
mkdir -p "$T"
mkvol "$T/v" 3 >/dev/null 2>&1
randfile "$T/f.bin" 1048576
"$HYPER" -c "$T/v/cfg.txt" write "$T/f.bin" f >/dev/null 2>&1
# flip 3 bits in one data stripe (poly 0044, t=8: correctable)
"$CORRUPT_BITS" "$T/v/vol/s4.bin" 7 3 >/dev/null 2>&1
out=$("$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out" 2>&1)
rc=$?
cmp -s "$T/f.bin" "$T/f.out" && [ $rc = 0 ] && \
    ok "bit-flip: 3 flipped bits in a stripe, read corrects via BCH" || bad "bit-flip: 3 flipped bits in a stripe, read corrects via BCH (rc=$rc)"
echo "$out" | grep -q "BCH corrected 3 bit" && \
    ok "bit-flip: read reports the correction" || bad "bit-flip: read reports the correction (got: $out)"
# check reports the correction too
out=$("$HYPER" -c "$T/v/cfg.txt" check f 2>&1)
echo "$out" | grep -q "BCH corrected 3 bit" && \
    ok "bit-flip: check reports the correction" || bad "bit-flip: check reports the correction (got: $out)"
# flip 3 bits in a parity stripe's parity-bytes region (offset 200..100000,
# well inside the parity bytes for a 1 MiB file; the header and BCH bytes
# are untouched): data is intact, read must still work
"$CORRUPT_BITS" "$T/v/vol/p0.bin" 11 3 200 100000 >/dev/null 2>&1
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out2" >/dev/null 2>&1 && \
cmp -s "$T/f.bin" "$T/f.out2" && \
    ok "bit-flip: 3 flipped bits in a parity stripe, data still readable" || bad "bit-flip: 3 flipped bits in a parity stripe, data still readable"

# --- 10. Parity stripe loss ---------------------------------------------
T=$WORK/parloss
mkdir -p "$T"
mkvol "$T/v" 3 >/dev/null 2>&1
randfile "$T/f.bin" 1048576
"$HYPER" -c "$T/v/cfg.txt" write "$T/f.bin" f >/dev/null 2>&1
rm "$T/v/vol/p1.bin"
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out" >/dev/null 2>&1 && \
cmp -s "$T/f.bin" "$T/f.out" && \
    ok "parity loss: delete 1 parity stripe, data still readable" || bad "parity loss: delete 1 parity stripe, data still readable"
"$HYPER" -c "$T/v/cfg.txt" -rebuild >/dev/null 2>&1 && \
[ -f "$T/v/vol/p1.bin" ] && \
"$HYPER" -c "$T/v/cfg.txt" list 2>/dev/null | grep -q "f " && \
    ok "parity loss: -rebuild restores the parity stripe" || bad "parity loss: -rebuild restores the parity stripe"
# delete ALL parity stripes: data is still readable in principle, but
# the index is gone, so read must fail clearly (documented failure mode)
rm "$T/v/vol/p0.bin" "$T/v/vol/p1.bin" "$T/v/vol/p2.bin"
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out2" >/dev/null 2>&1 && \
    bad "parity loss: all parity stripes dead, read must FAIL (no index)" || ok "parity loss: all parity stripes dead, read must FAIL (no index)"

# --- 11. Capacity overflow ----------------------------------------------
T=$WORK/cap
mkdir -p "$T"
mkvol "$T/v" 1 0044 4 1K >/dev/null 2>&1
randfile "$T/big.bin" 8192
"$HYPER" -c "$T/v/cfg.txt" write "$T/big.bin" big >/dev/null 2>&1 && \
    ok "capacity: 8 KiB file exactly fills 1 KiB stripes" || bad "capacity: 8 KiB file exactly fills 1 KiB stripes"
randfile "$T/small.bin" 64
"$HYPER" -c "$T/v/cfg.txt" write "$T/small.bin" small >/dev/null 2>&1 && \
    bad "capacity: write past the stripe size must FAIL" || ok "capacity: write past the stripe size must FAIL"
# and the first file is still intact
"$HYPER" -c "$T/v/cfg.txt" read big "$T/big.out" >/dev/null 2>&1 && \
cmp -s "$T/big.bin" "$T/big.out" && \
    ok "capacity: failed write leaves the volume intact" || bad "capacity: failed write leaves the volume intact"

# --- 12. SHA-256 verification (tamper) -----------------------------------
T=$WORK/tamper
mkdir -p "$T"
mkvol "$T/v" 3 >/dev/null 2>&1
randfile "$T/f.bin" 1048576
"$HYPER" -c "$T/v/cfg.txt" write "$T/f.bin" f >/dev/null 2>&1
# flip 12 bits in the first 1024 bytes of a data stripe: those map to
# file bytes 0..8191, all inside BCH block 0 (poly 0044, t=8, max block
# 131,051 bytes), so 12 errors > t=8 and the block is uncorrectable.
# (Flipping 12 bits spread over the whole stripe would land ~1-2 per
# block and be correctable — that is the bit-flip test above, not this one.)
"$CORRUPT_BITS" "$T/v/vol/s6.bin" 99 12 0 1024 >/dev/null 2>&1
"$HYPER" -c "$T/v/cfg.txt" check f >/dev/null 2>&1 && \
    bad "tamper: 12 flipped bits in one BCH block, check must FAIL" || ok "tamper: 12 flipped bits in one BCH block, check must FAIL"
"$HYPER" -c "$T/v/cfg.txt" read f "$T/f.out" >/dev/null 2>&1 && \
    bad "tamper: 12 flipped bits in one BCH block, read must FAIL" || ok "tamper: 12 flipped bits in one BCH block, read must FAIL"
[ -f "$T/f.out" ] && cmp -s "$T/f.bin" "$T/f.out" && \
    bad "tamper: no byte-identical output may be produced" || ok "tamper: no byte-identical output produced"

# --- 13. Read-speed benchmark --------------------------------------------
T=$WORK/bench
mkdir -p "$T"
mkvol "$T/v" 3 >/dev/null 2>&1
randfile "$T/big.bin" 33554432
"$HYPER" -c "$T/v/cfg.txt" write "$T/big.bin" big >/dev/null 2>&1
t0=$(date +%s%N)
"$HYPER" -c "$T/v/cfg.txt" read big "$T/big.out" >/dev/null 2>&1
t1=$(date +%s%N)
cmp -s "$T/big.bin" "$T/big.out" || bad "bench: 32 MiB roundtrip byte-identical"
ms=$(( (t1 - t0) / 1000000 ))
mbps=$(python3 -c "print(f'{33554432 / ($ms / 1000.0) / 1048576:.1f}')")
echo "BENCH: read 32 MiB in ${ms} ms = ${mbps} MiB/s"
[ "$ms" -gt 0 ] && ok "bench: read 32 MiB in ${ms} ms (${mbps} MiB/s)" || bad "bench: read timing failed"

# --- summary --------------------------------------------------------------
echo
echo "lzply_hyper tests: $PASS passed, $FAIL failed"
[ "$FAIL" = 0 ]

tests/corrupt_bits.c

Bit-flip helper used by the BCH corruption tests

/* corrupt_bits.c - flip N bits in a file at pseudo-random positions.
 *
 * Usage: corrupt_bits <file> <seed> <count> [start] [end]
 * Flips `count` distinct bits in the byte range [start, end) by
 * toggling one bit per chosen byte position (each flipped bit is in
 * a different byte, so `count` bits = `count` bytes each changed by
 * exactly one bit). Prints the bit positions flipped.
 * Used by the lzply test suite to prove BCH bit-error recovery and
 * failure behaviour. Deterministic for a given seed.
 *
 * This is the bit-level counterpart of corrupt.c (which flips whole
 * bytes, i.e. up to 8 bit errors per byte, for Reed-Solomon).
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

static uint32_t st;

static uint32_t rnd(void)
{
    st ^= st << 13;
    st ^= st >> 17;
    st ^= st << 5;
    return st;
}

int main(int argc, char **argv)
{
    const char *path;
    long seed, count;
    long start = 0, end = -1;
    FILE *f;
    long size, i;
    uint8_t *data;
    long *picked;

    if (argc < 4) {
        fprintf(stderr, "Usage: %s <file> <seed> <count> [start] [end]\n",
                argv[0]);
        return 1;
    }
    path = argv[1];
    seed = atol(argv[2]);
    count = atol(argv[3]);
    if (argc >= 5)
        start = atol(argv[4]);
    if (argc >= 6)
        end = atol(argv[5]);
    st = (uint32_t)(seed ? seed : 1);

    f = fopen(path, "r+b");
    if (!f) {
        perror("open");
        return 1;
    }
    fseek(f, 0, SEEK_END);
    size = ftell(f);
    if (end < 0 || end > size)
        end = size;
    if (start < 0 || start >= end || count < 0 || count > (end - start) * 8) {
        fprintf(stderr, "corrupt_bits: bad range (start=%ld end=%ld count=%ld size=%ld)\n",
                start, end, count, size);
        fclose(f);
        return 1;
    }
    data = malloc((size_t)(end - start));
    if (!data) {
        fclose(f);
        return 1;
    }
    fseek(f, start, SEEK_SET);
    if (fread(data, 1, (size_t)(end - start), f) != (size_t)(end - start)) {
        fclose(f);
        free(data);
        return 1;
    }
    /* pick `count` distinct bit positions, one per byte at most, so
     * each flipped byte differs by exactly one bit. */
    picked = malloc(sizeof(long) * (size_t)(count ? count : 1));
    for (i = 0; i < count; i++) {
        long pos;
        int dup;
        do {
            pos = start + (long)(rnd() % (uint32_t)(end - start));
            dup = 0;
            for (long q = 0; q < i; q++)
                if (picked[q] == pos)
                    dup = 1;
        } while (dup);
        picked[i] = pos;
        data[pos - start] ^= (uint8_t)(1u << (rnd() % 8));
        printf("%ld ", pos);
    }
    printf("\n");
    fseek(f, start, SEEK_SET);
    fwrite(data, 1, (size_t)(end - start), f);
    fclose(f);
    free(data);
    free(picked);
    return 0;
}

Makefile

Build rules (lzply_hyper links bch.o + sha256.o only)

CC = gcc
CFLAGS = -O2 -Wall -Wextra
LDLIBS = -llz
PREFIX = /usr/local

all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper

# Shared core: the v4 archive format, the per-entry pipeline
# (lzip -> BCH), header I/O, scan, and filters. The
# 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
	ar rcs $@ $^

lzply_lib.o: lzply_lib.c lzply_lib.h bch.h bch_polys.h sha256.h
	$(CC) $(CFLAGS) -c -o $@ lzply_lib.c

sha256.o: sha256.c sha256.h
	$(CC) $(CFLAGS) -c -o $@ sha256.c

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
	$(CC) $(CFLAGS) -c -o $@ lzply.c

lzply: lzply.o liblzply.a
	$(CC) $(CFLAGS) -o $@ lzply.o liblzply.a $(LDLIBS)

# 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).
FUSE_CFLAGS = -D_FILE_OFFSET_BITS=64
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)

# Shared helpers for lzply_stat and lzply_heal (mount resolution via
# /proc, human-size formatting). No FUSE needed.
lzply_util.o: lzply_util.c lzply_lib.h lzply_util.h
	$(CC) $(CFLAGS) -c -o $@ lzply_util.c

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_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)

# Bit error rate detector. Read-only: decodes each BCH entry's stored
# bytes in memory and counts the corrected bit errors. Links the same
# shared util (mount resolution) as stat and heal.
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

# In-place platter refresher. Reads a file (or every regular file
# under a directory / mount point) and rewrites it over itself, with
# SHA-256 verification. Links the same shared util (mount
# resolution) as stat, heal and check.
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)

# 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
# liblz, no lzply_lib.
lzply_hyper.o: lzply_hyper.c bch.h bch_polys.h sha256.h
	$(CC) $(CFLAGS) -c -o $@ lzply_hyper.c

lzply_hyper: lzply_hyper.o bch.o sha256.o
	$(CC) $(CFLAGS) -o $@ 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

# 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
# NOT rebuilt by make. Regenerate manually after a re-crawl with:
#   python3 gen_bch_polys.py

# The shell suite lives in ./tests when built from the repo layout
# (~/workspace/lzply) and in ../tests when built from /opt/lzply/src.
# run_tests.sh derives its ROOT from its own location, so it works
# in both layouts; LZPLY_TEST_ROOT overrides it explicitly.
# NB: lzply_mount is a test dep on purpose — without it the mount
# tests in run_tests.sh silently skip after a `make clean`, even on a
# machine with /dev/fuse. (Needs libfuse3-dev; present on the server
# and the dev VM. The mount tests themselves still skip cleanly
# where /dev/fuse is absent.)
test: bch_test lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper
	./bch_test
	if [ -x ./tests/run_tests.sh ]; then \
		./tests/run_tests.sh ./lzply; \
	elif [ -x ../tests/run_tests.sh ]; then \
		../tests/run_tests.sh ./lzply; \
	else echo "run_tests.sh not found"; exit 1; fi
	if [ -x ./tests/run_hyper_tests.sh ]; then \
		./tests/run_hyper_tests.sh ./lzply_hyper; \
	elif [ -x ../tests/run_hyper_tests.sh ]; then \
		../tests/run_hyper_tests.sh ./lzply_hyper; \
	else echo "run_hyper_tests.sh not found"; exit 1; fi

install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper
	install -m 755 lzply $(PREFIX)/bin/lzply
	install -m 755 lzply_mount $(PREFIX)/bin/lzply_mount
	install -m 755 lzply_stat $(PREFIX)/bin/lzply_stat
	install -m 755 lzply_heal $(PREFIX)/bin/lzply_heal
	install -m 755 lzply_check $(PREFIX)/bin/lzply_check
	install -m 755 lzply_refresh $(PREFIX)/bin/lzply_refresh
	install -m 755 lzply_hyper $(PREFIX)/bin/lzply_hyper
	install -m 755 mount.lzply /sbin/mount.lzply

clean:
	rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper bch_test *.o liblzply.a

.PHONY: all test install clean

METHOD AND SOURCES

  • Bit-plane striping: byte i splits into its 8 bits, bit j to stripe j; reassembly by 8x8 bit-matrix transpose (SWAR). The layout is verified against hand-computed values, not just roundtrips.
  • Stripe-loss parity: P = XOR (RAID-5 style); Q and R = GF(256) weighted sums with coefficients g^j and g^(2j), g = 2, primitive polynomial 0x11d; recovery by Gauss-Jordan inversion of the k×k coefficient system over GF(256), k ≤ 3.
  • Bit-rot layer: binary BCH, systematic encoding by polynomial remainder, decoding by syndromes, Berlekamp-Massey, and Chien search (no magnitude step — binary). The 82 generator polynomials come from the rssearch exhaustive search (see the companion articles); every one was re-derived orbit-only from its parent's primitive polynomial and checked byte-identical before embedding. The codec was validated against its own properties (not against a reference implementation) by the harness described above.
  • SHA-256: a small in-tree FIPS 180-4 implementation (no OpenSSL dependency).
  • All numbers in this article are measured on the server (Debian 12, gcc 12.2.0), not copied from documentation.