cpu.cc revision 8948:e95ee70f876c
1/*
2 * Copyright (c) 2011-2012 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    assert(pkt->isResponse());
93    DPRINTF(O3CPU, "Fetch unit received timing\n");
94    // We shouldn't ever get a block in ownership state
95    assert(!(pkt->memInhibitAsserted() && !pkt->sharedAsserted()));
96    fetch->processCacheCompletion(pkt);
97
98    return true;
99}
100
101template<class Impl>
102void
103FullO3CPU<Impl>::IcachePort::recvRetry()
104{
105    fetch->recvRetry();
106}
107
108template <class Impl>
109bool
110FullO3CPU<Impl>::DcachePort::recvTiming(PacketPtr pkt)
111{
112    assert(pkt->isResponse());
113    return lsq->recvTiming(pkt);
114}
115
116template <class Impl>
117bool
118FullO3CPU<Impl>::DcachePort::recvTimingSnoop(PacketPtr pkt)
119{
120    assert(pkt->isRequest());
121    return lsq->recvTimingSnoop(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 (params->checker) {
270        BaseCPU *temp_checker = params->checker;
271        checker = dynamic_cast<Checker<Impl> *>(temp_checker);
272        checker->setIcachePort(&icachePort);
273        checker->setSystem(params->system);
274    } else {
275        checker = NULL;
276    }
277
278    if (!FullSystem) {
279        thread.resize(numThreads);
280        tids.resize(numThreads);
281    }
282
283    // The stages also need their CPU pointer setup.  However this
284    // must be done at the upper level CPU because they have pointers
285    // to the upper level CPU, and not this FullO3CPU.
286
287    // Set up Pointers to the activeThreads list for each stage
288    fetch.setActiveThreads(&activeThreads);
289    decode.setActiveThreads(&activeThreads);
290    rename.setActiveThreads(&activeThreads);
291    iew.setActiveThreads(&activeThreads);
292    commit.setActiveThreads(&activeThreads);
293
294    // Give each of the stages the time buffer they will use.
295    fetch.setTimeBuffer(&timeBuffer);
296    decode.setTimeBuffer(&timeBuffer);
297    rename.setTimeBuffer(&timeBuffer);
298    iew.setTimeBuffer(&timeBuffer);
299    commit.setTimeBuffer(&timeBuffer);
300
301    // Also setup each of the stages' queues.
302    fetch.setFetchQueue(&fetchQueue);
303    decode.setFetchQueue(&fetchQueue);
304    commit.setFetchQueue(&fetchQueue);
305    decode.setDecodeQueue(&decodeQueue);
306    rename.setDecodeQueue(&decodeQueue);
307    rename.setRenameQueue(&renameQueue);
308    iew.setRenameQueue(&renameQueue);
309    iew.setIEWQueue(&iewQueue);
310    commit.setIEWQueue(&iewQueue);
311    commit.setRenameQueue(&renameQueue);
312
313    commit.setIEWStage(&iew);
314    rename.setIEWStage(&iew);
315    rename.setCommitStage(&commit);
316
317    ThreadID active_threads;
318    if (FullSystem) {
319        active_threads = 1;
320    } else {
321        active_threads = params->workload.size();
322
323        if (active_threads > Impl::MaxThreads) {
324            panic("Workload Size too large. Increase the 'MaxThreads' "
325                  "constant in your O3CPU impl. file (e.g. o3/alpha/impl.hh) "
326                  "or edit your workload size.");
327        }
328    }
329
330    //Make Sure That this a Valid Architeture
331    assert(params->numPhysIntRegs   >= numThreads * TheISA::NumIntRegs);
332    assert(params->numPhysFloatRegs >= numThreads * TheISA::NumFloatRegs);
333
334    rename.setScoreboard(&scoreboard);
335    iew.setScoreboard(&scoreboard);
336
337    // Setup the rename map for whichever stages need it.
338    PhysRegIndex lreg_idx = 0;
339    PhysRegIndex freg_idx = params->numPhysIntRegs; //Index to 1 after int regs
340
341    for (ThreadID tid = 0; tid < numThreads; tid++) {
342        bool bindRegs = (tid <= active_threads - 1);
343
344        commitRenameMap[tid].init(TheISA::NumIntRegs,
345                                  params->numPhysIntRegs,
346                                  lreg_idx,            //Index for Logical. Regs
347
348                                  TheISA::NumFloatRegs,
349                                  params->numPhysFloatRegs,
350                                  freg_idx,            //Index for Float Regs
351
352                                  TheISA::NumMiscRegs,
353
354                                  TheISA::ZeroReg,
355                                  TheISA::ZeroReg,
356
357                                  tid,
358                                  false);
359
360        renameMap[tid].init(TheISA::NumIntRegs,
361                            params->numPhysIntRegs,
362                            lreg_idx,                  //Index for Logical. Regs
363
364                            TheISA::NumFloatRegs,
365                            params->numPhysFloatRegs,
366                            freg_idx,                  //Index for Float Regs
367
368                            TheISA::NumMiscRegs,
369
370                            TheISA::ZeroReg,
371                            TheISA::ZeroReg,
372
373                            tid,
374                            bindRegs);
375
376        activateThreadEvent[tid].init(tid, this);
377        deallocateContextEvent[tid].init(tid, this);
378    }
379
380    rename.setRenameMap(renameMap);
381    commit.setRenameMap(commitRenameMap);
382
383    // Give renameMap & rename stage access to the freeList;
384    for (ThreadID tid = 0; tid < numThreads; tid++)
385        renameMap[tid].setFreeList(&freeList);
386    rename.setFreeList(&freeList);
387
388    // Setup the ROB for whichever stages need it.
389    commit.setROB(&rob);
390
391    lastRunningCycle = curTick();
392
393    lastActivatedCycle = -1;
394#if 0
395    // Give renameMap & rename stage access to the freeList;
396    for (ThreadID tid = 0; tid < numThreads; tid++)
397        globalSeqNum[tid] = 1;
398#endif
399
400    contextSwitch = false;
401    DPRINTF(O3CPU, "Creating O3CPU object.\n");
402
403    // Setup any thread state.
404    this->thread.resize(this->numThreads);
405
406    for (ThreadID tid = 0; tid < this->numThreads; ++tid) {
407        if (FullSystem) {
408            // SMT is not supported in FS mode yet.
409            assert(this->numThreads == 1);
410            this->thread[tid] = new Thread(this, 0, NULL);
411        } else {
412            if (tid < params->workload.size()) {
413                DPRINTF(O3CPU, "Workload[%i] process is %#x",
414                        tid, this->thread[tid]);
415                this->thread[tid] = new typename FullO3CPU<Impl>::Thread(
416                        (typename Impl::O3CPU *)(this),
417                        tid, params->workload[tid]);
418
419                //usedTids[tid] = true;
420                //threadMap[tid] = tid;
421            } else {
422                //Allocate Empty thread so M5 can use later
423                //when scheduling threads to CPU
424                Process* dummy_proc = NULL;
425
426                this->thread[tid] = new typename FullO3CPU<Impl>::Thread(
427                        (typename Impl::O3CPU *)(this),
428                        tid, dummy_proc);
429                //usedTids[tid] = false;
430            }
431        }
432
433        ThreadContext *tc;
434
435        // Setup the TC that will serve as the interface to the threads/CPU.
436        O3ThreadContext<Impl> *o3_tc = new O3ThreadContext<Impl>;
437
438        tc = o3_tc;
439
440        // If we're using a checker, then the TC should be the
441        // CheckerThreadContext.
442        if (params->checker) {
443            tc = new CheckerThreadContext<O3ThreadContext<Impl> >(
444                o3_tc, this->checker);
445        }
446
447        o3_tc->cpu = (typename Impl::O3CPU *)(this);
448        assert(o3_tc->cpu);
449        o3_tc->thread = this->thread[tid];
450
451        if (FullSystem) {
452            // Setup quiesce event.
453            this->thread[tid]->quiesceEvent = new EndQuiesceEvent(tc);
454        }
455        // Give the thread the TC.
456        this->thread[tid]->tc = tc;
457
458        // Add the TC to the CPU's list of TC's.
459        this->threadContexts.push_back(tc);
460    }
461
462    // FullO3CPU always requires an interrupt controller.
463    if (!params->defer_registration && !interrupts) {
464        fatal("FullO3CPU %s has no interrupt controller.\n"
465              "Ensure createInterruptController() is called.\n", name());
466    }
467
468    for (ThreadID tid = 0; tid < this->numThreads; tid++)
469        this->thread[tid]->setFuncExeInst(0);
470
471    lockAddr = 0;
472    lockFlag = false;
473}
474
475template <class Impl>
476FullO3CPU<Impl>::~FullO3CPU()
477{
478}
479
480template <class Impl>
481void
482FullO3CPU<Impl>::regStats()
483{
484    BaseO3CPU::regStats();
485
486    // Register any of the O3CPU's stats here.
487    timesIdled
488        .name(name() + ".timesIdled")
489        .desc("Number of times that the entire CPU went into an idle state and"
490              " unscheduled itself")
491        .prereq(timesIdled);
492
493    idleCycles
494        .name(name() + ".idleCycles")
495        .desc("Total number of cycles that the CPU has spent unscheduled due "
496              "to idling")
497        .prereq(idleCycles);
498
499    quiesceCycles
500        .name(name() + ".quiesceCycles")
501        .desc("Total number of cycles that CPU has spent quiesced or waiting "
502              "for an interrupt")
503        .prereq(quiesceCycles);
504
505    // Number of Instructions simulated
506    // --------------------------------
507    // Should probably be in Base CPU but need templated
508    // MaxThreads so put in here instead
509    committedInsts
510        .init(numThreads)
511        .name(name() + ".committedInsts")
512        .desc("Number of Instructions Simulated");
513
514    committedOps
515        .init(numThreads)
516        .name(name() + ".committedOps")
517        .desc("Number of Ops (including micro ops) Simulated");
518
519    totalCommittedInsts
520        .name(name() + ".committedInsts_total")
521        .desc("Number of Instructions Simulated");
522
523    cpi
524        .name(name() + ".cpi")
525        .desc("CPI: Cycles Per Instruction")
526        .precision(6);
527    cpi = numCycles / committedInsts;
528
529    totalCpi
530        .name(name() + ".cpi_total")
531        .desc("CPI: Total CPI of All Threads")
532        .precision(6);
533    totalCpi = numCycles / totalCommittedInsts;
534
535    ipc
536        .name(name() + ".ipc")
537        .desc("IPC: Instructions Per Cycle")
538        .precision(6);
539    ipc =  committedInsts / numCycles;
540
541    totalIpc
542        .name(name() + ".ipc_total")
543        .desc("IPC: Total IPC of All Threads")
544        .precision(6);
545    totalIpc =  totalCommittedInsts / numCycles;
546
547    this->fetch.regStats();
548    this->decode.regStats();
549    this->rename.regStats();
550    this->iew.regStats();
551    this->commit.regStats();
552    this->rob.regStats();
553
554    intRegfileReads
555        .name(name() + ".int_regfile_reads")
556        .desc("number of integer regfile reads")
557        .prereq(intRegfileReads);
558
559    intRegfileWrites
560        .name(name() + ".int_regfile_writes")
561        .desc("number of integer regfile writes")
562        .prereq(intRegfileWrites);
563
564    fpRegfileReads
565        .name(name() + ".fp_regfile_reads")
566        .desc("number of floating regfile reads")
567        .prereq(fpRegfileReads);
568
569    fpRegfileWrites
570        .name(name() + ".fp_regfile_writes")
571        .desc("number of floating regfile writes")
572        .prereq(fpRegfileWrites);
573
574    miscRegfileReads
575        .name(name() + ".misc_regfile_reads")
576        .desc("number of misc regfile reads")
577        .prereq(miscRegfileReads);
578
579    miscRegfileWrites
580        .name(name() + ".misc_regfile_writes")
581        .desc("number of misc regfile writes")
582        .prereq(miscRegfileWrites);
583}
584
585template <class Impl>
586void
587FullO3CPU<Impl>::tick()
588{
589    DPRINTF(O3CPU, "\n\nFullO3CPU: Ticking main, FullO3CPU.\n");
590
591    ++numCycles;
592
593//    activity = false;
594
595    //Tick each of the stages
596    fetch.tick();
597
598    decode.tick();
599
600    rename.tick();
601
602    iew.tick();
603
604    commit.tick();
605
606    if (!FullSystem)
607        doContextSwitch();
608
609    // Now advance the time buffers
610    timeBuffer.advance();
611
612    fetchQueue.advance();
613    decodeQueue.advance();
614    renameQueue.advance();
615    iewQueue.advance();
616
617    activityRec.advance();
618
619    if (removeInstsThisCycle) {
620        cleanUpRemovedInsts();
621    }
622
623    if (!tickEvent.scheduled()) {
624        if (_status == SwitchedOut ||
625            getState() == SimObject::Drained) {
626            DPRINTF(O3CPU, "Switched out!\n");
627            // increment stat
628            lastRunningCycle = curTick();
629        } else if (!activityRec.active() || _status == Idle) {
630            DPRINTF(O3CPU, "Idle!\n");
631            lastRunningCycle = curTick();
632            timesIdled++;
633        } else {
634            schedule(tickEvent, nextCycle(curTick() + ticks(1)));
635            DPRINTF(O3CPU, "Scheduling next tick!\n");
636        }
637    }
638
639    if (!FullSystem)
640        updateThreadPriority();
641}
642
643template <class Impl>
644void
645FullO3CPU<Impl>::init()
646{
647    BaseCPU::init();
648
649    for (ThreadID tid = 0; tid < numThreads; ++tid) {
650        // Set inSyscall so that the CPU doesn't squash when initially
651        // setting up registers.
652        thread[tid]->inSyscall = true;
653        // Initialise the ThreadContext's memory proxies
654        thread[tid]->initMemProxies(thread[tid]->getTC());
655    }
656
657    // this CPU could still be unconnected if we are restoring from a
658    // checkpoint and this CPU is to be switched in, thus we can only
659    // do this here if the instruction port is actually connected, if
660    // not we have to do it as part of takeOverFrom
661    if (icachePort.isConnected())
662        fetch.setIcache();
663
664    if (FullSystem && !params()->defer_registration) {
665        for (ThreadID tid = 0; tid < numThreads; tid++) {
666            ThreadContext *src_tc = threadContexts[tid];
667            TheISA::initCPU(src_tc, src_tc->contextId());
668        }
669    }
670
671    // Clear inSyscall.
672    for (int tid = 0; tid < numThreads; ++tid)
673        thread[tid]->inSyscall = false;
674
675    // Initialize stages.
676    fetch.initStage();
677    iew.initStage();
678    rename.initStage();
679    commit.initStage();
680
681    commit.setThreads(thread);
682}
683
684template <class Impl>
685void
686FullO3CPU<Impl>::activateThread(ThreadID tid)
687{
688    list<ThreadID>::iterator isActive =
689        std::find(activeThreads.begin(), activeThreads.end(), tid);
690
691    DPRINTF(O3CPU, "[tid:%i]: Calling activate thread.\n", tid);
692
693    if (isActive == activeThreads.end()) {
694        DPRINTF(O3CPU, "[tid:%i]: Adding to active threads list\n",
695                tid);
696
697        activeThreads.push_back(tid);
698    }
699}
700
701template <class Impl>
702void
703FullO3CPU<Impl>::deactivateThread(ThreadID tid)
704{
705    //Remove From Active List, if Active
706    list<ThreadID>::iterator thread_it =
707        std::find(activeThreads.begin(), activeThreads.end(), tid);
708
709    DPRINTF(O3CPU, "[tid:%i]: Calling deactivate thread.\n", tid);
710
711    if (thread_it != activeThreads.end()) {
712        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
713                tid);
714        activeThreads.erase(thread_it);
715    }
716}
717
718template <class Impl>
719Counter
720FullO3CPU<Impl>::totalInsts() const
721{
722    Counter total(0);
723
724    ThreadID size = thread.size();
725    for (ThreadID i = 0; i < size; i++)
726        total += thread[i]->numInst;
727
728    return total;
729}
730
731template <class Impl>
732Counter
733FullO3CPU<Impl>::totalOps() const
734{
735    Counter total(0);
736
737    ThreadID size = thread.size();
738    for (ThreadID i = 0; i < size; i++)
739        total += thread[i]->numOp;
740
741    return total;
742}
743
744template <class Impl>
745void
746FullO3CPU<Impl>::activateContext(ThreadID tid, int delay)
747{
748    // Needs to set each stage to running as well.
749    if (delay){
750        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to activate "
751                "on cycle %d\n", tid, curTick() + ticks(delay));
752        scheduleActivateThreadEvent(tid, delay);
753    } else {
754        activateThread(tid);
755    }
756
757    if (lastActivatedCycle < curTick()) {
758        scheduleTickEvent(delay);
759
760        // Be sure to signal that there's some activity so the CPU doesn't
761        // deschedule itself.
762        activityRec.activity();
763        fetch.wakeFromQuiesce();
764
765        quiesceCycles += tickToCycles((curTick() - 1) - lastRunningCycle);
766
767        lastActivatedCycle = curTick();
768
769        _status = Running;
770    }
771}
772
773template <class Impl>
774bool
775FullO3CPU<Impl>::scheduleDeallocateContext(ThreadID tid, bool remove,
776                                           int delay)
777{
778    // Schedule removal of thread data from CPU
779    if (delay){
780        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to deallocate "
781                "on cycle %d\n", tid, curTick() + ticks(delay));
782        scheduleDeallocateContextEvent(tid, remove, delay);
783        return false;
784    } else {
785        deactivateThread(tid);
786        if (remove)
787            removeThread(tid);
788        return true;
789    }
790}
791
792template <class Impl>
793void
794FullO3CPU<Impl>::suspendContext(ThreadID tid)
795{
796    DPRINTF(O3CPU,"[tid: %i]: Suspending Thread Context.\n", tid);
797    bool deallocated = scheduleDeallocateContext(tid, false, 1);
798    // If this was the last thread then unschedule the tick event.
799    if ((activeThreads.size() == 1 && !deallocated) ||
800        activeThreads.size() == 0)
801        unscheduleTickEvent();
802
803    DPRINTF(Quiesce, "Suspending Context\n");
804    lastRunningCycle = curTick();
805    _status = Idle;
806}
807
808template <class Impl>
809void
810FullO3CPU<Impl>::haltContext(ThreadID tid)
811{
812    //For now, this is the same as deallocate
813    DPRINTF(O3CPU,"[tid:%i]: Halt Context called. Deallocating", tid);
814    scheduleDeallocateContext(tid, true, 1);
815}
816
817template <class Impl>
818void
819FullO3CPU<Impl>::insertThread(ThreadID tid)
820{
821    DPRINTF(O3CPU,"[tid:%i] Initializing thread into CPU");
822    // Will change now that the PC and thread state is internal to the CPU
823    // and not in the ThreadContext.
824    ThreadContext *src_tc;
825    if (FullSystem)
826        src_tc = system->threadContexts[tid];
827    else
828        src_tc = tcBase(tid);
829
830    //Bind Int Regs to Rename Map
831    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
832        PhysRegIndex phys_reg = freeList.getIntReg();
833
834        renameMap[tid].setEntry(ireg,phys_reg);
835        scoreboard.setReg(phys_reg);
836    }
837
838    //Bind Float Regs to Rename Map
839    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
840        PhysRegIndex phys_reg = freeList.getFloatReg();
841
842        renameMap[tid].setEntry(freg,phys_reg);
843        scoreboard.setReg(phys_reg);
844    }
845
846    //Copy Thread Data Into RegFile
847    //this->copyFromTC(tid);
848
849    //Set PC/NPC/NNPC
850    pcState(src_tc->pcState(), tid);
851
852    src_tc->setStatus(ThreadContext::Active);
853
854    activateContext(tid,1);
855
856    //Reset ROB/IQ/LSQ Entries
857    commit.rob->resetEntries();
858    iew.resetEntries();
859}
860
861template <class Impl>
862void
863FullO3CPU<Impl>::removeThread(ThreadID tid)
864{
865    DPRINTF(O3CPU,"[tid:%i] Removing thread context from CPU.\n", tid);
866
867    // Copy Thread Data From RegFile
868    // If thread is suspended, it might be re-allocated
869    // this->copyToTC(tid);
870
871
872    // @todo: 2-27-2008: Fix how we free up rename mappings
873    // here to alleviate the case for double-freeing registers
874    // in SMT workloads.
875
876    // Unbind Int Regs from Rename Map
877    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
878        PhysRegIndex phys_reg = renameMap[tid].lookup(ireg);
879
880        scoreboard.unsetReg(phys_reg);
881        freeList.addReg(phys_reg);
882    }
883
884    // Unbind Float Regs from Rename Map
885    for (int freg = TheISA::NumIntRegs; freg < TheISA::NumFloatRegs; freg++) {
886        PhysRegIndex phys_reg = renameMap[tid].lookup(freg);
887
888        scoreboard.unsetReg(phys_reg);
889        freeList.addReg(phys_reg);
890    }
891
892    // Squash Throughout Pipeline
893    DynInstPtr inst = commit.rob->readHeadInst(tid);
894    InstSeqNum squash_seq_num = inst->seqNum;
895    fetch.squash(0, squash_seq_num, inst, tid);
896    decode.squash(tid);
897    rename.squash(squash_seq_num, tid);
898    iew.squash(tid);
899    iew.ldstQueue.squash(squash_seq_num, tid);
900    commit.rob->squash(squash_seq_num, tid);
901
902
903    assert(iew.instQueue.getCount(tid) == 0);
904    assert(iew.ldstQueue.getCount(tid) == 0);
905
906    // Reset ROB/IQ/LSQ Entries
907
908    // Commented out for now.  This should be possible to do by
909    // telling all the pipeline stages to drain first, and then
910    // checking until the drain completes.  Once the pipeline is
911    // drained, call resetEntries(). - 10-09-06 ktlim
912/*
913    if (activeThreads.size() >= 1) {
914        commit.rob->resetEntries();
915        iew.resetEntries();
916    }
917*/
918}
919
920
921template <class Impl>
922void
923FullO3CPU<Impl>::activateWhenReady(ThreadID tid)
924{
925    DPRINTF(O3CPU,"[tid:%i]: Checking if resources are available for incoming"
926            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
927            tid);
928
929    bool ready = true;
930
931    if (freeList.numFreeIntRegs() >= TheISA::NumIntRegs) {
932        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
933                "Phys. Int. Regs.\n",
934                tid);
935        ready = false;
936    } else if (freeList.numFreeFloatRegs() >= TheISA::NumFloatRegs) {
937        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
938                "Phys. Float. Regs.\n",
939                tid);
940        ready = false;
941    } else if (commit.rob->numFreeEntries() >=
942               commit.rob->entryAmount(activeThreads.size() + 1)) {
943        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
944                "ROB entries.\n",
945                tid);
946        ready = false;
947    } else if (iew.instQueue.numFreeEntries() >=
948               iew.instQueue.entryAmount(activeThreads.size() + 1)) {
949        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
950                "IQ entries.\n",
951                tid);
952        ready = false;
953    } else if (iew.ldstQueue.numFreeEntries() >=
954               iew.ldstQueue.entryAmount(activeThreads.size() + 1)) {
955        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
956                "LSQ entries.\n",
957                tid);
958        ready = false;
959    }
960
961    if (ready) {
962        insertThread(tid);
963
964        contextSwitch = false;
965
966        cpuWaitList.remove(tid);
967    } else {
968        suspendContext(tid);
969
970        //blocks fetch
971        contextSwitch = true;
972
973        //@todo: dont always add to waitlist
974        //do waitlist
975        cpuWaitList.push_back(tid);
976    }
977}
978
979template <class Impl>
980Fault
981FullO3CPU<Impl>::hwrei(ThreadID tid)
982{
983#if THE_ISA == ALPHA_ISA
984    // Need to clear the lock flag upon returning from an interrupt.
985    this->setMiscRegNoEffect(AlphaISA::MISCREG_LOCKFLAG, false, tid);
986
987    this->thread[tid]->kernelStats->hwrei();
988
989    // FIXME: XXX check for interrupts? XXX
990#endif
991    return NoFault;
992}
993
994template <class Impl>
995bool
996FullO3CPU<Impl>::simPalCheck(int palFunc, ThreadID tid)
997{
998#if THE_ISA == ALPHA_ISA
999    if (this->thread[tid]->kernelStats)
1000        this->thread[tid]->kernelStats->callpal(palFunc,
1001                                                this->threadContexts[tid]);
1002
1003    switch (palFunc) {
1004      case PAL::halt:
1005        halt();
1006        if (--System::numSystemsRunning == 0)
1007            exitSimLoop("all cpus halted");
1008        break;
1009
1010      case PAL::bpt:
1011      case PAL::bugchk:
1012        if (this->system->breakpoint())
1013            return false;
1014        break;
1015    }
1016#endif
1017    return true;
1018}
1019
1020template <class Impl>
1021Fault
1022FullO3CPU<Impl>::getInterrupts()
1023{
1024    // Check if there are any outstanding interrupts
1025    return this->interrupts->getInterrupt(this->threadContexts[0]);
1026}
1027
1028template <class Impl>
1029void
1030FullO3CPU<Impl>::processInterrupts(Fault interrupt)
1031{
1032    // Check for interrupts here.  For now can copy the code that
1033    // exists within isa_fullsys_traits.hh.  Also assume that thread 0
1034    // is the one that handles the interrupts.
1035    // @todo: Possibly consolidate the interrupt checking code.
1036    // @todo: Allow other threads to handle interrupts.
1037
1038    assert(interrupt != NoFault);
1039    this->interrupts->updateIntrInfo(this->threadContexts[0]);
1040
1041    DPRINTF(O3CPU, "Interrupt %s being handled\n", interrupt->name());
1042    this->trap(interrupt, 0, NULL);
1043}
1044
1045template <class Impl>
1046void
1047FullO3CPU<Impl>::trap(Fault fault, ThreadID tid, StaticInstPtr inst)
1048{
1049    // Pass the thread's TC into the invoke method.
1050    fault->invoke(this->threadContexts[tid], inst);
1051}
1052
1053template <class Impl>
1054void
1055FullO3CPU<Impl>::syscall(int64_t callnum, ThreadID tid)
1056{
1057    DPRINTF(O3CPU, "[tid:%i] Executing syscall().\n\n", tid);
1058
1059    DPRINTF(Activity,"Activity: syscall() called.\n");
1060
1061    // Temporarily increase this by one to account for the syscall
1062    // instruction.
1063    ++(this->thread[tid]->funcExeInst);
1064
1065    // Execute the actual syscall.
1066    this->thread[tid]->syscall(callnum);
1067
1068    // Decrease funcExeInst by one as the normal commit will handle
1069    // incrementing it.
1070    --(this->thread[tid]->funcExeInst);
1071}
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
1211    if (checker)
1212        checker->switchOut();
1213
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);
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, DynInstPtr &inst)
1474{
1475    // Keep an instruction count.
1476    if (!inst->isMicroop() || inst->isLastMicroop()) {
1477        thread[tid]->numInst++;
1478        thread[tid]->numInsts++;
1479        committedInsts[tid]++;
1480        totalCommittedInsts++;
1481    }
1482    thread[tid]->numOp++;
1483    thread[tid]->numOps++;
1484    committedOps[tid]++;
1485
1486    system->totalNumInsts++;
1487    // Check for instruction-count-based events.
1488    comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1489    system->instEventQueue.serviceEvents(system->totalNumInsts);
1490}
1491
1492template <class Impl>
1493void
1494FullO3CPU<Impl>::removeFrontInst(DynInstPtr &inst)
1495{
1496    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %s "
1497            "[sn:%lli]\n",
1498            inst->threadNumber, inst->pcState(), inst->seqNum);
1499
1500    removeInstsThisCycle = true;
1501
1502    // Remove the front instruction.
1503    removeList.push(inst->getInstListIt());
1504}
1505
1506template <class Impl>
1507void
1508FullO3CPU<Impl>::removeInstsNotInROB(ThreadID tid)
1509{
1510    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
1511            " list.\n", tid);
1512
1513    ListIt end_it;
1514
1515    bool rob_empty = false;
1516
1517    if (instList.empty()) {
1518        return;
1519    } else if (rob.isEmpty(/*tid*/)) {
1520        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
1521        end_it = instList.begin();
1522        rob_empty = true;
1523    } else {
1524        end_it = (rob.readTailInst(tid))->getInstListIt();
1525        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
1526    }
1527
1528    removeInstsThisCycle = true;
1529
1530    ListIt inst_it = instList.end();
1531
1532    inst_it--;
1533
1534    // Walk through the instruction list, removing any instructions
1535    // that were inserted after the given instruction iterator, end_it.
1536    while (inst_it != end_it) {
1537        assert(!instList.empty());
1538
1539        squashInstIt(inst_it, tid);
1540
1541        inst_it--;
1542    }
1543
1544    // If the ROB was empty, then we actually need to remove the first
1545    // instruction as well.
1546    if (rob_empty) {
1547        squashInstIt(inst_it, tid);
1548    }
1549}
1550
1551template <class Impl>
1552void
1553FullO3CPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid)
1554{
1555    assert(!instList.empty());
1556
1557    removeInstsThisCycle = true;
1558
1559    ListIt inst_iter = instList.end();
1560
1561    inst_iter--;
1562
1563    DPRINTF(O3CPU, "Deleting instructions from instruction "
1564            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1565            tid, seq_num, (*inst_iter)->seqNum);
1566
1567    while ((*inst_iter)->seqNum > seq_num) {
1568
1569        bool break_loop = (inst_iter == instList.begin());
1570
1571        squashInstIt(inst_iter, tid);
1572
1573        inst_iter--;
1574
1575        if (break_loop)
1576            break;
1577    }
1578}
1579
1580template <class Impl>
1581inline void
1582FullO3CPU<Impl>::squashInstIt(const ListIt &instIt, ThreadID tid)
1583{
1584    if ((*instIt)->threadNumber == tid) {
1585        DPRINTF(O3CPU, "Squashing instruction, "
1586                "[tid:%i] [sn:%lli] PC %s\n",
1587                (*instIt)->threadNumber,
1588                (*instIt)->seqNum,
1589                (*instIt)->pcState());
1590
1591        // Mark it as squashed.
1592        (*instIt)->setSquashed();
1593
1594        // @todo: Formulate a consistent method for deleting
1595        // instructions from the instruction list
1596        // Remove the instruction from the list.
1597        removeList.push(instIt);
1598    }
1599}
1600
1601template <class Impl>
1602void
1603FullO3CPU<Impl>::cleanUpRemovedInsts()
1604{
1605    while (!removeList.empty()) {
1606        DPRINTF(O3CPU, "Removing instruction, "
1607                "[tid:%i] [sn:%lli] PC %s\n",
1608                (*removeList.front())->threadNumber,
1609                (*removeList.front())->seqNum,
1610                (*removeList.front())->pcState());
1611
1612        instList.erase(removeList.front());
1613
1614        removeList.pop();
1615    }
1616
1617    removeInstsThisCycle = false;
1618}
1619/*
1620template <class Impl>
1621void
1622FullO3CPU<Impl>::removeAllInsts()
1623{
1624    instList.clear();
1625}
1626*/
1627template <class Impl>
1628void
1629FullO3CPU<Impl>::dumpInsts()
1630{
1631    int num = 0;
1632
1633    ListIt inst_list_it = instList.begin();
1634
1635    cprintf("Dumping Instruction List\n");
1636
1637    while (inst_list_it != instList.end()) {
1638        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1639                "Squashed:%i\n\n",
1640                num, (*inst_list_it)->instAddr(), (*inst_list_it)->threadNumber,
1641                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1642                (*inst_list_it)->isSquashed());
1643        inst_list_it++;
1644        ++num;
1645    }
1646}
1647/*
1648template <class Impl>
1649void
1650FullO3CPU<Impl>::wakeDependents(DynInstPtr &inst)
1651{
1652    iew.wakeDependents(inst);
1653}
1654*/
1655template <class Impl>
1656void
1657FullO3CPU<Impl>::wakeCPU()
1658{
1659    if (activityRec.active() || tickEvent.scheduled()) {
1660        DPRINTF(Activity, "CPU already running.\n");
1661        return;
1662    }
1663
1664    DPRINTF(Activity, "Waking up CPU\n");
1665
1666    idleCycles += tickToCycles((curTick() - 1) - lastRunningCycle);
1667    numCycles += tickToCycles((curTick() - 1) - lastRunningCycle);
1668
1669    schedule(tickEvent, nextCycle());
1670}
1671
1672template <class Impl>
1673void
1674FullO3CPU<Impl>::wakeup()
1675{
1676    if (this->thread[0]->status() != ThreadContext::Suspended)
1677        return;
1678
1679    this->wakeCPU();
1680
1681    DPRINTF(Quiesce, "Suspended Processor woken\n");
1682    this->threadContexts[0]->activate();
1683}
1684
1685template <class Impl>
1686ThreadID
1687FullO3CPU<Impl>::getFreeTid()
1688{
1689    for (ThreadID tid = 0; tid < numThreads; tid++) {
1690        if (!tids[tid]) {
1691            tids[tid] = true;
1692            return tid;
1693        }
1694    }
1695
1696    return InvalidThreadID;
1697}
1698
1699template <class Impl>
1700void
1701FullO3CPU<Impl>::doContextSwitch()
1702{
1703    if (contextSwitch) {
1704
1705        //ADD CODE TO DEACTIVE THREAD HERE (???)
1706
1707        ThreadID size = cpuWaitList.size();
1708        for (ThreadID tid = 0; tid < size; tid++) {
1709            activateWhenReady(tid);
1710        }
1711
1712        if (cpuWaitList.size() == 0)
1713            contextSwitch = true;
1714    }
1715}
1716
1717template <class Impl>
1718void
1719FullO3CPU<Impl>::updateThreadPriority()
1720{
1721    if (activeThreads.size() > 1) {
1722        //DEFAULT TO ROUND ROBIN SCHEME
1723        //e.g. Move highest priority to end of thread list
1724        list<ThreadID>::iterator list_begin = activeThreads.begin();
1725
1726        unsigned high_thread = *list_begin;
1727
1728        activeThreads.erase(list_begin);
1729
1730        activeThreads.push_back(high_thread);
1731    }
1732}
1733
1734// Forward declaration of FullO3CPU.
1735template class FullO3CPU<O3CPUImpl>;
1736