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