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 "cpu/base.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/system.hh"
70 #include "sim/stat_control.hh"
71 #include "sim/stats.hh"
72 #include "sim/root.hh"
77 volatile bool async_event
= false;
78 volatile bool async_dump
= false;
79 volatile bool async_dumpreset
= false;
80 volatile bool async_exit
= false;
81 volatile bool async_io
= false;
82 volatile bool async_alarm
= false;
84 /// Stats signal handler.
86 dumpStatsHandler(int sigtype
)
93 dumprstStatsHandler(int sigtype
)
96 async_dumpreset
= true;
99 /// Exit signal handler.
101 exitNowHandler(int sigtype
)
107 /// Abort signal handler.
109 abortHandler(int sigtype
)
111 cerr
<< "Program aborted at cycle " << curTick
<< endl
;
114 // dump trace buffer, if there is one
115 Trace::theLog
.dump(cerr
);
119 extern "C" { void init_cc_main(); }
122 main(int argc
, char **argv
)
124 signal(SIGFPE
, SIG_IGN
); // may occur on misspeculated paths
125 signal(SIGTRAP
, SIG_IGN
);
126 signal(SIGUSR1
, dumpStatsHandler
); // dump intermediate stats
127 signal(SIGUSR2
, dumprstStatsHandler
); // dump and reset stats
128 signal(SIGINT
, exitNowHandler
); // dump final stats and exit
129 signal(SIGABRT
, abortHandler
);
131 Py_SetProgramName(argv
[0]);
133 // default path to m5 python code is the currently executing
134 // file... Python ZipImporter will find embedded zip archive.
135 // The M5_ARCHIVE environment variable can be used to override this.
136 char *m5_archive
= getenv("M5_ARCHIVE");
137 string pythonpath
= m5_archive
? m5_archive
: argv
[0];
139 char *oldpath
= getenv("PYTHONPATH");
140 if (oldpath
!= NULL
) {
142 pythonpath
+= oldpath
;
145 if (setenv("PYTHONPATH", pythonpath
.c_str(), true) == -1)
146 fatal("setenv: %s\n", strerror(errno
));
148 // initialize embedded Python interpreter
150 PySys_SetArgv(argc
, argv
);
152 // initialize SWIG 'cc_main' module
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
= -1)
308 warn("Entering event queue @ %d. Starting simulation...\n", curTick
);
310 // Fix up num_cycles. Special default value -1 means simulate
311 // "forever"... schedule event at MaxTick just to be safe.
312 // Otherwise it's a delta for additional cycles to simulate past
313 // curTick, and thus must be non-negative.
314 if (num_cycles
== -1)
315 num_cycles
= MaxTick
;
316 else if (num_cycles
< 0)
317 fatal("simulate: num_cycles must be >= 0 (was %d)\n", num_cycles
);
319 num_cycles
= curTick
+ num_cycles
;
321 Event
*limit_event
= schedExitSimLoop("simulate() limit reached",
325 // there should always be at least one event (the SimLoopExitEvent
326 // we just scheduled) in the queue
327 assert(!mainEventQueue
.empty());
328 assert(curTick
<= mainEventQueue
.nextTick() &&
329 "event scheduled in the past");
331 // forward current cycle to the time of the first event on the
333 curTick
= mainEventQueue
.nextTick();
334 Event
*exit_event
= mainEventQueue
.serviceOne();
335 if (exit_event
!= NULL
) {
336 // hit some kind of exit event; return to Python
337 // event must be subclass of SimLoopExitEvent...
338 SimLoopExitEvent
*se_event
= dynamic_cast<SimLoopExitEvent
*>(exit_event
);
339 if (se_event
== NULL
)
340 panic("Bogus exit event class!");
342 // if we didn't hit limit_event, delete it
343 if (se_event
!= limit_event
) {
344 assert(limit_event
->scheduled());
345 limit_event
->deschedule();
357 using namespace Stats
;
358 SetupEvent(Dump
, curTick
);
361 if (async_dumpreset
) {
362 async_dumpreset
= false;
364 using namespace Stats
;
365 SetupEvent(Dump
| Reset
, curTick
);
370 exitSimLoop("user interrupt received");
373 if (async_io
|| async_alarm
) {
381 // not reached... only exit is return on SimLoopExitEvent
387 return new CountedDrainEvent();
391 cleanupCountedDrain(Event
*counted_drain
)
393 CountedDrainEvent
*event
=
394 dynamic_cast<CountedDrainEvent
*>(counted_drain
);
396 fatal("Called cleanupCountedDrain() on an event that was not "
397 "a CountedDrainEvent.");
399 assert(event
->getCount() == 0);
404 serializeAll(const std::string
&cpt_dir
)
406 Serializable::serializeAll(cpt_dir
);
410 unserializeAll(const std::string
&cpt_dir
)
412 Serializable::unserializeAll(cpt_dir
);
416 * Queue of C++ callbacks to invoke on simulator exit.
421 static CallbackQueue theQueue
;
426 * Register an exit callback.
429 registerExitCallback(Callback
*callback
)
431 exitCallbacks().add(callback
);
435 convertToBaseCPUPtr(SimObject
*obj
)
437 BaseCPU
*ptr
= dynamic_cast<BaseCPU
*>(obj
);
440 warn("Casting to BaseCPU pointer failed");
445 convertToSystemPtr(SimObject
*obj
)
447 System
*ptr
= dynamic_cast<System
*>(obj
);
450 warn("Casting to System pointer failed");
456 * Do C++ simulator exit processing. Exported to SWIG to be invoked
457 * when simulator terminates via Python's atexit mechanism.
462 exitCallbacks().process();
463 exitCallbacks().clear();
467 ParamContext::cleanupAllContexts();
469 // print simulation stats