summaryrefslogtreecommitdiff
path: root/arbiter.v
blob: 0e834037f25b86b2f7f6c741c5c40cce5c2bdf43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* Arbiter
 * A module that grants access to a shared ressource (e.g a bus)
 * to an arbitrary amount of drivers. A driver of the shared resource
 * has a bit on the `request` line and fires it up when it wants to use
 * the resource. The arbiter fires the corresponding `grant` bit when
 * the driver is allowed to use the resource */
module arbiter #(
    parameter NUM_CLIENTS = 4
) (
    input clk,

    // Request bits, each driver has its request line
    input[NUM_CLIENTS-1:0] request,

    // Grant bits, each driver has its grant line
    output[NUM_CLIENTS-1:0] grant
);
    // The current round of the arbiter
    reg[NUM_CLIENTS-1:0] round = 1;

    // A circle of wires used by the arbiter to
    // indicate that a driver that has the priority
    // to use the resource yields it to the next driver
    // because it doesn't need to use the resource
    wire pass_on_rollover;
    /* verilator lint_off UNOPTFLAT */
    logic pass_on;
    assign pass_on_rollover = pass_on; // NOTE: assign is applied on last assignment to wire
    
    // Logic bitfield used to generate the grant bus
    logic[NUM_CLIENTS-1:0] grant_gen;
    assign grant = grant_gen;

    always @(posedge clk) begin
        // Keep current grant as round, allowing a selected driver
        // to freeze the arbiter during the entire duration of its
        // resource utilization
        round <= |grant ?
            grant : { round[NUM_CLIENTS-2:0], round[NUM_CLIENTS-1] };
    end

    always_comb begin
        pass_on = pass_on_rollover;

        for (integer i = 0; i < NUM_CLIENTS; i++) begin
            logic has_priority;

            // Current driver has priority if it's its round
            // or previous driver has passed on its
            has_priority = round[i] || pass_on;

            // By default, do not grant to driver
            grant_gen[i] = 0;

            // By default, do not pass on priority
            // to next driver (current may not have it)
            pass_on = 0;
        
            if (has_priority) begin
                if (request[i])
                    grant_gen[i] = 1;
                else
                    pass_on = 1;
            end
        end
    end
endmodule