如何计算快照 CRC64 并落盘校验?

解读

在国内中大型后端或存储团队面试中,“快照 CRC64 计算与落盘校验”常被用来考察候选人对大文件一致性、增量更新、断电恢复的理解。
核心诉求不是背算法,而是给出一条可工程落地的 C 实现路径:

  1. 64 bit 滚动 CRC 的查表法实现;
  2. 快照分块(如 4 MiB)并行计算,内存占用可控;
  3. 结果原子写到文件尾部,重启后秒级校验;
  4. 处理稀疏文件、hole、punch等 Linux 特殊场景;
  5. 失败时返回 errno 语义化错误码,方便上层重试或告警。

知识点

  • CRC64-ECMA 规范:多项式 0x42F0E1EBA9EA3693,反射输入输出,初始值 0xFFFFFFFFFFFFFFFF。
  • slice-by-8 查表:预生成 8×256 条 64 bit 表,把 CPU Cache Miss 降到 1/8,在 x86_64 上实测 >3 GB/s。
  • O_DIRECT 对齐:块大小必须是 512 的倍数,用户缓冲区按 page 对齐,防止内核 bounce buffer。
  • posix_fadvise(POSIX_FADV_SEQUENTIAL):提前驱逐 Cache,避免污染业务热数据。
  • fdatasync() 先于 rename():保证目录项原子提交,掉电不撕裂。
  • mmap 只读模式校验:把 CRC 文件映射进来,省一次 read 系统调用,对容器场景友好。
  • 线程池 + 无锁队列:分块任务用 单生产者单消费者 模型,避免 false sharing。
  • errno 标准化:返回 -EIO_CRC_MISMATCH(自定义 512)、-EIO、-ENOMEM 等,与 systemd 日志级别对齐。

答案

以下代码可直接放进存储仓库的 crc64_snapshot.c,编译 flags:-O2 -D_GNU_SOURCE -lpthread。
思路:主线程负责 I/O,线程池做 CPU 计算,CRC 结果最后 8 byte 原子写回;重启时只读映射并比对。

#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <pthread.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>

#define CHUNK_SHIFT 22              /* 4 MiB */
#define CHUNK_SIZE  (1U<<CHUNK_SHIFT)
#define THREADS     4
static uint64_t crc64_table[8][256];

/* 初始化 slice-by-8 表,程序启动调用一次 */
static void crc64_init(void)
{
    uint64_t poly = 0x42F0E1EBA9EA3693;
    for (int i = 0; i < 256; i++) {
        uint64_t v = i;
        for (int j = 0; j < 8; j++) v = (v >> 1) ^ (poly & -(v & 1));
        crc64_table[0][i] = v;
    }
    for (int s = 1; s < 8; s++)
        for (int i = 0; i < 256; i++)
            crc64_table[s][i] =
                (crc64_table[s-1][i] >> 8) ^ crc64_table[0][crc64_table[s-1][i] & 0xff];
}

static uint64_t crc64_update(uint64_t crc, const uint8_t *p, size_t len)
{
    crc = ~crc;
    while (len >= 8) {
        crc ^= *(uint64_t *)p;
        for (int i = 0; i < 8; i++)
            crc = (crc >> 8) ^ crc64_table[i][crc & 0xff];
        p += 8; len -= 8;
    }
    while (len--) crc = (crc >> 8) ^ crc64_table[0][(crc & 0xff) ^ *p++];
    return ~crc;
}

typedef struct {
    int      fd;
    off_t    offset;
    size_t   size;
    uint64_t crc;
} task_t;

static pthread_mutex_t q_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t  q_cond = PTHREAD_COND_INITIALIZER;
static task_t queue[128];
static int q_in, q_out;

static void *worker(void *arg)
{
    for (;;) {
        pthread_mutex_lock(&q_lock);
        while (q_in == q_out) pthread_cond_wait(&q_cond, &q_lock);
        task_t t = queue[q_out++];
        pthread_mutex_unlock(&q_lock);

        uint8_t *buf = aligned_alloc(512, t.size);
        if (pread(t.fd, buf, t.size, t.offset) != (ssize_t)t.size) {
            free(buf); return (void *)(long)-EIO;
        }
        t.crc = crc64_update(0, buf, t.size);
        free(buf);

        pthread_mutex_lock(&q_lock);
        /* 把结果写回原位,主线程聚合 */
        for (int i = 0; i < q_in; i++)
            if (queue[i].offset == t.offset) { queue[i].crc = t.crc; break; }
        pthread_mutex_unlock(&q_lock);
    }
    return 0;
}

/* 计算快照 CRC64 并追加到文件末尾,返回 0 或 -errno */
int snapshot_crc64_append(const char *path)
{
    int fd = open(path, O_RDWR | O_DIRECT);
    if (fd < 0) return -errno;

    struct stat st;
    if (fstat(fd, &st) < 0) { close(fd); return -errno; }
    off_t total = st.st_size;

    pthread_t tid[THREADS];
    for (int i = 0; i < THREADS; i++)
        pthread_create(&tid[i], NULL, worker, NULL);

    off_t off = 0;
    while (off < total) {
        size_t len = CHUNK_SIZE;
        if (off + len > total) len = total - off;
        pthread_mutex_lock(&q_lock);
        queue[q_in++] = (task_t){fd, off, len, 0};
        pthread_cond_signal(&q_cond);
        pthread_mutex_unlock(&q_lock);
        off += len;
    }

    /* 等待所有任务完成 */
    while (q_in > q_out) usleep(1000);

    uint64_t final = 0;
    for (int i = 0; i < q_in; i++) final = crc64_update(final, (uint8_t *)&queue[i].crc, 8);

    /* 原子追加 */
    if (pwrite(fd, &final, 8, total) != 8) { close(fd); return -EIO; }
    if (fdatasync(fd) < 0) { close(fd); return -errno; }
    close(fd);
    return 0;
}

/* 重启后校验,返回 0 或 -EIO_CRC_MISMATCH */
int snapshot_crc64_verify(const char *path)
{
    int fd = open(path, O_RDONLY);
    if (fd < 0) return -errno;
    struct stat st;
    if (fstat(fd, &st) < 0) { close(fd); return -errno; }
    if (st.st_size < 8) { close(fd); return -EIO; }

    uint64_t expected;
    if (pread(fd, &expected, 8, st.st_size - 8) != 8) { close(fd); return -EIO; }

    /* 重新计算前面所有数据的 CRC64 */
    off_t total = st.st_size - 8;
    off_t off = 0;
    uint64_t crc = 0;
    uint8_t *buf = aligned_alloc(512, CHUNK_SIZE);
    while (off < total) {
        size_t len = CHUNK_SIZE;
        if (off + len > total) len = total - off;
        if (pread(fd, buf, len, off) != (ssize_t)len) { free(buf); close(fd); return -EIO; }
        crc = crc64_update(crc, buf, len);
        off += len;
    }
    free(buf); close(fd);
    return (crc == expected) ? 0 : -EIO_CRC_MISMATCH;
}

使用示例:
snapshot_crc64_append("/data/vol1.snap") 落盘;重启后调用 snapshot_crc64_verify 做秒级开机自检,失败直接触发 rsync 拉取远端副本。

拓展思考

  1. 增量快照:结合 bmap(block bitmap)只计算发生写时复制的 4 KiB 块,把 CRC64 拆成 16 层 Merkle 树,实现 秒级增量校验。
  2. SIMD 优化:用 AVX-512 vpclmulqdq 一次处理 64 byte,单核可达 20 GB/s,但需 运行时 cpuid 检测降级到 slice-by-8。
  3. 加密需求:在 CRC64 后追加 HMAC-SHA256,防止恶意篡改,密钥走 kernel keyring 避免驻留进程内存。
  4. 容器场景:把 CRC 文件放到 tmpfs,降低 overlayfs 双倍写放大;主机掉电时由 external-log 重放保证一致性。