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