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