Add xspike program
[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)),
23 procs(_nprocs), 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 mmu = new mmu_t(mem, memsz);
42
43 if (_nprocs == 0)
44 _nprocs = 1;
45 for (size_t i = 0; i < _nprocs; i++)
46 procs[i] = new processor_t(this, new mmu_t(mem, memsz), i);
47 }
48
49 sim_t::~sim_t()
50 {
51 for (size_t i = 0; i < procs.size(); i++)
52 {
53 mmu_t* pmmu = &procs[i]->mmu;
54 delete procs[i];
55 delete pmmu;
56 }
57 delete mmu;
58 free(mem);
59 }
60
61 void sim_t::send_ipi(reg_t who)
62 {
63 if (who < procs.size())
64 procs[who]->deliver_ipi();
65 }
66
67 reg_t sim_t::get_scr(int which)
68 {
69 switch (which)
70 {
71 case 0: return procs.size();
72 case 1: return memsz >> 20;
73 default: return -1;
74 }
75 }
76
77 void sim_t::run()
78 {
79 while (!htif->done())
80 {
81 if (debug || ctrlc_pressed)
82 interactive();
83 else
84 step(INTERLEAVE, false);
85 }
86 }
87
88 void sim_t::step(size_t n, bool noisy)
89 {
90 for (size_t i = 0, steps = 0; i < n; i += steps)
91 {
92 htif->tick();
93 if (!running())
94 break;
95
96 steps = std::min(n - i, INTERLEAVE - current_step);
97 procs[current_proc]->step(steps, noisy);
98
99 current_step += steps;
100 if (current_step == INTERLEAVE)
101 {
102 current_step = 0;
103 procs[current_proc]->mmu.yield_load_reservation();
104 if (++current_proc == procs.size())
105 current_proc = 0;
106 }
107 }
108 }
109
110 bool sim_t::running()
111 {
112 for (size_t i = 0; i < procs.size(); i++)
113 if (procs[i]->running())
114 return true;
115 return false;
116 }
117
118 void sim_t::stop()
119 {
120 procs[0]->tohost = 1;
121 while (!htif->done())
122 htif->tick();
123 }