// Exercise P4: a round-robin arbiter for two requesters.
//
// Generic version that matches schematic 1, not tied to any chip.  A grant
// goes to a requester that asks for it; when both ask, the one that did not
// get the last grant wins.  last remembers who got the last grant: 1 means
// requester 1.  The grants follow the requests at once, within the clock
// cycle; last changes at the rising edge of clk.  rst clears last at once,
// without the clock.  Synthesizable.
//
// With both requests held at 1, the grants alternate every clock, so
// neither requester can starve the other.

module arbiter
(
    input  logic       clk,
    input  logic       rst,
    input  logic [1:0] req,
    output logic [1:0] gnt,
    output logic       last   // 1: the last grant went to requester 1
);

    assign gnt [0] = req [0] & ~ (req [1] & ~ last);
    assign gnt [1] = req [1] & ~ (req [0] &   last);

    always_ff @ (posedge clk or posedge rst)
        if (rst)
            last <= 1'b0;
        else if (gnt [1])
            last <= 1'b1;
        else if (gnt [0])
            last <= 1'b0;

endmodule
