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