Merge branch 'master' of github.com:ucb-bar/riscv-isa-sim into confprec
[riscv-isa-sim.git] / riscv / sim.cc
1 // See LICENSE for license details.
2
3 #include "sim.h"
4 #include "htif.h"
5 #include <map>
6 #include <iostream>
7 #include <climits>
8 #include <cstdlib>
9 #include <cassert>
10 #include <signal.h>
11
12 volatile bool ctrlc_pressed = false;
13 static void handle_signal(int sig)
14 {
15 if (ctrlc_pressed)
16 exit(-1);
17 ctrlc_pressed = true;
18 signal(sig, &handle_signal);
19 }
20
21 sim_t::sim_t(size_t nprocs, size_t mem_mb, const std::vector<std::string>& args)
22 : htif(new htif_isasim_t(this, args)), procs(std::max(nprocs, size_t(1))),
23 current_step(0), current_proc(0), debug(false)
24 {
25 signal(SIGINT, &handle_signal);
26 // allocate target machine's memory, shrinking it as necessary
27 // until the allocation succeeds
28 size_t memsz0 = (size_t)mem_mb << 20;
29 size_t quantum = 1L << 20;
30 if (memsz0 == 0)
31 memsz0 = 1L << (sizeof(size_t) == 8 ? 32 : 30);
32
33 memsz = memsz0;
34 while ((mem = (char*)calloc(1, memsz)) == NULL)
35 memsz = memsz*10/11/quantum*quantum;
36
37 if (memsz != memsz)
38 fprintf(stderr, "warning: only got %lu bytes of target mem (wanted %lu)\n",
39 (unsigned long)memsz, (unsigned long)memsz0);
40
41 debug_mmu = new mmu_t(mem, memsz);
42
43 for (size_t i = 0; i < procs.size(); i++)
44 procs[i] = new processor_t(this, new mmu_t(mem, memsz), i);
45 }
46
47 sim_t::~sim_t()
48 {
49 for (size_t i = 0; i < procs.size(); i++)
50 {
51 mmu_t* pmmu = procs[i]->get_mmu();
52 delete procs[i];
53 delete pmmu;
54 }
55 delete debug_mmu;
56 free(mem);
57 }
58
59 void sim_t::send_ipi(reg_t who)
60 {
61 if (who < procs.size())
62 procs[who]->deliver_ipi();
63 }
64
65 reg_t sim_t::get_scr(int which)
66 {
67 switch (which)
68 {
69 case 0: return procs.size();
70 case 1: return memsz >> 20;
71 default: return -1;
72 }
73 }
74
75 int sim_t::run()
76 {
77 while (htif->tick())
78 {
79 if (debug || ctrlc_pressed)
80 interactive();
81 else
82 step(INTERLEAVE);
83 }
84 return htif->exit_code();
85 }
86
87 void sim_t::step(size_t n)
88 {
89 for (size_t i = 0, steps = 0; i < n; i += steps)
90 {
91 steps = std::min(n - i, INTERLEAVE - current_step);
92 procs[current_proc]->step(steps);
93
94 current_step += steps;
95 if (current_step == INTERLEAVE)
96 {
97 current_step = 0;
98 procs[current_proc]->yield_load_reservation();
99 if (++current_proc == procs.size())
100 current_proc = 0;
101
102 htif->tick();
103 }
104 }
105 }
106
107 bool sim_t::running()
108 {
109 for (size_t i = 0; i < procs.size(); i++)
110 if (procs[i]->running())
111 return true;
112 return false;
113 }
114
115 void sim_t::stop()
116 {
117 procs[0]->state.tohost = 1;
118 while (htif->tick())
119 ;
120 }
121
122 void sim_t::set_debug(bool value)
123 {
124 debug = value;
125 }
126
127 void sim_t::set_procs_debug(bool value)
128 {
129 for (size_t i=0; i< procs.size(); i++)
130 procs[i]->set_debug(value);
131 }