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