base.cc revision 10905
1/*
2 * Copyright (c) 2010-2012 ARM Limited
3 * Copyright (c) 2013 Advanced Micro Devices, Inc.
4 * All rights reserved
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder.  You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2002-2005 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: Steve Reinhardt
42 */
43
44#include "arch/kernel_stats.hh"
45#include "arch/stacktrace.hh"
46#include "arch/tlb.hh"
47#include "arch/utility.hh"
48#include "arch/vtophys.hh"
49#include "base/loader/symtab.hh"
50#include "base/cp_annotate.hh"
51#include "base/cprintf.hh"
52#include "base/inifile.hh"
53#include "base/misc.hh"
54#include "base/pollevent.hh"
55#include "base/trace.hh"
56#include "base/types.hh"
57#include "config/the_isa.hh"
58#include "cpu/simple/base.hh"
59#include "cpu/base.hh"
60#include "cpu/checker/cpu.hh"
61#include "cpu/checker/thread_context.hh"
62#include "cpu/exetrace.hh"
63#include "cpu/pred/bpred_unit.hh"
64#include "cpu/profile.hh"
65#include "cpu/simple_thread.hh"
66#include "cpu/smt.hh"
67#include "cpu/static_inst.hh"
68#include "cpu/thread_context.hh"
69#include "debug/Decode.hh"
70#include "debug/Fetch.hh"
71#include "debug/Quiesce.hh"
72#include "mem/mem_object.hh"
73#include "mem/packet.hh"
74#include "mem/request.hh"
75#include "params/BaseSimpleCPU.hh"
76#include "sim/byteswap.hh"
77#include "sim/debug.hh"
78#include "sim/faults.hh"
79#include "sim/full_system.hh"
80#include "sim/sim_events.hh"
81#include "sim/sim_object.hh"
82#include "sim/stats.hh"
83#include "sim/system.hh"
84
85using namespace std;
86using namespace TheISA;
87
88BaseSimpleCPU::BaseSimpleCPU(BaseSimpleCPUParams *p)
89    : BaseCPU(p),
90      branchPred(p->branchPred),
91      traceData(NULL), thread(NULL), _status(Idle), interval_stats(false),
92      inst()
93{
94    if (FullSystem)
95        thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb,
96                                  p->isa[0]);
97    else
98        thread = new SimpleThread(this, /* thread_num */ 0, p->system,
99                                  p->workload[0], p->itb, p->dtb, p->isa[0]);
100
101    thread->setStatus(ThreadContext::Halted);
102
103    tc = thread->getTC();
104
105    if (p->checker) {
106        BaseCPU *temp_checker = p->checker;
107        checker = dynamic_cast<CheckerCPU *>(temp_checker);
108        checker->setSystem(p->system);
109        // Manipulate thread context
110        ThreadContext *cpu_tc = tc;
111        tc = new CheckerThreadContext<ThreadContext>(cpu_tc, this->checker);
112    } else {
113        checker = NULL;
114    }
115
116    numInst = 0;
117    startNumInst = 0;
118    numOp = 0;
119    startNumOp = 0;
120    numLoad = 0;
121    startNumLoad = 0;
122    lastIcacheStall = 0;
123    lastDcacheStall = 0;
124
125    threadContexts.push_back(tc);
126
127
128    fetchOffset = 0;
129    stayAtPC = false;
130}
131
132BaseSimpleCPU::~BaseSimpleCPU()
133{
134}
135
136void
137BaseSimpleCPU::haltContext(ThreadID thread_num)
138{
139    // for now, these are equivalent
140    suspendContext(thread_num);
141}
142
143
144void
145BaseSimpleCPU::regStats()
146{
147    using namespace Stats;
148
149    BaseCPU::regStats();
150
151    numInsts
152        .name(name() + ".committedInsts")
153        .desc("Number of instructions committed")
154        ;
155
156    numOps
157        .name(name() + ".committedOps")
158        .desc("Number of ops (including micro ops) committed")
159        ;
160
161    numIntAluAccesses
162        .name(name() + ".num_int_alu_accesses")
163        .desc("Number of integer alu accesses")
164        ;
165
166    numFpAluAccesses
167        .name(name() + ".num_fp_alu_accesses")
168        .desc("Number of float alu accesses")
169        ;
170
171    numCallsReturns
172        .name(name() + ".num_func_calls")
173        .desc("number of times a function call or return occured")
174        ;
175
176    numCondCtrlInsts
177        .name(name() + ".num_conditional_control_insts")
178        .desc("number of instructions that are conditional controls")
179        ;
180
181    numIntInsts
182        .name(name() + ".num_int_insts")
183        .desc("number of integer instructions")
184        ;
185
186    numFpInsts
187        .name(name() + ".num_fp_insts")
188        .desc("number of float instructions")
189        ;
190
191    numIntRegReads
192        .name(name() + ".num_int_register_reads")
193        .desc("number of times the integer registers were read")
194        ;
195
196    numIntRegWrites
197        .name(name() + ".num_int_register_writes")
198        .desc("number of times the integer registers were written")
199        ;
200
201    numFpRegReads
202        .name(name() + ".num_fp_register_reads")
203        .desc("number of times the floating registers were read")
204        ;
205
206    numFpRegWrites
207        .name(name() + ".num_fp_register_writes")
208        .desc("number of times the floating registers were written")
209        ;
210
211    numCCRegReads
212        .name(name() + ".num_cc_register_reads")
213        .desc("number of times the CC registers were read")
214        .flags(nozero)
215        ;
216
217    numCCRegWrites
218        .name(name() + ".num_cc_register_writes")
219        .desc("number of times the CC registers were written")
220        .flags(nozero)
221        ;
222
223    numMemRefs
224        .name(name()+".num_mem_refs")
225        .desc("number of memory refs")
226        ;
227
228    numStoreInsts
229        .name(name() + ".num_store_insts")
230        .desc("Number of store instructions")
231        ;
232
233    numLoadInsts
234        .name(name() + ".num_load_insts")
235        .desc("Number of load instructions")
236        ;
237
238    notIdleFraction
239        .name(name() + ".not_idle_fraction")
240        .desc("Percentage of non-idle cycles")
241        ;
242
243    idleFraction
244        .name(name() + ".idle_fraction")
245        .desc("Percentage of idle cycles")
246        ;
247
248    numBusyCycles
249        .name(name() + ".num_busy_cycles")
250        .desc("Number of busy cycles")
251        ;
252
253    numIdleCycles
254        .name(name()+".num_idle_cycles")
255        .desc("Number of idle cycles")
256        ;
257
258    icacheStallCycles
259        .name(name() + ".icache_stall_cycles")
260        .desc("ICache total stall cycles")
261        .prereq(icacheStallCycles)
262        ;
263
264    dcacheStallCycles
265        .name(name() + ".dcache_stall_cycles")
266        .desc("DCache total stall cycles")
267        .prereq(dcacheStallCycles)
268        ;
269
270    statExecutedInstType
271        .init(Enums::Num_OpClass)
272        .name(name() + ".op_class")
273        .desc("Class of executed instruction")
274        .flags(total | pdf | dist)
275        ;
276    for (unsigned i = 0; i < Num_OpClasses; ++i) {
277        statExecutedInstType.subname(i, Enums::OpClassStrings[i]);
278    }
279
280    idleFraction = constant(1.0) - notIdleFraction;
281    numIdleCycles = idleFraction * numCycles;
282    numBusyCycles = (notIdleFraction)*numCycles;
283
284    numBranches
285        .name(name() + ".Branches")
286        .desc("Number of branches fetched")
287        .prereq(numBranches);
288
289    numPredictedBranches
290        .name(name() + ".predictedBranches")
291        .desc("Number of branches predicted as taken")
292        .prereq(numPredictedBranches);
293
294    numBranchMispred
295        .name(name() + ".BranchMispred")
296        .desc("Number of branch mispredictions")
297        .prereq(numBranchMispred);
298}
299
300void
301BaseSimpleCPU::resetStats()
302{
303//    startNumInst = numInst;
304     notIdleFraction = (_status != Idle);
305}
306
307void
308BaseSimpleCPU::serializeThread(CheckpointOut &cp, ThreadID tid) const
309{
310    assert(_status == Idle || _status == Running);
311    assert(tid == 0);
312
313    thread->serialize(cp);
314}
315
316void
317BaseSimpleCPU::unserializeThread(CheckpointIn &cp, ThreadID tid)
318{
319    if (tid != 0)
320        fatal("Trying to load more than one thread into a SimpleCPU\n");
321    thread->unserialize(cp);
322}
323
324void
325change_thread_state(ThreadID tid, int activate, int priority)
326{
327}
328
329Addr
330BaseSimpleCPU::dbg_vtophys(Addr addr)
331{
332    return vtophys(tc, addr);
333}
334
335void
336BaseSimpleCPU::wakeup()
337{
338    getAddrMonitor()->gotWakeup = true;
339
340    if (thread->status() != ThreadContext::Suspended)
341        return;
342
343    DPRINTF(Quiesce,"Suspended Processor awoke\n");
344    thread->activate();
345}
346
347void
348BaseSimpleCPU::checkForInterrupts()
349{
350    if (checkInterrupts(tc)) {
351        Fault interrupt = interrupts->getInterrupt(tc);
352
353        if (interrupt != NoFault) {
354            fetchOffset = 0;
355            interrupts->updateIntrInfo(tc);
356            interrupt->invoke(tc);
357            thread->decoder.reset();
358        }
359    }
360}
361
362
363void
364BaseSimpleCPU::setupFetchRequest(Request *req)
365{
366    Addr instAddr = thread->instAddr();
367
368    // set up memory request for instruction fetch
369    DPRINTF(Fetch, "Fetch: PC:%08p\n", instAddr);
370
371    Addr fetchPC = (instAddr & PCMask) + fetchOffset;
372    req->setVirt(0, fetchPC, sizeof(MachInst), Request::INST_FETCH, instMasterId(),
373            instAddr);
374}
375
376
377void
378BaseSimpleCPU::preExecute()
379{
380    // maintain $r0 semantics
381    thread->setIntReg(ZeroReg, 0);
382#if THE_ISA == ALPHA_ISA
383    thread->setFloatReg(ZeroReg, 0.0);
384#endif // ALPHA_ISA
385
386    // check for instruction-count-based events
387    comInstEventQueue[0]->serviceEvents(numInst);
388    system->instEventQueue.serviceEvents(system->totalNumInsts);
389
390    // decode the instruction
391    inst = gtoh(inst);
392
393    TheISA::PCState pcState = thread->pcState();
394
395    if (isRomMicroPC(pcState.microPC())) {
396        stayAtPC = false;
397        curStaticInst = microcodeRom.fetchMicroop(pcState.microPC(),
398                                                  curMacroStaticInst);
399    } else if (!curMacroStaticInst) {
400        //We're not in the middle of a macro instruction
401        StaticInstPtr instPtr = NULL;
402
403        TheISA::Decoder *decoder = &(thread->decoder);
404
405        //Predecode, ie bundle up an ExtMachInst
406        //If more fetch data is needed, pass it in.
407        Addr fetchPC = (pcState.instAddr() & PCMask) + fetchOffset;
408        //if(decoder->needMoreBytes())
409            decoder->moreBytes(pcState, fetchPC, inst);
410        //else
411        //    decoder->process();
412
413        //Decode an instruction if one is ready. Otherwise, we'll have to
414        //fetch beyond the MachInst at the current pc.
415        instPtr = decoder->decode(pcState);
416        if (instPtr) {
417            stayAtPC = false;
418            thread->pcState(pcState);
419        } else {
420            stayAtPC = true;
421            fetchOffset += sizeof(MachInst);
422        }
423
424        //If we decoded an instruction and it's microcoded, start pulling
425        //out micro ops
426        if (instPtr && instPtr->isMacroop()) {
427            curMacroStaticInst = instPtr;
428            curStaticInst = curMacroStaticInst->fetchMicroop(pcState.microPC());
429        } else {
430            curStaticInst = instPtr;
431        }
432    } else {
433        //Read the next micro op from the macro op
434        curStaticInst = curMacroStaticInst->fetchMicroop(pcState.microPC());
435    }
436
437    //If we decoded an instruction this "tick", record information about it.
438    if (curStaticInst) {
439#if TRACING_ON
440        traceData = tracer->getInstRecord(curTick(), tc,
441                curStaticInst, thread->pcState(), curMacroStaticInst);
442
443        DPRINTF(Decode,"Decode: Decoded %s instruction: %#x\n",
444                curStaticInst->getName(), curStaticInst->machInst);
445#endif // TRACING_ON
446    }
447
448    if (branchPred && curStaticInst && curStaticInst->isControl()) {
449        // Use a fake sequence number since we only have one
450        // instruction in flight at the same time.
451        const InstSeqNum cur_sn(0);
452        const ThreadID tid(0);
453        pred_pc = thread->pcState();
454        const bool predict_taken(
455            branchPred->predict(curStaticInst, cur_sn, pred_pc, tid));
456
457        if (predict_taken)
458            ++numPredictedBranches;
459    }
460}
461
462void
463BaseSimpleCPU::postExecute()
464{
465    assert(curStaticInst);
466
467    TheISA::PCState pc = tc->pcState();
468    Addr instAddr = pc.instAddr();
469    if (FullSystem && thread->profile) {
470        bool usermode = TheISA::inUserMode(tc);
471        thread->profilePC = usermode ? 1 : instAddr;
472        ProfileNode *node = thread->profile->consume(tc, curStaticInst);
473        if (node)
474            thread->profileNode = node;
475    }
476
477    if (curStaticInst->isMemRef()) {
478        numMemRefs++;
479    }
480
481    if (curStaticInst->isLoad()) {
482        ++numLoad;
483        comLoadEventQueue[0]->serviceEvents(numLoad);
484    }
485
486    if (CPA::available()) {
487        CPA::cpa()->swAutoBegin(tc, pc.nextInstAddr());
488    }
489
490    if (curStaticInst->isControl()) {
491        ++numBranches;
492    }
493
494    /* Power model statistics */
495    //integer alu accesses
496    if (curStaticInst->isInteger()){
497        numIntAluAccesses++;
498        numIntInsts++;
499    }
500
501    //float alu accesses
502    if (curStaticInst->isFloating()){
503        numFpAluAccesses++;
504        numFpInsts++;
505    }
506
507    //number of function calls/returns to get window accesses
508    if (curStaticInst->isCall() || curStaticInst->isReturn()){
509        numCallsReturns++;
510    }
511
512    //the number of branch predictions that will be made
513    if (curStaticInst->isCondCtrl()){
514        numCondCtrlInsts++;
515    }
516
517    //result bus acceses
518    if (curStaticInst->isLoad()){
519        numLoadInsts++;
520    }
521
522    if (curStaticInst->isStore()){
523        numStoreInsts++;
524    }
525    /* End power model statistics */
526
527    statExecutedInstType[curStaticInst->opClass()]++;
528
529    if (FullSystem)
530        traceFunctions(instAddr);
531
532    if (traceData) {
533        traceData->dump();
534        delete traceData;
535        traceData = NULL;
536    }
537
538    // Call CPU instruction commit probes
539    probeInstCommit(curStaticInst);
540}
541
542void
543BaseSimpleCPU::advancePC(const Fault &fault)
544{
545    const bool branching(thread->pcState().branching());
546
547    //Since we're moving to a new pc, zero out the offset
548    fetchOffset = 0;
549    if (fault != NoFault) {
550        curMacroStaticInst = StaticInst::nullStaticInstPtr;
551        fault->invoke(tc, curStaticInst);
552        thread->decoder.reset();
553    } else {
554        if (curStaticInst) {
555            if (curStaticInst->isLastMicroop())
556                curMacroStaticInst = StaticInst::nullStaticInstPtr;
557            TheISA::PCState pcState = thread->pcState();
558            TheISA::advancePC(pcState, curStaticInst);
559            thread->pcState(pcState);
560        }
561    }
562
563    if (branchPred && curStaticInst && curStaticInst->isControl()) {
564        // Use a fake sequence number since we only have one
565        // instruction in flight at the same time.
566        const InstSeqNum cur_sn(0);
567        const ThreadID tid(0);
568
569        if (pred_pc == thread->pcState()) {
570            // Correctly predicted branch
571            branchPred->update(cur_sn, tid);
572        } else {
573            // Mis-predicted branch
574            branchPred->squash(cur_sn, pcState(),
575                               branching, tid);
576            ++numBranchMispred;
577        }
578    }
579}
580
581void
582BaseSimpleCPU::startup()
583{
584    BaseCPU::startup();
585    thread->startup();
586}
587