pseudo_inst.cc revision 9681:4597012dfa97
1/*
2 * Copyright (c) 2010-2012 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) 2011 Advanced Micro Devices, Inc.
15 * Copyright (c) 2003-2006 The Regents of The University of Michigan
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Nathan Binkert
42 */
43
44#include <fcntl.h>
45#include <unistd.h>
46
47#include <cerrno>
48#include <fstream>
49#include <string>
50#include <vector>
51
52#include "arch/kernel_stats.hh"
53#include "arch/utility.hh"
54#include "arch/vtophys.hh"
55#include "base/debug.hh"
56#include "base/output.hh"
57#include "config/the_isa.hh"
58#include "cpu/base.hh"
59#include "cpu/quiesce_event.hh"
60#include "cpu/thread_context.hh"
61#include "debug/Loader.hh"
62#include "debug/Quiesce.hh"
63#include "debug/WorkItems.hh"
64#include "params/BaseCPU.hh"
65#include "sim/full_system.hh"
66#include "sim/pseudo_inst.hh"
67#include "sim/serialize.hh"
68#include "sim/sim_events.hh"
69#include "sim/sim_exit.hh"
70#include "sim/stat_control.hh"
71#include "sim/stats.hh"
72#include "sim/system.hh"
73#include "sim/vptr.hh"
74
75using namespace std;
76
77using namespace Stats;
78using namespace TheISA;
79
80namespace PseudoInst {
81
82static inline void
83panicFsOnlyPseudoInst(const char *name)
84{
85    panic("Pseudo inst \"%s\" is only available in Full System mode.");
86}
87
88uint64_t
89pseudoInst(ThreadContext *tc, uint8_t func, uint8_t subfunc)
90{
91    uint64_t args[4];
92
93    // We need to do this in a slightly convoluted way since
94    // getArgument() might have side-effects on arg_num. We could have
95    // used the Argument class, but due to the possible side effects
96    // from getArgument, it'd most likely break.
97    int arg_num(0);
98    for (int i = 0; i < sizeof(args) / sizeof(*args); ++i)
99        args[arg_num++] = getArgument(tc, arg_num, sizeof(uint64_t), false);
100
101    switch (func) {
102      case 0x00: // arm_func
103        arm(tc);
104        break;
105
106      case 0x01: // quiesce_func
107        quiesce(tc);
108        break;
109
110      case 0x02: // quiescens_func
111        quiesceSkip(tc);
112        break;
113
114      case 0x03: // quiescecycle_func
115        quiesceNs(tc, args[0]);
116        break;
117
118      case 0x04: // quiescetime_func
119        return quiesceTime(tc);
120
121      case 0x07: // rpns_func
122        return rpns(tc);
123
124      case 0x09: // wakecpu_func
125        wakeCPU(tc, args[0]);
126        break;
127
128      case 0x21: // exit_func
129        m5exit(tc, args[0]);
130        break;
131
132      case 0x22:
133        m5fail(tc, args[0], args[1]);
134        break;
135
136      case 0x30: // initparam_func
137        return initParam(tc);
138
139      case 0x31: // loadsymbol_func
140        loadsymbol(tc);
141        break;
142
143      case 0x40: // resetstats_func
144        resetstats(tc, args[0], args[1]);
145        break;
146
147      case 0x41: // dumpstats_func
148        dumpstats(tc, args[0], args[1]);
149        break;
150
151      case 0x42: // dumprststats_func
152        dumpresetstats(tc, args[0], args[1]);
153        break;
154
155      case 0x43: // ckpt_func
156        m5checkpoint(tc, args[0], args[1]);
157        break;
158
159      case 0x4f: // writefile_func
160        return writefile(tc, args[0], args[1], args[2], args[3]);
161
162      case 0x50: // readfile_func
163        return readfile(tc, args[0], args[1], args[2]);
164
165      case 0x51: // debugbreak_func
166        debugbreak(tc);
167        break;
168
169      case 0x52: // switchcpu_func
170        switchcpu(tc);
171        break;
172
173      case 0x53: // addsymbol_func
174        addsymbol(tc, args[0], args[1]);
175        break;
176
177      case 0x54: // panic_func
178        panic("M5 panic instruction called at %s\n", tc->pcState());
179
180      case 0x5a: // work_begin_func
181        workbegin(tc, args[0], args[1]);
182        break;
183
184      case 0x5b: // work_end_func
185        workend(tc, args[0], args[1]);
186        break;
187
188      case 0x55: // annotate_func
189      case 0x56: // reserved2_func
190      case 0x57: // reserved3_func
191      case 0x58: // reserved4_func
192      case 0x59: // reserved5_func
193        warn("Unimplemented m5 op (0x%x)\n", func);
194        break;
195
196      default:
197        warn("Unhandled m5 op: 0x%x\n", func);
198        break;
199    }
200
201    return 0;
202}
203
204void
205arm(ThreadContext *tc)
206{
207    if (!FullSystem)
208        panicFsOnlyPseudoInst("arm");
209
210    if (tc->getKernelStats())
211        tc->getKernelStats()->arm();
212}
213
214void
215quiesce(ThreadContext *tc)
216{
217    if (!FullSystem)
218        panicFsOnlyPseudoInst("quiesce");
219
220    if (!tc->getCpuPtr()->params()->do_quiesce)
221        return;
222
223    DPRINTF(Quiesce, "%s: quiesce()\n", tc->getCpuPtr()->name());
224
225    tc->suspend();
226    if (tc->getKernelStats())
227        tc->getKernelStats()->quiesce();
228}
229
230void
231quiesceSkip(ThreadContext *tc)
232{
233    if (!FullSystem)
234        panicFsOnlyPseudoInst("quiesceSkip");
235
236    BaseCPU *cpu = tc->getCpuPtr();
237
238    if (!cpu->params()->do_quiesce)
239        return;
240
241    EndQuiesceEvent *quiesceEvent = tc->getQuiesceEvent();
242
243    Tick resume = curTick() + 1;
244
245    cpu->reschedule(quiesceEvent, resume, true);
246
247    DPRINTF(Quiesce, "%s: quiesceSkip() until %d\n",
248            cpu->name(), resume);
249
250    tc->suspend();
251    if (tc->getKernelStats())
252        tc->getKernelStats()->quiesce();
253}
254
255void
256quiesceNs(ThreadContext *tc, uint64_t ns)
257{
258    if (!FullSystem)
259        panicFsOnlyPseudoInst("quiesceNs");
260
261    BaseCPU *cpu = tc->getCpuPtr();
262
263    if (!cpu->params()->do_quiesce || ns == 0)
264        return;
265
266    EndQuiesceEvent *quiesceEvent = tc->getQuiesceEvent();
267
268    Tick resume = curTick() + SimClock::Int::ns * ns;
269
270    cpu->reschedule(quiesceEvent, resume, true);
271
272    DPRINTF(Quiesce, "%s: quiesceNs(%d) until %d\n",
273            cpu->name(), ns, resume);
274
275    tc->suspend();
276    if (tc->getKernelStats())
277        tc->getKernelStats()->quiesce();
278}
279
280void
281quiesceCycles(ThreadContext *tc, uint64_t cycles)
282{
283    if (!FullSystem)
284        panicFsOnlyPseudoInst("quiesceCycles");
285
286    BaseCPU *cpu = tc->getCpuPtr();
287
288    if (!cpu->params()->do_quiesce || cycles == 0)
289        return;
290
291    EndQuiesceEvent *quiesceEvent = tc->getQuiesceEvent();
292
293    Tick resume = cpu->clockEdge(Cycles(cycles));
294
295    cpu->reschedule(quiesceEvent, resume, true);
296
297    DPRINTF(Quiesce, "%s: quiesceCycles(%d) until %d\n",
298            cpu->name(), cycles, resume);
299
300    tc->suspend();
301    if (tc->getKernelStats())
302        tc->getKernelStats()->quiesce();
303}
304
305uint64_t
306quiesceTime(ThreadContext *tc)
307{
308    if (!FullSystem) {
309        panicFsOnlyPseudoInst("quiesceTime");
310        return 0;
311    }
312
313    return (tc->readLastActivate() - tc->readLastSuspend()) /
314        SimClock::Int::ns;
315}
316
317uint64_t
318rpns(ThreadContext *tc)
319{
320    return curTick() / SimClock::Int::ns;
321}
322
323void
324wakeCPU(ThreadContext *tc, uint64_t cpuid)
325{
326    System *sys = tc->getSystemPtr();
327    ThreadContext *other_tc = sys->threadContexts[cpuid];
328    if (other_tc->status() == ThreadContext::Suspended)
329        other_tc->activate();
330}
331
332void
333m5exit(ThreadContext *tc, Tick delay)
334{
335    Tick when = curTick() + delay * SimClock::Int::ns;
336    exitSimLoop("m5_exit instruction encountered", 0, when);
337}
338
339void
340m5fail(ThreadContext *tc, Tick delay, uint64_t code)
341{
342    Tick when = curTick() + delay * SimClock::Int::ns;
343    exitSimLoop("m5_fail instruction encountered", code, when);
344}
345
346void
347loadsymbol(ThreadContext *tc)
348{
349    if (!FullSystem)
350        panicFsOnlyPseudoInst("loadsymbol");
351
352    const string &filename = tc->getCpuPtr()->system->params()->symbolfile;
353    if (filename.empty()) {
354        return;
355    }
356
357    std::string buffer;
358    ifstream file(filename.c_str());
359
360    if (!file)
361        fatal("file error: Can't open symbol table file %s\n", filename);
362
363    while (!file.eof()) {
364        getline(file, buffer);
365
366        if (buffer.empty())
367            continue;
368
369        string::size_type idx = buffer.find(' ');
370        if (idx == string::npos)
371            continue;
372
373        string address = "0x" + buffer.substr(0, idx);
374        eat_white(address);
375        if (address.empty())
376            continue;
377
378        // Skip over letter and space
379        string symbol = buffer.substr(idx + 3);
380        eat_white(symbol);
381        if (symbol.empty())
382            continue;
383
384        Addr addr;
385        if (!to_number(address, addr))
386            continue;
387
388        if (!tc->getSystemPtr()->kernelSymtab->insert(addr, symbol))
389            continue;
390
391
392        DPRINTF(Loader, "Loaded symbol: %s @ %#llx\n", symbol, addr);
393    }
394    file.close();
395}
396
397void
398addsymbol(ThreadContext *tc, Addr addr, Addr symbolAddr)
399{
400    if (!FullSystem)
401        panicFsOnlyPseudoInst("addSymbol");
402
403    char symb[100];
404    CopyStringOut(tc, symb, symbolAddr, 100);
405    std::string symbol(symb);
406
407    DPRINTF(Loader, "Loaded symbol: %s @ %#llx\n", symbol, addr);
408
409    tc->getSystemPtr()->kernelSymtab->insert(addr,symbol);
410    debugSymbolTable->insert(addr,symbol);
411}
412
413uint64_t
414initParam(ThreadContext *tc)
415{
416    if (!FullSystem) {
417        panicFsOnlyPseudoInst("initParam");
418        return 0;
419    }
420
421    return tc->getCpuPtr()->system->init_param;
422}
423
424
425void
426resetstats(ThreadContext *tc, Tick delay, Tick period)
427{
428    if (!tc->getCpuPtr()->params()->do_statistics_insts)
429        return;
430
431
432    Tick when = curTick() + delay * SimClock::Int::ns;
433    Tick repeat = period * SimClock::Int::ns;
434
435    Stats::schedStatEvent(false, true, when, repeat);
436}
437
438void
439dumpstats(ThreadContext *tc, Tick delay, Tick period)
440{
441    if (!tc->getCpuPtr()->params()->do_statistics_insts)
442        return;
443
444
445    Tick when = curTick() + delay * SimClock::Int::ns;
446    Tick repeat = period * SimClock::Int::ns;
447
448    Stats::schedStatEvent(true, false, when, repeat);
449}
450
451void
452dumpresetstats(ThreadContext *tc, Tick delay, Tick period)
453{
454    if (!tc->getCpuPtr()->params()->do_statistics_insts)
455        return;
456
457
458    Tick when = curTick() + delay * SimClock::Int::ns;
459    Tick repeat = period * SimClock::Int::ns;
460
461    Stats::schedStatEvent(true, true, when, repeat);
462}
463
464void
465m5checkpoint(ThreadContext *tc, Tick delay, Tick period)
466{
467    if (!tc->getCpuPtr()->params()->do_checkpoint_insts)
468        return;
469
470    Tick when = curTick() + delay * SimClock::Int::ns;
471    Tick repeat = period * SimClock::Int::ns;
472
473    exitSimLoop("checkpoint", 0, when, repeat);
474}
475
476uint64_t
477readfile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset)
478{
479    if (!FullSystem) {
480        panicFsOnlyPseudoInst("readfile");
481        return 0;
482    }
483
484    const string &file = tc->getSystemPtr()->params()->readfile;
485    if (file.empty()) {
486        return ULL(0);
487    }
488
489    uint64_t result = 0;
490
491    int fd = ::open(file.c_str(), O_RDONLY, 0);
492    if (fd < 0)
493        panic("could not open file %s\n", file);
494
495    if (::lseek(fd, offset, SEEK_SET) < 0)
496        panic("could not seek: %s", strerror(errno));
497
498    char *buf = new char[len];
499    char *p = buf;
500    while (len > 0) {
501        int bytes = ::read(fd, p, len);
502        if (bytes <= 0)
503            break;
504
505        p += bytes;
506        result += bytes;
507        len -= bytes;
508    }
509
510    close(fd);
511    CopyIn(tc, vaddr, buf, result);
512    delete [] buf;
513    return result;
514}
515
516uint64_t
517writefile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset,
518            Addr filename_addr)
519{
520    ostream *os;
521
522    // copy out target filename
523    char fn[100];
524    std::string filename;
525    CopyStringOut(tc, fn, filename_addr, 100);
526    filename = std::string(fn);
527
528    if (offset == 0) {
529        // create a new file (truncate)
530        os = simout.create(filename, true);
531    } else {
532        // do not truncate file if offset is non-zero
533        // (ios::in flag is required as well to keep the existing data
534        //  intact, otherwise existing data will be zeroed out.)
535        os = simout.openFile(simout.directory() + filename,
536                            ios::in | ios::out | ios::binary);
537    }
538    if (!os)
539        panic("could not open file %s\n", filename);
540
541    // seek to offset
542    os->seekp(offset);
543
544    // copy out data and write to file
545    char *buf = new char[len];
546    CopyOut(tc, buf, vaddr, len);
547    os->write(buf, len);
548    if (os->fail() || os->bad())
549        panic("Error while doing writefile!\n");
550
551    simout.close(os);
552
553    delete [] buf;
554
555    return len;
556}
557
558void
559debugbreak(ThreadContext *tc)
560{
561    Debug::breakpoint();
562}
563
564void
565switchcpu(ThreadContext *tc)
566{
567    exitSimLoop("switchcpu");
568}
569
570//
571// This function is executed when annotated work items begin.  Depending on
572// what the user specified at the command line, the simulation may exit and/or
573// take a checkpoint when a certain work item begins.
574//
575void
576workbegin(ThreadContext *tc, uint64_t workid, uint64_t threadid)
577{
578    tc->getCpuPtr()->workItemBegin();
579    System *sys = tc->getSystemPtr();
580    const System::Params *params = sys->params();
581    sys->workItemBegin(threadid, workid);
582
583    DPRINTF(WorkItems, "Work Begin workid: %d, threadid %d\n", workid,
584            threadid);
585
586    //
587    // If specified, determine if this is the specific work item the user
588    // identified
589    //
590    if (params->work_item_id == -1 || params->work_item_id == workid) {
591
592        uint64_t systemWorkBeginCount = sys->incWorkItemsBegin();
593        int cpuId = tc->getCpuPtr()->cpuId();
594
595        if (params->work_cpus_ckpt_count != 0 &&
596            sys->markWorkItem(cpuId) >= params->work_cpus_ckpt_count) {
597            //
598            // If active cpus equals checkpoint count, create checkpoint
599            //
600            exitSimLoop("checkpoint");
601        }
602
603        if (systemWorkBeginCount == params->work_begin_ckpt_count) {
604            //
605            // Note: the string specified as the cause of the exit event must
606            // exactly equal "checkpoint" inorder to create a checkpoint
607            //
608            exitSimLoop("checkpoint");
609        }
610
611        if (systemWorkBeginCount == params->work_begin_exit_count) {
612            //
613            // If a certain number of work items started, exit simulation
614            //
615            exitSimLoop("work started count reach");
616        }
617
618        if (cpuId == params->work_begin_cpu_id_exit) {
619            //
620            // If work started on the cpu id specified, exit simulation
621            //
622            exitSimLoop("work started on specific cpu");
623        }
624    }
625}
626
627//
628// This function is executed when annotated work items end.  Depending on
629// what the user specified at the command line, the simulation may exit and/or
630// take a checkpoint when a certain work item ends.
631//
632void
633workend(ThreadContext *tc, uint64_t workid, uint64_t threadid)
634{
635    tc->getCpuPtr()->workItemEnd();
636    System *sys = tc->getSystemPtr();
637    const System::Params *params = sys->params();
638    sys->workItemEnd(threadid, workid);
639
640    DPRINTF(WorkItems, "Work End workid: %d, threadid %d\n", workid, threadid);
641
642    //
643    // If specified, determine if this is the specific work item the user
644    // identified
645    //
646    if (params->work_item_id == -1 || params->work_item_id == workid) {
647
648        uint64_t systemWorkEndCount = sys->incWorkItemsEnd();
649        int cpuId = tc->getCpuPtr()->cpuId();
650
651        if (params->work_cpus_ckpt_count != 0 &&
652            sys->markWorkItem(cpuId) >= params->work_cpus_ckpt_count) {
653            //
654            // If active cpus equals checkpoint count, create checkpoint
655            //
656            exitSimLoop("checkpoint");
657        }
658
659        if (params->work_end_ckpt_count != 0 &&
660            systemWorkEndCount == params->work_end_ckpt_count) {
661            //
662            // If total work items completed equals checkpoint count, create
663            // checkpoint
664            //
665            exitSimLoop("checkpoint");
666        }
667
668        if (params->work_end_exit_count != 0 &&
669            systemWorkEndCount == params->work_end_exit_count) {
670            //
671            // If total work items completed equals exit count, exit simulation
672            //
673            exitSimLoop("work items exit count reached");
674        }
675    }
676}
677
678} // namespace PseudoInst
679