Changed supervisor mode
[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, htif_t* _htif)
14 : htif(_htif),
15 procs(_nprocs),
16 running(false)
17 {
18 // allocate target machine's memory, shrinking it as necessary
19 // until the allocation succeeds
20
21 size_t memsz0 = sizeof(size_t) == 8 ? 0x100000000ULL : 0x70000000UL;
22 size_t quantum = std::max(PGSIZE, (reg_t)sysconf(_SC_PAGESIZE));
23 memsz0 = memsz0/quantum*quantum;
24
25 memsz = memsz0;
26 mem = (char*)mmap(NULL, memsz, PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
27
28 if(mem == MAP_FAILED)
29 {
30 while(mem == MAP_FAILED && (memsz = memsz*10/11/quantum*quantum))
31 mem = (char*)mmap(NULL, memsz, PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
32 assert(mem != MAP_FAILED);
33 fprintf(stderr, "warning: only got %lu bytes of target mem (wanted %lu)\n",
34 (unsigned long)memsz, (unsigned long)memsz0);
35 }
36
37 mmu = new mmu_t(mem, memsz);
38
39 for(size_t i = 0; i < num_cores(); i++)
40 procs[i] = new processor_t(this, new mmu_t(mem, memsz), i);
41
42 htif->init(this);
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::set_tohost(reg_t val)
58 {
59 fromhost = 0;
60 tohost = val;
61 htif->wait_for_tohost_write();
62 }
63
64 reg_t sim_t::get_fromhost()
65 {
66 htif->wait_for_fromhost_write();
67 return fromhost;
68 }
69
70 void sim_t::send_ipi(reg_t who)
71 {
72 if(who < num_cores())
73 procs[who]->deliver_ipi();
74 }
75
76 void sim_t::run(bool debug)
77 {
78 htif->wait_for_start();
79
80 // word 0 of memory contains the memory capacity in MB
81 mmu->store_uint32(0, memsz >> 20);
82 // word 1 of memory contains the core count
83 mmu->store_uint32(4, num_cores());
84
85 // start core 0
86 send_ipi(0);
87
88 for(running = true; running; )
89 {
90 if(!debug)
91 step_all(100,100,false);
92 else
93 interactive();
94 }
95 }
96
97 void sim_t::step_all(size_t n, size_t interleave, bool noisy)
98 {
99 for(size_t j = 0; j < n; j+=interleave)
100 for(int i = 0; i < (int)num_cores(); i++)
101 procs[i]->step(interleave,noisy);
102 }