main.cc revision 2768:5f23b83c8b0c
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/sim_events.hh" 66#include "sim/sim_exit.hh" 67#include "sim/sim_object.hh" 68#include "sim/stat_control.hh" 69#include "sim/stats.hh" 70#include "sim/root.hh" 71 72using namespace std; 73 74// See async.h. 75volatile bool async_event = false; 76volatile bool async_dump = false; 77volatile bool async_dumpreset = false; 78volatile bool async_exit = false; 79volatile bool async_io = false; 80volatile bool async_alarm = false; 81 82/// Stats signal handler. 83void 84dumpStatsHandler(int sigtype) 85{ 86 async_event = true; 87 async_dump = true; 88} 89 90void 91dumprstStatsHandler(int sigtype) 92{ 93 async_event = true; 94 async_dumpreset = true; 95} 96 97/// Exit signal handler. 98void 99exitNowHandler(int sigtype) 100{ 101 async_event = true; 102 async_exit = true; 103} 104 105/// Abort signal handler. 106void 107abortHandler(int sigtype) 108{ 109 cerr << "Program aborted at cycle " << curTick << endl; 110 111#if TRACING_ON 112 // dump trace buffer, if there is one 113 Trace::theLog.dump(cerr); 114#endif 115} 116 117/// Simulator executable name 118char *myProgName = ""; 119 120/// Show brief help message. 121void 122showBriefHelp(ostream &out) 123{ 124 char *prog = basename(myProgName); 125 126 ccprintf(out, "Usage:\n"); 127 ccprintf(out, 128"%s [-p <path>] [-i ] [-h] <config file>\n" 129"\n" 130" -p, --path <path> prepends <path> to PYTHONPATH instead of using\n" 131" built-in zip archive. Useful when developing/debugging\n" 132" changes to built-in Python libraries, as the new Python\n" 133" can be tested without building a new m5 binary.\n\n" 134" -i, --interactive forces entry into interactive mode after the supplied\n" 135" script is executed (just like the -i option to the\n" 136" Python interpreter).\n\n" 137" -h Prints this help\n\n" 138" <configfile> config file name which ends in .py. (Normally you can\n" 139" run <configfile> --help to get help on that config files\n" 140" parameters.\n\n", 141 prog); 142 143} 144 145const char *briefCopyright = 146"Copyright (c) 2001-2006\n" 147"The Regents of The University of Michigan\n" 148"All Rights Reserved\n"; 149 150/// Print welcome message. 151void 152sayHello(ostream &out) 153{ 154 extern const char *compileDate; // from date.cc 155 156 ccprintf(out, "M5 Simulator System\n"); 157 // display copyright 158 ccprintf(out, "%s\n", briefCopyright); 159 ccprintf(out, "M5 compiled %d\n", compileDate); 160 ccprintf(out, "M5 started %s\n", Time::start); 161 162 char *host = getenv("HOSTNAME"); 163 if (!host) 164 host = getenv("HOST"); 165 166 if (host) 167 ccprintf(out, "M5 executing on %s\n", host); 168} 169 170 171extern "C" { void init_main(); } 172 173int 174main(int argc, char **argv) 175{ 176 // Saze off program name 177 myProgName = argv[0]; 178 179 sayHello(cerr); 180 181 signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths 182 signal(SIGTRAP, SIG_IGN); 183 signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats 184 signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats 185 signal(SIGINT, exitNowHandler); // dump final stats and exit 186 signal(SIGABRT, abortHandler); 187 188 Py_SetProgramName(argv[0]); 189 190 // default path to m5 python code is the currently executing 191 // file... Python ZipImporter will find embedded zip archive 192 char *pythonpath = argv[0]; 193 194 bool interactive = false; 195 bool show_help = false; 196 bool getopt_done = false; 197 int opt_index = 0; 198 199 static struct option long_options[] = { 200 {"python", 1, 0, 'p'}, 201 {"interactive", 0, 0, 'i'}, 202 {"help", 0, 0, 'h'}, 203 {0,0,0,0} 204 }; 205 206 do { 207 switch (getopt_long(argc, argv, "+p:ih", long_options, &opt_index)) { 208 // -p <path> prepends <path> to PYTHONPATH instead of 209 // using built-in zip archive. Useful when 210 // developing/debugging changes to built-in Python 211 // libraries, as the new Python can be tested without 212 // building a new m5 binary. 213 case 'p': 214 pythonpath = optarg; 215 break; 216 217 // -i forces entry into interactive mode after the 218 // supplied script is executed (just like the -i option to 219 // the Python interpreter). 220 case 'i': 221 interactive = true; 222 break; 223 224 case 'h': 225 show_help = true; 226 break; 227 case -1: 228 getopt_done = true; 229 break; 230 231 default: 232 fatal("Unrecognized option %c\n", optopt); 233 } 234 } while (!getopt_done); 235 236 if (show_help) { 237 showBriefHelp(cerr); 238 exit(1); 239 } 240 241 // Fix up argc & argv to hide arguments we just processed. 242 // getopt() sets optind to the index of the first non-processed 243 // argv element. 244 argc -= optind; 245 argv += optind; 246 247 // Set up PYTHONPATH to make sure the m5 module is found 248 string newpath(pythonpath); 249 250 char *oldpath = getenv("PYTHONPATH"); 251 if (oldpath != NULL) { 252 newpath += ":"; 253 newpath += oldpath; 254 } 255 256 if (setenv("PYTHONPATH", newpath.c_str(), true) == -1) 257 fatal("setenv: %s\n", strerror(errno)); 258 259 // initialize embedded Python interpreter 260 Py_Initialize(); 261 PySys_SetArgv(argc, argv); 262 263 // initialize SWIG 'main' module 264 init_main(); 265 266 if (argc > 0) { 267 // extra arg(s): first is script file, remaining ones are args 268 // to script file 269 char *filename = argv[0]; 270 FILE *fp = fopen(filename, "r"); 271 if (!fp) { 272 fatal("cannot open file '%s'\n", filename); 273 } 274 275 PyRun_AnyFile(fp, filename); 276 } else { 277 // no script file argument... force interactive prompt 278 interactive = true; 279 } 280 281 if (interactive) { 282 // The following code to import readline was copied from Python 283 // 2.4.3's Modules/main.c. 284 // Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 285 // Python Software Foundation; All Rights Reserved 286 // We should only enable this if we're actually using an 287 // interactive prompt. 288 PyObject *v; 289 v = PyImport_ImportModule("readline"); 290 if (v == NULL) 291 PyErr_Clear(); 292 else 293 Py_DECREF(v); 294 295 PyRun_InteractiveLoop(stdin, "stdin"); 296 } 297 298 // clean up Python intepreter. 299 Py_Finalize(); 300} 301 302IniFile inifile; 303 304SimObject * 305createSimObject(const string &name) 306{ 307 return SimObjectClass::createObject(inifile, name); 308} 309 310 311/** 312 * Pointer to the Python function that maps names to SimObjects. 313 */ 314PyObject *resolveFunc = NULL; 315 316/** 317 * Convert a pointer to the Python object that SWIG wraps around a C++ 318 * SimObject pointer back to the actual C++ pointer. See main.i. 319 */ 320extern "C" SimObject *convertSwigSimObjectPtr(PyObject *); 321 322 323SimObject * 324resolveSimObject(const string &name) 325{ 326 PyObject *pyPtr = PyEval_CallFunction(resolveFunc, "(s)", name.c_str()); 327 if (pyPtr == NULL) { 328 PyErr_Print(); 329 panic("resolveSimObject: failure on call to Python for %s", name); 330 } 331 332 SimObject *simObj = convertSwigSimObjectPtr(pyPtr); 333 if (simObj == NULL) 334 panic("resolveSimObject: failure on pointer conversion for %s", name); 335 336 return simObj; 337} 338 339 340/** 341 * Load config.ini into C++ database. Exported to Python via SWIG; 342 * invoked from m5.instantiate(). 343 */ 344void 345loadIniFile(PyObject *_resolveFunc) 346{ 347 resolveFunc = _resolveFunc; 348 configStream = simout.find("config.out"); 349 350 // The configuration database is now complete; start processing it. 351 inifile.load("config.ini"); 352 353 // Initialize statistics database 354 Stats::InitSimStats(); 355} 356 357 358/** 359 * Look up a MemObject port. Helper function for connectPorts(). 360 */ 361Port * 362lookupPort(SimObject *so, const std::string &name, int i) 363{ 364 MemObject *mo = dynamic_cast<MemObject *>(so); 365 if (mo == NULL) { 366 warn("error casting SimObject %s to MemObject", so->name()); 367 return NULL; 368 } 369 370 Port *p = mo->getPort(name, i); 371 if (p == NULL) 372 warn("error looking up port %s on object %s", name, so->name()); 373 return p; 374} 375 376 377/** 378 * Connect the described MemObject ports. Called from Python via SWIG. 379 */ 380int 381connectPorts(SimObject *o1, const std::string &name1, int i1, 382 SimObject *o2, const std::string &name2, int i2) 383{ 384 Port *p1 = lookupPort(o1, name1, i1); 385 Port *p2 = lookupPort(o2, name2, i2); 386 387 if (p1 == NULL || p2 == NULL) { 388 warn("connectPorts: port lookup error"); 389 return 0; 390 } 391 392 p1->setPeer(p2); 393 p2->setPeer(p1); 394 395 return 1; 396} 397 398/** 399 * Do final initialization steps after object construction but before 400 * start of simulation. 401 */ 402void 403finalInit() 404{ 405 // Parse and check all non-config-hierarchy parameters. 406 ParamContext::parseAllContexts(inifile); 407 ParamContext::checkAllContexts(); 408 409 // Echo all parameter settings to stats file as well. 410 ParamContext::showAllContexts(*configStream); 411 412 // Do a second pass to finish initializing the sim objects 413 SimObject::initAll(); 414 415 // Restore checkpointed state, if any. 416#if 0 417 configHierarchy.unserializeSimObjects(); 418#endif 419 420 SimObject::regAllStats(); 421 422 // uncomment the following to get PC-based execution-time profile 423#ifdef DO_PROFILE 424 init_profile((char *)&_init, (char *)&_fini); 425#endif 426 427 // Check to make sure that the stats package is properly initialized 428 Stats::check(); 429 430 // Reset to put the stats in a consistent state. 431 Stats::reset(); 432 433 SimStartup(); 434} 435 436 437/** Simulate for num_cycles additional cycles. If num_cycles is -1 438 * (the default), do not limit simulation; some other event must 439 * terminate the loop. Exported to Python via SWIG. 440 * @return The SimLoopExitEvent that caused the loop to exit. 441 */ 442SimLoopExitEvent * 443simulate(Tick num_cycles = -1) 444{ 445 warn("Entering event queue @ %d. Starting simulation...\n", curTick); 446 447 // Fix up num_cycles. Special default value -1 means simulate 448 // "forever"... schedule event at MaxTick just to be safe. 449 // Otherwise it's a delta for additional cycles to simulate past 450 // curTick, and thus must be non-negative. 451 if (num_cycles == -1) 452 num_cycles = MaxTick; 453 else if (num_cycles < 0) 454 fatal("simulate: num_cycles must be >= 0 (was %d)\n", num_cycles); 455 else 456 num_cycles = curTick + num_cycles; 457 458 Event *limit_event = new SimLoopExitEvent(num_cycles, 459 "simulate() limit reached"); 460 461 while (1) { 462 // there should always be at least one event (the SimLoopExitEvent 463 // we just scheduled) in the queue 464 assert(!mainEventQueue.empty()); 465 assert(curTick <= mainEventQueue.nextTick() && 466 "event scheduled in the past"); 467 468 // forward current cycle to the time of the first event on the 469 // queue 470 curTick = mainEventQueue.nextTick(); 471 Event *exit_event = mainEventQueue.serviceOne(); 472 if (exit_event != NULL) { 473 // hit some kind of exit event; return to Python 474 // event must be subclass of SimLoopExitEvent... 475 SimLoopExitEvent *se_event = dynamic_cast<SimLoopExitEvent *>(exit_event); 476 if (se_event == NULL) 477 panic("Bogus exit event class!"); 478 479 // if we didn't hit limit_event, delete it 480 if (se_event != limit_event) { 481 assert(limit_event->scheduled()); 482 limit_event->deschedule(); 483 delete limit_event; 484 } 485 486 return se_event; 487 } 488 489 if (async_event) { 490 async_event = false; 491 if (async_dump) { 492 async_dump = false; 493 494 using namespace Stats; 495 SetupEvent(Dump, curTick); 496 } 497 498 if (async_dumpreset) { 499 async_dumpreset = false; 500 501 using namespace Stats; 502 SetupEvent(Dump | Reset, curTick); 503 } 504 505 if (async_exit) { 506 async_exit = false; 507 exitSimLoop("user interrupt received"); 508 } 509 510 if (async_io || async_alarm) { 511 async_io = false; 512 async_alarm = false; 513 pollQueue.service(); 514 } 515 } 516 } 517 518 // not reached... only exit is return on SimLoopExitEvent 519} 520 521/** 522 * Queue of C++ callbacks to invoke on simulator exit. 523 */ 524CallbackQueue exitCallbacks; 525 526/** 527 * Register an exit callback. 528 */ 529void 530registerExitCallback(Callback *callback) 531{ 532 exitCallbacks.add(callback); 533} 534 535/** 536 * Do C++ simulator exit processing. Exported to SWIG to be invoked 537 * when simulator terminates via Python's atexit mechanism. 538 */ 539void 540doExitCleanup() 541{ 542 exitCallbacks.process(); 543 exitCallbacks.clear(); 544 545 cout.flush(); 546 547 ParamContext::cleanupAllContexts(); 548 549 // print simulation stats 550 Stats::DumpNow(); 551} 552