工程实践:基于 Verilator 搭建"设计可自检"的验证平台

写在前面:这篇文章不是讲 Verilator 怎么用,而是讲怎么让验证平台自己判定对错。我用项目里真实的 zcle_aenc_wrapper 作例子——它有 CSR、literals 从接口、AXI 主接口、三路编码通道、错误注入和 debug 总线,是典型的”跑起来不崩、但很难确认结果对不对”的模块。

口径说明:文中的接口信号取自真实设计 zcle_aenc_wrapper.v;代码是按这些端口写的可运行骨架,你可以直接拷到项目里改路径使用。涉及项目内部的状态编码只做必要抽象,不影响平台结构。

1. 为什么”跑完不崩”不算验证通过

用 Verilator 仿真一个 RTL 模块,最低限度只需要:例化顶层、打时钟、复位、跑若干周期、打印一句 PASS。项目里已有的 verilator_sim_main.cpp 就是这么做的:

1
2
3
4
5
for (int i = 0; i < SIM_CYCLES; i++) {
top->clk = 0; top->eval();
top->clk = 1; top->eval();
}
printf("[PASS] Verilator simulation completed: %d cycles without crash.\n", ...);

这能验证”编译能过、仿真不崩”,但回答不了三个真正重要的问题:

  1. 输出码流对不对? 没有 golden,只有波形,肉眼不可能逐 bit 核对 256 bit × N 拍的 AXI 写数据;
  2. 回压/边界场景会不会出错? 上游 ready 一直拉高、下游 AXI 一直 ready,等于没测握手与状态保持;
  3. 错误注入与 debug 总线是否按预期工作? 这些功能不触发就永远是”未验证”。

一套可自检的平台,要把这三点变成机器可判定的结论:输入与 golden 同源、输出自动抓包重组、结果自动比对、异常自动报错退出。

2. DUT 接口分析:从 wrapper 端口推导平台组件

zcle_aenc_wrapper 的端口按功能可以分成五组,每组对应平台里的一个组件:

Verilator 自检验证平台架构

端口组 真实信号(节选) 平台对应组件
CSR 配置 csr_aenc_enable、csr_aenc_cmp_thr[31:0]、csr_aenc_error_int[1:0] driver 的配置阶段
literals 输入 zcle_lit_hist_qvalid/qdata[127:0]/qstrb/block_last/chunk_last/frame_last/qready stimulus driver
literals 读返回 aenc_lit_pvalid/rdata[127:0]/rresp/pready、aenc_lit_qvalid/qdata/qstrb 简化 AXI 从模型
码流输出 zcle_zpke_arith_m_axi_aw*/w*/b*(256 bit 写数据通道) AXI monitor + 码流重组
状态与调试 aenc_descrp_vld/rsp_data[63:0]、aenc_debug_info_bus[164:0]、aenc_error_int[1:0] scoreboard / 断言

平台设计的第一条原则由此确定:先按端口分组,再决定组件边界。不要写一个大而全的 main() 把所有信号堆在一起——那样回压逻辑、抓包逻辑、比对逻辑会互相纠缠,调试时无法定位是 driver 错了还是 DUT 错了。

3. 平台分层与数据流

平台分四层,每层只做一件事:

1
2
3
4
① golden 层(Python)      —— 生成 stimulus.bin 与 expected.bin
② driver 层(C++) —— 按握手协议把 stimulus 喂给 DUT,随机化 ready
③ monitor 层(C++) —— 监听 AXI W 通道,按 wstrb 抽取有效字节重组码流
④ check 层(C++) —— 逐字节比对、检查描述符、检查错误注入与断言

四层之间只通过文件(stimulus.bin / expected.bin)和内存中的 std::vector<uint8_t> 传递数据。这个解耦很关键:golden 用 Python 写、比对在 C++ 做,两边独立实现,可以避免”用同一份错误逻辑既生成激励又生成期望”的自欺。

4. Golden 生成:Python 脚本

Golden 的目标是产出两个文件:喂给 DUT 的字面量字节流 stimulus.bin,以及期望的压缩码流 expected.bin。项目里已有 data/gen_stimulus.py、tb/compute_expected.py 等脚本,下面的 make_golden.py 是把它们整合成”一次生成、契约清晰”的版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python3
# make_golden.py —— 生成 stimulus.bin 与 expected.bin
import argparse, random, struct
from pathlib import Path

def gen_literals(nbytes: int, seed: int) -> bytes:
rng = random.Random(seed)
# 混合高熵与低熵段,覆盖不同压缩比
out = bytearray()
while len(out) < nbytes:
mode = rng.randrange(3)
if mode == 0: # 高熵随机
out += bytes(rng.randrange(256) for _ in range(rng.randrange(64, 512)))
elif mode == 1: # 低熵重复
v = rng.randrange(256)
out += bytes([v]) * rng.randrange(64, 512)
else: # 小幅游走,制造局部相关
v = rng.randrange(256)
for _ in range(rng.randrange(64, 512)):
out.append(v)
v = (v + rng.choice([-1, 0, 0, 0, 1])) & 0xff
return bytes(out[:nbytes])

def golden_compress(data: bytes) -> bytes:
# 项目里替换为 cmodel 的 arithmetic_compress_literals() 输出
# 这里用恒等变换占位,目的是固定 golden 与 RTL 的接口契约
return data

def main():
ap = argparse.ArgumentParser()
ap.add_argument("--nbytes", type=int, default=4096)
ap.add_argument("--seed", type=int, default=20261121)
ap.add_argument("--out", type=Path, default=Path("golden"))
args = ap.parse_args()
args.out.mkdir(exist_ok=True)

stim = gen_literals(args.nbytes, args.seed)
gold = golden_compress(stim)
(args.out / "stimulus.bin").write_bytes(stim)
(args.out / "expected.bin").write_bytes(gold)
# 元数据单独存,C++ 侧按同一格式读取
(args.out / "meta.txt").write_text(
f"stimulus_bytes={len(stim)}\nexpected_bytes={len(gold)}\nseed={args.seed}\n"
)
print(f"[GOLDEN] stimulus={len(stim)}B expected={len(gold)}B")

if __name__ == "__main__":
main()

三个注意点:

  1. 激励必须同时覆盖高熵、低熵和局部相关三种分布,否则只能验证”压缩器恰好工作”的一种情形;
  2. golden 与 stimulus 必须同一次生成、写在同一目录,避免版本错配;
  3. meta.txt 提供长度契约,C++ 侧先读它再分配缓冲,能提前发现 golden 与 testbench 不一致。

5. C++ Testbench:驱动、抓包、自检

下面是平台主体。代码按 zcle_aenc_wrapper.v 的真实端口写,Verilator 生成的头为 Vzcle_aenc_wrapper.h。

5.1 工具函数与状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "Vzcle_aenc_wrapper.h"
#include "verilated.h"
#include <cstdint>
#include <cstdio>
#include <fstream>
#include <vector>
#include <random>
#include <algorithm>

using u8 = uint8_t;
using u32 = uint32_t;
using u64 = uint64_t;
using u128 = unsigned __int128; // GCC/Clang 扩展,128-bit literals 数据用


static std::vector<u8> read_bin(const char* p) {
std::ifstream f(p, std::ios::binary);
return std::vector<u8>((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
}

struct AxiWrite {
u32 addr;
u8 strb; // 本拍有效字节掩码
u8 data[32]; // 256-bit 写数据按字节展开
bool last;
};

class TB {
public:
Vzcle_aenc_wrapper* dut;
std::mt19937 rng{20261121};
vluint64_t tick = 0;

std::vector<u8> stim, gold, captured;
std::vector<AxiWrite> wq; // AXI monitor 抓到的写事务
size_t stim_pos = 0;
int misfires = 0;
bool descrp_seen = false;

explicit TB(Vzcle_aenc_wrapper* d) : dut(d) {}

void reset() {
dut->clk = 0; dut->rst_n = 0;
dut->csr_aenc_enable = 0;
dut->csr_aenc_cmp_thr = 0;
dut->csr_aenc_error_int = 0;
dut->zcle_lit_hist_qvalid = 0;
dut->zcle_lit_hist_qwrite = 0;
dut->zcle_lit_hist_qaddr = 0;
dut->zcle_lit_hist_qdata = 0;
dut->zcle_lit_hist_qstrb = 0;
dut->aenc_lit_qready = 0;
dut->aenc_lit_pvalid = 0;
dut->zcle_zpke_arith_m_axi_awready = 0;
dut->zcle_zpke_arith_m_axi_wready = 0;
dut->zcle_zpke_arith_m_axi_bvalid = 0;
for (int i = 0; i < 10; ++i) step();
dut->rst_n = 1;
}

void step() {
dut->clk = 0; dut->eval();
dut->clk = 1; dut->eval();
tick++;
monitor(); // 在时钟上升沿后抓 AXI 写通道
}
...
};

关键点:monitor() 放在 step() 里、每个上升沿后调用,而不是写在 driver 循环里。这样无论 driver 做什么(发激励、等响应、故意停顿),monitor 都不会漏拍——抓包逻辑与驱动逻辑解耦是自检平台最重要的结构约束。

5.2 AXI monitor:把 256-bit 写数据重组为字节流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
void monitor() {
auto* d = dut;
// AW 通道:记录地址(用于描述符校验)
if (d->zcle_zpke_arith_m_axi_awvalid && d->zcle_zpke_arith_m_axi_awready) {
// 真实设计中 awaddr[25:20] 是 CBID,[19:0] 是块内偏移
// 这里只校验写地址在合理范围内
u32 off = d->zcle_zpke_arith_m_axi_awaddr & 0xfffff;
if (off > 0x200000) misfires++;
}

// W 通道:按 wstrb 抽取有效字节,重组码流
if (d->zcle_zpke_arith_m_axi_wvalid && d->zcle_zpke_arith_m_axi_wready) {
AxiWrite w;
w.addr = d->zcle_zpke_arith_m_axi_awaddr & 0xfffff;
w.strb = (u8)(d->zcle_zpke_arith_m_axi_wstrb & 0xff);
w.last = d->zcle_zpke_arith_m_axi_wlast;
// Verilator 把 256-bit 端口生成成 4 个 64-bit word(小端:word0 是低 64 位)
const u64 word[4] = {
(u64)d->zcle_zpke_arith_m_axi_wdata[0],
(u64)d->zcle_zpke_arith_m_axi_wdata[1],
(u64)d->zcle_zpke_arith_m_axi_wdata[2],
(u64)d->zcle_zpke_arith_m_axi_wdata[3]
};
for (int b = 0; b < 32; ++b) {
w.data[b] = (u8)((word[b / 8] >> ((b % 8) * 8)) & 0xff);
}
wq.push_back(w);
for (int b = 0; b < 32; ++b) {
if (w.strb & (1u << b)) captured.push_back(w.data[b]);
}
}

// 描述符响应:aenc_descrp_vld 是"本 chunk 完成"的判定信号
if (d->aenc_descrp_vld) descrp_seen = true;
}

注意这里用的是 zcle_aenc_wrapper.v 里的真实端口:wdata[255:0]、wstrb[31:0]、wlast,地址高 6 位是 CBID。按 wstrb 抽取有效字节是关键——AXI 的最后一拍通常不是满 32 字节,直接把 wdata 全部写入会导致 golden 比对错位。

5.3 Driver:喂 literals 并随机化回压

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void drive_stim() {
const int LIT_BEATS = 16; // 128-bit 数据 / 8-bit 字节 = 16 字节每拍
while (stim_pos < stim.size() || aenc_lit_pending()) {
dut->zcle_lit_hist_qvalid = (stim_pos < stim.size());
if (dut->zcle_lit_hist_qvalid && dut->zcle_lit_hist_qready) {
u8 buf[16] = {0};
size_t n = std::min<size_t>(16, stim.size() - stim_pos);
for (size_t i = 0; i < n; ++i) buf[i] = stim[stim_pos + i];
u128 val = 0;
for (int i = 15; i >= 0; --i) val = (val << 8) | buf[i];
dut->zcle_lit_hist_qdata = val;
dut->zcle_lit_hist_qstrb = (n == 16) ? 0xffff : (u16)((1u << n) - 1);
dut->zcle_lit_hist_block_last = (stim_pos + n >= stim.size());
dut->zcle_lit_hist_chunk_last = dut->zcle_lit_hist_block_last;
dut->zcle_lit_hist_frame_last = dut->zcle_lit_hist_block_last;
stim_pos += n;
}

// 随机化下游 AXI ready,制造真实回压
dut->zcle_zpke_arith_m_axi_awready = (rng() % 4) != 0;
dut->zcle_zpke_arith_m_axi_wready = (rng() % 3) != 0;
step();
}
dut->zcle_lit_hist_qvalid = 0;
}

bool aenc_lit_pending() const {
// aenc_lit_qvalid/qwrite 是 DUT 输出,代表它要向我们发起的 literals 搬运
return dut->aenc_lit_qvalid || dut->aenc_lit_pvalid;
}

回压随机化不是可选项。如果 awready/wready 恒为 1,AXI 写通道永远不反压,DUT 内部 store 状态机与 FIFO 的”暂停/恢复”分支就完全没被激励到。这里用 (rng()%4)!=0 和 (rng()%3)!=0 制造不同概率的反压,能在回归中触发大量平时遇不到的状态组合。

5.4 Scoreboard:自检判定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int check() {
int errs = 0;
// ① 码流逐字节比对
if (captured.size() != gold.size()) {
std::printf("[FAIL] size: DUT=%zu GOLD=%zu\n", captured.size(), gold.size());
errs++;
}
size_t n = std::min(captured.size(), gold.size());
for (size_t i = 0; i < n; ++i) {
if (captured[i] != gold[i]) {
if (errs < 10)
std::printf("[MIS %zu] DUT=%02x GOLD=%02x\n", i, captured[i], gold[i]);
errs++;
}
}
// ② 描述符响应:aenc_descrp_vld 必须出现,且 rsp_data 非零
if (!descrp_seen) { std::printf("[FAIL] no descriptor response\n"); errs++; }
// ③ 错误注入未开启时,error_int 必须为 0
if (dut->aenc_error_int != 0) { std::printf("[FAIL] unexpected error_int\n"); errs++; }
// ④ 超时/死锁
if (tick > 2'000'000) { std::printf("[FAIL] timeout\n"); errs++; }

std::printf("[%s] bytes=%zu mismatches=%d ticks=%llu\n",
errs ? "FAIL" : "PASS", n, errs, (unsigned long long)tick);
return errs ? 1 : 0;
}

四条检查分别对应四类风险:数据错误、协议响应缺失、异常误报、死锁。只有四条全过,平台才打印 PASS 并返回 0——这就是”设计可自检”的含义:退出码本身就是验证结论,可以直接接 CI。

5.5 main:组装四层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int main(int argc, char** argv) {
Verilated::commandArgs(argc, argv);
auto* dut = new Vzcle_aenc_wrapper;
TB tb(dut);

tb.stim = read_bin("golden/stimulus.bin");
tb.gold = read_bin("golden/expected.bin");
if (tb.stim.empty() || tb.gold.empty()) {
std::fprintf(stderr, "run make_golden.py first\n");
return 2;
}

tb.reset();
dut->csr_aenc_enable = 1;
dut->csr_aenc_cmp_thr = 0xffff;
tb.drive_stim();

// 等待描述符响应与 AXI 事务收尾
for (int i = 0; i < 20000 && !tb.descrp_seen; ++i) {
dut->zcle_zpke_arith_m_axi_awready = 1;
dut->zcle_zpke_arith_m_axi_wready = 1;
tb.step();
}

int rc = tb.check();
dut->final();
delete dut;
return rc;
}

6. Makefile 与一键运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Makefile —— Verilator 自检平台
RTL_DIR ?= ../../RTL/zcle_aenc
TB_DIR ?= ../../tb
GOLDEN ?= golden

VERILATOR ?= verilator
CXX ?= g++
OPT := -O2 -std=c++17
INC := -I$(RTL_DIR)/rtl -I$(RTL_DIR)/rtl/zcle_aenc_core_wrapper \
-I$(RTL_DIR)/rtl/zcle_aenc_core_wrapper/sfifo_wrapper \
-I$(RTL_DIR)/rtl/zcle_aenc_core_wrapper/mem_wrapper \
-I$(RTL_DIR)/common -I$(RTL_DIR)/mem

# Verilator 规范化生成的源文件列表由 --top-module 自动展开
VL_FLAGS := --cc --exe --build -j 0 -Wno-fatal \
--top-module zcle_aenc_wrapper \
$(INC) -CFLAGS "$(OPT)"

.PHONY: golden sim clean
golden:
python3 make_golden.py --nbytes 4096 --out $(GOLDEN)

sim: golden
$(VERILATOR) $(VL_FLAGS) -Mdir obj_dir \
$(RTL_DIR)/rtl/zcle_aenc_wrapper.v \
$(shell find $(RTL_DIR)/rtl -name '*.v' ! -name 'zcle_aenc_wrapper.v') \
$(RTL_DIR)/common/*.v $(RTL_DIR)/mem/*.v \
sim_main.cpp -o sim
./obj_dir/sim

clean:
rm -rf obj_dir sim $(GOLDEN)

一键运行:

1
2
make sim      # 生成 golden → 编译 Verilator → 跑自检 → 看 PASS/FAIL
echo $? # 0 = 通过,1 = 比对失败,2 = golden 缺失

Windows 下把 rm -rf 换成 if exist ... rmdir /s /q,其余逻辑不变;项目原有的 .bat 脚本已经用同样思路做了 iverilog 编译 + findstr "RESULT: PASS" 判定,可以沿用那套批处理风格。

7. 让自检更可靠的四个实践

7.1 错误注入要专门跑一遍

zcle_aenc_wrapper 有 zcle_aenc_par_chk_en、zcle_aenc_err_ins[2:0] 和 csr_aenc_error_int[1:0]。自检平台应该有一个反向用例:打开错误注入,确认 aenc_error_int 确实拉起、并且 aenc_descrp_rsp_data 携带了错误码。否则”错误注入功能”在验证里等于不存在。

7.2 debug 总线做状态断言

aenc_debug_info_bus[164:0] 是内部状态观测口。与其只拿它打印波形,不如在 monitor 里加断言:

1
2
3
4
5
6
// 伪代码:debug bus 的某几位代表 loader/core 状态
if (dut->aenc_debug_info_bus & DEBUG_CORE_BUSY_MASK) core_busy_seen = true;
if (core_busy_seen && !dut->csr_aenc_enable) {
std::printf("[FAIL] core busy while disabled\n");
errs++;
}

断言要围绕状态一致性,而不是”某信号等于某值”——后者一旦 RTL 重构就全部失效。

7.3 golden 与 RTL 用不同实现路径

项目 plan 里给出三种对齐方法,自检平台应按层次选用:

层次 方法 本平台对应
单元级 Verilator + DPI 调 cmodel,逐 bit 比对 unit/ 子平台
模块级 Python golden model,比对中间结果(ctx / lane_size / stream) make_golden.py 的元数据扩展
系统级 Verilator + cmodel DPI,AXI 输出逐 bit 对比 本文的 wrapper 平台

关键是 golden 不能由 RTL 反向生成。用 Python 独立实现、或从 cmodel 导出,才能形成真正的交叉验证。

7.4 回归要随机化 seed

把 --seed 暴露成命令行参数,在 CI 里跑一组 seed:

1
2
3
4
for s in 1 2 3 4 5 11 21 42 99 20261121; do
python3 make_golden.py --seed $s --out golden_$s || exit 1
./obj_dir/sim golden_$s || exit 1
done

不同 seed 生成不同数据分布,能覆盖更多压缩比与边界长度组合,比固定一个用例反复跑有效得多。

8. 小结

给一套复杂 RTL 搭 Verilator 平台,真正要解决的问题不是”怎么让波形跑起来”,而是怎么让平台自己给出可信结论。本文用 zcle_aenc_wrapper 把这件事拆成四条:

  1. 接口分组决定组件边界:CSR / 输入 / AXI 输出 / 状态,各对应一个 driver 或 monitor;
  2. golden 与 stimulus 同源但异构:Python 独立生成,契约文件固定长度与种子;
  3. monitor 独立于 driver:抓包放在 step() 里,保证不漏拍;按 wstrb 抽取有效字节,避免最后一拍错位;
  4. 判定标准化:退出码 = 验证结论,比对、响应、异常、超时四类检查全过才 PASS。

这样搭出来的平台,不依赖人工看波形,可以直接接 CI;换一个 DUT,只需要替换端口驱动部分,monitor 和 scoreboard 基本可以原样复用。

相关阅读