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