Repository navigation
Expand file tree
/
Copy pathCache.java
More file actions
65 lines (53 loc) · 1.69 KB
/
Copy pathCache.java
File metadata and controls
65 lines (53 loc) · 1.69 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
public class Cache {
private final byte[][] data;
private final int[] tags;
private final boolean[] valid;
private int hits = 0;
private int misses = 0;
public Cache() {
data = new byte[8][2]; // 8 block, 2 byte/block
tags = new int[8];
valid = new boolean[8];
}
public byte read(int address, Memory memory) {
int blockIndex = (address / 2) % 8;
int tag = address / 16;
if (!valid[blockIndex] || tags[blockIndex] != tag) {
// MISS
misses++;
int blockAddress = address & ~1;
data[blockIndex][0] = memory.readByte(blockAddress);
data[blockIndex][1] = memory.readByte(blockAddress + 1);
tags[blockIndex] = tag;
valid[blockIndex] = true;
} else {
// HIT
hits++;
}
return data[blockIndex][address % 2];
}
public void write(int address, byte value, Memory memory) {
int blockIndex = (address / 2) % 8;
int tag = address / 16;
// Write-through
memory.writeByte(address, value);
// Cache update
if (!valid[blockIndex] || tags[blockIndex] != tag) {
// MISS
misses++;
int blockAddress = address & ~1;
data[blockIndex][0] = memory.readByte(blockAddress);
data[blockIndex][1] = memory.readByte(blockAddress + 1);
tags[blockIndex] = tag;
valid[blockIndex] = true;
}
// Write into cache
data[blockIndex][address % 2] = value;
}
public int getTotalAccesses() {
return hits + misses;
}
public int getHits() {
return hits;
}
}