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