cpu.cc revision 5702:bf84e2fa05f7
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>
909Fault
910FullO3CPU<Impl>::hwrei(unsigned tid)
911{
912#if THE_ISA == ALPHA_ISA
913    // Need to clear the lock flag upon returning from an interrupt.
914    this->setMiscRegNoEffect(AlphaISA::MISCREG_LOCKFLAG, false, tid);
915
916    this->thread[tid]->kernelStats->hwrei();
917
918    // FIXME: XXX check for interrupts? XXX
919#endif
920    return NoFault;
921}
922
923template <class Impl>
924bool
925FullO3CPU<Impl>::simPalCheck(int palFunc, unsigned tid)
926{
927#if THE_ISA == ALPHA_ISA
928    if (this->thread[tid]->kernelStats)
929        this->thread[tid]->kernelStats->callpal(palFunc,
930                                                this->threadContexts[tid]);
931
932    switch (palFunc) {
933      case PAL::halt:
934        halt();
935        if (--System::numSystemsRunning == 0)
936            exitSimLoop("all cpus halted");
937        break;
938
939      case PAL::bpt:
940      case PAL::bugchk:
941        if (this->system->breakpoint())
942            return false;
943        break;
944    }
945#endif
946    return true;
947}
948
949template <class Impl>
950Fault
951FullO3CPU<Impl>::getInterrupts()
952{
953    // Check if there are any outstanding interrupts
954    return this->interrupts->getInterrupt(this->threadContexts[0]);
955}
956
957template <class Impl>
958void
959FullO3CPU<Impl>::processInterrupts(Fault interrupt)
960{
961    // Check for interrupts here.  For now can copy the code that
962    // exists within isa_fullsys_traits.hh.  Also assume that thread 0
963    // is the one that handles the interrupts.
964    // @todo: Possibly consolidate the interrupt checking code.
965    // @todo: Allow other threads to handle interrupts.
966
967    assert(interrupt != NoFault);
968    this->interrupts->updateIntrInfo(this->threadContexts[0]);
969
970    DPRINTF(O3CPU, "Interrupt %s being handled\n", interrupt->name());
971    this->trap(interrupt, 0);
972}
973
974template <class Impl>
975void
976FullO3CPU<Impl>::updateMemPorts()
977{
978    // Update all ThreadContext's memory ports (Functional/Virtual
979    // Ports)
980    for (int i = 0; i < thread.size(); ++i)
981        thread[i]->connectMemPorts(thread[i]->getTC());
982}
983#endif
984
985template <class Impl>
986void
987FullO3CPU<Impl>::trap(Fault fault, unsigned tid)
988{
989    // Pass the thread's TC into the invoke method.
990    fault->invoke(this->threadContexts[tid]);
991}
992
993#if !FULL_SYSTEM
994
995template <class Impl>
996void
997FullO3CPU<Impl>::syscall(int64_t callnum, int tid)
998{
999    DPRINTF(O3CPU, "[tid:%i] Executing syscall().\n\n", tid);
1000
1001    DPRINTF(Activity,"Activity: syscall() called.\n");
1002
1003    // Temporarily increase this by one to account for the syscall
1004    // instruction.
1005    ++(this->thread[tid]->funcExeInst);
1006
1007    // Execute the actual syscall.
1008    this->thread[tid]->syscall(callnum);
1009
1010    // Decrease funcExeInst by one as the normal commit will handle
1011    // incrementing it.
1012    --(this->thread[tid]->funcExeInst);
1013}
1014
1015template <class Impl>
1016void
1017FullO3CPU<Impl>::setSyscallReturn(SyscallReturn return_value, int tid)
1018{
1019    TheISA::setSyscallReturn(return_value, this->tcBase(tid));
1020}
1021
1022#endif
1023
1024template <class Impl>
1025void
1026FullO3CPU<Impl>::serialize(std::ostream &os)
1027{
1028    SimObject::State so_state = SimObject::getState();
1029    SERIALIZE_ENUM(so_state);
1030    BaseCPU::serialize(os);
1031    nameOut(os, csprintf("%s.tickEvent", name()));
1032    tickEvent.serialize(os);
1033
1034    // Use SimpleThread's ability to checkpoint to make it easier to
1035    // write out the registers.  Also make this static so it doesn't
1036    // get instantiated multiple times (causes a panic in statistics).
1037    static SimpleThread temp;
1038
1039    for (int i = 0; i < thread.size(); i++) {
1040        nameOut(os, csprintf("%s.xc.%i", name(), i));
1041        temp.copyTC(thread[i]->getTC());
1042        temp.serialize(os);
1043    }
1044}
1045
1046template <class Impl>
1047void
1048FullO3CPU<Impl>::unserialize(Checkpoint *cp, const std::string &section)
1049{
1050    SimObject::State so_state;
1051    UNSERIALIZE_ENUM(so_state);
1052    BaseCPU::unserialize(cp, section);
1053    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));
1054
1055    // Use SimpleThread's ability to checkpoint to make it easier to
1056    // read in the registers.  Also make this static so it doesn't
1057    // get instantiated multiple times (causes a panic in statistics).
1058    static SimpleThread temp;
1059
1060    for (int i = 0; i < thread.size(); i++) {
1061        temp.copyTC(thread[i]->getTC());
1062        temp.unserialize(cp, csprintf("%s.xc.%i", section, i));
1063        thread[i]->getTC()->copyArchRegs(temp.getTC());
1064    }
1065}
1066
1067template <class Impl>
1068unsigned int
1069FullO3CPU<Impl>::drain(Event *drain_event)
1070{
1071    DPRINTF(O3CPU, "Switching out\n");
1072
1073    // If the CPU isn't doing anything, then return immediately.
1074    if (_status == Idle || _status == SwitchedOut) {
1075        return 0;
1076    }
1077
1078    drainCount = 0;
1079    fetch.drain();
1080    decode.drain();
1081    rename.drain();
1082    iew.drain();
1083    commit.drain();
1084
1085    // Wake the CPU and record activity so everything can drain out if
1086    // the CPU was not able to immediately drain.
1087    if (getState() != SimObject::Drained) {
1088        // A bit of a hack...set the drainEvent after all the drain()
1089        // calls have been made, that way if all of the stages drain
1090        // immediately, the signalDrained() function knows not to call
1091        // process on the drain event.
1092        drainEvent = drain_event;
1093
1094        wakeCPU();
1095        activityRec.activity();
1096
1097        return 1;
1098    } else {
1099        return 0;
1100    }
1101}
1102
1103template <class Impl>
1104void
1105FullO3CPU<Impl>::resume()
1106{
1107    fetch.resume();
1108    decode.resume();
1109    rename.resume();
1110    iew.resume();
1111    commit.resume();
1112
1113    changeState(SimObject::Running);
1114
1115    if (_status == SwitchedOut || _status == Idle)
1116        return;
1117
1118#if FULL_SYSTEM
1119    assert(system->getMemoryMode() == Enums::timing);
1120#endif
1121
1122    if (!tickEvent.scheduled())
1123        schedule(tickEvent, nextCycle());
1124    _status = Running;
1125}
1126
1127template <class Impl>
1128void
1129FullO3CPU<Impl>::signalDrained()
1130{
1131    if (++drainCount == NumStages) {
1132        if (tickEvent.scheduled())
1133            tickEvent.squash();
1134
1135        changeState(SimObject::Drained);
1136
1137        BaseCPU::switchOut();
1138
1139        if (drainEvent) {
1140            drainEvent->process();
1141            drainEvent = NULL;
1142        }
1143    }
1144    assert(drainCount <= 5);
1145}
1146
1147template <class Impl>
1148void
1149FullO3CPU<Impl>::switchOut()
1150{
1151    fetch.switchOut();
1152    rename.switchOut();
1153    iew.switchOut();
1154    commit.switchOut();
1155    instList.clear();
1156    while (!removeList.empty()) {
1157        removeList.pop();
1158    }
1159
1160    _status = SwitchedOut;
1161#if USE_CHECKER
1162    if (checker)
1163        checker->switchOut();
1164#endif
1165    if (tickEvent.scheduled())
1166        tickEvent.squash();
1167}
1168
1169template <class Impl>
1170void
1171FullO3CPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
1172{
1173    // Flush out any old data from the time buffers.
1174    for (int i = 0; i < timeBuffer.getSize(); ++i) {
1175        timeBuffer.advance();
1176        fetchQueue.advance();
1177        decodeQueue.advance();
1178        renameQueue.advance();
1179        iewQueue.advance();
1180    }
1181
1182    activityRec.reset();
1183
1184    BaseCPU::takeOverFrom(oldCPU, fetch.getIcachePort(), iew.getDcachePort());
1185
1186    fetch.takeOverFrom();
1187    decode.takeOverFrom();
1188    rename.takeOverFrom();
1189    iew.takeOverFrom();
1190    commit.takeOverFrom();
1191
1192    assert(!tickEvent.scheduled());
1193
1194    // @todo: Figure out how to properly select the tid to put onto
1195    // the active threads list.
1196    int tid = 0;
1197
1198    std::list<unsigned>::iterator isActive =
1199        std::find(activeThreads.begin(), activeThreads.end(), tid);
1200
1201    if (isActive == activeThreads.end()) {
1202        //May Need to Re-code this if the delay variable is the delay
1203        //needed for thread to activate
1204        DPRINTF(O3CPU, "Adding Thread %i to active threads list\n",
1205                tid);
1206
1207        activeThreads.push_back(tid);
1208    }
1209
1210    // Set all statuses to active, schedule the CPU's tick event.
1211    // @todo: Fix up statuses so this is handled properly
1212    for (int i = 0; i < threadContexts.size(); ++i) {
1213        ThreadContext *tc = threadContexts[i];
1214        if (tc->status() == ThreadContext::Active && _status != Running) {
1215            _status = Running;
1216            schedule(tickEvent, nextCycle());
1217        }
1218    }
1219    if (!tickEvent.scheduled())
1220        schedule(tickEvent, nextCycle());
1221}
1222
1223template <class Impl>
1224TheISA::MiscReg
1225FullO3CPU<Impl>::readMiscRegNoEffect(int misc_reg, unsigned tid)
1226{
1227    return this->regFile.readMiscRegNoEffect(misc_reg, tid);
1228}
1229
1230template <class Impl>
1231TheISA::MiscReg
1232FullO3CPU<Impl>::readMiscReg(int misc_reg, unsigned tid)
1233{
1234    return this->regFile.readMiscReg(misc_reg, tid);
1235}
1236
1237template <class Impl>
1238void
1239FullO3CPU<Impl>::setMiscRegNoEffect(int misc_reg,
1240        const TheISA::MiscReg &val, unsigned tid)
1241{
1242    this->regFile.setMiscRegNoEffect(misc_reg, val, tid);
1243}
1244
1245template <class Impl>
1246void
1247FullO3CPU<Impl>::setMiscReg(int misc_reg,
1248        const TheISA::MiscReg &val, unsigned tid)
1249{
1250    this->regFile.setMiscReg(misc_reg, val, tid);
1251}
1252
1253template <class Impl>
1254uint64_t
1255FullO3CPU<Impl>::readIntReg(int reg_idx)
1256{
1257    return regFile.readIntReg(reg_idx);
1258}
1259
1260template <class Impl>
1261FloatReg
1262FullO3CPU<Impl>::readFloatReg(int reg_idx, int width)
1263{
1264    return regFile.readFloatReg(reg_idx, width);
1265}
1266
1267template <class Impl>
1268FloatReg
1269FullO3CPU<Impl>::readFloatReg(int reg_idx)
1270{
1271    return regFile.readFloatReg(reg_idx);
1272}
1273
1274template <class Impl>
1275FloatRegBits
1276FullO3CPU<Impl>::readFloatRegBits(int reg_idx, int width)
1277{
1278    return regFile.readFloatRegBits(reg_idx, width);
1279}
1280
1281template <class Impl>
1282FloatRegBits
1283FullO3CPU<Impl>::readFloatRegBits(int reg_idx)
1284{
1285    return regFile.readFloatRegBits(reg_idx);
1286}
1287
1288template <class Impl>
1289void
1290FullO3CPU<Impl>::setIntReg(int reg_idx, uint64_t val)
1291{
1292    regFile.setIntReg(reg_idx, val);
1293}
1294
1295template <class Impl>
1296void
1297FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val, int width)
1298{
1299    regFile.setFloatReg(reg_idx, val, width);
1300}
1301
1302template <class Impl>
1303void
1304FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val)
1305{
1306    regFile.setFloatReg(reg_idx, val);
1307}
1308
1309template <class Impl>
1310void
1311FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val, int width)
1312{
1313    regFile.setFloatRegBits(reg_idx, val, width);
1314}
1315
1316template <class Impl>
1317void
1318FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val)
1319{
1320    regFile.setFloatRegBits(reg_idx, val);
1321}
1322
1323template <class Impl>
1324uint64_t
1325FullO3CPU<Impl>::readArchIntReg(int reg_idx, unsigned tid)
1326{
1327    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1328
1329    return regFile.readIntReg(phys_reg);
1330}
1331
1332template <class Impl>
1333float
1334FullO3CPU<Impl>::readArchFloatRegSingle(int reg_idx, unsigned tid)
1335{
1336    int idx = reg_idx + TheISA::FP_Base_DepTag;
1337    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1338
1339    return regFile.readFloatReg(phys_reg);
1340}
1341
1342template <class Impl>
1343double
1344FullO3CPU<Impl>::readArchFloatRegDouble(int reg_idx, unsigned tid)
1345{
1346    int idx = reg_idx + TheISA::FP_Base_DepTag;
1347    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1348
1349    return regFile.readFloatReg(phys_reg, 64);
1350}
1351
1352template <class Impl>
1353uint64_t
1354FullO3CPU<Impl>::readArchFloatRegInt(int reg_idx, unsigned tid)
1355{
1356    int idx = reg_idx + TheISA::FP_Base_DepTag;
1357    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1358
1359    return regFile.readFloatRegBits(phys_reg);
1360}
1361
1362template <class Impl>
1363void
1364FullO3CPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, unsigned tid)
1365{
1366    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1367
1368    regFile.setIntReg(phys_reg, val);
1369}
1370
1371template <class Impl>
1372void
1373FullO3CPU<Impl>::setArchFloatRegSingle(int reg_idx, float val, unsigned tid)
1374{
1375    int idx = reg_idx + TheISA::FP_Base_DepTag;
1376    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1377
1378    regFile.setFloatReg(phys_reg, val);
1379}
1380
1381template <class Impl>
1382void
1383FullO3CPU<Impl>::setArchFloatRegDouble(int reg_idx, double val, unsigned tid)
1384{
1385    int idx = reg_idx + TheISA::FP_Base_DepTag;
1386    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1387
1388    regFile.setFloatReg(phys_reg, val, 64);
1389}
1390
1391template <class Impl>
1392void
1393FullO3CPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid)
1394{
1395    int idx = reg_idx + TheISA::FP_Base_DepTag;
1396    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1397
1398    regFile.setFloatRegBits(phys_reg, val);
1399}
1400
1401template <class Impl>
1402uint64_t
1403FullO3CPU<Impl>::readPC(unsigned tid)
1404{
1405    return commit.readPC(tid);
1406}
1407
1408template <class Impl>
1409void
1410FullO3CPU<Impl>::setPC(Addr new_PC,unsigned tid)
1411{
1412    commit.setPC(new_PC, tid);
1413}
1414
1415template <class Impl>
1416uint64_t
1417FullO3CPU<Impl>::readMicroPC(unsigned tid)
1418{
1419    return commit.readMicroPC(tid);
1420}
1421
1422template <class Impl>
1423void
1424FullO3CPU<Impl>::setMicroPC(Addr new_PC,unsigned tid)
1425{
1426    commit.setMicroPC(new_PC, tid);
1427}
1428
1429template <class Impl>
1430uint64_t
1431FullO3CPU<Impl>::readNextPC(unsigned tid)
1432{
1433    return commit.readNextPC(tid);
1434}
1435
1436template <class Impl>
1437void
1438FullO3CPU<Impl>::setNextPC(uint64_t val,unsigned tid)
1439{
1440    commit.setNextPC(val, tid);
1441}
1442
1443template <class Impl>
1444uint64_t
1445FullO3CPU<Impl>::readNextNPC(unsigned tid)
1446{
1447    return commit.readNextNPC(tid);
1448}
1449
1450template <class Impl>
1451void
1452FullO3CPU<Impl>::setNextNPC(uint64_t val,unsigned tid)
1453{
1454    commit.setNextNPC(val, tid);
1455}
1456
1457template <class Impl>
1458uint64_t
1459FullO3CPU<Impl>::readNextMicroPC(unsigned tid)
1460{
1461    return commit.readNextMicroPC(tid);
1462}
1463
1464template <class Impl>
1465void
1466FullO3CPU<Impl>::setNextMicroPC(Addr new_PC,unsigned tid)
1467{
1468    commit.setNextMicroPC(new_PC, tid);
1469}
1470
1471template <class Impl>
1472void
1473FullO3CPU<Impl>::squashFromTC(unsigned tid)
1474{
1475    this->thread[tid]->inSyscall = true;
1476    this->commit.generateTCEvent(tid);
1477}
1478
1479template <class Impl>
1480typename FullO3CPU<Impl>::ListIt
1481FullO3CPU<Impl>::addInst(DynInstPtr &inst)
1482{
1483    instList.push_back(inst);
1484
1485    return --(instList.end());
1486}
1487
1488template <class Impl>
1489void
1490FullO3CPU<Impl>::instDone(unsigned tid)
1491{
1492    // Keep an instruction count.
1493    thread[tid]->numInst++;
1494    thread[tid]->numInsts++;
1495    committedInsts[tid]++;
1496    totalCommittedInsts++;
1497
1498    // Check for instruction-count-based events.
1499    comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1500}
1501
1502template <class Impl>
1503void
1504FullO3CPU<Impl>::addToRemoveList(DynInstPtr &inst)
1505{
1506    removeInstsThisCycle = true;
1507
1508    removeList.push(inst->getInstListIt());
1509}
1510
1511template <class Impl>
1512void
1513FullO3CPU<Impl>::removeFrontInst(DynInstPtr &inst)
1514{
1515    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %#x "
1516            "[sn:%lli]\n",
1517            inst->threadNumber, inst->readPC(), inst->seqNum);
1518
1519    removeInstsThisCycle = true;
1520
1521    // Remove the front instruction.
1522    removeList.push(inst->getInstListIt());
1523}
1524
1525template <class Impl>
1526void
1527FullO3CPU<Impl>::removeInstsNotInROB(unsigned tid)
1528{
1529    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
1530            " list.\n", tid);
1531
1532    ListIt end_it;
1533
1534    bool rob_empty = false;
1535
1536    if (instList.empty()) {
1537        return;
1538    } else if (rob.isEmpty(/*tid*/)) {
1539        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
1540        end_it = instList.begin();
1541        rob_empty = true;
1542    } else {
1543        end_it = (rob.readTailInst(tid))->getInstListIt();
1544        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
1545    }
1546
1547    removeInstsThisCycle = true;
1548
1549    ListIt inst_it = instList.end();
1550
1551    inst_it--;
1552
1553    // Walk through the instruction list, removing any instructions
1554    // that were inserted after the given instruction iterator, end_it.
1555    while (inst_it != end_it) {
1556        assert(!instList.empty());
1557
1558        squashInstIt(inst_it, tid);
1559
1560        inst_it--;
1561    }
1562
1563    // If the ROB was empty, then we actually need to remove the first
1564    // instruction as well.
1565    if (rob_empty) {
1566        squashInstIt(inst_it, tid);
1567    }
1568}
1569
1570template <class Impl>
1571void
1572FullO3CPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num,
1573                                  unsigned tid)
1574{
1575    assert(!instList.empty());
1576
1577    removeInstsThisCycle = true;
1578
1579    ListIt inst_iter = instList.end();
1580
1581    inst_iter--;
1582
1583    DPRINTF(O3CPU, "Deleting instructions from instruction "
1584            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1585            tid, seq_num, (*inst_iter)->seqNum);
1586
1587    while ((*inst_iter)->seqNum > seq_num) {
1588
1589        bool break_loop = (inst_iter == instList.begin());
1590
1591        squashInstIt(inst_iter, tid);
1592
1593        inst_iter--;
1594
1595        if (break_loop)
1596            break;
1597    }
1598}
1599
1600template <class Impl>
1601inline void
1602FullO3CPU<Impl>::squashInstIt(const ListIt &instIt, const unsigned &tid)
1603{
1604    if ((*instIt)->threadNumber == tid) {
1605        DPRINTF(O3CPU, "Squashing instruction, "
1606                "[tid:%i] [sn:%lli] PC %#x\n",
1607                (*instIt)->threadNumber,
1608                (*instIt)->seqNum,
1609                (*instIt)->readPC());
1610
1611        // Mark it as squashed.
1612        (*instIt)->setSquashed();
1613
1614        // @todo: Formulate a consistent method for deleting
1615        // instructions from the instruction list
1616        // Remove the instruction from the list.
1617        removeList.push(instIt);
1618    }
1619}
1620
1621template <class Impl>
1622void
1623FullO3CPU<Impl>::cleanUpRemovedInsts()
1624{
1625    while (!removeList.empty()) {
1626        DPRINTF(O3CPU, "Removing instruction, "
1627                "[tid:%i] [sn:%lli] PC %#x\n",
1628                (*removeList.front())->threadNumber,
1629                (*removeList.front())->seqNum,
1630                (*removeList.front())->readPC());
1631
1632        instList.erase(removeList.front());
1633
1634        removeList.pop();
1635    }
1636
1637    removeInstsThisCycle = false;
1638}
1639/*
1640template <class Impl>
1641void
1642FullO3CPU<Impl>::removeAllInsts()
1643{
1644    instList.clear();
1645}
1646*/
1647template <class Impl>
1648void
1649FullO3CPU<Impl>::dumpInsts()
1650{
1651    int num = 0;
1652
1653    ListIt inst_list_it = instList.begin();
1654
1655    cprintf("Dumping Instruction List\n");
1656
1657    while (inst_list_it != instList.end()) {
1658        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1659                "Squashed:%i\n\n",
1660                num, (*inst_list_it)->readPC(), (*inst_list_it)->threadNumber,
1661                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1662                (*inst_list_it)->isSquashed());
1663        inst_list_it++;
1664        ++num;
1665    }
1666}
1667/*
1668template <class Impl>
1669void
1670FullO3CPU<Impl>::wakeDependents(DynInstPtr &inst)
1671{
1672    iew.wakeDependents(inst);
1673}
1674*/
1675template <class Impl>
1676void
1677FullO3CPU<Impl>::wakeCPU()
1678{
1679    if (activityRec.active() || tickEvent.scheduled()) {
1680        DPRINTF(Activity, "CPU already running.\n");
1681        return;
1682    }
1683
1684    DPRINTF(Activity, "Waking up CPU\n");
1685
1686    idleCycles += tickToCycles((curTick - 1) - lastRunningCycle);
1687    numCycles += tickToCycles((curTick - 1) - lastRunningCycle);
1688
1689    schedule(tickEvent, nextCycle());
1690}
1691
1692template <class Impl>
1693int
1694FullO3CPU<Impl>::getFreeTid()
1695{
1696    for (int i=0; i < numThreads; i++) {
1697        if (!tids[i]) {
1698            tids[i] = true;
1699            return i;
1700        }
1701    }
1702
1703    return -1;
1704}
1705
1706template <class Impl>
1707void
1708FullO3CPU<Impl>::doContextSwitch()
1709{
1710    if (contextSwitch) {
1711
1712        //ADD CODE TO DEACTIVE THREAD HERE (???)
1713
1714        for (int tid=0; tid < cpuWaitList.size(); tid++) {
1715            activateWhenReady(tid);
1716        }
1717
1718        if (cpuWaitList.size() == 0)
1719            contextSwitch = true;
1720    }
1721}
1722
1723template <class Impl>
1724void
1725FullO3CPU<Impl>::updateThreadPriority()
1726{
1727    if (activeThreads.size() > 1)
1728    {
1729        //DEFAULT TO ROUND ROBIN SCHEME
1730        //e.g. Move highest priority to end of thread list
1731        std::list<unsigned>::iterator list_begin = activeThreads.begin();
1732        std::list<unsigned>::iterator list_end   = activeThreads.end();
1733
1734        unsigned high_thread = *list_begin;
1735
1736        activeThreads.erase(list_begin);
1737
1738        activeThreads.push_back(high_thread);
1739    }
1740}
1741
1742// Forward declaration of FullO3CPU.
1743template class FullO3CPU<O3CPUImpl>;
1744