Verifying an RTL Block with a SystemVerilog UVM Testbench
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
During a hardware verification interview, you are asked to walk through how you would design, implement, and sign off a SystemVerilog UVM verification environment for a digital RTL module.
As a concrete target, consider a pipelined processing unit with one upstream streaming port and one downstream streaming port, both synchronized by a standard valid/ready handshake. Every accepted upstream beat carries a transaction tag (id) and a payload word (data); the module transforms the payload and produces one downstream beat per accepted input. (You may substitute a comparable RTL module from your own experience provided you explicitly define its ports and handshakes.)
Begin by stating clear assumptions for any open architectural details—such as whether downstream beats always exit in arrival order or can overtake one another across distinct id values, whether golden predictions come from an external C/C++ model or native SystemVerilog logic, whether control/mode registers are programmed before traffic flows, and whether the unit bench must later plug into a larger subsystem or SoC testbench. Then organize your design across three areas:
- Environment topology and signal plumbing: Lay out the UVM class hierarchy, the role of active versus passive agents, TLM communication channels, how dynamic class instances access static RTL wires, UVM phase ordering, factory-based test customization, pin-level protocol assertions, and the step-by-step path of a single item from sequence creation to pin toggles.
- Independent monitoring and scoreboarding: Explain why a dedicated monitor observes physical pins instead of trusting driver intent, how expected outputs are predicted and matched under both FIFO and out-of-order completion rules, how end-of-test drain handling catches silently dropped or spurious outputs, and what context error logs should capture for fast triage.
- Coverage strategy and verification closure: Contrast structural RTL code coverage against plan-driven functional coverage, sketch representative coverpoints, corner bins, crosses, and assertion coverage for this module, and describe the closed-loop workflow—combining constrained-random seeds, hole analysis, and surgical directed tests—needed to reach true sign-off.
Scope & Expectations
- Clear architectural boundaries: A crisp distinction between static hardware modules/interfaces and dynamic UVM classes, showing how virtual interfaces, clocking blocks, TLM analysis ports, and active/passive agent modes fit together cleanly for both unit testing and subsystem reuse.
- Self-checking rigor under reordering and drops: A concrete scoreboard and assertion strategy that predicts results using the configuration active at arrival time, handles cross-ID reordering without losing per-ID FIFO guarantees, and catches missing, hung, or unexpected transfers before simulation exits.
- Actionable coverage design: Well-chosen covergroups (value corners, stall/back-pressure profiles, cross combinations) paired with concurrent protocol properties, alongside a clear explanation of what code coverage and functional coverage each miss in isolation.
- Disciplined closure criteria: Practical reasoning about constraint weighting, coverage exclusions, non-vacuous assertions, multi-seed regression stability, and bug-rate convergence rather than treating a raw percentage as proof of correctness.
Step-by-step walkthrough
Clarify the hardware spec and build a verification plan
Before sketching any classes, pin down how the DUT (Design Under Test — the RTL, or Register-Transfer Level hardware block written in Verilog/SystemVerilog, that we are testing) behaves at its boundaries. Locking down the interface, ordering, prediction, and reuse assumptions up front anchors every architectural decision that follows:
- Interfaces and handshake: Both the input port (
in_valid,in_ready,in_id[3:0],in_data[31:0]) and output port (out_valid,out_ready,out_id[3:0],out_data[31:0]) share a rising-edge clockclkand active-low resetrst_n. They use a standard valid/ready handshake: a transaction transfers on any rising clock edge wherevalid && readyare both1, and once the sender raisesvalid, it must keepvalid,id, anddatasteady untilreadyis1. - Ordering rule (assumed): Transactions with different IDs (
0..15) may finish out of order, whereas transactions with the same ID must come out in FIFO (first-in, first-out) order — a very common rule in AXI-style hardware pipelines. - Reference model (assumed): A golden C function
ref_model(mode, id, data)exists and is called from SystemVerilog via DPI-C (Direct Programming Interface for C, which lets SystemVerilog call C functions directly). Without a C model, we write an equivalent predictor function in SystemVerilog. - Configuration & reuse (assumed): A
ctrl.moderegister is programmed over a control bus before traffic starts, tracked using RAL (the UVM Register Abstraction Layer, a software mirror of hardware registers), and the block-level environment must be reusable inside a larger chip or subsystem testbench.
From those rules, we write a concise verification plan mapping every spec requirement to how we check it and how we measure that we tested it:
Spec Requirement Checked By Covered By ------------------------------- -------------------------------- ---------------------------------- Output math matches spec Scoreboard vs C reference model Data corner bins crossed with mode Same-ID FIFO, cross-ID reorder Scoreboard per-ID FIFO queues ID crossed with out-of-order event Valid/ready hold under stall Interface SVA assertions Input/output wait-cycle bins No dropped or phantom outputs Drain + check_phase + watchdog (Pass/fail check, not a bin) Clean recovery from mid-run rst Scoreboard flush + reset SVA Reset-while-busy cover property- Interfaces and handshake: Both the input port (
Sketch the UVM architecture and component roles
UVM (Universal Verification Methodology) separates a testbench into two worlds:
- The static world (
modules):tb_top, clock/reset generators, SystemVeriloginterfaceinstances, and the RTLdut. These are wired together at elaboration time (before time0, like soldering chips onto a board). - The dynamic world (
classobjects): UVM components (env, agents, drivers, monitors, scoreboard, coverage) and short-lived transaction objects (txn), constructed at run time whenrun_test()executes.
tb_top (SystemVerilog module — static world, exists from time 0) ├─ clk / rst_n generators ├─ in_if : in_stream_if (wires + clocking blocks + SVA protocol assertions) ├─ out_if : out_stream_if (wires + clocking blocks + SVA protocol assertions) ├─ dut : my_block (RTL pins wired to in_if and out_if) └─ initial: uvm_config_db::set(... "vif" ...); run_test(); ==================================================================================== uvm_test_top : base_test (UVM classes — dynamic world, built at run time) └─ env ├─ in_agt (ACTIVE) sequencer ──► in_driver ─────────────► drives in_if wires │ in_monitor ◄── samples in_if; ap ──────────────────┐ ├─ out_agt (ACTIVE) sequencer ──► out_ready_driver ──────► out_if.ready│ │ out_monitor ◄─ samples out_if; ap ───────────────┐ │ ├─ reg_agt + RAL register mirror (tracks ctrl.mode writes) │ │ ├─ scoreboard in_imp ◄────────────────────────────────────────┼─┤ │ out_imp ◄────────────────────────────────────────┘ │ └─ in_coverage / out_coverage (subscribers) ◄────────────────────────────┘Each UVM component has one focused job, connected by TLM (Transaction-Level Modeling) ports (typed message pipes that pass
txnobjects between classes):txn(uvm_sequence_item): A data packet holding one transaction (id,data, stimulus delayidle, and observed stall countwaited).- Sequence & Sequencer: A sequence generates randomized
txnitems; the sequencer arbitrates when multiple sequences run and hands one item at a time to the driver. - Driver: Pulls
txnitems from the sequencer and wiggles hardware pins cycle-by-cycle according to the valid/ready protocol. - Monitor: Passively watches the hardware pins, reconstructs a
txnevery time a realvalid && readytransfer occurs, and broadcasts it out an analysis port (ap, a one-to-many publish-subscribe port). - Agent: Bundles sequencer, driver, and monitor for one interface. An active agent (
UVM_ACTIVE) instantiates all three to drive pins; a passive agent (UVM_PASSIVE) instantiates only the monitor when real neighboring RTL drives the pins. Noticeout_agtis active at block level because someone must driveout_ready(injecting random back-pressure — holdingout_ready = 0to stall the DUT's output pipeline).
- The static world (
Bridge static wires to classes with virtual interfaces and SVA
Because a dynamic SystemVerilog
classcannot contain hardwaremoduleports, UVM bridges the two worlds with a virtual interface (virtual in_stream_if vif) — a pointer-like handle to a physicalinterfaceinstance.tb_topstores each handle intouvm_config_db(UVM's key-value configuration dictionary) at time0, and drivers/monitors look up"vif"duringbuild_phasewithout hard-coding brittle hierarchical paths liketb_top.dut.in_valid.Inside the
interface, we place two essential constructs: - Clocking blocks (drv_cb,mon_cb): Prevent simulator race conditions between testbench classes and RTL flip-flops by sampling inputs#1step(immediately before the clock edge, seeing the exact pre-edge values the flip-flops capture) and driving outputs#1time unit after the clock edge. - SVA (SystemVerilog Assertions): Concurrent cycle-by-cycle protocol checks that stay active whether the pins are driven by a UVM driver or by real RTL in a subsystem!interface in_stream_if (input logic clk, input logic rst_n); logic valid; logic ready; logic [3:0] id; logic [31:0] data; // Driver clocking block: sample ready just before posedge clk, drive outputs 1ns after. clocking drv_cb @(posedge clk); default input #1step output #1; output valid, id, data; input ready; endclocking // Monitor clocking block: passively sample all signals (including reset) before posedge clk. clocking mon_cb @(posedge clk); default input #1step; input rst_n, valid, ready, id, data; endclocking // Protocol SVA: once valid is asserted without ready, valid/id/data must stay stable next cycle. a_hold: assert property (@(posedge clk) disable iff (!rst_n) valid && !ready |=> valid && $stable(id) && $stable(data)) else $error("in_if: valid dropped or payload changed before ready handshake"); a_known: assert property (@(posedge clk) disable iff (!rst_n) !$isunknown(valid)); c_long_stall: cover property (@(posedge clk) disable iff (!rst_n) (valid && !ready) [*4]); endinterfacetb_topwires the interfaces todut, registers them inuvm_config_db, and launches the test selected on the command line via+UVM_TESTNAME=<name>:`include "uvm_macros.svh" module tb_top; import uvm_pkg::*; logic clk = 0; logic rst_n = 0; always #5 clk = ~clk; // 100 MHz clock (10 ns period) initial #100 rst_n = 1; // release active-low reset after 100 ns in_stream_if in_if (clk, rst_n); out_stream_if out_if(clk, rst_n); my_block dut ( .clk (clk), .rst_n (rst_n), .in_valid (in_if.valid), .in_ready (in_if.ready), .in_id (in_if.id), .in_data (in_if.data), .out_valid(out_if.valid), .out_ready(out_if.ready), .out_id(out_if.id), .out_data(out_if.data) ); initial begin uvm_config_db#(virtual in_stream_if)::set(null, "uvm_test_top.env.in_agt*", "vif", in_if); uvm_config_db#(virtual out_stream_if)::set(null, "uvm_test_top.env.out_agt*", "vif", out_if); run_test(); end endmoduleTrace one transaction and vary stimulus with phases and the factory
Let's follow a single transaction from a test class all the way to the DUT's input pins:
base_test.run_phaseraises a UVM objection (telling UVM "do not end simulation yet") and startsrand_seqonenv.in_agt.sqr.rand_seq.body()creates a transaction via the UVM factory (txn::type_id::create("t")), callsstart_item(t)to wait until the sequencer grants access to the driver, randomizestafter the grant (late randomization, so constraints see the freshest state), and callsfinish_item(t).in_driver.run_phasereceivestfromseq_item_port.get_next_item(req), waitsreq.idleclock cycles (0cycles means back-to-back streaming with zero bubble cycles!), drivesvalid <= 1withidanddata, loops untildrv_cb.ready === 1on a clock edge, schedulesvalid <= 0, and callsitem_done()to unblockfinish_item(t).
class txn extends uvm_sequence_item; rand bit [3:0] id; rand bit [31:0] data; rand int unsigned idle; // stimulus knob: idle cycles before asserting valid (0 = back-to-back) int unsigned waited; // measured by monitor: cycles valid waited while ready was 0 // :/ divides weight across a range so P(idle==0) = 60%, P(1..3) = 30%, P(4..20) = 10%. constraint c_idle { idle dist {0 :/ 60, [1:3] :/ 30, [4:20] :/ 10}; } constraint c_data { data dist {32'h0 :/ 5, 32'hFFFF_FFFF :/ 5, [32'h1:32'hFFFF_FFFE] :/ 90}; } `uvm_object_utils_begin(txn) `uvm_field_int(id, UVM_ALL_ON) `uvm_field_int(data, UVM_ALL_ON) `uvm_object_utils_end function new(string name = "txn"); super.new(name); endfunction endclass class in_driver extends uvm_driver #(txn); `uvm_component_utils(in_driver) virtual in_stream_if vif; function new(string name, uvm_component parent); super.new(name, parent); endfunction function void build_phase(uvm_phase phase); super.build_phase(phase); if (!uvm_config_db#(virtual in_stream_if)::get(this, "", "vif", vif)) `uvm_fatal("NOVIF", "in_driver: virtual interface missing from uvm_config_db") endfunction task run_phase(uvm_phase phase); vif.drv_cb.valid <= 1'b0; wait (vif.rst_n === 1'b1); @(vif.drv_cb); // align once to the clocking edge after reset release forever begin seq_item_port.get_next_item(req); repeat (req.idle) @(vif.drv_cb); // 0 cycles -> back-to-back; >0 -> idle gap with valid=0 vif.drv_cb.valid <= 1'b1; // if idle==0, overrides valid<=0 from previous cycle! vif.drv_cb.id <= req.id; vif.drv_cb.data <= req.data; do @(vif.drv_cb); while (vif.drv_cb.ready !== 1'b1); vif.drv_cb.valid <= 1'b0; // drops valid cleanly if no back-to-back item follows seq_item_port.item_done(); end endtask endclassHow do UVM phases and the factory let tests vary stimulus without editing
env? -build_phaseexecutes top-down (test->env->agent->driver), so a test can register a factory override (txn::type_id::set_type_override(same_id_txn::get_type())) or push config knobs intouvm_config_dbbeforeenvbuilds its children. -connect_phaseexecutes bottom-up to wire TLM ports after all child components exist. -run_phaseconsumes simulation time while traffic flows and drains; afterward,extract_phase,check_phase, andreport_phaserun in zero simulation time for final bookkeeping.Separate the monitor from the driver and check out-of-order outputs
Why must a monitor sample the physical pins instead of letting the driver forward
reqdirectly to the scoreboard? 1. Check reality, not intent: If the driver has a bug (say it dropsvalidearly or drives the wrong wires), comparing the DUT against the driver's intent hides the bug! Sampling pins checks what actually entered the DUT. 2. Subsystem reuse: When neighboring RTL replaces the driver in a larger chip testbench, the driver is turned off (UVM_PASSIVE), while the monitor, scoreboard, and coverage keep working unchanged.Crucially, the monitor allocates a brand-new
txnobject on every handshake (type_id::create) becauseap.write(t)passes an object handle, not a deep copy:// Inside in_monitor::run_phase task run_phase(uvm_phase phase); int unsigned waited = 0; forever begin @(vif.mon_cb); if (vif.mon_cb.rst_n !== 1'b1 || vif.mon_cb.valid !== 1'b1) begin waited = 0; end else if (vif.mon_cb.ready !== 1'b1) begin waited++; // valid=1, ready=0: count stall cycles end else begin txn t = txn::type_id::create("t"); // allocate fresh object per transfer! t.id = vif.mon_cb.id; t.data = vif.mon_cb.data; t.waited = waited; ap.write(t); // broadcast to scoreboard and coverage waited = 0; end end endtaskNow look at how the scoreboard handles out-of-order IDs, register modes, and missing outputs (the sneaky bug where a dropped packet produces zero mismatches during
run_phase!):- Predict at input arrival time: Inside
write_in, immediately compute the expected output using the RAL mirror's currentctrl.mode(get_mirrored_value()). Computing later at output time would use the wrong mode if software changedctrl.modewhile the packet was in the pipeline! - Per-ID FIFO queues (
pending[id][$]): An associative array indexed byid, where each bucket is a FIFO queue of{expected_data, input_time}. Different IDs pop independently in any order, while same-ID transfers pop strictly oldest-first (pop_front()). - Catch dropped, phantom, and hung transactions:
- Drain time before dropping objection: After the input sequence finishes, wait until
scoreboard.outstanding == 0(guarded by a timeout) so in-flight items can exit the pipeline. - End-of-test
check_phase: Flag every leftover entry inpendingasSB_MISSING(for example, 1,000 inputs sent and 998 outputs received leaves 2 exact leftover entries with their timestampst_in), whilewrite_outimmediately flags unexpected outputs on empty queues asSB_EXTRA. - Per-transaction latency watchdog: If the spec bounds latency to 200 cycles, flag any
pendingentry older than 200 cycles right away instead of waiting for a global simulation timeout.
- Drain time before dropping objection: After the input sequence finishes, wait until
`uvm_analysis_imp_decl(_in) `uvm_analysis_imp_decl(_out) import "DPI-C" function int unsigned ref_model(int unsigned mode, int unsigned id, int unsigned data); class my_scoreboard extends uvm_scoreboard; `uvm_component_utils(my_scoreboard) uvm_analysis_imp_in #(txn, my_scoreboard) in_imp; uvm_analysis_imp_out #(txn, my_scoreboard) out_imp; my_reg_block regs; typedef struct { bit [31:0] data; time t_in; } expect_t; expect_t pending [bit [3:0]][$]; // id -> FIFO queue of expected results int unsigned outstanding, n_ok, n_bad; function new(string name, uvm_component parent); super.new(name, parent); in_imp = new("in_imp", this); out_imp = new("out_imp", this); endfunction function void write_in(txn t); expect_t exp; exp.data = ref_model(regs.ctrl.mode.get_mirrored_value(), t.id, t.data); exp.t_in = $time; pending[t.id].push_back(exp); outstanding++; endfunction function void write_out(txn t); expect_t exp; if (!pending.exists(t.id) || pending[t.id].size() == 0) begin `uvm_error("SB_EXTRA", $sformatf("id=%0d data=0x%08h arrived with no pending input", t.id, t.data)) return; end exp = pending[t.id].pop_front(); outstanding--; if (t.data === exp.data) begin n_ok++; end else begin n_bad++; `uvm_error("SB_MISMATCH", $sformatf("id=%0d: got 0x%08h, expected 0x%08h (input accepted at %0t)", t.id, t.data, exp.data, exp.t_in)) end endfunction function void check_phase(uvm_phase phase); super.check_phase(phase); foreach (pending[id]) begin foreach (pending[id][i]) begin `uvm_error("SB_MISSING", $sformatf("id=%0d: input sent at %0t never produced an output", id, pending[id][i].t_in)) end end endfunction endclass- Predict at input arrival time: Inside
Combine code coverage and functional coverage
How do we measure whether our tests exercised enough of the design? We need two complementary lenses because neither is sufficient alone:
Coverage Type How It Is Built What It Measures Blind Spot Code coverage Automatically instrumented from RTL (line, branch, condition, bit toggle, FSM state/arc) Which parts of the implemented RTL code executed Cannot detect unimplemented spec features (you cannot miss a line of code the designer forgot to write!) Functional coverage Hand-written by verification engineer ( covergroup,coverpoint,cross, SVAcover property)Which specified scenarios, corners, and feature combinations occurred Cannot detect undocumented RTL branches (like hidden debug logic or internal buffer-wrap states not in your covergroup) Here is a clean functional coverage subscriber for our input stream, including corner-value bins (buckets of values we must hit) and a cross (every pair of
idand back-pressure level):class in_coverage extends uvm_subscriber #(txn); `uvm_component_utils(in_coverage) txn t; covergroup cg; cp_id : coverpoint t.id; // 16 automatic bins: IDs 0..15 cp_data : coverpoint t.data { bins all_zeros = {32'h0000_0000}; bins all_ones = {32'hFFFF_FFFF}; bins interior = {[32'h0000_0001 : 32'hFFFF_FFFE]}; } cp_wait : coverpoint t.waited { // stall cycles before ready=1 bins zero_wait = {0}; bins short_wait = {[1:3]}; bins long_wait = {[4:$]}; } x_id_wait : cross cp_id, cp_wait; // 16 * 3 = 48 combination bins endgroup function new(string name, uvm_component parent); super.new(name, parent); cg = new(); endfunction function void write(txn t); this.t = t; cg.sample(); endfunction endclassWhy did our
txnclass biasc_datato give32'h0a5%weight instead of pure uniform randomness? Look at the math: - Under uniform 32-bit randomness,P(data == 0) = 1 / 2^32 ≈ 2.3 × 10^-10. Even across1,000,000random transactions, the probability of hitting0at least once is1 - (1 - 2^-32)^1,000,000 ≈ 0.023%— practically never! - With a5%weight inc_data,0appears once every20transactions on average, and100transactions hit0with probability1 - 0.95^100 ≈ 99.4%.Also track assertion coverage (
cover propertysuch asc_long_stallabove): an assertionA |-> Bwhose triggerAnever occurs passes vacuously (0 failures, 0 real checks!).Steer coverage closure toward sign-off
Verification runs in a closed feedback loop rather than a single giant random run:
[1. Run multi-seed constrained-random regression & merge coverage DBs] │ ▼ [2. Inspect uncovered holes in functional bins & RTL code lines] │ ┌───────────────────────────┼───────────────────────────┐ ▼ ▼ ▼ [Reweight constraints [Write a directed test [Document + review or add env stall knobs] for surgical corners] unreachable exclusions]Why not just run more random seeds when bins remain empty? Consider our 48-bin cross
x_id_wait: - If all 48 bins were equally likely (1/48each), filling all 48 takes48 × (1 + 1/2 + ... + 1/48) ≈ 214transactions on average (the coupon-collector problem — expected draws needed to collect every distinct coupon). - In reality, bins are skewed: iflong_waitonly happens when the DUT's internal FIFO fills up (p = 1/1,000under light back-pressure), hitting just one rare bin with 95% confidence requiresln(0.05) / ln(0.999) ≈ 2,995samples, and rare multi-way crosses might never hit in a week! Reweightingout_agt's ready-stall constraint or writing a directed test (for example, assertingrst_n = 0on the exact cycle the internal FIFO hits full) closes those holes in seconds.Finally, verification sign-off requires far more than "functional coverage = 100%": 1. Plan closure: 100% of verification-plan features are linked to active checks and covered bins, with every coverage exclusion jointly reviewed with the RTL designer. 2. Code + assertion closure: Line, branch, toggle, and FSM coverage holes are analyzed line-by-line; zero assertions fail and every assertion's trigger was exercised (no vacuous passes). 3. Regression & bug-rate stability: Multi-seed nightly regressions pass cleanly across consecutive runs, zero critical/high bugs remain open, and the new-bug discovery curve has flattened to zero. 4. Checker sanity (mutation check): Deliberately injecting a bogus bit flip into the DUT or reference model triggers an immediate scoreboard or SVA failure, proving the checkers are genuinely connected.
Intuition & how it works
Think of verifying a hardware chip block (DUT, or Design Under Test, written in RTL — Register-Transfer Level SystemVerilog) like quality-testing a multi-lane restaurant kitchen that takes numbered meal tickets (id, data) at a pass-through window and hands finished plates out the other side. Rather than letting the person placing orders claim what entered the kitchen, you station two independent inspectors with clipboards (monitors) right at the input and output windows to record every ticket that actually changes hands when both sides agree (valid/ready handshake — a transfer occurs on a clock edge where valid and ready are both 1). A head auditor (scoreboard) computes what each dish should look like using a trusted recipe book (reference model), files that prediction into a per-table folder (pending[id]), checks each finished plate as it comes out (even if Table 5's salad finishes before Table 2's steak!), and checks at closing time (check_phase) that zero tickets were silently lost in the kitchen.
Why does a naive Verilog testbench with a few hand-written stimulus tasks fall short? First, hand-written directed tests only check the 5 scenarios the author thought of, missing subtle pipeline hazards when stalls, specific IDs, and corner-case values collide simultaneously. Second, checking outputs against what the driver tried to send (instead of what a separate monitor observed on the wires) hides handshake bugs and makes the checker useless when real neighboring hardware replaces the driver in a full-chip simulation. Third, checking only output mismatches completely misses a "black-hole" bug where the hardware silently drops every 100th packet!
Let's trace 3 transactions (id=3, id=7, id=3) passing through our scoreboard when different IDs reorder (id=7 overtakes id=3) while same-ID order is preserved:
1. Input monitor sees (id=3, data=40) in mode=ADD_2 -> scoreboard pushes expected 42:
pending[3] = [42]
2. Input monitor sees (id=7, data=90) in mode=ADD_2 -> scoreboard pushes expected 92:
pending[3] = [42], pending[7] = [92]
3. Input monitor sees (id=3, data=15) in mode=ADD_2 -> scoreboard pushes expected 17:
pending[3] = [42, 17], pending[7] = [92] (outstanding = 3)
4. Output monitor sees (id=7, data=92) first (out of order across IDs!):
pops pending[7].pop_front() -> 92 == 92 (PASS!) pending[3] = [42, 17], outstanding = 2
5. Output monitor sees (id=3, data=42), then (id=3, data=17) (FIFO order within ID 3):
pops 42 == 42 (PASS!), then 17 == 17 (PASS!) all queues empty, outstanding = 0 at check_phase!
Key points
- Bridge static modules and dynamic classes via virtual interfaces: Hardware
modules andinterfaces exist statically from time0, whereas UVM (Universal Verification Methodology) testbench components are dynamicclassobjects built at run time. Passing virtual interface handles throughuvm_config_dbconnects drivers and monitors to wires without brittle hierarchical paths, whileinterfaceclocking blocks (#1stepinput sampling,#1output skew) eliminate testbench/RTL race conditions. - Keep stimulus, pin driving, monitoring, and checking decoupled: Sequences randomize
txnitems; drivers wiggle pins; monitors passively reconstruct observed transfers and publish them on TLM analysis ports (one-to-many broadcast channels); and the UVM factory (type_id::create+ overrides) lets tests swap transaction constraints without editing the environment. - Check observed pins and predict at input time: Separate monitors verify actual wire transfers rather than driver intent. The scoreboard computes expected outputs inside
write_inusing a golden model (C via DPI-C or SystemVerilog) and the RAL (Register Abstraction Layer) mirror's active configuration at that exact cycle, storing predictions in per-ID FIFO queues (pending[id][$]) to support cross-ID reordering alongside same-ID ordering. - Catch silent drops and hangs explicitly: Wait for in-flight transactions to drain (
outstanding == 0with a timeout) before dropping the run-phase objection, fail on any leftoverpendingentries incheck_phase, fail immediately on unexpected outputs (SB_EXTRA), and run a cycle-count watchdog for hung IDs. - Pair code coverage with functional coverage for closure: Code coverage (automatically measuring RTL lines, branches, toggles, and FSM arcs) reveals unexercised implementation logic, while functional coverage (hand-written
covergroupbins, crosses, and SVAcover propertyitems derived from a verification plan) reveals unexercised spec scenarios. Sign-off requires closing both alongside clean multi-seed regressions, reviewed exclusions, non-vacuous assertions, and a flat bug rate.
Common mistakes
- Sending expected transactions directly from the driver to the scoreboard: Bypasses the physical wires, masking driver handshake bugs and breaking reuse when the agent is switched to passive mode (
UVM_PASSIVE) at the subsystem level. - Reusing a single
txnclass handle inside the monitor loop: Becauseap.write(t)passes a reference rather than a copy, mutatington the next clock cycle silently overwrites transactions already queued inside subscribers! Always allocate a fresh object per transfer. - Forgetting end-of-test drain or
check_phasequeue inspection: Dropping the UVM objection on the final input cuts off legitimate in-flight outputs, while omittingcheck_phaselets a DUT that drops transactions pass with zero mismatches. - Sampling register configuration when the output exits instead of when the input enters: Produces false scoreboard mismatches whenever software updates a control register while older packets are still draining through the pipeline.
- Confusing SystemVerilog
:=and:/distribution weights: Inidle dist {0 := 60, [1:3] := 30, [4:20] := 10},:=gives every integer in[4:20]weight10(17 × 10 = 170), ballooning the denominator to60 + 90 + 170 = 320soP(idle == 0)drops from the intended60%to60 / 320 = 18.75%! Use:/to divide weight across a range. - Inserting an accidental bubble cycle in the driver loop: Placing an unconditional
@(vif.drv_cb)before drivingvalid <= 1forces at least 1 idle cycle between transfers even whenreq.idle == 0, preventing back-to-back streaming from ever being tested! - Equating "100% coverage" with "verification complete": Coverage without self-checking assertions and scoreboard comparisons only proves lines wiggled, not that outputs were right, and assertions whose preconditions never fired pass vacuously unless
cover propertycounts confirm they triggered.
Follow-up questions
- What changes are needed to embed this unit-level testbench inside a subsystem or full-chip environment? Reconfigure the block's upstream and downstream agents to passive mode (
is_active = UVM_PASSIVEviauvm_config_db) so sequencers and drivers are omitted while monitors, interface SVA checks, functional covergroups, and the block scoreboard continue checking internal wires driven by adjacent RTL. Instantiate the unitenvinside the parent subsystemenv, map its RAL register block as a sub-map at the subsystem's address offset, and coordinate end-to-end stimulus from top-level ports through a virtual sequence (a supervisor sequence that dispatches traffic across multiple interface sequencers). - Suppose functional coverage reaches 100%, yet RTL code coverage reports an unhit branch. How would you investigate and resolve that gap? An unhit RTL branch signals either an omission in your functional coverage model or unreachable/dead hardware logic: inspect the surrounding RTL and consult the designer to see what microarchitectural event enters that arm (for instance, an internal skid-buffer wraparound or error recovery path). When the branch represents genuine functionality, add a corresponding coverpoint/cross to the verification plan, steer constraints or write a targeted test to trigger it, and confirm the scoreboard validates the result; when it is provably unreachable (such as a defensive
defaultbranch), record a formally proven or designer-signed exclusion instead of writing a check-free stimulus hack just to inflate coverage numbers. - Out of thousands of regression seeds, a single seed triggers a scoreboard data mismatch. Walk through your debugging workflow. Reproduce the failure deterministically on the exact same compiled snapshot using that seed (
+ntb_random_seed=<seed>or+svseed=<seed>), preserving SystemVerilog random stability by avoiding debug edits that addrandomize()calls before the failure point. Capture waveforms in a window around theSB_MISMATCHacceptance timestamp (input accepted at %0t), trace backward to the earliest corrupted transfer on thatidto determine whether the fault lies in RTL pipeline logic, reference-model math, or monitor sampling skew, and finally add a dedicatedcoverpointor directed regression test for that corner combination so the fix stays permanently guarded. - How do you decide whether a hardware rule belongs in a SystemVerilog assertion or inside the UVM scoreboard? Put local, cycle-accurate temporal invariants on control signals into SVA—for example, "
validand payload remain steady whilereadyis low", "control wires never goX/Zout of reset", "internal FIFO occupancy never exceeds depth", or "bounded handshake latency"—because concurrent assertions check every clock edge, flag the exact offending cycle, and carry directly into formal property verification. Reserve the scoreboard for end-to-end data integrity across variable pipeline depths and out-of-order tag queues, where predicting transformed payloads and pairing completions requires dynamic queues, RAL state snapshots, or DPI-C golden models.
Follow-up questions
- What changes are needed to embed this unit-level testbench inside a subsystem or full-chip environment?
- Suppose functional coverage reaches 100%, yet RTL code coverage reports an unhit branch. How would you investigate and resolve that gap?
- Out of thousands of regression seeds, a single seed triggers a scoreboard data mismatch. Walk through your debugging workflow.
- How do you decide whether a hardware rule belongs in a SystemVerilog assertion or inside the UVM scoreboard?
Similar questions
- Debugging Singly Linked-List Insertion and Tracing C++ Method Dispatch
- Constant-Time Fixed-Capacity LRU Cache
- CI/CD Ownership, Jenkins Pipelines, and Inspecting Multi-Gigabyte Logs
- Cache-Set Conflicts, False Sharing, and GPU Bank Serialization
- GPU Kernel Register Spilling, Occupancy Trade-Offs, and Performance Diagnosis
- Agent Skill Packaging and Progressive Context Disclosure
More AMD interview questions
- Top K Elements via Partition Selection Medium
- Debugging Singly Linked-List Insertion and Tracing C++ Method Dispatch Medium
- Single-Agent Versus Multi-Agent Orchestration Architectures Medium Pro
- Constant-Time Fixed-Capacity LRU Cache Medium Pro
- CI/CD Ownership, Jenkins Pipelines, and Inspecting Multi-Gigabyte Logs Medium Pro
- Validation Architecture for Kernel and Compiler Optimization Agents Medium Pro
- Cache-Set Conflicts, False Sharing, and GPU Bank Serialization Medium Pro
- GPU Kernel Register Spilling, Occupancy Trade-Offs, and Performance Diagnosis Medium Pro
- Mastering and Validating Unfamiliar Technologies Medium Pro
- Agent Skill Packaging and Progressive Context Disclosure Medium Pro