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