cpu.cc revision 8921:e53972f72165
1/*
2 * Copyright (c) 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) 2004-2006 The Regents of The University of Michigan
15 * Copyright (c) 2011 Regents of the University of California
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: Kevin Lim
42 *          Korey Sewell
43 *          Rick Strong
44 */
45
46#include "arch/kernel_stats.hh"
47#include "config/the_isa.hh"
48#include "cpu/checker/cpu.hh"
49#include "cpu/checker/thread_context.hh"
50#include "cpu/o3/cpu.hh"
51#include "cpu/o3/isa_specific.hh"
52#include "cpu/o3/thread_context.hh"
53#include "cpu/activity.hh"
54#include "cpu/quiesce_event.hh"
55#include "cpu/simple_thread.hh"
56#include "cpu/thread_context.hh"
57#include "debug/Activity.hh"
58#include "debug/O3CPU.hh"
59#include "debug/Quiesce.hh"
60#include "enums/MemoryMode.hh"
61#include "sim/core.hh"
62#include "sim/full_system.hh"
63#include "sim/process.hh"
64#include "sim/stat_control.hh"
65#include "sim/system.hh"
66
67#if THE_ISA == ALPHA_ISA
68#include "arch/alpha/osfpal.hh"
69#include "debug/Activity.hh"
70#endif
71
72struct BaseCPUParams;
73
74using namespace TheISA;
75using namespace std;
76
77BaseO3CPU::BaseO3CPU(BaseCPUParams *params)
78    : BaseCPU(params)
79{
80}
81
82void
83BaseO3CPU::regStats()
84{
85    BaseCPU::regStats();
86}
87
88template<class Impl>
89bool
90FullO3CPU<Impl>::IcachePort::recvTiming(PacketPtr pkt)
91{
92    DPRINTF(O3CPU, "Fetch unit received timing\n");
93    if (pkt->isResponse()) {
94        // We shouldn't ever get a block in ownership state
95        assert(!(pkt->memInhibitAsserted() && !pkt->sharedAsserted()));
96
97        fetch->processCacheCompletion(pkt);
98    }
99    //else Snooped a coherence request, just return
100    return true;
101}
102
103template<class Impl>
104void
105FullO3CPU<Impl>::IcachePort::recvRetry()
106{
107    fetch->recvRetry();
108}
109
110template <class Impl>
111bool
112FullO3CPU<Impl>::DcachePort::recvTiming(PacketPtr pkt)
113{
114    return lsq->recvTiming(pkt);
115}
116
117template <class Impl>
118void
119FullO3CPU<Impl>::DcachePort::recvRetry()
120{
121    lsq->recvRetry();
122}
123
124template <class Impl>
125FullO3CPU<Impl>::TickEvent::TickEvent(FullO3CPU<Impl> *c)
126    : Event(CPU_Tick_Pri), cpu(c)
127{
128}
129
130template <class Impl>
131void
132FullO3CPU<Impl>::TickEvent::process()
133{
134    cpu->tick();
135}
136
137template <class Impl>
138const char *
139FullO3CPU<Impl>::TickEvent::description() const
140{
141    return "FullO3CPU tick";
142}
143
144template <class Impl>
145FullO3CPU<Impl>::ActivateThreadEvent::ActivateThreadEvent()
146    : Event(CPU_Switch_Pri)
147{
148}
149
150template <class Impl>
151void
152FullO3CPU<Impl>::ActivateThreadEvent::init(int thread_num,
153                                           FullO3CPU<Impl> *thread_cpu)
154{
155    tid = thread_num;
156    cpu = thread_cpu;
157}
158
159template <class Impl>
160void
161FullO3CPU<Impl>::ActivateThreadEvent::process()
162{
163    cpu->activateThread(tid);
164}
165
166template <class Impl>
167const char *
168FullO3CPU<Impl>::ActivateThreadEvent::description() const
169{
170    return "FullO3CPU \"Activate Thread\"";
171}
172
173template <class Impl>
174FullO3CPU<Impl>::DeallocateContextEvent::DeallocateContextEvent()
175    : Event(CPU_Tick_Pri), tid(0), remove(false), cpu(NULL)
176{
177}
178
179template <class Impl>
180void
181FullO3CPU<Impl>::DeallocateContextEvent::init(int thread_num,
182                                              FullO3CPU<Impl> *thread_cpu)
183{
184    tid = thread_num;
185    cpu = thread_cpu;
186    remove = false;
187}
188
189template <class Impl>
190void
191FullO3CPU<Impl>::DeallocateContextEvent::process()
192{
193    cpu->deactivateThread(tid);
194    if (remove)
195        cpu->removeThread(tid);
196}
197
198template <class Impl>
199const char *
200FullO3CPU<Impl>::DeallocateContextEvent::description() const
201{
202    return "FullO3CPU \"Deallocate Context\"";
203}
204
205template <class Impl>
206FullO3CPU<Impl>::FullO3CPU(DerivO3CPUParams *params)
207    : BaseO3CPU(params),
208      itb(params->itb),
209      dtb(params->dtb),
210      tickEvent(this),
211#ifndef NDEBUG
212      instcount(0),
213#endif
214      removeInstsThisCycle(false),
215      fetch(this, params),
216      decode(this, params),
217      rename(this, params),
218      iew(this, params),
219      commit(this, params),
220
221      regFile(this, params->numPhysIntRegs,
222              params->numPhysFloatRegs),
223
224      freeList(params->numThreads,
225               TheISA::NumIntRegs, params->numPhysIntRegs,
226               TheISA::NumFloatRegs, params->numPhysFloatRegs),
227
228      rob(this,
229          params->numROBEntries, params->squashWidth,
230          params->smtROBPolicy, params->smtROBThreshold,
231          params->numThreads),
232
233      scoreboard(params->numThreads,
234                 TheISA::NumIntRegs, params->numPhysIntRegs,
235                 TheISA::NumFloatRegs, params->numPhysFloatRegs,
236                 TheISA::NumMiscRegs * numThreads,
237                 TheISA::ZeroReg),
238
239      icachePort(&fetch, this),
240      dcachePort(&iew.ldstQueue, this),
241
242      timeBuffer(params->backComSize, params->forwardComSize),
243      fetchQueue(params->backComSize, params->forwardComSize),
244      decodeQueue(params->backComSize, params->forwardComSize),
245      renameQueue(params->backComSize, params->forwardComSize),
246      iewQueue(params->backComSize, params->forwardComSize),
247      activityRec(name(), NumStages,
248                  params->backComSize + params->forwardComSize,
249                  params->activity),
250
251      globalSeqNum(1),
252      system(params->system),
253      drainCount(0),
254      deferRegistration(params->defer_registration)
255{
256    if (!deferRegistration) {
257        _status = Running;
258    } else {
259        _status = Idle;
260    }
261
262    if (params->checker) {
263        BaseCPU *temp_checker = params->checker;
264        checker = dynamic_cast<Checker<Impl> *>(temp_checker);
265        checker->setIcachePort(&icachePort);
266        checker->setSystem(params->system);
267    } else {
268        checker = NULL;
269    }
270
271    if (!FullSystem) {
272        thread.resize(numThreads);
273        tids.resize(numThreads);
274    }
275
276    // The stages also need their CPU pointer setup.  However this
277    // must be done at the upper level CPU because they have pointers
278    // to the upper level CPU, and not this FullO3CPU.
279
280    // Set up Pointers to the activeThreads list for each stage
281    fetch.setActiveThreads(&activeThreads);
282    decode.setActiveThreads(&activeThreads);
283    rename.setActiveThreads(&activeThreads);
284    iew.setActiveThreads(&activeThreads);
285    commit.setActiveThreads(&activeThreads);
286
287    // Give each of the stages the time buffer they will use.
288    fetch.setTimeBuffer(&timeBuffer);
289    decode.setTimeBuffer(&timeBuffer);
290    rename.setTimeBuffer(&timeBuffer);
291    iew.setTimeBuffer(&timeBuffer);
292    commit.setTimeBuffer(&timeBuffer);
293
294    // Also setup each of the stages' queues.
295    fetch.setFetchQueue(&fetchQueue);
296    decode.setFetchQueue(&fetchQueue);
297    commit.setFetchQueue(&fetchQueue);
298    decode.setDecodeQueue(&decodeQueue);
299    rename.setDecodeQueue(&decodeQueue);
300    rename.setRenameQueue(&renameQueue);
301    iew.setRenameQueue(&renameQueue);
302    iew.setIEWQueue(&iewQueue);
303    commit.setIEWQueue(&iewQueue);
304    commit.setRenameQueue(&renameQueue);
305
306    commit.setIEWStage(&iew);
307    rename.setIEWStage(&iew);
308    rename.setCommitStage(&commit);
309
310    ThreadID active_threads;
311    if (FullSystem) {
312        active_threads = 1;
313    } else {
314        active_threads = params->workload.size();
315
316        if (active_threads > Impl::MaxThreads) {
317            panic("Workload Size too large. Increase the 'MaxThreads' "
318                  "constant in your O3CPU impl. file (e.g. o3/alpha/impl.hh) "
319                  "or edit your workload size.");
320        }
321    }
322
323    //Make Sure That this a Valid Architeture
324    assert(params->numPhysIntRegs   >= numThreads * TheISA::NumIntRegs);
325    assert(params->numPhysFloatRegs >= numThreads * TheISA::NumFloatRegs);
326
327    rename.setScoreboard(&scoreboard);
328    iew.setScoreboard(&scoreboard);
329
330    // Setup the rename map for whichever stages need it.
331    PhysRegIndex lreg_idx = 0;
332    PhysRegIndex freg_idx = params->numPhysIntRegs; //Index to 1 after int regs
333
334    for (ThreadID tid = 0; tid < numThreads; tid++) {
335        bool bindRegs = (tid <= active_threads - 1);
336
337        commitRenameMap[tid].init(TheISA::NumIntRegs,
338                                  params->numPhysIntRegs,
339                                  lreg_idx,            //Index for Logical. Regs
340
341                                  TheISA::NumFloatRegs,
342                                  params->numPhysFloatRegs,
343                                  freg_idx,            //Index for Float Regs
344
345                                  TheISA::NumMiscRegs,
346
347                                  TheISA::ZeroReg,
348                                  TheISA::ZeroReg,
349
350                                  tid,
351                                  false);
352
353        renameMap[tid].init(TheISA::NumIntRegs,
354                            params->numPhysIntRegs,
355                            lreg_idx,                  //Index for Logical. Regs
356
357                            TheISA::NumFloatRegs,
358                            params->numPhysFloatRegs,
359                            freg_idx,                  //Index for Float Regs
360
361                            TheISA::NumMiscRegs,
362
363                            TheISA::ZeroReg,
364                            TheISA::ZeroReg,
365
366                            tid,
367                            bindRegs);
368
369        activateThreadEvent[tid].init(tid, this);
370        deallocateContextEvent[tid].init(tid, this);
371    }
372
373    rename.setRenameMap(renameMap);
374    commit.setRenameMap(commitRenameMap);
375
376    // Give renameMap & rename stage access to the freeList;
377    for (ThreadID tid = 0; tid < numThreads; tid++)
378        renameMap[tid].setFreeList(&freeList);
379    rename.setFreeList(&freeList);
380
381    // Setup the ROB for whichever stages need it.
382    commit.setROB(&rob);
383
384    lastRunningCycle = curTick();
385
386    lastActivatedCycle = -1;
387#if 0
388    // Give renameMap & rename stage access to the freeList;
389    for (ThreadID tid = 0; tid < numThreads; tid++)
390        globalSeqNum[tid] = 1;
391#endif
392
393    contextSwitch = false;
394    DPRINTF(O3CPU, "Creating O3CPU object.\n");
395
396    // Setup any thread state.
397    this->thread.resize(this->numThreads);
398
399    for (ThreadID tid = 0; tid < this->numThreads; ++tid) {
400        if (FullSystem) {
401            // SMT is not supported in FS mode yet.
402            assert(this->numThreads == 1);
403            this->thread[tid] = new Thread(this, 0, NULL);
404        } else {
405            if (tid < params->workload.size()) {
406                DPRINTF(O3CPU, "Workload[%i] process is %#x",
407                        tid, this->thread[tid]);
408                this->thread[tid] = new typename FullO3CPU<Impl>::Thread(
409                        (typename Impl::O3CPU *)(this),
410                        tid, params->workload[tid]);
411
412                //usedTids[tid] = true;
413                //threadMap[tid] = tid;
414            } else {
415                //Allocate Empty thread so M5 can use later
416                //when scheduling threads to CPU
417                Process* dummy_proc = NULL;
418
419                this->thread[tid] = new typename FullO3CPU<Impl>::Thread(
420                        (typename Impl::O3CPU *)(this),
421                        tid, dummy_proc);
422                //usedTids[tid] = false;
423            }
424        }
425
426        ThreadContext *tc;
427
428        // Setup the TC that will serve as the interface to the threads/CPU.
429        O3ThreadContext<Impl> *o3_tc = new O3ThreadContext<Impl>;
430
431        tc = o3_tc;
432
433        // If we're using a checker, then the TC should be the
434        // CheckerThreadContext.
435        if (params->checker) {
436            tc = new CheckerThreadContext<O3ThreadContext<Impl> >(
437                o3_tc, this->checker);
438        }
439
440        o3_tc->cpu = (typename Impl::O3CPU *)(this);
441        assert(o3_tc->cpu);
442        o3_tc->thread = this->thread[tid];
443
444        if (FullSystem) {
445            // Setup quiesce event.
446            this->thread[tid]->quiesceEvent = new EndQuiesceEvent(tc);
447        }
448        // Give the thread the TC.
449        this->thread[tid]->tc = tc;
450
451        // Add the TC to the CPU's list of TC's.
452        this->threadContexts.push_back(tc);
453    }
454
455    // FullO3CPU always requires an interrupt controller.
456    if (!params->defer_registration && !interrupts) {
457        fatal("FullO3CPU %s has no interrupt controller.\n"
458              "Ensure createInterruptController() is called.\n", name());
459    }
460
461    for (ThreadID tid = 0; tid < this->numThreads; tid++)
462        this->thread[tid]->setFuncExeInst(0);
463
464    lockAddr = 0;
465    lockFlag = false;
466}
467
468template <class Impl>
469FullO3CPU<Impl>::~FullO3CPU()
470{
471}
472
473template <class Impl>
474void
475FullO3CPU<Impl>::regStats()
476{
477    BaseO3CPU::regStats();
478
479    // Register any of the O3CPU's stats here.
480    timesIdled
481        .name(name() + ".timesIdled")
482        .desc("Number of times that the entire CPU went into an idle state and"
483              " unscheduled itself")
484        .prereq(timesIdled);
485
486    idleCycles
487        .name(name() + ".idleCycles")
488        .desc("Total number of cycles that the CPU has spent unscheduled due "
489              "to idling")
490        .prereq(idleCycles);
491
492    quiesceCycles
493        .name(name() + ".quiesceCycles")
494        .desc("Total number of cycles that CPU has spent quiesced or waiting "
495              "for an interrupt")
496        .prereq(quiesceCycles);
497
498    // Number of Instructions simulated
499    // --------------------------------
500    // Should probably be in Base CPU but need templated
501    // MaxThreads so put in here instead
502    committedInsts
503        .init(numThreads)
504        .name(name() + ".committedInsts")
505        .desc("Number of Instructions Simulated");
506
507    committedOps
508        .init(numThreads)
509        .name(name() + ".committedOps")
510        .desc("Number of Ops (including micro ops) Simulated");
511
512    totalCommittedInsts
513        .name(name() + ".committedInsts_total")
514        .desc("Number of Instructions Simulated");
515
516    cpi
517        .name(name() + ".cpi")
518        .desc("CPI: Cycles Per Instruction")
519        .precision(6);
520    cpi = numCycles / committedInsts;
521
522    totalCpi
523        .name(name() + ".cpi_total")
524        .desc("CPI: Total CPI of All Threads")
525        .precision(6);
526    totalCpi = numCycles / totalCommittedInsts;
527
528    ipc
529        .name(name() + ".ipc")
530        .desc("IPC: Instructions Per Cycle")
531        .precision(6);
532    ipc =  committedInsts / numCycles;
533
534    totalIpc
535        .name(name() + ".ipc_total")
536        .desc("IPC: Total IPC of All Threads")
537        .precision(6);
538    totalIpc =  totalCommittedInsts / numCycles;
539
540    this->fetch.regStats();
541    this->decode.regStats();
542    this->rename.regStats();
543    this->iew.regStats();
544    this->commit.regStats();
545    this->rob.regStats();
546
547    intRegfileReads
548        .name(name() + ".int_regfile_reads")
549        .desc("number of integer regfile reads")
550        .prereq(intRegfileReads);
551
552    intRegfileWrites
553        .name(name() + ".int_regfile_writes")
554        .desc("number of integer regfile writes")
555        .prereq(intRegfileWrites);
556
557    fpRegfileReads
558        .name(name() + ".fp_regfile_reads")
559        .desc("number of floating regfile reads")
560        .prereq(fpRegfileReads);
561
562    fpRegfileWrites
563        .name(name() + ".fp_regfile_writes")
564        .desc("number of floating regfile writes")
565        .prereq(fpRegfileWrites);
566
567    miscRegfileReads
568        .name(name() + ".misc_regfile_reads")
569        .desc("number of misc regfile reads")
570        .prereq(miscRegfileReads);
571
572    miscRegfileWrites
573        .name(name() + ".misc_regfile_writes")
574        .desc("number of misc regfile writes")
575        .prereq(miscRegfileWrites);
576}
577
578template <class Impl>
579void
580FullO3CPU<Impl>::tick()
581{
582    DPRINTF(O3CPU, "\n\nFullO3CPU: Ticking main, FullO3CPU.\n");
583
584    ++numCycles;
585
586//    activity = false;
587
588    //Tick each of the stages
589    fetch.tick();
590
591    decode.tick();
592
593    rename.tick();
594
595    iew.tick();
596
597    commit.tick();
598
599    if (!FullSystem)
600        doContextSwitch();
601
602    // Now advance the time buffers
603    timeBuffer.advance();
604
605    fetchQueue.advance();
606    decodeQueue.advance();
607    renameQueue.advance();
608    iewQueue.advance();
609
610    activityRec.advance();
611
612    if (removeInstsThisCycle) {
613        cleanUpRemovedInsts();
614    }
615
616    if (!tickEvent.scheduled()) {
617        if (_status == SwitchedOut ||
618            getState() == SimObject::Drained) {
619            DPRINTF(O3CPU, "Switched out!\n");
620            // increment stat
621            lastRunningCycle = curTick();
622        } else if (!activityRec.active() || _status == Idle) {
623            DPRINTF(O3CPU, "Idle!\n");
624            lastRunningCycle = curTick();
625            timesIdled++;
626        } else {
627            schedule(tickEvent, nextCycle(curTick() + ticks(1)));
628            DPRINTF(O3CPU, "Scheduling next tick!\n");
629        }
630    }
631
632    if (!FullSystem)
633        updateThreadPriority();
634}
635
636template <class Impl>
637void
638FullO3CPU<Impl>::init()
639{
640    BaseCPU::init();
641
642    for (ThreadID tid = 0; tid < numThreads; ++tid) {
643        // Set inSyscall so that the CPU doesn't squash when initially
644        // setting up registers.
645        thread[tid]->inSyscall = true;
646        // Initialise the ThreadContext's memory proxies
647        thread[tid]->initMemProxies(thread[tid]->getTC());
648    }
649
650    // this CPU could still be unconnected if we are restoring from a
651    // checkpoint and this CPU is to be switched in, thus we can only
652    // do this here if the instruction port is actually connected, if
653    // not we have to do it as part of takeOverFrom
654    if (icachePort.isConnected())
655        fetch.setIcache();
656
657    if (FullSystem && !params()->defer_registration) {
658        for (ThreadID tid = 0; tid < numThreads; tid++) {
659            ThreadContext *src_tc = threadContexts[tid];
660            TheISA::initCPU(src_tc, src_tc->contextId());
661        }
662    }
663
664    // Clear inSyscall.
665    for (int tid = 0; tid < numThreads; ++tid)
666        thread[tid]->inSyscall = false;
667
668    // Initialize stages.
669    fetch.initStage();
670    iew.initStage();
671    rename.initStage();
672    commit.initStage();
673
674    commit.setThreads(thread);
675}
676
677template <class Impl>
678void
679FullO3CPU<Impl>::activateThread(ThreadID tid)
680{
681    list<ThreadID>::iterator isActive =
682        std::find(activeThreads.begin(), activeThreads.end(), tid);
683
684    DPRINTF(O3CPU, "[tid:%i]: Calling activate thread.\n", tid);
685
686    if (isActive == activeThreads.end()) {
687        DPRINTF(O3CPU, "[tid:%i]: Adding to active threads list\n",
688                tid);
689
690        activeThreads.push_back(tid);
691    }
692}
693
694template <class Impl>
695void
696FullO3CPU<Impl>::deactivateThread(ThreadID tid)
697{
698    //Remove From Active List, if Active
699    list<ThreadID>::iterator thread_it =
700        std::find(activeThreads.begin(), activeThreads.end(), tid);
701
702    DPRINTF(O3CPU, "[tid:%i]: Calling deactivate thread.\n", tid);
703
704    if (thread_it != activeThreads.end()) {
705        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
706                tid);
707        activeThreads.erase(thread_it);
708    }
709}
710
711template <class Impl>
712Counter
713FullO3CPU<Impl>::totalInsts() const
714{
715    Counter total(0);
716
717    ThreadID size = thread.size();
718    for (ThreadID i = 0; i < size; i++)
719        total += thread[i]->numInst;
720
721    return total;
722}
723
724template <class Impl>
725Counter
726FullO3CPU<Impl>::totalOps() const
727{
728    Counter total(0);
729
730    ThreadID size = thread.size();
731    for (ThreadID i = 0; i < size; i++)
732        total += thread[i]->numOp;
733
734    return total;
735}
736
737template <class Impl>
738void
739FullO3CPU<Impl>::activateContext(ThreadID tid, int delay)
740{
741    // Needs to set each stage to running as well.
742    if (delay){
743        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to activate "
744                "on cycle %d\n", tid, curTick() + ticks(delay));
745        scheduleActivateThreadEvent(tid, delay);
746    } else {
747        activateThread(tid);
748    }
749
750    if (lastActivatedCycle < curTick()) {
751        scheduleTickEvent(delay);
752
753        // Be sure to signal that there's some activity so the CPU doesn't
754        // deschedule itself.
755        activityRec.activity();
756        fetch.wakeFromQuiesce();
757
758        quiesceCycles += tickToCycles((curTick() - 1) - lastRunningCycle);
759
760        lastActivatedCycle = curTick();
761
762        _status = Running;
763    }
764}
765
766template <class Impl>
767bool
768FullO3CPU<Impl>::scheduleDeallocateContext(ThreadID tid, bool remove,
769                                           int delay)
770{
771    // Schedule removal of thread data from CPU
772    if (delay){
773        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to deallocate "
774                "on cycle %d\n", tid, curTick() + ticks(delay));
775        scheduleDeallocateContextEvent(tid, remove, delay);
776        return false;
777    } else {
778        deactivateThread(tid);
779        if (remove)
780            removeThread(tid);
781        return true;
782    }
783}
784
785template <class Impl>
786void
787FullO3CPU<Impl>::suspendContext(ThreadID tid)
788{
789    DPRINTF(O3CPU,"[tid: %i]: Suspending Thread Context.\n", tid);
790    bool deallocated = scheduleDeallocateContext(tid, false, 1);
791    // If this was the last thread then unschedule the tick event.
792    if ((activeThreads.size() == 1 && !deallocated) ||
793        activeThreads.size() == 0)
794        unscheduleTickEvent();
795
796    DPRINTF(Quiesce, "Suspending Context\n");
797    lastRunningCycle = curTick();
798    _status = Idle;
799}
800
801template <class Impl>
802void
803FullO3CPU<Impl>::haltContext(ThreadID tid)
804{
805    //For now, this is the same as deallocate
806    DPRINTF(O3CPU,"[tid:%i]: Halt Context called. Deallocating", tid);
807    scheduleDeallocateContext(tid, true, 1);
808}
809
810template <class Impl>
811void
812FullO3CPU<Impl>::insertThread(ThreadID tid)
813{
814    DPRINTF(O3CPU,"[tid:%i] Initializing thread into CPU");
815    // Will change now that the PC and thread state is internal to the CPU
816    // and not in the ThreadContext.
817    ThreadContext *src_tc;
818    if (FullSystem)
819        src_tc = system->threadContexts[tid];
820    else
821        src_tc = tcBase(tid);
822
823    //Bind Int Regs to Rename Map
824    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
825        PhysRegIndex phys_reg = freeList.getIntReg();
826
827        renameMap[tid].setEntry(ireg,phys_reg);
828        scoreboard.setReg(phys_reg);
829    }
830
831    //Bind Float Regs to Rename Map
832    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
833        PhysRegIndex phys_reg = freeList.getFloatReg();
834
835        renameMap[tid].setEntry(freg,phys_reg);
836        scoreboard.setReg(phys_reg);
837    }
838
839    //Copy Thread Data Into RegFile
840    //this->copyFromTC(tid);
841
842    //Set PC/NPC/NNPC
843    pcState(src_tc->pcState(), tid);
844
845    src_tc->setStatus(ThreadContext::Active);
846
847    activateContext(tid,1);
848
849    //Reset ROB/IQ/LSQ Entries
850    commit.rob->resetEntries();
851    iew.resetEntries();
852}
853
854template <class Impl>
855void
856FullO3CPU<Impl>::removeThread(ThreadID tid)
857{
858    DPRINTF(O3CPU,"[tid:%i] Removing thread context from CPU.\n", tid);
859
860    // Copy Thread Data From RegFile
861    // If thread is suspended, it might be re-allocated
862    // this->copyToTC(tid);
863
864
865    // @todo: 2-27-2008: Fix how we free up rename mappings
866    // here to alleviate the case for double-freeing registers
867    // in SMT workloads.
868
869    // Unbind Int Regs from Rename Map
870    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
871        PhysRegIndex phys_reg = renameMap[tid].lookup(ireg);
872
873        scoreboard.unsetReg(phys_reg);
874        freeList.addReg(phys_reg);
875    }
876
877    // Unbind Float Regs from Rename Map
878    for (int freg = TheISA::NumIntRegs; freg < TheISA::NumFloatRegs; freg++) {
879        PhysRegIndex phys_reg = renameMap[tid].lookup(freg);
880
881        scoreboard.unsetReg(phys_reg);
882        freeList.addReg(phys_reg);
883    }
884
885    // Squash Throughout Pipeline
886    DynInstPtr inst = commit.rob->readHeadInst(tid);
887    InstSeqNum squash_seq_num = inst->seqNum;
888    fetch.squash(0, squash_seq_num, inst, tid);
889    decode.squash(tid);
890    rename.squash(squash_seq_num, tid);
891    iew.squash(tid);
892    iew.ldstQueue.squash(squash_seq_num, tid);
893    commit.rob->squash(squash_seq_num, tid);
894
895
896    assert(iew.instQueue.getCount(tid) == 0);
897    assert(iew.ldstQueue.getCount(tid) == 0);
898
899    // Reset ROB/IQ/LSQ Entries
900
901    // Commented out for now.  This should be possible to do by
902    // telling all the pipeline stages to drain first, and then
903    // checking until the drain completes.  Once the pipeline is
904    // drained, call resetEntries(). - 10-09-06 ktlim
905/*
906    if (activeThreads.size() >= 1) {
907        commit.rob->resetEntries();
908        iew.resetEntries();
909    }
910*/
911}
912
913
914template <class Impl>
915void
916FullO3CPU<Impl>::activateWhenReady(ThreadID tid)
917{
918    DPRINTF(O3CPU,"[tid:%i]: Checking if resources are available for incoming"
919            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
920            tid);
921
922    bool ready = true;
923
924    if (freeList.numFreeIntRegs() >= TheISA::NumIntRegs) {
925        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
926                "Phys. Int. Regs.\n",
927                tid);
928        ready = false;
929    } else if (freeList.numFreeFloatRegs() >= TheISA::NumFloatRegs) {
930        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
931                "Phys. Float. Regs.\n",
932                tid);
933        ready = false;
934    } else if (commit.rob->numFreeEntries() >=
935               commit.rob->entryAmount(activeThreads.size() + 1)) {
936        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
937                "ROB entries.\n",
938                tid);
939        ready = false;
940    } else if (iew.instQueue.numFreeEntries() >=
941               iew.instQueue.entryAmount(activeThreads.size() + 1)) {
942        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
943                "IQ entries.\n",
944                tid);
945        ready = false;
946    } else if (iew.ldstQueue.numFreeEntries() >=
947               iew.ldstQueue.entryAmount(activeThreads.size() + 1)) {
948        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
949                "LSQ entries.\n",
950                tid);
951        ready = false;
952    }
953
954    if (ready) {
955        insertThread(tid);
956
957        contextSwitch = false;
958
959        cpuWaitList.remove(tid);
960    } else {
961        suspendContext(tid);
962
963        //blocks fetch
964        contextSwitch = true;
965
966        //@todo: dont always add to waitlist
967        //do waitlist
968        cpuWaitList.push_back(tid);
969    }
970}
971
972template <class Impl>
973Fault
974FullO3CPU<Impl>::hwrei(ThreadID tid)
975{
976#if THE_ISA == ALPHA_ISA
977    // Need to clear the lock flag upon returning from an interrupt.
978    this->setMiscRegNoEffect(AlphaISA::MISCREG_LOCKFLAG, false, tid);
979
980    this->thread[tid]->kernelStats->hwrei();
981
982    // FIXME: XXX check for interrupts? XXX
983#endif
984    return NoFault;
985}
986
987template <class Impl>
988bool
989FullO3CPU<Impl>::simPalCheck(int palFunc, ThreadID tid)
990{
991#if THE_ISA == ALPHA_ISA
992    if (this->thread[tid]->kernelStats)
993        this->thread[tid]->kernelStats->callpal(palFunc,
994                                                this->threadContexts[tid]);
995
996    switch (palFunc) {
997      case PAL::halt:
998        halt();
999        if (--System::numSystemsRunning == 0)
1000            exitSimLoop("all cpus halted");
1001        break;
1002
1003      case PAL::bpt:
1004      case PAL::bugchk:
1005        if (this->system->breakpoint())
1006            return false;
1007        break;
1008    }
1009#endif
1010    return true;
1011}
1012
1013template <class Impl>
1014Fault
1015FullO3CPU<Impl>::getInterrupts()
1016{
1017    // Check if there are any outstanding interrupts
1018    return this->interrupts->getInterrupt(this->threadContexts[0]);
1019}
1020
1021template <class Impl>
1022void
1023FullO3CPU<Impl>::processInterrupts(Fault interrupt)
1024{
1025    // Check for interrupts here.  For now can copy the code that
1026    // exists within isa_fullsys_traits.hh.  Also assume that thread 0
1027    // is the one that handles the interrupts.
1028    // @todo: Possibly consolidate the interrupt checking code.
1029    // @todo: Allow other threads to handle interrupts.
1030
1031    assert(interrupt != NoFault);
1032    this->interrupts->updateIntrInfo(this->threadContexts[0]);
1033
1034    DPRINTF(O3CPU, "Interrupt %s being handled\n", interrupt->name());
1035    this->trap(interrupt, 0, NULL);
1036}
1037
1038template <class Impl>
1039void
1040FullO3CPU<Impl>::trap(Fault fault, ThreadID tid, StaticInstPtr inst)
1041{
1042    // Pass the thread's TC into the invoke method.
1043    fault->invoke(this->threadContexts[tid], inst);
1044}
1045
1046template <class Impl>
1047void
1048FullO3CPU<Impl>::syscall(int64_t callnum, ThreadID tid)
1049{
1050    DPRINTF(O3CPU, "[tid:%i] Executing syscall().\n\n", tid);
1051
1052    DPRINTF(Activity,"Activity: syscall() called.\n");
1053
1054    // Temporarily increase this by one to account for the syscall
1055    // instruction.
1056    ++(this->thread[tid]->funcExeInst);
1057
1058    // Execute the actual syscall.
1059    this->thread[tid]->syscall(callnum);
1060
1061    // Decrease funcExeInst by one as the normal commit will handle
1062    // incrementing it.
1063    --(this->thread[tid]->funcExeInst);
1064}
1065
1066template <class Impl>
1067void
1068FullO3CPU<Impl>::serialize(std::ostream &os)
1069{
1070    SimObject::State so_state = SimObject::getState();
1071    SERIALIZE_ENUM(so_state);
1072    BaseCPU::serialize(os);
1073    nameOut(os, csprintf("%s.tickEvent", name()));
1074    tickEvent.serialize(os);
1075
1076    // Use SimpleThread's ability to checkpoint to make it easier to
1077    // write out the registers.  Also make this static so it doesn't
1078    // get instantiated multiple times (causes a panic in statistics).
1079    static SimpleThread temp;
1080
1081    ThreadID size = thread.size();
1082    for (ThreadID i = 0; i < size; i++) {
1083        nameOut(os, csprintf("%s.xc.%i", name(), i));
1084        temp.copyTC(thread[i]->getTC());
1085        temp.serialize(os);
1086    }
1087}
1088
1089template <class Impl>
1090void
1091FullO3CPU<Impl>::unserialize(Checkpoint *cp, const std::string &section)
1092{
1093    SimObject::State so_state;
1094    UNSERIALIZE_ENUM(so_state);
1095    BaseCPU::unserialize(cp, section);
1096    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));
1097
1098    // Use SimpleThread's ability to checkpoint to make it easier to
1099    // read in the registers.  Also make this static so it doesn't
1100    // get instantiated multiple times (causes a panic in statistics).
1101    static SimpleThread temp;
1102
1103    ThreadID size = thread.size();
1104    for (ThreadID i = 0; i < size; i++) {
1105        temp.copyTC(thread[i]->getTC());
1106        temp.unserialize(cp, csprintf("%s.xc.%i", section, i));
1107        thread[i]->getTC()->copyArchRegs(temp.getTC());
1108    }
1109}
1110
1111template <class Impl>
1112unsigned int
1113FullO3CPU<Impl>::drain(Event *drain_event)
1114{
1115    DPRINTF(O3CPU, "Switching out\n");
1116
1117    // If the CPU isn't doing anything, then return immediately.
1118    if (_status == Idle || _status == SwitchedOut) {
1119        return 0;
1120    }
1121
1122    drainCount = 0;
1123    fetch.drain();
1124    decode.drain();
1125    rename.drain();
1126    iew.drain();
1127    commit.drain();
1128
1129    // Wake the CPU and record activity so everything can drain out if
1130    // the CPU was not able to immediately drain.
1131    if (getState() != SimObject::Drained) {
1132        // A bit of a hack...set the drainEvent after all the drain()
1133        // calls have been made, that way if all of the stages drain
1134        // immediately, the signalDrained() function knows not to call
1135        // process on the drain event.
1136        drainEvent = drain_event;
1137
1138        wakeCPU();
1139        activityRec.activity();
1140
1141        return 1;
1142    } else {
1143        return 0;
1144    }
1145}
1146
1147template <class Impl>
1148void
1149FullO3CPU<Impl>::resume()
1150{
1151    fetch.resume();
1152    decode.resume();
1153    rename.resume();
1154    iew.resume();
1155    commit.resume();
1156
1157    changeState(SimObject::Running);
1158
1159    if (_status == SwitchedOut || _status == Idle)
1160        return;
1161
1162    assert(system->getMemoryMode() == Enums::timing);
1163
1164    if (!tickEvent.scheduled())
1165        schedule(tickEvent, nextCycle());
1166    _status = Running;
1167}
1168
1169template <class Impl>
1170void
1171FullO3CPU<Impl>::signalDrained()
1172{
1173    if (++drainCount == NumStages) {
1174        if (tickEvent.scheduled())
1175            tickEvent.squash();
1176
1177        changeState(SimObject::Drained);
1178
1179        BaseCPU::switchOut();
1180
1181        if (drainEvent) {
1182            drainEvent->process();
1183            drainEvent = NULL;
1184        }
1185    }
1186    assert(drainCount <= 5);
1187}
1188
1189template <class Impl>
1190void
1191FullO3CPU<Impl>::switchOut()
1192{
1193    fetch.switchOut();
1194    rename.switchOut();
1195    iew.switchOut();
1196    commit.switchOut();
1197    instList.clear();
1198    while (!removeList.empty()) {
1199        removeList.pop();
1200    }
1201
1202    _status = SwitchedOut;
1203
1204    if (checker)
1205        checker->switchOut();
1206
1207    if (tickEvent.scheduled())
1208        tickEvent.squash();
1209}
1210
1211template <class Impl>
1212void
1213FullO3CPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
1214{
1215    // Flush out any old data from the time buffers.
1216    for (int i = 0; i < timeBuffer.getSize(); ++i) {
1217        timeBuffer.advance();
1218        fetchQueue.advance();
1219        decodeQueue.advance();
1220        renameQueue.advance();
1221        iewQueue.advance();
1222    }
1223
1224    activityRec.reset();
1225
1226    BaseCPU::takeOverFrom(oldCPU);
1227
1228    fetch.takeOverFrom();
1229    decode.takeOverFrom();
1230    rename.takeOverFrom();
1231    iew.takeOverFrom();
1232    commit.takeOverFrom();
1233
1234    assert(!tickEvent.scheduled() || tickEvent.squashed());
1235
1236    // @todo: Figure out how to properly select the tid to put onto
1237    // the active threads list.
1238    ThreadID tid = 0;
1239
1240    list<ThreadID>::iterator isActive =
1241        std::find(activeThreads.begin(), activeThreads.end(), tid);
1242
1243    if (isActive == activeThreads.end()) {
1244        //May Need to Re-code this if the delay variable is the delay
1245        //needed for thread to activate
1246        DPRINTF(O3CPU, "Adding Thread %i to active threads list\n",
1247                tid);
1248
1249        activeThreads.push_back(tid);
1250    }
1251
1252    // Set all statuses to active, schedule the CPU's tick event.
1253    // @todo: Fix up statuses so this is handled properly
1254    ThreadID size = threadContexts.size();
1255    for (ThreadID i = 0; i < size; ++i) {
1256        ThreadContext *tc = threadContexts[i];
1257        if (tc->status() == ThreadContext::Active && _status != Running) {
1258            _status = Running;
1259            reschedule(tickEvent, nextCycle(), true);
1260        }
1261    }
1262    if (!tickEvent.scheduled())
1263        schedule(tickEvent, nextCycle());
1264
1265    lastRunningCycle = curTick();
1266}
1267
1268template <class Impl>
1269TheISA::MiscReg
1270FullO3CPU<Impl>::readMiscRegNoEffect(int misc_reg, ThreadID tid)
1271{
1272    return this->isa[tid].readMiscRegNoEffect(misc_reg);
1273}
1274
1275template <class Impl>
1276TheISA::MiscReg
1277FullO3CPU<Impl>::readMiscReg(int misc_reg, ThreadID tid)
1278{
1279    miscRegfileReads++;
1280    return this->isa[tid].readMiscReg(misc_reg, tcBase(tid));
1281}
1282
1283template <class Impl>
1284void
1285FullO3CPU<Impl>::setMiscRegNoEffect(int misc_reg,
1286        const TheISA::MiscReg &val, ThreadID tid)
1287{
1288    this->isa[tid].setMiscRegNoEffect(misc_reg, val);
1289}
1290
1291template <class Impl>
1292void
1293FullO3CPU<Impl>::setMiscReg(int misc_reg,
1294        const TheISA::MiscReg &val, ThreadID tid)
1295{
1296    miscRegfileWrites++;
1297    this->isa[tid].setMiscReg(misc_reg, val, tcBase(tid));
1298}
1299
1300template <class Impl>
1301uint64_t
1302FullO3CPU<Impl>::readIntReg(int reg_idx)
1303{
1304    intRegfileReads++;
1305    return regFile.readIntReg(reg_idx);
1306}
1307
1308template <class Impl>
1309FloatReg
1310FullO3CPU<Impl>::readFloatReg(int reg_idx)
1311{
1312    fpRegfileReads++;
1313    return regFile.readFloatReg(reg_idx);
1314}
1315
1316template <class Impl>
1317FloatRegBits
1318FullO3CPU<Impl>::readFloatRegBits(int reg_idx)
1319{
1320    fpRegfileReads++;
1321    return regFile.readFloatRegBits(reg_idx);
1322}
1323
1324template <class Impl>
1325void
1326FullO3CPU<Impl>::setIntReg(int reg_idx, uint64_t val)
1327{
1328    intRegfileWrites++;
1329    regFile.setIntReg(reg_idx, val);
1330}
1331
1332template <class Impl>
1333void
1334FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val)
1335{
1336    fpRegfileWrites++;
1337    regFile.setFloatReg(reg_idx, val);
1338}
1339
1340template <class Impl>
1341void
1342FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val)
1343{
1344    fpRegfileWrites++;
1345    regFile.setFloatRegBits(reg_idx, val);
1346}
1347
1348template <class Impl>
1349uint64_t
1350FullO3CPU<Impl>::readArchIntReg(int reg_idx, ThreadID tid)
1351{
1352    intRegfileReads++;
1353    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1354
1355    return regFile.readIntReg(phys_reg);
1356}
1357
1358template <class Impl>
1359float
1360FullO3CPU<Impl>::readArchFloatReg(int reg_idx, ThreadID tid)
1361{
1362    fpRegfileReads++;
1363    int idx = reg_idx + TheISA::NumIntRegs;
1364    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1365
1366    return regFile.readFloatReg(phys_reg);
1367}
1368
1369template <class Impl>
1370uint64_t
1371FullO3CPU<Impl>::readArchFloatRegInt(int reg_idx, ThreadID tid)
1372{
1373    fpRegfileReads++;
1374    int idx = reg_idx + TheISA::NumIntRegs;
1375    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1376
1377    return regFile.readFloatRegBits(phys_reg);
1378}
1379
1380template <class Impl>
1381void
1382FullO3CPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, ThreadID tid)
1383{
1384    intRegfileWrites++;
1385    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1386
1387    regFile.setIntReg(phys_reg, val);
1388}
1389
1390template <class Impl>
1391void
1392FullO3CPU<Impl>::setArchFloatReg(int reg_idx, float val, ThreadID tid)
1393{
1394    fpRegfileWrites++;
1395    int idx = reg_idx + TheISA::NumIntRegs;
1396    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1397
1398    regFile.setFloatReg(phys_reg, val);
1399}
1400
1401template <class Impl>
1402void
1403FullO3CPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, ThreadID tid)
1404{
1405    fpRegfileWrites++;
1406    int idx = reg_idx + TheISA::NumIntRegs;
1407    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1408
1409    regFile.setFloatRegBits(phys_reg, val);
1410}
1411
1412template <class Impl>
1413TheISA::PCState
1414FullO3CPU<Impl>::pcState(ThreadID tid)
1415{
1416    return commit.pcState(tid);
1417}
1418
1419template <class Impl>
1420void
1421FullO3CPU<Impl>::pcState(const TheISA::PCState &val, ThreadID tid)
1422{
1423    commit.pcState(val, tid);
1424}
1425
1426template <class Impl>
1427Addr
1428FullO3CPU<Impl>::instAddr(ThreadID tid)
1429{
1430    return commit.instAddr(tid);
1431}
1432
1433template <class Impl>
1434Addr
1435FullO3CPU<Impl>::nextInstAddr(ThreadID tid)
1436{
1437    return commit.nextInstAddr(tid);
1438}
1439
1440template <class Impl>
1441MicroPC
1442FullO3CPU<Impl>::microPC(ThreadID tid)
1443{
1444    return commit.microPC(tid);
1445}
1446
1447template <class Impl>
1448void
1449FullO3CPU<Impl>::squashFromTC(ThreadID tid)
1450{
1451    this->thread[tid]->inSyscall = true;
1452    this->commit.generateTCEvent(tid);
1453}
1454
1455template <class Impl>
1456typename FullO3CPU<Impl>::ListIt
1457FullO3CPU<Impl>::addInst(DynInstPtr &inst)
1458{
1459    instList.push_back(inst);
1460
1461    return --(instList.end());
1462}
1463
1464template <class Impl>
1465void
1466FullO3CPU<Impl>::instDone(ThreadID tid, DynInstPtr &inst)
1467{
1468    // Keep an instruction count.
1469    if (!inst->isMicroop() || inst->isLastMicroop()) {
1470        thread[tid]->numInst++;
1471        thread[tid]->numInsts++;
1472        committedInsts[tid]++;
1473        totalCommittedInsts++;
1474    }
1475    thread[tid]->numOp++;
1476    thread[tid]->numOps++;
1477    committedOps[tid]++;
1478
1479    system->totalNumInsts++;
1480    // Check for instruction-count-based events.
1481    comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1482    system->instEventQueue.serviceEvents(system->totalNumInsts);
1483}
1484
1485template <class Impl>
1486void
1487FullO3CPU<Impl>::removeFrontInst(DynInstPtr &inst)
1488{
1489    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %s "
1490            "[sn:%lli]\n",
1491            inst->threadNumber, inst->pcState(), inst->seqNum);
1492
1493    removeInstsThisCycle = true;
1494
1495    // Remove the front instruction.
1496    removeList.push(inst->getInstListIt());
1497}
1498
1499template <class Impl>
1500void
1501FullO3CPU<Impl>::removeInstsNotInROB(ThreadID tid)
1502{
1503    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
1504            " list.\n", tid);
1505
1506    ListIt end_it;
1507
1508    bool rob_empty = false;
1509
1510    if (instList.empty()) {
1511        return;
1512    } else if (rob.isEmpty(/*tid*/)) {
1513        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
1514        end_it = instList.begin();
1515        rob_empty = true;
1516    } else {
1517        end_it = (rob.readTailInst(tid))->getInstListIt();
1518        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
1519    }
1520
1521    removeInstsThisCycle = true;
1522
1523    ListIt inst_it = instList.end();
1524
1525    inst_it--;
1526
1527    // Walk through the instruction list, removing any instructions
1528    // that were inserted after the given instruction iterator, end_it.
1529    while (inst_it != end_it) {
1530        assert(!instList.empty());
1531
1532        squashInstIt(inst_it, tid);
1533
1534        inst_it--;
1535    }
1536
1537    // If the ROB was empty, then we actually need to remove the first
1538    // instruction as well.
1539    if (rob_empty) {
1540        squashInstIt(inst_it, tid);
1541    }
1542}
1543
1544template <class Impl>
1545void
1546FullO3CPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid)
1547{
1548    assert(!instList.empty());
1549
1550    removeInstsThisCycle = true;
1551
1552    ListIt inst_iter = instList.end();
1553
1554    inst_iter--;
1555
1556    DPRINTF(O3CPU, "Deleting instructions from instruction "
1557            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1558            tid, seq_num, (*inst_iter)->seqNum);
1559
1560    while ((*inst_iter)->seqNum > seq_num) {
1561
1562        bool break_loop = (inst_iter == instList.begin());
1563
1564        squashInstIt(inst_iter, tid);
1565
1566        inst_iter--;
1567
1568        if (break_loop)
1569            break;
1570    }
1571}
1572
1573template <class Impl>
1574inline void
1575FullO3CPU<Impl>::squashInstIt(const ListIt &instIt, ThreadID tid)
1576{
1577    if ((*instIt)->threadNumber == tid) {
1578        DPRINTF(O3CPU, "Squashing instruction, "
1579                "[tid:%i] [sn:%lli] PC %s\n",
1580                (*instIt)->threadNumber,
1581                (*instIt)->seqNum,
1582                (*instIt)->pcState());
1583
1584        // Mark it as squashed.
1585        (*instIt)->setSquashed();
1586
1587        // @todo: Formulate a consistent method for deleting
1588        // instructions from the instruction list
1589        // Remove the instruction from the list.
1590        removeList.push(instIt);
1591    }
1592}
1593
1594template <class Impl>
1595void
1596FullO3CPU<Impl>::cleanUpRemovedInsts()
1597{
1598    while (!removeList.empty()) {
1599        DPRINTF(O3CPU, "Removing instruction, "
1600                "[tid:%i] [sn:%lli] PC %s\n",
1601                (*removeList.front())->threadNumber,
1602                (*removeList.front())->seqNum,
1603                (*removeList.front())->pcState());
1604
1605        instList.erase(removeList.front());
1606
1607        removeList.pop();
1608    }
1609
1610    removeInstsThisCycle = false;
1611}
1612/*
1613template <class Impl>
1614void
1615FullO3CPU<Impl>::removeAllInsts()
1616{
1617    instList.clear();
1618}
1619*/
1620template <class Impl>
1621void
1622FullO3CPU<Impl>::dumpInsts()
1623{
1624    int num = 0;
1625
1626    ListIt inst_list_it = instList.begin();
1627
1628    cprintf("Dumping Instruction List\n");
1629
1630    while (inst_list_it != instList.end()) {
1631        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1632                "Squashed:%i\n\n",
1633                num, (*inst_list_it)->instAddr(), (*inst_list_it)->threadNumber,
1634                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1635                (*inst_list_it)->isSquashed());
1636        inst_list_it++;
1637        ++num;
1638    }
1639}
1640/*
1641template <class Impl>
1642void
1643FullO3CPU<Impl>::wakeDependents(DynInstPtr &inst)
1644{
1645    iew.wakeDependents(inst);
1646}
1647*/
1648template <class Impl>
1649void
1650FullO3CPU<Impl>::wakeCPU()
1651{
1652    if (activityRec.active() || tickEvent.scheduled()) {
1653        DPRINTF(Activity, "CPU already running.\n");
1654        return;
1655    }
1656
1657    DPRINTF(Activity, "Waking up CPU\n");
1658
1659    idleCycles += tickToCycles((curTick() - 1) - lastRunningCycle);
1660    numCycles += tickToCycles((curTick() - 1) - lastRunningCycle);
1661
1662    schedule(tickEvent, nextCycle());
1663}
1664
1665template <class Impl>
1666void
1667FullO3CPU<Impl>::wakeup()
1668{
1669    if (this->thread[0]->status() != ThreadContext::Suspended)
1670        return;
1671
1672    this->wakeCPU();
1673
1674    DPRINTF(Quiesce, "Suspended Processor woken\n");
1675    this->threadContexts[0]->activate();
1676}
1677
1678template <class Impl>
1679ThreadID
1680FullO3CPU<Impl>::getFreeTid()
1681{
1682    for (ThreadID tid = 0; tid < numThreads; tid++) {
1683        if (!tids[tid]) {
1684            tids[tid] = true;
1685            return tid;
1686        }
1687    }
1688
1689    return InvalidThreadID;
1690}
1691
1692template <class Impl>
1693void
1694FullO3CPU<Impl>::doContextSwitch()
1695{
1696    if (contextSwitch) {
1697
1698        //ADD CODE TO DEACTIVE THREAD HERE (???)
1699
1700        ThreadID size = cpuWaitList.size();
1701        for (ThreadID tid = 0; tid < size; tid++) {
1702            activateWhenReady(tid);
1703        }
1704
1705        if (cpuWaitList.size() == 0)
1706            contextSwitch = true;
1707    }
1708}
1709
1710template <class Impl>
1711void
1712FullO3CPU<Impl>::updateThreadPriority()
1713{
1714    if (activeThreads.size() > 1) {
1715        //DEFAULT TO ROUND ROBIN SCHEME
1716        //e.g. Move highest priority to end of thread list
1717        list<ThreadID>::iterator list_begin = activeThreads.begin();
1718
1719        unsigned high_thread = *list_begin;
1720
1721        activeThreads.erase(list_begin);
1722
1723        activeThreads.push_back(high_thread);
1724    }
1725}
1726
1727// Forward declaration of FullO3CPU.
1728template class FullO3CPU<O3CPUImpl>;
1729