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