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