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