// Testbench for exercise BB8.
//
// Runs the generic design (fifo_demo.sv) and the chip-level design
// (fifo_demo_chips.sv) side by side and compares both with a reference
// model, a queue kept as an array with the head in place 0.  Works with
// Icarus Verilog, Verilator (--binary) and Questa.
//
// Like the testbenches of Basics-Graphics-Music, it drives and samples
// signals only at rising clock edges.  It pushes and pops a few words,
// fills the FIFO beyond its sixteen places, empties it beyond the last
// word, presses both buttons at once, runs a stretch of pseudo-random
// presses, resets in the middle, and checks that reset acts at once.

// Time units.  The design files have none: Yosys does not accept timeunit
// and timeprecision, and the Tiny Tapeout template sets `timescale 1ns / 1ps
// in its own testbench.  This line sets the same units here and for the
// design files compiled after it, so tb.sv comes first in the file list.

`timescale 1ns / 1ps

module tb;

    logic       clk;
    logic       rst;
    logic       push = 1'b0;
    logic       pop  = 1'b0;
    logic [2:0] data = '0;

    wire  [2:0] head, head_chips;
    wire        dor,  dor_chips;
    wire        dir,  dir_chips;

    fifo_demo i_generic
    (
        .clk  ( clk  ),
        .rst  ( rst  ),
        .push ( push ),
        .pop  ( pop  ),
        .data ( data ),
        .head ( head ),
        .dor  ( dor  ),
        .dir  ( dir  )
    );

    fifo_demo_chips i_chips
    (
        .clk  ( clk        ),
        .rst  ( rst        ),
        .push ( push       ),
        .pop  ( pop        ),
        .data ( data       ),
        .head ( head_chips ),
        .dor  ( dor_chips  ),
        .dir  ( dir_chips  )
    );

    //------------------------------------------------------------------------
    // Clock with a period of 10 ns.
    // On the breadboard one period is about a second.

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model.  A press is the first clock edge that sees the button
    // at 1.  A push into a full queue and a pop from an empty one do
    // nothing.  rst empties the queue at once.

    logic [2:0] model [0:15];  // model [0] is the head of the queue
    int         count;         // words in the queue
    logic       push_was, pop_was;

    wire pushed = push & ~ push_was;
    wire popped = pop  & ~ pop_was;

    wire model_push = pushed & count < 16;
    wire model_pop  = popped & count > 0;

    always @ (posedge clk or posedge rst)
        if (rst)
        begin
            count    <= 0;
            push_was <= 1'b0;
            pop_was  <= 1'b0;
        end
        else
        begin
            push_was <= push;
            pop_was  <= pop;

            if (model_pop)
                for (int k = 0; k < 15; k ++)
                    model [k] <= model [k + 1];

            // After the shift above, so that this write wins

            if (model_push)
                model [model_pop ? count - 1 : count] <= data;

            count <= count + (model_push ? 1 : 0) - (model_pop ? 1 : 0);
        end

    wire       dor_expected  = count > 0;
    wire       dir_expected  = count < 16;
    wire [2:0] head_expected = model [0];

    // The head is checked only while DOR is 1: an empty FIFO shows an old
    // word, or nothing at all after power-up

    wire ok_generic =    dor === dor_expected && dir === dir_expected
                      && (! dor_expected || head === head_expected);

    wire ok_chips   =    dor_chips === dor_expected && dir_chips === dir_expected
                      && (! dor_expected || head_chips === head_expected);

    //------------------------------------------------------------------------
    // Checking at every rising clock edge.  At the edge both designs and the
    // model still show the clock cycle that ends there, the same values that
    // a flip-flop would sample.

    // Initial values are fine in a testbench, and the checker samples rst at
    // the clock edge on purpose, although the designs reset asynchronously

    // verilator lint_off PROCASSINIT
    // verilator lint_off SYNCASYNCNET

    logic was_reset = 1'b0;
    logic done      = 1'b0;  // Set by the stimulus before $finish

    int cycle    = 0;
    int n_checks = 0;
    int n_errors = 0;

    // What the run has seen: a full queue, a push into it, a pop from an
    // empty queue, and a push and a pop at the same edge

    logic seen_full = 1'b0, seen_push_full = 1'b0, seen_pop_empty = 1'b0, seen_both = 1'b0;

    always @ (posedge clk)
    begin
        if (rst)
            was_reset <= 1'b1;

        if ((rst | was_reset) & ~ done)
        begin
            cycle          <= cycle + 1;
            n_checks       <= n_checks + 2;
            n_errors       <= n_errors + (ok_generic ? 0 : 1) + (ok_chips ? 0 : 1);

            seen_full      <= seen_full      | count == 16;
            seen_push_full <= seen_push_full | ~ rst & pushed & count == 16;
            seen_pop_empty <= seen_pop_empty | ~ rst & popped & count == 0;
            seen_both      <= seen_both      | ~ rst & model_push & model_pop;

            $display ("%5d  %b    %b     %b    %0d     %b    %b    %c     %2d    %s  %s",
                cycle + 1, rst, push, pop, data, dor, dir, dor ? 8'd48 + 8' (head) : 8'd45, count,
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Asynchronous reset: right after rst rises, both FIFOs must be empty.

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ dor, dir, dor_chips, dir_chips } !== 4'b0101)
        begin
            $display ("WRONG: reset did not act at once");
            n_errors <= n_errors + 1;
        end

        n_async <= n_async + 1;
    end

    //------------------------------------------------------------------------
    // Driving the inputs.
    //
    // As on the breadboard, the data bits change only while PUSH is
    // released.  The 40105 takes D0-D2 at the very edge that loads them, one
    // clock after PUSH is pressed, so data that changed at that edge would
    // make a race in the simulation, and a wrong word on the breadboard.

    // One press: hold the buttons for a number of clock edges, then release
    // them for one edge, so that the next press is a new one

    task automatic press (input logic push_on, input logic pop_on, input logic [2:0] value, input int edges);
        data <= value;
        push <= push_on;
        pop  <= pop_on;
        repeat (edges) @ (posedge clk);
        push <= 1'b0;
        pop  <= 1'b0;
        @ (posedge clk);
    endtask

    logic [31:0] seed = 32'd1;

    initial
    begin
        $dumpfile ("tb.vcd");

        `ifdef __ICARUS__
            $dumpvars (0, tb);  // Without a scope Icarus also tries to dump $unit
        `else
            $dumpvars;
        `endif

        $display ("cycle  rst  push  pop  data  DOR  DIR  head  words  generic  chips");

        // Before reset the FIFOs are unknown, as after power-up

        rst <= 1'bx;
        repeat (2) @ (posedge clk);
        rst <= 1'b1;
        repeat (2) @ (posedge clk);
        rst <= 1'b0;

        // The example of section 2: push 2, 5, 7, pop, push 3, pop four
        // times, the last time from an empty queue.  Some presses are long.

        press (1, 0, 2, 1);
        press (1, 0, 5, 3);
        press (1, 0, 7, 2);
        press (0, 1, 0, 1);
        press (1, 0, 3, 1);
        repeat (4) press (0, 1, 0, 2);

        // Eighteen pushes: the last two find the FIFO full

        for (int k = 0; k < 18; k ++)
            press (1, 0, 3' (k), 1);

        // Both buttons at once: on a full FIFO only the pop works, with one
        // place free both work

        press (1, 1, 6, 1);
        press (1, 1, 5, 1);

        // Empty it, and two pops more

        repeat (17) press (0, 1, 0, 1);

        // Pseudo-random presses, the same in every simulator.  The data
        // change only while push is 0 at this edge.

        for (int i = 0; i < 160; i ++)
        begin
            seed = seed * 32'd1664525 + 32'd1013904223;

            if (! push)
                data <= seed [26:24];

            push <= seed [29] & seed [28];
            pop  <= seed [31] & (seed [30] | seed [27]);

            @ (posedge clk);
        end

        push <= 1'b0;
        pop  <= 1'b0;
        @ (posedge clk);

        // Reset in the middle, with words in the queue

        press (1, 0, 1, 1);
        press (1, 0, 4, 1);
        rst <= 1'b1;
        @ (posedge clk);
        rst <= 1'b0;
        @ (posedge clk);

        press (1, 0, 6, 1);
        press (0, 1, 0, 1);
        press (0, 1, 0, 1);

        // Stop checking one clock edge before $finish, so that every
        // simulator reports the same number of checks

        done <= '1;
        @ (posedge clk);

        $finish;
    end

    //------------------------------------------------------------------------

    final
    begin
        if (n_errors == 0 && seen_full && seen_push_full && seen_pop_empty && seen_both && n_async >= 2)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, seen full %b, push full %b, pop empty %b, both %b, %0d resets",
                      n_errors, n_checks, seen_full, seen_push_full, seen_pop_empty, seen_both, n_async);
    end

endmodule
