main.cc revision 329
12817Sksewell@umich.edu/*
22817Sksewell@umich.edu * Copyright (c) 2003 The Regents of The University of Michigan
32817Sksewell@umich.edu * All rights reserved.
42817Sksewell@umich.edu *
52817Sksewell@umich.edu * Redistribution and use in source and binary forms, with or without
62817Sksewell@umich.edu * modification, are permitted provided that the following conditions are
72817Sksewell@umich.edu * met: redistributions of source code must retain the above copyright
82817Sksewell@umich.edu * notice, this list of conditions and the following disclaimer;
92817Sksewell@umich.edu * redistributions in binary form must reproduce the above copyright
102817Sksewell@umich.edu * notice, this list of conditions and the following disclaimer in the
112817Sksewell@umich.edu * documentation and/or other materials provided with the distribution;
122817Sksewell@umich.edu * neither the name of the copyright holders nor the names of its
132817Sksewell@umich.edu * contributors may be used to endorse or promote products derived from
142817Sksewell@umich.edu * this software without specific prior written permission.
152817Sksewell@umich.edu *
162817Sksewell@umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
172817Sksewell@umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
182817Sksewell@umich.edu * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
192817Sksewell@umich.edu * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
202817Sksewell@umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
212817Sksewell@umich.edu * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
222817Sksewell@umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
232817Sksewell@umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
242817Sksewell@umich.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
252817Sksewell@umich.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
262817Sksewell@umich.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
272817Sksewell@umich.edu */
282817Sksewell@umich.edu
292817Sksewell@umich.edu///
302817Sksewell@umich.edu/// @file sim/main.cc
312817Sksewell@umich.edu///
322817Sksewell@umich.edu#include <sys/types.h>
332817Sksewell@umich.edu#include <sys/stat.h>
342817Sksewell@umich.edu#include <stdlib.h>
352817Sksewell@umich.edu#include <signal.h>
362817Sksewell@umich.edu
372817Sksewell@umich.edu#include <string>
382817Sksewell@umich.edu#include <vector>
392817Sksewell@umich.edu
402817Sksewell@umich.edu#include "base/copyright.hh"
412817Sksewell@umich.edu#include "base/inifile.hh"
422817Sksewell@umich.edu#include "base/misc.hh"
432817Sksewell@umich.edu#include "base/pollevent.hh"
442817Sksewell@umich.edu#include "base/statistics.hh"
452817Sksewell@umich.edu#include "cpu/base_cpu.hh"
462817Sksewell@umich.edu#include "cpu/full_cpu/smt.hh"
472817Sksewell@umich.edu#include "sim/async.hh"
482817Sksewell@umich.edu#include "sim/builder.hh"
492817Sksewell@umich.edu#include "sim/configfile.hh"
502817Sksewell@umich.edu#include "sim/host.hh"
512817Sksewell@umich.edu#include "sim/sim_events.hh"
522817Sksewell@umich.edu#include "sim/sim_exit.hh"
532817Sksewell@umich.edu#include "sim/sim_object.hh"
542817Sksewell@umich.edu#include "sim/sim_stats.hh"
552935Sksewell@umich.edu#include "sim/sim_time.hh"
562935Sksewell@umich.edu
572935Sksewell@umich.eduusing namespace std;
582935Sksewell@umich.edu
592935Sksewell@umich.edu// See async.h.
602935Sksewell@umich.eduvolatile bool async_event = false;
612817Sksewell@umich.eduvolatile bool async_dump = false;
622935Sksewell@umich.eduvolatile bool async_dumpreset = false;
632817Sksewell@umich.eduvolatile bool async_exit = false;
642817Sksewell@umich.eduvolatile bool async_io = false;
652817Sksewell@umich.eduvolatile bool async_alarm = false;
662817Sksewell@umich.edu
672817Sksewell@umich.edu/// Stats signal handler.
682817Sksewell@umich.eduvoid
692817Sksewell@umich.edudumpStatsHandler(int sigtype)
702817Sksewell@umich.edu{
712817Sksewell@umich.edu    async_event = true;
722817Sksewell@umich.edu    async_dump = true;
732817Sksewell@umich.edu}
742817Sksewell@umich.edu
752817Sksewell@umich.eduvoid
762817Sksewell@umich.edudumprstStatsHandler(int sigtype)
772817Sksewell@umich.edu{
782817Sksewell@umich.edu    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(SIGPIPE, SIG_IGN);
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    // Nothing to simulate if we don't have at least one CPU somewhere.
394    if (BaseCPU::numSimulatedCPUs() == 0) {
395        cerr << "Fatal: no CPUs to simulate." << endl;
396        exit(1);
397    }
398
399    while (!mainEventQueue.empty()) {
400        assert(curTick <= mainEventQueue.nextTick() &&
401               "event scheduled in the past");
402
403        // forward current cycle to the time of the first event on the
404        // queue
405        curTick = mainEventQueue.nextTick();
406        mainEventQueue.serviceOne();
407
408        if (async_event) {
409            async_event = false;
410            if (async_dump) {
411                async_dump = false;
412
413                using namespace Statistics;
414                SetupEvent(Dump, curTick);
415            }
416
417            if (async_dumpreset) {
418                async_dumpreset = false;
419
420                using namespace Statistics;
421                SetupEvent(Dump | Reset, curTick);
422            }
423
424            if (async_exit) {
425                async_exit = false;
426                new SimExitEvent("User requested STOP");
427            }
428
429            if (async_io || async_alarm) {
430                async_io = false;
431                async_alarm = false;
432                pollQueue.service();
433            }
434        }
435    }
436
437    // This should never happen... every conceivable way for the
438    // simulation to terminate (hit max cycles/insts, signal,
439    // simulated system halts/exits) generates an exit event, so we
440    // should never run out of events on the queue.
441    exitNow("improperly exited event loop!", 1);
442
443    return 0;
444}
445