new 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 tohost(0),
16 fromhost(0),
17 procs(_nprocs),
18 running(false)
19 {
20 // allocate target machine's memory, shrinking it as necessary
21 // until the allocation succeeds
22
23 size_t memsz0 = sizeof(size_t) == 8 ? 0x100000000ULL : 0x70000000UL;
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 htif->init(this);
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::set_tohost(reg_t val)
60 {
61 fromhost = 0;
62 tohost = val;
63 htif->wait_for_tohost_write();
64 }
65
66 reg_t sim_t::get_tohost()
67 {
68 return tohost;
69 }
70
71 reg_t sim_t::get_fromhost()
72 {
73 htif->wait_for_fromhost_write();
74 return fromhost;
75 }
76
77 void sim_t::send_ipi(reg_t who)
78 {
79 if(who < num_cores())
80 procs[who]->deliver_ipi();
81 }
82
83 void sim_t::run(bool debug)
84 {
85 htif->wait_for_start();
86
87 // word 0 of memory contains the memory capacity in MB
88 mmu->store_uint32(0, memsz >> 20);
89 // word 1 of memory contains the core count
90 mmu->store_uint32(4, num_cores());
91
92 // start core 0
93 send_ipi(0);
94
95 for(running = true; running; )
96 {
97 for (int i = 0; i < 1000; i++)
98 {
99 if(!debug)
100 step_all(100,100,false);
101 else
102 interactive();
103 }
104
105 htif->poll();
106 }
107 }
108
109 void sim_t::step_all(size_t n, size_t interleave, bool noisy)
110 {
111 for(size_t j = 0; j < n; j+=interleave)
112 for(int i = 0; i < (int)num_cores(); i++)
113 procs[i]->step(interleave,noisy);
114 }