f8f36449367d60cd22a94c634bb058741951517b
[soc.git] / TLB / CamEntry.py
1 from nmigen import Module, Signal
2 from nmigen.compat.fhdl.structure import If
3 from nmigen.compat.sim import run_simulation
4
5 class CamEntry:
6 def __init__(self, key_size, data_size):
7 # Internal
8 self.key = Signal(key_size)
9
10 # Input
11 self.write = Signal(1) # Read => 0 Write => 1
12 self.key_in = Signal(key_size) # Reference key for the CAM
13 self.data_in = Signal(data_size) # Data input when writing
14
15 # Output
16 self.match = Signal(1) # Result of the internal/input key comparison
17 self.data = Signal(data_size)
18
19
20 def get_fragment(self, platform=None):
21 m = Module()
22 with m.If(self.write == 1):
23 m.d.comb += [
24 self.key.eq(self.key_in),
25 self.data.eq(self.data_in),
26 self.match.eq(1)
27 ]
28 with m.Else():
29 with m.If(self.key_in == self.key):
30 m.d.comb += self.match.eq(0)
31 with m.Else():
32 m.d.comb += self.match.eq(1)
33
34 return m
35
36 #########
37 # TESTING
38 ########
39
40 # This function allows for the easy setting of values to the Cam Entry
41 # unless the key is incorrect
42 # Arguments:
43 # dut: The CamEntry being tested
44 # w (write): Read (0) or Write (1)
45 # k (key): The key to be set
46 # d (data): The data to be set
47 def set_cam(dut, w, k, d):
48 yield dut.write.eq(w)
49 yield dut.key_in.eq(k)
50 yield dut.data_in.eq(d)
51 yield
52
53 def check(pre, e, out, op):
54 if(op == 0):
55 assert out == e, pre + " Output " + str(out) + " Expected " + str(e)
56 else:
57 assert out != e, pre + " Output " + str(out) + " Expected " + str(e)
58
59 def check_key(dut, k, op):
60 out_k = yield dut.key
61 check("K", out_k, k, op)
62
63 def check_data(dut, d, op):
64 out_d = yield dut.data
65 check("D", out_d, d, op)
66
67 def check_match(dut, m, op):
68 out_m = yield dut.match
69 check("M", out_m, m, op)
70
71 def check_all(dut, k, d, m, kop, dop, mop):
72 yield from check_key(dut, k, kop)
73 yield from check_data(dut, d, dop)
74 yield from check_match(dut, m, mop)
75
76 # This testbench goes through the paces of testing the CamEntry module
77 # It is done by writing and then reading various combinations of key/data pairs
78 # and reading the results with varying keys to verify the resulting stored
79 # data is correct.
80 def testbench(dut):
81 # Check write
82 write = 1
83 key = 0
84 data = 1
85 match = 1
86 yield from set_cam(dut, write, key, data)
87 yield from check_all(dut, key, data, match, 0, 0, 0)
88
89 # Check read miss
90 write = 0
91 key = 2
92 data = 1
93 match = 0
94 yield from set_cam(dut, write, key, data)
95 yield from check_all(dut, key, data, match, 1, 0, 0)
96
97 if __name__ == "__main__":
98 dut = CamEntry(4, 4)
99 run_simulation(dut, testbench(dut), vcd_name="Waveforms/cam_entry_test.vcd")