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