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