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