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