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