cpu.cc revision 5363:c474cb7a2b9c
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    // Unbind Int Regs from Rename Map
677    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
678        PhysRegIndex phys_reg = renameMap[tid].lookup(ireg);
679
680        scoreboard.unsetReg(phys_reg);
681        freeList.addReg(phys_reg);
682    }
683
684    // Unbind Float Regs from Rename Map
685    for (int freg = TheISA::NumIntRegs; freg < TheISA::NumFloatRegs; freg++) {
686        PhysRegIndex phys_reg = renameMap[tid].lookup(freg);
687
688        scoreboard.unsetReg(phys_reg);
689        freeList.addReg(phys_reg);
690    }
691
692    // Squash Throughout Pipeline
693    InstSeqNum squash_seq_num = commit.rob->readHeadInst(tid)->seqNum;
694    fetch.squash(0, sizeof(TheISA::MachInst), 0, squash_seq_num, tid);
695    decode.squash(tid);
696    rename.squash(squash_seq_num, tid);
697    iew.squash(tid);
698    iew.ldstQueue.squash(squash_seq_num, tid);
699    commit.rob->squash(squash_seq_num, tid);
700
701
702    assert(iew.instQueue.getCount(tid) == 0);
703    assert(iew.ldstQueue.getCount(tid) == 0);
704
705    // Reset ROB/IQ/LSQ Entries
706
707    // Commented out for now.  This should be possible to do by
708    // telling all the pipeline stages to drain first, and then
709    // checking until the drain completes.  Once the pipeline is
710    // drained, call resetEntries(). - 10-09-06 ktlim
711/*
712    if (activeThreads.size() >= 1) {
713        commit.rob->resetEntries();
714        iew.resetEntries();
715    }
716*/
717}
718
719
720template <class Impl>
721void
722FullO3CPU<Impl>::activateWhenReady(int tid)
723{
724    DPRINTF(O3CPU,"[tid:%i]: Checking if resources are available for incoming"
725            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
726            tid);
727
728    bool ready = true;
729
730    if (freeList.numFreeIntRegs() >= TheISA::NumIntRegs) {
731        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
732                "Phys. Int. Regs.\n",
733                tid);
734        ready = false;
735    } else if (freeList.numFreeFloatRegs() >= TheISA::NumFloatRegs) {
736        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
737                "Phys. Float. Regs.\n",
738                tid);
739        ready = false;
740    } else if (commit.rob->numFreeEntries() >=
741               commit.rob->entryAmount(activeThreads.size() + 1)) {
742        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
743                "ROB entries.\n",
744                tid);
745        ready = false;
746    } else if (iew.instQueue.numFreeEntries() >=
747               iew.instQueue.entryAmount(activeThreads.size() + 1)) {
748        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
749                "IQ entries.\n",
750                tid);
751        ready = false;
752    } else if (iew.ldstQueue.numFreeEntries() >=
753               iew.ldstQueue.entryAmount(activeThreads.size() + 1)) {
754        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
755                "LSQ entries.\n",
756                tid);
757        ready = false;
758    }
759
760    if (ready) {
761        insertThread(tid);
762
763        contextSwitch = false;
764
765        cpuWaitList.remove(tid);
766    } else {
767        suspendContext(tid);
768
769        //blocks fetch
770        contextSwitch = true;
771
772        //@todo: dont always add to waitlist
773        //do waitlist
774        cpuWaitList.push_back(tid);
775    }
776}
777
778#if FULL_SYSTEM
779template <class Impl>
780void
781FullO3CPU<Impl>::updateMemPorts()
782{
783    // Update all ThreadContext's memory ports (Functional/Virtual
784    // Ports)
785    for (int i = 0; i < thread.size(); ++i)
786        thread[i]->connectMemPorts();
787}
788#endif
789
790template <class Impl>
791void
792FullO3CPU<Impl>::serialize(std::ostream &os)
793{
794    SimObject::State so_state = SimObject::getState();
795    SERIALIZE_ENUM(so_state);
796    BaseCPU::serialize(os);
797    nameOut(os, csprintf("%s.tickEvent", name()));
798    tickEvent.serialize(os);
799
800    // Use SimpleThread's ability to checkpoint to make it easier to
801    // write out the registers.  Also make this static so it doesn't
802    // get instantiated multiple times (causes a panic in statistics).
803    static SimpleThread temp;
804
805    for (int i = 0; i < thread.size(); i++) {
806        nameOut(os, csprintf("%s.xc.%i", name(), i));
807        temp.copyTC(thread[i]->getTC());
808        temp.serialize(os);
809    }
810}
811
812template <class Impl>
813void
814FullO3CPU<Impl>::unserialize(Checkpoint *cp, const std::string &section)
815{
816    SimObject::State so_state;
817    UNSERIALIZE_ENUM(so_state);
818    BaseCPU::unserialize(cp, section);
819    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));
820
821    // Use SimpleThread's ability to checkpoint to make it easier to
822    // read in the registers.  Also make this static so it doesn't
823    // get instantiated multiple times (causes a panic in statistics).
824    static SimpleThread temp;
825
826    for (int i = 0; i < thread.size(); i++) {
827        temp.copyTC(thread[i]->getTC());
828        temp.unserialize(cp, csprintf("%s.xc.%i", section, i));
829        thread[i]->getTC()->copyArchRegs(temp.getTC());
830    }
831}
832
833template <class Impl>
834unsigned int
835FullO3CPU<Impl>::drain(Event *drain_event)
836{
837    DPRINTF(O3CPU, "Switching out\n");
838
839    // If the CPU isn't doing anything, then return immediately.
840    if (_status == Idle || _status == SwitchedOut) {
841        return 0;
842    }
843
844    drainCount = 0;
845    fetch.drain();
846    decode.drain();
847    rename.drain();
848    iew.drain();
849    commit.drain();
850
851    // Wake the CPU and record activity so everything can drain out if
852    // the CPU was not able to immediately drain.
853    if (getState() != SimObject::Drained) {
854        // A bit of a hack...set the drainEvent after all the drain()
855        // calls have been made, that way if all of the stages drain
856        // immediately, the signalDrained() function knows not to call
857        // process on the drain event.
858        drainEvent = drain_event;
859
860        wakeCPU();
861        activityRec.activity();
862
863        return 1;
864    } else {
865        return 0;
866    }
867}
868
869template <class Impl>
870void
871FullO3CPU<Impl>::resume()
872{
873    fetch.resume();
874    decode.resume();
875    rename.resume();
876    iew.resume();
877    commit.resume();
878
879    changeState(SimObject::Running);
880
881    if (_status == SwitchedOut || _status == Idle)
882        return;
883
884#if FULL_SYSTEM
885    assert(system->getMemoryMode() == Enums::timing);
886#endif
887
888    if (!tickEvent.scheduled())
889        tickEvent.schedule(nextCycle());
890    _status = Running;
891}
892
893template <class Impl>
894void
895FullO3CPU<Impl>::signalDrained()
896{
897    if (++drainCount == NumStages) {
898        if (tickEvent.scheduled())
899            tickEvent.squash();
900
901        changeState(SimObject::Drained);
902
903        BaseCPU::switchOut();
904
905        if (drainEvent) {
906            drainEvent->process();
907            drainEvent = NULL;
908        }
909    }
910    assert(drainCount <= 5);
911}
912
913template <class Impl>
914void
915FullO3CPU<Impl>::switchOut()
916{
917    fetch.switchOut();
918    rename.switchOut();
919    iew.switchOut();
920    commit.switchOut();
921    instList.clear();
922    while (!removeList.empty()) {
923        removeList.pop();
924    }
925
926    _status = SwitchedOut;
927#if USE_CHECKER
928    if (checker)
929        checker->switchOut();
930#endif
931    if (tickEvent.scheduled())
932        tickEvent.squash();
933}
934
935template <class Impl>
936void
937FullO3CPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
938{
939    // Flush out any old data from the time buffers.
940    for (int i = 0; i < timeBuffer.getSize(); ++i) {
941        timeBuffer.advance();
942        fetchQueue.advance();
943        decodeQueue.advance();
944        renameQueue.advance();
945        iewQueue.advance();
946    }
947
948    activityRec.reset();
949
950    BaseCPU::takeOverFrom(oldCPU, fetch.getIcachePort(), iew.getDcachePort());
951
952    fetch.takeOverFrom();
953    decode.takeOverFrom();
954    rename.takeOverFrom();
955    iew.takeOverFrom();
956    commit.takeOverFrom();
957
958    assert(!tickEvent.scheduled());
959
960    // @todo: Figure out how to properly select the tid to put onto
961    // the active threads list.
962    int tid = 0;
963
964    std::list<unsigned>::iterator isActive =
965        std::find(activeThreads.begin(), activeThreads.end(), tid);
966
967    if (isActive == activeThreads.end()) {
968        //May Need to Re-code this if the delay variable is the delay
969        //needed for thread to activate
970        DPRINTF(O3CPU, "Adding Thread %i to active threads list\n",
971                tid);
972
973        activeThreads.push_back(tid);
974    }
975
976    // Set all statuses to active, schedule the CPU's tick event.
977    // @todo: Fix up statuses so this is handled properly
978    for (int i = 0; i < threadContexts.size(); ++i) {
979        ThreadContext *tc = threadContexts[i];
980        if (tc->status() == ThreadContext::Active && _status != Running) {
981            _status = Running;
982            tickEvent.schedule(nextCycle());
983        }
984    }
985    if (!tickEvent.scheduled())
986        tickEvent.schedule(nextCycle());
987}
988
989template <class Impl>
990uint64_t
991FullO3CPU<Impl>::readIntReg(int reg_idx)
992{
993    return regFile.readIntReg(reg_idx);
994}
995
996template <class Impl>
997FloatReg
998FullO3CPU<Impl>::readFloatReg(int reg_idx, int width)
999{
1000    return regFile.readFloatReg(reg_idx, width);
1001}
1002
1003template <class Impl>
1004FloatReg
1005FullO3CPU<Impl>::readFloatReg(int reg_idx)
1006{
1007    return regFile.readFloatReg(reg_idx);
1008}
1009
1010template <class Impl>
1011FloatRegBits
1012FullO3CPU<Impl>::readFloatRegBits(int reg_idx, int width)
1013{
1014    return regFile.readFloatRegBits(reg_idx, width);
1015}
1016
1017template <class Impl>
1018FloatRegBits
1019FullO3CPU<Impl>::readFloatRegBits(int reg_idx)
1020{
1021    return regFile.readFloatRegBits(reg_idx);
1022}
1023
1024template <class Impl>
1025void
1026FullO3CPU<Impl>::setIntReg(int reg_idx, uint64_t val)
1027{
1028    regFile.setIntReg(reg_idx, val);
1029}
1030
1031template <class Impl>
1032void
1033FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val, int width)
1034{
1035    regFile.setFloatReg(reg_idx, val, width);
1036}
1037
1038template <class Impl>
1039void
1040FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val)
1041{
1042    regFile.setFloatReg(reg_idx, val);
1043}
1044
1045template <class Impl>
1046void
1047FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val, int width)
1048{
1049    regFile.setFloatRegBits(reg_idx, val, width);
1050}
1051
1052template <class Impl>
1053void
1054FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val)
1055{
1056    regFile.setFloatRegBits(reg_idx, val);
1057}
1058
1059template <class Impl>
1060uint64_t
1061FullO3CPU<Impl>::readArchIntReg(int reg_idx, unsigned tid)
1062{
1063    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1064
1065    return regFile.readIntReg(phys_reg);
1066}
1067
1068template <class Impl>
1069float
1070FullO3CPU<Impl>::readArchFloatRegSingle(int reg_idx, unsigned tid)
1071{
1072    int idx = reg_idx + TheISA::FP_Base_DepTag;
1073    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1074
1075    return regFile.readFloatReg(phys_reg);
1076}
1077
1078template <class Impl>
1079double
1080FullO3CPU<Impl>::readArchFloatRegDouble(int reg_idx, unsigned tid)
1081{
1082    int idx = reg_idx + TheISA::FP_Base_DepTag;
1083    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1084
1085    return regFile.readFloatReg(phys_reg, 64);
1086}
1087
1088template <class Impl>
1089uint64_t
1090FullO3CPU<Impl>::readArchFloatRegInt(int reg_idx, unsigned tid)
1091{
1092    int idx = reg_idx + TheISA::FP_Base_DepTag;
1093    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1094
1095    return regFile.readFloatRegBits(phys_reg);
1096}
1097
1098template <class Impl>
1099void
1100FullO3CPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, unsigned tid)
1101{
1102    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1103
1104    regFile.setIntReg(phys_reg, val);
1105}
1106
1107template <class Impl>
1108void
1109FullO3CPU<Impl>::setArchFloatRegSingle(int reg_idx, float val, unsigned tid)
1110{
1111    int idx = reg_idx + TheISA::FP_Base_DepTag;
1112    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1113
1114    regFile.setFloatReg(phys_reg, val);
1115}
1116
1117template <class Impl>
1118void
1119FullO3CPU<Impl>::setArchFloatRegDouble(int reg_idx, double val, unsigned tid)
1120{
1121    int idx = reg_idx + TheISA::FP_Base_DepTag;
1122    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1123
1124    regFile.setFloatReg(phys_reg, val, 64);
1125}
1126
1127template <class Impl>
1128void
1129FullO3CPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid)
1130{
1131    int idx = reg_idx + TheISA::FP_Base_DepTag;
1132    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1133
1134    regFile.setFloatRegBits(phys_reg, val);
1135}
1136
1137template <class Impl>
1138uint64_t
1139FullO3CPU<Impl>::readPC(unsigned tid)
1140{
1141    return commit.readPC(tid);
1142}
1143
1144template <class Impl>
1145void
1146FullO3CPU<Impl>::setPC(Addr new_PC,unsigned tid)
1147{
1148    commit.setPC(new_PC, tid);
1149}
1150
1151template <class Impl>
1152uint64_t
1153FullO3CPU<Impl>::readMicroPC(unsigned tid)
1154{
1155    return commit.readMicroPC(tid);
1156}
1157
1158template <class Impl>
1159void
1160FullO3CPU<Impl>::setMicroPC(Addr new_PC,unsigned tid)
1161{
1162    commit.setMicroPC(new_PC, tid);
1163}
1164
1165template <class Impl>
1166uint64_t
1167FullO3CPU<Impl>::readNextPC(unsigned tid)
1168{
1169    return commit.readNextPC(tid);
1170}
1171
1172template <class Impl>
1173void
1174FullO3CPU<Impl>::setNextPC(uint64_t val,unsigned tid)
1175{
1176    commit.setNextPC(val, tid);
1177}
1178
1179template <class Impl>
1180uint64_t
1181FullO3CPU<Impl>::readNextNPC(unsigned tid)
1182{
1183    return commit.readNextNPC(tid);
1184}
1185
1186template <class Impl>
1187void
1188FullO3CPU<Impl>::setNextNPC(uint64_t val,unsigned tid)
1189{
1190    commit.setNextNPC(val, tid);
1191}
1192
1193template <class Impl>
1194uint64_t
1195FullO3CPU<Impl>::readNextMicroPC(unsigned tid)
1196{
1197    return commit.readNextMicroPC(tid);
1198}
1199
1200template <class Impl>
1201void
1202FullO3CPU<Impl>::setNextMicroPC(Addr new_PC,unsigned tid)
1203{
1204    commit.setNextMicroPC(new_PC, tid);
1205}
1206
1207template <class Impl>
1208typename FullO3CPU<Impl>::ListIt
1209FullO3CPU<Impl>::addInst(DynInstPtr &inst)
1210{
1211    instList.push_back(inst);
1212
1213    return --(instList.end());
1214}
1215
1216template <class Impl>
1217void
1218FullO3CPU<Impl>::instDone(unsigned tid)
1219{
1220    // Keep an instruction count.
1221    thread[tid]->numInst++;
1222    thread[tid]->numInsts++;
1223    committedInsts[tid]++;
1224    totalCommittedInsts++;
1225
1226    // Check for instruction-count-based events.
1227    comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1228}
1229
1230template <class Impl>
1231void
1232FullO3CPU<Impl>::addToRemoveList(DynInstPtr &inst)
1233{
1234    removeInstsThisCycle = true;
1235
1236    removeList.push(inst->getInstListIt());
1237}
1238
1239template <class Impl>
1240void
1241FullO3CPU<Impl>::removeFrontInst(DynInstPtr &inst)
1242{
1243    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %#x "
1244            "[sn:%lli]\n",
1245            inst->threadNumber, inst->readPC(), inst->seqNum);
1246
1247    removeInstsThisCycle = true;
1248
1249    // Remove the front instruction.
1250    removeList.push(inst->getInstListIt());
1251}
1252
1253template <class Impl>
1254void
1255FullO3CPU<Impl>::removeInstsNotInROB(unsigned tid)
1256{
1257    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
1258            " list.\n", tid);
1259
1260    ListIt end_it;
1261
1262    bool rob_empty = false;
1263
1264    if (instList.empty()) {
1265        return;
1266    } else if (rob.isEmpty(/*tid*/)) {
1267        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
1268        end_it = instList.begin();
1269        rob_empty = true;
1270    } else {
1271        end_it = (rob.readTailInst(tid))->getInstListIt();
1272        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
1273    }
1274
1275    removeInstsThisCycle = true;
1276
1277    ListIt inst_it = instList.end();
1278
1279    inst_it--;
1280
1281    // Walk through the instruction list, removing any instructions
1282    // that were inserted after the given instruction iterator, end_it.
1283    while (inst_it != end_it) {
1284        assert(!instList.empty());
1285
1286        squashInstIt(inst_it, tid);
1287
1288        inst_it--;
1289    }
1290
1291    // If the ROB was empty, then we actually need to remove the first
1292    // instruction as well.
1293    if (rob_empty) {
1294        squashInstIt(inst_it, tid);
1295    }
1296}
1297
1298template <class Impl>
1299void
1300FullO3CPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num,
1301                                  unsigned tid)
1302{
1303    assert(!instList.empty());
1304
1305    removeInstsThisCycle = true;
1306
1307    ListIt inst_iter = instList.end();
1308
1309    inst_iter--;
1310
1311    DPRINTF(O3CPU, "Deleting instructions from instruction "
1312            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1313            tid, seq_num, (*inst_iter)->seqNum);
1314
1315    while ((*inst_iter)->seqNum > seq_num) {
1316
1317        bool break_loop = (inst_iter == instList.begin());
1318
1319        squashInstIt(inst_iter, tid);
1320
1321        inst_iter--;
1322
1323        if (break_loop)
1324            break;
1325    }
1326}
1327
1328template <class Impl>
1329inline void
1330FullO3CPU<Impl>::squashInstIt(const ListIt &instIt, const unsigned &tid)
1331{
1332    if ((*instIt)->threadNumber == tid) {
1333        DPRINTF(O3CPU, "Squashing instruction, "
1334                "[tid:%i] [sn:%lli] PC %#x\n",
1335                (*instIt)->threadNumber,
1336                (*instIt)->seqNum,
1337                (*instIt)->readPC());
1338
1339        // Mark it as squashed.
1340        (*instIt)->setSquashed();
1341
1342        // @todo: Formulate a consistent method for deleting
1343        // instructions from the instruction list
1344        // Remove the instruction from the list.
1345        removeList.push(instIt);
1346    }
1347}
1348
1349template <class Impl>
1350void
1351FullO3CPU<Impl>::cleanUpRemovedInsts()
1352{
1353    while (!removeList.empty()) {
1354        DPRINTF(O3CPU, "Removing instruction, "
1355                "[tid:%i] [sn:%lli] PC %#x\n",
1356                (*removeList.front())->threadNumber,
1357                (*removeList.front())->seqNum,
1358                (*removeList.front())->readPC());
1359
1360        instList.erase(removeList.front());
1361
1362        removeList.pop();
1363    }
1364
1365    removeInstsThisCycle = false;
1366}
1367/*
1368template <class Impl>
1369void
1370FullO3CPU<Impl>::removeAllInsts()
1371{
1372    instList.clear();
1373}
1374*/
1375template <class Impl>
1376void
1377FullO3CPU<Impl>::dumpInsts()
1378{
1379    int num = 0;
1380
1381    ListIt inst_list_it = instList.begin();
1382
1383    cprintf("Dumping Instruction List\n");
1384
1385    while (inst_list_it != instList.end()) {
1386        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1387                "Squashed:%i\n\n",
1388                num, (*inst_list_it)->readPC(), (*inst_list_it)->threadNumber,
1389                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1390                (*inst_list_it)->isSquashed());
1391        inst_list_it++;
1392        ++num;
1393    }
1394}
1395/*
1396template <class Impl>
1397void
1398FullO3CPU<Impl>::wakeDependents(DynInstPtr &inst)
1399{
1400    iew.wakeDependents(inst);
1401}
1402*/
1403template <class Impl>
1404void
1405FullO3CPU<Impl>::wakeCPU()
1406{
1407    if (activityRec.active() || tickEvent.scheduled()) {
1408        DPRINTF(Activity, "CPU already running.\n");
1409        return;
1410    }
1411
1412    DPRINTF(Activity, "Waking up CPU\n");
1413
1414    idleCycles += tickToCycles((curTick - 1) - lastRunningCycle);
1415    numCycles += tickToCycles((curTick - 1) - lastRunningCycle);
1416
1417    tickEvent.schedule(nextCycle());
1418}
1419
1420template <class Impl>
1421int
1422FullO3CPU<Impl>::getFreeTid()
1423{
1424    for (int i=0; i < numThreads; i++) {
1425        if (!tids[i]) {
1426            tids[i] = true;
1427            return i;
1428        }
1429    }
1430
1431    return -1;
1432}
1433
1434template <class Impl>
1435void
1436FullO3CPU<Impl>::doContextSwitch()
1437{
1438    if (contextSwitch) {
1439
1440        //ADD CODE TO DEACTIVE THREAD HERE (???)
1441
1442        for (int tid=0; tid < cpuWaitList.size(); tid++) {
1443            activateWhenReady(tid);
1444        }
1445
1446        if (cpuWaitList.size() == 0)
1447            contextSwitch = true;
1448    }
1449}
1450
1451template <class Impl>
1452void
1453FullO3CPU<Impl>::updateThreadPriority()
1454{
1455    if (activeThreads.size() > 1)
1456    {
1457        //DEFAULT TO ROUND ROBIN SCHEME
1458        //e.g. Move highest priority to end of thread list
1459        std::list<unsigned>::iterator list_begin = activeThreads.begin();
1460        std::list<unsigned>::iterator list_end   = activeThreads.end();
1461
1462        unsigned high_thread = *list_begin;
1463
1464        activeThreads.erase(list_begin);
1465
1466        activeThreads.push_back(high_thread);
1467    }
1468}
1469
1470// Forward declaration of FullO3CPU.
1471template class FullO3CPU<O3CPUImpl>;
1472