change htif to link against libfesvr
[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 htif;
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 (1)
76 {
77 if(!debug)
78 step_all(1000, 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 }