c9fbd48a077cc30934bef0fb69d8cce3e13e33e6
[gem5.git] / util / systemc / main.cc
1 /*
2 * Copyright (c) 2014 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are
16 * met: redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer;
18 * redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution;
21 * neither the name of the copyright holders nor the names of its
22 * contributors may be used to endorse or promote products derived from
23 * this software without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 *
37 * Authors: Andrew Bardsley
38 * Abdul Mutaal Ahmad
39 */
40
41 /**
42 * @file
43 *
44 * Example top level file for SystemC integration with C++-only
45 * instantiation.
46 *
47 * Build with something like:
48 *
49 * scons --without-python build/ARM/libgem5_opt.so
50 *
51 * g++ -std=c++0x -Ibuild/ARM -Isrc -DTRACING_ON \
52 * -o gem5cxx.opt -Lbuild/ARM -lgem5_opt \
53 * src/sim/sc_main_cxx.cc src/sim/cxx_stats.cc \
54 * src/sim/sc_module.cc src/sim/sc_logger.cc
55 */
56
57 #include <cstdlib>
58 #include <iostream>
59 #include <sstream>
60 #include <systemc>
61
62 #include "base/statistics.hh"
63 #include "base/str.hh"
64 #include "base/trace.hh"
65 #include "cpu/base.hh"
66 #include "sim/cxx_config_ini.hh"
67 #include "sim/cxx_manager.hh"
68 #include "sim/init_signals.hh"
69 #include "sim/serialize.hh"
70 #include "sim/simulate.hh"
71 #include "sim/stat_control.hh"
72 #include "sim/system.hh"
73 #include "sc_logger.hh"
74 #include "sc_module.hh"
75 #include "stats.hh"
76
77 // Defining global string variable decalred in stats.hh
78 std::string filename;
79
80 void
81 usage(const std::string &prog_name)
82 {
83 std::cerr << "Usage: " << prog_name << (
84 " <config_file.ini> [ <option> ]\n\n"
85 "OPTIONS:\n"
86 " -p <object> <param> <value> -- set a parameter\n"
87 " -v <object> <param> <values> -- set a vector parameter from"
88 " a comma\n"
89 " separated values string\n"
90 " -d <flag> -- set a debug flag (-<flag>\n"
91 " clear a flag)\n"
92 " -s <dir> <ticks> -- save checkpoint to dir after"
93 " the given\n"
94 " number of ticks\n"
95 " -r <dir> -- restore checkpoint to dir\n"
96 " -c <from> <to> <ticks> -- switch from cpu 'from' to cpu"
97 " 'to' after\n"
98 " the given number of ticks\n"
99 "\n"
100 );
101
102 std::exit(EXIT_FAILURE);
103 }
104
105 class SimControl : public Gem5SystemC::Module
106 {
107 protected:
108 int argc;
109 char **argv;
110 CxxConfigManager *config_manager;
111 Gem5SystemC::Logger logger;
112
113 bool checkpoint_restore;
114 bool checkpoint_save;
115 bool switch_cpus;
116 std::string checkpoint_dir;
117 std::string from_cpu;
118 std::string to_cpu;
119 Tick pre_run_time;
120 Tick pre_switch_time;
121
122 public:
123 SC_HAS_PROCESS(SimControl);
124
125 SimControl(sc_core::sc_module_name name, int argc_, char **argv_);
126
127 void run();
128 };
129
130 SimControl::SimControl(sc_core::sc_module_name name,
131 int argc_, char **argv_) :
132 Gem5SystemC::Module(name),
133 argc(argc_),
134 argv(argv_)
135 {
136 SC_THREAD(run);
137
138 std::string prog_name(argv[0]);
139 unsigned int arg_ptr = 1;
140
141 if (argc == 1)
142 usage(prog_name);
143
144 cxxConfigInit();
145
146 /* Pass DPRINTF messages to SystemC */
147 Trace::setDebugLogger(&logger);
148
149 /* @todo need this as an option */
150 Gem5SystemC::setTickFrequency();
151
152 /* Make a SystemC-synchronising event queue and install it as the
153 * sole top level gem5 EventQueue */
154 Gem5SystemC::Module::setupEventQueues(*this);
155
156 if (sc_core::sc_get_time_resolution() !=
157 sc_core::sc_time(1, sc_core::SC_PS))
158 {
159 fatal("Time resolution must be set to 1 ps for gem5 to work");
160 }
161
162 /* Enable keyboard interrupt, async I/O etc. */
163 initSignals();
164
165 /* Enable stats */
166 Stats::initSimStats();
167 Stats::registerHandlers(CxxConfig::statsReset, CxxConfig::statsDump);
168
169 Trace::enable();
170 setDebugFlag("Terminal");
171
172 checkpoint_restore = false;
173 checkpoint_save = false;
174 switch_cpus = false;
175 checkpoint_dir = "";
176 from_cpu = "";
177 to_cpu = "";
178 pre_run_time = 1000000;
179 pre_switch_time = 1000000;
180
181 const std::string config_file(argv[arg_ptr]);
182
183 CxxConfigFileBase *conf = new CxxIniFile();
184
185 if (!conf->load(config_file.c_str()))
186 fatal("Can't open config file: %s", config_file);
187
188 arg_ptr++;
189
190 config_manager = new CxxConfigManager(*conf);
191
192 try {
193 while (arg_ptr < argc) {
194 std::string option(argv[arg_ptr]);
195 arg_ptr++;
196 unsigned num_args = argc - arg_ptr;
197
198 if (option == "-p") {
199 if (num_args < 3)
200 usage(prog_name);
201 config_manager->setParam(argv[arg_ptr], argv[arg_ptr + 1],
202 argv[arg_ptr + 2]);
203 arg_ptr += 3;
204 } else if (option == "-v") {
205 std::vector<std::string> values;
206
207 if (num_args < 3)
208 usage(prog_name);
209 tokenize(values, argv[2], ',');
210 config_manager->setParamVector(argv[arg_ptr],
211 argv[arg_ptr], values);
212 arg_ptr += 3;
213 } else if (option == "-d") {
214 if (num_args < 1)
215 usage(prog_name);
216 if (argv[arg_ptr][0] == '-')
217 clearDebugFlag(argv[arg_ptr] + 1);
218 else
219 setDebugFlag(argv[arg_ptr]);
220 arg_ptr++;
221 } else if (option == "-r") {
222 if (num_args < 1)
223 usage(prog_name);
224 checkpoint_dir = argv[arg_ptr];
225 checkpoint_restore = true;
226 arg_ptr++;
227 } else if (option == "-s") {
228 if (num_args < 2)
229 usage(prog_name);
230 checkpoint_dir = argv[arg_ptr];
231 std::istringstream(argv[arg_ptr + 1]) >> pre_run_time;
232 checkpoint_save = true;
233 arg_ptr += 2;
234 } else if (option == "-c") {
235 if (num_args < 3)
236 usage(prog_name);
237 switch_cpus = true;
238 from_cpu = argv[arg_ptr];
239 to_cpu = argv[arg_ptr + 1];
240 std::istringstream(argv[arg_ptr + 2]) >> pre_switch_time;
241 arg_ptr += 3;
242 } else {
243 usage(prog_name);
244 }
245 }
246 } catch (CxxConfigManager::Exception &e) {
247 fatal("Config problem in sim object %s: %s", e.name, e.message);
248 }
249
250 if (checkpoint_save && checkpoint_restore) {
251 fatal("Don't try to save and restore a checkpoint in the same"
252 "run");
253 }
254
255 CxxConfig::statsEnable();
256 getEventQueue(0)->dump();
257
258 try {
259 config_manager->instantiate();
260 } catch (CxxConfigManager::Exception &e) {
261 fatal("Config problem in sim object %s: %s", e.name, e.message);
262 }
263 }
264
265 void SimControl::run()
266 {
267 EventQueue *eventq = getEventQueue(0);
268 GlobalSimLoopExitEvent *exit_event = NULL;
269
270 /* There *must* be no scheduled events yet */
271 fatal_if(!eventq->empty(), "There must be no posted events"
272 " before SimControl::run");
273
274 try {
275 if (checkpoint_restore) {
276 std::cerr << "Restoring checkpoint\n";
277
278 CheckpointIn *checkpoint = new CheckpointIn(checkpoint_dir,
279 config_manager->getSimObjectResolver());
280
281 /* Catch SystemC up with gem5 after checkpoint restore.
282 * Note that gem5 leading SystemC is always a violation of the
283 * required relationship between the two, hence this careful
284 * catchup */
285
286 DrainManager::instance().preCheckpointRestore();
287 Serializable::unserializeGlobals(*checkpoint);
288
289 Tick systemc_time = sc_core::sc_time_stamp().value();
290 if (curTick() > systemc_time) {
291 Tick wait_period = curTick() - systemc_time;
292
293 std::cerr << "Waiting for " << wait_period << "ps for"
294 " SystemC to catch up to gem5\n";
295 wait(sc_core::sc_time::from_value(wait_period));
296 }
297
298 config_manager->loadState(*checkpoint);
299 config_manager->startup();
300 config_manager->drainResume();
301
302 std::cerr << "Restored from Checkpoint\n";
303 } else {
304 config_manager->initState();
305 config_manager->startup();
306 }
307 } catch (CxxConfigManager::Exception &e) {
308 fatal("Config problem in sim object %s: %s", e.name, e.message);
309 }
310
311 fatal_if(eventq->empty(), "No events to process after system startup");
312
313 if (checkpoint_save) {
314 exit_event = simulate(pre_run_time);
315
316 unsigned int drain_count = 1;
317 do {
318 drain_count = config_manager->drain();
319
320 std::cerr << "Draining " << drain_count << '\n';
321
322 if (drain_count > 0) {
323 exit_event = simulate();
324 }
325 } while (drain_count > 0);
326
327 std::cerr << "Simulation stop at tick " << curTick()
328 << ", cause: " << exit_event->getCause() << '\n';
329
330 std::cerr << "Checkpointing\n";
331
332 /* FIXME, this should really be serialising just for
333 * config_manager rather than using serializeAll's ugly
334 * SimObject static object list */
335 Serializable::serializeAll(checkpoint_dir);
336
337 std::cerr << "Completed checkpoint\n";
338
339 config_manager->drainResume();
340 }
341
342 if (switch_cpus) {
343 exit_event = simulate(pre_switch_time);
344
345 std::cerr << "Switching CPU\n";
346
347 /* Assume the system is called system */
348 System &system = config_manager->getObject<System>("system");
349 BaseCPU &old_cpu = config_manager->getObject<BaseCPU>(from_cpu);
350 BaseCPU &new_cpu = config_manager->getObject<BaseCPU>(to_cpu);
351
352 unsigned int drain_count = 1;
353 do {
354 drain_count = config_manager->drain();
355
356 std::cerr << "Draining " << drain_count << '\n';
357
358 if (drain_count > 0) {
359 exit_event = simulate();
360 }
361 } while (drain_count > 0);
362
363 old_cpu.switchOut();
364 system.setMemoryMode(Enums::timing);
365
366 new_cpu.takeOverFrom(&old_cpu);
367 config_manager->drainResume();
368
369 std::cerr << "Switched CPU\n";
370 }
371
372 exit_event = simulate();
373
374 std::cerr << "Exit at tick " << curTick()
375 << ", cause: " << exit_event->getCause() << '\n';
376
377 getEventQueue(0)->dump();
378
379 #if TRY_CLEAN_DELETE
380 config_manager->deleteObjects();
381 #endif
382 }
383
384 int
385 sc_main(int argc, char **argv)
386 {
387 SimControl sim_control("gem5", argc, argv);
388
389 filename = "m5out/stats-systemc.txt";
390
391 sc_core::sc_start();
392
393 CxxConfig::statsDump();
394
395 return EXIT_SUCCESS;
396 }