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