-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
270 lines (210 loc) · 8.6 KB
/
main.py
File metadata and controls
270 lines (210 loc) · 8.6 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import pandas as pd
def get_address_to_write(tag, slot, offset):
comp = [tag, slot, offset]
comp = [str(hex(i))[2:] for i in comp]
address_to_write = "".join(comp)
address_to_write = int(address_to_write, 16)
return address_to_write
def initialize_memory(size=0x7FF):
memory = [i % 0x100 for i in range(size + 1)]
return memory
def get_offset(address):
return address & 0b000000001111
def get_slot(address):
return (address & 0b000011110000) >> 4
def get_tag(address):
return (address & 0b111100000000) >> 8
def get_tag_slot_offset(address):
offset = get_offset(address)
slot = get_slot(address)
tag = get_tag(address)
return tag, slot, offset
class Cache:
# Direct Mapped Cache
# Block size is 16 bytes
# 16 slots in the cache
def __init__(self, number_of_slots=16, main_memory=None):
if main_memory is None:
self.main_memory = initialize_memory()
self.number_of_slots = number_of_slots
self.cache_slots = [Record(slot=i, valid=0, tag=0, block_data=Block()) for i in range(0, number_of_slots)]
print("Cache initialized")
def get_record_by_slot(self, slot):
for record in self.cache_slots:
if record.slot == slot:
return record
return None
def get_block_from_memory(self, address):
offset = get_offset(address)
block_starting_address = address - offset
# Block size is 16 bytes so we add 15 to the starting address to get the end address and add 1 to include it
block_end_address = block_starting_address + 15 + 1
block = self.main_memory[block_starting_address:block_end_address]
return block
def read(self, address):
tag, slot, offset = get_tag_slot_offset(address)
record_in_cache = self.get_record_by_slot(slot)
cache_hit = (record_in_cache.tag == tag and record_in_cache.valid == 1)
if cache_hit:
print(f"Read address {hex(address)[2:]} -> tag={hex(tag)[2:]}, slot={hex(slot)[2:]}, offset={hex(offset)[2:]} (Cache hit)")
print("Data: ", hex(record_in_cache.block_data.block[offset])[2:])
print("\n")
else:
print(
f"Read address {hex(address)[2:]} -> tag={hex(tag)[2:]}, slot={hex(slot)[2:]}, offset={hex(offset)[2:]} (Cache miss)")
if record_in_cache.dirty:
print("Dirty bit found in slot: ", hex(slot)[2:])
address_to_write_old_block = get_address_to_write(record_in_cache.tag, slot, offset)
self.write_block_to_memory(address_to_write_old_block, record_in_cache.block_data.block)
record_in_cache.dirty = 0
print(f"Retrieving block starting at {hex(address - offset)[2:]} from memory...")
block_to_add_to_cache = Block(block=self.get_block_from_memory(address))
record_in_cache.block_data = block_to_add_to_cache
record_in_cache.tag = tag
record_in_cache.valid = 1
print("Data: ", hex(record_in_cache.block_data.block[offset])[2:])
print("\n")
def write_block_to_memory(self, address, data):
offset = get_offset(address)
block_starting_address = address - offset
block_end_address = block_starting_address + 16
print(f"Writing block {hex(block_starting_address)[2:]} to memory...")
self.main_memory[block_starting_address:block_end_address] = data
def write(self, address, data):
tag, slot, offset = get_tag_slot_offset(address)
data_hex_str = hex(data)[2:]
record = self.get_record_by_slot(slot)
print(f"Write {hex(data)[2:]} to address {hex(address)[2:]} -> tag: ", hex(tag)[2:], "slot: ", hex(slot)[2:], "offset: ",
hex(offset)[2:])
def add_block_to_cache_record_from_memory(record, block_address):
block_to_add_to_cache = Block(block=self.get_block_from_memory(block_address))
record.block_data = block_to_add_to_cache
record.tag = tag
record.valid = 1
record.block_data.block[offset] = data
record.dirty = 1
print(f"Data: {data_hex_str} written to cache")
print("\n")
if record.tag == tag and record.valid == 1:
print("Cache hit")
record.block_data.block[offset] = data
record.dirty = 1
print(f"Data: {data_hex_str} written to cache")
print("\n")
elif record.tag != tag and record.dirty == 1:
print("Cache miss")
print("Dirty bit found in slot: ", hex(slot)[2:])
print("Writing old record to memory...")
# Write the old record to memory
old_block = record.block_data.block
address_to_write_old_block = get_address_to_write(record.tag, slot, offset)
self.write_block_to_memory(address_to_write_old_block, old_block)
print("Old record written to memory")
record.dirty = 0
print("Now retrieving block starting at ", hex(address - offset)[2:], " from memory...")
add_block_to_cache_record_from_memory(record, address)
else:
print("Cache miss")
print("Retrieving block starting at ", hex(address - offset)[2:], " from memory...")
record = self.get_record_by_slot(slot)
# Now retrieve the required block from memory
add_block_to_cache_record_from_memory(record, address)
def display(self):
df = pd.DataFrame([vars(i) for i in self.cache_slots])
column_names = ["slot", "valid", "tag", "dirty", " ", "block_data"]
# Add a column with no data between tag and data
df[" "] = ""
df = df[column_names]
df["slot"] = df["slot"].apply(hex)
df["slot"] = df["slot"].apply(lambda x: x[2:])
df["tag"] = df["tag"].apply(hex)
df["tag"] = df["tag"].apply(lambda x: x[2:])
print("Displaying cache".center(77, "-"))
print(df)
print("\n")
class Record:
def __init__(self, slot, valid, tag, block_data):
self.block_data = block_data
self.slot = slot
self.tag = tag
self.valid = valid
self.dirty = 0
class Block:
def __init__(self, size=16, block=None):
self.size = size
if block is None:
self.block = []
for _ in range(0, size):
self.block.append(0)
else:
self.block = block
def __str__(self):
string = ""
for i in self.block:
hex_repr = hex(i)[2:]
if len(hex_repr) == 1:
string += hex_repr + " "
else:
string += hex_repr + " "
return string
def user_interface(cache):
while True:
print("To interact with the cache please select an action (R)ead, (W)rite, (D)isplay ->")
action = input().lower().strip()
match action:
case "r":
user_read(cache)
case "w":
user_write(cache)
case "d":
user_display(cache)
case _:
print("Invalid input!")
def user_read(cache):
print("Read selected.")
print("What address would you like to read? Please enter in hex")
print("Max tag is 7, max slot is F, max offset is F")
address = input()
address = int(address, 16)
cache.read(address)
def user_write(cache):
print("Write selected.")
print("What address would you like to write to? Please enter in hex")
print("Max tag is 7, max slot is F, max offset is F")
address = input()
address = int(address, 16)
print("What data would you like to write? Please enter in hex")
data = input()
data = int(data, 16)
cache.write(address, data)
def user_display(cache):
print("Display selected.")
cache.display()
def main():
# cache = Cache()
# user_interface(cache)
final_test()
def final_test():
cache = Cache()
addresses_to_read = [0x5, 0x6, 0x7, 0x14c, 0x14d, 0x14e, 0x14f, 0x150, 0x151, 0x3A6, 0x4C3]
for x in addresses_to_read:
cache.read(address=x)
cache.display()
cache.write(0x14c, 0x99)
cache.write(0x63B, 0x7)
cache.read(0x582)
cache.display()
cache.read(0x348)
cache.read(0x3f)
cache.display()
cache.read(0x14b)
cache.read(0x14c)
cache.read(0x63f)
cache.read(0x83)
cache.display()
if __name__ == "__main__":
# Ensure there is no max width for dataframe
pd.set_option("display.max_columns", None)
pd.set_option("display.expand_frame_repr", False)
pd.set_option('display.width', 1000)
main()