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