cpu.cc revision 9152:86c0e6ca5e7c
1/*
2 * Copyright (c) 2011-2012 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder.  You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Copyright (c) 2004-2006 The Regents of The University of Michigan
15 * Copyright (c) 2011 Regents of the University of California
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Kevin Lim
42 *          Korey Sewell
43 *          Rick Strong
44 */
45
46#include "arch/kernel_stats.hh"
47#include "config/the_isa.hh"
48#include "cpu/checker/cpu.hh"
49#include "cpu/checker/thread_context.hh"
50#include "cpu/o3/cpu.hh"
51#include "cpu/o3/isa_specific.hh"
52#include "cpu/o3/thread_context.hh"
53#include "cpu/activity.hh"
54#include "cpu/quiesce_event.hh"
55#include "cpu/simple_thread.hh"
56#include "cpu/thread_context.hh"
57#include "debug/Activity.hh"
58#include "debug/Drain.hh"
59#include "debug/O3CPU.hh"
60#include "debug/Quiesce.hh"
61#include "enums/MemoryMode.hh"
62#include "sim/core.hh"
63#include "sim/full_system.hh"
64#include "sim/process.hh"
65#include "sim/stat_control.hh"
66#include "sim/system.hh"
67
68#if THE_ISA == ALPHA_ISA
69#include "arch/alpha/osfpal.hh"
70#include "debug/Activity.hh"
71#endif
72
73struct BaseCPUParams;
74
75using namespace TheISA;
76using namespace std;
77
78BaseO3CPU::BaseO3CPU(BaseCPUParams *params)
79    : BaseCPU(params)
80{
81}
82
83void
84BaseO3CPU::regStats()
85{
86    BaseCPU::regStats();
87}
88
89template<class Impl>
90bool
91FullO3CPU<Impl>::IcachePort::recvTimingResp(PacketPtr pkt)
92{
93    DPRINTF(O3CPU, "Fetch unit received timing\n");
94    // We shouldn't ever get a block in ownership state
95    assert(!(pkt->memInhibitAsserted() && !pkt->sharedAsserted()));
96    fetch->processCacheCompletion(pkt);
97
98    return true;
99}
100
101template<class Impl>
102void
103FullO3CPU<Impl>::IcachePort::recvRetry()
104{
105    fetch->recvRetry();
106}
107
108template <class Impl>
109bool
110FullO3CPU<Impl>::DcachePort::recvTimingResp(PacketPtr pkt)
111{
112    return lsq->recvTimingResp(pkt);
113}
114
115template <class Impl>
116void
117FullO3CPU<Impl>::DcachePort::recvTimingSnoopReq(PacketPtr pkt)
118{
119    lsq->recvTimingSnoopReq(pkt);
120}
121
122template <class Impl>
123void
124FullO3CPU<Impl>::DcachePort::recvRetry()
125{
126    lsq->recvRetry();
127}
128
129template <class Impl>
130FullO3CPU<Impl>::TickEvent::TickEvent(FullO3CPU<Impl> *c)
131    : Event(CPU_Tick_Pri), cpu(c)
132{
133}
134
135template <class Impl>
136void
137FullO3CPU<Impl>::TickEvent::process()
138{
139    cpu->tick();
140}
141
142template <class Impl>
143const char *
144FullO3CPU<Impl>::TickEvent::description() const
145{
146    return "FullO3CPU tick";
147}
148
149template <class Impl>
150FullO3CPU<Impl>::ActivateThreadEvent::ActivateThreadEvent()
151    : Event(CPU_Switch_Pri)
152{
153}
154
155template <class Impl>
156void
157FullO3CPU<Impl>::ActivateThreadEvent::init(int thread_num,
158                                           FullO3CPU<Impl> *thread_cpu)
159{
160    tid = thread_num;
161    cpu = thread_cpu;
162}
163
164template <class Impl>
165void
166FullO3CPU<Impl>::ActivateThreadEvent::process()
167{
168    cpu->activateThread(tid);
169}
170
171template <class Impl>
172const char *
173FullO3CPU<Impl>::ActivateThreadEvent::description() const
174{
175    return "FullO3CPU \"Activate Thread\"";
176}
177
178template <class Impl>
179FullO3CPU<Impl>::DeallocateContextEvent::DeallocateContextEvent()
180    : Event(CPU_Tick_Pri), tid(0), remove(false), cpu(NULL)
181{
182}
183
184template <class Impl>
185void
186FullO3CPU<Impl>::DeallocateContextEvent::init(int thread_num,
187                                              FullO3CPU<Impl> *thread_cpu)
188{
189    tid = thread_num;
190    cpu = thread_cpu;
191    remove = false;
192}
193
194template <class Impl>
195void
196FullO3CPU<Impl>::DeallocateContextEvent::process()
197{
198    cpu->deactivateThread(tid);
199    if (remove)
200        cpu->removeThread(tid);
201}
202
203template <class Impl>
204const char *
205FullO3CPU<Impl>::DeallocateContextEvent::description() const
206{
207    return "FullO3CPU \"Deallocate Context\"";
208}
209
210template <class Impl>
211FullO3CPU<Impl>::FullO3CPU(DerivO3CPUParams *params)
212    : BaseO3CPU(params),
213      itb(params->itb),
214      dtb(params->dtb),
215      tickEvent(this),
216#ifndef NDEBUG
217      instcount(0),
218#endif
219      removeInstsThisCycle(false),
220      fetch(this, params),
221      decode(this, params),
222      rename(this, params),
223      iew(this, params),
224      commit(this, params),
225
226      regFile(this, params->numPhysIntRegs,
227              params->numPhysFloatRegs),
228
229      freeList(params->numThreads,
230               TheISA::NumIntRegs, params->numPhysIntRegs,
231               TheISA::NumFloatRegs, params->numPhysFloatRegs),
232
233      rob(this,
234          params->numROBEntries, params->squashWidth,
235          params->smtROBPolicy, params->smtROBThreshold,
236          params->numThreads),
237
238      scoreboard(params->numThreads,
239                 TheISA::NumIntRegs, params->numPhysIntRegs,
240                 TheISA::NumFloatRegs, params->numPhysFloatRegs,
241                 TheISA::NumMiscRegs * numThreads,
242                 TheISA::ZeroReg),
243
244      icachePort(&fetch, this),
245      dcachePort(&iew.ldstQueue, this),
246
247      timeBuffer(params->backComSize, params->forwardComSize),
248      fetchQueue(params->backComSize, params->forwardComSize),
249      decodeQueue(params->backComSize, params->forwardComSize),
250      renameQueue(params->backComSize, params->forwardComSize),
251      iewQueue(params->backComSize, params->forwardComSize),
252      activityRec(name(), NumStages,
253                  params->backComSize + params->forwardComSize,
254                  params->activity),
255
256      globalSeqNum(1),
257      system(params->system),
258      drainCount(0),
259      deferRegistration(params->defer_registration)
260{
261    if (!deferRegistration) {
262        _status = Running;
263    } else {
264        _status = SwitchedOut;
265    }
266
267    if (params->checker) {
268        BaseCPU *temp_checker = params->checker;
269        checker = dynamic_cast<Checker<Impl> *>(temp_checker);
270        checker->setIcachePort(&icachePort);
271        checker->setSystem(params->system);
272    } else {
273        checker = NULL;
274    }
275
276    if (!FullSystem) {
277        thread.resize(numThreads);
278        tids.resize(numThreads);
279    }
280
281    // The stages also need their CPU pointer setup.  However this
282    // must be done at the upper level CPU because they have pointers
283    // to the upper level CPU, and not this FullO3CPU.
284
285    // Set up Pointers to the activeThreads list for each stage
286    fetch.setActiveThreads(&activeThreads);
287    decode.setActiveThreads(&activeThreads);
288    rename.setActiveThreads(&activeThreads);
289    iew.setActiveThreads(&activeThreads);
290    commit.setActiveThreads(&activeThreads);
291
292    // Give each of the stages the time buffer they will use.
293    fetch.setTimeBuffer(&timeBuffer);
294    decode.setTimeBuffer(&timeBuffer);
295    rename.setTimeBuffer(&timeBuffer);
296    iew.setTimeBuffer(&timeBuffer);
297    commit.setTimeBuffer(&timeBuffer);
298
299    // Also setup each of the stages' queues.
300    fetch.setFetchQueue(&fetchQueue);
301    decode.setFetchQueue(&fetchQueue);
302    commit.setFetchQueue(&fetchQueue);
303    decode.setDecodeQueue(&decodeQueue);
304    rename.setDecodeQueue(&decodeQueue);
305    rename.setRenameQueue(&renameQueue);
306    iew.setRenameQueue(&renameQueue);
307    iew.setIEWQueue(&iewQueue);
308    commit.setIEWQueue(&iewQueue);
309    commit.setRenameQueue(&renameQueue);
310
311    commit.setIEWStage(&iew);
312    rename.setIEWStage(&iew);
313    rename.setCommitStage(&commit);
314
315    ThreadID active_threads;
316    if (FullSystem) {
317        active_threads = 1;
318    } else {
319        active_threads = params->workload.size();
320
321        if (active_threads > Impl::MaxThreads) {
322            panic("Workload Size too large. Increase the 'MaxThreads' "
323                  "constant in your O3CPU impl. file (e.g. o3/alpha/impl.hh) "
324                  "or edit your workload size.");
325        }
326    }
327
328    //Make Sure That this a Valid Architeture
329    assert(params->numPhysIntRegs   >= numThreads * TheISA::NumIntRegs);
330    assert(params->numPhysFloatRegs >= numThreads * TheISA::NumFloatRegs);
331
332    rename.setScoreboard(&scoreboard);
333    iew.setScoreboard(&scoreboard);
334
335    // Setup the rename map for whichever stages need it.
336    PhysRegIndex lreg_idx = 0;
337    PhysRegIndex freg_idx = params->numPhysIntRegs; //Index to 1 after int regs
338
339    for (ThreadID tid = 0; tid < numThreads; tid++) {
340        bool bindRegs = (tid <= active_threads - 1);
341
342        commitRenameMap[tid].init(TheISA::NumIntRegs,
343                                  params->numPhysIntRegs,
344                                  lreg_idx,            //Index for Logical. Regs
345
346                                  TheISA::NumFloatRegs,
347                                  params->numPhysFloatRegs,
348                                  freg_idx,            //Index for Float Regs
349
350                                  TheISA::NumMiscRegs,
351
352                                  TheISA::ZeroReg,
353                                  TheISA::ZeroReg,
354
355                                  tid,
356                                  false);
357
358        renameMap[tid].init(TheISA::NumIntRegs,
359                            params->numPhysIntRegs,
360                            lreg_idx,                  //Index for Logical. Regs
361
362                            TheISA::NumFloatRegs,
363                            params->numPhysFloatRegs,
364                            freg_idx,                  //Index for Float Regs
365
366                            TheISA::NumMiscRegs,
367
368                            TheISA::ZeroReg,
369                            TheISA::ZeroReg,
370
371                            tid,
372                            bindRegs);
373
374        activateThreadEvent[tid].init(tid, this);
375        deallocateContextEvent[tid].init(tid, this);
376    }
377
378    rename.setRenameMap(renameMap);
379    commit.setRenameMap(commitRenameMap);
380
381    // Give renameMap & rename stage access to the freeList;
382    for (ThreadID tid = 0; tid < numThreads; tid++)
383        renameMap[tid].setFreeList(&freeList);
384    rename.setFreeList(&freeList);
385
386    // Setup the ROB for whichever stages need it.
387    commit.setROB(&rob);
388
389    lastRunningCycle = curTick();
390
391    lastActivatedCycle = -1;
392#if 0
393    // Give renameMap & rename stage access to the freeList;
394    for (ThreadID tid = 0; tid < numThreads; tid++)
395        globalSeqNum[tid] = 1;
396#endif
397
398    contextSwitch = false;
399    DPRINTF(O3CPU, "Creating O3CPU object.\n");
400
401    // Setup any thread state.
402    this->thread.resize(this->numThreads);
403
404    for (ThreadID tid = 0; tid < this->numThreads; ++tid) {
405        if (FullSystem) {
406            // SMT is not supported in FS mode yet.
407            assert(this->numThreads == 1);
408            this->thread[tid] = new Thread(this, 0, NULL);
409        } else {
410            if (tid < params->workload.size()) {
411                DPRINTF(O3CPU, "Workload[%i] process is %#x",
412                        tid, this->thread[tid]);
413                this->thread[tid] = new typename FullO3CPU<Impl>::Thread(
414                        (typename Impl::O3CPU *)(this),
415                        tid, params->workload[tid]);
416
417                //usedTids[tid] = true;
418                //threadMap[tid] = tid;
419            } else {
420                //Allocate Empty thread so M5 can use later
421                //when scheduling threads to CPU
422                Process* dummy_proc = NULL;
423
424                this->thread[tid] = new typename FullO3CPU<Impl>::Thread(
425                        (typename Impl::O3CPU *)(this),
426                        tid, dummy_proc);
427                //usedTids[tid] = false;
428            }
429        }
430
431        ThreadContext *tc;
432
433        // Setup the TC that will serve as the interface to the threads/CPU.
434        O3ThreadContext<Impl> *o3_tc = new O3ThreadContext<Impl>;
435
436        tc = o3_tc;
437
438        // If we're using a checker, then the TC should be the
439        // CheckerThreadContext.
440        if (params->checker) {
441            tc = new CheckerThreadContext<O3ThreadContext<Impl> >(
442                o3_tc, this->checker);
443        }
444
445        o3_tc->cpu = (typename Impl::O3CPU *)(this);
446        assert(o3_tc->cpu);
447        o3_tc->thread = this->thread[tid];
448
449        if (FullSystem) {
450            // Setup quiesce event.
451            this->thread[tid]->quiesceEvent = new EndQuiesceEvent(tc);
452        }
453        // Give the thread the TC.
454        this->thread[tid]->tc = tc;
455
456        // Add the TC to the CPU's list of TC's.
457        this->threadContexts.push_back(tc);
458    }
459
460    // FullO3CPU always requires an interrupt controller.
461    if (!params->defer_registration && !interrupts) {
462        fatal("FullO3CPU %s has no interrupt controller.\n"
463              "Ensure createInterruptController() is called.\n", name());
464    }
465
466    for (ThreadID tid = 0; tid < this->numThreads; tid++)
467        this->thread[tid]->setFuncExeInst(0);
468
469    lockAddr = 0;
470    lockFlag = false;
471}
472
473template <class Impl>
474FullO3CPU<Impl>::~FullO3CPU()
475{
476}
477
478template <class Impl>
479void
480FullO3CPU<Impl>::regStats()
481{
482    BaseO3CPU::regStats();
483
484    // Register any of the O3CPU's stats here.
485    timesIdled
486        .name(name() + ".timesIdled")
487        .desc("Number of times that the entire CPU went into an idle state and"
488              " unscheduled itself")
489        .prereq(timesIdled);
490
491    idleCycles
492        .name(name() + ".idleCycles")
493        .desc("Total number of cycles that the CPU has spent unscheduled due "
494              "to idling")
495        .prereq(idleCycles);
496
497    quiesceCycles
498        .name(name() + ".quiesceCycles")
499        .desc("Total number of cycles that CPU has spent quiesced or waiting "
500              "for an interrupt")
501        .prereq(quiesceCycles);
502
503    // Number of Instructions simulated
504    // --------------------------------
505    // Should probably be in Base CPU but need templated
506    // MaxThreads so put in here instead
507    committedInsts
508        .init(numThreads)
509        .name(name() + ".committedInsts")
510        .desc("Number of Instructions Simulated");
511
512    committedOps
513        .init(numThreads)
514        .name(name() + ".committedOps")
515        .desc("Number of Ops (including micro ops) Simulated");
516
517    totalCommittedInsts
518        .name(name() + ".committedInsts_total")
519        .desc("Number of Instructions Simulated");
520
521    cpi
522        .name(name() + ".cpi")
523        .desc("CPI: Cycles Per Instruction")
524        .precision(6);
525    cpi = numCycles / committedInsts;
526
527    totalCpi
528        .name(name() + ".cpi_total")
529        .desc("CPI: Total CPI of All Threads")
530        .precision(6);
531    totalCpi = numCycles / totalCommittedInsts;
532
533    ipc
534        .name(name() + ".ipc")
535        .desc("IPC: Instructions Per Cycle")
536        .precision(6);
537    ipc =  committedInsts / numCycles;
538
539    totalIpc
540        .name(name() + ".ipc_total")
541        .desc("IPC: Total IPC of All Threads")
542        .precision(6);
543    totalIpc =  totalCommittedInsts / numCycles;
544
545    this->fetch.regStats();
546    this->decode.regStats();
547    this->rename.regStats();
548    this->iew.regStats();
549    this->commit.regStats();
550    this->rob.regStats();
551
552    intRegfileReads
553        .name(name() + ".int_regfile_reads")
554        .desc("number of integer regfile reads")
555        .prereq(intRegfileReads);
556
557    intRegfileWrites
558        .name(name() + ".int_regfile_writes")
559        .desc("number of integer regfile writes")
560        .prereq(intRegfileWrites);
561
562    fpRegfileReads
563        .name(name() + ".fp_regfile_reads")
564        .desc("number of floating regfile reads")
565        .prereq(fpRegfileReads);
566
567    fpRegfileWrites
568        .name(name() + ".fp_regfile_writes")
569        .desc("number of floating regfile writes")
570        .prereq(fpRegfileWrites);
571
572    miscRegfileReads
573        .name(name() + ".misc_regfile_reads")
574        .desc("number of misc regfile reads")
575        .prereq(miscRegfileReads);
576
577    miscRegfileWrites
578        .name(name() + ".misc_regfile_writes")
579        .desc("number of misc regfile writes")
580        .prereq(miscRegfileWrites);
581}
582
583template <class Impl>
584void
585FullO3CPU<Impl>::tick()
586{
587    DPRINTF(O3CPU, "\n\nFullO3CPU: Ticking main, FullO3CPU.\n");
588
589    ++numCycles;
590
591//    activity = false;
592
593    //Tick each of the stages
594    fetch.tick();
595
596    decode.tick();
597
598    rename.tick();
599
600    iew.tick();
601
602    commit.tick();
603
604    if (!FullSystem)
605        doContextSwitch();
606
607    // Now advance the time buffers
608    timeBuffer.advance();
609
610    fetchQueue.advance();
611    decodeQueue.advance();
612    renameQueue.advance();
613    iewQueue.advance();
614
615    activityRec.advance();
616
617    if (removeInstsThisCycle) {
618        cleanUpRemovedInsts();
619    }
620
621    if (!tickEvent.scheduled()) {
622        if (_status == SwitchedOut ||
623            getState() == SimObject::Drained) {
624            DPRINTF(O3CPU, "Switched out!\n");
625            // increment stat
626            lastRunningCycle = curTick();
627        } else if (!activityRec.active() || _status == Idle) {
628            DPRINTF(O3CPU, "Idle!\n");
629            lastRunningCycle = curTick();
630            timesIdled++;
631        } else {
632            schedule(tickEvent, nextCycle(curTick() + ticks(1)));
633            DPRINTF(O3CPU, "Scheduling next tick!\n");
634        }
635    }
636
637    if (!FullSystem)
638        updateThreadPriority();
639}
640
641template <class Impl>
642void
643FullO3CPU<Impl>::init()
644{
645    BaseCPU::init();
646
647    for (ThreadID tid = 0; tid < numThreads; ++tid) {
648        // Set inSyscall so that the CPU doesn't squash when initially
649        // setting up registers.
650        thread[tid]->inSyscall = true;
651        // Initialise the ThreadContext's memory proxies
652        thread[tid]->initMemProxies(thread[tid]->getTC());
653    }
654
655    // this CPU could still be unconnected if we are restoring from a
656    // checkpoint and this CPU is to be switched in, thus we can only
657    // do this here if the instruction port is actually connected, if
658    // not we have to do it as part of takeOverFrom
659    if (icachePort.isConnected())
660        fetch.setIcache();
661
662    if (FullSystem && !params()->defer_registration) {
663        for (ThreadID tid = 0; tid < numThreads; tid++) {
664            ThreadContext *src_tc = threadContexts[tid];
665            TheISA::initCPU(src_tc, src_tc->contextId());
666        }
667    }
668
669    // Clear inSyscall.
670    for (int tid = 0; tid < numThreads; ++tid)
671        thread[tid]->inSyscall = false;
672
673    // Initialize stages.
674    fetch.initStage();
675    iew.initStage();
676    rename.initStage();
677    commit.initStage();
678
679    commit.setThreads(thread);
680}
681
682template <class Impl>
683void
684FullO3CPU<Impl>::activateThread(ThreadID tid)
685{
686    list<ThreadID>::iterator isActive =
687        std::find(activeThreads.begin(), activeThreads.end(), tid);
688
689    DPRINTF(O3CPU, "[tid:%i]: Calling activate thread.\n", tid);
690
691    if (isActive == activeThreads.end()) {
692        DPRINTF(O3CPU, "[tid:%i]: Adding to active threads list\n",
693                tid);
694
695        activeThreads.push_back(tid);
696    }
697}
698
699template <class Impl>
700void
701FullO3CPU<Impl>::deactivateThread(ThreadID tid)
702{
703    //Remove From Active List, if Active
704    list<ThreadID>::iterator thread_it =
705        std::find(activeThreads.begin(), activeThreads.end(), tid);
706
707    DPRINTF(O3CPU, "[tid:%i]: Calling deactivate thread.\n", tid);
708
709    if (thread_it != activeThreads.end()) {
710        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
711                tid);
712        activeThreads.erase(thread_it);
713    }
714}
715
716template <class Impl>
717Counter
718FullO3CPU<Impl>::totalInsts() const
719{
720    Counter total(0);
721
722    ThreadID size = thread.size();
723    for (ThreadID i = 0; i < size; i++)
724        total += thread[i]->numInst;
725
726    return total;
727}
728
729template <class Impl>
730Counter
731FullO3CPU<Impl>::totalOps() const
732{
733    Counter total(0);
734
735    ThreadID size = thread.size();
736    for (ThreadID i = 0; i < size; i++)
737        total += thread[i]->numOp;
738
739    return total;
740}
741
742template <class Impl>
743void
744FullO3CPU<Impl>::activateContext(ThreadID tid, int delay)
745{
746    // Needs to set each stage to running as well.
747    if (delay){
748        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to activate "
749                "on cycle %d\n", tid, curTick() + ticks(delay));
750        scheduleActivateThreadEvent(tid, delay);
751    } else {
752        activateThread(tid);
753    }
754
755    if (lastActivatedCycle < curTick()) {
756        scheduleTickEvent(delay);
757
758        // Be sure to signal that there's some activity so the CPU doesn't
759        // deschedule itself.
760        activityRec.activity();
761        fetch.wakeFromQuiesce();
762
763        quiesceCycles += tickToCycles((curTick() - 1) - lastRunningCycle);
764
765        lastActivatedCycle = curTick();
766
767        _status = Running;
768    }
769}
770
771template <class Impl>
772bool
773FullO3CPU<Impl>::scheduleDeallocateContext(ThreadID tid, bool remove,
774                                           int delay)
775{
776    // Schedule removal of thread data from CPU
777    if (delay){
778        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to deallocate "
779                "on cycle %d\n", tid, curTick() + ticks(delay));
780        scheduleDeallocateContextEvent(tid, remove, delay);
781        return false;
782    } else {
783        deactivateThread(tid);
784        if (remove)
785            removeThread(tid);
786        return true;
787    }
788}
789
790template <class Impl>
791void
792FullO3CPU<Impl>::suspendContext(ThreadID tid)
793{
794    DPRINTF(O3CPU,"[tid: %i]: Suspending Thread Context.\n", tid);
795    bool deallocated = scheduleDeallocateContext(tid, false, 1);
796    // If this was the last thread then unschedule the tick event.
797    if ((activeThreads.size() == 1 && !deallocated) ||
798        activeThreads.size() == 0)
799        unscheduleTickEvent();
800
801    DPRINTF(Quiesce, "Suspending Context\n");
802    lastRunningCycle = curTick();
803    _status = Idle;
804}
805
806template <class Impl>
807void
808FullO3CPU<Impl>::haltContext(ThreadID tid)
809{
810    //For now, this is the same as deallocate
811    DPRINTF(O3CPU,"[tid:%i]: Halt Context called. Deallocating", tid);
812    scheduleDeallocateContext(tid, true, 1);
813}
814
815template <class Impl>
816void
817FullO3CPU<Impl>::insertThread(ThreadID tid)
818{
819    DPRINTF(O3CPU,"[tid:%i] Initializing thread into CPU");
820    // Will change now that the PC and thread state is internal to the CPU
821    // and not in the ThreadContext.
822    ThreadContext *src_tc;
823    if (FullSystem)
824        src_tc = system->threadContexts[tid];
825    else
826        src_tc = tcBase(tid);
827
828    //Bind Int Regs to Rename Map
829    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
830        PhysRegIndex phys_reg = freeList.getIntReg();
831
832        renameMap[tid].setEntry(ireg,phys_reg);
833        scoreboard.setReg(phys_reg);
834    }
835
836    //Bind Float Regs to Rename Map
837    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
838        PhysRegIndex phys_reg = freeList.getFloatReg();
839
840        renameMap[tid].setEntry(freg,phys_reg);
841        scoreboard.setReg(phys_reg);
842    }
843
844    //Copy Thread Data Into RegFile
845    //this->copyFromTC(tid);
846
847    //Set PC/NPC/NNPC
848    pcState(src_tc->pcState(), tid);
849
850    src_tc->setStatus(ThreadContext::Active);
851
852    activateContext(tid,1);
853
854    //Reset ROB/IQ/LSQ Entries
855    commit.rob->resetEntries();
856    iew.resetEntries();
857}
858
859template <class Impl>
860void
861FullO3CPU<Impl>::removeThread(ThreadID tid)
862{
863    DPRINTF(O3CPU,"[tid:%i] Removing thread context from CPU.\n", tid);
864
865    // Copy Thread Data From RegFile
866    // If thread is suspended, it might be re-allocated
867    // this->copyToTC(tid);
868
869
870    // @todo: 2-27-2008: Fix how we free up rename mappings
871    // here to alleviate the case for double-freeing registers
872    // in SMT workloads.
873
874    // Unbind Int Regs from Rename Map
875    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
876        PhysRegIndex phys_reg = renameMap[tid].lookup(ireg);
877
878        scoreboard.unsetReg(phys_reg);
879        freeList.addReg(phys_reg);
880    }
881
882    // Unbind Float Regs from Rename Map
883    for (int freg = TheISA::NumIntRegs; freg < TheISA::NumFloatRegs; freg++) {
884        PhysRegIndex phys_reg = renameMap[tid].lookup(freg);
885
886        scoreboard.unsetReg(phys_reg);
887        freeList.addReg(phys_reg);
888    }
889
890    // Squash Throughout Pipeline
891    DynInstPtr inst = commit.rob->readHeadInst(tid);
892    InstSeqNum squash_seq_num = inst->seqNum;
893    fetch.squash(0, squash_seq_num, inst, tid);
894    decode.squash(tid);
895    rename.squash(squash_seq_num, tid);
896    iew.squash(tid);
897    iew.ldstQueue.squash(squash_seq_num, tid);
898    commit.rob->squash(squash_seq_num, tid);
899
900
901    assert(iew.instQueue.getCount(tid) == 0);
902    assert(iew.ldstQueue.getCount(tid) == 0);
903
904    // Reset ROB/IQ/LSQ Entries
905
906    // Commented out for now.  This should be possible to do by
907    // telling all the pipeline stages to drain first, and then
908    // checking until the drain completes.  Once the pipeline is
909    // drained, call resetEntries(). - 10-09-06 ktlim
910/*
911    if (activeThreads.size() >= 1) {
912        commit.rob->resetEntries();
913        iew.resetEntries();
914    }
915*/
916}
917
918
919template <class Impl>
920void
921FullO3CPU<Impl>::activateWhenReady(ThreadID tid)
922{
923    DPRINTF(O3CPU,"[tid:%i]: Checking if resources are available for incoming"
924            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
925            tid);
926
927    bool ready = true;
928
929    if (freeList.numFreeIntRegs() >= TheISA::NumIntRegs) {
930        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
931                "Phys. Int. Regs.\n",
932                tid);
933        ready = false;
934    } else if (freeList.numFreeFloatRegs() >= TheISA::NumFloatRegs) {
935        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
936                "Phys. Float. Regs.\n",
937                tid);
938        ready = false;
939    } else if (commit.rob->numFreeEntries() >=
940               commit.rob->entryAmount(activeThreads.size() + 1)) {
941        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
942                "ROB entries.\n",
943                tid);
944        ready = false;
945    } else if (iew.instQueue.numFreeEntries() >=
946               iew.instQueue.entryAmount(activeThreads.size() + 1)) {
947        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
948                "IQ entries.\n",
949                tid);
950        ready = false;
951    } else if (iew.ldstQueue.numFreeEntries() >=
952               iew.ldstQueue.entryAmount(activeThreads.size() + 1)) {
953        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
954                "LSQ entries.\n",
955                tid);
956        ready = false;
957    }
958
959    if (ready) {
960        insertThread(tid);
961
962        contextSwitch = false;
963
964        cpuWaitList.remove(tid);
965    } else {
966        suspendContext(tid);
967
968        //blocks fetch
969        contextSwitch = true;
970
971        //@todo: dont always add to waitlist
972        //do waitlist
973        cpuWaitList.push_back(tid);
974    }
975}
976
977template <class Impl>
978Fault
979FullO3CPU<Impl>::hwrei(ThreadID tid)
980{
981#if THE_ISA == ALPHA_ISA
982    // Need to clear the lock flag upon returning from an interrupt.
983    this->setMiscRegNoEffect(AlphaISA::MISCREG_LOCKFLAG, false, tid);
984
985    this->thread[tid]->kernelStats->hwrei();
986
987    // FIXME: XXX check for interrupts? XXX
988#endif
989    return NoFault;
990}
991
992template <class Impl>
993bool
994FullO3CPU<Impl>::simPalCheck(int palFunc, ThreadID tid)
995{
996#if THE_ISA == ALPHA_ISA
997    if (this->thread[tid]->kernelStats)
998        this->thread[tid]->kernelStats->callpal(palFunc,
999                                                this->threadContexts[tid]);
1000
1001    switch (palFunc) {
1002      case PAL::halt:
1003        halt();
1004        if (--System::numSystemsRunning == 0)
1005            exitSimLoop("all cpus halted");
1006        break;
1007
1008      case PAL::bpt:
1009      case PAL::bugchk:
1010        if (this->system->breakpoint())
1011            return false;
1012        break;
1013    }
1014#endif
1015    return true;
1016}
1017
1018template <class Impl>
1019Fault
1020FullO3CPU<Impl>::getInterrupts()
1021{
1022    // Check if there are any outstanding interrupts
1023    return this->interrupts->getInterrupt(this->threadContexts[0]);
1024}
1025
1026template <class Impl>
1027void
1028FullO3CPU<Impl>::processInterrupts(Fault interrupt)
1029{
1030    // Check for interrupts here.  For now can copy the code that
1031    // exists within isa_fullsys_traits.hh.  Also assume that thread 0
1032    // is the one that handles the interrupts.
1033    // @todo: Possibly consolidate the interrupt checking code.
1034    // @todo: Allow other threads to handle interrupts.
1035
1036    assert(interrupt != NoFault);
1037    this->interrupts->updateIntrInfo(this->threadContexts[0]);
1038
1039    DPRINTF(O3CPU, "Interrupt %s being handled\n", interrupt->name());
1040    this->trap(interrupt, 0, NULL);
1041}
1042
1043template <class Impl>
1044void
1045FullO3CPU<Impl>::trap(Fault fault, ThreadID tid, StaticInstPtr inst)
1046{
1047    // Pass the thread's TC into the invoke method.
1048    fault->invoke(this->threadContexts[tid], inst);
1049}
1050
1051template <class Impl>
1052void
1053FullO3CPU<Impl>::syscall(int64_t callnum, ThreadID tid)
1054{
1055    DPRINTF(O3CPU, "[tid:%i] Executing syscall().\n\n", tid);
1056
1057    DPRINTF(Activity,"Activity: syscall() called.\n");
1058
1059    // Temporarily increase this by one to account for the syscall
1060    // instruction.
1061    ++(this->thread[tid]->funcExeInst);
1062
1063    // Execute the actual syscall.
1064    this->thread[tid]->syscall(callnum);
1065
1066    // Decrease funcExeInst by one as the normal commit will handle
1067    // incrementing it.
1068    --(this->thread[tid]->funcExeInst);
1069}
1070
1071template <class Impl>
1072void
1073FullO3CPU<Impl>::serialize(std::ostream &os)
1074{
1075    SimObject::State so_state = SimObject::getState();
1076    SERIALIZE_ENUM(so_state);
1077    BaseCPU::serialize(os);
1078    nameOut(os, csprintf("%s.tickEvent", name()));
1079    tickEvent.serialize(os);
1080
1081    // Use SimpleThread's ability to checkpoint to make it easier to
1082    // write out the registers.  Also make this static so it doesn't
1083    // get instantiated multiple times (causes a panic in statistics).
1084    static SimpleThread temp;
1085
1086    ThreadID size = thread.size();
1087    for (ThreadID i = 0; i < size; i++) {
1088        nameOut(os, csprintf("%s.xc.%i", name(), i));
1089        temp.copyTC(thread[i]->getTC());
1090        temp.serialize(os);
1091    }
1092}
1093
1094template <class Impl>
1095void
1096FullO3CPU<Impl>::unserialize(Checkpoint *cp, const std::string &section)
1097{
1098    SimObject::State so_state;
1099    UNSERIALIZE_ENUM(so_state);
1100    BaseCPU::unserialize(cp, section);
1101    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));
1102
1103    // Use SimpleThread's ability to checkpoint to make it easier to
1104    // read in the registers.  Also make this static so it doesn't
1105    // get instantiated multiple times (causes a panic in statistics).
1106    static SimpleThread temp;
1107
1108    ThreadID size = thread.size();
1109    for (ThreadID i = 0; i < size; i++) {
1110        temp.copyTC(thread[i]->getTC());
1111        temp.unserialize(cp, csprintf("%s.xc.%i", section, i));
1112        thread[i]->getTC()->copyArchRegs(temp.getTC());
1113    }
1114}
1115
1116template <class Impl>
1117unsigned int
1118FullO3CPU<Impl>::drain(Event *drain_event)
1119{
1120    DPRINTF(O3CPU, "Switching out\n");
1121
1122    // If the CPU isn't doing anything, then return immediately.
1123    if (_status == SwitchedOut)
1124        return 0;
1125
1126    drainCount = 0;
1127    fetch.drain();
1128    decode.drain();
1129    rename.drain();
1130    iew.drain();
1131    commit.drain();
1132
1133    // Wake the CPU and record activity so everything can drain out if
1134    // the CPU was not able to immediately drain.
1135    if (getState() != SimObject::Drained) {
1136        // A bit of a hack...set the drainEvent after all the drain()
1137        // calls have been made, that way if all of the stages drain
1138        // immediately, the signalDrained() function knows not to call
1139        // process on the drain event.
1140        drainEvent = drain_event;
1141
1142        wakeCPU();
1143        activityRec.activity();
1144
1145        DPRINTF(Drain, "CPU not drained\n");
1146
1147        return 1;
1148    } else {
1149        return 0;
1150    }
1151}
1152
1153template <class Impl>
1154void
1155FullO3CPU<Impl>::resume()
1156{
1157    fetch.resume();
1158    decode.resume();
1159    rename.resume();
1160    iew.resume();
1161    commit.resume();
1162
1163    changeState(SimObject::Running);
1164
1165    if (_status == SwitchedOut)
1166        return;
1167
1168    assert(system->getMemoryMode() == Enums::timing);
1169
1170    if (!tickEvent.scheduled())
1171        schedule(tickEvent, nextCycle());
1172    _status = Running;
1173}
1174
1175template <class Impl>
1176void
1177FullO3CPU<Impl>::signalDrained()
1178{
1179    if (++drainCount == NumStages) {
1180        if (tickEvent.scheduled())
1181            tickEvent.squash();
1182
1183        changeState(SimObject::Drained);
1184
1185        BaseCPU::switchOut();
1186
1187        if (drainEvent) {
1188            DPRINTF(Drain, "CPU done draining, processing drain event\n");
1189            drainEvent->process();
1190            drainEvent = NULL;
1191        }
1192    }
1193    assert(drainCount <= 5);
1194}
1195
1196template <class Impl>
1197void
1198FullO3CPU<Impl>::switchOut()
1199{
1200    fetch.switchOut();
1201    rename.switchOut();
1202    iew.switchOut();
1203    commit.switchOut();
1204    instList.clear();
1205    while (!removeList.empty()) {
1206        removeList.pop();
1207    }
1208
1209    _status = SwitchedOut;
1210
1211    if (checker)
1212        checker->switchOut();
1213
1214    if (tickEvent.scheduled())
1215        tickEvent.squash();
1216}
1217
1218template <class Impl>
1219void
1220FullO3CPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
1221{
1222    // Flush out any old data from the time buffers.
1223    for (int i = 0; i < timeBuffer.getSize(); ++i) {
1224        timeBuffer.advance();
1225        fetchQueue.advance();
1226        decodeQueue.advance();
1227        renameQueue.advance();
1228        iewQueue.advance();
1229    }
1230
1231    activityRec.reset();
1232
1233    BaseCPU::takeOverFrom(oldCPU);
1234
1235    fetch.takeOverFrom();
1236    decode.takeOverFrom();
1237    rename.takeOverFrom();
1238    iew.takeOverFrom();
1239    commit.takeOverFrom();
1240
1241    assert(!tickEvent.scheduled() || tickEvent.squashed());
1242
1243    FullO3CPU<Impl> *oldO3CPU = dynamic_cast<FullO3CPU<Impl>*>(oldCPU);
1244    if (oldO3CPU)
1245        globalSeqNum = oldO3CPU->globalSeqNum;
1246
1247    // @todo: Figure out how to properly select the tid to put onto
1248    // the active threads list.
1249    ThreadID tid = 0;
1250
1251    list<ThreadID>::iterator isActive =
1252        std::find(activeThreads.begin(), activeThreads.end(), tid);
1253
1254    if (isActive == activeThreads.end()) {
1255        //May Need to Re-code this if the delay variable is the delay
1256        //needed for thread to activate
1257        DPRINTF(O3CPU, "Adding Thread %i to active threads list\n",
1258                tid);
1259
1260        activeThreads.push_back(tid);
1261    }
1262
1263    // Set all statuses to active, schedule the CPU's tick event.
1264    // @todo: Fix up statuses so this is handled properly
1265    ThreadID size = threadContexts.size();
1266    for (ThreadID i = 0; i < size; ++i) {
1267        ThreadContext *tc = threadContexts[i];
1268        if (tc->status() == ThreadContext::Active && _status != Running) {
1269            _status = Running;
1270            reschedule(tickEvent, nextCycle(), true);
1271        }
1272    }
1273    if (!tickEvent.scheduled())
1274        schedule(tickEvent, nextCycle());
1275
1276    lastRunningCycle = curTick();
1277}
1278
1279template <class Impl>
1280TheISA::MiscReg
1281FullO3CPU<Impl>::readMiscRegNoEffect(int misc_reg, ThreadID tid)
1282{
1283    return this->isa[tid].readMiscRegNoEffect(misc_reg);
1284}
1285
1286template <class Impl>
1287TheISA::MiscReg
1288FullO3CPU<Impl>::readMiscReg(int misc_reg, ThreadID tid)
1289{
1290    miscRegfileReads++;
1291    return this->isa[tid].readMiscReg(misc_reg, tcBase(tid));
1292}
1293
1294template <class Impl>
1295void
1296FullO3CPU<Impl>::setMiscRegNoEffect(int misc_reg,
1297        const TheISA::MiscReg &val, ThreadID tid)
1298{
1299    this->isa[tid].setMiscRegNoEffect(misc_reg, val);
1300}
1301
1302template <class Impl>
1303void
1304FullO3CPU<Impl>::setMiscReg(int misc_reg,
1305        const TheISA::MiscReg &val, ThreadID tid)
1306{
1307    miscRegfileWrites++;
1308    this->isa[tid].setMiscReg(misc_reg, val, tcBase(tid));
1309}
1310
1311template <class Impl>
1312uint64_t
1313FullO3CPU<Impl>::readIntReg(int reg_idx)
1314{
1315    intRegfileReads++;
1316    return regFile.readIntReg(reg_idx);
1317}
1318
1319template <class Impl>
1320FloatReg
1321FullO3CPU<Impl>::readFloatReg(int reg_idx)
1322{
1323    fpRegfileReads++;
1324    return regFile.readFloatReg(reg_idx);
1325}
1326
1327template <class Impl>
1328FloatRegBits
1329FullO3CPU<Impl>::readFloatRegBits(int reg_idx)
1330{
1331    fpRegfileReads++;
1332    return regFile.readFloatRegBits(reg_idx);
1333}
1334
1335template <class Impl>
1336void
1337FullO3CPU<Impl>::setIntReg(int reg_idx, uint64_t val)
1338{
1339    intRegfileWrites++;
1340    regFile.setIntReg(reg_idx, val);
1341}
1342
1343template <class Impl>
1344void
1345FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val)
1346{
1347    fpRegfileWrites++;
1348    regFile.setFloatReg(reg_idx, val);
1349}
1350
1351template <class Impl>
1352void
1353FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val)
1354{
1355    fpRegfileWrites++;
1356    regFile.setFloatRegBits(reg_idx, val);
1357}
1358
1359template <class Impl>
1360uint64_t
1361FullO3CPU<Impl>::readArchIntReg(int reg_idx, ThreadID tid)
1362{
1363    intRegfileReads++;
1364    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1365
1366    return regFile.readIntReg(phys_reg);
1367}
1368
1369template <class Impl>
1370float
1371FullO3CPU<Impl>::readArchFloatReg(int reg_idx, ThreadID tid)
1372{
1373    fpRegfileReads++;
1374    int idx = reg_idx + TheISA::NumIntRegs;
1375    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1376
1377    return regFile.readFloatReg(phys_reg);
1378}
1379
1380template <class Impl>
1381uint64_t
1382FullO3CPU<Impl>::readArchFloatRegInt(int reg_idx, ThreadID tid)
1383{
1384    fpRegfileReads++;
1385    int idx = reg_idx + TheISA::NumIntRegs;
1386    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1387
1388    return regFile.readFloatRegBits(phys_reg);
1389}
1390
1391template <class Impl>
1392void
1393FullO3CPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, ThreadID tid)
1394{
1395    intRegfileWrites++;
1396    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1397
1398    regFile.setIntReg(phys_reg, val);
1399}
1400
1401template <class Impl>
1402void
1403FullO3CPU<Impl>::setArchFloatReg(int reg_idx, float val, ThreadID tid)
1404{
1405    fpRegfileWrites++;
1406    int idx = reg_idx + TheISA::NumIntRegs;
1407    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1408
1409    regFile.setFloatReg(phys_reg, val);
1410}
1411
1412template <class Impl>
1413void
1414FullO3CPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, ThreadID tid)
1415{
1416    fpRegfileWrites++;
1417    int idx = reg_idx + TheISA::NumIntRegs;
1418    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1419
1420    regFile.setFloatRegBits(phys_reg, val);
1421}
1422
1423template <class Impl>
1424TheISA::PCState
1425FullO3CPU<Impl>::pcState(ThreadID tid)
1426{
1427    return commit.pcState(tid);
1428}
1429
1430template <class Impl>
1431void
1432FullO3CPU<Impl>::pcState(const TheISA::PCState &val, ThreadID tid)
1433{
1434    commit.pcState(val, tid);
1435}
1436
1437template <class Impl>
1438Addr
1439FullO3CPU<Impl>::instAddr(ThreadID tid)
1440{
1441    return commit.instAddr(tid);
1442}
1443
1444template <class Impl>
1445Addr
1446FullO3CPU<Impl>::nextInstAddr(ThreadID tid)
1447{
1448    return commit.nextInstAddr(tid);
1449}
1450
1451template <class Impl>
1452MicroPC
1453FullO3CPU<Impl>::microPC(ThreadID tid)
1454{
1455    return commit.microPC(tid);
1456}
1457
1458template <class Impl>
1459void
1460FullO3CPU<Impl>::squashFromTC(ThreadID tid)
1461{
1462    this->thread[tid]->inSyscall = true;
1463    this->commit.generateTCEvent(tid);
1464}
1465
1466template <class Impl>
1467typename FullO3CPU<Impl>::ListIt
1468FullO3CPU<Impl>::addInst(DynInstPtr &inst)
1469{
1470    instList.push_back(inst);
1471
1472    return --(instList.end());
1473}
1474
1475template <class Impl>
1476void
1477FullO3CPU<Impl>::instDone(ThreadID tid, DynInstPtr &inst)
1478{
1479    // Keep an instruction count.
1480    if (!inst->isMicroop() || inst->isLastMicroop()) {
1481        thread[tid]->numInst++;
1482        thread[tid]->numInsts++;
1483        committedInsts[tid]++;
1484        totalCommittedInsts++;
1485    }
1486    thread[tid]->numOp++;
1487    thread[tid]->numOps++;
1488    committedOps[tid]++;
1489
1490    system->totalNumInsts++;
1491    // Check for instruction-count-based events.
1492    comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1493    system->instEventQueue.serviceEvents(system->totalNumInsts);
1494}
1495
1496template <class Impl>
1497void
1498FullO3CPU<Impl>::removeFrontInst(DynInstPtr &inst)
1499{
1500    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %s "
1501            "[sn:%lli]\n",
1502            inst->threadNumber, inst->pcState(), inst->seqNum);
1503
1504    removeInstsThisCycle = true;
1505
1506    // Remove the front instruction.
1507    removeList.push(inst->getInstListIt());
1508}
1509
1510template <class Impl>
1511void
1512FullO3CPU<Impl>::removeInstsNotInROB(ThreadID tid)
1513{
1514    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
1515            " list.\n", tid);
1516
1517    ListIt end_it;
1518
1519    bool rob_empty = false;
1520
1521    if (instList.empty()) {
1522        return;
1523    } else if (rob.isEmpty(/*tid*/)) {
1524        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
1525        end_it = instList.begin();
1526        rob_empty = true;
1527    } else {
1528        end_it = (rob.readTailInst(tid))->getInstListIt();
1529        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
1530    }
1531
1532    removeInstsThisCycle = true;
1533
1534    ListIt inst_it = instList.end();
1535
1536    inst_it--;
1537
1538    // Walk through the instruction list, removing any instructions
1539    // that were inserted after the given instruction iterator, end_it.
1540    while (inst_it != end_it) {
1541        assert(!instList.empty());
1542
1543        squashInstIt(inst_it, tid);
1544
1545        inst_it--;
1546    }
1547
1548    // If the ROB was empty, then we actually need to remove the first
1549    // instruction as well.
1550    if (rob_empty) {
1551        squashInstIt(inst_it, tid);
1552    }
1553}
1554
1555template <class Impl>
1556void
1557FullO3CPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid)
1558{
1559    assert(!instList.empty());
1560
1561    removeInstsThisCycle = true;
1562
1563    ListIt inst_iter = instList.end();
1564
1565    inst_iter--;
1566
1567    DPRINTF(O3CPU, "Deleting instructions from instruction "
1568            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1569            tid, seq_num, (*inst_iter)->seqNum);
1570
1571    while ((*inst_iter)->seqNum > seq_num) {
1572
1573        bool break_loop = (inst_iter == instList.begin());
1574
1575        squashInstIt(inst_iter, tid);
1576
1577        inst_iter--;
1578
1579        if (break_loop)
1580            break;
1581    }
1582}
1583
1584template <class Impl>
1585inline void
1586FullO3CPU<Impl>::squashInstIt(const ListIt &instIt, ThreadID tid)
1587{
1588    if ((*instIt)->threadNumber == tid) {
1589        DPRINTF(O3CPU, "Squashing instruction, "
1590                "[tid:%i] [sn:%lli] PC %s\n",
1591                (*instIt)->threadNumber,
1592                (*instIt)->seqNum,
1593                (*instIt)->pcState());
1594
1595        // Mark it as squashed.
1596        (*instIt)->setSquashed();
1597
1598        // @todo: Formulate a consistent method for deleting
1599        // instructions from the instruction list
1600        // Remove the instruction from the list.
1601        removeList.push(instIt);
1602    }
1603}
1604
1605template <class Impl>
1606void
1607FullO3CPU<Impl>::cleanUpRemovedInsts()
1608{
1609    while (!removeList.empty()) {
1610        DPRINTF(O3CPU, "Removing instruction, "
1611                "[tid:%i] [sn:%lli] PC %s\n",
1612                (*removeList.front())->threadNumber,
1613                (*removeList.front())->seqNum,
1614                (*removeList.front())->pcState());
1615
1616        instList.erase(removeList.front());
1617
1618        removeList.pop();
1619    }
1620
1621    removeInstsThisCycle = false;
1622}
1623/*
1624template <class Impl>
1625void
1626FullO3CPU<Impl>::removeAllInsts()
1627{
1628    instList.clear();
1629}
1630*/
1631template <class Impl>
1632void
1633FullO3CPU<Impl>::dumpInsts()
1634{
1635    int num = 0;
1636
1637    ListIt inst_list_it = instList.begin();
1638
1639    cprintf("Dumping Instruction List\n");
1640
1641    while (inst_list_it != instList.end()) {
1642        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1643                "Squashed:%i\n\n",
1644                num, (*inst_list_it)->instAddr(), (*inst_list_it)->threadNumber,
1645                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1646                (*inst_list_it)->isSquashed());
1647        inst_list_it++;
1648        ++num;
1649    }
1650}
1651/*
1652template <class Impl>
1653void
1654FullO3CPU<Impl>::wakeDependents(DynInstPtr &inst)
1655{
1656    iew.wakeDependents(inst);
1657}
1658*/
1659template <class Impl>
1660void
1661FullO3CPU<Impl>::wakeCPU()
1662{
1663    if (activityRec.active() || tickEvent.scheduled()) {
1664        DPRINTF(Activity, "CPU already running.\n");
1665        return;
1666    }
1667
1668    DPRINTF(Activity, "Waking up CPU\n");
1669
1670    idleCycles += tickToCycles((curTick() - 1) - lastRunningCycle);
1671    numCycles += tickToCycles((curTick() - 1) - lastRunningCycle);
1672
1673    schedule(tickEvent, nextCycle());
1674}
1675
1676template <class Impl>
1677void
1678FullO3CPU<Impl>::wakeup()
1679{
1680    if (this->thread[0]->status() != ThreadContext::Suspended)
1681        return;
1682
1683    this->wakeCPU();
1684
1685    DPRINTF(Quiesce, "Suspended Processor woken\n");
1686    this->threadContexts[0]->activate();
1687}
1688
1689template <class Impl>
1690ThreadID
1691FullO3CPU<Impl>::getFreeTid()
1692{
1693    for (ThreadID tid = 0; tid < numThreads; tid++) {
1694        if (!tids[tid]) {
1695            tids[tid] = true;
1696            return tid;
1697        }
1698    }
1699
1700    return InvalidThreadID;
1701}
1702
1703template <class Impl>
1704void
1705FullO3CPU<Impl>::doContextSwitch()
1706{
1707    if (contextSwitch) {
1708
1709        //ADD CODE TO DEACTIVE THREAD HERE (???)
1710
1711        ThreadID size = cpuWaitList.size();
1712        for (ThreadID tid = 0; tid < size; tid++) {
1713            activateWhenReady(tid);
1714        }
1715
1716        if (cpuWaitList.size() == 0)
1717            contextSwitch = true;
1718    }
1719}
1720
1721template <class Impl>
1722void
1723FullO3CPU<Impl>::updateThreadPriority()
1724{
1725    if (activeThreads.size() > 1) {
1726        //DEFAULT TO ROUND ROBIN SCHEME
1727        //e.g. Move highest priority to end of thread list
1728        list<ThreadID>::iterator list_begin = activeThreads.begin();
1729
1730        unsigned high_thread = *list_begin;
1731
1732        activeThreads.erase(list_begin);
1733
1734        activeThreads.push_back(high_thread);
1735    }
1736}
1737
1738// Forward declaration of FullO3CPU.
1739template class FullO3CPU<O3CPUImpl>;
1740