main.cc revision 1717
1/*
2 * Copyright (c) 2000-2004 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
29///
30/// @file sim/main.cc
31///
32#include <sys/types.h>
33#include <sys/stat.h>
34#include <errno.h>
35#include <libgen.h>
36#include <stdlib.h>
37#include <signal.h>
38
39#include <list>
40#include <string>
41#include <vector>
42
43#include "base/copyright.hh"
44#include "base/embedfile.hh"
45#include "base/inifile.hh"
46#include "base/misc.hh"
47#include "base/output.hh"
48#include "base/pollevent.hh"
49#include "base/statistics.hh"
50#include "base/str.hh"
51#include "base/time.hh"
52#include "cpu/base.hh"
53#include "cpu/smt.hh"
54#include "python/pyconfig.hh"
55#include "sim/async.hh"
56#include "sim/builder.hh"
57#include "sim/configfile.hh"
58#include "sim/host.hh"
59#include "sim/sim_events.hh"
60#include "sim/sim_exit.hh"
61#include "sim/sim_object.hh"
62#include "sim/stat_control.hh"
63#include "sim/stats.hh"
64#include "sim/root.hh"
65
66using namespace std;
67
68// See async.h.
69volatile bool async_event = false;
70volatile bool async_dump = false;
71volatile bool async_dumpreset = false;
72volatile bool async_exit = false;
73volatile bool async_io = false;
74volatile bool async_alarm = false;
75
76/// Stats signal handler.
77void
78dumpStatsHandler(int sigtype)
79{
80    async_event = true;
81    async_dump = true;
82}
83
84void
85dumprstStatsHandler(int sigtype)
86{
87    async_event = true;
88    async_dumpreset = true;
89}
90
91/// Exit signal handler.
92void
93exitNowHandler(int sigtype)
94{
95    async_event = true;
96    async_exit = true;
97}
98
99/// Abort signal handler.
100void
101abortHandler(int sigtype)
102{
103    cerr << "Program aborted at cycle " << curTick << endl;
104
105#if TRACING_ON
106    // dump trace buffer, if there is one
107    Trace::theLog.dump(cerr);
108#endif
109}
110
111/// Simulator executable name
112char *myProgName = "";
113
114/// Show brief help message.
115void
116showBriefHelp(ostream &out)
117{
118    char *prog = basename(myProgName);
119
120    ccprintf(out, "Usage:\n");
121    ccprintf(out,
122"%s [-d <dir>] [-E <var>[=<val>]] [-I <dir>] [-P <python>]\n"
123"        [--<var>=<val>] <config file>\n"
124"\n"
125"   -d            set the output directory to <dir>\n"
126"   -E            set the environment variable <var> to <val> (or 'True')\n"
127"   -I            add the directory <dir> to python's path\n"
128"   -P            execute <python> directly in the configuration\n"
129"   --var=val     set the python variable <var> to '<val>'\n"
130"   <configfile>  config file name (ends in .py)\n\n",
131             prog);
132
133    ccprintf(out, "%s -X\n   -X            extract embedded files\n\n", prog);
134    ccprintf(out, "%s -h\n   -h            print short help\n\n", prog);
135    ccprintf(out, "%s -H\n   -H            print long help\n\n", prog);
136}
137
138/// Show verbose help message.  Includes parameter listing from
139/// showBriefHelp(), plus an exhaustive list of ini-file parameters
140/// and SimObjects (with their parameters).
141void
142showLongHelp(ostream &out)
143{
144    showBriefHelp(out);
145
146    out << endl
147        << endl
148        << "-----------------" << endl
149        << "Global Parameters" << endl
150        << "-----------------" << endl
151        << endl;
152
153    ParamContext::describeAllContexts(out);
154
155    out << endl
156        << endl
157        << "-----------------" << endl
158        << "Simulator Objects" << endl
159        << "-----------------" << endl
160        << endl;
161
162    SimObjectClass::describeAllClasses(out);
163}
164
165/// Print welcome message.
166void
167sayHello(ostream &out)
168{
169    extern const char *compileDate;	// from date.cc
170
171    ccprintf(out, "M5 Simulator System\n");
172    // display copyright
173    ccprintf(out, "%s\n", briefCopyright);
174    ccprintf(out, "M5 compiled on %d\n", compileDate);
175
176    char *host = getenv("HOSTNAME");
177    if (!host)
178        host = getenv("HOST");
179
180    if (host)
181        ccprintf(out, "M5 executing on %s\n", host);
182
183    ccprintf(out, "M5 simulation started %s\n", Time::start);
184}
185
186///
187/// Echo the command line for posterity in such a way that it can be
188/// used to rerun the same simulation (given the same .ini files).
189///
190void
191echoCommandLine(int argc, char **argv, ostream &out)
192{
193    out << "command line: " << argv[0];
194    for (int i = 1; i < argc; i++) {
195        string arg(argv[i]);
196
197        out << ' ';
198
199        // If the arg contains spaces, we need to quote it.
200        // The rest of this is overkill to make it look purty.
201
202        // print dashes first outside quotes
203        int non_dash_pos = arg.find_first_not_of("-");
204        out << arg.substr(0, non_dash_pos);	// print dashes
205        string body = arg.substr(non_dash_pos);	// the rest
206
207        // if it's an assignment, handle the lhs & rhs separately
208        int eq_pos = body.find("=");
209        if (eq_pos == string::npos) {
210            out << quote(body);
211        }
212        else {
213            string lhs(body.substr(0, eq_pos));
214            string rhs(body.substr(eq_pos + 1));
215
216            out << quote(lhs) << "=" << quote(rhs);
217        }
218    }
219    out << endl << endl;
220}
221
222char *
223getOptionString(int &index, int argc, char **argv)
224{
225    char *option = argv[index] + 2;
226    if (*option != '\0')
227        return option;
228
229    // We didn't find an argument, it must be in the next variable.
230    if (++index >= argc)
231        panic("option string for option '%s' not found", argv[index - 1]);
232
233    return argv[index];
234}
235
236int
237main(int argc, char **argv)
238{
239    // Save off program name
240    myProgName = argv[0];
241
242    signal(SIGFPE, SIG_IGN);		// may occur on misspeculated paths
243    signal(SIGTRAP, SIG_IGN);
244    signal(SIGUSR1, dumpStatsHandler);		// dump intermediate stats
245    signal(SIGUSR2, dumprstStatsHandler);	// dump and reset stats
246    signal(SIGINT, exitNowHandler);		// dump final stats and exit
247    signal(SIGABRT, abortHandler);
248
249    bool configfile_found = false;
250    PythonConfig pyconfig;
251    string outdir;
252
253    if (argc < 2) {
254        showBriefHelp(cerr);
255        exit(1);
256    }
257
258    sayHello(cerr);
259
260    // Parse command-line options.
261    // Since most of the complex options are handled through the
262    // config database, we don't mess with getopts, and just parse
263    // manually.
264    for (int i = 1; i < argc; ++i) {
265        char *arg_str = argv[i];
266
267        // if arg starts with '--', parse as a special python option
268        // of the format --<python var>=<string value>, if the arg
269        // starts with '-', it should be a simulator option with a
270        // format similar to getopt.  In any other case, treat the
271        // option as a configuration file name and load it.
272        if (arg_str[0] == '-' && arg_str[1] == '-') {
273            string str = &arg_str[2];
274            string var, val;
275
276            if (!split_first(str, var, val, '='))
277                panic("Could not parse configuration argument '%s'\n"
278                      "Expecting --<variable>=<value>\n", arg_str);
279
280            pyconfig.setVariable(var, val);
281        } else if (arg_str[0] == '-') {
282            char *option;
283            string var, val;
284
285            // switch on second char
286            switch (arg_str[1]) {
287              case 'd':
288                outdir = getOptionString(i, argc, argv);
289                break;
290
291              case 'h':
292                showBriefHelp(cerr);
293                exit(1);
294
295              case 'H':
296                showLongHelp(cerr);
297                exit(1);
298
299              case 'E':
300                option = getOptionString(i, argc, argv);
301                if (!split_first(option, var, val, '='))
302                    val = "True";
303
304                if (setenv(var.c_str(), val.c_str(), true) == -1)
305                    panic("setenv: %s\n", strerror(errno));
306                break;
307
308              case 'I':
309                option = getOptionString(i, argc, argv);
310                pyconfig.addPath(option);
311                break;
312
313              case 'P':
314                option = getOptionString(i, argc, argv);
315                pyconfig.writeLine(option);
316                break;
317
318              case 'X': {
319                  list<EmbedFile> lst;
320                  EmbedMap::all(lst);
321                  list<EmbedFile>::iterator i = lst.begin();
322                  list<EmbedFile>::iterator end = lst.end();
323
324                  while (i != end) {
325                      cprintf("Embedded File: %s\n", i->name);
326                      cout.write(i->data, i->length);
327                      ++i;
328                  }
329
330                  return 0;
331              }
332
333              default:
334                showBriefHelp(cerr);
335                panic("invalid argument '%s'\n", arg_str);
336            }
337        } else {
338            string file(arg_str);
339            string base, ext;
340
341            if (!split_last(file, base, ext, '.') || ext != "py")
342                panic("Config file '%s' must end in '.py'\n", file);
343
344            pyconfig.load(file);
345            configfile_found = true;
346        }
347    }
348
349    if (outdir.empty()) {
350        char *env = getenv("OUTPUT_DIR");
351        outdir = env ? env : ".";
352    }
353
354    simout.setDirectory(outdir);
355
356    char *env = getenv("CONFIG_OUTPUT");
357    if (!env)
358        env = "config.out";
359    configStream = simout.find(env);
360
361    if (!configfile_found)
362        panic("no configuration file specified!");
363
364    // The configuration database is now complete; start processing it.
365    IniFile inifile;
366    if (!pyconfig.output(inifile))
367        panic("Error processing python code");
368
369    // Initialize statistics database
370    Stats::InitSimStats();
371
372    // Now process the configuration hierarchy and create the SimObjects.
373    ConfigHierarchy configHierarchy(inifile);
374    configHierarchy.build();
375    configHierarchy.createSimObjects();
376
377    // Parse and check all non-config-hierarchy parameters.
378    ParamContext::parseAllContexts(inifile);
379    ParamContext::checkAllContexts();
380
381    // Print hello message to stats file if it's actually a file.  If
382    // it's not (i.e. it's cout or cerr) then we already did it above.
383    if (simout.isFile(*outputStream))
384        sayHello(*outputStream);
385
386    // Echo command line and all parameter settings to stats file as well.
387    echoCommandLine(argc, argv, *outputStream);
388    ParamContext::showAllContexts(*configStream);
389
390    // Do a second pass to finish initializing the sim objects
391    SimObject::initAll();
392
393    // Restore checkpointed state, if any.
394    configHierarchy.unserializeSimObjects();
395
396    // Done processing the configuration database.
397    // Check for unreferenced entries.
398    if (inifile.printUnreferenced())
399        panic("unreferenced sections/entries in the intermediate ini file");
400
401    SimObject::regAllStats();
402
403    // uncomment the following to get PC-based execution-time profile
404#ifdef DO_PROFILE
405    init_profile((char *)&_init, (char *)&_fini);
406#endif
407
408    // Check to make sure that the stats package is properly initialized
409    Stats::check();
410
411    // Reset to put the stats in a consistent state.
412    Stats::reset();
413
414    warn("Entering event queue.  Starting simulation...\n");
415    SimStartup();
416    while (!mainEventQueue.empty()) {
417        assert(curTick <= mainEventQueue.nextTick() &&
418               "event scheduled in the past");
419
420        // forward current cycle to the time of the first event on the
421        // queue
422        curTick = mainEventQueue.nextTick();
423        mainEventQueue.serviceOne();
424
425        if (async_event) {
426            async_event = false;
427            if (async_dump) {
428                async_dump = false;
429
430                using namespace Stats;
431                SetupEvent(Dump, curTick);
432            }
433
434            if (async_dumpreset) {
435                async_dumpreset = false;
436
437                using namespace Stats;
438                SetupEvent(Dump | Reset, curTick);
439            }
440
441            if (async_exit) {
442                async_exit = false;
443                new SimExitEvent("User requested STOP");
444            }
445
446            if (async_io || async_alarm) {
447                async_io = false;
448                async_alarm = false;
449                pollQueue.service();
450            }
451        }
452    }
453
454    // This should never happen... every conceivable way for the
455    // simulation to terminate (hit max cycles/insts, signal,
456    // simulated system halts/exits) generates an exit event, so we
457    // should never run out of events on the queue.
458    exitNow("no events on event loop!  All CPUs must be idle.", 1);
459
460    return 0;
461}
462