1/*
2 * Copyright (c) 2014 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are
16 * met: redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer;
18 * redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution;
21 * neither the name of the copyright holders nor the names of its
22 * contributors may be used to endorse or promote products derived from
23 * this software without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 *
37 * Authors: Andrew Bardsley
38 */
39
40/**
41 * @file
42 *
43 *  C++-only configuration and instantiation support.  This allows a
44 *  config to be read back from a .ini and instantiated without
45 *  Python.  Useful if you want to embed gem5 within a larger system
46 *  without carrying the integration cost of the fully-featured
47 *  configuration system.
48 *
49 *  This file contains a demonstration main using CxxConfigManager.
50 *  Build with something like:
51 *
52 *      scons --without-python build/ARM/libgem5_opt.so
53 *
54 *      g++ -DTRACING_ON -std=c++0x -Ibuild/ARM src/sim/cxx_main.cc \
55 *          -o gem5cxx.opt -Lbuild/ARM -lgem5_opt
56 */
57
58#include <cstdlib>
59#include <iostream>
60#include <sstream>
61
62#include "base/inifile.hh"
63#include "base/statistics.hh"
64#include "base/str.hh"
65#include "base/trace.hh"
66#include "cpu/base.hh"
67#include "sim/cxx_config_ini.hh"
68#include "sim/cxx_manager.hh"
69#include "sim/init_signals.hh"
70#include "sim/serialize.hh"
71#include "sim/sim_events.hh"
72#include "sim/simulate.hh"
73#include "sim/stat_control.hh"
74#include "sim/system.hh"
75#include "stats.hh"
76
77void
78usage(const std::string &prog_name)
79{
80    std::cerr << "Usage: " << prog_name << (
81        " <config-file.ini> [ <option> ]\n\n"
82        "OPTIONS:\n"
83        "    -p <object> <param> <value>  -- set a parameter\n"
84        "    -v <object> <param> <values> -- set a vector parameter from"
85        " a comma\n"
86        "                                    separated values string\n"
87        "    -d <flag>                    -- set a debug flag (-<flag>\n"
88        "                                    clear a flag)\n"
89        "    -s <dir> <ticks>             -- save checkpoint to dir after"
90        " the given\n"
91        "                                    number of ticks\n"
92        "    -r <dir>                     -- restore checkpoint from dir\n"
93        "    -c <from> <to> <ticks>       -- switch from cpu 'from' to cpu"
94        " 'to' after\n"
95        "                                    the given number of ticks\n"
96        "\n"
97        );
98
99    std::exit(EXIT_FAILURE);
100}
101
102int
103main(int argc, char **argv)
104{
105    std::string prog_name(argv[0]);
106    unsigned int arg_ptr = 1;
107
108    if (argc == 1)
109        usage(prog_name);
110
111    cxxConfigInit();
112
113    initSignals();
114
115    setClockFrequency(1000000000000);
116    curEventQueue(getEventQueue(0));
117
118    Stats::initSimStats();
119    Stats::registerHandlers(CxxConfig::statsReset, CxxConfig::statsDump);
120
121    Trace::enable();
122    setDebugFlag("Terminal");
123    // setDebugFlag("CxxConfig");
124
125    const std::string config_file(argv[arg_ptr]);
126
127    CxxConfigFileBase *conf = new CxxIniFile();
128
129    if (!conf->load(config_file.c_str())) {
130        std::cerr << "Can't open config file: " << config_file << '\n';
131        return EXIT_FAILURE;
132    }
133    arg_ptr++;
134
135    CxxConfigManager *config_manager = new CxxConfigManager(*conf);
136
137    bool checkpoint_restore = false;
138    bool checkpoint_save = false;
139    bool switch_cpus = false;
140    std::string checkpoint_dir = "";
141    std::string from_cpu = "";
142    std::string to_cpu = "";
143    Tick pre_run_time = 1000000;
144    Tick pre_switch_time = 1000000;
145
146    try {
147        while (arg_ptr < argc) {
148            std::string option(argv[arg_ptr]);
149            arg_ptr++;
150            unsigned num_args = argc - arg_ptr;
151
152            if (option == "-p") {
153                if (num_args < 3)
154                    usage(prog_name);
155                config_manager->setParam(argv[arg_ptr], argv[arg_ptr + 1],
156                    argv[arg_ptr + 2]);
157                arg_ptr += 3;
158            } else if (option == "-v") {
159                std::vector<std::string> values;
160
161                if (num_args < 3)
162                    usage(prog_name);
163                tokenize(values, argv[arg_ptr + 2], ',');
164                config_manager->setParamVector(argv[arg_ptr],
165                    argv[arg_ptr + 1], values);
166                arg_ptr += 3;
167            } else if (option == "-d") {
168                if (num_args < 1)
169                    usage(prog_name);
170                if (argv[arg_ptr][0] == '-')
171                    clearDebugFlag(argv[arg_ptr] + 1);
172                else
173                    setDebugFlag(argv[arg_ptr]);
174                arg_ptr++;
175            } else if (option == "-r") {
176                if (num_args < 1)
177                    usage(prog_name);
178                checkpoint_dir = argv[arg_ptr];
179                checkpoint_restore = true;
180                arg_ptr++;
181            } else if (option == "-s") {
182                if (num_args < 2)
183                    usage(prog_name);
184                checkpoint_dir = argv[arg_ptr];
185                std::istringstream(argv[arg_ptr + 1]) >> pre_run_time;
186                checkpoint_save = true;
187                arg_ptr += 2;
188            } else if (option == "-c") {
189                if (num_args < 3)
190                    usage(prog_name);
191                switch_cpus = true;
192                from_cpu = argv[arg_ptr];
193                to_cpu = argv[arg_ptr + 1];
194                std::istringstream(argv[arg_ptr + 2]) >> pre_switch_time;
195                arg_ptr += 3;
196            } else {
197                usage(prog_name);
198            }
199        }
200    } catch (CxxConfigManager::Exception &e) {
201        std::cerr << e.name << ": " << e.message << "\n";
202        return EXIT_FAILURE;
203    }
204
205    if (checkpoint_save && checkpoint_restore) {
206        std::cerr << "Don't try and save and restore a checkpoint in the"
207            " same run\n";
208        return EXIT_FAILURE;
209    }
210
211    CxxConfig::statsEnable();
212    getEventQueue(0)->dump();
213
214    try {
215        config_manager->instantiate();
216        if (!checkpoint_restore) {
217            config_manager->initState();
218            config_manager->startup();
219        }
220    } catch (CxxConfigManager::Exception &e) {
221        std::cerr << "Config problem in sim object " << e.name
222            << ": " << e.message << "\n";
223
224        return EXIT_FAILURE;
225    }
226
227    GlobalSimLoopExitEvent *exit_event = NULL;
228
229    if (checkpoint_save) {
230        exit_event = simulate(pre_run_time);
231
232        unsigned int drain_count = 1;
233        do {
234            drain_count = config_manager->drain();
235
236            std::cerr << "Draining " << drain_count << '\n';
237
238            if (drain_count > 0) {
239                exit_event = simulate();
240            }
241        } while (drain_count > 0);
242
243        std::cerr << "Simulation stop at tick " << curTick()
244            << ", cause: " << exit_event->getCause() << '\n';
245
246        std::cerr << "Checkpointing\n";
247
248        /* FIXME, this should really be serialising just for
249         *  config_manager rather than using serializeAll's ugly
250         *  SimObject static object list */
251        Serializable::serializeAll(checkpoint_dir);
252
253        std::cerr << "Completed checkpoint\n";
254
255        config_manager->drainResume();
256    }
257
258    if (checkpoint_restore) {
259        std::cerr << "Restoring checkpoint\n";
260
261        CheckpointIn *checkpoint = new CheckpointIn(checkpoint_dir,
262            config_manager->getSimObjectResolver());
263
264        DrainManager::instance().preCheckpointRestore();
265        Serializable::unserializeGlobals(*checkpoint);
266        config_manager->loadState(*checkpoint);
267        config_manager->startup();
268
269        config_manager->drainResume();
270
271        std::cerr << "Restored from checkpoint\n";
272    }
273
274    if (switch_cpus) {
275        exit_event = simulate(pre_switch_time);
276
277        std::cerr << "Switching CPU\n";
278
279        /* Assume the system is called system */
280        System &system = config_manager->getObject<System>("system");
281        BaseCPU &old_cpu = config_manager->getObject<BaseCPU>(from_cpu);
282        BaseCPU &new_cpu = config_manager->getObject<BaseCPU>(to_cpu);
283
284        unsigned int drain_count = 1;
285        do {
286            drain_count = config_manager->drain();
287
288            std::cerr << "Draining " << drain_count << '\n';
289
290            if (drain_count > 0) {
291                exit_event = simulate();
292            }
293        } while (drain_count > 0);
294
295        old_cpu.switchOut();
296        system.setMemoryMode(Enums::timing);
297        new_cpu.takeOverFrom(&old_cpu);
298        config_manager->drainResume();
299
300        std::cerr << "Switched CPU\n";
301    }
302
303    exit_event = simulate();
304
305    std::cerr << "Exit at tick " << curTick()
306        << ", cause: " << exit_event->getCause() << '\n';
307
308    getEventQueue(0)->dump();
309
310#if TRY_CLEAN_DELETE
311    config_manager->deleteObjects();
312#endif
313
314    delete config_manager;
315
316    return EXIT_SUCCESS;
317}
318