8a56cd975e5433778564adccdada09188bee5b62
[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 steps(0)
18 {
19 // allocate target machine's memory, shrinking it as necessary
20 // until the allocation succeeds
21
22 size_t memsz0 = sizeof(size_t) == 8 ? 0x100000000ULL : 0x70000000UL;
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 htif->init(this);
44 }
45
46 sim_t::~sim_t()
47 {
48 for(size_t i = 0; i < num_cores(); i++)
49 {
50 mmu_t* pmmu = &procs[i]->mmu;
51 delete procs[i];
52 delete pmmu;
53 }
54 delete mmu;
55 munmap(mem, memsz);
56 }
57
58 void sim_t::send_ipi(reg_t who)
59 {
60 if(who < num_cores())
61 procs[who]->deliver_ipi();
62 }
63
64 void sim_t::run(bool debug)
65 {
66 // word 0 of memory contains the memory capacity in MB
67 mmu->store_uint32(0, memsz >> 20);
68 // word 1 of memory contains the core count
69 mmu->store_uint32(4, num_cores());
70
71 htif->wait_for_start();
72
73 for(running = true; running; )
74 {
75 if(!debug)
76 step_all(10000, 100, false);
77 else
78 interactive();
79 }
80 }
81
82 void sim_t::step_all(size_t n, size_t interleave, bool noisy)
83 {
84 for(size_t j = 0; j < n; j+=interleave)
85 {
86 if (steps % 16384 + interleave >= 16384)
87 htif->wait_for_packet();
88 steps += interleave;
89 for(int i = 0; i < (int)num_cores(); i++)
90 procs[i]->step(interleave,noisy);
91 }
92 }