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