pseudo_inst.cc revision 11703:08b78e0a3717
1/*
2 * Copyright (c) 2010-2012, 2015 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 "arch/pseudo_inst.hh"
56#include "base/debug.hh"
57#include "base/output.hh"
58#include "config/the_isa.hh"
59#include "cpu/base.hh"
60#include "cpu/quiesce_event.hh"
61#include "cpu/thread_context.hh"
62#include "debug/Loader.hh"
63#include "debug/PseudoInst.hh"
64#include "debug/Quiesce.hh"
65#include "debug/WorkItems.hh"
66#include "dev/net/dist_iface.hh"
67#include "params/BaseCPU.hh"
68#include "sim/full_system.hh"
69#include "sim/initparam_keys.hh"
70#include "sim/process.hh"
71#include "sim/pseudo_inst.hh"
72#include "sim/serialize.hh"
73#include "sim/sim_events.hh"
74#include "sim/sim_exit.hh"
75#include "sim/stat_control.hh"
76#include "sim/stats.hh"
77#include "sim/system.hh"
78#include "sim/vptr.hh"
79
80using namespace std;
81
82using namespace Stats;
83using namespace TheISA;
84
85namespace PseudoInst {
86
87static inline void
88panicFsOnlyPseudoInst(const char *name)
89{
90    panic("Pseudo inst \"%s\" is only available in Full System mode.");
91}
92
93uint64_t
94pseudoInst(ThreadContext *tc, uint8_t func, uint8_t subfunc)
95{
96    uint64_t args[4];
97
98    DPRINTF(PseudoInst, "PseudoInst::pseudoInst(%i, %i)\n", func, subfunc);
99
100    // We need to do this in a slightly convoluted way since
101    // getArgument() might have side-effects on arg_num. We could have
102    // used the Argument class, but due to the possible side effects
103    // from getArgument, it'd most likely break.
104    int arg_num(0);
105    for (int i = 0; i < sizeof(args) / sizeof(*args); ++i) {
106        args[arg_num] = getArgument(tc, arg_num, sizeof(uint64_t), false);
107        ++arg_num;
108    }
109
110    switch (func) {
111      case 0x00: // arm_func
112        arm(tc);
113        break;
114
115      case 0x01: // quiesce_func
116        quiesce(tc);
117        break;
118
119      case 0x02: // quiescens_func
120        quiesceSkip(tc);
121        break;
122
123      case 0x03: // quiescecycle_func
124        quiesceNs(tc, args[0]);
125        break;
126
127      case 0x04: // quiescetime_func
128        return quiesceTime(tc);
129
130      case 0x07: // rpns_func
131        return rpns(tc);
132
133      case 0x09: // wakecpu_func
134        wakeCPU(tc, args[0]);
135        break;
136
137      case 0x21: // exit_func
138        m5exit(tc, args[0]);
139        break;
140
141      case 0x22:
142        m5fail(tc, args[0], args[1]);
143        break;
144
145      case 0x30: // initparam_func
146        return initParam(tc, args[0], args[1]);
147
148      case 0x31: // loadsymbol_func
149        loadsymbol(tc);
150        break;
151
152      case 0x40: // resetstats_func
153        resetstats(tc, args[0], args[1]);
154        break;
155
156      case 0x41: // dumpstats_func
157        dumpstats(tc, args[0], args[1]);
158        break;
159
160      case 0x42: // dumprststats_func
161        dumpresetstats(tc, args[0], args[1]);
162        break;
163
164      case 0x43: // ckpt_func
165        m5checkpoint(tc, args[0], args[1]);
166        break;
167
168      case 0x4f: // writefile_func
169        return writefile(tc, args[0], args[1], args[2], args[3]);
170
171      case 0x50: // readfile_func
172        return readfile(tc, args[0], args[1], args[2]);
173
174      case 0x51: // debugbreak_func
175        debugbreak(tc);
176        break;
177
178      case 0x52: // switchcpu_func
179        switchcpu(tc);
180        break;
181
182      case 0x53: // addsymbol_func
183        addsymbol(tc, args[0], args[1]);
184        break;
185
186      case 0x54: // panic_func
187        panic("M5 panic instruction called at %s\n", tc->pcState());
188
189      case 0x5a: // work_begin_func
190        workbegin(tc, args[0], args[1]);
191        break;
192
193      case 0x5b: // work_end_func
194        workend(tc, args[0], args[1]);
195        break;
196
197      case 0x55: // annotate_func
198      case 0x56: // reserved2_func
199      case 0x57: // reserved3_func
200      case 0x58: // reserved4_func
201      case 0x59: // reserved5_func
202        warn("Unimplemented m5 op (0x%x)\n", func);
203        break;
204
205      /* SE mode functions */
206      case 0x60: // syscall_func
207        m5Syscall(tc);
208        break;
209
210      case 0x61: // pagefault_func
211        m5PageFault(tc);
212        break;
213
214      /* dist-gem5 functions */
215      case 0x62: // distToggleSync_func
216        togglesync(tc);
217        break;
218
219      default:
220        warn("Unhandled m5 op: 0x%x\n", func);
221        break;
222    }
223
224    return 0;
225}
226
227void
228arm(ThreadContext *tc)
229{
230    DPRINTF(PseudoInst, "PseudoInst::arm()\n");
231    if (!FullSystem)
232        panicFsOnlyPseudoInst("arm");
233
234    if (tc->getKernelStats())
235        tc->getKernelStats()->arm();
236}
237
238void
239quiesce(ThreadContext *tc)
240{
241    DPRINTF(PseudoInst, "PseudoInst::quiesce()\n");
242    tc->quiesce();
243}
244
245void
246quiesceSkip(ThreadContext *tc)
247{
248    DPRINTF(PseudoInst, "PseudoInst::quiesceSkip()\n");
249    tc->quiesceTick(tc->getCpuPtr()->nextCycle() + 1);
250}
251
252void
253quiesceNs(ThreadContext *tc, uint64_t ns)
254{
255    DPRINTF(PseudoInst, "PseudoInst::quiesceNs(%i)\n", ns);
256    tc->quiesceTick(curTick() + SimClock::Int::ns * ns);
257}
258
259void
260quiesceCycles(ThreadContext *tc, uint64_t cycles)
261{
262    DPRINTF(PseudoInst, "PseudoInst::quiesceCycles(%i)\n", cycles);
263    tc->quiesceTick(tc->getCpuPtr()->clockEdge(Cycles(cycles)));
264}
265
266uint64_t
267quiesceTime(ThreadContext *tc)
268{
269    DPRINTF(PseudoInst, "PseudoInst::quiesceTime()\n");
270
271    return (tc->readLastActivate() - tc->readLastSuspend()) /
272        SimClock::Int::ns;
273}
274
275uint64_t
276rpns(ThreadContext *tc)
277{
278    DPRINTF(PseudoInst, "PseudoInst::rpns()\n");
279    return curTick() / SimClock::Int::ns;
280}
281
282void
283wakeCPU(ThreadContext *tc, uint64_t cpuid)
284{
285    DPRINTF(PseudoInst, "PseudoInst::wakeCPU(%i)\n", cpuid);
286    System *sys = tc->getSystemPtr();
287    ThreadContext *other_tc = sys->threadContexts[cpuid];
288    if (other_tc->status() == ThreadContext::Suspended)
289        other_tc->activate();
290}
291
292void
293m5exit(ThreadContext *tc, Tick delay)
294{
295    DPRINTF(PseudoInst, "PseudoInst::m5exit(%i)\n", delay);
296    if (DistIface::readyToExit(delay)) {
297        Tick when = curTick() + delay * SimClock::Int::ns;
298        exitSimLoop("m5_exit instruction encountered", 0, when, 0, true);
299    }
300}
301
302void
303m5fail(ThreadContext *tc, Tick delay, uint64_t code)
304{
305    DPRINTF(PseudoInst, "PseudoInst::m5fail(%i, %i)\n", delay, code);
306    Tick when = curTick() + delay * SimClock::Int::ns;
307    exitSimLoop("m5_fail instruction encountered", code, when, 0, true);
308}
309
310void
311loadsymbol(ThreadContext *tc)
312{
313    DPRINTF(PseudoInst, "PseudoInst::loadsymbol()\n");
314    if (!FullSystem)
315        panicFsOnlyPseudoInst("loadsymbol");
316
317    const string &filename = tc->getCpuPtr()->system->params()->symbolfile;
318    if (filename.empty()) {
319        return;
320    }
321
322    std::string buffer;
323    ifstream file(filename.c_str());
324
325    if (!file)
326        fatal("file error: Can't open symbol table file %s\n", filename);
327
328    while (!file.eof()) {
329        getline(file, buffer);
330
331        if (buffer.empty())
332            continue;
333
334        string::size_type idx = buffer.find(' ');
335        if (idx == string::npos)
336            continue;
337
338        string address = "0x" + buffer.substr(0, idx);
339        eat_white(address);
340        if (address.empty())
341            continue;
342
343        // Skip over letter and space
344        string symbol = buffer.substr(idx + 3);
345        eat_white(symbol);
346        if (symbol.empty())
347            continue;
348
349        Addr addr;
350        if (!to_number(address, addr))
351            continue;
352
353        if (!tc->getSystemPtr()->kernelSymtab->insert(addr, symbol))
354            continue;
355
356
357        DPRINTF(Loader, "Loaded symbol: %s @ %#llx\n", symbol, addr);
358    }
359    file.close();
360}
361
362void
363addsymbol(ThreadContext *tc, Addr addr, Addr symbolAddr)
364{
365    DPRINTF(PseudoInst, "PseudoInst::addsymbol(0x%x, 0x%x)\n",
366            addr, symbolAddr);
367    if (!FullSystem)
368        panicFsOnlyPseudoInst("addSymbol");
369
370    char symb[100];
371    CopyStringOut(tc, symb, symbolAddr, 100);
372    std::string symbol(symb);
373
374    DPRINTF(Loader, "Loaded symbol: %s @ %#llx\n", symbol, addr);
375
376    tc->getSystemPtr()->kernelSymtab->insert(addr,symbol);
377    debugSymbolTable->insert(addr,symbol);
378}
379
380uint64_t
381initParam(ThreadContext *tc, uint64_t key_str1, uint64_t key_str2)
382{
383    DPRINTF(PseudoInst, "PseudoInst::initParam() key:%s%s\n", (char *)&key_str1,
384            (char *)&key_str2);
385    if (!FullSystem) {
386        panicFsOnlyPseudoInst("initParam");
387        return 0;
388    }
389
390    // The key parameter string is passed in via two 64-bit registers. We copy
391    // out the characters from the 64-bit integer variables here and concatenate
392    // them in the key_str character buffer
393    const int len = 2 * sizeof(uint64_t) + 1;
394    char key_str[len];
395    memset(key_str, '\0', len);
396    if (key_str1 == 0) {
397        assert(key_str2 == 0);
398    } else {
399        strncpy(key_str, (char *)&key_str1, sizeof(uint64_t));
400    }
401
402    if (strlen(key_str) == sizeof(uint64_t)) {
403        strncpy(key_str + sizeof(uint64_t), (char *)&key_str2,
404                sizeof(uint64_t));
405    } else {
406        assert(key_str2 == 0);
407    }
408
409    // Compare the key parameter with the known values to select the return
410    // value
411    uint64_t val;
412    if (strcmp(key_str, InitParamKey::DEFAULT) == 0) {
413        val = tc->getCpuPtr()->system->init_param;
414    } else if (strcmp(key_str, InitParamKey::DIST_RANK) == 0) {
415        val = DistIface::rankParam();
416    } else if (strcmp(key_str, InitParamKey::DIST_SIZE) == 0) {
417        val = DistIface::sizeParam();
418    } else {
419        panic("Unknown key for initparam pseudo instruction:\"%s\"", key_str);
420    }
421    return val;
422}
423
424
425void
426resetstats(ThreadContext *tc, Tick delay, Tick period)
427{
428    DPRINTF(PseudoInst, "PseudoInst::resetstats(%i, %i)\n", delay, period);
429    if (!tc->getCpuPtr()->params()->do_statistics_insts)
430        return;
431
432
433    Tick when = curTick() + delay * SimClock::Int::ns;
434    Tick repeat = period * SimClock::Int::ns;
435
436    Stats::schedStatEvent(false, true, when, repeat);
437}
438
439void
440dumpstats(ThreadContext *tc, Tick delay, Tick period)
441{
442    DPRINTF(PseudoInst, "PseudoInst::dumpstats(%i, %i)\n", delay, period);
443    if (!tc->getCpuPtr()->params()->do_statistics_insts)
444        return;
445
446
447    Tick when = curTick() + delay * SimClock::Int::ns;
448    Tick repeat = period * SimClock::Int::ns;
449
450    Stats::schedStatEvent(true, false, when, repeat);
451}
452
453void
454dumpresetstats(ThreadContext *tc, Tick delay, Tick period)
455{
456    DPRINTF(PseudoInst, "PseudoInst::dumpresetstats(%i, %i)\n", delay, period);
457    if (!tc->getCpuPtr()->params()->do_statistics_insts)
458        return;
459
460
461    Tick when = curTick() + delay * SimClock::Int::ns;
462    Tick repeat = period * SimClock::Int::ns;
463
464    Stats::schedStatEvent(true, true, when, repeat);
465}
466
467void
468m5checkpoint(ThreadContext *tc, Tick delay, Tick period)
469{
470    DPRINTF(PseudoInst, "PseudoInst::m5checkpoint(%i, %i)\n", delay, period);
471    if (!tc->getCpuPtr()->params()->do_checkpoint_insts)
472        return;
473
474    if (DistIface::readyToCkpt(delay, period)) {
475        Tick when = curTick() + delay * SimClock::Int::ns;
476        Tick repeat = period * SimClock::Int::ns;
477        exitSimLoop("checkpoint", 0, when, repeat);
478    }
479}
480
481uint64_t
482readfile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset)
483{
484    DPRINTF(PseudoInst, "PseudoInst::readfile(0x%x, 0x%x, 0x%x)\n",
485            vaddr, len, offset);
486    if (!FullSystem) {
487        panicFsOnlyPseudoInst("readfile");
488        return 0;
489    }
490
491    const string &file = tc->getSystemPtr()->params()->readfile;
492    if (file.empty()) {
493        return ULL(0);
494    }
495
496    uint64_t result = 0;
497
498    int fd = ::open(file.c_str(), O_RDONLY, 0);
499    if (fd < 0)
500        panic("could not open file %s\n", file);
501
502    if (::lseek(fd, offset, SEEK_SET) < 0)
503        panic("could not seek: %s", strerror(errno));
504
505    char *buf = new char[len];
506    char *p = buf;
507    while (len > 0) {
508        int bytes = ::read(fd, p, len);
509        if (bytes <= 0)
510            break;
511
512        p += bytes;
513        result += bytes;
514        len -= bytes;
515    }
516
517    close(fd);
518    CopyIn(tc, vaddr, buf, result);
519    delete [] buf;
520    return result;
521}
522
523uint64_t
524writefile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset,
525            Addr filename_addr)
526{
527    DPRINTF(PseudoInst, "PseudoInst::writefile(0x%x, 0x%x, 0x%x, 0x%x)\n",
528            vaddr, len, offset, filename_addr);
529
530    // copy out target filename
531    char fn[100];
532    std::string filename;
533    CopyStringOut(tc, fn, filename_addr, 100);
534    filename = std::string(fn);
535
536    OutputStream *out;
537    if (offset == 0) {
538        // create a new file (truncate)
539        out = simout.create(filename, true, true);
540    } else {
541        // do not truncate file if offset is non-zero
542        // (ios::in flag is required as well to keep the existing data
543        //  intact, otherwise existing data will be zeroed out.)
544        out = simout.open(filename, ios::in | ios::out | ios::binary, true);
545    }
546
547    ostream *os(out->stream());
548    if (!os)
549        panic("could not open file %s\n", filename);
550
551    // seek to offset
552    os->seekp(offset);
553
554    // copy out data and write to file
555    char *buf = new char[len];
556    CopyOut(tc, buf, vaddr, len);
557    os->write(buf, len);
558    if (os->fail() || os->bad())
559        panic("Error while doing writefile!\n");
560
561    simout.close(out);
562
563    delete [] buf;
564
565    return len;
566}
567
568void
569debugbreak(ThreadContext *tc)
570{
571    DPRINTF(PseudoInst, "PseudoInst::debugbreak()\n");
572    Debug::breakpoint();
573}
574
575void
576switchcpu(ThreadContext *tc)
577{
578    DPRINTF(PseudoInst, "PseudoInst::switchcpu()\n");
579    exitSimLoop("switchcpu");
580}
581
582void
583togglesync(ThreadContext *tc)
584{
585    DPRINTF(PseudoInst, "PseudoInst::togglesync()\n");
586    DistIface::toggleSync(tc);
587}
588
589//
590// This function is executed when annotated work items begin.  Depending on
591// what the user specified at the command line, the simulation may exit and/or
592// take a checkpoint when a certain work item begins.
593//
594void
595workbegin(ThreadContext *tc, uint64_t workid, uint64_t threadid)
596{
597    DPRINTF(PseudoInst, "PseudoInst::workbegin(%i, %i)\n", workid, threadid);
598    System *sys = tc->getSystemPtr();
599    const System::Params *params = sys->params();
600
601    if (params->exit_on_work_items) {
602        exitSimLoop("workbegin", static_cast<int>(workid));
603        return;
604    }
605
606    DPRINTF(WorkItems, "Work Begin workid: %d, threadid %d\n", workid,
607            threadid);
608    tc->getCpuPtr()->workItemBegin();
609    sys->workItemBegin(threadid, workid);
610
611    //
612    // If specified, determine if this is the specific work item the user
613    // identified
614    //
615    if (params->work_item_id == -1 || params->work_item_id == workid) {
616
617        uint64_t systemWorkBeginCount = sys->incWorkItemsBegin();
618        int cpuId = tc->getCpuPtr()->cpuId();
619
620        if (params->work_cpus_ckpt_count != 0 &&
621            sys->markWorkItem(cpuId) >= params->work_cpus_ckpt_count) {
622            //
623            // If active cpus equals checkpoint count, create checkpoint
624            //
625            exitSimLoop("checkpoint");
626        }
627
628        if (systemWorkBeginCount == params->work_begin_ckpt_count) {
629            //
630            // Note: the string specified as the cause of the exit event must
631            // exactly equal "checkpoint" inorder to create a checkpoint
632            //
633            exitSimLoop("checkpoint");
634        }
635
636        if (systemWorkBeginCount == params->work_begin_exit_count) {
637            //
638            // If a certain number of work items started, exit simulation
639            //
640            exitSimLoop("work started count reach");
641        }
642
643        if (cpuId == params->work_begin_cpu_id_exit) {
644            //
645            // If work started on the cpu id specified, exit simulation
646            //
647            exitSimLoop("work started on specific cpu");
648        }
649    }
650}
651
652//
653// This function is executed when annotated work items end.  Depending on
654// what the user specified at the command line, the simulation may exit and/or
655// take a checkpoint when a certain work item ends.
656//
657void
658workend(ThreadContext *tc, uint64_t workid, uint64_t threadid)
659{
660    DPRINTF(PseudoInst, "PseudoInst::workend(%i, %i)\n", workid, threadid);
661    System *sys = tc->getSystemPtr();
662    const System::Params *params = sys->params();
663
664    if (params->exit_on_work_items) {
665        exitSimLoop("workend", static_cast<int>(workid));
666        return;
667    }
668
669    DPRINTF(WorkItems, "Work End workid: %d, threadid %d\n", workid, threadid);
670    tc->getCpuPtr()->workItemEnd();
671    sys->workItemEnd(threadid, workid);
672
673    //
674    // If specified, determine if this is the specific work item the user
675    // identified
676    //
677    if (params->work_item_id == -1 || params->work_item_id == workid) {
678
679        uint64_t systemWorkEndCount = sys->incWorkItemsEnd();
680        int cpuId = tc->getCpuPtr()->cpuId();
681
682        if (params->work_cpus_ckpt_count != 0 &&
683            sys->markWorkItem(cpuId) >= params->work_cpus_ckpt_count) {
684            //
685            // If active cpus equals checkpoint count, create checkpoint
686            //
687            exitSimLoop("checkpoint");
688        }
689
690        if (params->work_end_ckpt_count != 0 &&
691            systemWorkEndCount == params->work_end_ckpt_count) {
692            //
693            // If total work items completed equals checkpoint count, create
694            // checkpoint
695            //
696            exitSimLoop("checkpoint");
697        }
698
699        if (params->work_end_exit_count != 0 &&
700            systemWorkEndCount == params->work_end_exit_count) {
701            //
702            // If total work items completed equals exit count, exit simulation
703            //
704            exitSimLoop("work items exit count reached");
705        }
706    }
707}
708
709} // namespace PseudoInst
710