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/stat_control.hh"
70 #include "sim/stats.hh"
71 #include "sim/root.hh"
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;
83 /// Stats signal handler.
85 dumpStatsHandler(int sigtype
)
92 dumprstStatsHandler(int sigtype
)
95 async_dumpreset
= true;
98 /// Exit signal handler.
100 exitNowHandler(int sigtype
)
106 /// Abort signal handler.
108 abortHandler(int sigtype
)
110 cerr
<< "Program aborted at cycle " << curTick
<< endl
;
113 // dump trace buffer, if there is one
114 Trace::theLog
.dump(cerr
);
118 extern "C" { void init_cc_main(); }
121 main(int argc
, char **argv
)
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
);
130 Py_SetProgramName(argv
[0]);
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];
138 char *oldpath
= getenv("PYTHONPATH");
139 if (oldpath
!= NULL
) {
141 pythonpath
+= oldpath
;
144 if (setenv("PYTHONPATH", pythonpath
.c_str(), true) == -1)
145 fatal("setenv: %s\n", strerror(errno
));
147 // initialize embedded Python interpreter
149 PySys_SetArgv(argc
, argv
);
151 // initialize SWIG 'cc_main' module
154 PyRun_SimpleString("import m5");
155 PyRun_SimpleString("m5.main()");
157 // clean up Python intepreter.
163 setOutputDir(const string
&dir
)
165 simout
.setDirectory(dir
);
172 createSimObject(const string
&name
)
174 return SimObjectClass::createObject(inifile
, name
);
179 * Pointer to the Python function that maps names to SimObjects.
181 PyObject
*resolveFunc
= NULL
;
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.
187 extern "C" SimObject
*convertSwigSimObjectPtr(PyObject
*);
191 resolveSimObject(const string
&name
)
193 PyObject
*pyPtr
= PyEval_CallFunction(resolveFunc
, "(s)", name
.c_str());
196 panic("resolveSimObject: failure on call to Python for %s", name
);
199 SimObject
*simObj
= convertSwigSimObjectPtr(pyPtr
);
201 panic("resolveSimObject: failure on pointer conversion for %s", name
);
208 * Load config.ini into C++ database. Exported to Python via SWIG;
209 * invoked from m5.instantiate().
212 loadIniFile(PyObject
*_resolveFunc
)
214 resolveFunc
= _resolveFunc
;
215 configStream
= simout
.find("config.out");
217 // The configuration database is now complete; start processing it.
218 inifile
.load("config.ini");
220 // Initialize statistics database
221 Stats::InitSimStats();
226 * Look up a MemObject port. Helper function for connectPorts().
229 lookupPort(SimObject
*so
, const std::string
&name
, int i
)
231 MemObject
*mo
= dynamic_cast<MemObject
*>(so
);
233 warn("error casting SimObject %s to MemObject", so
->name());
237 Port
*p
= mo
->getPort(name
, i
);
239 warn("error looking up port %s on object %s", name
, so
->name());
245 * Connect the described MemObject ports. Called from Python via SWIG.
248 connectPorts(SimObject
*o1
, const std::string
&name1
, int i1
,
249 SimObject
*o2
, const std::string
&name2
, int i2
)
251 Port
*p1
= lookupPort(o1
, name1
, i1
);
252 Port
*p2
= lookupPort(o2
, name2
, i2
);
254 if (p1
== NULL
|| p2
== NULL
) {
255 warn("connectPorts: port lookup error");
266 * Do final initialization steps after object construction but before
267 * start of simulation.
272 // Parse and check all non-config-hierarchy parameters.
273 ParamContext::parseAllContexts(inifile
);
274 ParamContext::checkAllContexts();
276 // Echo all parameter settings to stats file as well.
277 ParamContext::showAllContexts(*configStream
);
279 // Do a second pass to finish initializing the sim objects
280 SimObject::initAll();
282 // Restore checkpointed state, if any.
284 configHierarchy
.unserializeSimObjects();
287 SimObject::regAllStats();
289 // Check to make sure that the stats package is properly initialized
292 // Reset to put the stats in a consistent state.
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.
305 simulate(Tick num_cycles
= -1)
307 warn("Entering event queue @ %d. Starting simulation...\n", curTick
);
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
);
318 num_cycles
= curTick
+ num_cycles
;
320 Event
*limit_event
= new SimLoopExitEvent(num_cycles
,
321 "simulate() limit reached");
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");
330 // forward current cycle to the time of the first event on the
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!");
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();
356 using namespace Stats
;
357 SetupEvent(Dump
, curTick
);
360 if (async_dumpreset
) {
361 async_dumpreset
= false;
363 using namespace Stats
;
364 SetupEvent(Dump
| Reset
, curTick
);
369 exitSimLoop("user interrupt received");
372 if (async_io
|| async_alarm
) {
380 // not reached... only exit is return on SimLoopExitEvent
386 return new CountedDrainEvent();
390 cleanupCountedDrain(Event
*counted_drain
)
392 CountedDrainEvent
*event
=
393 dynamic_cast<CountedDrainEvent
*>(counted_drain
);
395 fatal("Called cleanupCountedDrain() on an event that was not "
396 "a CountedDrainEvent.");
398 assert(event
->getCount() == 0);
403 serializeAll(const std::string
&cpt_dir
)
405 Serializable::serializeAll(cpt_dir
);
409 unserializeAll(const std::string
&cpt_dir
)
411 Serializable::unserializeAll(cpt_dir
);
415 * Queue of C++ callbacks to invoke on simulator exit.
417 CallbackQueue exitCallbacks
;
420 * Register an exit callback.
423 registerExitCallback(Callback
*callback
)
425 exitCallbacks
.add(callback
);
429 convertToBaseCPUPtr(SimObject
*obj
)
431 BaseCPU
*ptr
= dynamic_cast<BaseCPU
*>(obj
);
434 warn("Casting to BaseCPU pointer failed");
439 * Do C++ simulator exit processing. Exported to SWIG to be invoked
440 * when simulator terminates via Python's atexit mechanism.
445 exitCallbacks
.process();
446 exitCallbacks
.clear();
450 ParamContext::cleanupAllContexts();
452 // print simulation stats