add load-reserved/store-conditional instructions
[riscv-isa-sim.git] / riscv / sim.cc
1 // See LICENSE for license details.
2
3 #include "sim.h"
4 #include "htif.h"
5 #include <sys/mman.h>
6 #include <map>
7 #include <iostream>
8 #include <climits>
9 #include <assert.h>
10 #include <unistd.h>
11
12 #ifdef __linux__
13 # define mmap mmap64
14 #endif
15
16 sim_t::sim_t(int _nprocs, int mem_mb, const std::vector<std::string>& args)
17 : htif(new htif_isasim_t(this, args)),
18 procs(_nprocs), current_step(0), current_proc(0)
19 {
20 // allocate target machine's memory, shrinking it as necessary
21 // until the allocation succeeds
22 size_t memsz0 = (size_t)mem_mb << 20;
23 if (memsz0 == 0)
24 memsz0 = 1L << (sizeof(size_t) == 8 ? 32 : 30);
25
26 size_t quantum = std::max(PGSIZE, (reg_t)sysconf(_SC_PAGESIZE));
27 memsz0 = memsz0/quantum*quantum;
28
29 memsz = memsz0;
30 mem = (char*)mmap(NULL, memsz, PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
31
32 if(mem == MAP_FAILED)
33 {
34 while(mem == MAP_FAILED && (memsz = memsz*10/11/quantum*quantum))
35 mem = (char*)mmap(NULL, memsz, PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
36 assert(mem != MAP_FAILED);
37 fprintf(stderr, "warning: only got %lu bytes of target mem (wanted %lu)\n",
38 (unsigned long)memsz, (unsigned long)memsz0);
39 }
40
41 mmu = new mmu_t(mem, memsz);
42
43 for(size_t i = 0; i < num_cores(); i++)
44 procs[i] = new processor_t(this, new mmu_t(mem, memsz), i);
45 }
46
47 sim_t::~sim_t()
48 {
49 for(size_t i = 0; i < num_cores(); i++)
50 {
51 mmu_t* pmmu = &procs[i]->mmu;
52 delete procs[i];
53 delete pmmu;
54 }
55 delete mmu;
56 munmap(mem, memsz);
57 }
58
59 void sim_t::send_ipi(reg_t who)
60 {
61 if(who < num_cores())
62 procs[who]->deliver_ipi();
63 }
64
65 reg_t sim_t::get_scr(int which)
66 {
67 switch (which)
68 {
69 case 0: return num_cores();
70 case 1: return memsz >> 20;
71 default: return -1;
72 }
73 }
74
75 void sim_t::run(bool debug)
76 {
77 while (!htif->done())
78 {
79 if(!debug)
80 step(INTERLEAVE, false);
81 else
82 interactive();
83 }
84 }
85
86 void sim_t::step(size_t n, bool noisy)
87 {
88 for (size_t i = 0, steps = 0; i < n; i += steps)
89 {
90 htif->tick();
91
92 steps = std::min(n - i, INTERLEAVE - current_step);
93 procs[current_proc]->step(steps, noisy);
94
95 current_step += steps;
96 if (current_step == INTERLEAVE)
97 {
98 current_step = 0;
99 procs[current_proc]->mmu.yield_load_reservation();
100 if (++current_proc == num_cores())
101 current_proc = 0;
102 }
103 }
104 }