cpu.cc revision 5314:e902f12a3af1
1/*
2 * Copyright (c) 2004-2006 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Kevin Lim
29 *          Korey Sewell
30 */
31
32#include "config/full_system.hh"
33#include "config/use_checker.hh"
34
35#include "cpu/activity.hh"
36#include "cpu/simple_thread.hh"
37#include "cpu/thread_context.hh"
38#include "cpu/o3/isa_specific.hh"
39#include "cpu/o3/cpu.hh"
40#include "enums/MemoryMode.hh"
41#include "sim/core.hh"
42#include "sim/stat_control.hh"
43
44#if FULL_SYSTEM
45#include "cpu/quiesce_event.hh"
46#include "sim/system.hh"
47#else
48#include "sim/process.hh"
49#endif
50
51#if USE_CHECKER
52#include "cpu/checker/cpu.hh"
53#endif
54
55using namespace TheISA;
56
57BaseO3CPU::BaseO3CPU(Params *params)
58    : BaseCPU(params), cpu_id(0)
59{
60}
61
62void
63BaseO3CPU::regStats()
64{
65    BaseCPU::regStats();
66}
67
68template <class Impl>
69FullO3CPU<Impl>::TickEvent::TickEvent(FullO3CPU<Impl> *c)
70    : Event(&mainEventQueue, CPU_Tick_Pri), cpu(c)
71{
72}
73
74template <class Impl>
75void
76FullO3CPU<Impl>::TickEvent::process()
77{
78    cpu->tick();
79}
80
81template <class Impl>
82const char *
83FullO3CPU<Impl>::TickEvent::description()
84{
85    return "FullO3CPU tick";
86}
87
88template <class Impl>
89FullO3CPU<Impl>::ActivateThreadEvent::ActivateThreadEvent()
90    : Event(&mainEventQueue, CPU_Switch_Pri)
91{
92}
93
94template <class Impl>
95void
96FullO3CPU<Impl>::ActivateThreadEvent::init(int thread_num,
97                                           FullO3CPU<Impl> *thread_cpu)
98{
99    tid = thread_num;
100    cpu = thread_cpu;
101}
102
103template <class Impl>
104void
105FullO3CPU<Impl>::ActivateThreadEvent::process()
106{
107    cpu->activateThread(tid);
108}
109
110template <class Impl>
111const char *
112FullO3CPU<Impl>::ActivateThreadEvent::description()
113{
114    return "FullO3CPU \"Activate Thread\"";
115}
116
117template <class Impl>
118FullO3CPU<Impl>::DeallocateContextEvent::DeallocateContextEvent()
119    : Event(&mainEventQueue, CPU_Tick_Pri), tid(0), remove(false), cpu(NULL)
120{
121}
122
123template <class Impl>
124void
125FullO3CPU<Impl>::DeallocateContextEvent::init(int thread_num,
126                                              FullO3CPU<Impl> *thread_cpu)
127{
128    tid = thread_num;
129    cpu = thread_cpu;
130    remove = false;
131}
132
133template <class Impl>
134void
135FullO3CPU<Impl>::DeallocateContextEvent::process()
136{
137    cpu->deactivateThread(tid);
138    if (remove)
139        cpu->removeThread(tid);
140}
141
142template <class Impl>
143const char *
144FullO3CPU<Impl>::DeallocateContextEvent::description()
145{
146    return "FullO3CPU \"Deallocate Context\"";
147}
148
149template <class Impl>
150FullO3CPU<Impl>::FullO3CPU(O3CPU *o3_cpu, Params *params)
151    : BaseO3CPU(params),
152      itb(params->itb),
153      dtb(params->dtb),
154      tickEvent(this),
155      removeInstsThisCycle(false),
156      fetch(o3_cpu, params),
157      decode(o3_cpu, params),
158      rename(o3_cpu, params),
159      iew(o3_cpu, params),
160      commit(o3_cpu, params),
161
162      regFile(o3_cpu, params->numPhysIntRegs,
163              params->numPhysFloatRegs),
164
165      freeList(params->numberOfThreads,
166               TheISA::NumIntRegs, params->numPhysIntRegs,
167               TheISA::NumFloatRegs, params->numPhysFloatRegs),
168
169      rob(o3_cpu,
170          params->numROBEntries, params->squashWidth,
171          params->smtROBPolicy, params->smtROBThreshold,
172          params->numberOfThreads),
173
174      scoreboard(params->numberOfThreads,
175                 TheISA::NumIntRegs, params->numPhysIntRegs,
176                 TheISA::NumFloatRegs, params->numPhysFloatRegs,
177                 TheISA::NumMiscRegs * number_of_threads,
178                 TheISA::ZeroReg),
179
180      timeBuffer(params->backComSize, params->forwardComSize),
181      fetchQueue(params->backComSize, params->forwardComSize),
182      decodeQueue(params->backComSize, params->forwardComSize),
183      renameQueue(params->backComSize, params->forwardComSize),
184      iewQueue(params->backComSize, params->forwardComSize),
185      activityRec(NumStages,
186                  params->backComSize + params->forwardComSize,
187                  params->activity),
188
189      globalSeqNum(1),
190#if FULL_SYSTEM
191      system(params->system),
192      physmem(system->physmem),
193#endif // FULL_SYSTEM
194      drainCount(0),
195      deferRegistration(params->deferRegistration),
196      numThreads(number_of_threads)
197{
198    if (!deferRegistration) {
199        _status = Running;
200    } else {
201        _status = Idle;
202    }
203
204#if USE_CHECKER
205    if (params->checker) {
206        BaseCPU *temp_checker = params->checker;
207        checker = dynamic_cast<Checker<DynInstPtr> *>(temp_checker);
208#if FULL_SYSTEM
209        checker->setSystem(params->system);
210#endif
211    } else {
212        checker = NULL;
213    }
214#endif // USE_CHECKER
215
216#if !FULL_SYSTEM
217    thread.resize(number_of_threads);
218    tids.resize(number_of_threads);
219#endif
220
221    // The stages also need their CPU pointer setup.  However this
222    // must be done at the upper level CPU because they have pointers
223    // to the upper level CPU, and not this FullO3CPU.
224
225    // Set up Pointers to the activeThreads list for each stage
226    fetch.setActiveThreads(&activeThreads);
227    decode.setActiveThreads(&activeThreads);
228    rename.setActiveThreads(&activeThreads);
229    iew.setActiveThreads(&activeThreads);
230    commit.setActiveThreads(&activeThreads);
231
232    // Give each of the stages the time buffer they will use.
233    fetch.setTimeBuffer(&timeBuffer);
234    decode.setTimeBuffer(&timeBuffer);
235    rename.setTimeBuffer(&timeBuffer);
236    iew.setTimeBuffer(&timeBuffer);
237    commit.setTimeBuffer(&timeBuffer);
238
239    // Also setup each of the stages' queues.
240    fetch.setFetchQueue(&fetchQueue);
241    decode.setFetchQueue(&fetchQueue);
242    commit.setFetchQueue(&fetchQueue);
243    decode.setDecodeQueue(&decodeQueue);
244    rename.setDecodeQueue(&decodeQueue);
245    rename.setRenameQueue(&renameQueue);
246    iew.setRenameQueue(&renameQueue);
247    iew.setIEWQueue(&iewQueue);
248    commit.setIEWQueue(&iewQueue);
249    commit.setRenameQueue(&renameQueue);
250
251    commit.setIEWStage(&iew);
252    rename.setIEWStage(&iew);
253    rename.setCommitStage(&commit);
254
255#if !FULL_SYSTEM
256    int active_threads = params->workload.size();
257
258    if (active_threads > Impl::MaxThreads) {
259        panic("Workload Size too large. Increase the 'MaxThreads'"
260              "constant in your O3CPU impl. file (e.g. o3/alpha/impl.hh) or "
261              "edit your workload size.");
262    }
263#else
264    int active_threads = 1;
265#endif
266
267    //Make Sure That this a Valid Architeture
268    assert(params->numPhysIntRegs   >= numThreads * TheISA::NumIntRegs);
269    assert(params->numPhysFloatRegs >= numThreads * TheISA::NumFloatRegs);
270
271    rename.setScoreboard(&scoreboard);
272    iew.setScoreboard(&scoreboard);
273
274    // Setup the rename map for whichever stages need it.
275    PhysRegIndex lreg_idx = 0;
276    PhysRegIndex freg_idx = params->numPhysIntRegs; //Index to 1 after int regs
277
278    for (int tid=0; tid < numThreads; tid++) {
279        bool bindRegs = (tid <= active_threads - 1);
280
281        commitRenameMap[tid].init(TheISA::NumIntRegs,
282                                  params->numPhysIntRegs,
283                                  lreg_idx,            //Index for Logical. Regs
284
285                                  TheISA::NumFloatRegs,
286                                  params->numPhysFloatRegs,
287                                  freg_idx,            //Index for Float Regs
288
289                                  TheISA::NumMiscRegs,
290
291                                  TheISA::ZeroReg,
292                                  TheISA::ZeroReg,
293
294                                  tid,
295                                  false);
296
297        renameMap[tid].init(TheISA::NumIntRegs,
298                            params->numPhysIntRegs,
299                            lreg_idx,                  //Index for Logical. Regs
300
301                            TheISA::NumFloatRegs,
302                            params->numPhysFloatRegs,
303                            freg_idx,                  //Index for Float Regs
304
305                            TheISA::NumMiscRegs,
306
307                            TheISA::ZeroReg,
308                            TheISA::ZeroReg,
309
310                            tid,
311                            bindRegs);
312
313        activateThreadEvent[tid].init(tid, this);
314        deallocateContextEvent[tid].init(tid, this);
315    }
316
317    rename.setRenameMap(renameMap);
318    commit.setRenameMap(commitRenameMap);
319
320    // Give renameMap & rename stage access to the freeList;
321    for (int i=0; i < numThreads; i++) {
322        renameMap[i].setFreeList(&freeList);
323    }
324    rename.setFreeList(&freeList);
325
326    // Setup the ROB for whichever stages need it.
327    commit.setROB(&rob);
328
329    lastRunningCycle = curTick;
330
331    lastActivatedCycle = -1;
332
333    // Give renameMap & rename stage access to the freeList;
334    //for (int i=0; i < numThreads; i++) {
335        //globalSeqNum[i] = 1;
336        //}
337
338    contextSwitch = false;
339}
340
341template <class Impl>
342FullO3CPU<Impl>::~FullO3CPU()
343{
344}
345
346template <class Impl>
347void
348FullO3CPU<Impl>::fullCPURegStats()
349{
350    BaseO3CPU::regStats();
351
352    // Register any of the O3CPU's stats here.
353    timesIdled
354        .name(name() + ".timesIdled")
355        .desc("Number of times that the entire CPU went into an idle state and"
356              " unscheduled itself")
357        .prereq(timesIdled);
358
359    idleCycles
360        .name(name() + ".idleCycles")
361        .desc("Total number of cycles that the CPU has spent unscheduled due "
362              "to idling")
363        .prereq(idleCycles);
364
365    // Number of Instructions simulated
366    // --------------------------------
367    // Should probably be in Base CPU but need templated
368    // MaxThreads so put in here instead
369    committedInsts
370        .init(numThreads)
371        .name(name() + ".committedInsts")
372        .desc("Number of Instructions Simulated");
373
374    totalCommittedInsts
375        .name(name() + ".committedInsts_total")
376        .desc("Number of Instructions Simulated");
377
378    cpi
379        .name(name() + ".cpi")
380        .desc("CPI: Cycles Per Instruction")
381        .precision(6);
382    cpi = numCycles / committedInsts;
383
384    totalCpi
385        .name(name() + ".cpi_total")
386        .desc("CPI: Total CPI of All Threads")
387        .precision(6);
388    totalCpi = numCycles / totalCommittedInsts;
389
390    ipc
391        .name(name() + ".ipc")
392        .desc("IPC: Instructions Per Cycle")
393        .precision(6);
394    ipc =  committedInsts / numCycles;
395
396    totalIpc
397        .name(name() + ".ipc_total")
398        .desc("IPC: Total IPC of All Threads")
399        .precision(6);
400    totalIpc =  totalCommittedInsts / numCycles;
401
402}
403
404template <class Impl>
405Port *
406FullO3CPU<Impl>::getPort(const std::string &if_name, int idx)
407{
408    if (if_name == "dcache_port")
409        return iew.getDcachePort();
410    else if (if_name == "icache_port")
411        return fetch.getIcachePort();
412    else
413        panic("No Such Port\n");
414}
415
416template <class Impl>
417void
418FullO3CPU<Impl>::tick()
419{
420    DPRINTF(O3CPU, "\n\nFullO3CPU: Ticking main, FullO3CPU.\n");
421
422    ++numCycles;
423
424//    activity = false;
425
426    //Tick each of the stages
427    fetch.tick();
428
429    decode.tick();
430
431    rename.tick();
432
433    iew.tick();
434
435    commit.tick();
436
437#if !FULL_SYSTEM
438    doContextSwitch();
439#endif
440
441    // Now advance the time buffers
442    timeBuffer.advance();
443
444    fetchQueue.advance();
445    decodeQueue.advance();
446    renameQueue.advance();
447    iewQueue.advance();
448
449    activityRec.advance();
450
451    if (removeInstsThisCycle) {
452        cleanUpRemovedInsts();
453    }
454
455    if (!tickEvent.scheduled()) {
456        if (_status == SwitchedOut ||
457            getState() == SimObject::Drained) {
458            DPRINTF(O3CPU, "Switched out!\n");
459            // increment stat
460            lastRunningCycle = curTick;
461        } else if (!activityRec.active() || _status == Idle) {
462            DPRINTF(O3CPU, "Idle!\n");
463            lastRunningCycle = curTick;
464            timesIdled++;
465        } else {
466            tickEvent.schedule(nextCycle(curTick + ticks(1)));
467            DPRINTF(O3CPU, "Scheduling next tick!\n");
468        }
469    }
470
471#if !FULL_SYSTEM
472    updateThreadPriority();
473#endif
474
475}
476
477template <class Impl>
478void
479FullO3CPU<Impl>::init()
480{
481    if (!deferRegistration) {
482        registerThreadContexts();
483    }
484
485    // Set inSyscall so that the CPU doesn't squash when initially
486    // setting up registers.
487    for (int i = 0; i < number_of_threads; ++i)
488        thread[i]->inSyscall = true;
489
490    for (int tid=0; tid < number_of_threads; tid++) {
491#if FULL_SYSTEM
492        ThreadContext *src_tc = threadContexts[tid];
493#else
494        ThreadContext *src_tc = thread[tid]->getTC();
495#endif
496        // Threads start in the Suspended State
497        if (src_tc->status() != ThreadContext::Suspended) {
498            continue;
499        }
500
501#if FULL_SYSTEM
502        TheISA::initCPU(src_tc, src_tc->readCpuId());
503#endif
504    }
505
506    // Clear inSyscall.
507    for (int i = 0; i < number_of_threads; ++i)
508        thread[i]->inSyscall = false;
509
510    // Initialize stages.
511    fetch.initStage();
512    iew.initStage();
513    rename.initStage();
514    commit.initStage();
515
516    commit.setThreads(thread);
517}
518
519template <class Impl>
520void
521FullO3CPU<Impl>::activateThread(unsigned tid)
522{
523    std::list<unsigned>::iterator isActive =
524        std::find(activeThreads.begin(), activeThreads.end(), tid);
525
526    DPRINTF(O3CPU, "[tid:%i]: Calling activate thread.\n", tid);
527
528    if (isActive == activeThreads.end()) {
529        DPRINTF(O3CPU, "[tid:%i]: Adding to active threads list\n",
530                tid);
531
532        activeThreads.push_back(tid);
533    }
534}
535
536template <class Impl>
537void
538FullO3CPU<Impl>::deactivateThread(unsigned tid)
539{
540    //Remove From Active List, if Active
541    std::list<unsigned>::iterator thread_it =
542        std::find(activeThreads.begin(), activeThreads.end(), tid);
543
544    DPRINTF(O3CPU, "[tid:%i]: Calling deactivate thread.\n", tid);
545
546    if (thread_it != activeThreads.end()) {
547        DPRINTF(O3CPU,"[tid:%i]: Removing from active threads list\n",
548                tid);
549        activeThreads.erase(thread_it);
550    }
551}
552
553template <class Impl>
554void
555FullO3CPU<Impl>::activateContext(int tid, int delay)
556{
557    // Needs to set each stage to running as well.
558    if (delay){
559        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to activate "
560                "on cycle %d\n", tid, curTick + ticks(delay));
561        scheduleActivateThreadEvent(tid, delay);
562    } else {
563        activateThread(tid);
564    }
565
566    if (lastActivatedCycle < curTick) {
567        scheduleTickEvent(delay);
568
569        // Be sure to signal that there's some activity so the CPU doesn't
570        // deschedule itself.
571        activityRec.activity();
572        fetch.wakeFromQuiesce();
573
574        lastActivatedCycle = curTick;
575
576        _status = Running;
577    }
578}
579
580template <class Impl>
581bool
582FullO3CPU<Impl>::deallocateContext(int tid, bool remove, int delay)
583{
584    // Schedule removal of thread data from CPU
585    if (delay){
586        DPRINTF(O3CPU, "[tid:%i]: Scheduling thread context to deallocate "
587                "on cycle %d\n", tid, curTick + ticks(delay));
588        scheduleDeallocateContextEvent(tid, remove, delay);
589        return false;
590    } else {
591        deactivateThread(tid);
592        if (remove)
593            removeThread(tid);
594        return true;
595    }
596}
597
598template <class Impl>
599void
600FullO3CPU<Impl>::suspendContext(int tid)
601{
602    DPRINTF(O3CPU,"[tid: %i]: Suspending Thread Context.\n", tid);
603    bool deallocated = deallocateContext(tid, false, 1);
604    // If this was the last thread then unschedule the tick event.
605    if (activeThreads.size() == 1 && !deallocated ||
606        activeThreads.size() == 0)
607        unscheduleTickEvent();
608    _status = Idle;
609}
610
611template <class Impl>
612void
613FullO3CPU<Impl>::haltContext(int tid)
614{
615    //For now, this is the same as deallocate
616    DPRINTF(O3CPU,"[tid:%i]: Halt Context called. Deallocating", tid);
617    deallocateContext(tid, true, 1);
618}
619
620template <class Impl>
621void
622FullO3CPU<Impl>::insertThread(unsigned tid)
623{
624    DPRINTF(O3CPU,"[tid:%i] Initializing thread into CPU");
625    // Will change now that the PC and thread state is internal to the CPU
626    // and not in the ThreadContext.
627#if FULL_SYSTEM
628    ThreadContext *src_tc = system->threadContexts[tid];
629#else
630    ThreadContext *src_tc = tcBase(tid);
631#endif
632
633    //Bind Int Regs to Rename Map
634    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
635        PhysRegIndex phys_reg = freeList.getIntReg();
636
637        renameMap[tid].setEntry(ireg,phys_reg);
638        scoreboard.setReg(phys_reg);
639    }
640
641    //Bind Float Regs to Rename Map
642    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
643        PhysRegIndex phys_reg = freeList.getFloatReg();
644
645        renameMap[tid].setEntry(freg,phys_reg);
646        scoreboard.setReg(phys_reg);
647    }
648
649    //Copy Thread Data Into RegFile
650    //this->copyFromTC(tid);
651
652    //Set PC/NPC/NNPC
653    setPC(src_tc->readPC(), tid);
654    setNextPC(src_tc->readNextPC(), tid);
655    setNextNPC(src_tc->readNextNPC(), tid);
656
657    src_tc->setStatus(ThreadContext::Active);
658
659    activateContext(tid,1);
660
661    //Reset ROB/IQ/LSQ Entries
662    commit.rob->resetEntries();
663    iew.resetEntries();
664}
665
666template <class Impl>
667void
668FullO3CPU<Impl>::removeThread(unsigned tid)
669{
670    DPRINTF(O3CPU,"[tid:%i] Removing thread context from CPU.\n", tid);
671
672    // Copy Thread Data From RegFile
673    // If thread is suspended, it might be re-allocated
674    //this->copyToTC(tid);
675
676    // Unbind Int Regs from Rename Map
677    for (int ireg = 0; ireg < TheISA::NumIntRegs; ireg++) {
678        PhysRegIndex phys_reg = renameMap[tid].lookup(ireg);
679
680        scoreboard.unsetReg(phys_reg);
681        freeList.addReg(phys_reg);
682    }
683
684    // Unbind Float Regs from Rename Map
685    for (int freg = 0; freg < TheISA::NumFloatRegs; freg++) {
686        PhysRegIndex phys_reg = renameMap[tid].lookup(freg);
687
688        scoreboard.unsetReg(phys_reg);
689        freeList.addReg(phys_reg);
690    }
691
692    // Squash Throughout Pipeline
693    InstSeqNum squash_seq_num = commit.rob->readHeadInst(tid)->seqNum;
694    fetch.squash(0, sizeof(TheISA::MachInst), 0, squash_seq_num, tid);
695    decode.squash(tid);
696    rename.squash(squash_seq_num, tid);
697    iew.squash(tid);
698    commit.rob->squash(squash_seq_num, tid);
699
700    assert(iew.ldstQueue.getCount(tid) == 0);
701
702    // Reset ROB/IQ/LSQ Entries
703
704    // Commented out for now.  This should be possible to do by
705    // telling all the pipeline stages to drain first, and then
706    // checking until the drain completes.  Once the pipeline is
707    // drained, call resetEntries(). - 10-09-06 ktlim
708/*
709    if (activeThreads.size() >= 1) {
710        commit.rob->resetEntries();
711        iew.resetEntries();
712    }
713*/
714}
715
716
717template <class Impl>
718void
719FullO3CPU<Impl>::activateWhenReady(int tid)
720{
721    DPRINTF(O3CPU,"[tid:%i]: Checking if resources are available for incoming"
722            "(e.g. PhysRegs/ROB/IQ/LSQ) \n",
723            tid);
724
725    bool ready = true;
726
727    if (freeList.numFreeIntRegs() >= TheISA::NumIntRegs) {
728        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
729                "Phys. Int. Regs.\n",
730                tid);
731        ready = false;
732    } else if (freeList.numFreeFloatRegs() >= TheISA::NumFloatRegs) {
733        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
734                "Phys. Float. Regs.\n",
735                tid);
736        ready = false;
737    } else if (commit.rob->numFreeEntries() >=
738               commit.rob->entryAmount(activeThreads.size() + 1)) {
739        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
740                "ROB entries.\n",
741                tid);
742        ready = false;
743    } else if (iew.instQueue.numFreeEntries() >=
744               iew.instQueue.entryAmount(activeThreads.size() + 1)) {
745        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
746                "IQ entries.\n",
747                tid);
748        ready = false;
749    } else if (iew.ldstQueue.numFreeEntries() >=
750               iew.ldstQueue.entryAmount(activeThreads.size() + 1)) {
751        DPRINTF(O3CPU,"[tid:%i] Suspending thread due to not enough "
752                "LSQ entries.\n",
753                tid);
754        ready = false;
755    }
756
757    if (ready) {
758        insertThread(tid);
759
760        contextSwitch = false;
761
762        cpuWaitList.remove(tid);
763    } else {
764        suspendContext(tid);
765
766        //blocks fetch
767        contextSwitch = true;
768
769        //@todo: dont always add to waitlist
770        //do waitlist
771        cpuWaitList.push_back(tid);
772    }
773}
774
775#if FULL_SYSTEM
776template <class Impl>
777void
778FullO3CPU<Impl>::updateMemPorts()
779{
780    // Update all ThreadContext's memory ports (Functional/Virtual
781    // Ports)
782    for (int i = 0; i < thread.size(); ++i)
783        thread[i]->connectMemPorts();
784}
785#endif
786
787template <class Impl>
788void
789FullO3CPU<Impl>::serialize(std::ostream &os)
790{
791    SimObject::State so_state = SimObject::getState();
792    SERIALIZE_ENUM(so_state);
793    BaseCPU::serialize(os);
794    nameOut(os, csprintf("%s.tickEvent", name()));
795    tickEvent.serialize(os);
796
797    // Use SimpleThread's ability to checkpoint to make it easier to
798    // write out the registers.  Also make this static so it doesn't
799    // get instantiated multiple times (causes a panic in statistics).
800    static SimpleThread temp;
801
802    for (int i = 0; i < thread.size(); i++) {
803        nameOut(os, csprintf("%s.xc.%i", name(), i));
804        temp.copyTC(thread[i]->getTC());
805        temp.serialize(os);
806    }
807}
808
809template <class Impl>
810void
811FullO3CPU<Impl>::unserialize(Checkpoint *cp, const std::string &section)
812{
813    SimObject::State so_state;
814    UNSERIALIZE_ENUM(so_state);
815    BaseCPU::unserialize(cp, section);
816    tickEvent.unserialize(cp, csprintf("%s.tickEvent", section));
817
818    // Use SimpleThread's ability to checkpoint to make it easier to
819    // read in the registers.  Also make this static so it doesn't
820    // get instantiated multiple times (causes a panic in statistics).
821    static SimpleThread temp;
822
823    for (int i = 0; i < thread.size(); i++) {
824        temp.copyTC(thread[i]->getTC());
825        temp.unserialize(cp, csprintf("%s.xc.%i", section, i));
826        thread[i]->getTC()->copyArchRegs(temp.getTC());
827    }
828}
829
830template <class Impl>
831unsigned int
832FullO3CPU<Impl>::drain(Event *drain_event)
833{
834    DPRINTF(O3CPU, "Switching out\n");
835
836    // If the CPU isn't doing anything, then return immediately.
837    if (_status == Idle || _status == SwitchedOut) {
838        return 0;
839    }
840
841    drainCount = 0;
842    fetch.drain();
843    decode.drain();
844    rename.drain();
845    iew.drain();
846    commit.drain();
847
848    // Wake the CPU and record activity so everything can drain out if
849    // the CPU was not able to immediately drain.
850    if (getState() != SimObject::Drained) {
851        // A bit of a hack...set the drainEvent after all the drain()
852        // calls have been made, that way if all of the stages drain
853        // immediately, the signalDrained() function knows not to call
854        // process on the drain event.
855        drainEvent = drain_event;
856
857        wakeCPU();
858        activityRec.activity();
859
860        return 1;
861    } else {
862        return 0;
863    }
864}
865
866template <class Impl>
867void
868FullO3CPU<Impl>::resume()
869{
870    fetch.resume();
871    decode.resume();
872    rename.resume();
873    iew.resume();
874    commit.resume();
875
876    changeState(SimObject::Running);
877
878    if (_status == SwitchedOut || _status == Idle)
879        return;
880
881#if FULL_SYSTEM
882    assert(system->getMemoryMode() == Enums::timing);
883#endif
884
885    if (!tickEvent.scheduled())
886        tickEvent.schedule(nextCycle());
887    _status = Running;
888}
889
890template <class Impl>
891void
892FullO3CPU<Impl>::signalDrained()
893{
894    if (++drainCount == NumStages) {
895        if (tickEvent.scheduled())
896            tickEvent.squash();
897
898        changeState(SimObject::Drained);
899
900        BaseCPU::switchOut();
901
902        if (drainEvent) {
903            drainEvent->process();
904            drainEvent = NULL;
905        }
906    }
907    assert(drainCount <= 5);
908}
909
910template <class Impl>
911void
912FullO3CPU<Impl>::switchOut()
913{
914    fetch.switchOut();
915    rename.switchOut();
916    iew.switchOut();
917    commit.switchOut();
918    instList.clear();
919    while (!removeList.empty()) {
920        removeList.pop();
921    }
922
923    _status = SwitchedOut;
924#if USE_CHECKER
925    if (checker)
926        checker->switchOut();
927#endif
928    if (tickEvent.scheduled())
929        tickEvent.squash();
930}
931
932template <class Impl>
933void
934FullO3CPU<Impl>::takeOverFrom(BaseCPU *oldCPU)
935{
936    // Flush out any old data from the time buffers.
937    for (int i = 0; i < timeBuffer.getSize(); ++i) {
938        timeBuffer.advance();
939        fetchQueue.advance();
940        decodeQueue.advance();
941        renameQueue.advance();
942        iewQueue.advance();
943    }
944
945    activityRec.reset();
946
947    BaseCPU::takeOverFrom(oldCPU, fetch.getIcachePort(), iew.getDcachePort());
948
949    fetch.takeOverFrom();
950    decode.takeOverFrom();
951    rename.takeOverFrom();
952    iew.takeOverFrom();
953    commit.takeOverFrom();
954
955    assert(!tickEvent.scheduled());
956
957    // @todo: Figure out how to properly select the tid to put onto
958    // the active threads list.
959    int tid = 0;
960
961    std::list<unsigned>::iterator isActive =
962        std::find(activeThreads.begin(), activeThreads.end(), tid);
963
964    if (isActive == activeThreads.end()) {
965        //May Need to Re-code this if the delay variable is the delay
966        //needed for thread to activate
967        DPRINTF(O3CPU, "Adding Thread %i to active threads list\n",
968                tid);
969
970        activeThreads.push_back(tid);
971    }
972
973    // Set all statuses to active, schedule the CPU's tick event.
974    // @todo: Fix up statuses so this is handled properly
975    for (int i = 0; i < threadContexts.size(); ++i) {
976        ThreadContext *tc = threadContexts[i];
977        if (tc->status() == ThreadContext::Active && _status != Running) {
978            _status = Running;
979            tickEvent.schedule(nextCycle());
980        }
981    }
982    if (!tickEvent.scheduled())
983        tickEvent.schedule(nextCycle());
984}
985
986template <class Impl>
987uint64_t
988FullO3CPU<Impl>::readIntReg(int reg_idx)
989{
990    return regFile.readIntReg(reg_idx);
991}
992
993template <class Impl>
994FloatReg
995FullO3CPU<Impl>::readFloatReg(int reg_idx, int width)
996{
997    return regFile.readFloatReg(reg_idx, width);
998}
999
1000template <class Impl>
1001FloatReg
1002FullO3CPU<Impl>::readFloatReg(int reg_idx)
1003{
1004    return regFile.readFloatReg(reg_idx);
1005}
1006
1007template <class Impl>
1008FloatRegBits
1009FullO3CPU<Impl>::readFloatRegBits(int reg_idx, int width)
1010{
1011    return regFile.readFloatRegBits(reg_idx, width);
1012}
1013
1014template <class Impl>
1015FloatRegBits
1016FullO3CPU<Impl>::readFloatRegBits(int reg_idx)
1017{
1018    return regFile.readFloatRegBits(reg_idx);
1019}
1020
1021template <class Impl>
1022void
1023FullO3CPU<Impl>::setIntReg(int reg_idx, uint64_t val)
1024{
1025    regFile.setIntReg(reg_idx, val);
1026}
1027
1028template <class Impl>
1029void
1030FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val, int width)
1031{
1032    regFile.setFloatReg(reg_idx, val, width);
1033}
1034
1035template <class Impl>
1036void
1037FullO3CPU<Impl>::setFloatReg(int reg_idx, FloatReg val)
1038{
1039    regFile.setFloatReg(reg_idx, val);
1040}
1041
1042template <class Impl>
1043void
1044FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val, int width)
1045{
1046    regFile.setFloatRegBits(reg_idx, val, width);
1047}
1048
1049template <class Impl>
1050void
1051FullO3CPU<Impl>::setFloatRegBits(int reg_idx, FloatRegBits val)
1052{
1053    regFile.setFloatRegBits(reg_idx, val);
1054}
1055
1056template <class Impl>
1057uint64_t
1058FullO3CPU<Impl>::readArchIntReg(int reg_idx, unsigned tid)
1059{
1060    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1061
1062    return regFile.readIntReg(phys_reg);
1063}
1064
1065template <class Impl>
1066float
1067FullO3CPU<Impl>::readArchFloatRegSingle(int reg_idx, unsigned tid)
1068{
1069    int idx = reg_idx + TheISA::FP_Base_DepTag;
1070    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1071
1072    return regFile.readFloatReg(phys_reg);
1073}
1074
1075template <class Impl>
1076double
1077FullO3CPU<Impl>::readArchFloatRegDouble(int reg_idx, unsigned tid)
1078{
1079    int idx = reg_idx + TheISA::FP_Base_DepTag;
1080    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1081
1082    return regFile.readFloatReg(phys_reg, 64);
1083}
1084
1085template <class Impl>
1086uint64_t
1087FullO3CPU<Impl>::readArchFloatRegInt(int reg_idx, unsigned tid)
1088{
1089    int idx = reg_idx + TheISA::FP_Base_DepTag;
1090    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1091
1092    return regFile.readFloatRegBits(phys_reg);
1093}
1094
1095template <class Impl>
1096void
1097FullO3CPU<Impl>::setArchIntReg(int reg_idx, uint64_t val, unsigned tid)
1098{
1099    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(reg_idx);
1100
1101    regFile.setIntReg(phys_reg, val);
1102}
1103
1104template <class Impl>
1105void
1106FullO3CPU<Impl>::setArchFloatRegSingle(int reg_idx, float val, unsigned tid)
1107{
1108    int idx = reg_idx + TheISA::FP_Base_DepTag;
1109    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1110
1111    regFile.setFloatReg(phys_reg, val);
1112}
1113
1114template <class Impl>
1115void
1116FullO3CPU<Impl>::setArchFloatRegDouble(int reg_idx, double val, unsigned tid)
1117{
1118    int idx = reg_idx + TheISA::FP_Base_DepTag;
1119    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1120
1121    regFile.setFloatReg(phys_reg, val, 64);
1122}
1123
1124template <class Impl>
1125void
1126FullO3CPU<Impl>::setArchFloatRegInt(int reg_idx, uint64_t val, unsigned tid)
1127{
1128    int idx = reg_idx + TheISA::FP_Base_DepTag;
1129    PhysRegIndex phys_reg = commitRenameMap[tid].lookup(idx);
1130
1131    regFile.setFloatRegBits(phys_reg, val);
1132}
1133
1134template <class Impl>
1135uint64_t
1136FullO3CPU<Impl>::readPC(unsigned tid)
1137{
1138    return commit.readPC(tid);
1139}
1140
1141template <class Impl>
1142void
1143FullO3CPU<Impl>::setPC(Addr new_PC,unsigned tid)
1144{
1145    commit.setPC(new_PC, tid);
1146}
1147
1148template <class Impl>
1149uint64_t
1150FullO3CPU<Impl>::readMicroPC(unsigned tid)
1151{
1152    return commit.readMicroPC(tid);
1153}
1154
1155template <class Impl>
1156void
1157FullO3CPU<Impl>::setMicroPC(Addr new_PC,unsigned tid)
1158{
1159    commit.setMicroPC(new_PC, tid);
1160}
1161
1162template <class Impl>
1163uint64_t
1164FullO3CPU<Impl>::readNextPC(unsigned tid)
1165{
1166    return commit.readNextPC(tid);
1167}
1168
1169template <class Impl>
1170void
1171FullO3CPU<Impl>::setNextPC(uint64_t val,unsigned tid)
1172{
1173    commit.setNextPC(val, tid);
1174}
1175
1176template <class Impl>
1177uint64_t
1178FullO3CPU<Impl>::readNextNPC(unsigned tid)
1179{
1180    return commit.readNextNPC(tid);
1181}
1182
1183template <class Impl>
1184void
1185FullO3CPU<Impl>::setNextNPC(uint64_t val,unsigned tid)
1186{
1187    commit.setNextNPC(val, tid);
1188}
1189
1190template <class Impl>
1191uint64_t
1192FullO3CPU<Impl>::readNextMicroPC(unsigned tid)
1193{
1194    return commit.readNextMicroPC(tid);
1195}
1196
1197template <class Impl>
1198void
1199FullO3CPU<Impl>::setNextMicroPC(Addr new_PC,unsigned tid)
1200{
1201    commit.setNextMicroPC(new_PC, tid);
1202}
1203
1204template <class Impl>
1205typename FullO3CPU<Impl>::ListIt
1206FullO3CPU<Impl>::addInst(DynInstPtr &inst)
1207{
1208    instList.push_back(inst);
1209
1210    return --(instList.end());
1211}
1212
1213template <class Impl>
1214void
1215FullO3CPU<Impl>::instDone(unsigned tid)
1216{
1217    // Keep an instruction count.
1218    thread[tid]->numInst++;
1219    thread[tid]->numInsts++;
1220    committedInsts[tid]++;
1221    totalCommittedInsts++;
1222
1223    // Check for instruction-count-based events.
1224    comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1225}
1226
1227template <class Impl>
1228void
1229FullO3CPU<Impl>::addToRemoveList(DynInstPtr &inst)
1230{
1231    removeInstsThisCycle = true;
1232
1233    removeList.push(inst->getInstListIt());
1234}
1235
1236template <class Impl>
1237void
1238FullO3CPU<Impl>::removeFrontInst(DynInstPtr &inst)
1239{
1240    DPRINTF(O3CPU, "Removing committed instruction [tid:%i] PC %#x "
1241            "[sn:%lli]\n",
1242            inst->threadNumber, inst->readPC(), inst->seqNum);
1243
1244    removeInstsThisCycle = true;
1245
1246    // Remove the front instruction.
1247    removeList.push(inst->getInstListIt());
1248}
1249
1250template <class Impl>
1251void
1252FullO3CPU<Impl>::removeInstsNotInROB(unsigned tid)
1253{
1254    DPRINTF(O3CPU, "Thread %i: Deleting instructions from instruction"
1255            " list.\n", tid);
1256
1257    ListIt end_it;
1258
1259    bool rob_empty = false;
1260
1261    if (instList.empty()) {
1262        return;
1263    } else if (rob.isEmpty(/*tid*/)) {
1264        DPRINTF(O3CPU, "ROB is empty, squashing all insts.\n");
1265        end_it = instList.begin();
1266        rob_empty = true;
1267    } else {
1268        end_it = (rob.readTailInst(tid))->getInstListIt();
1269        DPRINTF(O3CPU, "ROB is not empty, squashing insts not in ROB.\n");
1270    }
1271
1272    removeInstsThisCycle = true;
1273
1274    ListIt inst_it = instList.end();
1275
1276    inst_it--;
1277
1278    // Walk through the instruction list, removing any instructions
1279    // that were inserted after the given instruction iterator, end_it.
1280    while (inst_it != end_it) {
1281        assert(!instList.empty());
1282
1283        squashInstIt(inst_it, tid);
1284
1285        inst_it--;
1286    }
1287
1288    // If the ROB was empty, then we actually need to remove the first
1289    // instruction as well.
1290    if (rob_empty) {
1291        squashInstIt(inst_it, tid);
1292    }
1293}
1294
1295template <class Impl>
1296void
1297FullO3CPU<Impl>::removeInstsUntil(const InstSeqNum &seq_num,
1298                                  unsigned tid)
1299{
1300    assert(!instList.empty());
1301
1302    removeInstsThisCycle = true;
1303
1304    ListIt inst_iter = instList.end();
1305
1306    inst_iter--;
1307
1308    DPRINTF(O3CPU, "Deleting instructions from instruction "
1309            "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1310            tid, seq_num, (*inst_iter)->seqNum);
1311
1312    while ((*inst_iter)->seqNum > seq_num) {
1313
1314        bool break_loop = (inst_iter == instList.begin());
1315
1316        squashInstIt(inst_iter, tid);
1317
1318        inst_iter--;
1319
1320        if (break_loop)
1321            break;
1322    }
1323}
1324
1325template <class Impl>
1326inline void
1327FullO3CPU<Impl>::squashInstIt(const ListIt &instIt, const unsigned &tid)
1328{
1329    if ((*instIt)->threadNumber == tid) {
1330        DPRINTF(O3CPU, "Squashing instruction, "
1331                "[tid:%i] [sn:%lli] PC %#x\n",
1332                (*instIt)->threadNumber,
1333                (*instIt)->seqNum,
1334                (*instIt)->readPC());
1335
1336        // Mark it as squashed.
1337        (*instIt)->setSquashed();
1338
1339        // @todo: Formulate a consistent method for deleting
1340        // instructions from the instruction list
1341        // Remove the instruction from the list.
1342        removeList.push(instIt);
1343    }
1344}
1345
1346template <class Impl>
1347void
1348FullO3CPU<Impl>::cleanUpRemovedInsts()
1349{
1350    while (!removeList.empty()) {
1351        DPRINTF(O3CPU, "Removing instruction, "
1352                "[tid:%i] [sn:%lli] PC %#x\n",
1353                (*removeList.front())->threadNumber,
1354                (*removeList.front())->seqNum,
1355                (*removeList.front())->readPC());
1356
1357        instList.erase(removeList.front());
1358
1359        removeList.pop();
1360    }
1361
1362    removeInstsThisCycle = false;
1363}
1364/*
1365template <class Impl>
1366void
1367FullO3CPU<Impl>::removeAllInsts()
1368{
1369    instList.clear();
1370}
1371*/
1372template <class Impl>
1373void
1374FullO3CPU<Impl>::dumpInsts()
1375{
1376    int num = 0;
1377
1378    ListIt inst_list_it = instList.begin();
1379
1380    cprintf("Dumping Instruction List\n");
1381
1382    while (inst_list_it != instList.end()) {
1383        cprintf("Instruction:%i\nPC:%#x\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1384                "Squashed:%i\n\n",
1385                num, (*inst_list_it)->readPC(), (*inst_list_it)->threadNumber,
1386                (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1387                (*inst_list_it)->isSquashed());
1388        inst_list_it++;
1389        ++num;
1390    }
1391}
1392/*
1393template <class Impl>
1394void
1395FullO3CPU<Impl>::wakeDependents(DynInstPtr &inst)
1396{
1397    iew.wakeDependents(inst);
1398}
1399*/
1400template <class Impl>
1401void
1402FullO3CPU<Impl>::wakeCPU()
1403{
1404    if (activityRec.active() || tickEvent.scheduled()) {
1405        DPRINTF(Activity, "CPU already running.\n");
1406        return;
1407    }
1408
1409    DPRINTF(Activity, "Waking up CPU\n");
1410
1411    idleCycles += tickToCycles((curTick - 1) - lastRunningCycle);
1412    numCycles += tickToCycles((curTick - 1) - lastRunningCycle);
1413
1414    tickEvent.schedule(nextCycle());
1415}
1416
1417template <class Impl>
1418int
1419FullO3CPU<Impl>::getFreeTid()
1420{
1421    for (int i=0; i < numThreads; i++) {
1422        if (!tids[i]) {
1423            tids[i] = true;
1424            return i;
1425        }
1426    }
1427
1428    return -1;
1429}
1430
1431template <class Impl>
1432void
1433FullO3CPU<Impl>::doContextSwitch()
1434{
1435    if (contextSwitch) {
1436
1437        //ADD CODE TO DEACTIVE THREAD HERE (???)
1438
1439        for (int tid=0; tid < cpuWaitList.size(); tid++) {
1440            activateWhenReady(tid);
1441        }
1442
1443        if (cpuWaitList.size() == 0)
1444            contextSwitch = true;
1445    }
1446}
1447
1448template <class Impl>
1449void
1450FullO3CPU<Impl>::updateThreadPriority()
1451{
1452    if (activeThreads.size() > 1)
1453    {
1454        //DEFAULT TO ROUND ROBIN SCHEME
1455        //e.g. Move highest priority to end of thread list
1456        std::list<unsigned>::iterator list_begin = activeThreads.begin();
1457        std::list<unsigned>::iterator list_end   = activeThreads.end();
1458
1459        unsigned high_thread = *list_begin;
1460
1461        activeThreads.erase(list_begin);
1462
1463        activeThreads.push_back(high_thread);
1464    }
1465}
1466
1467// Forward declaration of FullO3CPU.
1468template class FullO3CPU<O3CPUImpl>;
1469