summaryrefslogtreecommitdiff
path: root/arbiter.h
blob: 79a99205faee2dd586b9e96e0f8e4825cf89ea68 (plain) (blame)
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
#pragma once

#include <array>
#include <cassert>

#include "infra/sim.h"

namespace infra {
    template<typename T, unsigned int peers> struct priority_arbiter : public sim {
        std::array<port<T>, peers> peerp;
        port<T> *outp = nullptr;

        void clock() {
            for (unsigned int i = 0; i < peers; ++i) {
                if (outp->can_write() && peerp[i].can_read())
                    outp->write(peerp[i].read());
            }
        }
    };

    template<typename T, unsigned int peers> struct round_robin_arbiter : public sim {
        std::array<port<T>, peers> peerp;
        port<T> *outp = nullptr;
        unsigned int initial = 0;

        void clock() {
            bool initially_empty = outp->can_write();
            for (unsigned int i = initial; i < peers; ++i) {
                if (outp->can_write() && peerp[i].can_read())
                    outp->write(peerp[i].read());
            }
            for (unsigned int i = 0; i < initial; ++i) {
                if (outp->can_write() && peerp[i].can_read())
                    outp->write(peerp[i].read());
            }
            if (initially_empty && !outp->can_write())
                if (++initial == peers)
                    initial = 0;
        }
    };

    template<typename T, unsigned int peers> struct shared_bus : public sim {
        std::array<port<T>, peers> peerp;
        port<T> *outp = nullptr;

        void clock() {
            for (unsigned int i = 0; i < peers; ++i) {
                if (peerp[i].can_read()) {
                    assert(outp->can_write());
                    outp->write(peerp[i].read());
                }
            }
        }
    };
}