cpu.cc revision 5364:66d1251b7ae6
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 "enums/MemoryMode.hh"
41#include "sim/core.hh"
42#include "sim/stat_control.hh"
43
44#if FULL_SYSTEM
45#include "cpu/quiesce_event.hh"
46#include "sim/system.hh"
47#else
48#include "sim/process.hh"
49#endif
50
51#if USE_CHECKER
52#include "cpu/checker/cpu.hh"
53#endif
54
55using namespace TheISA;
56
57BaseO3CPU::BaseO3CPU(Params *params)
58    : BaseCPU(params), cpu_id(0)
59{
60}
61
62void
63BaseO3CPU::regStats()
64{
65    BaseCPU::regStats();
66}
67
68template <class Impl>
69FullO3CPU<Impl>::TickEvent::TickEvent(FullO3CPU<Impl> *c)
70    : Event(&mainEventQueue, CPU_Tick_Pri), cpu(c)
71{
72}
73
74template <class Impl>
75void
76FullO3CPU<Impl>::TickEvent::process()
77{
78    cpu->tick();
79}
80
81template <class Impl>
82const char *
83FullO3CPU<Impl>::TickEvent::description() const
84{
85    return "FullO3CPU tick";
86}
87
88template <class Impl>
89FullO3CPU<Impl>::ActivateThreadEvent::ActivateThreadEvent()
90    : Event(&mainEventQueue, CPU_Switch_Pri)
91{
92}
93
94template <class Impl>
95void
96FullO3CPU<Impl>::ActivateThreadEvent::init(int thread_num,
97                                           FullO3CPU<Impl> *thread_cpu)
98{
99    tid = thread_num;
100    cpu = thread_cpu;
101}
102
103template <class Impl>
104void
105FullO3CPU<Impl>::ActivateThreadEvent::process()
106{
107    cpu->activateThread(tid);
108}
109
110template <class Impl>
111const char *
112FullO3CPU<Impl>::ActivateThreadEvent::description() const
113{
114    return "FullO3CPU \"Activate Thread\"";
115}
116
117template <class Impl>
118FullO3CPU<Impl>::DeallocateContextEvent::DeallocateContextEvent()
119    : Event(&mainEventQueue, CPU_Tick_Pri), tid(0), remove(false), cpu(NULL)
120{
121}
122
123template <class Impl>
124void
125FullO3CPU<Impl>::DeallocateContextEvent::init(int thread_num,
126                                              FullO3CPU<Impl> *thread_cpu)
127{
128    tid = thread_num;
129    cpu = thread_cpu;
130    remove = false;
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() const
145{
146    return "FullO3CPU \"Deallocate Context\"";
147}
148
149template <class Impl>
150FullO3CPU<Impl>::FullO3CPU(O3CPU *o3_cpu, Params *params)
151    : BaseO3CPU(params),
152      itb(params->itb),
153      dtb(params->dtb),
154      tickEvent(this),
155      removeInstsThisCycle(false),
156      fetch(o3_cpu, params),
157      decode(o3_cpu, params),
158      rename(o3_cpu, params),
159      iew(o3_cpu, params),
160      commit(o3_cpu, params),
161
162      regFile(o3_cpu, params->numPhysIntRegs,
163              params->numPhysFloatRegs),
164
165      freeList(params->numberOfThreads,
166               TheISA::NumIntRegs, params->numPhysIntRegs,
167               TheISA::NumFloatRegs, params->numPhysFloatRegs),
168
169      rob(o3_cpu,
170          params->numROBEntries, params->squashWidth,
171          params->smtROBPolicy, params->smtROBThreshold,
172          params->numberOfThreads),
173
174      scoreboard(params->numberOfThreads,
175                 TheISA::NumIntRegs, params->numPhysIntRegs,
176                 TheISA::NumFloatRegs, params->numPhysFloatRegs,
177                 TheISA::NumMiscRegs * number_of_threads,
178                 TheISA::ZeroReg),
179
180      timeBuffer(params->backComSize, params->forwardComSize),
181      fetchQueue(params->backComSize, params->forwardComSize),
182      decodeQueue(params->backComSize, params->forwardComSize),
183      renameQueue(params->backComSize, params->forwardComSize),
184      iewQueue(params->backComSize, params->forwardComSize),
185      activityRec(NumStages,
186                  params->backComSize + params->forwardComSize,
187                  params->activity),
188
189      globalSeqNum(1),
190#if FULL_SYSTEM
191      system(params->system),
192      physmem(system->physmem),
193#endif // FULL_SYSTEM
194      drainCount(0),
195      deferRegistration(params->deferRegistration),
196      numThreads(number_of_threads)
197{
198    if (!deferRegistration) {
199        _status = Running;
200    } else {
201        _status = Idle;
202    }
203
204#if USE_CHECKER
205    if (params->checker) {
206        BaseCPU *temp_checker = params->checker;
207        checker = dynamic_cast<Checker<DynInstPtr> *>(temp_checker);
208#if FULL_SYSTEM
209        checker->setSystem(params->system);
210#endif
211    } else {
212        checker = NULL;
213    }
214#endif // USE_CHECKER
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 = numCycles / committedInsts;
383
384    totalCpi
385        .name(name() + ".cpi_total")
386        .desc("CPI: Total CPI of All Threads")
387        .precision(6);
388    totalCpi = numCycles / totalCommittedInsts;
389
390    ipc
391        .name(name() + ".ipc")
392        .desc("IPC: Instructions Per Cycle")
393        .precision(6);
394    ipc =  committedInsts / numCycles;
395
396    totalIpc
397        .name(name() + ".ipc_total")
398        .desc("IPC: Total IPC of All Threads")
399        .precision(6);
400    totalIpc =  totalCommittedInsts / numCycles;
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(nextCycle(curTick + ticks(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    std::list<unsigned>::iterator isActive =
524        std::find(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    std::list<unsigned>::iterator thread_it =
542        std::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 + ticks(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 + ticks(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 ||
606        activeThreads.size() == 0)
607        unscheduleTickEvent();
608    _status = Idle;
609}
610
611template <class Impl>
612void
613FullO3CPU<Impl>::haltContext(int tid)
614{
615    //For now, this is the same as deallocate
616    DPRINTF(O3CPU,"[tid:%i]: Halt Context called. Deallocating", tid);
617    deallocateContext(tid, true, 1);
618}
619
620template <class Impl>
621void
622FullO3CPU<Impl>::insertThread(unsigned tid)
623{
624    DPRINTF(O3CPU,"[tid:%i] Initializing thread into CPU");
625    // Will change now that the PC and thread state is internal to the CPU
626    // and not in the ThreadContext.
627#if FULL_SYSTEM
628    ThreadContext *src_tc = system->threadContexts[tid];
629#else
630    ThreadContext *src_tc = tcBase(tid);
631#endif
632
633    //Bind Int Regs to Rename Map
634    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
635        PhysRegIndex phys_reg = freeList.getIntReg();
636
637        renameMap[tid].setEntry(ireg,phys_reg);
638        scoreboard.setReg(phys_reg);
639    }
640
641    //Bind Float Regs to Rename Map
642    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
643        PhysRegIndex phys_reg = freeList.getFloatReg();
644
645        renameMap[tid].setEntry(freg,phys_reg);
646        scoreboard.setReg(phys_reg);
647    }
648
649    //Copy Thread Data Into RegFile
650    //this->copyFromTC(tid);
651
652    //Set PC/NPC/NNPC
653    setPC(src_tc->readPC(), tid);
654    setNextPC(src_tc->readNextPC(), tid);
655    setNextNPC(src_tc->readNextNPC(), tid);
656
657    src_tc->setStatus(ThreadContext::Active);
658
659    activateContext(tid,1);
660
661    //Reset ROB/IQ/LSQ Entries
662    commit.rob->resetEntries();
663    iew.resetEntries();
664}
665
666template <class Impl>
667void
668FullO3CPU<Impl>::removeThread(unsigned tid)
669{
670    DPRINTF(O3CPU,"[tid:%i] Removing thread context from CPU.\n", tid);
671
672    // Copy Thread Data From RegFile
673    // If thread is suspended, it might be re-allocated
674    // this->copyToTC(tid);
675
676
677    // @todo: 2-27-2008: Fix how we free up rename mappings
678    // here to alleviate the case for double-freeing registers
679    // in SMT workloads.
680
681    // Unbind Int Regs from Rename Map
682    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
683        PhysRegIndex phys_reg = renameMap[tid].lookup(ireg);
684
685        scoreboard.unsetReg(phys_reg);
686        freeList.addReg(phys_reg);
687    }
688
689    // Unbind Float Regs from Rename Map
690    for (int freg = TheISA::NumIntRegs; freg < TheISA::NumFloatRegs; freg++) {
691        PhysRegIndex phys_reg = renameMap[tid].lookup(freg);
692
693        scoreboard.unsetReg(phys_reg);
694        freeList.addReg(phys_reg);
695    }
696
697    // Squash Throughout Pipeline
698    InstSeqNum squash_seq_num = commit.rob->readHeadInst(tid)->seqNum;
699    fetch.squash(0, sizeof(TheISA::MachInst), 0, squash_seq_num, tid);
700    decode.squash(tid);
701    rename.squash(squash_seq_num, tid);
702    iew.squash(tid);
703    iew.ldstQueue.squash(squash_seq_num, tid);
704    commit.rob->squash(squash_seq_num, tid);
705
706
707    assert(iew.instQueue.getCount(tid) == 0);
708    assert(iew.ldstQueue.getCount(tid) == 0);
709
710    // Reset ROB/IQ/LSQ Entries
711
712    // Commented out for now.  This should be possible to do by
713    // telling all the pipeline stages to drain first, and then
714    // checking until the drain completes.  Once the pipeline is
715    // drained, call resetEntries(). - 10-09-06 ktlim
716/*
717    if (activeThreads.size() >= 1) {
718        commit.rob->resetEntries();
719        iew.resetEntries();
720    }
721*/
722}
723
724
725template <class Impl>
726void
727FullO3CPU<Impl>::activateWhenReady(int tid)
728{
729    DPRINTF(O3CPU,"[tid:%i]: Checking if resources are available for incoming"
730            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
731            tid);
732
733    bool ready = true;
734
735    if (freeList.numFreeIntRegs() >= TheISA::NumIntRegs) {
736        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
737                "Phys. Int. Regs.\n",
738                tid);
739        ready = false;
740    } else if (freeList.numFreeFloatRegs() >= TheISA::NumFloatRegs) {
741        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
742                "Phys. Float. Regs.\n",
743                tid);
744        ready = false;
745    } else if (commit.rob->numFreeEntries() >=
746               commit.rob->entryAmount(activeThreads.size() + 1)) {
747        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
748                "ROB entries.\n",
749                tid);
750        ready = false;
751    } else if (iew.instQueue.numFreeEntries() >=
752               iew.instQueue.entryAmount(activeThreads.size() + 1)) {
753        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
754                "IQ entries.\n",
755                tid);
756        ready = false;
757    } else if (iew.ldstQueue.numFreeEntries() >=
758               iew.ldstQueue.entryAmount(activeThreads.size() + 1)) {
759        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
760                "LSQ entries.\n",
761                tid);
762        ready = false;
763    }
764
765    if (ready) {
766        insertThread(tid);
767
768        contextSwitch = false;
769
770        cpuWaitList.remove(tid);
771    } else {
772        suspendContext(tid);
773
774        //blocks fetch
775        contextSwitch = true;
776
777        //@todo: dont always add to waitlist
778        //do waitlist
779        cpuWaitList.push_back(tid);
780    }
781}
782
783#if FULL_SYSTEM
784template <class Impl>
785void
786FullO3CPU<Impl>::updateMemPorts()
787{
788    // Update all ThreadContext's memory ports (Functional/Virtual
789    // Ports)
790    for (int i = 0; i < thread.size(); ++i)
791        thread[i]->connectMemPorts();
792}
793#endif
794
795template <class Impl>
796void
797FullO3CPU<Impl>::serialize(std::ostream &os)
798{
799    SimObject::State so_state = SimObject::getState();
800    SERIALIZE_ENUM(so_state);
801    BaseCPU::serialize(os);
802    nameOut(os, csprintf("%s.tickEvent", name()));
803    tickEvent.serialize(os);
804
805    // Use SimpleThread's ability to checkpoint to make it easier to
806    // write out 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        nameOut(os, csprintf("%s.xc.%i", name(), i));
812        temp.copyTC(thread[i]->getTC());
813        temp.serialize(os);
814    }
815}
816
817template <class Impl>
818void
819FullO3CPU<Impl>::unserialize(Checkpoint *cp, const std::string &section)
820{
821    SimObject::State so_state;
822    UNSERIALIZE_ENUM(so_state);
823    BaseCPU::unserialize(cp, section);
824    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));
825
826    // Use SimpleThread's ability to checkpoint to make it easier to
827    // read in the registers.  Also make this static so it doesn't
828    // get instantiated multiple times (causes a panic in statistics).
829    static SimpleThread temp;
830
831    for (int i = 0; i < thread.size(); i++) {
832        temp.copyTC(thread[i]->getTC());
833        temp.unserialize(cp, csprintf("%s.xc.%i", section, i));
834        thread[i]->getTC()->copyArchRegs(temp.getTC());
835    }
836}
837
838template <class Impl>
839unsigned int
840FullO3CPU<Impl>::drain(Event *drain_event)
841{
842    DPRINTF(O3CPU, "Switching out\n");
843
844    // If the CPU isn't doing anything, then return immediately.
845    if (_status == Idle || _status == SwitchedOut) {
846        return 0;
847    }
848
849    drainCount = 0;
850    fetch.drain();
851    decode.drain();
852    rename.drain();
853    iew.drain();
854    commit.drain();
855
856    // Wake the CPU and record activity so everything can drain out if
857    // the CPU was not able to immediately drain.
858    if (getState() != SimObject::Drained) {
859        // A bit of a hack...set the drainEvent after all the drain()
860        // calls have been made, that way if all of the stages drain
861        // immediately, the signalDrained() function knows not to call
862        // process on the drain event.
863        drainEvent = drain_event;
864
865        wakeCPU();
866        activityRec.activity();
867
868        return 1;
869    } else {
870        return 0;
871    }
872}
873
874template <class Impl>
875void
876FullO3CPU<Impl>::resume()
877{
878    fetch.resume();
879    decode.resume();
880    rename.resume();
881    iew.resume();
882    commit.resume();
883
884    changeState(SimObject::Running);
885
886    if (_status == SwitchedOut || _status == Idle)
887        return;
888
889#if FULL_SYSTEM
890    assert(system->getMemoryMode() == Enums::timing);
891#endif
892
893    if (!tickEvent.scheduled())
894        tickEvent.schedule(nextCycle());
895    _status = Running;
896}
897
898template <class Impl>
899void
900FullO3CPU<Impl>::signalDrained()
901{
902    if (++drainCount == NumStages) {
903        if (tickEvent.scheduled())
904            tickEvent.squash();
905
906        changeState(SimObject::Drained);
907
908        BaseCPU::switchOut();
909
910        if (drainEvent) {
911            drainEvent->process();
912            drainEvent = NULL;
913        }
914    }
915    assert(drainCount <= 5);
916}
917
918template <class Impl>
919void
920FullO3CPU<Impl>::switchOut()
921{
922    fetch.switchOut();
923    rename.switchOut();
924    iew.switchOut();
925    commit.switchOut();
926    instList.clear();
927    while (!removeList.empty()) {
928        removeList.pop();
929    }
930
931    _status = SwitchedOut;
932#if USE_CHECKER
933    if (checker)
934        checker->switchOut();
935#endif
936    if (tickEvent.scheduled())
937        tickEvent.squash();
938}
939
940template <class Impl>
941void
942FullO3CPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
943{
944    // Flush out any old data from the time buffers.
945    for (int i = 0; i < timeBuffer.getSize(); ++i) {
946        timeBuffer.advance();
947        fetchQueue.advance();
948        decodeQueue.advance();
949        renameQueue.advance();
950        iewQueue.advance();
951    }
952
953    activityRec.reset();
954
955    BaseCPU::takeOverFrom(oldCPU, fetch.getIcachePort(), iew.getDcachePort());
956
957    fetch.takeOverFrom();
958    decode.takeOverFrom();
959    rename.takeOverFrom();
960    iew.takeOverFrom();
961    commit.takeOverFrom();
962
963    assert(!tickEvent.scheduled());
964
965    // @todo: Figure out how to properly select the tid to put onto
966    // the active threads list.
967    int tid = 0;
968
969    std::list<unsigned>::iterator isActive =
970        std::find(activeThreads.begin(), activeThreads.end(), tid);
971
972    if (isActive == activeThreads.end()) {
973        //May Need to Re-code this if the delay variable is the delay
974        //needed for thread to activate
975        DPRINTF(O3CPU, "Adding Thread %i to active threads list\n",
976                tid);
977
978        activeThreads.push_back(tid);
979    }
980
981    // Set all statuses to active, schedule the CPU's tick event.
982    // @todo: Fix up statuses so this is handled properly
983    for (int i = 0; i < threadContexts.size(); ++i) {
984        ThreadContext *tc = threadContexts[i];
985        if (tc->status() == ThreadContext::Active && _status != Running) {
986            _status = Running;
987            tickEvent.schedule(nextCycle());
988        }
989    }
990    if (!tickEvent.scheduled())
991        tickEvent.schedule(nextCycle());
992}
993
994template <class Impl>
995uint64_t
996FullO3CPU<Impl>::readIntReg(int reg_idx)
997{
998    return regFile.readIntReg(reg_idx);
999}
1000
1001template <class Impl>
1002FloatReg
1003FullO3CPU<Impl>::readFloatReg(int reg_idx, int width)
1004{
1005    return regFile.readFloatReg(reg_idx, width);
1006}
1007
1008template <class Impl>
1009FloatReg
1010FullO3CPU<Impl>::readFloatReg(int reg_idx)
1011{
1012    return regFile.readFloatReg(reg_idx);
1013}
1014
1015template <class Impl>
1016FloatRegBits
1017FullO3CPU<Impl>::readFloatRegBits(int reg_idx, int width)
1018{
1019    return regFile.readFloatRegBits(reg_idx, width);
1020}
1021
1022template <class Impl>
1023FloatRegBits
1024FullO3CPU<Impl>::readFloatRegBits(int reg_idx)
1025{
1026    return regFile.readFloatRegBits(reg_idx);
1027}
1028
1029template <class Impl>
1030void
1031FullO3CPU<Impl>::setIntReg(int reg_idx, uint64_t val)
1032{
1033    regFile.setIntReg(reg_idx, val);
1034}
1035
1036template <class Impl>
1037void
1038FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val, int width)
1039{
1040    regFile.setFloatReg(reg_idx, val, width);
1041}
1042
1043template <class Impl>
1044void
1045FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val)
1046{
1047    regFile.setFloatReg(reg_idx, val);
1048}
1049
1050template <class Impl>
1051void
1052FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val, int width)
1053{
1054    regFile.setFloatRegBits(reg_idx, val, width);
1055}
1056
1057template <class Impl>
1058void
1059FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val)
1060{
1061    regFile.setFloatRegBits(reg_idx, val);
1062}
1063
1064template <class Impl>
1065uint64_t
1066FullO3CPU<Impl>::readArchIntReg(int reg_idx, unsigned tid)
1067{
1068    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1069
1070    return regFile.readIntReg(phys_reg);
1071}
1072
1073template <class Impl>
1074float
1075FullO3CPU<Impl>::readArchFloatRegSingle(int reg_idx, unsigned tid)
1076{
1077    int idx = reg_idx + TheISA::FP_Base_DepTag;
1078    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1079
1080    return regFile.readFloatReg(phys_reg);
1081}
1082
1083template <class Impl>
1084double
1085FullO3CPU<Impl>::readArchFloatRegDouble(int reg_idx, unsigned tid)
1086{
1087    int idx = reg_idx + TheISA::FP_Base_DepTag;
1088    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1089
1090    return regFile.readFloatReg(phys_reg, 64);
1091}
1092
1093template <class Impl>
1094uint64_t
1095FullO3CPU<Impl>::readArchFloatRegInt(int reg_idx, unsigned tid)
1096{
1097    int idx = reg_idx + TheISA::FP_Base_DepTag;
1098    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1099
1100    return regFile.readFloatRegBits(phys_reg);
1101}
1102
1103template <class Impl>
1104void
1105FullO3CPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, unsigned tid)
1106{
1107    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1108
1109    regFile.setIntReg(phys_reg, val);
1110}
1111
1112template <class Impl>
1113void
1114FullO3CPU<Impl>::setArchFloatRegSingle(int reg_idx, float val, unsigned tid)
1115{
1116    int idx = reg_idx + TheISA::FP_Base_DepTag;
1117    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1118
1119    regFile.setFloatReg(phys_reg, val);
1120}
1121
1122template <class Impl>
1123void
1124FullO3CPU<Impl>::setArchFloatRegDouble(int reg_idx, double val, unsigned tid)
1125{
1126    int idx = reg_idx + TheISA::FP_Base_DepTag;
1127    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1128
1129    regFile.setFloatReg(phys_reg, val, 64);
1130}
1131
1132template <class Impl>
1133void
1134FullO3CPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid)
1135{
1136    int idx = reg_idx + TheISA::FP_Base_DepTag;
1137    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1138
1139    regFile.setFloatRegBits(phys_reg, val);
1140}
1141
1142template <class Impl>
1143uint64_t
1144FullO3CPU<Impl>::readPC(unsigned tid)
1145{
1146    return commit.readPC(tid);
1147}
1148
1149template <class Impl>
1150void
1151FullO3CPU<Impl>::setPC(Addr new_PC,unsigned tid)
1152{
1153    commit.setPC(new_PC, tid);
1154}
1155
1156template <class Impl>
1157uint64_t
1158FullO3CPU<Impl>::readMicroPC(unsigned tid)
1159{
1160    return commit.readMicroPC(tid);
1161}
1162
1163template <class Impl>
1164void
1165FullO3CPU<Impl>::setMicroPC(Addr new_PC,unsigned tid)
1166{
1167    commit.setMicroPC(new_PC, tid);
1168}
1169
1170template <class Impl>
1171uint64_t
1172FullO3CPU<Impl>::readNextPC(unsigned tid)
1173{
1174    return commit.readNextPC(tid);
1175}
1176
1177template <class Impl>
1178void
1179FullO3CPU<Impl>::setNextPC(uint64_t val,unsigned tid)
1180{
1181    commit.setNextPC(val, tid);
1182}
1183
1184template <class Impl>
1185uint64_t
1186FullO3CPU<Impl>::readNextNPC(unsigned tid)
1187{
1188    return commit.readNextNPC(tid);
1189}
1190
1191template <class Impl>
1192void
1193FullO3CPU<Impl>::setNextNPC(uint64_t val,unsigned tid)
1194{
1195    commit.setNextNPC(val, tid);
1196}
1197
1198template <class Impl>
1199uint64_t
1200FullO3CPU<Impl>::readNextMicroPC(unsigned tid)
1201{
1202    return commit.readNextMicroPC(tid);
1203}
1204
1205template <class Impl>
1206void
1207FullO3CPU<Impl>::setNextMicroPC(Addr new_PC,unsigned tid)
1208{
1209    commit.setNextMicroPC(new_PC, tid);
1210}
1211
1212template <class Impl>
1213typename FullO3CPU<Impl>::ListIt
1214FullO3CPU<Impl>::addInst(DynInstPtr &inst)
1215{
1216    instList.push_back(inst);
1217
1218    return --(instList.end());
1219}
1220
1221template <class Impl>
1222void
1223FullO3CPU<Impl>::instDone(unsigned tid)
1224{
1225    // Keep an instruction count.
1226    thread[tid]->numInst++;
1227    thread[tid]->numInsts++;
1228    committedInsts[tid]++;
1229    totalCommittedInsts++;
1230
1231    // Check for instruction-count-based events.
1232    comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1233}
1234
1235template <class Impl>
1236void
1237FullO3CPU<Impl>::addToRemoveList(DynInstPtr &inst)
1238{
1239    removeInstsThisCycle = true;
1240
1241    removeList.push(inst->getInstListIt());
1242}
1243
1244template <class Impl>
1245void
1246FullO3CPU<Impl>::removeFrontInst(DynInstPtr &inst)
1247{
1248    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %#x "
1249            "[sn:%lli]\n",
1250            inst->threadNumber, inst->readPC(), inst->seqNum);
1251
1252    removeInstsThisCycle = true;
1253
1254    // Remove the front instruction.
1255    removeList.push(inst->getInstListIt());
1256}
1257
1258template <class Impl>
1259void
1260FullO3CPU<Impl>::removeInstsNotInROB(unsigned tid)
1261{
1262    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
1263            " list.\n", tid);
1264
1265    ListIt end_it;
1266
1267    bool rob_empty = false;
1268
1269    if (instList.empty()) {
1270        return;
1271    } else if (rob.isEmpty(/*tid*/)) {
1272        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
1273        end_it = instList.begin();
1274        rob_empty = true;
1275    } else {
1276        end_it = (rob.readTailInst(tid))->getInstListIt();
1277        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
1278    }
1279
1280    removeInstsThisCycle = true;
1281
1282    ListIt inst_it = instList.end();
1283
1284    inst_it--;
1285
1286    // Walk through the instruction list, removing any instructions
1287    // that were inserted after the given instruction iterator, end_it.
1288    while (inst_it != end_it) {
1289        assert(!instList.empty());
1290
1291        squashInstIt(inst_it, tid);
1292
1293        inst_it--;
1294    }
1295
1296    // If the ROB was empty, then we actually need to remove the first
1297    // instruction as well.
1298    if (rob_empty) {
1299        squashInstIt(inst_it, tid);
1300    }
1301}
1302
1303template <class Impl>
1304void
1305FullO3CPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num,
1306                                  unsigned tid)
1307{
1308    assert(!instList.empty());
1309
1310    removeInstsThisCycle = true;
1311
1312    ListIt inst_iter = instList.end();
1313
1314    inst_iter--;
1315
1316    DPRINTF(O3CPU, "Deleting instructions from instruction "
1317            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1318            tid, seq_num, (*inst_iter)->seqNum);
1319
1320    while ((*inst_iter)->seqNum > seq_num) {
1321
1322        bool break_loop = (inst_iter == instList.begin());
1323
1324        squashInstIt(inst_iter, tid);
1325
1326        inst_iter--;
1327
1328        if (break_loop)
1329            break;
1330    }
1331}
1332
1333template <class Impl>
1334inline void
1335FullO3CPU<Impl>::squashInstIt(const ListIt &instIt, const unsigned &tid)
1336{
1337    if ((*instIt)->threadNumber == tid) {
1338        DPRINTF(O3CPU, "Squashing instruction, "
1339                "[tid:%i] [sn:%lli] PC %#x\n",
1340                (*instIt)->threadNumber,
1341                (*instIt)->seqNum,
1342                (*instIt)->readPC());
1343
1344        // Mark it as squashed.
1345        (*instIt)->setSquashed();
1346
1347        // @todo: Formulate a consistent method for deleting
1348        // instructions from the instruction list
1349        // Remove the instruction from the list.
1350        removeList.push(instIt);
1351    }
1352}
1353
1354template <class Impl>
1355void
1356FullO3CPU<Impl>::cleanUpRemovedInsts()
1357{
1358    while (!removeList.empty()) {
1359        DPRINTF(O3CPU, "Removing instruction, "
1360                "[tid:%i] [sn:%lli] PC %#x\n",
1361                (*removeList.front())->threadNumber,
1362                (*removeList.front())->seqNum,
1363                (*removeList.front())->readPC());
1364
1365        instList.erase(removeList.front());
1366
1367        removeList.pop();
1368    }
1369
1370    removeInstsThisCycle = false;
1371}
1372/*
1373template <class Impl>
1374void
1375FullO3CPU<Impl>::removeAllInsts()
1376{
1377    instList.clear();
1378}
1379*/
1380template <class Impl>
1381void
1382FullO3CPU<Impl>::dumpInsts()
1383{
1384    int num = 0;
1385
1386    ListIt inst_list_it = instList.begin();
1387
1388    cprintf("Dumping Instruction List\n");
1389
1390    while (inst_list_it != instList.end()) {
1391        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1392                "Squashed:%i\n\n",
1393                num, (*inst_list_it)->readPC(), (*inst_list_it)->threadNumber,
1394                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1395                (*inst_list_it)->isSquashed());
1396        inst_list_it++;
1397        ++num;
1398    }
1399}
1400/*
1401template <class Impl>
1402void
1403FullO3CPU<Impl>::wakeDependents(DynInstPtr &inst)
1404{
1405    iew.wakeDependents(inst);
1406}
1407*/
1408template <class Impl>
1409void
1410FullO3CPU<Impl>::wakeCPU()
1411{
1412    if (activityRec.active() || tickEvent.scheduled()) {
1413        DPRINTF(Activity, "CPU already running.\n");
1414        return;
1415    }
1416
1417    DPRINTF(Activity, "Waking up CPU\n");
1418
1419    idleCycles += tickToCycles((curTick - 1) - lastRunningCycle);
1420    numCycles += tickToCycles((curTick - 1) - lastRunningCycle);
1421
1422    tickEvent.schedule(nextCycle());
1423}
1424
1425template <class Impl>
1426int
1427FullO3CPU<Impl>::getFreeTid()
1428{
1429    for (int i=0; i < numThreads; i++) {
1430        if (!tids[i]) {
1431            tids[i] = true;
1432            return i;
1433        }
1434    }
1435
1436    return -1;
1437}
1438
1439template <class Impl>
1440void
1441FullO3CPU<Impl>::doContextSwitch()
1442{
1443    if (contextSwitch) {
1444
1445        //ADD CODE TO DEACTIVE THREAD HERE (???)
1446
1447        for (int tid=0; tid < cpuWaitList.size(); tid++) {
1448            activateWhenReady(tid);
1449        }
1450
1451        if (cpuWaitList.size() == 0)
1452            contextSwitch = true;
1453    }
1454}
1455
1456template <class Impl>
1457void
1458FullO3CPU<Impl>::updateThreadPriority()
1459{
1460    if (activeThreads.size() > 1)
1461    {
1462        //DEFAULT TO ROUND ROBIN SCHEME
1463        //e.g. Move highest priority to end of thread list
1464        std::list<unsigned>::iterator list_begin = activeThreads.begin();
1465        std::list<unsigned>::iterator list_end   = activeThreads.end();
1466
1467        unsigned high_thread = *list_begin;
1468
1469        activeThreads.erase(list_begin);
1470
1471        activeThreads.push_back(high_thread);
1472    }
1473}
1474
1475// Forward declaration of FullO3CPU.
1476template class FullO3CPU<O3CPUImpl>;
1477