cpu.cc revision 9433:34971d2e0019
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      lastRunningCycle(curCycle())
262{
263    if (!params->switched_out) {
264        _status = Running;
265    } else {
266        _status = SwitchedOut;
267    }
268
269    if (params->checker) {
270        BaseCPU *temp_checker = params->checker;
271        checker = dynamic_cast<Checker<Impl> *>(temp_checker);
272        checker->setIcachePort(&icachePort);
273        checker->setSystem(params->system);
274    } else {
275        checker = NULL;
276    }
277
278    if (!FullSystem) {
279        thread.resize(numThreads);
280        tids.resize(numThreads);
281    }
282
283    // The stages also need their CPU pointer setup.  However this
284    // must be done at the upper level CPU because they have pointers
285    // to the upper level CPU, and not this FullO3CPU.
286
287    // Set up Pointers to the activeThreads list for each stage
288    fetch.setActiveThreads(&activeThreads);
289    decode.setActiveThreads(&activeThreads);
290    rename.setActiveThreads(&activeThreads);
291    iew.setActiveThreads(&activeThreads);
292    commit.setActiveThreads(&activeThreads);
293
294    // Give each of the stages the time buffer they will use.
295    fetch.setTimeBuffer(&timeBuffer);
296    decode.setTimeBuffer(&timeBuffer);
297    rename.setTimeBuffer(&timeBuffer);
298    iew.setTimeBuffer(&timeBuffer);
299    commit.setTimeBuffer(&timeBuffer);
300
301    // Also setup each of the stages' queues.
302    fetch.setFetchQueue(&fetchQueue);
303    decode.setFetchQueue(&fetchQueue);
304    commit.setFetchQueue(&fetchQueue);
305    decode.setDecodeQueue(&decodeQueue);
306    rename.setDecodeQueue(&decodeQueue);
307    rename.setRenameQueue(&renameQueue);
308    iew.setRenameQueue(&renameQueue);
309    iew.setIEWQueue(&iewQueue);
310    commit.setIEWQueue(&iewQueue);
311    commit.setRenameQueue(&renameQueue);
312
313    commit.setIEWStage(&iew);
314    rename.setIEWStage(&iew);
315    rename.setCommitStage(&commit);
316
317    ThreadID active_threads;
318    if (FullSystem) {
319        active_threads = 1;
320    } else {
321        active_threads = params->workload.size();
322
323        if (active_threads > Impl::MaxThreads) {
324            panic("Workload Size too large. Increase the 'MaxThreads' "
325                  "constant in your O3CPU impl. file (e.g. o3/alpha/impl.hh) "
326                  "or edit your workload size.");
327        }
328    }
329
330    //Make Sure That this a Valid Architeture
331    assert(params->numPhysIntRegs   >= numThreads * TheISA::NumIntRegs);
332    assert(params->numPhysFloatRegs >= numThreads * TheISA::NumFloatRegs);
333
334    rename.setScoreboard(&scoreboard);
335    iew.setScoreboard(&scoreboard);
336
337    // Setup the rename map for whichever stages need it.
338    PhysRegIndex lreg_idx = 0;
339    PhysRegIndex freg_idx = params->numPhysIntRegs; //Index to 1 after int regs
340
341    for (ThreadID tid = 0; tid < numThreads; tid++) {
342        bool bindRegs = (tid <= active_threads - 1);
343
344        isa[tid] = params->isa[tid];
345
346        commitRenameMap[tid].init(TheISA::NumIntRegs,
347                                  params->numPhysIntRegs,
348                                  lreg_idx,            //Index for Logical. Regs
349
350                                  TheISA::NumFloatRegs,
351                                  params->numPhysFloatRegs,
352                                  freg_idx,            //Index for Float Regs
353
354                                  TheISA::NumMiscRegs,
355
356                                  TheISA::ZeroReg,
357                                  TheISA::ZeroReg,
358
359                                  tid,
360                                  false);
361
362        renameMap[tid].init(TheISA::NumIntRegs,
363                            params->numPhysIntRegs,
364                            lreg_idx,                  //Index for Logical. Regs
365
366                            TheISA::NumFloatRegs,
367                            params->numPhysFloatRegs,
368                            freg_idx,                  //Index for Float Regs
369
370                            TheISA::NumMiscRegs,
371
372                            TheISA::ZeroReg,
373                            TheISA::ZeroReg,
374
375                            tid,
376                            bindRegs);
377
378        activateThreadEvent[tid].init(tid, this);
379        deallocateContextEvent[tid].init(tid, this);
380    }
381
382    rename.setRenameMap(renameMap);
383    commit.setRenameMap(commitRenameMap);
384
385    // Give renameMap & rename stage access to the freeList;
386    for (ThreadID tid = 0; tid < numThreads; tid++)
387        renameMap[tid].setFreeList(&freeList);
388    rename.setFreeList(&freeList);
389
390    // Setup the ROB for whichever stages need it.
391    commit.setROB(&rob);
392
393    lastActivatedCycle = 0;
394#if 0
395    // Give renameMap & rename stage access to the freeList;
396    for (ThreadID tid = 0; tid < numThreads; tid++)
397        globalSeqNum[tid] = 1;
398#endif
399
400    contextSwitch = false;
401    DPRINTF(O3CPU, "Creating O3CPU object.\n");
402
403    // Setup any thread state.
404    this->thread.resize(this->numThreads);
405
406    for (ThreadID tid = 0; tid < this->numThreads; ++tid) {
407        if (FullSystem) {
408            // SMT is not supported in FS mode yet.
409            assert(this->numThreads == 1);
410            this->thread[tid] = new Thread(this, 0, NULL);
411        } else {
412            if (tid < params->workload.size()) {
413                DPRINTF(O3CPU, "Workload[%i] process is %#x",
414                        tid, this->thread[tid]);
415                this->thread[tid] = new typename FullO3CPU<Impl>::Thread(
416                        (typename Impl::O3CPU *)(this),
417                        tid, params->workload[tid]);
418
419                //usedTids[tid] = true;
420                //threadMap[tid] = tid;
421            } else {
422                //Allocate Empty thread so M5 can use later
423                //when scheduling threads to CPU
424                Process* dummy_proc = NULL;
425
426                this->thread[tid] = new typename FullO3CPU<Impl>::Thread(
427                        (typename Impl::O3CPU *)(this),
428                        tid, dummy_proc);
429                //usedTids[tid] = false;
430            }
431        }
432
433        ThreadContext *tc;
434
435        // Setup the TC that will serve as the interface to the threads/CPU.
436        O3ThreadContext<Impl> *o3_tc = new O3ThreadContext<Impl>;
437
438        tc = o3_tc;
439
440        // If we're using a checker, then the TC should be the
441        // CheckerThreadContext.
442        if (params->checker) {
443            tc = new CheckerThreadContext<O3ThreadContext<Impl> >(
444                o3_tc, this->checker);
445        }
446
447        o3_tc->cpu = (typename Impl::O3CPU *)(this);
448        assert(o3_tc->cpu);
449        o3_tc->thread = this->thread[tid];
450
451        if (FullSystem) {
452            // Setup quiesce event.
453            this->thread[tid]->quiesceEvent = new EndQuiesceEvent(tc);
454        }
455        // Give the thread the TC.
456        this->thread[tid]->tc = tc;
457
458        // Add the TC to the CPU's list of TC's.
459        this->threadContexts.push_back(tc);
460    }
461
462    // FullO3CPU always requires an interrupt controller.
463    if (!params->switched_out && !interrupts) {
464        fatal("FullO3CPU %s has no interrupt controller.\n"
465              "Ensure createInterruptController() is called.\n", name());
466    }
467
468    for (ThreadID tid = 0; tid < this->numThreads; tid++)
469        this->thread[tid]->setFuncExeInst(0);
470
471    lockAddr = 0;
472    lockFlag = false;
473}
474
475template <class Impl>
476FullO3CPU<Impl>::~FullO3CPU()
477{
478}
479
480template <class Impl>
481void
482FullO3CPU<Impl>::regStats()
483{
484    BaseO3CPU::regStats();
485
486    // Register any of the O3CPU's stats here.
487    timesIdled
488        .name(name() + ".timesIdled")
489        .desc("Number of times that the entire CPU went into an idle state and"
490              " unscheduled itself")
491        .prereq(timesIdled);
492
493    idleCycles
494        .name(name() + ".idleCycles")
495        .desc("Total number of cycles that the CPU has spent unscheduled due "
496              "to idling")
497        .prereq(idleCycles);
498
499    quiesceCycles
500        .name(name() + ".quiesceCycles")
501        .desc("Total number of cycles that CPU has spent quiesced or waiting "
502              "for an interrupt")
503        .prereq(quiesceCycles);
504
505    // Number of Instructions simulated
506    // --------------------------------
507    // Should probably be in Base CPU but need templated
508    // MaxThreads so put in here instead
509    committedInsts
510        .init(numThreads)
511        .name(name() + ".committedInsts")
512        .desc("Number of Instructions Simulated");
513
514    committedOps
515        .init(numThreads)
516        .name(name() + ".committedOps")
517        .desc("Number of Ops (including micro ops) Simulated");
518
519    totalCommittedInsts
520        .name(name() + ".committedInsts_total")
521        .desc("Number of Instructions Simulated");
522
523    cpi
524        .name(name() + ".cpi")
525        .desc("CPI: Cycles Per Instruction")
526        .precision(6);
527    cpi = numCycles / committedInsts;
528
529    totalCpi
530        .name(name() + ".cpi_total")
531        .desc("CPI: Total CPI of All Threads")
532        .precision(6);
533    totalCpi = numCycles / totalCommittedInsts;
534
535    ipc
536        .name(name() + ".ipc")
537        .desc("IPC: Instructions Per Cycle")
538        .precision(6);
539    ipc =  committedInsts / numCycles;
540
541    totalIpc
542        .name(name() + ".ipc_total")
543        .desc("IPC: Total IPC of All Threads")
544        .precision(6);
545    totalIpc =  totalCommittedInsts / numCycles;
546
547    this->fetch.regStats();
548    this->decode.regStats();
549    this->rename.regStats();
550    this->iew.regStats();
551    this->commit.regStats();
552    this->rob.regStats();
553
554    intRegfileReads
555        .name(name() + ".int_regfile_reads")
556        .desc("number of integer regfile reads")
557        .prereq(intRegfileReads);
558
559    intRegfileWrites
560        .name(name() + ".int_regfile_writes")
561        .desc("number of integer regfile writes")
562        .prereq(intRegfileWrites);
563
564    fpRegfileReads
565        .name(name() + ".fp_regfile_reads")
566        .desc("number of floating regfile reads")
567        .prereq(fpRegfileReads);
568
569    fpRegfileWrites
570        .name(name() + ".fp_regfile_writes")
571        .desc("number of floating regfile writes")
572        .prereq(fpRegfileWrites);
573
574    miscRegfileReads
575        .name(name() + ".misc_regfile_reads")
576        .desc("number of misc regfile reads")
577        .prereq(miscRegfileReads);
578
579    miscRegfileWrites
580        .name(name() + ".misc_regfile_writes")
581        .desc("number of misc regfile writes")
582        .prereq(miscRegfileWrites);
583}
584
585template <class Impl>
586void
587FullO3CPU<Impl>::tick()
588{
589    DPRINTF(O3CPU, "\n\nFullO3CPU: Ticking main, FullO3CPU.\n");
590
591    ++numCycles;
592
593//    activity = false;
594
595    //Tick each of the stages
596    fetch.tick();
597
598    decode.tick();
599
600    rename.tick();
601
602    iew.tick();
603
604    commit.tick();
605
606    if (!FullSystem)
607        doContextSwitch();
608
609    // Now advance the time buffers
610    timeBuffer.advance();
611
612    fetchQueue.advance();
613    decodeQueue.advance();
614    renameQueue.advance();
615    iewQueue.advance();
616
617    activityRec.advance();
618
619    if (removeInstsThisCycle) {
620        cleanUpRemovedInsts();
621    }
622
623    if (!tickEvent.scheduled()) {
624        if (_status == SwitchedOut ||
625            getDrainState() == Drainable::Drained) {
626            DPRINTF(O3CPU, "Switched out!\n");
627            // increment stat
628            lastRunningCycle = curCycle();
629        } else if (!activityRec.active() || _status == Idle) {
630            DPRINTF(O3CPU, "Idle!\n");
631            lastRunningCycle = curCycle();
632            timesIdled++;
633        } else {
634            schedule(tickEvent, clockEdge(Cycles(1)));
635            DPRINTF(O3CPU, "Scheduling next tick!\n");
636        }
637    }
638
639    if (!FullSystem)
640        updateThreadPriority();
641}
642
643template <class Impl>
644void
645FullO3CPU<Impl>::init()
646{
647    BaseCPU::init();
648
649    if (!params()->switched_out &&
650        system->getMemoryMode() != Enums::timing) {
651        fatal("The O3 CPU requires the memory system to be in "
652              "'timing' mode.\n");
653    }
654
655    for (ThreadID tid = 0; tid < numThreads; ++tid) {
656        // Set noSquashFromTC so that the CPU doesn't squash when initially
657        // setting up registers.
658        thread[tid]->noSquashFromTC = true;
659        // Initialise the ThreadContext's memory proxies
660        thread[tid]->initMemProxies(thread[tid]->getTC());
661    }
662
663    // this CPU could still be unconnected if we are restoring from a
664    // checkpoint and this CPU is to be switched in, thus we can only
665    // do this here if the instruction port is actually connected, if
666    // not we have to do it as part of takeOverFrom
667    if (icachePort.isConnected())
668        fetch.setIcache();
669
670    if (FullSystem && !params()->switched_out) {
671        for (ThreadID tid = 0; tid < numThreads; tid++) {
672            ThreadContext *src_tc = threadContexts[tid];
673            TheISA::initCPU(src_tc, src_tc->contextId());
674        }
675    }
676
677    // Clear noSquashFromTC.
678    for (int tid = 0; tid < numThreads; ++tid)
679        thread[tid]->noSquashFromTC = false;
680
681    commit.setThreads(thread);
682}
683
684template <class Impl>
685void
686FullO3CPU<Impl>::startup()
687{
688    fetch.startupStage();
689    iew.startupStage();
690    rename.startupStage();
691    commit.startupStage();
692}
693
694template <class Impl>
695void
696FullO3CPU<Impl>::activateThread(ThreadID tid)
697{
698    list<ThreadID>::iterator isActive =
699        std::find(activeThreads.begin(), activeThreads.end(), tid);
700
701    DPRINTF(O3CPU, "[tid:%i]: Calling activate thread.\n", tid);
702
703    if (isActive == activeThreads.end()) {
704        DPRINTF(O3CPU, "[tid:%i]: Adding to active threads list\n",
705                tid);
706
707        activeThreads.push_back(tid);
708    }
709}
710
711template <class Impl>
712void
713FullO3CPU<Impl>::deactivateThread(ThreadID tid)
714{
715    //Remove From Active List, if Active
716    list<ThreadID>::iterator thread_it =
717        std::find(activeThreads.begin(), activeThreads.end(), tid);
718
719    DPRINTF(O3CPU, "[tid:%i]: Calling deactivate thread.\n", tid);
720
721    if (thread_it != activeThreads.end()) {
722        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
723                tid);
724        activeThreads.erase(thread_it);
725    }
726}
727
728template <class Impl>
729Counter
730FullO3CPU<Impl>::totalInsts() const
731{
732    Counter total(0);
733
734    ThreadID size = thread.size();
735    for (ThreadID i = 0; i < size; i++)
736        total += thread[i]->numInst;
737
738    return total;
739}
740
741template <class Impl>
742Counter
743FullO3CPU<Impl>::totalOps() const
744{
745    Counter total(0);
746
747    ThreadID size = thread.size();
748    for (ThreadID i = 0; i < size; i++)
749        total += thread[i]->numOp;
750
751    return total;
752}
753
754template <class Impl>
755void
756FullO3CPU<Impl>::activateContext(ThreadID tid, Cycles delay)
757{
758    // Needs to set each stage to running as well.
759    if (delay){
760        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to activate "
761                "on cycle %d\n", tid, clockEdge(delay));
762        scheduleActivateThreadEvent(tid, delay);
763    } else {
764        activateThread(tid);
765    }
766
767    // If we are time 0 or if the last activation time is in the past,
768    // schedule the next tick and wake up the fetch unit
769    if (lastActivatedCycle == 0 || lastActivatedCycle < curTick()) {
770        scheduleTickEvent(delay);
771
772        // Be sure to signal that there's some activity so the CPU doesn't
773        // deschedule itself.
774        activityRec.activity();
775        fetch.wakeFromQuiesce();
776
777        Cycles cycles(curCycle() - lastRunningCycle);
778        // @todo: This is an oddity that is only here to match the stats
779        if (cycles != 0)
780            --cycles;
781        quiesceCycles += cycles;
782
783        lastActivatedCycle = curTick();
784
785        _status = Running;
786    }
787}
788
789template <class Impl>
790bool
791FullO3CPU<Impl>::scheduleDeallocateContext(ThreadID tid, bool remove,
792                                           Cycles delay)
793{
794    // Schedule removal of thread data from CPU
795    if (delay){
796        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to deallocate "
797                "on tick %d\n", tid, clockEdge(delay));
798        scheduleDeallocateContextEvent(tid, remove, delay);
799        return false;
800    } else {
801        deactivateThread(tid);
802        if (remove)
803            removeThread(tid);
804        return true;
805    }
806}
807
808template <class Impl>
809void
810FullO3CPU<Impl>::suspendContext(ThreadID tid)
811{
812    DPRINTF(O3CPU,"[tid: %i]: Suspending Thread Context.\n", tid);
813    bool deallocated = scheduleDeallocateContext(tid, false, Cycles(1));
814    // If this was the last thread then unschedule the tick event.
815    if ((activeThreads.size() == 1 && !deallocated) ||
816        activeThreads.size() == 0)
817        unscheduleTickEvent();
818
819    DPRINTF(Quiesce, "Suspending Context\n");
820    lastRunningCycle = curCycle();
821    _status = Idle;
822}
823
824template <class Impl>
825void
826FullO3CPU<Impl>::haltContext(ThreadID tid)
827{
828    //For now, this is the same as deallocate
829    DPRINTF(O3CPU,"[tid:%i]: Halt Context called. Deallocating", tid);
830    scheduleDeallocateContext(tid, true, Cycles(1));
831}
832
833template <class Impl>
834void
835FullO3CPU<Impl>::insertThread(ThreadID tid)
836{
837    DPRINTF(O3CPU,"[tid:%i] Initializing thread into CPU");
838    // Will change now that the PC and thread state is internal to the CPU
839    // and not in the ThreadContext.
840    ThreadContext *src_tc;
841    if (FullSystem)
842        src_tc = system->threadContexts[tid];
843    else
844        src_tc = tcBase(tid);
845
846    //Bind Int Regs to Rename Map
847    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
848        PhysRegIndex phys_reg = freeList.getIntReg();
849
850        renameMap[tid].setEntry(ireg,phys_reg);
851        scoreboard.setReg(phys_reg);
852    }
853
854    //Bind Float Regs to Rename Map
855    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
856        PhysRegIndex phys_reg = freeList.getFloatReg();
857
858        renameMap[tid].setEntry(freg,phys_reg);
859        scoreboard.setReg(phys_reg);
860    }
861
862    //Copy Thread Data Into RegFile
863    //this->copyFromTC(tid);
864
865    //Set PC/NPC/NNPC
866    pcState(src_tc->pcState(), tid);
867
868    src_tc->setStatus(ThreadContext::Active);
869
870    activateContext(tid, Cycles(1));
871
872    //Reset ROB/IQ/LSQ Entries
873    commit.rob->resetEntries();
874    iew.resetEntries();
875}
876
877template <class Impl>
878void
879FullO3CPU<Impl>::removeThread(ThreadID tid)
880{
881    DPRINTF(O3CPU,"[tid:%i] Removing thread context from CPU.\n", tid);
882
883    // Copy Thread Data From RegFile
884    // If thread is suspended, it might be re-allocated
885    // this->copyToTC(tid);
886
887
888    // @todo: 2-27-2008: Fix how we free up rename mappings
889    // here to alleviate the case for double-freeing registers
890    // in SMT workloads.
891
892    // Unbind Int Regs from Rename Map
893    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
894        PhysRegIndex phys_reg = renameMap[tid].lookup(ireg);
895
896        scoreboard.unsetReg(phys_reg);
897        freeList.addReg(phys_reg);
898    }
899
900    // Unbind Float Regs from Rename Map
901    for (int freg = TheISA::NumIntRegs; freg < TheISA::NumFloatRegs; freg++) {
902        PhysRegIndex phys_reg = renameMap[tid].lookup(freg);
903
904        scoreboard.unsetReg(phys_reg);
905        freeList.addReg(phys_reg);
906    }
907
908    // Squash Throughout Pipeline
909    DynInstPtr inst = commit.rob->readHeadInst(tid);
910    InstSeqNum squash_seq_num = inst->seqNum;
911    fetch.squash(0, squash_seq_num, inst, tid);
912    decode.squash(tid);
913    rename.squash(squash_seq_num, tid);
914    iew.squash(tid);
915    iew.ldstQueue.squash(squash_seq_num, tid);
916    commit.rob->squash(squash_seq_num, tid);
917
918
919    assert(iew.instQueue.getCount(tid) == 0);
920    assert(iew.ldstQueue.getCount(tid) == 0);
921
922    // Reset ROB/IQ/LSQ Entries
923
924    // Commented out for now.  This should be possible to do by
925    // telling all the pipeline stages to drain first, and then
926    // checking until the drain completes.  Once the pipeline is
927    // drained, call resetEntries(). - 10-09-06 ktlim
928/*
929    if (activeThreads.size() >= 1) {
930        commit.rob->resetEntries();
931        iew.resetEntries();
932    }
933*/
934}
935
936
937template <class Impl>
938void
939FullO3CPU<Impl>::activateWhenReady(ThreadID tid)
940{
941    DPRINTF(O3CPU,"[tid:%i]: Checking if resources are available for incoming"
942            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
943            tid);
944
945    bool ready = true;
946
947    if (freeList.numFreeIntRegs() >= TheISA::NumIntRegs) {
948        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
949                "Phys. Int. Regs.\n",
950                tid);
951        ready = false;
952    } else if (freeList.numFreeFloatRegs() >= TheISA::NumFloatRegs) {
953        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
954                "Phys. Float. Regs.\n",
955                tid);
956        ready = false;
957    } else if (commit.rob->numFreeEntries() >=
958               commit.rob->entryAmount(activeThreads.size() + 1)) {
959        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
960                "ROB entries.\n",
961                tid);
962        ready = false;
963    } else if (iew.instQueue.numFreeEntries() >=
964               iew.instQueue.entryAmount(activeThreads.size() + 1)) {
965        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
966                "IQ entries.\n",
967                tid);
968        ready = false;
969    } else if (iew.ldstQueue.numFreeEntries() >=
970               iew.ldstQueue.entryAmount(activeThreads.size() + 1)) {
971        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
972                "LSQ entries.\n",
973                tid);
974        ready = false;
975    }
976
977    if (ready) {
978        insertThread(tid);
979
980        contextSwitch = false;
981
982        cpuWaitList.remove(tid);
983    } else {
984        suspendContext(tid);
985
986        //blocks fetch
987        contextSwitch = true;
988
989        //@todo: dont always add to waitlist
990        //do waitlist
991        cpuWaitList.push_back(tid);
992    }
993}
994
995template <class Impl>
996Fault
997FullO3CPU<Impl>::hwrei(ThreadID tid)
998{
999#if THE_ISA == ALPHA_ISA
1000    // Need to clear the lock flag upon returning from an interrupt.
1001    this->setMiscRegNoEffect(AlphaISA::MISCREG_LOCKFLAG, false, tid);
1002
1003    this->thread[tid]->kernelStats->hwrei();
1004
1005    // FIXME: XXX check for interrupts? XXX
1006#endif
1007    return NoFault;
1008}
1009
1010template <class Impl>
1011bool
1012FullO3CPU<Impl>::simPalCheck(int palFunc, ThreadID tid)
1013{
1014#if THE_ISA == ALPHA_ISA
1015    if (this->thread[tid]->kernelStats)
1016        this->thread[tid]->kernelStats->callpal(palFunc,
1017                                                this->threadContexts[tid]);
1018
1019    switch (palFunc) {
1020      case PAL::halt:
1021        halt();
1022        if (--System::numSystemsRunning == 0)
1023            exitSimLoop("all cpus halted");
1024        break;
1025
1026      case PAL::bpt:
1027      case PAL::bugchk:
1028        if (this->system->breakpoint())
1029            return false;
1030        break;
1031    }
1032#endif
1033    return true;
1034}
1035
1036template <class Impl>
1037Fault
1038FullO3CPU<Impl>::getInterrupts()
1039{
1040    // Check if there are any outstanding interrupts
1041    return this->interrupts->getInterrupt(this->threadContexts[0]);
1042}
1043
1044template <class Impl>
1045void
1046FullO3CPU<Impl>::processInterrupts(Fault interrupt)
1047{
1048    // Check for interrupts here.  For now can copy the code that
1049    // exists within isa_fullsys_traits.hh.  Also assume that thread 0
1050    // is the one that handles the interrupts.
1051    // @todo: Possibly consolidate the interrupt checking code.
1052    // @todo: Allow other threads to handle interrupts.
1053
1054    assert(interrupt != NoFault);
1055    this->interrupts->updateIntrInfo(this->threadContexts[0]);
1056
1057    DPRINTF(O3CPU, "Interrupt %s being handled\n", interrupt->name());
1058    this->trap(interrupt, 0, NULL);
1059}
1060
1061template <class Impl>
1062void
1063FullO3CPU<Impl>::trap(Fault fault, ThreadID tid, StaticInstPtr inst)
1064{
1065    // Pass the thread's TC into the invoke method.
1066    fault->invoke(this->threadContexts[tid], inst);
1067}
1068
1069template <class Impl>
1070void
1071FullO3CPU<Impl>::syscall(int64_t callnum, ThreadID tid)
1072{
1073    DPRINTF(O3CPU, "[tid:%i] Executing syscall().\n\n", tid);
1074
1075    DPRINTF(Activity,"Activity: syscall() called.\n");
1076
1077    // Temporarily increase this by one to account for the syscall
1078    // instruction.
1079    ++(this->thread[tid]->funcExeInst);
1080
1081    // Execute the actual syscall.
1082    this->thread[tid]->syscall(callnum);
1083
1084    // Decrease funcExeInst by one as the normal commit will handle
1085    // incrementing it.
1086    --(this->thread[tid]->funcExeInst);
1087}
1088
1089template <class Impl>
1090void
1091FullO3CPU<Impl>::serialize(std::ostream &os)
1092{
1093    Drainable::State so_state(getDrainState());
1094    SERIALIZE_ENUM(so_state);
1095    BaseCPU::serialize(os);
1096    nameOut(os, csprintf("%s.tickEvent", name()));
1097    tickEvent.serialize(os);
1098
1099    for (ThreadID i = 0; i < thread.size(); i++) {
1100        nameOut(os, csprintf("%s.xc.%i", name(), i));
1101        thread[i]->serialize(os);
1102    }
1103}
1104
1105template <class Impl>
1106void
1107FullO3CPU<Impl>::unserialize(Checkpoint *cp, const std::string &section)
1108{
1109    Drainable::State so_state;
1110    UNSERIALIZE_ENUM(so_state);
1111    BaseCPU::unserialize(cp, section);
1112    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));
1113
1114    for (ThreadID i = 0; i < thread.size(); i++) {
1115        thread[i]->unserialize(cp,
1116                               csprintf("%s.xc.%i", section, i));
1117        if (thread[i]->status() == ThreadContext::Active)
1118            activateThread(i);
1119    }
1120}
1121
1122template <class Impl>
1123unsigned int
1124FullO3CPU<Impl>::drain(DrainManager *drain_manager)
1125{
1126    DPRINTF(O3CPU, "Switching out\n");
1127
1128    // If the CPU isn't doing anything, then return immediately.
1129    if (_status == SwitchedOut)
1130        return 0;
1131
1132    drainCount = 0;
1133    fetch.drain();
1134    decode.drain();
1135    rename.drain();
1136    iew.drain();
1137    commit.drain();
1138
1139    // Wake the CPU and record activity so everything can drain out if
1140    // the CPU was not able to immediately drain.
1141    if (getDrainState() != Drainable::Drained) {
1142        // A bit of a hack...set the drainManager after all the drain()
1143        // calls have been made, that way if all of the stages drain
1144        // immediately, the signalDrained() function knows not to call
1145        // process on the drain event.
1146        drainManager = drain_manager;
1147
1148        wakeCPU();
1149        activityRec.activity();
1150
1151        DPRINTF(Drain, "CPU not drained\n");
1152
1153        return 1;
1154    } else {
1155        return 0;
1156    }
1157}
1158
1159template <class Impl>
1160void
1161FullO3CPU<Impl>::drainResume()
1162{
1163    fetch.resume();
1164    decode.resume();
1165    rename.resume();
1166    iew.resume();
1167    commit.resume();
1168
1169    setDrainState(Drainable::Running);
1170
1171    if (_status == SwitchedOut)
1172        return;
1173
1174    if (system->getMemoryMode() != Enums::timing) {
1175        fatal("The O3 CPU requires the memory system to be in "
1176              "'timing' mode.\n");
1177    }
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        if (drainManager) {
1195            DPRINTF(Drain, "CPU done draining, processing drain event\n");
1196            drainManager->signalDrainDone();
1197            drainManager = NULL;
1198        }
1199    }
1200    assert(drainCount <= 5);
1201}
1202
1203template <class Impl>
1204void
1205FullO3CPU<Impl>::switchOut()
1206{
1207    BaseCPU::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