96631a0d5abc382af0737af1ed2c59e27b70ff1e
[riscv-isa-sim.git] / riscv / cachesim.h
1 #ifndef _RISCV_CACHE_SIM_H
2 #define _RISCV_CACHE_SIM_H
3
4 #include "memtracer.h"
5 #include <cstring>
6 #include <string>
7 #include <map>
8 #include <stdint.h>
9
10 class lfsr_t
11 {
12 public:
13 lfsr_t() : reg(1) {}
14 lfsr_t(const lfsr_t& lfsr) : reg(lfsr.reg) {}
15 uint32_t next() { return reg = (reg>>1)^(-(reg&1) & 0xd0000001); }
16 private:
17 uint32_t reg;
18 };
19
20 class cache_sim_t
21 {
22 public:
23 cache_sim_t(size_t sets, size_t ways, size_t linesz, const char* name);
24 cache_sim_t(const cache_sim_t& rhs);
25 virtual ~cache_sim_t();
26
27 void access(uint64_t addr, size_t bytes, bool store);
28 void print_stats();
29 void set_miss_handler(cache_sim_t* mh) { miss_handler = mh; }
30
31 static cache_sim_t* construct(const char* config, const char* name);
32
33 protected:
34 static const uint64_t VALID = 1ULL << 63;
35 static const uint64_t DIRTY = 1ULL << 62;
36
37 virtual uint64_t* check_tag(uint64_t addr);
38 virtual uint64_t victimize(uint64_t addr);
39
40 lfsr_t lfsr;
41 cache_sim_t* miss_handler;
42
43 size_t sets;
44 size_t ways;
45 size_t linesz;
46 size_t idx_shift;
47
48 uint64_t* tags;
49
50 uint64_t read_accesses;
51 uint64_t read_misses;
52 uint64_t bytes_read;
53 uint64_t write_accesses;
54 uint64_t write_misses;
55 uint64_t bytes_written;
56 uint64_t writebacks;
57
58 std::string name;
59
60 void init();
61 };
62
63 class fa_cache_sim_t : public cache_sim_t
64 {
65 public:
66 fa_cache_sim_t(size_t ways, size_t linesz, const char* name);
67 uint64_t* check_tag(uint64_t addr);
68 uint64_t victimize(uint64_t addr);
69 private:
70 static bool cmp(uint64_t a, uint64_t b);
71 std::map<uint64_t, uint64_t> tags;
72 };
73
74 class cache_memtracer_t : public memtracer_t
75 {
76 public:
77 cache_memtracer_t(const char* config, const char* name)
78 {
79 cache = cache_sim_t::construct(config, name);
80 }
81 ~cache_memtracer_t()
82 {
83 delete cache;
84 }
85 void set_miss_handler(cache_sim_t* mh)
86 {
87 cache->set_miss_handler(mh);
88 }
89
90 protected:
91 cache_sim_t* cache;
92 };
93
94 class icache_sim_t : public cache_memtracer_t
95 {
96 public:
97 icache_sim_t(const char* config) : cache_memtracer_t(config, "I$") {}
98 bool interested_in_range(uint64_t begin, uint64_t end, bool store, bool fetch)
99 {
100 return fetch;
101 }
102 void trace(uint64_t addr, size_t bytes, bool store, bool fetch)
103 {
104 if (fetch) cache->access(addr, bytes, false);
105 }
106 };
107
108 class dcache_sim_t : public cache_memtracer_t
109 {
110 public:
111 dcache_sim_t(const char* config) : cache_memtracer_t(config, "D$") {}
112 bool interested_in_range(uint64_t begin, uint64_t end, bool store, bool fetch)
113 {
114 return !fetch;
115 }
116 void trace(uint64_t addr, size_t bytes, bool store, bool fetch)
117 {
118 if (!fetch) cache->access(addr, bytes, store);
119 }
120 };
121
122 #endif