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