cpu.cc revision 3229
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#if FULL_SYSTEM
36#include "cpu/quiesce_event.hh"
37#include "sim/system.hh"
38#else
39#include "sim/process.hh"
40#endif
41
42#include "cpu/activity.hh"
43#include "cpu/simple_thread.hh"
44#include "cpu/thread_context.hh"
45#include "cpu/o3/isa_specific.hh"
46#include "cpu/o3/cpu.hh"
47
48#include "sim/root.hh"
49#include "sim/stat_control.hh"
50
51#if USE_CHECKER
52#include "cpu/checker/cpu.hh"
53#endif
54
55using namespace std;
56using namespace TheISA;
57
58BaseO3CPU::BaseO3CPU(Params *params)
59    : BaseCPU(params), cpu_id(0)
60{
61}
62
63void
64BaseO3CPU::regStats()
65{
66    BaseCPU::regStats();
67}
68
69template <class Impl>
70FullO3CPU<Impl>::TickEvent::TickEvent(FullO3CPU<Impl> *c)
71    : Event(&mainEventQueue, CPU_Tick_Pri), cpu(c)
72{
73}
74
75template <class Impl>
76void
77FullO3CPU<Impl>::TickEvent::process()
78{
79    cpu->tick();
80}
81
82template <class Impl>
83const char *
84FullO3CPU<Impl>::TickEvent::description()
85{
86    return "FullO3CPU tick event";
87}
88
89template <class Impl>
90FullO3CPU<Impl>::ActivateThreadEvent::ActivateThreadEvent()
91    : Event(&mainEventQueue, CPU_Switch_Pri)
92{
93}
94
95template <class Impl>
96void
97FullO3CPU<Impl>::ActivateThreadEvent::init(int thread_num,
98                                           FullO3CPU<Impl> *thread_cpu)
99{
100    tid = thread_num;
101    cpu = thread_cpu;
102}
103
104template <class Impl>
105void
106FullO3CPU<Impl>::ActivateThreadEvent::process()
107{
108    cpu->activateThread(tid);
109}
110
111template <class Impl>
112const char *
113FullO3CPU<Impl>::ActivateThreadEvent::description()
114{
115    return "FullO3CPU \"Activate Thread\" event";
116}
117
118template <class Impl>
119FullO3CPU<Impl>::DeallocateContextEvent::DeallocateContextEvent()
120    : Event(&mainEventQueue, CPU_Tick_Pri)
121{
122}
123
124template <class Impl>
125void
126FullO3CPU<Impl>::DeallocateContextEvent::init(int thread_num,
127                                           FullO3CPU<Impl> *thread_cpu)
128{
129    tid = thread_num;
130    cpu = thread_cpu;
131}
132
133template <class Impl>
134void
135FullO3CPU<Impl>::DeallocateContextEvent::process()
136{
137    cpu->deactivateThread(tid);
138    if (remove)
139        cpu->removeThread(tid);
140}
141
142template <class Impl>
143const char *
144FullO3CPU<Impl>::DeallocateContextEvent::description()
145{
146    return "FullO3CPU \"Deallocate Context\" event";
147}
148
149template <class Impl>
150FullO3CPU<Impl>::FullO3CPU(Params *params)
151    : BaseO3CPU(params),
152      tickEvent(this),
153      removeInstsThisCycle(false),
154      fetch(params),
155      decode(params),
156      rename(params),
157      iew(params),
158      commit(params),
159
160      regFile(params->numPhysIntRegs, params->numPhysFloatRegs),
161
162      freeList(params->numberOfThreads,
163               TheISA::NumIntRegs, params->numPhysIntRegs,
164               TheISA::NumFloatRegs, params->numPhysFloatRegs),
165
166      rob(params->numROBEntries, params->squashWidth,
167          params->smtROBPolicy, params->smtROBThreshold,
168          params->numberOfThreads),
169
170      scoreboard(params->numberOfThreads,
171                 TheISA::NumIntRegs, params->numPhysIntRegs,
172                 TheISA::NumFloatRegs, params->numPhysFloatRegs,
173                 TheISA::NumMiscRegs * number_of_threads,
174                 TheISA::ZeroReg),
175
176      timeBuffer(params->backComSize, params->forwardComSize),
177      fetchQueue(params->backComSize, params->forwardComSize),
178      decodeQueue(params->backComSize, params->forwardComSize),
179      renameQueue(params->backComSize, params->forwardComSize),
180      iewQueue(params->backComSize, params->forwardComSize),
181      activityRec(NumStages,
182                  params->backComSize + params->forwardComSize,
183                  params->activity),
184
185      globalSeqNum(1),
186#if FULL_SYSTEM
187      system(params->system),
188      physmem(system->physmem),
189#endif // FULL_SYSTEM
190      mem(params->mem),
191      drainCount(0),
192      deferRegistration(params->deferRegistration),
193      numThreads(number_of_threads)
194{
195    if (!deferRegistration) {
196        _status = Running;
197    } else {
198        _status = Idle;
199    }
200
201    checker = NULL;
202
203    if (params->checker) {
204#if USE_CHECKER
205        BaseCPU *temp_checker = params->checker;
206        checker = dynamic_cast<Checker<DynInstPtr> *>(temp_checker);
207        checker->setMemory(mem);
208#if FULL_SYSTEM
209        checker->setSystem(params->system);
210#endif
211#else
212        panic("Checker enabled but not compiled in!");
213#endif // USE_CHECKER
214    }
215
216#if !FULL_SYSTEM
217    thread.resize(number_of_threads);
218    tids.resize(number_of_threads);
219#endif
220
221    // The stages also need their CPU pointer setup.  However this
222    // must be done at the upper level CPU because they have pointers
223    // to the upper level CPU, and not this FullO3CPU.
224
225    // Set up Pointers to the activeThreads list for each stage
226    fetch.setActiveThreads(&activeThreads);
227    decode.setActiveThreads(&activeThreads);
228    rename.setActiveThreads(&activeThreads);
229    iew.setActiveThreads(&activeThreads);
230    commit.setActiveThreads(&activeThreads);
231
232    // Give each of the stages the time buffer they will use.
233    fetch.setTimeBuffer(&timeBuffer);
234    decode.setTimeBuffer(&timeBuffer);
235    rename.setTimeBuffer(&timeBuffer);
236    iew.setTimeBuffer(&timeBuffer);
237    commit.setTimeBuffer(&timeBuffer);
238
239    // Also setup each of the stages' queues.
240    fetch.setFetchQueue(&fetchQueue);
241    decode.setFetchQueue(&fetchQueue);
242    commit.setFetchQueue(&fetchQueue);
243    decode.setDecodeQueue(&decodeQueue);
244    rename.setDecodeQueue(&decodeQueue);
245    rename.setRenameQueue(&renameQueue);
246    iew.setRenameQueue(&renameQueue);
247    iew.setIEWQueue(&iewQueue);
248    commit.setIEWQueue(&iewQueue);
249    commit.setRenameQueue(&renameQueue);
250
251    commit.setIEWStage(&iew);
252    rename.setIEWStage(&iew);
253    rename.setCommitStage(&commit);
254
255#if !FULL_SYSTEM
256    int active_threads = params->workload.size();
257
258    if (active_threads > Impl::MaxThreads) {
259        panic("Workload Size too large. Increase the 'MaxThreads'"
260              "constant in your O3CPU impl. file (e.g. o3/alpha/impl.hh) or "
261              "edit your workload size.");
262    }
263#else
264    int active_threads = 1;
265#endif
266
267    //Make Sure That this a Valid Architeture
268    assert(params->numPhysIntRegs   >= numThreads * TheISA::NumIntRegs);
269    assert(params->numPhysFloatRegs >= numThreads * TheISA::NumFloatRegs);
270
271    rename.setScoreboard(&scoreboard);
272    iew.setScoreboard(&scoreboard);
273
274    // Setup the rename map for whichever stages need it.
275    PhysRegIndex lreg_idx = 0;
276    PhysRegIndex freg_idx = params->numPhysIntRegs; //Index to 1 after int regs
277
278    for (int tid=0; tid < numThreads; tid++) {
279        bool bindRegs = (tid <= active_threads - 1);
280
281        commitRenameMap[tid].init(TheISA::NumIntRegs,
282                                  params->numPhysIntRegs,
283                                  lreg_idx,            //Index for Logical. Regs
284
285                                  TheISA::NumFloatRegs,
286                                  params->numPhysFloatRegs,
287                                  freg_idx,            //Index for Float Regs
288
289                                  TheISA::NumMiscRegs,
290
291                                  TheISA::ZeroReg,
292                                  TheISA::ZeroReg,
293
294                                  tid,
295                                  false);
296
297        renameMap[tid].init(TheISA::NumIntRegs,
298                            params->numPhysIntRegs,
299                            lreg_idx,                  //Index for Logical. Regs
300
301                            TheISA::NumFloatRegs,
302                            params->numPhysFloatRegs,
303                            freg_idx,                  //Index for Float Regs
304
305                            TheISA::NumMiscRegs,
306
307                            TheISA::ZeroReg,
308                            TheISA::ZeroReg,
309
310                            tid,
311                            bindRegs);
312
313        activateThreadEvent[tid].init(tid, this);
314        deallocateContextEvent[tid].init(tid, this);
315    }
316
317    rename.setRenameMap(renameMap);
318    commit.setRenameMap(commitRenameMap);
319
320    // Give renameMap & rename stage access to the freeList;
321    for (int i=0; i < numThreads; i++) {
322        renameMap[i].setFreeList(&freeList);
323    }
324    rename.setFreeList(&freeList);
325
326    // Setup the ROB for whichever stages need it.
327    commit.setROB(&rob);
328
329    lastRunningCycle = curTick;
330
331    lastActivatedCycle = -1;
332
333    // Give renameMap & rename stage access to the freeList;
334    //for (int i=0; i < numThreads; i++) {
335        //globalSeqNum[i] = 1;
336        //}
337
338    contextSwitch = false;
339}
340
341template <class Impl>
342FullO3CPU<Impl>::~FullO3CPU()
343{
344}
345
346template <class Impl>
347void
348FullO3CPU<Impl>::fullCPURegStats()
349{
350    BaseO3CPU::regStats();
351
352    // Register any of the O3CPU's stats here.
353    timesIdled
354        .name(name() + ".timesIdled")
355        .desc("Number of times that the entire CPU went into an idle state and"
356              " unscheduled itself")
357        .prereq(timesIdled);
358
359    idleCycles
360        .name(name() + ".idleCycles")
361        .desc("Total number of cycles that the CPU has spent unscheduled due "
362              "to idling")
363        .prereq(idleCycles);
364
365    // Number of Instructions simulated
366    // --------------------------------
367    // Should probably be in Base CPU but need templated
368    // MaxThreads so put in here instead
369    committedInsts
370        .init(numThreads)
371        .name(name() + ".committedInsts")
372        .desc("Number of Instructions Simulated");
373
374    totalCommittedInsts
375        .name(name() + ".committedInsts_total")
376        .desc("Number of Instructions Simulated");
377
378    cpi
379        .name(name() + ".cpi")
380        .desc("CPI: Cycles Per Instruction")
381        .precision(6);
382    cpi = simTicks / committedInsts;
383
384    totalCpi
385        .name(name() + ".cpi_total")
386        .desc("CPI: Total CPI of All Threads")
387        .precision(6);
388    totalCpi = simTicks / totalCommittedInsts;
389
390    ipc
391        .name(name() + ".ipc")
392        .desc("IPC: Instructions Per Cycle")
393        .precision(6);
394    ipc =  committedInsts / simTicks;
395
396    totalIpc
397        .name(name() + ".ipc_total")
398        .desc("IPC: Total IPC of All Threads")
399        .precision(6);
400    totalIpc =  totalCommittedInsts / simTicks;
401
402}
403
404template <class Impl>
405Port *
406FullO3CPU<Impl>::getPort(const std::string &if_name, int idx)
407{
408    if (if_name == "dcache_port")
409        return iew.getDcachePort();
410    else if (if_name == "icache_port")
411        return fetch.getIcachePort();
412    else
413        panic("No Such Port\n");
414}
415
416template <class Impl>
417void
418FullO3CPU<Impl>::tick()
419{
420    DPRINTF(O3CPU, "\n\nFullO3CPU: Ticking main, FullO3CPU.\n");
421
422    ++numCycles;
423
424//    activity = false;
425
426    //Tick each of the stages
427    fetch.tick();
428
429    decode.tick();
430
431    rename.tick();
432
433    iew.tick();
434
435    commit.tick();
436
437#if !FULL_SYSTEM
438    doContextSwitch();
439#endif
440
441    // Now advance the time buffers
442    timeBuffer.advance();
443
444    fetchQueue.advance();
445    decodeQueue.advance();
446    renameQueue.advance();
447    iewQueue.advance();
448
449    activityRec.advance();
450
451    if (removeInstsThisCycle) {
452        cleanUpRemovedInsts();
453    }
454
455    if (!tickEvent.scheduled()) {
456        if (_status == SwitchedOut ||
457            getState() == SimObject::Drained) {
458            DPRINTF(O3CPU, "Switched out!\n");
459            // increment stat
460            lastRunningCycle = curTick;
461        } else if (!activityRec.active() || _status == Idle) {
462            DPRINTF(O3CPU, "Idle!\n");
463            lastRunningCycle = curTick;
464            timesIdled++;
465        } else {
466            tickEvent.schedule(curTick + cycles(1));
467            DPRINTF(O3CPU, "Scheduling next tick!\n");
468        }
469    }
470
471#if !FULL_SYSTEM
472    updateThreadPriority();
473#endif
474
475}
476
477template <class Impl>
478void
479FullO3CPU<Impl>::init()
480{
481    if (!deferRegistration) {
482        registerThreadContexts();
483    }
484
485    // Set inSyscall so that the CPU doesn't squash when initially
486    // setting up registers.
487    for (int i = 0; i < number_of_threads; ++i)
488        thread[i]->inSyscall = true;
489
490    for (int tid=0; tid < number_of_threads; tid++) {
491#if FULL_SYSTEM
492        ThreadContext *src_tc = threadContexts[tid];
493#else
494        ThreadContext *src_tc = thread[tid]->getTC();
495#endif
496        // Threads start in the Suspended State
497        if (src_tc->status() != ThreadContext::Suspended) {
498            continue;
499        }
500
501#if FULL_SYSTEM
502        TheISA::initCPU(src_tc, src_tc->readCpuId());
503#endif
504    }
505
506    // Clear inSyscall.
507    for (int i = 0; i < number_of_threads; ++i)
508        thread[i]->inSyscall = false;
509
510    // Initialize stages.
511    fetch.initStage();
512    iew.initStage();
513    rename.initStage();
514    commit.initStage();
515
516    commit.setThreads(thread);
517}
518
519template <class Impl>
520void
521FullO3CPU<Impl>::activateThread(unsigned tid)
522{
523    list<unsigned>::iterator isActive = find(
524        activeThreads.begin(), activeThreads.end(), tid);
525
526    DPRINTF(O3CPU, "[tid:%i]: Calling activate thread.\n", tid);
527
528    if (isActive == activeThreads.end()) {
529        DPRINTF(O3CPU, "[tid:%i]: Adding to active threads list\n",
530                tid);
531
532        activeThreads.push_back(tid);
533    }
534}
535
536template <class Impl>
537void
538FullO3CPU<Impl>::deactivateThread(unsigned tid)
539{
540    //Remove From Active List, if Active
541    list<unsigned>::iterator thread_it =
542        find(activeThreads.begin(), activeThreads.end(), tid);
543
544    DPRINTF(O3CPU, "[tid:%i]: Calling deactivate thread.\n", tid);
545
546    if (thread_it != activeThreads.end()) {
547        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
548                tid);
549        activeThreads.erase(thread_it);
550    }
551}
552
553template <class Impl>
554void
555FullO3CPU<Impl>::activateContext(int tid, int delay)
556{
557    // Needs to set each stage to running as well.
558    if (delay){
559        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to activate "
560                "on cycle %d\n", tid, curTick + cycles(delay));
561        scheduleActivateThreadEvent(tid, delay);
562    } else {
563        activateThread(tid);
564    }
565
566    if (lastActivatedCycle < curTick) {
567        scheduleTickEvent(delay);
568
569        // Be sure to signal that there's some activity so the CPU doesn't
570        // deschedule itself.
571        activityRec.activity();
572        fetch.wakeFromQuiesce();
573
574        lastActivatedCycle = curTick;
575
576        _status = Running;
577    }
578}
579
580template <class Impl>
581bool
582FullO3CPU<Impl>::deallocateContext(int tid, bool remove, int delay)
583{
584    // Schedule removal of thread data from CPU
585    if (delay){
586        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to deallocate "
587                "on cycle %d\n", tid, curTick + cycles(delay));
588        scheduleDeallocateContextEvent(tid, remove, delay);
589        return false;
590    } else {
591        deactivateThread(tid);
592        if (remove)
593            removeThread(tid);
594        return true;
595    }
596}
597
598template <class Impl>
599void
600FullO3CPU<Impl>::suspendContext(int tid)
601{
602    DPRINTF(O3CPU,"[tid: %i]: Suspending Thread Context.\n", tid);
603    bool deallocated = deallocateContext(tid, false, 1);
604    // If this was the last thread then unschedule the tick event.
605    if ((activeThreads.size() == 1 && !deallocated) || activeThreads.size() == 0)
606        unscheduleTickEvent();
607    _status = Idle;
608}
609
610template <class Impl>
611void
612FullO3CPU<Impl>::haltContext(int tid)
613{
614    //For now, this is the same as deallocate
615    DPRINTF(O3CPU,"[tid:%i]: Halt Context called. Deallocating", tid);
616    deallocateContext(tid, true, 1);
617}
618
619template <class Impl>
620void
621FullO3CPU<Impl>::insertThread(unsigned tid)
622{
623    DPRINTF(O3CPU,"[tid:%i] Initializing thread into CPU");
624    // Will change now that the PC and thread state is internal to the CPU
625    // and not in the ThreadContext.
626#if FULL_SYSTEM
627    ThreadContext *src_tc = system->threadContexts[tid];
628#else
629    ThreadContext *src_tc = tcBase(tid);
630#endif
631
632    //Bind Int Regs to Rename Map
633    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
634        PhysRegIndex phys_reg = freeList.getIntReg();
635
636        renameMap[tid].setEntry(ireg,phys_reg);
637        scoreboard.setReg(phys_reg);
638    }
639
640    //Bind Float Regs to Rename Map
641    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
642        PhysRegIndex phys_reg = freeList.getFloatReg();
643
644        renameMap[tid].setEntry(freg,phys_reg);
645        scoreboard.setReg(phys_reg);
646    }
647
648    //Copy Thread Data Into RegFile
649    //this->copyFromTC(tid);
650
651    //Set PC/NPC/NNPC
652    setPC(src_tc->readPC(), tid);
653    setNextPC(src_tc->readNextPC(), tid);
654#if ISA_HAS_DELAY_SLOT
655    setNextNPC(src_tc->readNextNPC(), tid);
656#endif
657
658    src_tc->setStatus(ThreadContext::Active);
659
660    activateContext(tid,1);
661
662    //Reset ROB/IQ/LSQ Entries
663    commit.rob->resetEntries();
664    iew.resetEntries();
665}
666
667template <class Impl>
668void
669FullO3CPU<Impl>::removeThread(unsigned tid)
670{
671    DPRINTF(O3CPU,"[tid:%i] Removing thread context from CPU.\n", tid);
672
673    // Copy Thread Data From RegFile
674    // If thread is suspended, it might be re-allocated
675    //this->copyToTC(tid);
676
677    // Unbind Int Regs from Rename Map
678    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
679        PhysRegIndex phys_reg = renameMap[tid].lookup(ireg);
680
681        scoreboard.unsetReg(phys_reg);
682        freeList.addReg(phys_reg);
683    }
684
685    // Unbind Float Regs from Rename Map
686    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
687        PhysRegIndex phys_reg = renameMap[tid].lookup(freg);
688
689        scoreboard.unsetReg(phys_reg);
690        freeList.addReg(phys_reg);
691    }
692
693    // Squash Throughout Pipeline
694    InstSeqNum squash_seq_num = commit.rob->readHeadInst(tid)->seqNum;
695    fetch.squash(0, squash_seq_num, true, tid);
696    decode.squash(tid);
697    rename.squash(squash_seq_num, tid);
698    iew.squash(tid);
699    commit.rob->squash(squash_seq_num, tid);
700
701    assert(iew.ldstQueue.getCount(tid) == 0);
702
703    // Reset ROB/IQ/LSQ Entries
704
705    // Commented out for now.  This should be possible to do by
706    // telling all the pipeline stages to drain first, and then
707    // checking until the drain completes.  Once the pipeline is
708    // drained, call resetEntries(). - 10-09-06 ktlim
709/*
710    if (activeThreads.size() >= 1) {
711        commit.rob->resetEntries();
712        iew.resetEntries();
713    }
714*/
715}
716
717
718template <class Impl>
719void
720FullO3CPU<Impl>::activateWhenReady(int tid)
721{
722    DPRINTF(O3CPU,"[tid:%i]: Checking if resources are available for incoming"
723            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
724            tid);
725
726    bool ready = true;
727
728    if (freeList.numFreeIntRegs() >= TheISA::NumIntRegs) {
729        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
730                "Phys. Int. Regs.\n",
731                tid);
732        ready = false;
733    } else if (freeList.numFreeFloatRegs() >= TheISA::NumFloatRegs) {
734        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
735                "Phys. Float. Regs.\n",
736                tid);
737        ready = false;
738    } else if (commit.rob->numFreeEntries() >=
739               commit.rob->entryAmount(activeThreads.size() + 1)) {
740        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
741                "ROB entries.\n",
742                tid);
743        ready = false;
744    } else if (iew.instQueue.numFreeEntries() >=
745               iew.instQueue.entryAmount(activeThreads.size() + 1)) {
746        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
747                "IQ entries.\n",
748                tid);
749        ready = false;
750    } else if (iew.ldstQueue.numFreeEntries() >=
751               iew.ldstQueue.entryAmount(activeThreads.size() + 1)) {
752        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
753                "LSQ entries.\n",
754                tid);
755        ready = false;
756    }
757
758    if (ready) {
759        insertThread(tid);
760
761        contextSwitch = false;
762
763        cpuWaitList.remove(tid);
764    } else {
765        suspendContext(tid);
766
767        //blocks fetch
768        contextSwitch = true;
769
770        //@todo: dont always add to waitlist
771        //do waitlist
772        cpuWaitList.push_back(tid);
773    }
774}
775
776template <class Impl>
777void
778FullO3CPU<Impl>::serialize(std::ostream &os)
779{
780    SimObject::State so_state = SimObject::getState();
781    SERIALIZE_ENUM(so_state);
782    BaseCPU::serialize(os);
783    nameOut(os, csprintf("%s.tickEvent", name()));
784    tickEvent.serialize(os);
785
786    // Use SimpleThread's ability to checkpoint to make it easier to
787    // write out the registers.  Also make this static so it doesn't
788    // get instantiated multiple times (causes a panic in statistics).
789    static SimpleThread temp;
790
791    for (int i = 0; i < thread.size(); i++) {
792        nameOut(os, csprintf("%s.xc.%i", name(), i));
793        temp.copyTC(thread[i]->getTC());
794        temp.serialize(os);
795    }
796}
797
798template <class Impl>
799void
800FullO3CPU<Impl>::unserialize(Checkpoint *cp, const std::string &section)
801{
802    SimObject::State so_state;
803    UNSERIALIZE_ENUM(so_state);
804    BaseCPU::unserialize(cp, section);
805    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));
806
807    // Use SimpleThread's ability to checkpoint to make it easier to
808    // read in the registers.  Also make this static so it doesn't
809    // get instantiated multiple times (causes a panic in statistics).
810    static SimpleThread temp;
811
812    for (int i = 0; i < thread.size(); i++) {
813        temp.copyTC(thread[i]->getTC());
814        temp.unserialize(cp, csprintf("%s.xc.%i", section, i));
815        thread[i]->getTC()->copyArchRegs(temp.getTC());
816    }
817}
818
819template <class Impl>
820unsigned int
821FullO3CPU<Impl>::drain(Event *drain_event)
822{
823    DPRINTF(O3CPU, "Switching out\n");
824    drainCount = 0;
825    fetch.drain();
826    decode.drain();
827    rename.drain();
828    iew.drain();
829    commit.drain();
830
831    // Wake the CPU and record activity so everything can drain out if
832    // the CPU was not able to immediately drain.
833    if (getState() != SimObject::Drained) {
834        // A bit of a hack...set the drainEvent after all the drain()
835        // calls have been made, that way if all of the stages drain
836        // immediately, the signalDrained() function knows not to call
837        // process on the drain event.
838        drainEvent = drain_event;
839
840        wakeCPU();
841        activityRec.activity();
842
843        return 1;
844    } else {
845        return 0;
846    }
847}
848
849template <class Impl>
850void
851FullO3CPU<Impl>::resume()
852{
853#if FULL_SYSTEM
854    assert(system->getMemoryMode() == System::Timing);
855#endif
856    fetch.resume();
857    decode.resume();
858    rename.resume();
859    iew.resume();
860    commit.resume();
861
862    changeState(SimObject::Running);
863
864    if (_status == SwitchedOut || _status == Idle)
865        return;
866
867    if (!tickEvent.scheduled())
868        tickEvent.schedule(curTick);
869    _status = Running;
870}
871
872template <class Impl>
873void
874FullO3CPU<Impl>::signalDrained()
875{
876    if (++drainCount == NumStages) {
877        if (tickEvent.scheduled())
878            tickEvent.squash();
879
880        changeState(SimObject::Drained);
881
882        BaseCPU::switchOut();
883
884        if (drainEvent) {
885            drainEvent->process();
886            drainEvent = NULL;
887        }
888    }
889    assert(drainCount <= 5);
890}
891
892template <class Impl>
893void
894FullO3CPU<Impl>::switchOut()
895{
896    fetch.switchOut();
897    rename.switchOut();
898    iew.switchOut();
899    commit.switchOut();
900    instList.clear();
901    while (!removeList.empty()) {
902        removeList.pop();
903    }
904
905    _status = SwitchedOut;
906#if USE_CHECKER
907    if (checker)
908        checker->switchOut();
909#endif
910    if (tickEvent.scheduled())
911        tickEvent.squash();
912}
913
914template <class Impl>
915void
916FullO3CPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
917{
918    // Flush out any old data from the time buffers.
919    for (int i = 0; i < timeBuffer.getSize(); ++i) {
920        timeBuffer.advance();
921        fetchQueue.advance();
922        decodeQueue.advance();
923        renameQueue.advance();
924        iewQueue.advance();
925    }
926
927    activityRec.reset();
928
929    BaseCPU::takeOverFrom(oldCPU);
930
931    fetch.takeOverFrom();
932    decode.takeOverFrom();
933    rename.takeOverFrom();
934    iew.takeOverFrom();
935    commit.takeOverFrom();
936
937    assert(!tickEvent.scheduled());
938
939    // @todo: Figure out how to properly select the tid to put onto
940    // the active threads list.
941    int tid = 0;
942
943    list<unsigned>::iterator isActive = find(
944        activeThreads.begin(), activeThreads.end(), tid);
945
946    if (isActive == activeThreads.end()) {
947        //May Need to Re-code this if the delay variable is the delay
948        //needed for thread to activate
949        DPRINTF(O3CPU, "Adding Thread %i to active threads list\n",
950                tid);
951
952        activeThreads.push_back(tid);
953    }
954
955    // Set all statuses to active, schedule the CPU's tick event.
956    // @todo: Fix up statuses so this is handled properly
957    for (int i = 0; i < threadContexts.size(); ++i) {
958        ThreadContext *tc = threadContexts[i];
959        if (tc->status() == ThreadContext::Active && _status != Running) {
960            _status = Running;
961            tickEvent.schedule(curTick);
962        }
963    }
964    if (!tickEvent.scheduled())
965        tickEvent.schedule(curTick);
966
967    Port *peer;
968    Port *icachePort = fetch.getIcachePort();
969    if (icachePort->getPeer() == NULL) {
970        peer = oldCPU->getPort("icache_port")->getPeer();
971        icachePort->setPeer(peer);
972    } else {
973        peer = icachePort->getPeer();
974    }
975    peer->setPeer(icachePort);
976
977    Port *dcachePort = iew.getDcachePort();
978    if (dcachePort->getPeer() == NULL) {
979        peer = oldCPU->getPort("dcache_port")->getPeer();
980        dcachePort->setPeer(peer);
981    } else {
982        peer = dcachePort->getPeer();
983    }
984    peer->setPeer(dcachePort);
985}
986
987template <class Impl>
988uint64_t
989FullO3CPU<Impl>::readIntReg(int reg_idx)
990{
991    return regFile.readIntReg(reg_idx);
992}
993
994template <class Impl>
995FloatReg
996FullO3CPU<Impl>::readFloatReg(int reg_idx, int width)
997{
998    return regFile.readFloatReg(reg_idx, width);
999}
1000
1001template <class Impl>
1002FloatReg
1003FullO3CPU<Impl>::readFloatReg(int reg_idx)
1004{
1005    return regFile.readFloatReg(reg_idx);
1006}
1007
1008template <class Impl>
1009FloatRegBits
1010FullO3CPU<Impl>::readFloatRegBits(int reg_idx, int width)
1011{
1012    return regFile.readFloatRegBits(reg_idx, width);
1013}
1014
1015template <class Impl>
1016FloatRegBits
1017FullO3CPU<Impl>::readFloatRegBits(int reg_idx)
1018{
1019    return regFile.readFloatRegBits(reg_idx);
1020}
1021
1022template <class Impl>
1023void
1024FullO3CPU<Impl>::setIntReg(int reg_idx, uint64_t val)
1025{
1026    regFile.setIntReg(reg_idx, val);
1027}
1028
1029template <class Impl>
1030void
1031FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val, int width)
1032{
1033    regFile.setFloatReg(reg_idx, val, width);
1034}
1035
1036template <class Impl>
1037void
1038FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val)
1039{
1040    regFile.setFloatReg(reg_idx, val);
1041}
1042
1043template <class Impl>
1044void
1045FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val, int width)
1046{
1047    regFile.setFloatRegBits(reg_idx, val, width);
1048}
1049
1050template <class Impl>
1051void
1052FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val)
1053{
1054    regFile.setFloatRegBits(reg_idx, val);
1055}
1056
1057template <class Impl>
1058uint64_t
1059FullO3CPU<Impl>::readArchIntReg(int reg_idx, unsigned tid)
1060{
1061    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1062
1063    return regFile.readIntReg(phys_reg);
1064}
1065
1066template <class Impl>
1067float
1068FullO3CPU<Impl>::readArchFloatRegSingle(int reg_idx, unsigned tid)
1069{
1070    int idx = reg_idx + TheISA::FP_Base_DepTag;
1071    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1072
1073    return regFile.readFloatReg(phys_reg);
1074}
1075
1076template <class Impl>
1077double
1078FullO3CPU<Impl>::readArchFloatRegDouble(int reg_idx, unsigned tid)
1079{
1080    int idx = reg_idx + TheISA::FP_Base_DepTag;
1081    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1082
1083    return regFile.readFloatReg(phys_reg, 64);
1084}
1085
1086template <class Impl>
1087uint64_t
1088FullO3CPU<Impl>::readArchFloatRegInt(int reg_idx, unsigned tid)
1089{
1090    int idx = reg_idx + TheISA::FP_Base_DepTag;
1091    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1092
1093    return regFile.readFloatRegBits(phys_reg);
1094}
1095
1096template <class Impl>
1097void
1098FullO3CPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, unsigned tid)
1099{
1100    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1101
1102    regFile.setIntReg(phys_reg, val);
1103}
1104
1105template <class Impl>
1106void
1107FullO3CPU<Impl>::setArchFloatRegSingle(int reg_idx, float val, unsigned tid)
1108{
1109    int idx = reg_idx + TheISA::FP_Base_DepTag;
1110    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1111
1112    regFile.setFloatReg(phys_reg, val);
1113}
1114
1115template <class Impl>
1116void
1117FullO3CPU<Impl>::setArchFloatRegDouble(int reg_idx, double val, unsigned tid)
1118{
1119    int idx = reg_idx + TheISA::FP_Base_DepTag;
1120    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1121
1122    regFile.setFloatReg(phys_reg, val, 64);
1123}
1124
1125template <class Impl>
1126void
1127FullO3CPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid)
1128{
1129    int idx = reg_idx + TheISA::FP_Base_DepTag;
1130    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1131
1132    regFile.setFloatRegBits(phys_reg, val);
1133}
1134
1135template <class Impl>
1136uint64_t
1137FullO3CPU<Impl>::readPC(unsigned tid)
1138{
1139    return commit.readPC(tid);
1140}
1141
1142template <class Impl>
1143void
1144FullO3CPU<Impl>::setPC(Addr new_PC,unsigned tid)
1145{
1146    commit.setPC(new_PC, tid);
1147}
1148
1149template <class Impl>
1150uint64_t
1151FullO3CPU<Impl>::readNextPC(unsigned tid)
1152{
1153    return commit.readNextPC(tid);
1154}
1155
1156template <class Impl>
1157void
1158FullO3CPU<Impl>::setNextPC(uint64_t val,unsigned tid)
1159{
1160    commit.setNextPC(val, tid);
1161}
1162
1163template <class Impl>
1164uint64_t
1165FullO3CPU<Impl>::readNextNPC(unsigned tid)
1166{
1167    return commit.readNextNPC(tid);
1168}
1169
1170template <class Impl>
1171void
1172FullO3CPU<Impl>::setNextNPC(uint64_t val,unsigned tid)
1173{
1174    commit.setNextNPC(val, tid);
1175}
1176
1177template <class Impl>
1178typename FullO3CPU<Impl>::ListIt
1179FullO3CPU<Impl>::addInst(DynInstPtr &inst)
1180{
1181    instList.push_back(inst);
1182
1183    return --(instList.end());
1184}
1185
1186template <class Impl>
1187void
1188FullO3CPU<Impl>::instDone(unsigned tid)
1189{
1190    // Keep an instruction count.
1191    thread[tid]->numInst++;
1192    thread[tid]->numInsts++;
1193    committedInsts[tid]++;
1194    totalCommittedInsts++;
1195
1196    // Check for instruction-count-based events.
1197    comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1198}
1199
1200template <class Impl>
1201void
1202FullO3CPU<Impl>::addToRemoveList(DynInstPtr &inst)
1203{
1204    removeInstsThisCycle = true;
1205
1206    removeList.push(inst->getInstListIt());
1207}
1208
1209template <class Impl>
1210void
1211FullO3CPU<Impl>::removeFrontInst(DynInstPtr &inst)
1212{
1213    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %#x "
1214            "[sn:%lli]\n",
1215            inst->threadNumber, inst->readPC(), inst->seqNum);
1216
1217    removeInstsThisCycle = true;
1218
1219    // Remove the front instruction.
1220    removeList.push(inst->getInstListIt());
1221}
1222
1223template <class Impl>
1224void
1225FullO3CPU<Impl>::removeInstsNotInROB(unsigned tid,
1226                                     bool squash_delay_slot,
1227                                     const InstSeqNum &delay_slot_seq_num)
1228{
1229    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
1230            " list.\n", tid);
1231
1232    ListIt end_it;
1233
1234    bool rob_empty = false;
1235
1236    if (instList.empty()) {
1237        return;
1238    } else if (rob.isEmpty(/*tid*/)) {
1239        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
1240        end_it = instList.begin();
1241        rob_empty = true;
1242    } else {
1243        end_it = (rob.readTailInst(tid))->getInstListIt();
1244        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
1245    }
1246
1247    removeInstsThisCycle = true;
1248
1249    ListIt inst_it = instList.end();
1250
1251    inst_it--;
1252
1253    // Walk through the instruction list, removing any instructions
1254    // that were inserted after the given instruction iterator, end_it.
1255    while (inst_it != end_it) {
1256        assert(!instList.empty());
1257
1258#if ISA_HAS_DELAY_SLOT
1259        if(!squash_delay_slot &&
1260           delay_slot_seq_num >= (*inst_it)->seqNum) {
1261            break;
1262        }
1263#endif
1264        squashInstIt(inst_it, tid);
1265
1266        inst_it--;
1267    }
1268
1269    // If the ROB was empty, then we actually need to remove the first
1270    // instruction as well.
1271    if (rob_empty) {
1272        squashInstIt(inst_it, tid);
1273    }
1274}
1275
1276template <class Impl>
1277void
1278FullO3CPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num,
1279                                  unsigned tid)
1280{
1281    assert(!instList.empty());
1282
1283    removeInstsThisCycle = true;
1284
1285    ListIt inst_iter = instList.end();
1286
1287    inst_iter--;
1288
1289    DPRINTF(O3CPU, "Deleting instructions from instruction "
1290            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1291            tid, seq_num, (*inst_iter)->seqNum);
1292
1293    while ((*inst_iter)->seqNum > seq_num) {
1294
1295        bool break_loop = (inst_iter == instList.begin());
1296
1297        squashInstIt(inst_iter, tid);
1298
1299        inst_iter--;
1300
1301        if (break_loop)
1302            break;
1303    }
1304}
1305
1306template <class Impl>
1307inline void
1308FullO3CPU<Impl>::squashInstIt(const ListIt &instIt, const unsigned &tid)
1309{
1310    if ((*instIt)->threadNumber == tid) {
1311        DPRINTF(O3CPU, "Squashing instruction, "
1312                "[tid:%i] [sn:%lli] PC %#x\n",
1313                (*instIt)->threadNumber,
1314                (*instIt)->seqNum,
1315                (*instIt)->readPC());
1316
1317        // Mark it as squashed.
1318        (*instIt)->setSquashed();
1319
1320        // @todo: Formulate a consistent method for deleting
1321        // instructions from the instruction list
1322        // Remove the instruction from the list.
1323        removeList.push(instIt);
1324    }
1325}
1326
1327template <class Impl>
1328void
1329FullO3CPU<Impl>::cleanUpRemovedInsts()
1330{
1331    while (!removeList.empty()) {
1332        DPRINTF(O3CPU, "Removing instruction, "
1333                "[tid:%i] [sn:%lli] PC %#x\n",
1334                (*removeList.front())->threadNumber,
1335                (*removeList.front())->seqNum,
1336                (*removeList.front())->readPC());
1337
1338        instList.erase(removeList.front());
1339
1340        removeList.pop();
1341    }
1342
1343    removeInstsThisCycle = false;
1344}
1345/*
1346template <class Impl>
1347void
1348FullO3CPU<Impl>::removeAllInsts()
1349{
1350    instList.clear();
1351}
1352*/
1353template <class Impl>
1354void
1355FullO3CPU<Impl>::dumpInsts()
1356{
1357    int num = 0;
1358
1359    ListIt inst_list_it = instList.begin();
1360
1361    cprintf("Dumping Instruction List\n");
1362
1363    while (inst_list_it != instList.end()) {
1364        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1365                "Squashed:%i\n\n",
1366                num, (*inst_list_it)->readPC(), (*inst_list_it)->threadNumber,
1367                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1368                (*inst_list_it)->isSquashed());
1369        inst_list_it++;
1370        ++num;
1371    }
1372}
1373/*
1374template <class Impl>
1375void
1376FullO3CPU<Impl>::wakeDependents(DynInstPtr &inst)
1377{
1378    iew.wakeDependents(inst);
1379}
1380*/
1381template <class Impl>
1382void
1383FullO3CPU<Impl>::wakeCPU()
1384{
1385    if (activityRec.active() || tickEvent.scheduled()) {
1386        DPRINTF(Activity, "CPU already running.\n");
1387        return;
1388    }
1389
1390    DPRINTF(Activity, "Waking up CPU\n");
1391
1392    idleCycles += (curTick - 1) - lastRunningCycle;
1393
1394    tickEvent.schedule(curTick);
1395}
1396
1397template <class Impl>
1398int
1399FullO3CPU<Impl>::getFreeTid()
1400{
1401    for (int i=0; i < numThreads; i++) {
1402        if (!tids[i]) {
1403            tids[i] = true;
1404            return i;
1405        }
1406    }
1407
1408    return -1;
1409}
1410
1411template <class Impl>
1412void
1413FullO3CPU<Impl>::doContextSwitch()
1414{
1415    if (contextSwitch) {
1416
1417        //ADD CODE TO DEACTIVE THREAD HERE (???)
1418
1419        for (int tid=0; tid < cpuWaitList.size(); tid++) {
1420            activateWhenReady(tid);
1421        }
1422
1423        if (cpuWaitList.size() == 0)
1424            contextSwitch = true;
1425    }
1426}
1427
1428template <class Impl>
1429void
1430FullO3CPU<Impl>::updateThreadPriority()
1431{
1432    if (activeThreads.size() > 1)
1433    {
1434        //DEFAULT TO ROUND ROBIN SCHEME
1435        //e.g. Move highest priority to end of thread list
1436        list<unsigned>::iterator list_begin = activeThreads.begin();
1437        list<unsigned>::iterator list_end   = activeThreads.end();
1438
1439        unsigned high_thread = *list_begin;
1440
1441        activeThreads.erase(list_begin);
1442
1443        activeThreads.push_back(high_thread);
1444    }
1445}
1446
1447// Forward declaration of FullO3CPU.
1448template class FullO3CPU<O3CPUImpl>;
1449