cpu.cc revision 5639:67cc7f0427e7
1/*
2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Kevin Lim
29 *          Korey Sewell
30 */
31
32#include "config/full_system.hh"
33#include "config/use_checker.hh"
34
35#include "cpu/activity.hh"
36#include "cpu/simple_thread.hh"
37#include "cpu/thread_context.hh"
38#include "cpu/o3/isa_specific.hh"
39#include "cpu/o3/cpu.hh"
40#include "cpu/o3/thread_context.hh"
41#include "enums/MemoryMode.hh"
42#include "sim/core.hh"
43#include "sim/stat_control.hh"
44
45#if FULL_SYSTEM
46#include "cpu/quiesce_event.hh"
47#include "sim/system.hh"
48#else
49#include "sim/process.hh"
50#endif
51
52#if USE_CHECKER
53#include "cpu/checker/cpu.hh"
54#endif
55
56#if THE_ISA == ALPHA_ISA
57#include "arch/alpha/osfpal.hh"
58#endif
59
60class BaseCPUParams;
61
62using namespace TheISA;
63
64BaseO3CPU::BaseO3CPU(BaseCPUParams *params)
65    : BaseCPU(params), cpu_id(0)
66{
67}
68
69void
70BaseO3CPU::regStats()
71{
72    BaseCPU::regStats();
73}
74
75template <class Impl>
76FullO3CPU<Impl>::TickEvent::TickEvent(FullO3CPU<Impl> *c)
77    : Event(CPU_Tick_Pri), cpu(c)
78{
79}
80
81template <class Impl>
82void
83FullO3CPU<Impl>::TickEvent::process()
84{
85    cpu->tick();
86}
87
88template <class Impl>
89const char *
90FullO3CPU<Impl>::TickEvent::description() const
91{
92    return "FullO3CPU tick";
93}
94
95template <class Impl>
96FullO3CPU<Impl>::ActivateThreadEvent::ActivateThreadEvent()
97    : Event(CPU_Switch_Pri)
98{
99}
100
101template <class Impl>
102void
103FullO3CPU<Impl>::ActivateThreadEvent::init(int thread_num,
104                                           FullO3CPU<Impl> *thread_cpu)
105{
106    tid = thread_num;
107    cpu = thread_cpu;
108}
109
110template <class Impl>
111void
112FullO3CPU<Impl>::ActivateThreadEvent::process()
113{
114    cpu->activateThread(tid);
115}
116
117template <class Impl>
118const char *
119FullO3CPU<Impl>::ActivateThreadEvent::description() const
120{
121    return "FullO3CPU \"Activate Thread\"";
122}
123
124template <class Impl>
125FullO3CPU<Impl>::DeallocateContextEvent::DeallocateContextEvent()
126    : Event(CPU_Tick_Pri), tid(0), remove(false), cpu(NULL)
127{
128}
129
130template <class Impl>
131void
132FullO3CPU<Impl>::DeallocateContextEvent::init(int thread_num,
133                                              FullO3CPU<Impl> *thread_cpu)
134{
135    tid = thread_num;
136    cpu = thread_cpu;
137    remove = false;
138}
139
140template <class Impl>
141void
142FullO3CPU<Impl>::DeallocateContextEvent::process()
143{
144    cpu->deactivateThread(tid);
145    if (remove)
146        cpu->removeThread(tid);
147}
148
149template <class Impl>
150const char *
151FullO3CPU<Impl>::DeallocateContextEvent::description() const
152{
153    return "FullO3CPU \"Deallocate Context\"";
154}
155
156template <class Impl>
157FullO3CPU<Impl>::FullO3CPU(DerivO3CPUParams *params)
158    : BaseO3CPU(params),
159      itb(params->itb),
160      dtb(params->dtb),
161      tickEvent(this),
162      removeInstsThisCycle(false),
163      fetch(this, params),
164      decode(this, params),
165      rename(this, params),
166      iew(this, params),
167      commit(this, params),
168
169      regFile(this, params->numPhysIntRegs,
170              params->numPhysFloatRegs),
171
172      freeList(params->numThreads,
173               TheISA::NumIntRegs, params->numPhysIntRegs,
174               TheISA::NumFloatRegs, params->numPhysFloatRegs),
175
176      rob(this,
177          params->numROBEntries, params->squashWidth,
178          params->smtROBPolicy, params->smtROBThreshold,
179          params->numThreads),
180
181      scoreboard(params->numThreads,
182                 TheISA::NumIntRegs, params->numPhysIntRegs,
183                 TheISA::NumFloatRegs, params->numPhysFloatRegs,
184                 TheISA::NumMiscRegs * number_of_threads,
185                 TheISA::ZeroReg),
186
187      timeBuffer(params->backComSize, params->forwardComSize),
188      fetchQueue(params->backComSize, params->forwardComSize),
189      decodeQueue(params->backComSize, params->forwardComSize),
190      renameQueue(params->backComSize, params->forwardComSize),
191      iewQueue(params->backComSize, params->forwardComSize),
192      activityRec(NumStages,
193                  params->backComSize + params->forwardComSize,
194                  params->activity),
195
196      globalSeqNum(1),
197#if FULL_SYSTEM
198      system(params->system),
199      physmem(system->physmem),
200#endif // FULL_SYSTEM
201      drainCount(0),
202      deferRegistration(params->defer_registration),
203      numThreads(number_of_threads)
204{
205    if (!deferRegistration) {
206        _status = Running;
207    } else {
208        _status = Idle;
209    }
210
211#if USE_CHECKER
212    if (params->checker) {
213        BaseCPU *temp_checker = params->checker;
214        checker = dynamic_cast<Checker<DynInstPtr> *>(temp_checker);
215#if FULL_SYSTEM
216        checker->setSystem(params->system);
217#endif
218    } else {
219        checker = NULL;
220    }
221#endif // USE_CHECKER
222
223#if !FULL_SYSTEM
224    thread.resize(number_of_threads);
225    tids.resize(number_of_threads);
226#endif
227
228    // The stages also need their CPU pointer setup.  However this
229    // must be done at the upper level CPU because they have pointers
230    // to the upper level CPU, and not this FullO3CPU.
231
232    // Set up Pointers to the activeThreads list for each stage
233    fetch.setActiveThreads(&activeThreads);
234    decode.setActiveThreads(&activeThreads);
235    rename.setActiveThreads(&activeThreads);
236    iew.setActiveThreads(&activeThreads);
237    commit.setActiveThreads(&activeThreads);
238
239    // Give each of the stages the time buffer they will use.
240    fetch.setTimeBuffer(&timeBuffer);
241    decode.setTimeBuffer(&timeBuffer);
242    rename.setTimeBuffer(&timeBuffer);
243    iew.setTimeBuffer(&timeBuffer);
244    commit.setTimeBuffer(&timeBuffer);
245
246    // Also setup each of the stages' queues.
247    fetch.setFetchQueue(&fetchQueue);
248    decode.setFetchQueue(&fetchQueue);
249    commit.setFetchQueue(&fetchQueue);
250    decode.setDecodeQueue(&decodeQueue);
251    rename.setDecodeQueue(&decodeQueue);
252    rename.setRenameQueue(&renameQueue);
253    iew.setRenameQueue(&renameQueue);
254    iew.setIEWQueue(&iewQueue);
255    commit.setIEWQueue(&iewQueue);
256    commit.setRenameQueue(&renameQueue);
257
258    commit.setIEWStage(&iew);
259    rename.setIEWStage(&iew);
260    rename.setCommitStage(&commit);
261
262#if !FULL_SYSTEM
263    int active_threads = params->workload.size();
264
265    if (active_threads > Impl::MaxThreads) {
266        panic("Workload Size too large. Increase the 'MaxThreads'"
267              "constant in your O3CPU impl. file (e.g. o3/alpha/impl.hh) or "
268              "edit your workload size.");
269    }
270#else
271    int active_threads = 1;
272#endif
273
274    //Make Sure That this a Valid Architeture
275    assert(params->numPhysIntRegs   >= numThreads * TheISA::NumIntRegs);
276    assert(params->numPhysFloatRegs >= numThreads * TheISA::NumFloatRegs);
277
278    rename.setScoreboard(&scoreboard);
279    iew.setScoreboard(&scoreboard);
280
281    // Setup the rename map for whichever stages need it.
282    PhysRegIndex lreg_idx = 0;
283    PhysRegIndex freg_idx = params->numPhysIntRegs; //Index to 1 after int regs
284
285    for (int tid=0; tid < numThreads; tid++) {
286        bool bindRegs = (tid <= active_threads - 1);
287
288        commitRenameMap[tid].init(TheISA::NumIntRegs,
289                                  params->numPhysIntRegs,
290                                  lreg_idx,            //Index for Logical. Regs
291
292                                  TheISA::NumFloatRegs,
293                                  params->numPhysFloatRegs,
294                                  freg_idx,            //Index for Float Regs
295
296                                  TheISA::NumMiscRegs,
297
298                                  TheISA::ZeroReg,
299                                  TheISA::ZeroReg,
300
301                                  tid,
302                                  false);
303
304        renameMap[tid].init(TheISA::NumIntRegs,
305                            params->numPhysIntRegs,
306                            lreg_idx,                  //Index for Logical. Regs
307
308                            TheISA::NumFloatRegs,
309                            params->numPhysFloatRegs,
310                            freg_idx,                  //Index for Float Regs
311
312                            TheISA::NumMiscRegs,
313
314                            TheISA::ZeroReg,
315                            TheISA::ZeroReg,
316
317                            tid,
318                            bindRegs);
319
320        activateThreadEvent[tid].init(tid, this);
321        deallocateContextEvent[tid].init(tid, this);
322    }
323
324    rename.setRenameMap(renameMap);
325    commit.setRenameMap(commitRenameMap);
326
327    // Give renameMap & rename stage access to the freeList;
328    for (int i=0; i < numThreads; i++) {
329        renameMap[i].setFreeList(&freeList);
330    }
331    rename.setFreeList(&freeList);
332
333    // Setup the ROB for whichever stages need it.
334    commit.setROB(&rob);
335
336    lastRunningCycle = curTick;
337
338    lastActivatedCycle = -1;
339
340    // Give renameMap & rename stage access to the freeList;
341    //for (int i=0; i < numThreads; i++) {
342        //globalSeqNum[i] = 1;
343        //}
344
345    contextSwitch = false;
346    DPRINTF(O3CPU, "Creating O3CPU object.\n");
347
348    // Setup any thread state.
349    this->thread.resize(this->numThreads);
350
351    for (int i = 0; i < this->numThreads; ++i) {
352#if FULL_SYSTEM
353        // SMT is not supported in FS mode yet.
354        assert(this->numThreads == 1);
355        this->thread[i] = new Thread(this, 0);
356        this->thread[i]->setStatus(ThreadContext::Suspended);
357#else
358        if (i < params->workload.size()) {
359            DPRINTF(O3CPU, "Workload[%i] process is %#x",
360                    i, this->thread[i]);
361            this->thread[i] = new typename FullO3CPU<Impl>::Thread(
362                    (typename Impl::O3CPU *)(this),
363                    i, params->workload[i], i);
364
365            this->thread[i]->setStatus(ThreadContext::Suspended);
366
367            //usedTids[i] = true;
368            //threadMap[i] = i;
369        } else {
370            //Allocate Empty thread so M5 can use later
371            //when scheduling threads to CPU
372            Process* dummy_proc = NULL;
373
374            this->thread[i] = new typename FullO3CPU<Impl>::Thread(
375                    (typename Impl::O3CPU *)(this),
376                    i, dummy_proc, i);
377            //usedTids[i] = false;
378        }
379#endif // !FULL_SYSTEM
380
381        ThreadContext *tc;
382
383        // Setup the TC that will serve as the interface to the threads/CPU.
384        O3ThreadContext<Impl> *o3_tc = new O3ThreadContext<Impl>;
385
386        tc = o3_tc;
387
388        // If we're using a checker, then the TC should be the
389        // CheckerThreadContext.
390#if USE_CHECKER
391        if (params->checker) {
392            tc = new CheckerThreadContext<O3ThreadContext<Impl> >(
393                o3_tc, this->checker);
394        }
395#endif
396
397        o3_tc->cpu = (typename Impl::O3CPU *)(this);
398        assert(o3_tc->cpu);
399        o3_tc->thread = this->thread[i];
400
401#if FULL_SYSTEM
402        // Setup quiesce event.
403        this->thread[i]->quiesceEvent = new EndQuiesceEvent(tc);
404#endif
405        // Give the thread the TC.
406        this->thread[i]->tc = tc;
407        this->thread[i]->setCpuId(params->cpu_id);
408
409        // Add the TC to the CPU's list of TC's.
410        this->threadContexts.push_back(tc);
411    }
412
413    for (int i=0; i < this->numThreads; i++) {
414        this->thread[i]->setFuncExeInst(0);
415    }
416
417    lockAddr = 0;
418    lockFlag = false;
419}
420
421#if !FULL_SYSTEM
422
423template <class Impl>
424TheISA::IntReg
425FullO3CPU<Impl>::getSyscallArg(int i, int tid)
426{
427    assert(i < TheISA::NumArgumentRegs);
428    TheISA::IntReg idx = TheISA::flattenIntIndex(this->tcBase(tid),
429            TheISA::ArgumentReg[i]);
430    TheISA::IntReg val = this->readArchIntReg(idx, tid);
431#if THE_ISA == SPARC_ISA
432    if (bits(this->readMiscRegNoEffect(SparcISA::MISCREG_PSTATE, tid), 3, 3))
433        val = bits(val, 31, 0);
434#endif
435    return val;
436}
437
438template <class Impl>
439void
440FullO3CPU<Impl>::setSyscallArg(int i, TheISA::IntReg val, int tid)
441{
442    assert(i < TheISA::NumArgumentRegs);
443    TheISA::IntReg idx = TheISA::flattenIntIndex(this->tcBase(tid),
444            TheISA::ArgumentReg[i]);
445    this->setArchIntReg(idx, val, tid);
446}
447#endif
448
449template <class Impl>
450FullO3CPU<Impl>::~FullO3CPU()
451{
452}
453
454template <class Impl>
455void
456FullO3CPU<Impl>::regStats()
457{
458    BaseO3CPU::regStats();
459
460    // Register any of the O3CPU's stats here.
461    timesIdled
462        .name(name() + ".timesIdled")
463        .desc("Number of times that the entire CPU went into an idle state and"
464              " unscheduled itself")
465        .prereq(timesIdled);
466
467    idleCycles
468        .name(name() + ".idleCycles")
469        .desc("Total number of cycles that the CPU has spent unscheduled due "
470              "to idling")
471        .prereq(idleCycles);
472
473    // Number of Instructions simulated
474    // --------------------------------
475    // Should probably be in Base CPU but need templated
476    // MaxThreads so put in here instead
477    committedInsts
478        .init(numThreads)
479        .name(name() + ".committedInsts")
480        .desc("Number of Instructions Simulated");
481
482    totalCommittedInsts
483        .name(name() + ".committedInsts_total")
484        .desc("Number of Instructions Simulated");
485
486    cpi
487        .name(name() + ".cpi")
488        .desc("CPI: Cycles Per Instruction")
489        .precision(6);
490    cpi = numCycles / committedInsts;
491
492    totalCpi
493        .name(name() + ".cpi_total")
494        .desc("CPI: Total CPI of All Threads")
495        .precision(6);
496    totalCpi = numCycles / totalCommittedInsts;
497
498    ipc
499        .name(name() + ".ipc")
500        .desc("IPC: Instructions Per Cycle")
501        .precision(6);
502    ipc =  committedInsts / numCycles;
503
504    totalIpc
505        .name(name() + ".ipc_total")
506        .desc("IPC: Total IPC of All Threads")
507        .precision(6);
508    totalIpc =  totalCommittedInsts / numCycles;
509
510    this->fetch.regStats();
511    this->decode.regStats();
512    this->rename.regStats();
513    this->iew.regStats();
514    this->commit.regStats();
515}
516
517template <class Impl>
518Port *
519FullO3CPU<Impl>::getPort(const std::string &if_name, int idx)
520{
521    if (if_name == "dcache_port")
522        return iew.getDcachePort();
523    else if (if_name == "icache_port")
524        return fetch.getIcachePort();
525    else
526        panic("No Such Port\n");
527}
528
529template <class Impl>
530void
531FullO3CPU<Impl>::tick()
532{
533    DPRINTF(O3CPU, "\n\nFullO3CPU: Ticking main, FullO3CPU.\n");
534
535    ++numCycles;
536
537//    activity = false;
538
539    //Tick each of the stages
540    fetch.tick();
541
542    decode.tick();
543
544    rename.tick();
545
546    iew.tick();
547
548    commit.tick();
549
550#if !FULL_SYSTEM
551    doContextSwitch();
552#endif
553
554    // Now advance the time buffers
555    timeBuffer.advance();
556
557    fetchQueue.advance();
558    decodeQueue.advance();
559    renameQueue.advance();
560    iewQueue.advance();
561
562    activityRec.advance();
563
564    if (removeInstsThisCycle) {
565        cleanUpRemovedInsts();
566    }
567
568    if (!tickEvent.scheduled()) {
569        if (_status == SwitchedOut ||
570            getState() == SimObject::Drained) {
571            DPRINTF(O3CPU, "Switched out!\n");
572            // increment stat
573            lastRunningCycle = curTick;
574        } else if (!activityRec.active() || _status == Idle) {
575            DPRINTF(O3CPU, "Idle!\n");
576            lastRunningCycle = curTick;
577            timesIdled++;
578        } else {
579            schedule(tickEvent, nextCycle(curTick + ticks(1)));
580            DPRINTF(O3CPU, "Scheduling next tick!\n");
581        }
582    }
583
584#if !FULL_SYSTEM
585    updateThreadPriority();
586#endif
587}
588
589template <class Impl>
590void
591FullO3CPU<Impl>::init()
592{
593    if (!deferRegistration) {
594        registerThreadContexts();
595    }
596
597    // Set inSyscall so that the CPU doesn't squash when initially
598    // setting up registers.
599    for (int i = 0; i < number_of_threads; ++i)
600        thread[i]->inSyscall = true;
601
602    for (int tid=0; tid < number_of_threads; tid++) {
603#if FULL_SYSTEM
604        ThreadContext *src_tc = threadContexts[tid];
605#else
606        ThreadContext *src_tc = thread[tid]->getTC();
607#endif
608        // Threads start in the Suspended State
609        if (src_tc->status() != ThreadContext::Suspended) {
610            continue;
611        }
612
613#if FULL_SYSTEM
614        TheISA::initCPU(src_tc, src_tc->readCpuId());
615#endif
616    }
617
618    // Clear inSyscall.
619    for (int i = 0; i < number_of_threads; ++i)
620        thread[i]->inSyscall = false;
621
622    // Initialize stages.
623    fetch.initStage();
624    iew.initStage();
625    rename.initStage();
626    commit.initStage();
627
628    commit.setThreads(thread);
629}
630
631template <class Impl>
632void
633FullO3CPU<Impl>::activateThread(unsigned tid)
634{
635    std::list<unsigned>::iterator isActive =
636        std::find(activeThreads.begin(), activeThreads.end(), tid);
637
638    DPRINTF(O3CPU, "[tid:%i]: Calling activate thread.\n", tid);
639
640    if (isActive == activeThreads.end()) {
641        DPRINTF(O3CPU, "[tid:%i]: Adding to active threads list\n",
642                tid);
643
644        activeThreads.push_back(tid);
645    }
646}
647
648template <class Impl>
649void
650FullO3CPU<Impl>::deactivateThread(unsigned tid)
651{
652    //Remove From Active List, if Active
653    std::list<unsigned>::iterator thread_it =
654        std::find(activeThreads.begin(), activeThreads.end(), tid);
655
656    DPRINTF(O3CPU, "[tid:%i]: Calling deactivate thread.\n", tid);
657
658    if (thread_it != activeThreads.end()) {
659        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
660                tid);
661        activeThreads.erase(thread_it);
662    }
663}
664
665template <class Impl>
666void
667FullO3CPU<Impl>::activateContext(int tid, int delay)
668{
669    // Needs to set each stage to running as well.
670    if (delay){
671        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to activate "
672                "on cycle %d\n", tid, curTick + ticks(delay));
673        scheduleActivateThreadEvent(tid, delay);
674    } else {
675        activateThread(tid);
676    }
677
678    if (lastActivatedCycle < curTick) {
679        scheduleTickEvent(delay);
680
681        // Be sure to signal that there's some activity so the CPU doesn't
682        // deschedule itself.
683        activityRec.activity();
684        fetch.wakeFromQuiesce();
685
686        lastActivatedCycle = curTick;
687
688        _status = Running;
689    }
690}
691
692template <class Impl>
693bool
694FullO3CPU<Impl>::deallocateContext(int tid, bool remove, int delay)
695{
696    // Schedule removal of thread data from CPU
697    if (delay){
698        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to deallocate "
699                "on cycle %d\n", tid, curTick + ticks(delay));
700        scheduleDeallocateContextEvent(tid, remove, delay);
701        return false;
702    } else {
703        deactivateThread(tid);
704        if (remove)
705            removeThread(tid);
706        return true;
707    }
708}
709
710template <class Impl>
711void
712FullO3CPU<Impl>::suspendContext(int tid)
713{
714    DPRINTF(O3CPU,"[tid: %i]: Suspending Thread Context.\n", tid);
715    bool deallocated = deallocateContext(tid, false, 1);
716    // If this was the last thread then unschedule the tick event.
717    if ((activeThreads.size() == 1 && !deallocated) ||
718        activeThreads.size() == 0)
719        unscheduleTickEvent();
720    _status = Idle;
721}
722
723template <class Impl>
724void
725FullO3CPU<Impl>::haltContext(int tid)
726{
727    //For now, this is the same as deallocate
728    DPRINTF(O3CPU,"[tid:%i]: Halt Context called. Deallocating", tid);
729    deallocateContext(tid, true, 1);
730}
731
732template <class Impl>
733void
734FullO3CPU<Impl>::insertThread(unsigned tid)
735{
736    DPRINTF(O3CPU,"[tid:%i] Initializing thread into CPU");
737    // Will change now that the PC and thread state is internal to the CPU
738    // and not in the ThreadContext.
739#if FULL_SYSTEM
740    ThreadContext *src_tc = system->threadContexts[tid];
741#else
742    ThreadContext *src_tc = tcBase(tid);
743#endif
744
745    //Bind Int Regs to Rename Map
746    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
747        PhysRegIndex phys_reg = freeList.getIntReg();
748
749        renameMap[tid].setEntry(ireg,phys_reg);
750        scoreboard.setReg(phys_reg);
751    }
752
753    //Bind Float Regs to Rename Map
754    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
755        PhysRegIndex phys_reg = freeList.getFloatReg();
756
757        renameMap[tid].setEntry(freg,phys_reg);
758        scoreboard.setReg(phys_reg);
759    }
760
761    //Copy Thread Data Into RegFile
762    //this->copyFromTC(tid);
763
764    //Set PC/NPC/NNPC
765    setPC(src_tc->readPC(), tid);
766    setNextPC(src_tc->readNextPC(), tid);
767    setNextNPC(src_tc->readNextNPC(), tid);
768
769    src_tc->setStatus(ThreadContext::Active);
770
771    activateContext(tid,1);
772
773    //Reset ROB/IQ/LSQ Entries
774    commit.rob->resetEntries();
775    iew.resetEntries();
776}
777
778template <class Impl>
779void
780FullO3CPU<Impl>::removeThread(unsigned tid)
781{
782    DPRINTF(O3CPU,"[tid:%i] Removing thread context from CPU.\n", tid);
783
784    // Copy Thread Data From RegFile
785    // If thread is suspended, it might be re-allocated
786    // this->copyToTC(tid);
787
788
789    // @todo: 2-27-2008: Fix how we free up rename mappings
790    // here to alleviate the case for double-freeing registers
791    // in SMT workloads.
792
793    // Unbind Int Regs from Rename Map
794    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
795        PhysRegIndex phys_reg = renameMap[tid].lookup(ireg);
796
797        scoreboard.unsetReg(phys_reg);
798        freeList.addReg(phys_reg);
799    }
800
801    // Unbind Float Regs from Rename Map
802    for (int freg = TheISA::NumIntRegs; freg < TheISA::NumFloatRegs; freg++) {
803        PhysRegIndex phys_reg = renameMap[tid].lookup(freg);
804
805        scoreboard.unsetReg(phys_reg);
806        freeList.addReg(phys_reg);
807    }
808
809    // Squash Throughout Pipeline
810    InstSeqNum squash_seq_num = commit.rob->readHeadInst(tid)->seqNum;
811    fetch.squash(0, sizeof(TheISA::MachInst), 0, squash_seq_num, tid);
812    decode.squash(tid);
813    rename.squash(squash_seq_num, tid);
814    iew.squash(tid);
815    iew.ldstQueue.squash(squash_seq_num, tid);
816    commit.rob->squash(squash_seq_num, tid);
817
818
819    assert(iew.instQueue.getCount(tid) == 0);
820    assert(iew.ldstQueue.getCount(tid) == 0);
821
822    // Reset ROB/IQ/LSQ Entries
823
824    // Commented out for now.  This should be possible to do by
825    // telling all the pipeline stages to drain first, and then
826    // checking until the drain completes.  Once the pipeline is
827    // drained, call resetEntries(). - 10-09-06 ktlim
828/*
829    if (activeThreads.size() >= 1) {
830        commit.rob->resetEntries();
831        iew.resetEntries();
832    }
833*/
834}
835
836
837template <class Impl>
838void
839FullO3CPU<Impl>::activateWhenReady(int tid)
840{
841    DPRINTF(O3CPU,"[tid:%i]: Checking if resources are available for incoming"
842            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
843            tid);
844
845    bool ready = true;
846
847    if (freeList.numFreeIntRegs() >= TheISA::NumIntRegs) {
848        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
849                "Phys. Int. Regs.\n",
850                tid);
851        ready = false;
852    } else if (freeList.numFreeFloatRegs() >= TheISA::NumFloatRegs) {
853        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
854                "Phys. Float. Regs.\n",
855                tid);
856        ready = false;
857    } else if (commit.rob->numFreeEntries() >=
858               commit.rob->entryAmount(activeThreads.size() + 1)) {
859        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
860                "ROB entries.\n",
861                tid);
862        ready = false;
863    } else if (iew.instQueue.numFreeEntries() >=
864               iew.instQueue.entryAmount(activeThreads.size() + 1)) {
865        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
866                "IQ entries.\n",
867                tid);
868        ready = false;
869    } else if (iew.ldstQueue.numFreeEntries() >=
870               iew.ldstQueue.entryAmount(activeThreads.size() + 1)) {
871        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
872                "LSQ entries.\n",
873                tid);
874        ready = false;
875    }
876
877    if (ready) {
878        insertThread(tid);
879
880        contextSwitch = false;
881
882        cpuWaitList.remove(tid);
883    } else {
884        suspendContext(tid);
885
886        //blocks fetch
887        contextSwitch = true;
888
889        //@todo: dont always add to waitlist
890        //do waitlist
891        cpuWaitList.push_back(tid);
892    }
893}
894
895#if FULL_SYSTEM
896template <class Impl>
897void
898FullO3CPU<Impl>::post_interrupt(int int_num, int index)
899{
900    BaseCPU::post_interrupt(int_num, index);
901
902    if (this->thread[0]->status() == ThreadContext::Suspended) {
903        DPRINTF(IPI,"Suspended Processor awoke\n");
904        this->threadContexts[0]->activate();
905    }
906}
907
908template <class Impl>
909bool
910FullO3CPU<Impl>::simPalCheck(int palFunc, unsigned tid)
911{
912#if THE_ISA == ALPHA_ISA
913    if (this->thread[tid]->kernelStats)
914        this->thread[tid]->kernelStats->callpal(palFunc,
915                                                this->threadContexts[tid]);
916
917    switch (palFunc) {
918      case PAL::halt:
919        halt();
920        if (--System::numSystemsRunning == 0)
921            exitSimLoop("all cpus halted");
922        break;
923
924      case PAL::bpt:
925      case PAL::bugchk:
926        if (this->system->breakpoint())
927            return false;
928        break;
929    }
930#endif
931    return true;
932}
933
934template <class Impl>
935Fault
936FullO3CPU<Impl>::getInterrupts()
937{
938    // Check if there are any outstanding interrupts
939    return this->interrupts.getInterrupt(this->threadContexts[0]);
940}
941
942template <class Impl>
943void
944FullO3CPU<Impl>::processInterrupts(Fault interrupt)
945{
946    // Check for interrupts here.  For now can copy the code that
947    // exists within isa_fullsys_traits.hh.  Also assume that thread 0
948    // is the one that handles the interrupts.
949    // @todo: Possibly consolidate the interrupt checking code.
950    // @todo: Allow other threads to handle interrupts.
951
952    assert(interrupt != NoFault);
953    this->interrupts.updateIntrInfo(this->threadContexts[0]);
954
955    DPRINTF(O3CPU, "Interrupt %s being handled\n", interrupt->name());
956    this->trap(interrupt, 0);
957}
958
959template <class Impl>
960void
961FullO3CPU<Impl>::updateMemPorts()
962{
963    // Update all ThreadContext's memory ports (Functional/Virtual
964    // Ports)
965    for (int i = 0; i < thread.size(); ++i)
966        thread[i]->connectMemPorts(thread[i]->getTC());
967}
968#endif
969
970template <class Impl>
971void
972FullO3CPU<Impl>::trap(Fault fault, unsigned tid)
973{
974    // Pass the thread's TC into the invoke method.
975    fault->invoke(this->threadContexts[tid]);
976}
977
978#if !FULL_SYSTEM
979
980template <class Impl>
981void
982FullO3CPU<Impl>::syscall(int64_t callnum, int tid)
983{
984    DPRINTF(O3CPU, "[tid:%i] Executing syscall().\n\n", tid);
985
986    DPRINTF(Activity,"Activity: syscall() called.\n");
987
988    // Temporarily increase this by one to account for the syscall
989    // instruction.
990    ++(this->thread[tid]->funcExeInst);
991
992    // Execute the actual syscall.
993    this->thread[tid]->syscall(callnum);
994
995    // Decrease funcExeInst by one as the normal commit will handle
996    // incrementing it.
997    --(this->thread[tid]->funcExeInst);
998}
999
1000template <class Impl>
1001void
1002FullO3CPU<Impl>::setSyscallReturn(SyscallReturn return_value, int tid)
1003{
1004    TheISA::setSyscallReturn(return_value, this->tcBase(tid));
1005}
1006
1007#endif
1008
1009template <class Impl>
1010void
1011FullO3CPU<Impl>::serialize(std::ostream &os)
1012{
1013    SimObject::State so_state = SimObject::getState();
1014    SERIALIZE_ENUM(so_state);
1015    BaseCPU::serialize(os);
1016    nameOut(os, csprintf("%s.tickEvent", name()));
1017    tickEvent.serialize(os);
1018
1019    // Use SimpleThread's ability to checkpoint to make it easier to
1020    // write out the registers.  Also make this static so it doesn't
1021    // get instantiated multiple times (causes a panic in statistics).
1022    static SimpleThread temp;
1023
1024    for (int i = 0; i < thread.size(); i++) {
1025        nameOut(os, csprintf("%s.xc.%i", name(), i));
1026        temp.copyTC(thread[i]->getTC());
1027        temp.serialize(os);
1028    }
1029}
1030
1031template <class Impl>
1032void
1033FullO3CPU<Impl>::unserialize(Checkpoint *cp, const std::string &section)
1034{
1035    SimObject::State so_state;
1036    UNSERIALIZE_ENUM(so_state);
1037    BaseCPU::unserialize(cp, section);
1038    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));
1039
1040    // Use SimpleThread's ability to checkpoint to make it easier to
1041    // read in the registers.  Also make this static so it doesn't
1042    // get instantiated multiple times (causes a panic in statistics).
1043    static SimpleThread temp;
1044
1045    for (int i = 0; i < thread.size(); i++) {
1046        temp.copyTC(thread[i]->getTC());
1047        temp.unserialize(cp, csprintf("%s.xc.%i", section, i));
1048        thread[i]->getTC()->copyArchRegs(temp.getTC());
1049    }
1050}
1051
1052template <class Impl>
1053unsigned int
1054FullO3CPU<Impl>::drain(Event *drain_event)
1055{
1056    DPRINTF(O3CPU, "Switching out\n");
1057
1058    // If the CPU isn't doing anything, then return immediately.
1059    if (_status == Idle || _status == SwitchedOut) {
1060        return 0;
1061    }
1062
1063    drainCount = 0;
1064    fetch.drain();
1065    decode.drain();
1066    rename.drain();
1067    iew.drain();
1068    commit.drain();
1069
1070    // Wake the CPU and record activity so everything can drain out if
1071    // the CPU was not able to immediately drain.
1072    if (getState() != SimObject::Drained) {
1073        // A bit of a hack...set the drainEvent after all the drain()
1074        // calls have been made, that way if all of the stages drain
1075        // immediately, the signalDrained() function knows not to call
1076        // process on the drain event.
1077        drainEvent = drain_event;
1078
1079        wakeCPU();
1080        activityRec.activity();
1081
1082        return 1;
1083    } else {
1084        return 0;
1085    }
1086}
1087
1088template <class Impl>
1089void
1090FullO3CPU<Impl>::resume()
1091{
1092    fetch.resume();
1093    decode.resume();
1094    rename.resume();
1095    iew.resume();
1096    commit.resume();
1097
1098    changeState(SimObject::Running);
1099
1100    if (_status == SwitchedOut || _status == Idle)
1101        return;
1102
1103#if FULL_SYSTEM
1104    assert(system->getMemoryMode() == Enums::timing);
1105#endif
1106
1107    if (!tickEvent.scheduled())
1108        schedule(tickEvent, nextCycle());
1109    _status = Running;
1110}
1111
1112template <class Impl>
1113void
1114FullO3CPU<Impl>::signalDrained()
1115{
1116    if (++drainCount == NumStages) {
1117        if (tickEvent.scheduled())
1118            tickEvent.squash();
1119
1120        changeState(SimObject::Drained);
1121
1122        BaseCPU::switchOut();
1123
1124        if (drainEvent) {
1125            drainEvent->process();
1126            drainEvent = NULL;
1127        }
1128    }
1129    assert(drainCount <= 5);
1130}
1131
1132template <class Impl>
1133void
1134FullO3CPU<Impl>::switchOut()
1135{
1136    fetch.switchOut();
1137    rename.switchOut();
1138    iew.switchOut();
1139    commit.switchOut();
1140    instList.clear();
1141    while (!removeList.empty()) {
1142        removeList.pop();
1143    }
1144
1145    _status = SwitchedOut;
1146#if USE_CHECKER
1147    if (checker)
1148        checker->switchOut();
1149#endif
1150    if (tickEvent.scheduled())
1151        tickEvent.squash();
1152}
1153
1154template <class Impl>
1155void
1156FullO3CPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
1157{
1158    // Flush out any old data from the time buffers.
1159    for (int i = 0; i < timeBuffer.getSize(); ++i) {
1160        timeBuffer.advance();
1161        fetchQueue.advance();
1162        decodeQueue.advance();
1163        renameQueue.advance();
1164        iewQueue.advance();
1165    }
1166
1167    activityRec.reset();
1168
1169    BaseCPU::takeOverFrom(oldCPU, fetch.getIcachePort(), iew.getDcachePort());
1170
1171    fetch.takeOverFrom();
1172    decode.takeOverFrom();
1173    rename.takeOverFrom();
1174    iew.takeOverFrom();
1175    commit.takeOverFrom();
1176
1177    assert(!tickEvent.scheduled());
1178
1179    // @todo: Figure out how to properly select the tid to put onto
1180    // the active threads list.
1181    int tid = 0;
1182
1183    std::list<unsigned>::iterator isActive =
1184        std::find(activeThreads.begin(), activeThreads.end(), tid);
1185
1186    if (isActive == activeThreads.end()) {
1187        //May Need to Re-code this if the delay variable is the delay
1188        //needed for thread to activate
1189        DPRINTF(O3CPU, "Adding Thread %i to active threads list\n",
1190                tid);
1191
1192        activeThreads.push_back(tid);
1193    }
1194
1195    // Set all statuses to active, schedule the CPU's tick event.
1196    // @todo: Fix up statuses so this is handled properly
1197    for (int i = 0; i < threadContexts.size(); ++i) {
1198        ThreadContext *tc = threadContexts[i];
1199        if (tc->status() == ThreadContext::Active && _status != Running) {
1200            _status = Running;
1201            schedule(tickEvent, nextCycle());
1202        }
1203    }
1204    if (!tickEvent.scheduled())
1205        schedule(tickEvent, nextCycle());
1206}
1207
1208template <class Impl>
1209TheISA::MiscReg
1210FullO3CPU<Impl>::readMiscRegNoEffect(int misc_reg, unsigned tid)
1211{
1212    return this->regFile.readMiscRegNoEffect(misc_reg, tid);
1213}
1214
1215template <class Impl>
1216TheISA::MiscReg
1217FullO3CPU<Impl>::readMiscReg(int misc_reg, unsigned tid)
1218{
1219    return this->regFile.readMiscReg(misc_reg, tid);
1220}
1221
1222template <class Impl>
1223void
1224FullO3CPU<Impl>::setMiscRegNoEffect(int misc_reg,
1225        const TheISA::MiscReg &val, unsigned tid)
1226{
1227    this->regFile.setMiscRegNoEffect(misc_reg, val, tid);
1228}
1229
1230template <class Impl>
1231void
1232FullO3CPU<Impl>::setMiscReg(int misc_reg,
1233        const TheISA::MiscReg &val, unsigned tid)
1234{
1235    this->regFile.setMiscReg(misc_reg, val, tid);
1236}
1237
1238template <class Impl>
1239uint64_t
1240FullO3CPU<Impl>::readIntReg(int reg_idx)
1241{
1242    return regFile.readIntReg(reg_idx);
1243}
1244
1245template <class Impl>
1246FloatReg
1247FullO3CPU<Impl>::readFloatReg(int reg_idx, int width)
1248{
1249    return regFile.readFloatReg(reg_idx, width);
1250}
1251
1252template <class Impl>
1253FloatReg
1254FullO3CPU<Impl>::readFloatReg(int reg_idx)
1255{
1256    return regFile.readFloatReg(reg_idx);
1257}
1258
1259template <class Impl>
1260FloatRegBits
1261FullO3CPU<Impl>::readFloatRegBits(int reg_idx, int width)
1262{
1263    return regFile.readFloatRegBits(reg_idx, width);
1264}
1265
1266template <class Impl>
1267FloatRegBits
1268FullO3CPU<Impl>::readFloatRegBits(int reg_idx)
1269{
1270    return regFile.readFloatRegBits(reg_idx);
1271}
1272
1273template <class Impl>
1274void
1275FullO3CPU<Impl>::setIntReg(int reg_idx, uint64_t val)
1276{
1277    regFile.setIntReg(reg_idx, val);
1278}
1279
1280template <class Impl>
1281void
1282FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val, int width)
1283{
1284    regFile.setFloatReg(reg_idx, val, width);
1285}
1286
1287template <class Impl>
1288void
1289FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val)
1290{
1291    regFile.setFloatReg(reg_idx, val);
1292}
1293
1294template <class Impl>
1295void
1296FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val, int width)
1297{
1298    regFile.setFloatRegBits(reg_idx, val, width);
1299}
1300
1301template <class Impl>
1302void
1303FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val)
1304{
1305    regFile.setFloatRegBits(reg_idx, val);
1306}
1307
1308template <class Impl>
1309uint64_t
1310FullO3CPU<Impl>::readArchIntReg(int reg_idx, unsigned tid)
1311{
1312    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1313
1314    return regFile.readIntReg(phys_reg);
1315}
1316
1317template <class Impl>
1318float
1319FullO3CPU<Impl>::readArchFloatRegSingle(int reg_idx, unsigned tid)
1320{
1321    int idx = reg_idx + TheISA::FP_Base_DepTag;
1322    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1323
1324    return regFile.readFloatReg(phys_reg);
1325}
1326
1327template <class Impl>
1328double
1329FullO3CPU<Impl>::readArchFloatRegDouble(int reg_idx, unsigned tid)
1330{
1331    int idx = reg_idx + TheISA::FP_Base_DepTag;
1332    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1333
1334    return regFile.readFloatReg(phys_reg, 64);
1335}
1336
1337template <class Impl>
1338uint64_t
1339FullO3CPU<Impl>::readArchFloatRegInt(int reg_idx, unsigned tid)
1340{
1341    int idx = reg_idx + TheISA::FP_Base_DepTag;
1342    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1343
1344    return regFile.readFloatRegBits(phys_reg);
1345}
1346
1347template <class Impl>
1348void
1349FullO3CPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, unsigned tid)
1350{
1351    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1352
1353    regFile.setIntReg(phys_reg, val);
1354}
1355
1356template <class Impl>
1357void
1358FullO3CPU<Impl>::setArchFloatRegSingle(int reg_idx, float val, unsigned tid)
1359{
1360    int idx = reg_idx + TheISA::FP_Base_DepTag;
1361    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1362
1363    regFile.setFloatReg(phys_reg, val);
1364}
1365
1366template <class Impl>
1367void
1368FullO3CPU<Impl>::setArchFloatRegDouble(int reg_idx, double val, unsigned tid)
1369{
1370    int idx = reg_idx + TheISA::FP_Base_DepTag;
1371    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1372
1373    regFile.setFloatReg(phys_reg, val, 64);
1374}
1375
1376template <class Impl>
1377void
1378FullO3CPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid)
1379{
1380    int idx = reg_idx + TheISA::FP_Base_DepTag;
1381    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1382
1383    regFile.setFloatRegBits(phys_reg, val);
1384}
1385
1386template <class Impl>
1387uint64_t
1388FullO3CPU<Impl>::readPC(unsigned tid)
1389{
1390    return commit.readPC(tid);
1391}
1392
1393template <class Impl>
1394void
1395FullO3CPU<Impl>::setPC(Addr new_PC,unsigned tid)
1396{
1397    commit.setPC(new_PC, tid);
1398}
1399
1400template <class Impl>
1401uint64_t
1402FullO3CPU<Impl>::readMicroPC(unsigned tid)
1403{
1404    return commit.readMicroPC(tid);
1405}
1406
1407template <class Impl>
1408void
1409FullO3CPU<Impl>::setMicroPC(Addr new_PC,unsigned tid)
1410{
1411    commit.setMicroPC(new_PC, tid);
1412}
1413
1414template <class Impl>
1415uint64_t
1416FullO3CPU<Impl>::readNextPC(unsigned tid)
1417{
1418    return commit.readNextPC(tid);
1419}
1420
1421template <class Impl>
1422void
1423FullO3CPU<Impl>::setNextPC(uint64_t val,unsigned tid)
1424{
1425    commit.setNextPC(val, tid);
1426}
1427
1428template <class Impl>
1429uint64_t
1430FullO3CPU<Impl>::readNextNPC(unsigned tid)
1431{
1432    return commit.readNextNPC(tid);
1433}
1434
1435template <class Impl>
1436void
1437FullO3CPU<Impl>::setNextNPC(uint64_t val,unsigned tid)
1438{
1439    commit.setNextNPC(val, tid);
1440}
1441
1442template <class Impl>
1443uint64_t
1444FullO3CPU<Impl>::readNextMicroPC(unsigned tid)
1445{
1446    return commit.readNextMicroPC(tid);
1447}
1448
1449template <class Impl>
1450void
1451FullO3CPU<Impl>::setNextMicroPC(Addr new_PC,unsigned tid)
1452{
1453    commit.setNextMicroPC(new_PC, tid);
1454}
1455
1456template <class Impl>
1457void
1458FullO3CPU<Impl>::squashFromTC(unsigned tid)
1459{
1460    this->thread[tid]->inSyscall = true;
1461    this->commit.generateTCEvent(tid);
1462}
1463
1464template <class Impl>
1465typename FullO3CPU<Impl>::ListIt
1466FullO3CPU<Impl>::addInst(DynInstPtr &inst)
1467{
1468    instList.push_back(inst);
1469
1470    return --(instList.end());
1471}
1472
1473template <class Impl>
1474void
1475FullO3CPU<Impl>::instDone(unsigned tid)
1476{
1477    // Keep an instruction count.
1478    thread[tid]->numInst++;
1479    thread[tid]->numInsts++;
1480    committedInsts[tid]++;
1481    totalCommittedInsts++;
1482
1483    // Check for instruction-count-based events.
1484    comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1485}
1486
1487template <class Impl>
1488void
1489FullO3CPU<Impl>::addToRemoveList(DynInstPtr &inst)
1490{
1491    removeInstsThisCycle = true;
1492
1493    removeList.push(inst->getInstListIt());
1494}
1495
1496template <class Impl>
1497void
1498FullO3CPU<Impl>::removeFrontInst(DynInstPtr &inst)
1499{
1500    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %#x "
1501            "[sn:%lli]\n",
1502            inst->threadNumber, inst->readPC(), inst->seqNum);
1503
1504    removeInstsThisCycle = true;
1505
1506    // Remove the front instruction.
1507    removeList.push(inst->getInstListIt());
1508}
1509
1510template <class Impl>
1511void
1512FullO3CPU<Impl>::removeInstsNotInROB(unsigned tid)
1513{
1514    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
1515            " list.\n", tid);
1516
1517    ListIt end_it;
1518
1519    bool rob_empty = false;
1520
1521    if (instList.empty()) {
1522        return;
1523    } else if (rob.isEmpty(/*tid*/)) {
1524        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
1525        end_it = instList.begin();
1526        rob_empty = true;
1527    } else {
1528        end_it = (rob.readTailInst(tid))->getInstListIt();
1529        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
1530    }
1531
1532    removeInstsThisCycle = true;
1533
1534    ListIt inst_it = instList.end();
1535
1536    inst_it--;
1537
1538    // Walk through the instruction list, removing any instructions
1539    // that were inserted after the given instruction iterator, end_it.
1540    while (inst_it != end_it) {
1541        assert(!instList.empty());
1542
1543        squashInstIt(inst_it, tid);
1544
1545        inst_it--;
1546    }
1547
1548    // If the ROB was empty, then we actually need to remove the first
1549    // instruction as well.
1550    if (rob_empty) {
1551        squashInstIt(inst_it, tid);
1552    }
1553}
1554
1555template <class Impl>
1556void
1557FullO3CPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num,
1558                                  unsigned tid)
1559{
1560    assert(!instList.empty());
1561
1562    removeInstsThisCycle = true;
1563
1564    ListIt inst_iter = instList.end();
1565
1566    inst_iter--;
1567
1568    DPRINTF(O3CPU, "Deleting instructions from instruction "
1569            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1570            tid, seq_num, (*inst_iter)->seqNum);
1571
1572    while ((*inst_iter)->seqNum > seq_num) {
1573
1574        bool break_loop = (inst_iter == instList.begin());
1575
1576        squashInstIt(inst_iter, tid);
1577
1578        inst_iter--;
1579
1580        if (break_loop)
1581            break;
1582    }
1583}
1584
1585template <class Impl>
1586inline void
1587FullO3CPU<Impl>::squashInstIt(const ListIt &instIt, const unsigned &tid)
1588{
1589    if ((*instIt)->threadNumber == tid) {
1590        DPRINTF(O3CPU, "Squashing instruction, "
1591                "[tid:%i] [sn:%lli] PC %#x\n",
1592                (*instIt)->threadNumber,
1593                (*instIt)->seqNum,
1594                (*instIt)->readPC());
1595
1596        // Mark it as squashed.
1597        (*instIt)->setSquashed();
1598
1599        // @todo: Formulate a consistent method for deleting
1600        // instructions from the instruction list
1601        // Remove the instruction from the list.
1602        removeList.push(instIt);
1603    }
1604}
1605
1606template <class Impl>
1607void
1608FullO3CPU<Impl>::cleanUpRemovedInsts()
1609{
1610    while (!removeList.empty()) {
1611        DPRINTF(O3CPU, "Removing instruction, "
1612                "[tid:%i] [sn:%lli] PC %#x\n",
1613                (*removeList.front())->threadNumber,
1614                (*removeList.front())->seqNum,
1615                (*removeList.front())->readPC());
1616
1617        instList.erase(removeList.front());
1618
1619        removeList.pop();
1620    }
1621
1622    removeInstsThisCycle = false;
1623}
1624/*
1625template <class Impl>
1626void
1627FullO3CPU<Impl>::removeAllInsts()
1628{
1629    instList.clear();
1630}
1631*/
1632template <class Impl>
1633void
1634FullO3CPU<Impl>::dumpInsts()
1635{
1636    int num = 0;
1637
1638    ListIt inst_list_it = instList.begin();
1639
1640    cprintf("Dumping Instruction List\n");
1641
1642    while (inst_list_it != instList.end()) {
1643        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1644                "Squashed:%i\n\n",
1645                num, (*inst_list_it)->readPC(), (*inst_list_it)->threadNumber,
1646                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1647                (*inst_list_it)->isSquashed());
1648        inst_list_it++;
1649        ++num;
1650    }
1651}
1652/*
1653template <class Impl>
1654void
1655FullO3CPU<Impl>::wakeDependents(DynInstPtr &inst)
1656{
1657    iew.wakeDependents(inst);
1658}
1659*/
1660template <class Impl>
1661void
1662FullO3CPU<Impl>::wakeCPU()
1663{
1664    if (activityRec.active() || tickEvent.scheduled()) {
1665        DPRINTF(Activity, "CPU already running.\n");
1666        return;
1667    }
1668
1669    DPRINTF(Activity, "Waking up CPU\n");
1670
1671    idleCycles += tickToCycles((curTick - 1) - lastRunningCycle);
1672    numCycles += tickToCycles((curTick - 1) - lastRunningCycle);
1673
1674    schedule(tickEvent, nextCycle());
1675}
1676
1677template <class Impl>
1678int
1679FullO3CPU<Impl>::getFreeTid()
1680{
1681    for (int i=0; i < numThreads; i++) {
1682        if (!tids[i]) {
1683            tids[i] = true;
1684            return i;
1685        }
1686    }
1687
1688    return -1;
1689}
1690
1691template <class Impl>
1692void
1693FullO3CPU<Impl>::doContextSwitch()
1694{
1695    if (contextSwitch) {
1696
1697        //ADD CODE TO DEACTIVE THREAD HERE (???)
1698
1699        for (int tid=0; tid < cpuWaitList.size(); tid++) {
1700            activateWhenReady(tid);
1701        }
1702
1703        if (cpuWaitList.size() == 0)
1704            contextSwitch = true;
1705    }
1706}
1707
1708template <class Impl>
1709void
1710FullO3CPU<Impl>::updateThreadPriority()
1711{
1712    if (activeThreads.size() > 1)
1713    {
1714        //DEFAULT TO ROUND ROBIN SCHEME
1715        //e.g. Move highest priority to end of thread list
1716        std::list<unsigned>::iterator list_begin = activeThreads.begin();
1717        std::list<unsigned>::iterator list_end   = activeThreads.end();
1718
1719        unsigned high_thread = *list_begin;
1720
1721        activeThreads.erase(list_begin);
1722
1723        activeThreads.push_back(high_thread);
1724    }
1725}
1726
1727// Forward declaration of FullO3CPU.
1728template class FullO3CPU<O3CPUImpl>;
1729