Get the path to load the ini file from. I'm not sure if this fix is needed in other...
[gem5.git] / src / sim / main.cc
1 /*
2 * Copyright (c) 2000-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Steve Raasch
29 * Nathan Binkert
30 * Steve Reinhardt
31 */
32
33 ///
34 /// @file sim/main.cc
35 ///
36 #include <Python.h> // must be before system headers... see Python docs
37
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <errno.h>
41 #include <libgen.h>
42 #include <stdlib.h>
43 #include <signal.h>
44 #include <getopt.h>
45
46 #include <list>
47 #include <string>
48 #include <vector>
49
50 #include "base/callback.hh"
51 #include "base/inifile.hh"
52 #include "base/misc.hh"
53 #include "base/output.hh"
54 #include "base/pollevent.hh"
55 #include "base/statistics.hh"
56 #include "base/str.hh"
57 #include "base/time.hh"
58 #include "cpu/base.hh"
59 #include "cpu/smt.hh"
60 #include "mem/mem_object.hh"
61 #include "mem/port.hh"
62 #include "sim/async.hh"
63 #include "sim/builder.hh"
64 #include "sim/host.hh"
65 #include "sim/serialize.hh"
66 #include "sim/sim_events.hh"
67 #include "sim/sim_exit.hh"
68 #include "sim/sim_object.hh"
69 #include "sim/stat_control.hh"
70 #include "sim/stats.hh"
71 #include "sim/root.hh"
72
73 using namespace std;
74
75 // See async.h.
76 volatile bool async_event = false;
77 volatile bool async_dump = false;
78 volatile bool async_dumpreset = false;
79 volatile bool async_exit = false;
80 volatile bool async_io = false;
81 volatile bool async_alarm = false;
82
83 /// Stats signal handler.
84 void
85 dumpStatsHandler(int sigtype)
86 {
87 async_event = true;
88 async_dump = true;
89 }
90
91 void
92 dumprstStatsHandler(int sigtype)
93 {
94 async_event = true;
95 async_dumpreset = true;
96 }
97
98 /// Exit signal handler.
99 void
100 exitNowHandler(int sigtype)
101 {
102 async_event = true;
103 async_exit = true;
104 }
105
106 /// Abort signal handler.
107 void
108 abortHandler(int sigtype)
109 {
110 cerr << "Program aborted at cycle " << curTick << endl;
111
112 #if TRACING_ON
113 // dump trace buffer, if there is one
114 Trace::theLog.dump(cerr);
115 #endif
116 }
117
118 extern "C" { void init_cc_main(); }
119
120 int
121 main(int argc, char **argv)
122 {
123 signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths
124 signal(SIGTRAP, SIG_IGN);
125 signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats
126 signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats
127 signal(SIGINT, exitNowHandler); // dump final stats and exit
128 signal(SIGABRT, abortHandler);
129
130 Py_SetProgramName(argv[0]);
131
132 // default path to m5 python code is the currently executing
133 // file... Python ZipImporter will find embedded zip archive.
134 // The M5_ARCHIVE environment variable can be used to override this.
135 char *m5_archive = getenv("M5_ARCHIVE");
136 string pythonpath = m5_archive ? m5_archive : argv[0];
137
138 char *oldpath = getenv("PYTHONPATH");
139 if (oldpath != NULL) {
140 pythonpath += ":";
141 pythonpath += oldpath;
142 }
143
144 if (setenv("PYTHONPATH", pythonpath.c_str(), true) == -1)
145 fatal("setenv: %s\n", strerror(errno));
146
147 // initialize embedded Python interpreter
148 Py_Initialize();
149 PySys_SetArgv(argc, argv);
150
151 // initialize SWIG 'cc_main' module
152 init_cc_main();
153
154 PyRun_SimpleString("import m5");
155 PyRun_SimpleString("m5.main()");
156
157 // clean up Python intepreter.
158 Py_Finalize();
159 }
160
161
162 void
163 setOutputDir(const string &dir)
164 {
165 simout.setDirectory(dir);
166 }
167
168
169 IniFile inifile;
170
171 SimObject *
172 createSimObject(const string &name)
173 {
174 return SimObjectClass::createObject(inifile, name);
175 }
176
177
178 /**
179 * Pointer to the Python function that maps names to SimObjects.
180 */
181 PyObject *resolveFunc = NULL;
182
183 /**
184 * Convert a pointer to the Python object that SWIG wraps around a C++
185 * SimObject pointer back to the actual C++ pointer. See main.i.
186 */
187 extern "C" SimObject *convertSwigSimObjectPtr(PyObject *);
188
189
190 SimObject *
191 resolveSimObject(const string &name)
192 {
193 PyObject *pyPtr = PyEval_CallFunction(resolveFunc, "(s)", name.c_str());
194 if (pyPtr == NULL) {
195 PyErr_Print();
196 panic("resolveSimObject: failure on call to Python for %s", name);
197 }
198
199 SimObject *simObj = convertSwigSimObjectPtr(pyPtr);
200 if (simObj == NULL)
201 panic("resolveSimObject: failure on pointer conversion for %s", name);
202
203 return simObj;
204 }
205
206
207 /**
208 * Load config.ini into C++ database. Exported to Python via SWIG;
209 * invoked from m5.instantiate().
210 */
211 void
212 loadIniFile(PyObject *_resolveFunc)
213 {
214 resolveFunc = _resolveFunc;
215 configStream = simout.find("config.out");
216
217 // The configuration database is now complete; start processing it.
218 inifile.load(simout.resolve("config.ini"));
219
220 // Initialize statistics database
221 Stats::InitSimStats();
222 }
223
224
225 /**
226 * Look up a MemObject port. Helper function for connectPorts().
227 */
228 Port *
229 lookupPort(SimObject *so, const std::string &name, int i)
230 {
231 MemObject *mo = dynamic_cast<MemObject *>(so);
232 if (mo == NULL) {
233 warn("error casting SimObject %s to MemObject", so->name());
234 return NULL;
235 }
236
237 Port *p = mo->getPort(name, i);
238 if (p == NULL)
239 warn("error looking up port %s on object %s", name, so->name());
240 return p;
241 }
242
243
244 /**
245 * Connect the described MemObject ports. Called from Python via SWIG.
246 */
247 int
248 connectPorts(SimObject *o1, const std::string &name1, int i1,
249 SimObject *o2, const std::string &name2, int i2)
250 {
251 Port *p1 = lookupPort(o1, name1, i1);
252 Port *p2 = lookupPort(o2, name2, i2);
253
254 if (p1 == NULL || p2 == NULL) {
255 warn("connectPorts: port lookup error");
256 return 0;
257 }
258
259 p1->setPeer(p2);
260 p2->setPeer(p1);
261
262 return 1;
263 }
264
265 /**
266 * Do final initialization steps after object construction but before
267 * start of simulation.
268 */
269 void
270 finalInit()
271 {
272 // Parse and check all non-config-hierarchy parameters.
273 ParamContext::parseAllContexts(inifile);
274 ParamContext::checkAllContexts();
275
276 // Echo all parameter settings to stats file as well.
277 ParamContext::showAllContexts(*configStream);
278
279 // Do a second pass to finish initializing the sim objects
280 SimObject::initAll();
281
282 // Restore checkpointed state, if any.
283 #if 0
284 configHierarchy.unserializeSimObjects();
285 #endif
286
287 SimObject::regAllStats();
288
289 // Check to make sure that the stats package is properly initialized
290 Stats::check();
291
292 // Reset to put the stats in a consistent state.
293 Stats::reset();
294
295 SimStartup();
296 }
297
298
299 /** Simulate for num_cycles additional cycles. If num_cycles is -1
300 * (the default), do not limit simulation; some other event must
301 * terminate the loop. Exported to Python via SWIG.
302 * @return The SimLoopExitEvent that caused the loop to exit.
303 */
304 SimLoopExitEvent *
305 simulate(Tick num_cycles = -1)
306 {
307 warn("Entering event queue @ %d. Starting simulation...\n", curTick);
308
309 // Fix up num_cycles. Special default value -1 means simulate
310 // "forever"... schedule event at MaxTick just to be safe.
311 // Otherwise it's a delta for additional cycles to simulate past
312 // curTick, and thus must be non-negative.
313 if (num_cycles == -1)
314 num_cycles = MaxTick;
315 else if (num_cycles < 0)
316 fatal("simulate: num_cycles must be >= 0 (was %d)\n", num_cycles);
317 else
318 num_cycles = curTick + num_cycles;
319
320 Event *limit_event = new SimLoopExitEvent(num_cycles,
321 "simulate() limit reached");
322
323 while (1) {
324 // there should always be at least one event (the SimLoopExitEvent
325 // we just scheduled) in the queue
326 assert(!mainEventQueue.empty());
327 assert(curTick <= mainEventQueue.nextTick() &&
328 "event scheduled in the past");
329
330 // forward current cycle to the time of the first event on the
331 // queue
332 curTick = mainEventQueue.nextTick();
333 Event *exit_event = mainEventQueue.serviceOne();
334 if (exit_event != NULL) {
335 // hit some kind of exit event; return to Python
336 // event must be subclass of SimLoopExitEvent...
337 SimLoopExitEvent *se_event = dynamic_cast<SimLoopExitEvent *>(exit_event);
338 if (se_event == NULL)
339 panic("Bogus exit event class!");
340
341 // if we didn't hit limit_event, delete it
342 if (se_event != limit_event) {
343 assert(limit_event->scheduled());
344 limit_event->deschedule();
345 delete limit_event;
346 }
347
348 return se_event;
349 }
350
351 if (async_event) {
352 async_event = false;
353 if (async_dump) {
354 async_dump = false;
355
356 using namespace Stats;
357 SetupEvent(Dump, curTick);
358 }
359
360 if (async_dumpreset) {
361 async_dumpreset = false;
362
363 using namespace Stats;
364 SetupEvent(Dump | Reset, curTick);
365 }
366
367 if (async_exit) {
368 async_exit = false;
369 exitSimLoop("user interrupt received");
370 }
371
372 if (async_io || async_alarm) {
373 async_io = false;
374 async_alarm = false;
375 pollQueue.service();
376 }
377 }
378 }
379
380 // not reached... only exit is return on SimLoopExitEvent
381 }
382
383 Event *
384 createCountedDrain()
385 {
386 return new CountedDrainEvent();
387 }
388
389 void
390 cleanupCountedDrain(Event *counted_drain)
391 {
392 CountedDrainEvent *event =
393 dynamic_cast<CountedDrainEvent *>(counted_drain);
394 if (event == NULL) {
395 fatal("Called cleanupCountedDrain() on an event that was not "
396 "a CountedDrainEvent.");
397 }
398 assert(event->getCount() == 0);
399 delete event;
400 }
401
402 void
403 serializeAll(const std::string &cpt_dir)
404 {
405 Serializable::serializeAll(cpt_dir);
406 }
407
408 void
409 unserializeAll(const std::string &cpt_dir)
410 {
411 Serializable::unserializeAll(cpt_dir);
412 }
413
414 /**
415 * Queue of C++ callbacks to invoke on simulator exit.
416 */
417 CallbackQueue exitCallbacks;
418
419 /**
420 * Register an exit callback.
421 */
422 void
423 registerExitCallback(Callback *callback)
424 {
425 exitCallbacks.add(callback);
426 }
427
428 BaseCPU *
429 convertToBaseCPUPtr(SimObject *obj)
430 {
431 BaseCPU *ptr = dynamic_cast<BaseCPU *>(obj);
432
433 if (ptr == NULL)
434 warn("Casting to BaseCPU pointer failed");
435 return ptr;
436 }
437
438 /**
439 * Do C++ simulator exit processing. Exported to SWIG to be invoked
440 * when simulator terminates via Python's atexit mechanism.
441 */
442 void
443 doExitCleanup()
444 {
445 exitCallbacks.process();
446 exitCallbacks.clear();
447
448 cout.flush();
449
450 ParamContext::cleanupAllContexts();
451
452 // print simulation stats
453 Stats::DumpNow();
454 }