// tb_sync_fifo.sv // Self-checking testbench for sync_fifo. A queue holds the expected contents. // Random reads and writes run in three phases (mostly writes, balanced, mostly // reads) so the FIFO goes full and empty many times. Every cycle the testbench // checks full, empty and count; every read is checked against the queue. `timescale 1ns/1ps module tb_sync_fifo; localparam int DW = 8; localparam int AW = 3; // depth 8: small, so full is reached often localparam int DEPTH = 1 << AW; localparam int CYCLES_PER_PHASE = 2000; logic clk, rst; logic wr_en, rd_en; logic [DW-1:0] wr_data, rd_data; logic full, empty; logic [AW:0] count; logic [DW-1:0] model [$]; // reference model logic [DW-1:0] expected; logic check_rd; // a read was accepted last cycle int errors, n_writes, n_reads, n_full, n_empty; integer seed; sync_fifo #(.DW(DW), .AW(AW)) dut ( .clk(clk), .rst(rst), .wr_en(wr_en), .wr_data(wr_data), .full(full), .rd_en(rd_en), .rd_data(rd_data), .empty(empty), .count(count) ); initial begin clk = 1'b0; forever #5 clk = ~clk; end task automatic run_phase(input int wr_pct, input int rd_pct); for (int i = 0; i < CYCLES_PER_PHASE; i++) begin // Drive new inputs just after the falling edge. @(negedge clk); wr_en = (($unsigned($random(seed)) % 100) < wr_pct); rd_en = (($unsigned($random(seed)) % 100) < rd_pct); wr_data = DW'($random(seed)); // Check flags against the model before the rising edge. if (full !== (model.size() == DEPTH)) begin $display("ERROR %0t: full=%b, model size %0d", $time, full, model.size()); errors++; end if (empty !== (model.size() == 0)) begin $display("ERROR %0t: empty=%b, model size %0d", $time, empty, model.size()); errors++; end if ($isunknown(count) || int'(count) != model.size()) begin $display("ERROR %0t: count=%0d, model size %0d", $time, count, model.size()); errors++; end if (full) n_full++; if (empty) n_empty++; // Update the model with what the FIFO will do on this rising edge. check_rd = 1'b0; if (rd_en && !empty) begin expected = model.pop_front(); check_rd = 1'b1; n_reads++; end if (wr_en && !full) begin model.push_back(wr_data); n_writes++; end // After the rising edge, rd_data holds the word that was read. @(posedge clk); #1; if (check_rd && rd_data !== expected) begin $display("ERROR %0t: rd_data=%h, expected %h", $time, rd_data, expected); errors++; end end endtask initial begin seed = 7; // fixed seed: the run is repeatable errors = 0; n_writes = 0; n_reads = 0; n_full = 0; n_empty = 0; rst = 1'b1; wr_en = 1'b0; rd_en = 1'b0; wr_data = '0; repeat (3) @(posedge clk); @(negedge clk); rst = 1'b0; run_phase(80, 30); // fills up: exercises full run_phase(50, 50); // balanced run_phase(30, 80); // drains: exercises empty $display("writes %0d, reads %0d, cycles full %0d, cycles empty %0d", n_writes, n_reads, n_full, n_empty); if (errors == 0 && n_full > 0 && n_empty > 0) begin $display("PASS"); end else begin $display("FAIL: %0d errors", errors); end $finish; end endmodule