main.cc revision 146
1/*
2 * Copyright (c) 2003 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 <stdlib.h>
35#include <signal.h>
36
37#include <string>
38#include <vector>
39
40#include "base/copyright.hh"
41#include "base/inifile.hh"
42#include "base/misc.hh"
43#include "base/pollevent.hh"
44#include "base/statistics.hh"
45#include "cpu/base_cpu.hh"
46#include "cpu/full_cpu/smt.hh"
47#include "sim/async.hh"
48#include "sim/builder.hh"
49#include "sim/configfile.hh"
50#include "sim/host.hh"
51#include "sim/sim_events.hh"
52#include "sim/sim_exit.hh"
53#include "sim/sim_object.hh"
54#include "sim/sim_stats.hh"
55#include "sim/sim_time.hh"
56
57using namespace std;
58
59// See async.h.
60volatile bool async_event = false;
61volatile bool async_dump = false;
62volatile bool async_exit = false;
63volatile bool async_io = false;
64volatile bool async_alarm = false;
65
66/// Stats signal handler.
67void
68dumpStatsHandler(int sigtype)
69{
70    async_event = true;
71    async_dump = true;
72}
73
74/// Exit signal handler.
75void
76exitNowHandler(int sigtype)
77{
78    async_event = true;
79    async_exit = true;
80}
81
82/// Simulator executable name
83const char *myProgName = "";
84
85/// Show brief help message.
86static void
87showBriefHelp(ostream &out)
88{
89    out << "Usage: " << myProgName
90         << " [-hn] [-Dname[=def]] [-Uname] [-I[dir]] "
91         << "[--<section>:<param>=<value>] [<config file> ...]" << endl
92         << "   -h: print long help (including parameter listing)" << endl
93         << "   -n: don't load default.ini" << endl
94         << "   -u: don't quit on unreferenced parameters" << endl
95         << "   -D,-U,-I: passed to cpp for preprocessing .ini files" << endl;
96}
97
98/// Show verbose help message.  Includes parameter listing from
99/// showBriefHelp(), plus an exhaustive list of ini-file parameters
100/// and SimObjects (with their parameters).
101static void
102showLongHelp(ostream &out)
103{
104    showBriefHelp(out);
105
106    out << endl
107        << endl
108        << "-----------------" << endl
109        << "Global Parameters" << endl
110        << "-----------------" << endl
111        << endl;
112
113    ParamContext::describeAllContexts(out);
114
115    out << endl
116        << endl
117        << "-----------------" << endl
118        << "Simulator Objects" << endl
119        << "-----------------" << endl
120        << endl;
121
122    SimObjectClass::describeAllClasses(out);
123}
124
125/// Print welcome message.
126static void
127sayHello(ostream &out)
128{
129    extern const char *compileDate;	// from date.cc
130
131    ccprintf(out, "M5 Simulator System\n");
132    // display copyright
133    ccprintf(out, "%s\n", briefCopyright);
134    ccprintf(out, "M5 compiled on %d\n", compileDate);
135
136    char *host = getenv("HOSTNAME");
137    if (!host)
138        host = getenv("HOST");
139
140    if (host)
141        ccprintf(out, "M5 executing on %s\n", host);
142
143    ccprintf(out, "M5 simulation started %s\n", Time::start);
144}
145
146///
147/// Echo the command line for posterity in such a way that it can be
148/// used to rerun the same simulation (given the same .ini files).
149///
150static void
151echoCommandLine(int argc, char **argv, ostream &out)
152{
153    out << "command line: " << argv[0];
154    for (int i = 1; i < argc; i++) {
155        string arg(argv[i]);
156
157        out << ' ';
158
159        // If the arg contains spaces, we need to quote it.
160        // The rest of this is overkill to make it look purty.
161
162        // print dashes first outside quotes
163        int non_dash_pos = arg.find_first_not_of("-");
164        out << arg.substr(0, non_dash_pos);	// print dashes
165        string body = arg.substr(non_dash_pos);	// the rest
166
167        // if it's an assignment, handle the lhs & rhs separately
168        int eq_pos = body.find("=");
169        if (eq_pos == string::npos) {
170            out << quote(body);
171        }
172        else {
173            string lhs(body.substr(0, eq_pos));
174            string rhs(body.substr(eq_pos + 1));
175
176            out << quote(lhs) << "=" << quote(rhs);
177        }
178    }
179    out << endl << endl;
180}
181
182
183///
184/// The simulator configuration database.  This is the union of all
185/// specified .ini files.  This shouldn't need to be visible outside
186/// this file, as it is passed as a parameter to all the param-parsing
187/// routines.
188///
189static IniFile simConfigDB;
190
191/// Check for a default.ini file and load it if necessary.
192static void
193handleDefaultIni(bool &loadIt, vector<char *> &cppArgs)
194{
195    struct stat sb;
196
197    if (loadIt) {
198        if (stat("default.ini", &sb) == 0) {
199            if (!simConfigDB.loadCPP("default.ini", cppArgs)) {
200                cout << "Error processing file default.ini" << endl;
201                exit(1);
202            }
203        }
204
205        // set this whether it actually was found or not, so we don't
206        // bother to check again next time
207        loadIt = false;
208    }
209}
210
211
212/// M5 entry point.
213int
214main(int argc, char **argv)
215{
216    // Save off program name
217    myProgName = argv[0];
218
219    signal(SIGFPE, SIG_IGN);		// may occur on misspeculated paths
220    signal(SIGPIPE, SIG_IGN);
221    signal(SIGTRAP, SIG_IGN);
222    signal(SIGUSR1, dumpStatsHandler);	// dump intermediate stats
223    signal(SIGINT, exitNowHandler);	// dump final stats and exit
224
225    sayHello(cerr);
226
227    // Initialize statistics database
228    initBaseStats();
229
230    vector<char *> cppArgs;
231
232    // Should we use default.ini if it exists?  By default, yes.  (Use
233    // -n to override.)
234    bool loadDefaultIni = true;
235
236    // Should we quit if there are unreferenced parameters?  By
237    // default, yes... it's a good way of catching typos in
238    // section/parameter names (which otherwise go by silently).  Use
239    // -u to override.
240    bool quitOnUnreferenced = true;
241
242    // Parse command-line options.  The tricky part here is figuring
243    // out whether to look for & load default.ini, and if needed,
244    // doing so at the right time w.r.t. processing the other
245    // parameters.
246    //
247    // Since most of the complex options are handled through the
248    // config database, we don't mess with getopts, and just parse
249    // manually.
250    for (int i = 1; i < argc; ++i) {
251        char *arg_str = argv[i];
252
253        // if arg starts with '-', parse as option,
254        // else treat it as a configuration file name and load it
255        if (arg_str[0] == '-') {
256
257            // switch on second char
258            switch (arg_str[1]) {
259              case 'h':
260                // -h: show help
261                showLongHelp(cerr);
262                exit(1);
263
264              case 'n':
265                // -n: don't load default.ini
266                if (!loadDefaultIni) {
267                    cerr << "Warning: -n option needs to precede any "
268                         << "explicit configuration file name " << endl
269                         << "         or command-line configuration parameter."
270                         << endl;
271                }
272                loadDefaultIni = false;
273                break;
274
275              case 'u':
276                // -u: don't quit on unreferenced parameters
277                quitOnUnreferenced = false;
278                break;
279
280              case 'D':
281              case 'U':
282              case 'I':
283                // cpp options: record & pass to cpp.  Note that these
284                // cannot have spaces, i.e., '-Dname=val' is OK, but
285                // '-D name=val' is not.  I don't consider this a
286                // problem, since even though gnu cpp accepts the
287                // latter, other cpp implementations do not (Tru64,
288                // for one).
289                cppArgs.push_back(arg_str);
290                break;
291
292              case '-':
293                // command-line configuration parameter:
294                // '--<section>:<parameter>=<value>'
295
296                // Load default.ini if necessary -- see comment in
297                // else clause below.
298                handleDefaultIni(loadDefaultIni, cppArgs);
299
300                if (!simConfigDB.add(arg_str + 2)) {
301                    // parse error
302                    ccprintf(cerr,
303                             "Could not parse configuration argument '%s'\n"
304                             "Expecting --<section>:<parameter>=<value>\n",
305                             arg_str);
306                    exit(0);
307                }
308                break;
309
310              default:
311                showBriefHelp(cerr);
312                ccprintf(cerr, "Fatal: invalid argument '%s'\n", arg_str);
313                exit(0);
314            }
315        }
316        else {
317            // no '-', treat as config file name
318
319            // If we haven't loaded default.ini yet, and we want to,
320            // now is the time.  Can't do it sooner because we need to
321            // look for '-n', can't do it later since we want
322            // default.ini loaded first (so that any other settings
323            // override it).
324            handleDefaultIni(loadDefaultIni, cppArgs);
325
326            if (!simConfigDB.loadCPP(arg_str, cppArgs)) {
327                cprintf("Error processing file %s\n", arg_str);
328                exit(1);
329            }
330        }
331    }
332
333    // Final check for default.ini, in case no config files or
334    // command-line config parameters were given.
335    handleDefaultIni(loadDefaultIni, cppArgs);
336
337    // The configuration database is now complete; start processing it.
338
339    // Parse and check all non-config-hierarchy parameters.
340    ParamContext::parseAllContexts(simConfigDB);
341    ParamContext::checkAllContexts();
342
343    // Print header info into stats file.  Can't do this sooner since
344    // the stat file name is set via a .ini param... thus it just got
345    // opened above during ParamContext::checkAllContexts().
346
347    // Print hello message to stats file if it's actually a file.  If
348    // it's not (i.e. it's cout or cerr) then we already did it above.
349    if (statStreamIsFile)
350        sayHello(*statStream);
351
352    // Echo command line and all parameter settings to stats file as well.
353    echoCommandLine(argc, argv, *statStream);
354    ParamContext::showAllContexts(*statStream);
355
356    // Now process the configuration hierarchy and create the SimObjects.
357    ConfigHierarchy configHierarchy(simConfigDB);
358    configHierarchy.build();
359    configHierarchy.createSimObjects();
360
361    // Restore checkpointed state, if any.
362    configHierarchy.unserializeSimObjects();
363
364    // Done processing the configuration database.
365    // Check for unreferenced entries.
366    if (simConfigDB.printUnreferenced() && quitOnUnreferenced) {
367        cerr << "Fatal: unreferenced .ini sections/entries." << endl
368             << "If this is not an error, add 'unref_section_ok=y' or "
369             << "'unref_entries_ok=y' to the appropriate sections "
370             << "to suppress this message." << endl;
371        exit(1);
372    }
373
374    SimObject::regAllStats();
375
376    // uncomment the following to get PC-based execution-time profile
377#ifdef DO_PROFILE
378    init_profile((char *)&_init, (char *)&_fini);
379#endif
380
381    // Check to make sure that the stats package is properly initialized
382    Statistics::check();
383
384    // Nothing to simulate if we don't have at least one CPU somewhere.
385    if (BaseCPU::numSimulatedCPUs() == 0) {
386        cerr << "Fatal: no CPUs to simulate." << endl;
387        exit(1);
388    }
389
390    while (!mainEventQueue.empty()) {
391        assert(curTick <= mainEventQueue.nextTick() &&
392               "event scheduled in the past");
393
394        // forward current cycle to the time of the first event on the
395        // queue
396        curTick = mainEventQueue.nextTick();
397        mainEventQueue.serviceOne();
398
399        if (async_event) {
400            async_event = false;
401            if (async_dump) {
402                async_dump = false;
403                new DumpStatsEvent();
404            }
405
406            if (async_exit) {
407                async_exit = false;
408                new SimExitEvent("User requested STOP");
409            }
410
411            if (async_io || async_alarm) {
412                async_io = false;
413                async_alarm = false;
414                pollQueue.service();
415            }
416        }
417    }
418
419    // This should never happen... every conceivable way for the
420    // simulation to terminate (hit max cycles/insts, signal,
421    // simulated system halts/exits) generates an exit event, so we
422    // should never run out of events on the queue.
423    exitNow("improperly exited event loop!", 1);
424
425    return 0;
426}
427