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