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

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

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

No files matched your search

+61 -18
View File
@@ -3,6 +3,25 @@ CFLAGS = -O2 -Wall -Wextra
LDLIBS = -llz
PREFIX = /usr/local
# CUDA BCH remainder (optional): if nvcc is on PATH, bch_cuda.o is
# built and linked into liblzply.a and the tools; bch.c dispatches
# to it via weak symbols for large blobs. Without nvcc the build is
# unchanged (CPU-only). These definitions MUST stay above every rule
# that references $(CUDA_OBJ): make expands prerequisites when the
# rule is read, so a definition below the liblzply.a rule would
# silently leave bch_cuda.o out of the archive. NOTE: bch_cuda.o is
# still listed explicitly on each tool link line below, because the
# weak references from bch.o do not make the linker pull it out of
# the archive on their own.
NVCC ?= $(shell command -v nvcc 2>/dev/null)
CUDA_ARCH ?= sm_86
CUDA_OBJ =
CUDA_LIBS =
ifneq ($(NVCC),)
CUDA_OBJ = bch_cuda.o
CUDA_LIBS = -L$(dir $(NVCC))../lib64 -lcudart -lstdc++
endif
all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
# Shared core: the v5 archive format, the per-entry pipeline
@@ -10,7 +29,7 @@ all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyp
# command-line tool (lzply), the FUSE filesystem (lzply_mount),
# the statistics tool (lzply_stat) and the heal tool (lzply_heal)
# all link it.
liblzply.a: lzply_lib.o bch.o sha256.o
liblzply.a: lzply_lib.o bch.o sha256.o $(CUDA_OBJ)
ar rcs $@ $^
lzply_lib.o: lzply_lib.c lzply_lib.h bch.h bch_polys.h sha256.h
@@ -22,11 +41,35 @@ sha256.o: sha256.c sha256.h
bch.o: bch.c bch.h bch_polys.h
$(CC) $(CFLAGS) -c -o $@ bch.c
# CUDA BCH remainder rules (variables are defined at the top).
ifneq ($(NVCC),)
bch_cuda.o: bch_cuda.cu bch_cuda.h bch.h bch_polys.h
$(NVCC) -O3 -arch=$(CUDA_ARCH) -Xcompiler -O2 -c -o $@ bch_cuda.cu
bch_cuda_test.o: bch_cuda_test.c bch_cuda.h bch.h
$(CC) $(CFLAGS) -c -o $@ bch_cuda_test.c
bch_cuda_test: bch_cuda_test.o bch_cuda.o bch.o
$(NVCC) -arch=$(CUDA_ARCH) -o $@ bch_cuda_test.o bch_cuda.o bch.o
bch_bench.o: bch_bench.c bch.h
$(CC) $(CFLAGS) -c -o $@ bch_bench.c
bch_bench: bch_bench.o bch.o bch_cuda.o
$(NVCC) -arch=$(CUDA_ARCH) -o $@ bch_bench.o bch.o bch_cuda.o
else
bch_bench.o: bch_bench.c bch.h
$(CC) $(CFLAGS) -c -o $@ bch_bench.c
bch_bench: bch_bench.o bch.o
$(CC) $(CFLAGS) -o $@ bch_bench.o bch.o
endif
lzply.o: lzply.c lzply_lib.h bch.h bch_polys.h
$(CC) $(CFLAGS) -c -o $@ lzply.c
lzply: lzply.o liblzply.a
$(CC) $(CFLAGS) -o $@ lzply.o liblzply.a $(LDLIBS)
lzply: lzply.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply.o $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
# FUSE filesystem. Needs libfuse3-dev; no pkg-config on the server, so
# the flags are explicit (-D_FILE_OFFSET_BITS=64 is required by FUSE).
@@ -36,8 +79,8 @@ FUSE_LIBS = -lfuse3
lzply_mount.o: lzply_mount.c lzply_lib.h bch.h bch_polys.h
$(CC) $(CFLAGS) $(FUSE_CFLAGS) -c -o $@ lzply_mount.c
lzply_mount: lzply_mount.o liblzply.a
$(CC) $(CFLAGS) $(FUSE_CFLAGS) -o $@ lzply_mount.o liblzply.a $(LDLIBS) $(FUSE_LIBS)
lzply_mount: lzply_mount.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) $(FUSE_CFLAGS) -o $@ lzply_mount.o $(CUDA_OBJ) liblzply.a $(LDLIBS) $(FUSE_LIBS) $(CUDA_LIBS)
# Shared helpers for lzply_stat and lzply_heal (mount resolution via
# /proc, human-size formatting). No FUSE needed.
@@ -47,14 +90,14 @@ lzply_util.o: lzply_util.c lzply_lib.h lzply_util.h
lzply_stat.o: lzply_stat.c lzply_lib.h lzply_util.h
$(CC) $(CFLAGS) -c -o $@ lzply_stat.c
lzply_stat: lzply_stat.o lzply_util.o liblzply.a
$(CC) $(CFLAGS) -o $@ lzply_stat.o lzply_util.o liblzply.a $(LDLIBS)
lzply_stat: lzply_stat.o lzply_util.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply_stat.o lzply_util.o $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
lzply_heal.o: lzply_heal.c lzply_lib.h lzply_util.h
$(CC) $(CFLAGS) -c -o $@ lzply_heal.c
lzply_heal: lzply_heal.o lzply_util.o liblzply.a
$(CC) $(CFLAGS) -o $@ lzply_heal.o lzply_util.o liblzply.a $(LDLIBS)
lzply_heal: lzply_heal.o lzply_util.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply_heal.o lzply_util.o $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
# Bit error rate detector. Read-only: decodes each BCH entry's stored
# bytes in memory and counts the corrected bit errors. Links the same
@@ -62,8 +105,8 @@ lzply_heal: lzply_heal.o lzply_util.o liblzply.a
lzply_check.o: lzply_check.c lzply_lib.h lzply_util.h
$(CC) $(CFLAGS) -c -o $@ lzply_check.c
lzply_check: lzply_check.o lzply_util.o liblzply.a
$(CC) $(CFLAGS) -o $@ lzply_check.o lzply_util.o liblzply.a $(LDLIBS) -lm
lzply_check: lzply_check.o lzply_util.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply_check.o lzply_util.o $(CUDA_OBJ) liblzply.a $(LDLIBS) -lm $(CUDA_LIBS)
# In-place platter refresher. Reads a file (or every regular file
# under a directory / mount point) and rewrites it over itself, with
@@ -72,8 +115,8 @@ lzply_check: lzply_check.o lzply_util.o liblzply.a
lzply_refresh.o: lzply_refresh.c lzply_lib.h lzply_util.h
$(CC) $(CFLAGS) -c -o $@ lzply_refresh.c
lzply_refresh: lzply_refresh.o lzply_util.o liblzply.a
$(CC) $(CFLAGS) -o $@ lzply_refresh.o lzply_util.o liblzply.a $(LDLIBS)
lzply_refresh: lzply_refresh.o lzply_util.o liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply_refresh.o lzply_util.o $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
# Striped volume (bit-plane, 8 data stripes + 1-3 XOR/GF parity stripes
# + BCH). No compression, so it links only bch.o + sha256.o — no
@@ -102,8 +145,8 @@ liblzrs.a: lzrs_lib.o rs.o
lz_rs.o: lz_rs.c lzrs_lib.h lzply_lib.h bch.h bch_polys.h
$(CC) $(CFLAGS) -c -o $@ lz_rs.c
lz_rs: lz_rs.o liblzrs.a liblzply.a
$(CC) $(CFLAGS) -o $@ lz_rs.o liblzrs.a liblzply.a $(LDLIBS)
lz_rs: lz_rs.o liblzrs.a liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lz_rs.o liblzrs.a $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
rs_test: rs.c rs_test.c rs.h
$(CC) $(CFLAGS) -o $@ rs.c rs_test.c
@@ -122,8 +165,8 @@ deep_repair.o: deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h rs.h sha
lzply_deep_repair.o: lzply_deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h
$(CC) $(CFLAGS) -c -o $@ lzply_deep_repair.c
lzply_deep_repair: lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a
$(CC) $(CFLAGS) -o $@ lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a $(LDLIBS)
lzply_deep_repair: lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a $(CUDA_OBJ)
$(CC) $(CFLAGS) -o $@ lzply_deep_repair.o deep_repair.o liblzrs.a $(CUDA_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
# bch_polys.h is generated by gen_bch_polys.py from the rssearch data
# (~/workspace/rssearch/polys.txt + finds.txt) and checked in; it is
@@ -184,6 +227,6 @@ install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply
install -m 755 mount.lzply /sbin/mount.lzply
clean:
rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair bch_test rs_test crc16_test *.o liblzply.a liblzrs.a
rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair bch_test rs_test crc16_test bch_cuda_test bch_bench *.o liblzply.a liblzrs.a
.PHONY: all test install clean
+44
View File
@@ -42,6 +42,36 @@
#include <time.h>
#include "bch.h"
/* CUDA fast path (bch_cuda.cu, linked only when built with nvcc).
* Weak symbols: a CPU-only build leaves them NULL and always takes
* the CPU path below. bch_cuda_encode returns the stored length or 0
* on failure; bch_cuda_decode returns 0, -1 (uncorrectable) or -2
* (internal error). Any CUDA failure falls through to the CPU path,
* which re-verifies, so results are identical with or without a GPU. */
extern size_t bch_cuda_encode(const uint8_t *, size_t, const bch_poly_t *,
uint8_t *) __attribute__((weak));
extern int bch_cuda_decode(const uint8_t *, size_t, size_t,
const bch_poly_t *, uint8_t *,
int *) __attribute__((weak));
extern int bch_cuda_available(void) __attribute__((weak));
/* Minimum blob size for the GPU path, by t. A fresh process pays
* ~0.12 s of CUDA first-touch cost (context creation + first
* cudaMalloc, measured on hot_house) before any kernel runs, so the
* GPU only wins once the CPU remainder time exceeds that: t=8 runs
* ~87 MB/s on the CPU (break-even ~12 MB), t=32 ~23 MB/s
* (break-even ~3 MB). The thresholds are deliberately conservative
* and, critically, are checked BEFORE any CUDA call, so small blobs
* never pay the init cost at all. */
static size_t bch_cuda_min_len(int t)
{
if (t >= 32)
return 4u << 20;
if (t >= 16)
return 8u << 20;
return 16u << 20;
}
/* ------------------------------------------------------------------ */
/* polynomial lookup */
/* ------------------------------------------------------------------ */
@@ -614,6 +644,13 @@ size_t bch_encode(const uint8_t *data, size_t len, const bch_poly_t *p,
bch_encode_block(data, 0, p, out);
return bch_block_stored_len(0, p);
}
if (len >= bch_cuda_min_len(p->t) && bch_cuda_available &&
bch_cuda_available()) {
size_t n = bch_cuda_encode(data, len, p, out);
if (n != 0)
return n;
/* fall through to the CPU path on any CUDA failure */
}
while (off < len) {
size_t chunk = len - off;
if (chunk > maxd)
@@ -643,6 +680,13 @@ int bch_decode(const uint8_t *in, size_t len, size_t orig_len,
*corrected = c1;
return 0;
}
if (orig_len >= bch_cuda_min_len(p->t) && bch_cuda_available &&
bch_cuda_available()) {
if (bch_cuda_decode(in, len, orig_len, p, out, corrected) == 0)
return 0;
/* fall through to the CPU path on any CUDA failure or
* uncorrectable result (the CPU path re-verifies) */
}
while (off < orig_len) {
size_t chunk = orig_len - off;
if (chunk > maxd)
+165
View File
@@ -0,0 +1,165 @@
/* bch_bench.c - micro-benchmark for the BCH layer (encode/decode).
*
* Times bch_encode / bch_decode on an in-memory blob (no LZMA, SHA or
* I/O), so the numbers isolate the remainder + memcpy cost. Also times
* a plain memcpy of the same size for reference, and verifies the
* round-trip plus 1-bit-flip correction. The same binary measures the
* CUDA path when linked with bch_cuda.o (dispatch lives inside
* bch_encode/bch_decode); without it, it measures the CPU path.
*
* Usage: bch_bench [file] [reps]
* file: input blob (default: deterministic 50 MiB generated in RAM)
* reps: timed repetitions per case (default 5, median reported)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "bch.h"
static double now_s(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;
}
static int cmp_dbl(const void *a, const void *b)
{
double x = *(const double *)a, y = *(const double *)b;
return (x > y) - (x < y);
}
static double median(double *v, int n)
{
qsort(v, (size_t)n, sizeof(double), cmp_dbl);
return v[n / 2];
}
/* Deterministic filler: xorshift64, fast and incompressible-ish. */
static void fill_pattern(uint8_t *buf, size_t len)
{
uint64_t s = 0x9e3779b97f4a7c15ULL;
size_t i = 0;
while (i + 8 <= len) {
s ^= s << 13; s ^= s >> 7; s ^= s << 17;
memcpy(buf + i, &s, 8);
i += 8;
}
while (i < len) {
s ^= s << 13; s ^= s >> 7; s ^= s << 17;
buf[i++] = (uint8_t)s;
}
}
static const bch_poly_t *poly_for(size_t len, int t)
{
/* bch_poly_for_data(524000, t) returns the m=22 poly for that t:
* 8*524000 + t*22 < 2^22-1, while m=21 (N=2^21-1) is too small. */
const bch_poly_t *p = bch_poly_for_data(524000, t);
(void)len;
return p;
}
int main(int argc, char **argv)
{
const char *path = argc > 1 ? argv[1] : NULL;
int reps = argc > 2 ? atoi(argv[2]) : 5;
if (reps < 1) reps = 1;
if (reps > 21) reps = 21;
uint8_t *data = NULL;
size_t len = 0;
if (path) {
FILE *f = fopen(path, "rb");
if (!f) { perror("fopen"); return 1; }
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
if (n < 0) { fprintf(stderr, "ftell failed\n"); return 1; }
len = (size_t)n;
data = malloc(len ? len : 1);
if (fread(data, 1, len, f) != len) { fprintf(stderr, "short read\n"); return 1; }
fclose(f);
} else {
len = 50u << 20;
data = malloc(len);
fill_pattern(data, len);
}
printf("blob %zu bytes (%.3f MiB), reps %d\n", len,
(double)len / 1048576.0, reps);
double *ts = malloc(sizeof(double) * (size_t)reps);
double s, e;
/* memcpy reference */
uint8_t *tmp = malloc(len ? len : 1);
for (int i = 0; i < reps; i++) {
s = now_s();
memcpy(tmp, data, len);
e = now_s();
ts[i] = e - s;
}
printf("memcpy : median %.4f s %8.1f MB/s\n", median(ts, reps),
(double)len / 1048576.0 / median(ts, reps));
for (int ti = 0; ti < 2; ti++) {
int t = ti == 0 ? 8 : 32;
const bch_poly_t *p = poly_for(len, t);
if (!p) { printf("t=%d: no poly\n", t); continue; }
size_t maxd = bch_max_data(p);
size_t blocks = (len + maxd - 1) / maxd;
size_t eclen = bch_encoded_len(len, p);
uint8_t *enc = malloc(eclen ? eclen : 1);
uint8_t *dec = malloc(len ? len : 1);
printf("t=%-2d poly id 0x%04x m=%d r=%d maxdata=%zu blocks=%zu stored=%zu (+%.2f%%)\n",
t, p->id, p->m, p->r, maxd, blocks, eclen,
100.0 * (double)(eclen - len) / (double)len);
/* warmup + verify round-trip once */
if (bch_encode(data, len, p, enc) != eclen) {
printf("t=%d: encode failed\n", t); return 1;
}
int corr = 0;
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0 ||
memcmp(dec, data, len) != 0) {
printf("t=%d: round-trip FAILED\n", t); return 1;
}
/* 1-bit flip in the first block must still decode. */
enc[0] ^= 0x01;
corr = 0;
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0 ||
memcmp(dec, data, len) != 0 || corr != 1) {
printf("t=%d: 1-bit-flip decode FAILED (corr=%d)\n", t, corr);
return 1;
}
enc[0] ^= 0x01;
printf("t=%d: round-trip ok, 1-bit flip corrected (corr=1)\n", t);
for (int i = 0; i < reps; i++) {
s = now_s();
if (bch_encode(data, len, p, enc) != eclen) { printf("encode fail\n"); return 1; }
e = now_s();
ts[i] = e - s;
}
double med = median(ts, reps);
printf("t=%-2d encode : median %.4f s %8.1f MB/s\n", t, med,
(double)len / 1048576.0 / med);
for (int i = 0; i < reps; i++) {
s = now_s();
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0) { printf("decode fail\n"); return 1; }
e = now_s();
ts[i] = e - s;
}
med = median(ts, reps);
printf("t=%-2d decode : median %.4f s %8.1f MB/s (corr=%d)\n", t, med,
(double)len / 1048576.0 / med, corr);
free(enc);
free(dec);
}
free(tmp);
free(data);
free(ts);
printf("ALL OK\n");
return 0;
}
+735
View File
@@ -0,0 +1,735 @@
/* bch_cuda.cu - CUDA BCH remainder for lzply.
*
* See bch_cuda.h for the design. Remainder recap (bch.c): the state
* is an r-bit value, left-aligned in nb = (r+7)/8 bytes; feeding a
* byte is rem = shift8(rem) XOR T[rem[0] XOR b], where T is the
* 256*nb table built from the generator. That step is GF(2)-linear
* in (rem, b), so feeding a chunk from zero state gives a partial
* remainder, and concatenating chunks is partial-combining with an
* advance-by-k-bytes map Adv_k (itself linear, so it is a table:
* Adv_k(S) = XOR over bytes j of Adv_k[j][S[j]]).
*
* Host-side table building duplicates bch.c exactly (glow, T, and
* Adv_1); the 12 squarings Adv_1 -> Adv_4096 run on the device.
* Bit-identity vs the CPU remainder is verified by bch_cuda_test
* (GPU encode output byte-identical to CPU encode, all 82 polys
* via the (t, size) grid, plus decode agreement on dirty blocks).
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <cuda_runtime.h>
extern "C" {
#include "bch.h"
}
#include "bch_cuda.h"
/* Debug prints on failure paths, enabled by BCH_CUDA_DEBUG=1. */
static int cu_debug(void)
{
static int d = -1;
if (d < 0)
d = getenv("BCH_CUDA_DEBUG") ? 1 : 0;
return d;
}
#define CU_DBG(...) do { if (cu_debug()) { fprintf(stderr, "bch_cuda %s:%d: ", __func__, __LINE__); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); } } while (0)
#define BCH_CUDA_CHUNK 4096
#define BCH_CUDA_MAX_NB 88 /* r max = 32*22 = 704 bits -> nb = 88 */
#define BCH_CUDA_MAX_POLYS 8
/* ------------------------------------------------------------------ */
/* host-side LFSR helpers: bit-identical copies of bch.c */
/* ------------------------------------------------------------------ */
static void cu_rem_set_bit(uint8_t *rem, int r, int i)
{
int byte = (r - 1 - i) / 8;
int bit = 7 - ((r - 1 - i) % 8);
rem[byte] |= (uint8_t)(1u << bit);
}
static void cu_rem_shl1(uint8_t *rem, int nb)
{
for (int i = 0; i < nb; i++)
rem[i] = (uint8_t)((rem[i] << 1) | (i + 1 < nb ? (rem[i + 1] >> 7) : 0));
}
static void cu_rem_bitstep(uint8_t *rem, int m, const uint8_t *glow, int nb)
{
int fb = ((rem[0] >> 7) & 1) ^ (m & 1);
cu_rem_shl1(rem, nb);
if (fb)
for (int i = 0; i < nb; i++)
rem[i] ^= glow[i];
}
/* One table-driven byte step, given an explicit table. */
static void cu_rem_feed_byte(uint8_t *rem, uint8_t b,
const uint8_t *table, int nb)
{
int idx = rem[0] ^ b;
const uint8_t *t = table + (size_t)idx * nb;
for (int i = 0; i < nb - 1; i++)
rem[i] = rem[i + 1] ^ t[i];
rem[nb - 1] = t[nb - 1];
}
static int cu_rem_is_zero(const uint8_t *rem, int nb)
{
for (int i = 0; i < nb; i++)
if (rem[i])
return 0;
return 1;
}
/* ------------------------------------------------------------------ */
/* device availability */
/* ------------------------------------------------------------------ */
extern "C" int bch_cuda_available(void)
{
static int cached = -1;
if (cached < 0) {
int n = 0;
cudaError_t err = cudaGetDeviceCount(&n);
cached = (err == cudaSuccess && n > 0) ? 1 : 0;
}
return cached;
}
/* ------------------------------------------------------------------ */
/* kernels */
/* ------------------------------------------------------------------ */
/* One thread per chunk: serial table LFSR over the chunk, zero state.
* Templated on NB so the remainder stays in registers; the generic
* version covers any other nb (local-memory remainder). */
template <int NB>
__global__ void partial_kernel_t(const uint8_t *__restrict__ in,
const int *__restrict__ chunk_off,
const int *__restrict__ chunk_len,
const uint8_t *__restrict__ table,
uint8_t *__restrict__ part, int nchunks)
{
int c = blockIdx.x * blockDim.x + threadIdx.x;
if (c >= nchunks)
return;
const uint8_t *src = in + chunk_off[c];
int len = chunk_len[c];
uint8_t rem[NB];
#pragma unroll
for (int i = 0; i < NB; i++)
rem[i] = 0;
for (int k = 0; k < len; k++) {
int idx = rem[0] ^ src[k];
const uint8_t *t = table + (size_t)idx * NB;
#pragma unroll
for (int i = 0; i < NB - 1; i++)
rem[i] = rem[i + 1] ^ t[i];
rem[NB - 1] = t[NB - 1];
}
uint8_t *dst = part + (size_t)c * NB;
#pragma unroll
for (int i = 0; i < NB; i++)
dst[i] = rem[i];
}
__global__ void partial_kernel_g(const uint8_t *__restrict__ in,
const int *__restrict__ chunk_off,
const int *__restrict__ chunk_len,
const uint8_t *__restrict__ table,
uint8_t *__restrict__ part, int nchunks,
int nb)
{
int c = blockIdx.x * blockDim.x + threadIdx.x;
if (c >= nchunks)
return;
const uint8_t *src = in + chunk_off[c];
int len = chunk_len[c];
uint8_t rem[BCH_CUDA_MAX_NB];
for (int i = 0; i < nb; i++)
rem[i] = 0;
for (int k = 0; k < len; k++) {
int idx = rem[0] ^ src[k];
const uint8_t *t = table + (size_t)idx * nb;
for (int i = 0; i < nb - 1; i++)
rem[i] = rem[i + 1] ^ t[i];
rem[nb - 1] = t[nb - 1];
}
uint8_t *dst = part + (size_t)c * nb;
for (int i = 0; i < nb; i++)
dst[i] = rem[i];
}
/* One thread per block: combine that block's chunk partials.
* acc = P_first; then acc = Adv_CHUNK(acc) XOR P_k for each later
* (full) chunk. adv is the nb*256*nb advance table. */
template <int NB>
__global__ void combine_kernel_t(const uint8_t *__restrict__ part,
const int *__restrict__ block_first,
const int *__restrict__ block_nchunk,
const uint8_t *__restrict__ adv,
uint8_t *__restrict__ rem_out, int nblocks)
{
int b = blockIdx.x * blockDim.x + threadIdx.x;
if (b >= nblocks)
return;
uint8_t acc[NB];
const uint8_t *p0 = part + (size_t)block_first[b] * NB;
#pragma unroll
for (int i = 0; i < NB; i++)
acc[i] = p0[i];
for (int k = 1; k < block_nchunk[b]; k++) {
uint8_t nxt[NB];
#pragma unroll
for (int i = 0; i < NB; i++)
nxt[i] = 0;
#pragma unroll
for (int j = 0; j < NB; j++) {
const uint8_t *a = adv + ((size_t)j * 256 + acc[j]) * NB;
#pragma unroll
for (int i = 0; i < NB; i++)
nxt[i] ^= a[i];
}
const uint8_t *pk = part + (size_t)(block_first[b] + k) * NB;
#pragma unroll
for (int i = 0; i < NB; i++)
acc[i] = nxt[i] ^ pk[i];
}
uint8_t *dst = rem_out + (size_t)b * NB;
#pragma unroll
for (int i = 0; i < NB; i++)
dst[i] = acc[i];
}
__global__ void combine_kernel_g(const uint8_t *__restrict__ part,
const int *__restrict__ block_first,
const int *__restrict__ block_nchunk,
const uint8_t *__restrict__ adv,
uint8_t *__restrict__ rem_out, int nblocks,
int nb)
{
int b = blockIdx.x * blockDim.x + threadIdx.x;
if (b >= nblocks)
return;
uint8_t acc[BCH_CUDA_MAX_NB];
const uint8_t *p0 = part + (size_t)block_first[b] * nb;
for (int i = 0; i < nb; i++)
acc[i] = p0[i];
for (int k = 1; k < block_nchunk[b]; k++) {
uint8_t nxt[BCH_CUDA_MAX_NB];
for (int i = 0; i < nb; i++)
nxt[i] = 0;
for (int j = 0; j < nb; j++) {
const uint8_t *a = adv + ((size_t)j * 256 + acc[j]) * nb;
for (int i = 0; i < nb; i++)
nxt[i] ^= a[i];
}
const uint8_t *pk = part + (size_t)(block_first[b] + k) * nb;
for (int i = 0; i < nb; i++)
acc[i] = nxt[i] ^ pk[i];
}
uint8_t *dst = rem_out + (size_t)b * nb;
for (int i = 0; i < nb; i++)
dst[i] = acc[i];
}
/* Advance-table squaring: one thread per (byte j, value v) entry.
* out[j][v] = Adv(Adv[j][v]), i.e. Adv_{2k} from Adv_k. */
__global__ void adv_square_kernel(const uint8_t *__restrict__ adv_in,
uint8_t *__restrict__ adv_out, int nb)
{
int e = blockIdx.x * blockDim.x + threadIdx.x;
if (e >= nb * 256)
return;
uint8_t v[BCH_CUDA_MAX_NB];
const uint8_t *src = adv_in + (size_t)e * nb;
for (int i = 0; i < nb; i++)
v[i] = src[i];
uint8_t out[BCH_CUDA_MAX_NB];
for (int i = 0; i < nb; i++)
out[i] = 0;
for (int j = 0; j < nb; j++) {
const uint8_t *row = adv_in + ((size_t)j * 256 + v[j]) * nb;
for (int i = 0; i < nb; i++)
out[i] ^= row[i];
}
uint8_t *dst = adv_out + (size_t)e * nb;
for (int i = 0; i < nb; i++)
dst[i] = out[i];
}
/* ------------------------------------------------------------------ */
/* per-poly cached device state */
/* ------------------------------------------------------------------ */
typedef struct {
uint16_t id;
int nb;
int r;
uint8_t glow[BCH_CUDA_MAX_NB];
uint8_t *d_table; /* 256*nb */
uint8_t *d_adv; /* nb*256*nb, advance by BCH_CUDA_CHUNK */
uint8_t *d_adv2; /* scratch for squaring */
} cu_poly_t;
static cu_poly_t g_polys[BCH_CUDA_MAX_POLYS];
static int g_npolys = 0;
static void cu_poly_cleanup_partial(cu_poly_t *cp)
{
if (cp->d_table) { cudaFree(cp->d_table); cp->d_table = NULL; }
if (cp->d_adv) { cudaFree(cp->d_adv); cp->d_adv = NULL; }
if (cp->d_adv2) { cudaFree(cp->d_adv2); cp->d_adv2 = NULL; }
}
static cu_poly_t *cu_poly_get(const bch_poly_t *p)
{
for (int i = 0; i < g_npolys; i++)
if (g_polys[i].id == p->id && g_polys[i].d_table)
return &g_polys[i];
if (g_npolys >= BCH_CUDA_MAX_POLYS) {
/* Evict everything (rebuilds are ~ms: the squaring runs on
* the device). One lzply process normally uses 1-2 polys. */
for (int i = 0; i < g_npolys; i++)
cu_poly_cleanup_partial(&g_polys[i]);
memset(g_polys, 0, sizeof(g_polys));
g_npolys = 0;
CU_DBG("poly cache evicted");
}
cu_poly_t *cp = &g_polys[g_npolys];
memset(cp, 0, sizeof(*cp));
cp->id = p->id;
cp->r = p->r;
cp->nb = (p->r + 7) / 8;
int nb = cp->nb;
uint8_t *table = NULL;
uint8_t *adv1 = NULL;
/* glow + T on the host (same construction as bch_ctx_new). */
const uint8_t *gen = bch_poly_bytes + p->off;
for (int i = 0; i < p->r; i++)
if ((gen[i / 8] >> (i % 8)) & 1)
cu_rem_set_bit(cp->glow, p->r, i);
table = (uint8_t *)malloc((size_t)256 * nb);
if (!table)
goto fail;
for (int u = 0; u < 256; u++) {
uint8_t *t = table + (size_t)u * nb;
memset(t, 0, nb);
for (int b = 7; b >= 0; b--)
cu_rem_bitstep(t, (u >> b) & 1, cp->glow, nb);
}
/* Adv_1 on the host: one zero byte fed from each single-byte state. */
adv1 = (uint8_t *)malloc((size_t)nb * 256 * nb);
if (!adv1) {
free(table);
goto fail;
}
for (int j = 0; j < nb; j++) {
for (int v = 0; v < 256; v++) {
uint8_t *s = adv1 + ((size_t)j * 256 + v) * nb;
memset(s, 0, nb);
s[j] = (uint8_t)v;
cu_rem_feed_byte(s, 0, table, nb);
}
}
{
cudaError_t err;
err = cudaMalloc(&cp->d_table, (size_t)256 * nb);
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_table malloc: %s", p->id, cudaGetErrorString(err)); goto fail; }
err = cudaMemcpy(cp->d_table, table, (size_t)256 * nb,
cudaMemcpyHostToDevice);
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_table copy: %s", p->id, cudaGetErrorString(err)); goto fail; }
err = cudaMalloc(&cp->d_adv, (size_t)nb * 256 * nb);
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_adv malloc: %s", p->id, cudaGetErrorString(err)); goto fail; }
err = cudaMalloc(&cp->d_adv2, (size_t)nb * 256 * nb);
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_adv2 malloc: %s", p->id, cudaGetErrorString(err)); goto fail; }
err = cudaMemcpy(cp->d_adv, adv1, (size_t)nb * 256 * nb,
cudaMemcpyHostToDevice);
free(table);
free(adv1);
if (err != cudaSuccess) { CU_DBG("poly 0x%04x d_adv copy: %s", p->id, cudaGetErrorString(err)); goto fail; }
/* Square on the device: Adv_1 -> Adv_CHUNK (CHUNK is a power of 2). */
int steps = 0;
while ((1 << steps) < BCH_CUDA_CHUNK)
steps++;
uint8_t *cur = cp->d_adv, *nxt = cp->d_adv2;
int nentries = nb * 256;
for (int s = 0; s < steps; s++) {
adv_square_kernel<<<(nentries + 255) / 256, 256>>>(cur, nxt, nb);
err = cudaGetLastError();
if (err != cudaSuccess) { CU_DBG("poly 0x%04x square %d launch: %s", p->id, s, cudaGetErrorString(err)); goto fail; }
err = cudaDeviceSynchronize();
if (err != cudaSuccess) { CU_DBG("poly 0x%04x square %d sync: %s", p->id, s, cudaGetErrorString(err)); goto fail; }
uint8_t *tmp = cur;
cur = nxt;
nxt = tmp;
}
if (cur != cp->d_adv) {
err = cudaMemcpy(cp->d_adv, cur, (size_t)nb * 256 * nb,
cudaMemcpyDeviceToDevice);
if (err != cudaSuccess) { CU_DBG("poly 0x%04x adv copyback: %s", p->id, cudaGetErrorString(err)); goto fail; }
}
}
g_npolys++;
return cp;
fail:
/* Leave no poisoned slot behind: a retry rebuilds from scratch. */
cu_poly_cleanup_partial(cp);
memset(cp, 0, sizeof(*cp));
return NULL;
}
/* ------------------------------------------------------------------ */
/* cached device scratch buffers */
/* ------------------------------------------------------------------ */
static uint8_t *g_d_in = NULL;
static size_t g_d_in_cap = 0;
static uint8_t *g_d_part = NULL;
static size_t g_d_part_cap = 0;
static uint8_t *g_d_rem = NULL;
static size_t g_d_rem_cap = 0;
static int *g_d_coff = NULL, *g_d_clen = NULL;
static int *g_d_bfirst = NULL, *g_d_bnc = NULL;
static size_t g_d_coff_cap = 0;
static size_t g_d_clen_cap = 0;
static size_t g_d_bfirst_cap = 0;
static size_t g_d_bnc_cap = 0;
static int cu_ensure_u8(uint8_t **ptr, size_t *cap, size_t need)
{
if (*cap >= need)
return 0;
if (*ptr)
cudaFree(*ptr);
size_t ncap = *cap ? *cap : (1u << 20);
while (ncap < need)
ncap *= 2;
if (cudaMalloc(ptr, ncap) != cudaSuccess) {
*ptr = NULL;
*cap = 0;
return -1;
}
*cap = ncap;
return 0;
}
static int cu_ensure_int(int **ptr, size_t *cap, size_t need)
{
if (*cap >= need)
return 0;
if (*ptr)
cudaFree(*ptr);
size_t ncap = *cap ? *cap : 4096;
while (ncap < need)
ncap *= 2;
if (cudaMalloc((void **)ptr, ncap * sizeof(int)) != cudaSuccess) {
*ptr = NULL;
*cap = 0;
return -1;
}
*cap = ncap;
return 0;
}
/* ------------------------------------------------------------------ */
/* chunk plan + remainder runner */
/* ------------------------------------------------------------------ */
/* Blocks are byte strings [bstart[b], bstart[b]+blen[b]).
* Chunk 0 of each block is short (len - (n-1)*CHUNK), the rest are
* full CHUNK bytes, so every combine step advances by exactly CHUNK. */
static int cu_plan(const size_t *bstart, const size_t *blen, int nblocks,
int *coff, int *clen, int *bfirst, int *bnc)
{
int nc = 0;
for (int b = 0; b < nblocks; b++) {
size_t L = blen[b];
int n = (int)((L + BCH_CUDA_CHUNK - 1) / BCH_CUDA_CHUNK);
if (n < 1)
n = 1;
bfirst[b] = nc;
bnc[b] = n;
size_t first = L - (size_t)(n - 1) * BCH_CUDA_CHUNK;
for (int k = 0; k < n; k++) {
coff[nc] = (int)(bstart[b] +
(k == 0 ? 0 : first + (size_t)(k - 1) * BCH_CUDA_CHUNK));
clen[nc] = (int)(k == 0 ? first : BCH_CUDA_CHUNK);
nc++;
}
}
return nc;
}
static int cu_remainders(cu_poly_t *cp, int nchunks, int nblocks)
{
int nb = cp->nb;
dim3 pb(256);
dim3 pg((unsigned)((nchunks + 255) / 256));
switch (nb) {
case 3: partial_kernel_t<3><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
case 6: partial_kernel_t<6><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
case 11: partial_kernel_t<11><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
case 22: partial_kernel_t<22><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
case 44: partial_kernel_t<44><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
case 88: partial_kernel_t<88><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
default: partial_kernel_g<<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks, nb); break;
}
{
cudaError_t err = cudaGetLastError();
if (err != cudaSuccess) {
CU_DBG("partial kernel: %s", cudaGetErrorString(err));
return -1;
}
}
dim3 cb(256);
dim3 cg((unsigned)((nblocks + 255) / 256));
switch (nb) {
case 3: combine_kernel_t<3><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
case 6: combine_kernel_t<6><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
case 11: combine_kernel_t<11><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
case 22: combine_kernel_t<22><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
case 44: combine_kernel_t<44><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
case 88: combine_kernel_t<88><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
default: combine_kernel_g<<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks, nb); break;
}
{
cudaError_t err = cudaGetLastError();
if (err != cudaSuccess) {
CU_DBG("combine kernel: %s", cudaGetErrorString(err));
return -1;
}
err = cudaDeviceSynchronize();
if (err != cudaSuccess) {
CU_DBG("remainders sync: %s", cudaGetErrorString(err));
return -1;
}
}
return 0;
}
/* Upload the chunk plan; returns 0 or -1. */
static int cu_upload_plan(const int *coff, const int *clen,
const int *bfirst, const int *bnc,
int nchunks, int nblocks)
{
if (cu_ensure_int(&g_d_coff, &g_d_coff_cap, (size_t)nchunks) != 0)
return -1;
if (cu_ensure_int(&g_d_clen, &g_d_clen_cap, (size_t)nchunks) != 0)
return -1;
if (cu_ensure_int(&g_d_bfirst, &g_d_bfirst_cap, (size_t)nblocks) != 0)
return -1;
if (cu_ensure_int(&g_d_bnc, &g_d_bnc_cap, (size_t)nblocks) != 0)
return -1;
if (cudaMemcpy(g_d_coff, coff, (size_t)nchunks * sizeof(int),
cudaMemcpyHostToDevice) != cudaSuccess)
return -1;
if (cudaMemcpy(g_d_clen, clen, (size_t)nchunks * sizeof(int),
cudaMemcpyHostToDevice) != cudaSuccess)
return -1;
if (cudaMemcpy(g_d_bfirst, bfirst, (size_t)nblocks * sizeof(int),
cudaMemcpyHostToDevice) != cudaSuccess)
return -1;
if (cudaMemcpy(g_d_bnc, bnc, (size_t)nblocks * sizeof(int),
cudaMemcpyHostToDevice) != cudaSuccess)
return -1;
return 0;
}
/* ------------------------------------------------------------------ */
/* public API */
/* ------------------------------------------------------------------ */
extern "C" size_t bch_cuda_encode(const uint8_t *data, size_t len,
const bch_poly_t *p, uint8_t *out)
{
if (!data || !out || !p || len == 0)
return 0;
if (!bch_cuda_available())
return 0;
cu_poly_t *cp = cu_poly_get(p);
if (!cp)
return 0;
int nb = cp->nb;
size_t maxd = bch_max_data(p);
int nblocks = (int)((len + maxd - 1) / maxd);
size_t *bstart = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
size_t *blen = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
int *coff = NULL, *clen = NULL, *bfirst = NULL, *bnc = NULL;
uint8_t *rem = NULL;
size_t ret = 0;
if (!bstart || !blen)
goto done;
{
size_t off = 0;
for (int b = 0; b < nblocks; b++) {
size_t chunk = len - off;
if (chunk > maxd)
chunk = maxd;
bstart[b] = off;
blen[b] = chunk;
off += chunk;
}
}
/* Worst-case chunk count: every block split at CHUNK + 1. */
coff = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
clen = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
bfirst = (int *)malloc(sizeof(int) * (size_t)nblocks);
bnc = (int *)malloc(sizeof(int) * (size_t)nblocks);
if (!coff || !clen || !bfirst || !bnc)
goto done;
{
int nchunks = cu_plan(bstart, blen, nblocks, coff, clen, bfirst, bnc);
if (cu_ensure_u8(&g_d_in, &g_d_in_cap, len) != 0)
goto done;
if (cu_ensure_u8(&g_d_part, &g_d_part_cap, (size_t)nchunks * nb) != 0)
goto done;
if (cu_ensure_u8(&g_d_rem, &g_d_rem_cap, (size_t)nblocks * nb) != 0)
goto done;
if (cudaMemcpy(g_d_in, data, len, cudaMemcpyHostToDevice) != cudaSuccess)
goto done;
if (cu_upload_plan(coff, clen, bfirst, bnc, nchunks, nblocks) != 0)
goto done;
if (cu_remainders(cp, nchunks, nblocks) != 0)
goto done;
rem = (uint8_t *)malloc((size_t)nblocks * nb);
if (!rem)
goto done;
if (cudaMemcpy(rem, g_d_rem, (size_t)nblocks * nb,
cudaMemcpyDeviceToHost) != cudaSuccess)
goto done;
size_t woff = 0;
for (int b = 0; b < nblocks; b++) {
memcpy(out + woff, data + bstart[b], blen[b]);
memcpy(out + woff + blen[b], rem + (size_t)b * nb, nb);
woff += blen[b] + nb;
}
ret = woff;
}
done:
free(bstart);
free(blen);
free(coff);
free(clen);
free(bfirst);
free(bnc);
free(rem);
return ret;
}
extern "C" int bch_cuda_decode(const uint8_t *in, size_t len, size_t orig_len,
const bch_poly_t *p, uint8_t *out,
int *corrected)
{
if (corrected)
*corrected = 0;
if (!in || !out || !p)
return -2;
if (orig_len == 0)
return -2; /* CPU handles the empty-blob block */
if (len != bch_encoded_len(orig_len, p))
return -2; /* malformed length: let the CPU path report it */
if (!bch_cuda_available())
return -2;
cu_poly_t *cp = cu_poly_get(p);
if (!cp)
return -2;
int nb = cp->nb;
int r = cp->r;
size_t maxd = bch_max_data(p);
int nblocks = (int)((orig_len + maxd - 1) / maxd);
size_t *bstart = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
size_t *blen = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
size_t *dlen = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
size_t *doff = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
int *coff = NULL, *clen = NULL, *bfirst = NULL, *bnc = NULL;
uint8_t *rem = NULL;
int ret = -2;
if (!bstart || !blen || !dlen || !doff)
goto done;
{
size_t off = 0, roff = 0;
for (int b = 0; b < nblocks; b++) {
size_t chunk = orig_len - off;
if (chunk > maxd)
chunk = maxd;
dlen[b] = chunk;
doff[b] = off;
bstart[b] = roff; /* stored offset */
blen[b] = chunk + (size_t)(r / 8); /* data + whole parity bytes */
off += chunk;
roff += chunk + nb;
}
}
coff = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
clen = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
bfirst = (int *)malloc(sizeof(int) * (size_t)nblocks);
bnc = (int *)malloc(sizeof(int) * (size_t)nblocks);
if (!coff || !clen || !bfirst || !bnc)
goto done;
{
int nchunks = cu_plan(bstart, blen, nblocks, coff, clen, bfirst, bnc);
if (cu_ensure_u8(&g_d_in, &g_d_in_cap, len) != 0)
goto done;
if (cu_ensure_u8(&g_d_part, &g_d_part_cap, (size_t)nchunks * nb) != 0)
goto done;
if (cu_ensure_u8(&g_d_rem, &g_d_rem_cap, (size_t)nblocks * nb) != 0)
goto done;
if (cudaMemcpy(g_d_in, in, len, cudaMemcpyHostToDevice) != cudaSuccess)
goto done;
if (cu_upload_plan(coff, clen, bfirst, bnc, nchunks, nblocks) != 0)
goto done;
if (cu_remainders(cp, nchunks, nblocks) != 0)
goto done;
rem = (uint8_t *)malloc((size_t)nblocks * nb);
if (!rem)
goto done;
if (cudaMemcpy(rem, g_d_rem, (size_t)nblocks * nb,
cudaMemcpyDeviceToHost) != cudaSuccess)
goto done;
int whole = r / 8;
int total_corr = 0;
for (int b = 0; b < nblocks; b++) {
uint8_t *rb = rem + (size_t)b * nb;
/* Feed the remaining (r%8) parity bits, MSB first, from
* the final parity byte -- the same tail rem_of_codeword
* feeds bit-by-bit. */
const uint8_t *par = in + bstart[b] + dlen[b];
for (int bit = 7; bit >= 8 - (r % 8) && (r % 8); bit--)
cu_rem_bitstep(rb, (par[whole] >> bit) & 1, cp->glow, nb);
if (cu_rem_is_zero(rb, nb)) {
memcpy(out + doff[b], in + bstart[b], dlen[b]);
continue;
}
/* Dirty block: CPU BM + Chien, identical to the CPU path. */
int c1 = 0;
if (bch_decode_block(in + bstart[b], dlen[b] + nb, dlen[b], p,
out + doff[b], &c1) != 0) {
ret = -1;
goto done;
}
total_corr += c1;
}
if (corrected)
*corrected = total_corr;
ret = 0;
}
done:
free(bstart);
free(blen);
free(dlen);
free(doff);
free(coff);
free(clen);
free(bfirst);
free(bnc);
free(rem);
return ret;
}
+56
View File
@@ -0,0 +1,56 @@
/* bch_cuda.h - CUDA BCH remainder for lzply.
*
* GPU fast path for the BCH remainder (bch_encode / bch_decode).
* The remainder is GF(2)-linear, so parallel-CRC-style chunking
* applies: split each block into 4096-byte chunks, compute each
* chunk's partial remainder (zero initial state) on the GPU, then
* combine with a precomputed advance-by-4096-bytes table
* (Adv(S) = the state S advanced by 4096 zero bytes; built on the
* device by repeated squaring from Adv_1).
*
* Chunking puts the short chunk FIRST in each block, so every combine
* step advances by exactly 4096 bytes -- no arbitrary-length advance
* table is ever needed.
*
* Encode is fully GPU (remainder per block -> parity bytes). Decode
* uses the GPU remainder for the clean path (remainder zero -> copy
* the data out); a block with a nonzero remainder falls back to the
* CPU bch_decode_block (Berlekamp-Massey + Chien), so correction
* behaviour is identical to the CPU path.
*
* All functions fall back gracefully: bch_cuda_encode returns 0 and
* bch_cuda_decode returns -2 on any CUDA problem, and bch.c treats
* those as "use the CPU path". bch_cuda_available() is 0 when no
* CUDA device is present. The symbols are referenced weakly from
* bch.c, so a CPU-only build (no bch_cuda.o linked) works unchanged.
*/
#ifndef LZPLY_BCH_CUDA_H
#define LZPLY_BCH_CUDA_H
#include <stddef.h>
#include <stdint.h>
#include "bch.h"
#ifdef __cplusplus
extern "C" {
#endif
/* 1 if a CUDA device is present and usable, 0 otherwise. */
int bch_cuda_available(void);
/* Encode a whole blob on the GPU (same contract as bch_encode).
* Returns the stored length, or 0 on any failure (caller: use CPU). */
size_t bch_cuda_encode(const uint8_t *data, size_t len,
const bch_poly_t *p, uint8_t *out);
/* Decode a whole blob on the GPU (same contract as bch_decode).
* Returns 0 on success, -1 if any block is uncorrectable, -2 on an
* internal/CUDA error (caller: fall back to the CPU path). */
int bch_cuda_decode(const uint8_t *in, size_t len, size_t orig_len,
const bch_poly_t *p, uint8_t *out, int *corrected);
#ifdef __cplusplus
}
#endif
#endif /* LZPLY_BCH_CUDA_H */
+388
View File
@@ -0,0 +1,388 @@
/* bch_cuda_test.c - verification + benchmark for the CUDA BCH path.
*
* 1. Correctness: for t in {1,2,4,8,16,32} and a spread of blob sizes
* (1 B .. 1 MiB, incl. chunk and block boundaries), GPU encode must
* be byte-identical to a CPU reference encode built block-by-block
* from the INDEPENDENT brute-force remainder (bit-by-bit long
* division -- no table LFSR, no dispatch, so the comparison cannot
* be circular: for len >= 1MB bch_encode itself dispatches to the
* GPU). GPU decode of a CPU-encoded blob (clean, and with up to t
* flipped bits in one block) must match a per-block CPU decode via
* bch_decode_block; a t+1-bit flip must make GPU and CPU decode
* agree.
* 2. Benchmark: GPU encode/decode MB/s at 1/4/50 MB for t=8/32
* (median of 5), via the direct CUDA entry points and via the
* bch_encode/bch_decode dispatch (they must agree -- dispatch
* overhead ~0). The first CUDA call (table build + context init)
* is timed separately from steady state. True CPU numbers come
* from bch_bench_cpu (built without bch_cuda.o); compare against
* those in the report.
*
* Usage: bch_cuda_test [datafile]
* datafile: blob for the benchmark (default: generated 50 MiB).
* Exit 0 only if every check passes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "bch.h"
#include "bch_cuda.h"
static int fails = 0;
static int checks = 0;
#define CHECK(cond, ...) do { \
checks++; \
if (!(cond)) { fails++; printf("FAIL: " __VA_ARGS__); printf("\n"); } \
} while (0)
static uint64_t rng_state = 0x12345678abcdefULL;
static uint64_t xr(void)
{
rng_state ^= rng_state << 13;
rng_state ^= rng_state >> 7;
rng_state ^= rng_state << 17;
return rng_state;
}
static void rand_bytes(uint8_t *buf, size_t n)
{
for (size_t i = 0; i < n; i++)
buf[i] = (uint8_t)(xr() & 0xff);
}
static void flip_bits(uint8_t *buf, size_t nbits, int k)
{
size_t *pos = malloc(sizeof(size_t) * (size_t)(k > 0 ? k : 1));
int got = 0;
while (got < k) {
size_t p = (size_t)(xr() % nbits);
int dup = 0;
for (int i = 0; i < got; i++)
if (pos[i] == p)
dup = 1;
if (!dup)
pos[got++] = p;
}
for (int i = 0; i < k; i++)
buf[pos[i] / 8] ^= (uint8_t)(1u << (7 - (pos[i] % 8)));
free(pos);
}
static double now_s(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;
}
static int cmp_dbl(const void *a, const void *b)
{
double x = *(const double *)a, y = *(const double *)b;
return (x > y) - (x < y);
}
static double median(double *v, int n)
{
qsort(v, (size_t)n, sizeof(double), cmp_dbl);
return v[n / 2];
}
static int t_index(int t)
{
switch (t) {
case 1: return 0;
case 2: return 1;
case 4: return 2;
case 8: return 3;
case 16: return 4;
case 32: return 5;
default: return -1;
}
}
/* Same selection as lzply_lib: auto-pick, else largest m for the t. */
static const bch_poly_t *test_poly(size_t len, int t)
{
const bch_poly_t *p = bch_poly_for_data(len, t);
if (p)
return p;
int ti = t_index(t);
if (ti < 0)
return NULL;
for (int m = BCH_MAX_M; m >= BCH_MIN_M; m--) {
uint16_t id = bch_poly_by_mt[m - BCH_MIN_M][ti];
if (id)
return bch_poly_by_id(id);
}
return NULL;
}
/* CPU reference encode: block-by-block, brute-force remainder. */
static void ref_encode(const uint8_t *data, size_t len,
const bch_poly_t *p, uint8_t *out)
{
size_t maxd = bch_max_data(p);
size_t off = 0, woff = 0;
if (len == 0) {
if (bch_remainder_bruteforce(data, 0, p, out) != 0) {
printf("ref_encode: bruteforce failed\n");
exit(1);
}
return;
}
while (off < len) {
size_t chunk = len - off;
if (chunk > maxd)
chunk = maxd;
size_t nb = bch_block_stored_len(chunk, p) - chunk;
uint8_t *rem = malloc(nb);
if (bch_remainder_bruteforce(data + off, chunk, p, rem) != 0) {
printf("ref_encode: bruteforce failed\n");
exit(1);
}
memcpy(out + woff, data + off, chunk);
memcpy(out + woff + chunk, rem, nb);
free(rem);
woff += bch_block_stored_len(chunk, p);
off += chunk;
}
}
/* CPU reference decode: block-by-block via bch_decode_block.
* Returns 0 ok, -1 uncorrectable. */
static int ref_decode(const uint8_t *in, size_t len, size_t orig_len,
const bch_poly_t *p, uint8_t *out, int *corrected)
{
if (corrected)
*corrected = 0;
size_t maxd = bch_max_data(p);
size_t off = 0, roff = 0;
int total = 0;
if (orig_len == 0) {
if (len != bch_block_stored_len(0, p))
return -1;
int c1 = 0;
if (bch_decode_block(in, len, 0, p, out, &c1) != 0)
return -1;
if (corrected)
*corrected = c1;
return 0;
}
while (off < orig_len) {
size_t chunk = orig_len - off;
if (chunk > maxd)
chunk = maxd;
size_t slen = bch_block_stored_len(chunk, p);
if (roff + slen > len)
return -1;
int c1 = 0;
if (bch_decode_block(in + roff, slen, chunk, p, out + off, &c1) != 0)
return -1;
total += c1;
roff += slen;
off += chunk;
}
if (corrected)
*corrected = total;
return 0;
}
static void correctness_case(const uint8_t *data, size_t len, int t)
{
const bch_poly_t *p = test_poly(len, t);
if (!p) {
printf("SKIP t=%d len=%zu: no poly\n", t, len);
return;
}
size_t eclen = bch_encoded_len(len, p);
uint8_t *enc_cpu = malloc(eclen ? eclen : 1);
uint8_t *enc_gpu = malloc(eclen ? eclen : 1);
uint8_t *dec = malloc(len ? len : 1);
uint8_t *dec2 = malloc(len ? len : 1);
uint8_t *work = malloc(eclen ? eclen : 1);
if (!enc_cpu || !enc_gpu || !dec || !dec2 || !work) {
printf("OOM\n");
exit(1);
}
ref_encode(data, len, p, enc_cpu);
size_t gn = bch_cuda_encode(data, len, p, enc_gpu);
CHECK(gn == eclen, "t=%d len=%zu gpu encode len %zu != %zu",
t, len, gn, eclen);
CHECK(gn == eclen && memcmp(enc_cpu, enc_gpu, eclen) == 0,
"t=%d len=%zu poly 0x%04x m=%d gpu encode != cpu(bruteforce) encode",
t, len, p->id, p->m);
/* clean decode both ways */
int cc = -1, gc = -1;
CHECK(ref_decode(enc_cpu, eclen, len, p, dec, &cc) == 0 &&
memcmp(dec, data, len) == 0,
"t=%d len=%zu cpu decode of cpu encode", t, len);
CHECK(bch_cuda_decode(enc_cpu, eclen, len, p, dec2, &gc) == 0 &&
memcmp(dec2, data, len) == 0 && gc == 0,
"t=%d len=%zu gpu decode of cpu encode (gc=%d)", t, len, gc);
CHECK(ref_decode(enc_gpu, eclen, len, p, dec, &cc) == 0 &&
memcmp(dec, data, len) == 0,
"t=%d len=%zu cpu decode of gpu encode", t, len);
CHECK(bch_cuda_decode(enc_gpu, eclen, len, p, dec2, &gc) == 0 &&
memcmp(dec2, data, len) == 0 && gc == 0,
"t=%d len=%zu gpu decode of gpu encode", t, len);
/* dirty decode: flip k<=t bits in the first block. */
if (len > 0) {
size_t first = len < bch_max_data(p) ? len : bch_max_data(p);
size_t nbits = (size_t)8 * first + p->r;
int k = t < 3 ? t : 3;
memcpy(work, enc_cpu, eclen);
flip_bits(work, nbits, k);
int rc_cpu = ref_decode(work, eclen, len, p, dec, &cc);
int rc_gpu = bch_cuda_decode(work, eclen, len, p, dec2, &gc);
CHECK(rc_cpu == rc_gpu,
"t=%d len=%zu %d-bit flip: cpu rc=%d gpu rc=%d",
t, len, k, rc_cpu, rc_gpu);
if (rc_cpu == 0)
CHECK(memcmp(dec, dec2, len) == 0 && cc == gc,
"t=%d len=%zu %d-bit flip: decoded bytes/corr differ (cc=%d gc=%d)",
t, len, k, cc, gc);
/* t+1 bits in one block: GPU and CPU decode must agree. */
memcpy(work, enc_cpu, eclen);
flip_bits(work, nbits, t + 1);
rc_cpu = ref_decode(work, eclen, len, p, dec, &cc);
rc_gpu = bch_cuda_decode(work, eclen, len, p, dec2, &gc);
CHECK(rc_cpu == rc_gpu,
"t=%d len=%zu %d-bit flip: cpu rc=%d gpu rc=%d (must agree)",
t, len, t + 1, rc_cpu, rc_gpu);
if (rc_cpu == 0)
CHECK(memcmp(dec, dec2, len) == 0,
"t=%d len=%zu %d-bit flip: both decoded but differ",
t, len, t + 1);
}
free(enc_cpu);
free(enc_gpu);
free(dec);
free(dec2);
free(work);
}
static void bench_case(const uint8_t *data, size_t len, int t)
{
const bch_poly_t *p = test_poly(len, t);
if (!p) {
printf("SKIP bench t=%d len=%zu: no poly\n", t, len);
return;
}
size_t eclen = bch_encoded_len(len, p);
uint8_t *enc = malloc(eclen);
uint8_t *enc2 = malloc(eclen);
uint8_t *dec = malloc(len);
double ts[5];
double s, e;
int corr = 0;
/* first-call timing (table build + context init) */
s = now_s();
size_t gn = bch_cuda_encode(data, len, p, enc2);
e = now_s();
printf("t=%-2d len=%8zu first-gpu-encode %7.4f s (%7.1f MB/s, incl table build)\n",
t, len, e - s, (double)len / 1048576.0 / (e - s));
if (gn != eclen) { printf("gpu enc fail\n"); exit(1); }
/* steady-state GPU direct */
for (int i = 0; i < 5; i++) {
s = now_s();
gn = bch_cuda_encode(data, len, p, enc2);
e = now_s();
ts[i] = e - s;
if (gn != eclen) { printf("gpu enc fail\n"); exit(1); }
}
double gpu_enc = median(ts, 5);
/* dispatch path (bch_encode): must match GPU direct */
for (int i = 0; i < 5; i++) {
s = now_s();
if (bch_encode(data, len, p, enc) != eclen) { printf("disp enc fail\n"); exit(1); }
e = now_s();
ts[i] = e - s;
}
double disp_enc = median(ts, 5);
printf("t=%-2d len=%8zu ENCODE gpu-direct %7.4f s %8.1f MB/s | dispatch %7.4f s %8.1f MB/s | equal=%d\n",
t, len, gpu_enc, (double)len / 1048576.0 / gpu_enc,
disp_enc, (double)len / 1048576.0 / disp_enc,
memcmp(enc, enc2, eclen) == 0);
for (int i = 0; i < 5; i++) {
s = now_s();
if (bch_cuda_decode(enc, eclen, len, p, dec, &corr) != 0) { printf("gpu dec fail\n"); exit(1); }
e = now_s();
ts[i] = e - s;
}
double gpu_dec = median(ts, 5);
for (int i = 0; i < 5; i++) {
s = now_s();
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0) { printf("disp dec fail\n"); exit(1); }
e = now_s();
ts[i] = e - s;
}
double disp_dec = median(ts, 5);
printf("t=%-2d len=%8zu DECODE gpu-direct %7.4f s %8.1f MB/s | dispatch %7.4f s %8.1f MB/s\n",
t, len, gpu_dec, (double)len / 1048576.0 / gpu_dec,
disp_dec, (double)len / 1048576.0 / disp_dec);
CHECK(memcmp(dec, data, len) == 0, "t=%d len=%zu bench round-trip", t, len);
free(enc);
free(enc2);
free(dec);
}
int main(int argc, char **argv)
{
printf("CUDA available: %d\n", bch_cuda_available());
if (!bch_cuda_available()) {
printf("NO CUDA DEVICE -- cannot test\n");
return 1;
}
/* correctness grid */
static const size_t sizes[] = { 1, 2, 100, 4095, 4096, 4097, 8192,
65536, 524265, 524266, 1048576 };
static const int ts_[] = { 1, 2, 4, 8, 16, 32 };
size_t maxlen = 1048576;
uint8_t *buf = malloc(maxlen);
if (!buf) return 1;
rand_bytes(buf, maxlen);
for (size_t si = 0; si < sizeof(sizes) / sizeof(sizes[0]); si++) {
for (size_t ti = 0; ti < sizeof(ts_) / sizeof(ts_[0]); ti++) {
correctness_case(buf, sizes[si], ts_[ti]);
}
}
printf("correctness: %d checks, %d failures\n", checks, fails);
if (fails) {
printf("CORRECTNESS FAILED\n");
return 1;
}
/* benchmark data */
uint8_t *big = NULL;
size_t biglen = 0;
if (argc > 1) {
FILE *f = fopen(argv[1], "rb");
if (!f) { perror("fopen"); return 1; }
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
biglen = (size_t)n;
big = malloc(biglen);
if (fread(big, 1, biglen, f) != biglen) { printf("short read\n"); return 1; }
fclose(f);
} else {
biglen = 50u << 20;
big = malloc(biglen);
rand_bytes(big, biglen);
}
printf("bench blob %zu bytes (%.1f MiB)\n", biglen,
(double)biglen / 1048576.0);
for (size_t bi = 0; bi < 3; bi++) {
size_t L = bi == 0 ? (1u << 20) : bi == 1 ? (4u << 20) : biglen;
if (L > biglen)
L = biglen;
bench_case(big, L, 8);
bench_case(big, L, 32);
}
free(buf);
free(big);
printf("checks=%d fails=%d %s\n", checks, fails,
fails ? "FAILED" : "ALL OK");
return fails ? 1 : 0;
}