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