6.4 Verilog 竞争与冒险
系统剖析组合逻辑竞争与冒险的物理成因、代数法与卡诺图判定方法、四种经典消除策略(滤波电容、冗余项、同步打拍、格雷码),并逐条解读六大 Verilog 防竞争编码规范。
学完这一章,你能够
- 系统剖析组合逻辑竞争与冒险的物理成因、代数法与卡诺图判定方法、四种经典消除策略(滤波电容、冗余项、同步打拍、格雷码),并逐条解读六大 Verilog 防竞争编码规范。
竞争与冒险的成因及判定方法
真实数字电路中门级与连线均存在传播延时。在组合逻辑中,同一或不同来源的输入变化沿不同路径到达同一逻辑门的时间有先有后,称为竞争(Competition);由此在过渡期产生的瞬态错误输出(如尖峰毛刺脉冲)称为冒险(Hazard)。竞争不一定引发冒险,但冒险必然源于竞争——例如 `F = A & A'` 中因反相器引入额外延时,`A` 从 0 变 1 时 `A'` 尚未及时翻落,会令与门短暂吐出正毛刺;即便输入来自独立信号,只要门端到达时刻存在偏斜同样可能产生冒险。
静态冒险有两种经典判定方法。代数法:固定一个变量,将其他变量取 0 或 1 代入表达式,若能化简出 `Y = A + A'`(静态 1 冒险)或 `Y = A · A'`(静态 0 冒险),则电路存在竞争冒险,如 `Y = AB + A'C` 在 `B=C=1` 时化为 `A + A'`。卡诺图法更直观:当两个相邻卡诺圈相切且相切边界未被第三个卡诺圈覆盖时即存在冒险(例如 `Y = A'B' + AC` 在 `B=0, C=1` 时发生冒险,而 `Y = A'B' + AB` 不存在相切圆故无冒险);注意卡诺图具有首尾循环相邻性(如 `m6` 与 `m4` 相邻),高维复杂电路则需结合 EDA 仿真与时序工具分析。
消除竞争与冒险的四种方法
传统硬件与 RTL 设计中有四种消除思路:(1)输出端并联小滤波电容吸收窄毛刺,虽简单但会劣化边沿翻转速率、破坏数字波形,不用于片内 RTL 设计;(2)修改逻辑增加冗余项(共识项),例如为 `Y = A'B' + AC` 补入覆盖相切边界的卡诺圈 `B'C` 变为 `Y = A'B' + AC + B'C`,即可在 `B=0, C=1` 时锁死输出为 1,不过现代综合工具可能自动优化掉未加保留属性的冗余项。
(3)在同步时序电路中利用 D 触发器打拍同步,是 Verilog 设计最核心的工程手段。只要毛刺未落入建立/保持时间窗口,触发器 D 端对时钟沿之外的组合毛刺天然免疫。对照实验表明:异步信号 `en`(19ns 升 1)与 `din_rvs`(20ns 降 0)直接相与会在 `condition` 上形成 1ns 尖峰,紧贴时钟上升沿时极易被误采;先用触发器将输入同步打拍(工程上跨时钟域常用 2~3 拍)后再做组合逻辑运算,即可彻底消除内部组合毛刺。(注:可综合 RTL 中低有效异步复位敏感列表应规范写作 `always @(posedge clk or negedge rstn)`,避免对复位信号取反写入敏感列表。)
(4)采用格雷码计数器:普通二进制计数器从 `5`(`4'b0101`)跳变到 `6`(`4'b0110`)涉及多位同时翻转,若各位延时不同可能短暂经过 `4'b0111` 触发 `counter == 4'd7` 假脉冲;格雷码相邻数值仅翻转 1 bit,既能消除多比特偏斜冒险(常见于异步 FIFO 指针跨时钟域传递),也能在高速时钟下降低翻转功耗。综合来看,RTL 工程首要依靠同步触发器打拍与规范编码来根除竞争冒险。
六大 Verilog 防竞争编码规范
严格遵守六条编码纪律可规避绝大多数仿真与综合竞争:(1)时序电路建模一律使用非阻塞赋值 `<=`(如交换 `a <= b; b <= a;`,避免阻塞赋值因执行顺序产生覆盖竞争);(2)组合逻辑建模一律使用阻塞赋值 `=`,保证 `C = A & B; F = C & D;` 按顺序即时传递新值,防止非阻塞赋值读取旧值 `C` 甚至误推 Latch。
(3)在同一时序 `always` 块中同时包含组合表达式与寄存器输出时(如 `q <= a & b;`),仍统一采用非阻塞赋值;(4)严禁在同一 `always` 块内混用阻塞与非阻塞赋值,无论在组合块还是时序块中混用都会导致同一信号不同分支生效周期错乱、前后仿真不一致;(5)禁止在多个 `always` 块或多个 `assign` 语句中对同一变量多源驱动(Multiple Driver),综合与编译均会报 Error;(6)规范书写条件与分支以彻底避免意外 Latch(详见下一章)。来源工程压缩包已登记未联网抓取。
离线验证冗余项消冒险、异步毛刺打拍抑制、格雷码单比特翻转与编码规范
展开查看收起
"""Offline Verilog RTL verification lab for Chapter 25 (competition-hazard)."""
import json
VERSION = "CPython 3.12.14 offline Verilog RTL bit-accurate simulator (iverilog absent)"
def eval_with_skew(expr_fn, a_transitions, b, c):
"""Evaluate expression across a skewed transition of A and A_bar to detect static-1/0 glitch."""
# Suppose A transitions 0->1 while A_bar still lags at 1->0 (or 1->0 while A_bar stays 0->1)
outputs = []
for a_val, a_bar_val in a_transitions:
outputs.append(expr_fn(a_val, a_bar_val, b, c))
return outputs
def case_algebraic_and_redundant_term_elimination():
"""Verify static-1 hazard in Y = A'B' + AC at B=0, C=1 and elimination by consensus term B'C."""
# Transition A: 1->0 with inverter delay -> (A=1,A'=0) -> transient (A=0,A'=0) -> (A=0,A'=1)
skew_seq = [(1, 0), (0, 0), (0, 1)]
y_hazard = eval_with_skew(lambda a, ab, b, c: int((ab and (not b)) or (a and c)), skew_seq, b=0, c=1)
y_safe = eval_with_skew(
lambda a, ab, b, c: int((ab and (not b)) or (a and c) or ((not b) and c)), skew_seq, b=0, c=1
)
# Also check F = A & A' static-0 hazard during A: 0->1 -> (0,1) -> (1,1) -> (1,0)
f_and_glitch = eval_with_skew(lambda a, ab, b, c: int(a and ab), [(0, 1), (1, 1), (1, 0)], 0, 0)
expected = {
"y_without_consensus": [1, 0, 1],
"y_with_consensus_BbarC": [1, 1, 1],
"f_A_and_Abar_glitch": [0, 1, 0],
}
actual = {
"y_without_consensus": y_hazard,
"y_with_consensus_BbarC": y_safe,
"f_A_and_Abar_glitch": f_and_glitch,
}
return {
"name": "algebraic_and_redundant_term_elimination",
"summary": "验证逻辑表达式 Y=A'B'+AC 与 F=A&A' 在反相器延时下的毛刺及增加冗余项 B'C 消除冒险",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_async_glitch_vs_sync_register_clap():
"""Simulate competition_hazard vs clap_delay on t=19ns en=1 and t=20ns din_rvs=0."""
# Timeline t = 0..35ns, clk toggles every 5ns starting low (posedge at 10, 20, 30)
# Unregistered condition = en & din_rvs: at t=19ns en=1, din_rvs=1 -> glitch=1 for 1ns [19, 20)
raw_cond_at_19ns = 1 & 1
raw_cond_at_20ns = 1 & 0
# With 1-stage input register (clap_delay) sampling at posedge 10, 20, 30:
# At posedge 10: en=0, din_rvs=1 -> en_r=0, din_rvs_r=1 -> cond=0
# At posedge 20 (after din_rvs->0 at 20ns, or even before if setup missed): synchronized outputs change on edge only
sync_samples = []
for t_edge, en_val, din_val in [(10, 0, 1), (20, 1, 0), (30, 1, 0)]:
sync_samples.append((t_edge, en_val & din_val))
expected = {
"raw_glitch_at_19ns": 1,
"raw_settled_at_20ns": 0,
"sync_condition_all_zero": True,
}
actual = {
"raw_glitch_at_19ns": raw_cond_at_19ns,
"raw_settled_at_20ns": raw_cond_at_20ns,
"sync_condition_all_zero": all(v == 0 for _, v in sync_samples),
}
return {
"name": "async_glitch_vs_sync_register_clap",
"summary": "仿真异步信号 en/din_rvs 在 t=19ns 产生的 1ns 毛刺脉冲与时钟打拍同步后的毛刺抑制效果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_binary_vs_gray_counter_transitions():
"""Compare multi-bit binary transition (5->6 passing 7) against 1-bit Gray code transitions."""
# Binary 5 (0101) -> 6 (0110) flips 2 bits; transient intermediate 7 (0111) triggers cout==(counter==7)
bin_hamming_5_to_6 = bin(0b0101 ^ 0b0110).count("1")
gray_seq = [n ^ (n >> 1) for n in range(16)]
gray_hamming_all_one = all(
bin(gray_seq[i] ^ gray_seq[(i + 1) % 16]).count("1") == 1 for i in range(16)
)
expected = {"binary_5_to_6_bit_flips": 2, "transient_7_glitch_possible": True, "gray_4bit_all_hamming_1": True}
actual = {
"binary_5_to_6_bit_flips": bin_hamming_5_to_6,
"transient_7_glitch_possible": bin_hamming_5_to_6 > 1,
"gray_4bit_all_hamming_1": gray_hamming_all_one,
}
return {
"name": "binary_vs_gray_counter_transitions",
"summary": "验证 4-bit 二进制计数器 5->6 两位同时翻转可经 7 产生假脉冲,而格雷码相邻仅 1-bit 翻转",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_blocking_vs_nonblocking_coding_rules():
"""Verify the 6 Verilog coding rules: swap with NBA vs BA, and combinational chain BA vs NBA."""
# Rule 1: sequential swap (a=1, b=2)
a_ba, b_ba = 1, 2
a_ba = b_ba
b_ba = a_ba # clobbered -> (2, 2)
a_nba, b_nba = 1, 2
a_nba, b_nba = b_nba, a_nba # swapped -> (2, 1)
# Rule 2: combinational C=A&B; F=C&D; when A=1,B=1,D=1 and old C=0
old_c = 0
# NBA in comb uses old C
f_nba_wrong = old_c & 1
# BA in comb uses updated C
c_ba = 1 & 1
f_ba_right = c_ba & 1
expected = {
"seq_ba_swap_broken": [2, 2],
"seq_nba_swap_ok": [2, 1],
"comb_nba_stale_F": 0,
"comb_ba_fresh_F": 1,
}
actual = {
"seq_ba_swap_broken": [a_ba, b_ba],
"seq_nba_swap_ok": [a_nba, b_nba],
"comb_nba_stale_F": f_nba_wrong,
"comb_ba_fresh_F": f_ba_right,
}
return {
"name": "blocking_vs_nonblocking_coding_rules",
"summary": "验证时序块用非阻塞赋值、组合块用阻塞赋值以及混用/错用引发的仿真与综合偏差",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_algebraic_and_redundant_term_elimination(),
case_async_glitch_vs_sync_register_clap(),
case_binary_vs_gray_counter_transitions(),
case_blocking_vs_nonblocking_coding_rules(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
当 `B = 0, C = 1` 时表达式退化为 `Y = A' + A`,在 `A` 翻转期间因反相器延时会出现瞬态 0 凹陷(静态 1 冒险);依据共识定理添加冗余项 `B'C`(得 `Y = A'B' + AC + B'C`),在 `B = 0, C = 1` 时恒由 `B'C = 1` 维持输出为 1,从而消除冒险。