2 * Copyright (c) 2000-2005 The Regents of The University of Michigan
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.
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.
28 * Authors: Steve Raasch
36 #include <Python.h> // must be before system headers... see Python docs
38 #include <sys/types.h>
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 "config/pythonhome.hh"
59 #include "cpu/base.hh"
61 #include "mem/mem_object.hh"
62 #include "mem/port.hh"
63 #include "python/swig/init.hh"
64 #include "sim/async.hh"
65 #include "sim/builder.hh"
66 #include "sim/host.hh"
67 #include "sim/serialize.hh"
68 #include "sim/sim_events.hh"
69 #include "sim/sim_exit.hh"
70 #include "sim/sim_object.hh"
71 #include "sim/system.hh"
72 #include "sim/stat_control.hh"
73 #include "sim/stats.hh"
74 #include "sim/root.hh"
79 volatile bool async_event
= false;
80 volatile bool async_dump
= false;
81 volatile bool async_dumpreset
= false;
82 volatile bool async_exit
= false;
83 volatile bool async_io
= false;
84 volatile bool async_alarm
= false;
86 /// Stats signal handler.
88 dumpStatsHandler(int sigtype
)
95 dumprstStatsHandler(int sigtype
)
98 async_dumpreset
= true;
101 /// Exit signal handler.
103 exitNowHandler(int sigtype
)
109 /// Abort signal handler.
111 abortHandler(int sigtype
)
113 cerr
<< "Program aborted at cycle " << curTick
<< endl
;
117 main(int argc
, char **argv
)
119 signal(SIGFPE
, SIG_IGN
); // may occur on misspeculated paths
120 signal(SIGTRAP
, SIG_IGN
);
121 signal(SIGUSR1
, dumpStatsHandler
); // dump intermediate stats
122 signal(SIGUSR2
, dumprstStatsHandler
); // dump and reset stats
123 signal(SIGINT
, exitNowHandler
); // dump final stats and exit
124 signal(SIGABRT
, abortHandler
);
126 Py_SetProgramName(argv
[0]);
128 // default path to m5 python code is the currently executing
129 // file... Python ZipImporter will find embedded zip archive.
130 // The M5_ARCHIVE environment variable can be used to override this.
131 char *m5_archive
= getenv("M5_ARCHIVE");
132 string pythonpath
= m5_archive
? m5_archive
: argv
[0];
134 char *oldpath
= getenv("PYTHONPATH");
135 if (oldpath
!= NULL
) {
137 pythonpath
+= oldpath
;
140 if (setenv("PYTHONPATH", pythonpath
.c_str(), true) == -1)
141 fatal("setenv: %s\n", strerror(errno
));
143 char *python_home
= getenv("PYTHONHOME");
145 python_home
= PYTHONHOME
;
146 Py_SetPythonHome(python_home
);
148 // initialize embedded Python interpreter
150 PySys_SetArgv(argc
, argv
);
152 // initialize SWIG modules
155 PyRun_SimpleString("import m5.main");
156 PyRun_SimpleString("m5.main.main()");
158 // clean up Python intepreter.
164 setOutputDir(const string
&dir
)
166 simout
.setDirectory(dir
);
173 createSimObject(const string
&name
)
175 return SimObjectClass::createObject(inifile
, name
);
180 * Pointer to the Python function that maps names to SimObjects.
182 PyObject
*resolveFunc
= NULL
;
185 * Convert a pointer to the Python object that SWIG wraps around a C++
186 * SimObject pointer back to the actual C++ pointer. See main.i.
188 extern "C" SimObject
*convertSwigSimObjectPtr(PyObject
*);
192 resolveSimObject(const string
&name
)
194 PyObject
*pyPtr
= PyEval_CallFunction(resolveFunc
, "(s)", name
.c_str());
197 panic("resolveSimObject: failure on call to Python for %s", name
);
200 SimObject
*simObj
= convertSwigSimObjectPtr(pyPtr
);
202 panic("resolveSimObject: failure on pointer conversion for %s", name
);
209 * Load config.ini into C++ database. Exported to Python via SWIG;
210 * invoked from m5.instantiate().
213 loadIniFile(PyObject
*_resolveFunc
)
215 resolveFunc
= _resolveFunc
;
216 configStream
= simout
.find("config.out");
218 // The configuration database is now complete; start processing it.
219 inifile
.load(simout
.resolve("config.ini"));
221 // Initialize statistics database
222 Stats::InitSimStats();
227 * Look up a MemObject port. Helper function for connectPorts().
230 lookupPort(SimObject
*so
, const std::string
&name
, int i
)
232 MemObject
*mo
= dynamic_cast<MemObject
*>(so
);
234 warn("error casting SimObject %s to MemObject", so
->name());
238 Port
*p
= mo
->getPort(name
, i
);
240 warn("error looking up port %s on object %s", name
, so
->name());
246 * Connect the described MemObject ports. Called from Python via SWIG.
249 connectPorts(SimObject
*o1
, const std::string
&name1
, int i1
,
250 SimObject
*o2
, const std::string
&name2
, int i2
)
252 Port
*p1
= lookupPort(o1
, name1
, i1
);
253 Port
*p2
= lookupPort(o2
, name2
, i2
);
255 if (p1
== NULL
|| p2
== NULL
) {
256 warn("connectPorts: port lookup error");
267 * Do final initialization steps after object construction but before
268 * start of simulation.
273 // Parse and check all non-config-hierarchy parameters.
274 ParamContext::parseAllContexts(inifile
);
275 ParamContext::checkAllContexts();
277 // Echo all parameter settings to stats file as well.
278 ParamContext::showAllContexts(*configStream
);
280 // Do a second pass to finish initializing the sim objects
281 SimObject::initAll();
283 // Restore checkpointed state, if any.
285 configHierarchy
.unserializeSimObjects();
288 SimObject::regAllStats();
290 // Check to make sure that the stats package is properly initialized
293 // Reset to put the stats in a consistent state.
300 /** Simulate for num_cycles additional cycles. If num_cycles is -1
301 * (the default), do not limit simulation; some other event must
302 * terminate the loop. Exported to Python via SWIG.
303 * @return The SimLoopExitEvent that caused the loop to exit.
306 simulate(Tick num_cycles
= MaxTick
)
308 warn("Entering event queue @ %d. Starting simulation...\n", curTick
);
311 fatal("simulate: num_cycles must be >= 0 (was %d)\n", num_cycles
);
312 else if (curTick
+ num_cycles
< 0) //Overflow
313 num_cycles
= MaxTick
;
315 num_cycles
= curTick
+ num_cycles
;
317 Event
*limit_event
= schedExitSimLoop("simulate() limit reached",
321 // there should always be at least one event (the SimLoopExitEvent
322 // we just scheduled) in the queue
323 assert(!mainEventQueue
.empty());
324 assert(curTick
<= mainEventQueue
.nextTick() &&
325 "event scheduled in the past");
327 // forward current cycle to the time of the first event on the
329 curTick
= mainEventQueue
.nextTick();
330 Event
*exit_event
= mainEventQueue
.serviceOne();
331 if (exit_event
!= NULL
) {
332 // hit some kind of exit event; return to Python
333 // event must be subclass of SimLoopExitEvent...
334 SimLoopExitEvent
*se_event
= dynamic_cast<SimLoopExitEvent
*>(exit_event
);
335 if (se_event
== NULL
)
336 panic("Bogus exit event class!");
338 // if we didn't hit limit_event, delete it
339 if (se_event
!= limit_event
) {
340 assert(limit_event
->scheduled());
341 limit_event
->deschedule();
353 using namespace Stats
;
354 SetupEvent(Dump
, curTick
);
357 if (async_dumpreset
) {
358 async_dumpreset
= false;
360 using namespace Stats
;
361 SetupEvent(Dump
| Reset
, curTick
);
366 exitSimLoop("user interrupt received");
369 if (async_io
|| async_alarm
) {
377 // not reached... only exit is return on SimLoopExitEvent
383 return new CountedDrainEvent();
387 cleanupCountedDrain(Event
*counted_drain
)
389 CountedDrainEvent
*event
=
390 dynamic_cast<CountedDrainEvent
*>(counted_drain
);
392 fatal("Called cleanupCountedDrain() on an event that was not "
393 "a CountedDrainEvent.");
395 assert(event
->getCount() == 0);
400 serializeAll(const std::string
&cpt_dir
)
402 Serializable::serializeAll(cpt_dir
);
406 unserializeAll(const std::string
&cpt_dir
)
408 Serializable::unserializeAll(cpt_dir
);
412 * Queue of C++ callbacks to invoke on simulator exit.
417 static CallbackQueue theQueue
;
422 * Register an exit callback.
425 registerExitCallback(Callback
*callback
)
427 exitCallbacks().add(callback
);
431 convertToBaseCPUPtr(SimObject
*obj
)
433 BaseCPU
*ptr
= dynamic_cast<BaseCPU
*>(obj
);
436 warn("Casting to BaseCPU pointer failed");
441 convertToSystemPtr(SimObject
*obj
)
443 System
*ptr
= dynamic_cast<System
*>(obj
);
446 warn("Casting to System pointer failed");
452 * Do C++ simulator exit processing. Exported to SWIG to be invoked
453 * when simulator terminates via Python's atexit mechanism.
458 exitCallbacks().process();
459 exitCallbacks().clear();
463 ParamContext::cleanupAllContexts();
465 // print simulation stats