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