base.cc revision 8834:21e8d54ecf07
1/*
2 * Copyright (c) 2010-2011 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) 2002-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: Steve Reinhardt
41 */
42
43#include "arch/kernel_stats.hh"
44#include "arch/stacktrace.hh"
45#include "arch/tlb.hh"
46#include "arch/utility.hh"
47#include "arch/vtophys.hh"
48#include "base/loader/symtab.hh"
49#include "base/cp_annotate.hh"
50#include "base/cprintf.hh"
51#include "base/inifile.hh"
52#include "base/misc.hh"
53#include "base/pollevent.hh"
54#include "base/range.hh"
55#include "base/trace.hh"
56#include "base/types.hh"
57#include "config/the_isa.hh"
58#include "config/use_checker.hh"
59#include "cpu/simple/base.hh"
60#include "cpu/base.hh"
61#include "cpu/exetrace.hh"
62#include "cpu/profile.hh"
63#include "cpu/simple_thread.hh"
64#include "cpu/smt.hh"
65#include "cpu/static_inst.hh"
66#include "cpu/thread_context.hh"
67#include "debug/Decode.hh"
68#include "debug/Fetch.hh"
69#include "debug/Quiesce.hh"
70#include "mem/mem_object.hh"
71#include "mem/packet.hh"
72#include "mem/request.hh"
73#include "params/BaseSimpleCPU.hh"
74#include "sim/byteswap.hh"
75#include "sim/debug.hh"
76#include "sim/faults.hh"
77#include "sim/full_system.hh"
78#include "sim/sim_events.hh"
79#include "sim/sim_object.hh"
80#include "sim/stats.hh"
81#include "sim/system.hh"
82
83#if USE_CHECKER
84#include "cpu/checker/cpu.hh"
85#include "cpu/checker/thread_context.hh"
86#endif
87
88using namespace std;
89using namespace TheISA;
90
91BaseSimpleCPU::BaseSimpleCPU(BaseSimpleCPUParams *p)
92    : BaseCPU(p), traceData(NULL), thread(NULL), predecoder(NULL)
93{
94    if (FullSystem)
95        thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb);
96    else
97        thread = new SimpleThread(this, /* thread_num */ 0, p->system,
98                p->workload[0], p->itb, p->dtb);
99
100    thread->setStatus(ThreadContext::Halted);
101
102    tc = thread->getTC();
103
104#if USE_CHECKER
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#endif
116
117    numInst = 0;
118    startNumInst = 0;
119    numOp = 0;
120    startNumOp = 0;
121    numLoad = 0;
122    startNumLoad = 0;
123    lastIcacheStall = 0;
124    lastDcacheStall = 0;
125
126    threadContexts.push_back(tc);
127
128
129    fetchOffset = 0;
130    stayAtPC = false;
131}
132
133BaseSimpleCPU::~BaseSimpleCPU()
134{
135}
136
137void
138BaseSimpleCPU::deallocateContext(ThreadID thread_num)
139{
140    // for now, these are equivalent
141    suspendContext(thread_num);
142}
143
144
145void
146BaseSimpleCPU::haltContext(ThreadID thread_num)
147{
148    // for now, these are equivalent
149    suspendContext(thread_num);
150}
151
152
153void
154BaseSimpleCPU::regStats()
155{
156    using namespace Stats;
157
158    BaseCPU::regStats();
159
160    numInsts
161        .name(name() + ".committedInsts")
162        .desc("Number of instructions committed")
163        ;
164
165    numOps
166        .name(name() + ".committedOps")
167        .desc("Number of ops (including micro ops) committed")
168        ;
169
170    numIntAluAccesses
171        .name(name() + ".num_int_alu_accesses")
172        .desc("Number of integer alu accesses")
173        ;
174
175    numFpAluAccesses
176        .name(name() + ".num_fp_alu_accesses")
177        .desc("Number of float alu accesses")
178        ;
179
180    numCallsReturns
181        .name(name() + ".num_func_calls")
182        .desc("number of times a function call or return occured")
183        ;
184
185    numCondCtrlInsts
186        .name(name() + ".num_conditional_control_insts")
187        .desc("number of instructions that are conditional controls")
188        ;
189
190    numIntInsts
191        .name(name() + ".num_int_insts")
192        .desc("number of integer instructions")
193        ;
194
195    numFpInsts
196        .name(name() + ".num_fp_insts")
197        .desc("number of float instructions")
198        ;
199
200    numIntRegReads
201        .name(name() + ".num_int_register_reads")
202        .desc("number of times the integer registers were read")
203        ;
204
205    numIntRegWrites
206        .name(name() + ".num_int_register_writes")
207        .desc("number of times the integer registers were written")
208        ;
209
210    numFpRegReads
211        .name(name() + ".num_fp_register_reads")
212        .desc("number of times the floating registers were read")
213        ;
214
215    numFpRegWrites
216        .name(name() + ".num_fp_register_writes")
217        .desc("number of times the floating registers were written")
218        ;
219
220    numMemRefs
221        .name(name()+".num_mem_refs")
222        .desc("number of memory refs")
223        ;
224
225    numStoreInsts
226        .name(name() + ".num_store_insts")
227        .desc("Number of store instructions")
228        ;
229
230    numLoadInsts
231        .name(name() + ".num_load_insts")
232        .desc("Number of load instructions")
233        ;
234
235    notIdleFraction
236        .name(name() + ".not_idle_fraction")
237        .desc("Percentage of non-idle cycles")
238        ;
239
240    idleFraction
241        .name(name() + ".idle_fraction")
242        .desc("Percentage of idle cycles")
243        ;
244
245    numBusyCycles
246        .name(name() + ".num_busy_cycles")
247        .desc("Number of busy cycles")
248        ;
249
250    numIdleCycles
251        .name(name()+".num_idle_cycles")
252        .desc("Number of idle cycles")
253        ;
254
255    icacheStallCycles
256        .name(name() + ".icache_stall_cycles")
257        .desc("ICache total stall cycles")
258        .prereq(icacheStallCycles)
259        ;
260
261    dcacheStallCycles
262        .name(name() + ".dcache_stall_cycles")
263        .desc("DCache total stall cycles")
264        .prereq(dcacheStallCycles)
265        ;
266
267    icacheRetryCycles
268        .name(name() + ".icache_retry_cycles")
269        .desc("ICache total retry cycles")
270        .prereq(icacheRetryCycles)
271        ;
272
273    dcacheRetryCycles
274        .name(name() + ".dcache_retry_cycles")
275        .desc("DCache total retry cycles")
276        .prereq(dcacheRetryCycles)
277        ;
278
279    idleFraction = constant(1.0) - notIdleFraction;
280    numIdleCycles = idleFraction * numCycles;
281    numBusyCycles = (notIdleFraction)*numCycles;
282}
283
284void
285BaseSimpleCPU::resetStats()
286{
287//    startNumInst = numInst;
288     notIdleFraction = (_status != Idle);
289}
290
291void
292BaseSimpleCPU::serialize(ostream &os)
293{
294    SERIALIZE_ENUM(_status);
295    BaseCPU::serialize(os);
296//    SERIALIZE_SCALAR(inst);
297    nameOut(os, csprintf("%s.xc.0", name()));
298    thread->serialize(os);
299}
300
301void
302BaseSimpleCPU::unserialize(Checkpoint *cp, const string &section)
303{
304    UNSERIALIZE_ENUM(_status);
305    BaseCPU::unserialize(cp, section);
306//    UNSERIALIZE_SCALAR(inst);
307    thread->unserialize(cp, csprintf("%s.xc.0", section));
308}
309
310void
311change_thread_state(ThreadID tid, int activate, int priority)
312{
313}
314
315Addr
316BaseSimpleCPU::dbg_vtophys(Addr addr)
317{
318    return vtophys(tc, addr);
319}
320
321void
322BaseSimpleCPU::wakeup()
323{
324    if (thread->status() != ThreadContext::Suspended)
325        return;
326
327    DPRINTF(Quiesce,"Suspended Processor awoke\n");
328    thread->activate();
329}
330
331void
332BaseSimpleCPU::checkForInterrupts()
333{
334    if (checkInterrupts(tc)) {
335        Fault interrupt = interrupts->getInterrupt(tc);
336
337        if (interrupt != NoFault) {
338            fetchOffset = 0;
339            interrupts->updateIntrInfo(tc);
340            interrupt->invoke(tc);
341            predecoder.reset();
342        }
343    }
344}
345
346
347void
348BaseSimpleCPU::setupFetchRequest(Request *req)
349{
350    Addr instAddr = thread->instAddr();
351
352    // set up memory request for instruction fetch
353    DPRINTF(Fetch, "Fetch: PC:%08p\n", instAddr);
354
355    Addr fetchPC = (instAddr & PCMask) + fetchOffset;
356    req->setVirt(0, fetchPC, sizeof(MachInst), Request::INST_FETCH, instMasterId(),
357            instAddr);
358}
359
360
361void
362BaseSimpleCPU::preExecute()
363{
364    // maintain $r0 semantics
365    thread->setIntReg(ZeroReg, 0);
366#if THE_ISA == ALPHA_ISA
367    thread->setFloatReg(ZeroReg, 0.0);
368#endif // ALPHA_ISA
369
370    // check for instruction-count-based events
371    comInstEventQueue[0]->serviceEvents(numInst);
372    system->instEventQueue.serviceEvents(system->totalNumInsts);
373
374    // decode the instruction
375    inst = gtoh(inst);
376
377    TheISA::PCState pcState = thread->pcState();
378
379    if (isRomMicroPC(pcState.microPC())) {
380        stayAtPC = false;
381        curStaticInst = microcodeRom.fetchMicroop(pcState.microPC(),
382                                                  curMacroStaticInst);
383    } else if (!curMacroStaticInst) {
384        //We're not in the middle of a macro instruction
385        StaticInstPtr instPtr = NULL;
386
387        //Predecode, ie bundle up an ExtMachInst
388        //This should go away once the constructor can be set up properly
389        predecoder.setTC(thread->getTC());
390        //If more fetch data is needed, pass it in.
391        Addr fetchPC = (pcState.instAddr() & PCMask) + fetchOffset;
392        //if(predecoder.needMoreBytes())
393            predecoder.moreBytes(pcState, fetchPC, inst);
394        //else
395        //    predecoder.process();
396
397        //If an instruction is ready, decode it. Otherwise, we'll have to
398        //fetch beyond the MachInst at the current pc.
399        if (predecoder.extMachInstReady()) {
400            stayAtPC = false;
401            ExtMachInst machInst = predecoder.getExtMachInst(pcState);
402            thread->pcState(pcState);
403            instPtr = thread->decoder.decode(machInst, pcState.instAddr());
404        } else {
405            stayAtPC = true;
406            fetchOffset += sizeof(MachInst);
407        }
408
409        //If we decoded an instruction and it's microcoded, start pulling
410        //out micro ops
411        if (instPtr && instPtr->isMacroop()) {
412            curMacroStaticInst = instPtr;
413            curStaticInst = curMacroStaticInst->fetchMicroop(pcState.microPC());
414        } else {
415            curStaticInst = instPtr;
416        }
417    } else {
418        //Read the next micro op from the macro op
419        curStaticInst = curMacroStaticInst->fetchMicroop(pcState.microPC());
420    }
421
422    //If we decoded an instruction this "tick", record information about it.
423    if(curStaticInst)
424    {
425#if TRACING_ON
426        traceData = tracer->getInstRecord(curTick(), tc,
427                curStaticInst, thread->pcState(), curMacroStaticInst);
428
429        DPRINTF(Decode,"Decode: Decoded %s instruction: 0x%x\n",
430                curStaticInst->getName(), curStaticInst->machInst);
431#endif // TRACING_ON
432    }
433}
434
435void
436BaseSimpleCPU::postExecute()
437{
438    assert(curStaticInst);
439
440    TheISA::PCState pc = tc->pcState();
441    Addr instAddr = pc.instAddr();
442    if (FullSystem && thread->profile) {
443        bool usermode = TheISA::inUserMode(tc);
444        thread->profilePC = usermode ? 1 : instAddr;
445        ProfileNode *node = thread->profile->consume(tc, curStaticInst);
446        if (node)
447            thread->profileNode = node;
448    }
449
450    if (curStaticInst->isMemRef()) {
451        numMemRefs++;
452    }
453
454    if (curStaticInst->isLoad()) {
455        ++numLoad;
456        comLoadEventQueue[0]->serviceEvents(numLoad);
457    }
458
459    if (CPA::available()) {
460        CPA::cpa()->swAutoBegin(tc, pc.nextInstAddr());
461    }
462
463    /* Power model statistics */
464    //integer alu accesses
465    if (curStaticInst->isInteger()){
466        numIntAluAccesses++;
467        numIntInsts++;
468    }
469
470    //float alu accesses
471    if (curStaticInst->isFloating()){
472        numFpAluAccesses++;
473        numFpInsts++;
474    }
475
476    //number of function calls/returns to get window accesses
477    if (curStaticInst->isCall() || curStaticInst->isReturn()){
478        numCallsReturns++;
479    }
480
481    //the number of branch predictions that will be made
482    if (curStaticInst->isCondCtrl()){
483        numCondCtrlInsts++;
484    }
485
486    //result bus acceses
487    if (curStaticInst->isLoad()){
488        numLoadInsts++;
489    }
490
491    if (curStaticInst->isStore()){
492        numStoreInsts++;
493    }
494    /* End power model statistics */
495
496    if (FullSystem)
497        traceFunctions(instAddr);
498
499    if (traceData) {
500        traceData->dump();
501        delete traceData;
502        traceData = NULL;
503    }
504}
505
506
507void
508BaseSimpleCPU::advancePC(Fault fault)
509{
510    //Since we're moving to a new pc, zero out the offset
511    fetchOffset = 0;
512    if (fault != NoFault) {
513        curMacroStaticInst = StaticInst::nullStaticInstPtr;
514        fault->invoke(tc, curStaticInst);
515        predecoder.reset();
516    } else {
517        if (curStaticInst) {
518            if (curStaticInst->isLastMicroop())
519                curMacroStaticInst = StaticInst::nullStaticInstPtr;
520            TheISA::PCState pcState = thread->pcState();
521            TheISA::advancePC(pcState, curStaticInst);
522            thread->pcState(pcState);
523        }
524    }
525}
526
527/*Fault
528BaseSimpleCPU::CacheOp(uint8_t Op, Addr EffAddr)
529{
530    // translate to physical address
531    Fault fault = NoFault;
532    int CacheID = Op & 0x3; // Lower 3 bits identify Cache
533    int CacheOP = Op >> 2; // Upper 3 bits identify Cache Operation
534    if(CacheID > 1)
535      {
536        warn("CacheOps not implemented for secondary/tertiary caches\n");
537      }
538    else
539      {
540        switch(CacheOP)
541          { // Fill Packet Type
542          case 0: warn("Invalidate Cache Op\n");
543            break;
544          case 1: warn("Index Load Tag Cache Op\n");
545            break;
546          case 2: warn("Index Store Tag Cache Op\n");
547            break;
548          case 4: warn("Hit Invalidate Cache Op\n");
549            break;
550          case 5: warn("Fill/Hit Writeback Invalidate Cache Op\n");
551            break;
552          case 6: warn("Hit Writeback\n");
553            break;
554          case 7: warn("Fetch & Lock Cache Op\n");
555            break;
556          default: warn("Unimplemented Cache Op\n");
557          }
558      }
559    return fault;
560}*/
561