1/*
2 * Copyright (c) 2011, 2017 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 * Copyright (c) 2003-2005 The Regents of The University of Michigan
15 * All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * Authors: Nathan Binkert
41 */
42
43#ifdef linux
44#define _GNU_SOURCE
45#include <sched.h>
46
47#endif
48
49#include <err.h>
50#include <fcntl.h>
51#include <inttypes.h>
52#include <stdio.h>
53#include <stdlib.h>
54#include <string.h>
55#include <sys/mman.h>
56#include <sys/stat.h>
57#include <sys/types.h>
58#include <unistd.h>
59
60#include <gem5/m5ops.h>
61#include "m5_mmap.h"
62
63char *progname;
64char *command = "unspecified";
65void usage();
66
67void
68parse_int_args(int argc, char *argv[], uint64_t ints[], int len)
69{
70    if (argc > len)
71        usage();
72
73// On 32 bit platforms we need to use strtoull to do the conversion
74#ifdef __LP64__
75#define strto64 strtoul
76#else
77#define strto64 strtoull
78#endif
79    int i;
80    for (i = 0; i < len; ++i)
81        ints[i] = (i < argc) ? strto64(argv[i], NULL, 0) : 0;
82
83#undef strto64
84}
85
86void
87parse_str_args_to_regs(int argc, char *argv[], uint64_t regs[], int len)
88{
89    if (argc > 1 || (argc > 0 && strlen(argv[0]) > len * sizeof(uint64_t)))
90        usage();
91
92    int i;
93    for (i = 0; i < len; i++)
94        regs[i] = 0;
95
96    if (argc == 0)
97        return;
98
99    int n;
100    for (n = 0, i = 0; i < len && n < strlen(argv[0]); n++) {
101        *((char *)(&regs[i]) + (n % 8)) = argv[0][n];
102        if ((n % 8) == 7)
103            i++;
104    }
105}
106
107int
108read_file(int dest_fid)
109{
110    uint8_t buf[256*1024];
111    int offset = 0;
112    int len, ret;
113
114    // Touch all buffer pages to ensure they are mapped in the
115    // page table. This is required in the case of X86_FS, where
116    // Linux does demand paging.
117    memset(buf, 0, sizeof(buf));
118
119    while ((len = m5_read_file(buf, sizeof(buf), offset)) > 0) {
120        uint8_t *base = buf;
121        offset += len;
122        do {
123            ret = write(dest_fid, base, len);
124            if (ret < 0) {
125                perror("Failed to write file");
126                exit(2);
127            } else if (ret == 0) {
128                fprintf(stderr, "Failed to write file: "
129                        "Unhandled short write\n");
130                exit(2);
131            }
132
133            base += ret;
134            len -= ret;
135        } while (len);
136    }
137
138    return offset;
139}
140
141void
142write_file(const char *filename, const char *host_filename)
143{
144    fprintf(stderr, "opening %s\n", filename);
145    int src_fid = open(filename, O_RDONLY);
146
147    if (src_fid < 0) {
148        fprintf(stderr, "error opening %s\n", filename);
149        return;
150    }
151
152    char buf[256*1024];
153    int offset = 0;
154    int len;
155    int bytes = 0;
156
157    memset(buf, 0, sizeof(buf));
158
159    while ((len = read(src_fid, buf, sizeof(buf))) > 0) {
160        bytes += m5_write_file(buf, len, offset, host_filename);
161        offset += len;
162    }
163    fprintf(stderr, "written %d bytes\n", bytes);
164
165    close(src_fid);
166}
167
168void
169do_exit(int argc, char *argv[])
170{
171    if (argc > 1)
172        usage();
173
174    uint64_t ints[1];
175    parse_int_args(argc, argv, ints, 1);
176    m5_exit(ints[0]);
177}
178
179void
180do_fail(int argc, char *argv[])
181{
182    if (argc < 1 || argc > 2)
183        usage();
184
185    uint64_t ints[2] = {0,0};
186    parse_int_args(argc, argv, ints, argc);
187    m5_fail(ints[1], ints[0]);
188}
189
190void
191do_reset_stats(int argc, char *argv[])
192{
193    uint64_t ints[2];
194    parse_int_args(argc, argv, ints, 2);
195    m5_reset_stats(ints[0], ints[1]);
196}
197
198void
199do_dump_stats(int argc, char *argv[])
200{
201    uint64_t ints[2];
202    parse_int_args(argc, argv, ints, 2);
203    m5_dump_stats(ints[0], ints[1]);
204}
205
206void
207do_dump_reset_stats(int argc, char *argv[])
208{
209    uint64_t ints[2];
210    parse_int_args(argc, argv, ints, 2);
211    m5_dump_reset_stats(ints[0], ints[1]);
212}
213
214void
215do_read_file(int argc, char *argv[])
216{
217    if (argc > 0)
218        usage();
219
220    read_file(STDOUT_FILENO);
221}
222
223void
224do_write_file(int argc, char *argv[])
225{
226    if (argc != 1 && argc != 2)
227        usage();
228
229    const char *filename = argv[0];
230    const char *host_filename = (argc == 2) ? argv[1] : argv[0];
231
232    write_file(filename, host_filename);
233}
234
235void
236do_exec_file(int argc, char *argv[])
237{
238    if (argc > 0)
239        usage();
240
241    const char *destname = "/tmp/execfile";
242
243    int fid = open(destname, O_WRONLY, 0777);
244    int len = read_file(fid);
245    close(fid);
246    if (len > 0) {
247        execl(destname, "execfile", NULL);
248        err(1, "execl failed!");
249    }
250}
251
252void
253do_checkpoint(int argc, char *argv[])
254{
255    uint64_t ints[2];
256    parse_int_args(argc, argv, ints, 2);
257    m5_checkpoint(ints[0], ints[1]);
258}
259
260void
261do_addsymbol(int argc, char *argv[])
262{
263    if (argc != 2)
264        usage();
265
266    uint64_t addr = strtoul(argv[0], NULL, 0);
267    char *symbol = argv[1];
268    m5_add_symbol(addr, symbol);
269}
270
271
272void
273do_loadsymbol(int argc, char *argv[])
274{
275    if (argc > 0)
276        usage();
277
278    m5_load_symbol();
279}
280
281void
282do_initparam(int argc, char *argv[])
283{
284    if (argc > 1)
285        usage();
286
287    uint64_t key_str[2];
288    parse_str_args_to_regs(argc, argv, key_str, 2);
289    uint64_t val = m5_init_param(key_str[0], key_str[1]);
290    printf("%"PRIu64, val);
291}
292
293void
294do_sw99param(int argc, char *argv[])
295{
296    if (argc != 0)
297        usage();
298
299    uint64_t param = m5_init_param(0, 0);
300
301    // run-time, rampup-time, rampdown-time, warmup-time, connections
302    printf("%"PRId64" %"PRId64" %"PRId64" %"PRId64" %"PRId64,
303           (param >> 48) & 0xfff,
304           (param >> 36) & 0xfff, (param >> 24) & 0xfff,
305           (param >> 12) & 0xfff, (param >> 0) & 0xfff);
306}
307
308#ifdef linux
309void
310do_pin(int argc, char *argv[])
311{
312    if (argc < 2)
313        usage();
314
315    cpu_set_t mask;
316    CPU_ZERO(&mask);
317
318    const char *sep = ",";
319    char *target = strtok(argv[0], sep);
320    while (target) {
321        CPU_SET(atoi(target), &mask);
322        target = strtok(NULL, sep);
323    }
324
325    if (sched_setaffinity(0, sizeof(cpu_set_t), &mask) < 0)
326        err(1, "setaffinity");
327
328    execvp(argv[1], &argv[1]);
329    err(1, "execvp failed!");
330}
331#endif
332
333struct MainFunc
334{
335    char *name;
336    void (*func)(int argc, char *argv[]);
337    char *usage;
338};
339
340struct MainFunc mainfuncs[] = {
341    { "exit",           do_exit,             "[delay]" },
342    { "fail",           do_fail,             "<code> [delay]" },
343    { "resetstats",     do_reset_stats,      "[delay [period]]" },
344    { "dumpstats",      do_dump_stats,       "[delay [period]]" },
345    { "dumpresetstats", do_dump_reset_stats, "[delay [period]]" },
346    { "readfile",       do_read_file,        "" },
347    { "writefile",      do_write_file,       "<filename> [host filename]" },
348    { "execfile",       do_exec_file,        "" },
349    { "checkpoint",     do_checkpoint,       "[delay [period]]" },
350    { "addsymbol",      do_addsymbol,        "<address> <symbol>" },
351    { "loadsymbol",     do_loadsymbol,       "" },
352    { "initparam",      do_initparam,        "[key] // key must be shorter"
353                                             " than 16 chars" },
354    { "sw99param",      do_sw99param,        "" },
355#ifdef linux
356    { "pin",            do_pin,              "<cpu> <program> [args ...]" }
357#endif
358};
359int numfuncs = sizeof(mainfuncs) / sizeof(mainfuncs[0]);
360
361void
362usage()
363{
364    int i;
365
366    for (i = 0; i < numfuncs; ++i) {
367        char *header = i ? "" : "usage:";
368        fprintf(stderr, "%-6s %s %s %s\n",
369                header, progname, mainfuncs[i].name, mainfuncs[i].usage);
370    }
371    fprintf(stderr, "\n");
372    fprintf(stderr, "All times in nanoseconds!\n");
373
374    exit(1);
375}
376
377int
378main(int argc, char *argv[])
379{
380    progname = argv[0];
381    if (argc < 2)
382        usage(1);
383
384    map_m5_mem();
385
386    command = argv[1];
387
388    argv += 2;
389    argc -= 2;
390
391    int i;
392    for (i = 0; i < numfuncs; ++i) {
393        if (strcmp(command, mainfuncs[i].name) != 0)
394            continue;
395
396        mainfuncs[i].func(argc, argv);
397        exit(0);
398    }
399
400    usage(1);
401}
402