// Testbench for exercise P4.
//
// Runs the generic design (arbiter.sv) and the chip-level design
// (arbiter_chips.sv) side by side and compares both with a reference model
// written as a priority rule: one requester alone gets the grant; when both
// ask, the one that did not get the last grant does.  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 tries every request with both
// values of the state, holds both requests for a while to check that the
// grants alternate, makes pseudo-random requests, 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 [1:0] req = '0;

    wire  [1:0] gnt,  gnt_chips;
    wire        last, last_chips;

    arbiter i_generic
    (
        .clk  ( clk  ),
        .rst  ( rst  ),
        .req  ( req  ),
        .gnt  ( gnt  ),
        .last ( last )
    );

    arbiter_chips i_chips
    (
        .clk  ( clk        ),
        .rst  ( rst        ),
        .req  ( req        ),
        .gnt  ( gnt_chips  ),
        .last ( last_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

    logic last_model;

    wire [1:0] gnt_expected = req != 2'b11 ? req : last_model ? 2'b01 : 2'b10;

    always @ (posedge clk or posedge rst)
        if (rst)
            last_model <= 1'b0;
        else if (gnt_expected != 2'b00)
            last_model <= gnt_expected [1];

    wire ok_generic = gnt       === gnt_expected && last       === last_model;
    wire ok_chips   = gnt_chips === gnt_expected && last_chips === last_model;

    //------------------------------------------------------------------------
    // 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;

    logic [7:0] seen = '0;  // { last, req } combinations checked

    // Fairness: while both requests stay held, the grant changes hands at
    // every clock edge

    logic [1:0] req_before = '0, gnt_before = '0;
    int         n_alternations = 0, n_unfair = 0;

    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);

            if (~ rst)
                seen [{ last_model, req }] <= 1'b1;

            req_before <= rst ? 2'b00 : req;  // a reset clears L: start counting again
            gnt_before <= gnt;

            if (~ rst & req == 2'b11 & req_before == 2'b11)
            begin
                n_alternations <= n_alternations + 1;
                n_unfair       <= n_unfair + (gnt == gnt_before ? 1 : 0);
            end

            $display ("%5d  %b     %b %b     %b %b     %b   %s  %s",
                cycle + 1, rst, req [1], req [0], gnt [1], gnt [0], last,
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok" : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Asynchronous reset: right after rst rises, last must be 0 in both.

    int n_async = 0;

    always @ (posedge rst)
    begin
        # 1;

        if ({ last, last_chips } !== 2'b00)
        begin
            $display ("WRONG: reset did not act at once");
            n_errors <= n_errors + 1;
        end

        n_async <= n_async + 1;
    end

    //------------------------------------------------------------------------
    // Driving the inputs

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

    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  REQ 1 0  GNT 1 0  L   generic  chips");

        // Before reset the state is unknown, as after power-up

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

        // One requester at a time, then both for a while, then none

        req <= 2'b01;  repeat (2) @ (posedge clk);
        req <= 2'b10;  repeat (2) @ (posedge clk);
        req <= 2'b11;  repeat (6) @ (posedge clk);
        req <= 2'b00;  repeat (2) @ (posedge clk);
        req <= 2'b10;  @ (posedge clk);
        req <= 2'b00;  @ (posedge clk);
        req <= 2'b01;  @ (posedge clk);
        req <= 2'b11;  repeat (5) @ (posedge clk);

        // Reset in the middle, after requester 1 got the last grant

        req <= 2'b10;
        @ (posedge clk);
        rst <= 1'b1;
        req <= 2'b11;
        @ (posedge clk);
        rst <= 1'b0;
        repeat (3) @ (posedge clk);

        // Pseudo-random requests, the same in every simulator

        for (int i = 0; i < 80; i ++)
        begin
            seed = seed * 32'd1664525 + 32'd1013904223;
            req <= seed [31:30];
            @ (posedge clk);
        end

        // 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 == 8'hff && n_alternations >= 8 && n_unfair == 0 && n_async >= 2)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, combinations seen %b, %0d of %0d held requests unfair, %0d resets",
                      n_errors, n_checks, seen, n_unfair, n_alternations, n_async);
    end

endmodule
