2 * Copyright (c) 2007 MIPS Technologies, Inc.
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.
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.
28 * Authors: Korey Sewell
34 #include "arch/utility.hh"
35 #include "config/full_system.hh"
36 #include "config/the_isa.hh"
37 #include "cpu/activity.hh"
38 #include "cpu/base.hh"
39 #include "cpu/exetrace.hh"
40 #include "cpu/inorder/cpu.hh"
41 #include "cpu/inorder/first_stage.hh"
42 #include "cpu/inorder/inorder_dyn_inst.hh"
43 #include "cpu/inorder/pipeline_traits.hh"
44 #include "cpu/inorder/resource_pool.hh"
45 #include "cpu/inorder/resources/resource_list.hh"
46 #include "cpu/inorder/thread_context.hh"
47 #include "cpu/inorder/thread_state.hh"
48 #include "cpu/simple_thread.hh"
49 #include "cpu/thread_context.hh"
50 #include "mem/translating_port.hh"
51 #include "params/InOrderCPU.hh"
52 #include "sim/process.hh"
53 #include "sim/stat_control.hh"
56 #include "cpu/quiesce_event.hh"
57 #include "sim/system.hh"
60 #if THE_ISA == ALPHA_ISA
61 #include "arch/alpha/osfpal.hh"
65 using namespace TheISA
;
66 using namespace ThePipeline
;
68 InOrderCPU::TickEvent::TickEvent(InOrderCPU
*c
)
69 : Event(CPU_Tick_Pri
), cpu(c
)
74 InOrderCPU::TickEvent::process()
81 InOrderCPU::TickEvent::description()
83 return "InOrderCPU tick event";
86 InOrderCPU::CPUEvent::CPUEvent(InOrderCPU
*_cpu
, CPUEventType e_type
,
87 Fault fault
, ThreadID _tid
, DynInstPtr inst
,
88 unsigned event_pri_offset
)
89 : Event(Event::Priority((unsigned int)CPU_Tick_Pri
+ event_pri_offset
)),
92 setEvent(e_type
, fault
, _tid
, inst
);
96 std::string
InOrderCPU::eventNames
[NumCPUEvents
] =
99 "ActivateNextReadyThread",
105 "SquashFromMemStall",
110 InOrderCPU::CPUEvent::process()
112 switch (cpuEventType
)
115 cpu
->activateThread(tid
);
118 case ActivateNextReadyThread
:
119 cpu
->activateNextReadyThread();
122 case DeactivateThread
:
123 cpu
->deactivateThread(tid
);
127 cpu
->haltThread(tid
);
131 cpu
->suspendThread(tid
);
134 case SquashFromMemStall
:
135 cpu
->squashDueToMemStall(inst
->squashingStage
, inst
->seqNum
, tid
);
139 cpu
->trapCPU(fault
, tid
, inst
);
143 fatal("Unrecognized Event Type %s", eventNames
[cpuEventType
]);
146 cpu
->cpuEventRemoveList
.push(this);
152 InOrderCPU::CPUEvent::description()
154 return "InOrderCPU event";
158 InOrderCPU::CPUEvent::scheduleEvent(int delay
)
160 assert(!scheduled() || squashed());
161 cpu
->reschedule(this, cpu
->nextCycle(curTick() + cpu
->ticks(delay
)), true);
165 InOrderCPU::CPUEvent::unscheduleEvent()
171 InOrderCPU::InOrderCPU(Params
*params
)
173 cpu_id(params
->cpu_id
),
177 stageWidth(params
->stageWidth
),
179 removeInstsThisCycle(false),
180 activityRec(params
->name
, NumStages
, 10, params
->activity
),
182 system(params
->system
),
183 physmem(system
->physmem
),
184 #endif // FULL_SYSTEM
190 deferRegistration(false/*params->deferRegistration*/),
191 stageTracing(params
->stageTracing
),
194 ThreadID active_threads
;
197 resPool
= new ResourcePool(this, params
);
199 // Resize for Multithreading CPUs
200 thread
.resize(numThreads
);
205 active_threads
= params
->workload
.size();
207 if (active_threads
> MaxThreads
) {
208 panic("Workload Size too large. Increase the 'MaxThreads'"
209 "in your InOrder implementation or "
210 "edit your workload size.");
214 if (active_threads
> 1) {
215 threadModel
= (InOrderCPU::ThreadModel
) params
->threadModel
;
217 if (threadModel
== SMT
) {
218 DPRINTF(InOrderCPU
, "Setting Thread Model to SMT.\n");
219 } else if (threadModel
== SwitchOnCacheMiss
) {
220 DPRINTF(InOrderCPU
, "Setting Thread Model to "
221 "Switch On Cache Miss\n");
225 threadModel
= Single
;
232 // Bind the fetch & data ports from the resource pool.
233 fetchPortIdx
= resPool
->getPortIdx(params
->fetchMemPort
);
234 if (fetchPortIdx
== 0) {
235 fatal("Unable to find port to fetch instructions from.\n");
238 dataPortIdx
= resPool
->getPortIdx(params
->dataMemPort
);
239 if (dataPortIdx
== 0) {
240 fatal("Unable to find port for data.\n");
243 for (ThreadID tid
= 0; tid
< numThreads
; ++tid
) {
245 // SMT is not supported in FS mode yet.
246 assert(numThreads
== 1);
247 thread
[tid
] = new Thread(this, 0);
249 if (tid
< (ThreadID
)params
->workload
.size()) {
250 DPRINTF(InOrderCPU
, "Workload[%i] process is %#x\n",
251 tid
, params
->workload
[tid
]->prog_fname
);
253 new Thread(this, tid
, params
->workload
[tid
]);
255 //Allocate Empty thread so M5 can use later
256 //when scheduling threads to CPU
257 Process
* dummy_proc
= params
->workload
[0];
258 thread
[tid
] = new Thread(this, tid
, dummy_proc
);
261 // Eventually set this with parameters...
265 // Setup the TC that will serve as the interface to the threads/CPU.
266 InOrderThreadContext
*tc
= new InOrderThreadContext
;
268 tc
->thread
= thread
[tid
];
270 // Give the thread the TC.
271 thread
[tid
]->tc
= tc
;
272 thread
[tid
]->setFuncExeInst(0);
273 globalSeqNum
[tid
] = 1;
275 // Add the TC to the CPU's list of TC's.
276 this->threadContexts
.push_back(tc
);
279 // Initialize TimeBuffer Stage Queues
280 for (int stNum
=0; stNum
< NumStages
- 1; stNum
++) {
281 stageQueue
[stNum
] = new StageQueue(NumStages
, NumStages
);
282 stageQueue
[stNum
]->id(stNum
);
286 // Set Up Pipeline Stages
287 for (int stNum
=0; stNum
< NumStages
; stNum
++) {
289 pipelineStage
[stNum
] = new FirstStage(params
, stNum
);
291 pipelineStage
[stNum
] = new PipelineStage(params
, stNum
);
293 pipelineStage
[stNum
]->setCPU(this);
294 pipelineStage
[stNum
]->setActiveThreads(&activeThreads
);
295 pipelineStage
[stNum
]->setTimeBuffer(&timeBuffer
);
297 // Take Care of 1st/Nth stages
299 pipelineStage
[stNum
]->setPrevStageQueue(stageQueue
[stNum
- 1]);
300 if (stNum
< NumStages
- 1)
301 pipelineStage
[stNum
]->setNextStageQueue(stageQueue
[stNum
]);
304 // Initialize thread specific variables
305 for (ThreadID tid
= 0; tid
< numThreads
; tid
++) {
306 archRegDepMap
[tid
].setCPU(this);
308 nonSpecInstActive
[tid
] = false;
309 nonSpecSeqNum
[tid
] = 0;
311 squashSeqNum
[tid
] = MaxAddr
;
312 lastSquashCycle
[tid
] = 0;
314 memset(intRegs
[tid
], 0, sizeof(intRegs
[tid
]));
315 memset(floatRegs
.i
[tid
], 0, sizeof(floatRegs
.i
[tid
]));
318 isa
[tid
].expandForMultithreading(numThreads
, 1/*numVirtProcs*/);
320 // Define dummy instructions and resource requests to be used.
321 dummyInst
[tid
] = new InOrderDynInst(this,
327 dummyReq
[tid
] = new ResourceRequest(resPool
->getResource(0),
335 dummyReqInst
= new InOrderDynInst(this, NULL
, 0, 0, 0);
336 dummyReqInst
->setSquashed();
337 dummyReqInst
->resetInstCount();
339 dummyBufferInst
= new InOrderDynInst(this, NULL
, 0, 0, 0);
340 dummyBufferInst
->setSquashed();
341 dummyBufferInst
->resetInstCount();
343 endOfSkedIt
= skedCache
.end();
344 frontEndSked
= createFrontEndSked();
346 lastRunningCycle
= curTick();
348 // Reset CPU to reset state.
350 Fault resetFault
= new ResetFault();
351 resetFault
->invoke(tcBase());
357 // Schedule First Tick Event, CPU will reschedule itself from here on out.
358 scheduleTickEvent(0);
361 InOrderCPU::~InOrderCPU()
366 std::map
<InOrderCPU::SkedID
, ThePipeline::RSkedPtr
> InOrderCPU::skedCache
;
369 InOrderCPU::createFrontEndSked()
371 RSkedPtr res_sked
= new ResourceSked();
373 StageScheduler
F(res_sked
, stage_num
++);
374 StageScheduler
D(res_sked
, stage_num
++);
377 F
.needs(FetchSeq
, FetchSeqUnit::AssignNextPC
);
378 F
.needs(ICache
, FetchUnit::InitiateFetch
);
381 D
.needs(ICache
, FetchUnit::CompleteFetch
);
382 D
.needs(Decode
, DecodeUnit::DecodeInst
);
383 D
.needs(BPred
, BranchPredictor::PredictBranch
);
384 D
.needs(FetchSeq
, FetchSeqUnit::UpdateTargetPC
);
387 DPRINTF(SkedCache
, "Resource Sked created for instruction \"front_end\"\n");
393 InOrderCPU::createBackEndSked(DynInstPtr inst
)
395 RSkedPtr res_sked
= lookupSked(inst
);
396 if (res_sked
!= NULL
) {
397 DPRINTF(SkedCache
, "Found %s in sked cache.\n",
401 res_sked
= new ResourceSked();
404 int stage_num
= ThePipeline::BackEndStartStage
;
405 StageScheduler
X(res_sked
, stage_num
++);
406 StageScheduler
M(res_sked
, stage_num
++);
407 StageScheduler
W(res_sked
, stage_num
++);
409 if (!inst
->staticInst
) {
410 warn_once("Static Instruction Object Not Set. Can't Create"
411 " Back End Schedule");
416 for (int idx
=0; idx
< inst
->numSrcRegs(); idx
++) {
417 if (!idx
|| !inst
->isStore()) {
418 X
.needs(RegManager
, UseDefUnit::ReadSrcReg
, idx
);
422 if ( inst
->isNonSpeculative() ) {
423 // skip execution of non speculative insts until later
424 } else if ( inst
->isMemRef() ) {
425 if ( inst
->isLoad() ) {
426 X
.needs(AGEN
, AGENUnit::GenerateAddr
);
428 } else if (inst
->opClass() == IntMultOp
|| inst
->opClass() == IntDivOp
) {
429 X
.needs(MDU
, MultDivUnit::StartMultDiv
);
431 X
.needs(ExecUnit
, ExecutionUnit::ExecuteInst
);
434 if (inst
->opClass() == IntMultOp
|| inst
->opClass() == IntDivOp
) {
435 X
.needs(MDU
, MultDivUnit::EndMultDiv
);
439 if ( inst
->isLoad() ) {
440 M
.needs(DCache
, CacheUnit::InitiateReadData
);
441 } else if ( inst
->isStore() ) {
442 if ( inst
->numSrcRegs() >= 2 ) {
443 M
.needs(RegManager
, UseDefUnit::ReadSrcReg
, 1);
445 M
.needs(AGEN
, AGENUnit::GenerateAddr
);
446 M
.needs(DCache
, CacheUnit::InitiateWriteData
);
451 if ( inst
->isLoad() ) {
452 W
.needs(DCache
, CacheUnit::CompleteReadData
);
453 } else if ( inst
->isStore() ) {
454 W
.needs(DCache
, CacheUnit::CompleteWriteData
);
457 if ( inst
->isNonSpeculative() ) {
458 if ( inst
->isMemRef() ) fatal("Non-Speculative Memory Instruction");
459 W
.needs(ExecUnit
, ExecutionUnit::ExecuteInst
);
462 for (int idx
=0; idx
< inst
->numDestRegs(); idx
++) {
463 W
.needs(RegManager
, UseDefUnit::WriteDestReg
, idx
);
466 W
.needs(Grad
, GraduationUnit::GraduateInst
);
468 // Insert Front Schedule into our cache of
469 // resource schedules
470 addToSkedCache(inst
, res_sked
);
472 DPRINTF(SkedCache
, "Back End Sked Created for instruction: %s (%08p)\n",
473 inst
->instName(), inst
->getMachInst());
480 InOrderCPU::regStats()
482 /* Register the Resource Pool's stats here.*/
485 /* Register for each Pipeline Stage */
486 for (int stage_num
=0; stage_num
< ThePipeline::NumStages
; stage_num
++) {
487 pipelineStage
[stage_num
]->regStats();
490 /* Register any of the InOrderCPU's stats here.*/
492 .name(name() + ".instsPerContextSwitch")
493 .desc("Instructions Committed Per Context Switch")
494 .prereq(instsPerCtxtSwitch
);
497 .name(name() + ".contextSwitches")
498 .desc("Number of context switches");
501 .name(name() + ".comLoads")
502 .desc("Number of Load instructions committed");
505 .name(name() + ".comStores")
506 .desc("Number of Store instructions committed");
509 .name(name() + ".comBranches")
510 .desc("Number of Branches instructions committed");
513 .name(name() + ".comNops")
514 .desc("Number of Nop instructions committed");
517 .name(name() + ".comNonSpec")
518 .desc("Number of Non-Speculative instructions committed");
521 .name(name() + ".comInts")
522 .desc("Number of Integer instructions committed");
525 .name(name() + ".comFloats")
526 .desc("Number of Floating Point instructions committed");
529 .name(name() + ".timesIdled")
530 .desc("Number of times that the entire CPU went into an idle state and"
531 " unscheduled itself")
535 .name(name() + ".idleCycles")
536 .desc("Number of cycles cpu's stages were not processed");
539 .name(name() + ".runCycles")
540 .desc("Number of cycles cpu stages are processed.");
543 .name(name() + ".activity")
544 .desc("Percentage of cycles cpu is active")
546 activity
= (runCycles
/ numCycles
) * 100;
550 .name(name() + ".threadCycles")
551 .desc("Total Number of Cycles A Thread Was Active in CPU (Per-Thread)");
554 .name(name() + ".smtCycles")
555 .desc("Total number of cycles that the CPU was in SMT-mode");
559 .name(name() + ".committedInsts")
560 .desc("Number of Instructions Simulated (Per-Thread)");
564 .name(name() + ".smtCommittedInsts")
565 .desc("Number of SMT Instructions Simulated (Per-Thread)");
568 .name(name() + ".committedInsts_total")
569 .desc("Number of Instructions Simulated (Total)");
572 .name(name() + ".cpi")
573 .desc("CPI: Cycles Per Instruction (Per-Thread)")
575 cpi
= numCycles
/ committedInsts
;
578 .name(name() + ".smt_cpi")
579 .desc("CPI: Total SMT-CPI")
581 smtCpi
= smtCycles
/ smtCommittedInsts
;
584 .name(name() + ".cpi_total")
585 .desc("CPI: Total CPI of All Threads")
587 totalCpi
= numCycles
/ totalCommittedInsts
;
590 .name(name() + ".ipc")
591 .desc("IPC: Instructions Per Cycle (Per-Thread)")
593 ipc
= committedInsts
/ numCycles
;
596 .name(name() + ".smt_ipc")
597 .desc("IPC: Total SMT-IPC")
599 smtIpc
= smtCommittedInsts
/ smtCycles
;
602 .name(name() + ".ipc_total")
603 .desc("IPC: Total IPC of All Threads")
605 totalIpc
= totalCommittedInsts
/ numCycles
;
614 DPRINTF(InOrderCPU
, "\n\nInOrderCPU: Ticking main, InOrderCPU.\n");
618 bool pipes_idle
= true;
620 //Tick each of the stages
621 for (int stNum
=NumStages
- 1; stNum
>= 0 ; stNum
--) {
622 pipelineStage
[stNum
]->tick();
624 pipes_idle
= pipes_idle
&& pipelineStage
[stNum
]->idle
;
632 // Now advance the time buffers one tick
633 timeBuffer
.advance();
634 for (int sqNum
=0; sqNum
< NumStages
- 1; sqNum
++) {
635 stageQueue
[sqNum
]->advance();
637 activityRec
.advance();
639 // Any squashed events, or insts then remove them now
640 cleanUpRemovedEvents();
641 cleanUpRemovedInsts();
643 // Re-schedule CPU for this cycle
644 if (!tickEvent
.scheduled()) {
645 if (_status
== SwitchedOut
) {
647 lastRunningCycle
= curTick();
648 } else if (!activityRec
.active()) {
649 DPRINTF(InOrderCPU
, "sleeping CPU.\n");
650 lastRunningCycle
= curTick();
653 //Tick next_tick = curTick() + cycles(1);
654 //tickEvent.schedule(next_tick);
655 schedule(&tickEvent
, nextCycle(curTick() + 1));
656 DPRINTF(InOrderCPU
, "Scheduled CPU for next tick @ %i.\n",
657 nextCycle(curTick() + 1));
662 updateThreadPriority();
669 if (!deferRegistration
) {
670 registerThreadContexts();
673 // Set inSyscall so that the CPU doesn't squash when initially
674 // setting up registers.
675 for (ThreadID tid
= 0; tid
< numThreads
; ++tid
)
676 thread
[tid
]->inSyscall
= true;
679 for (ThreadID tid
= 0; tid
< numThreads
; tid
++) {
680 ThreadContext
*src_tc
= threadContexts
[tid
];
681 TheISA::initCPU(src_tc
, src_tc
->contextId());
686 for (ThreadID tid
= 0; tid
< numThreads
; ++tid
)
687 thread
[tid
]->inSyscall
= false;
689 // Call Initializiation Routine for Resource Pool
696 for (int i
= 0; i
< numThreads
; i
++) {
697 isa
[i
].reset(coreType
, numThreads
,
698 1/*numVirtProcs*/, dynamic_cast<BaseCPU
*>(this));
703 InOrderCPU::getPort(const std::string
&if_name
, int idx
)
705 return resPool
->getPort(if_name
, idx
);
710 InOrderCPU::hwrei(ThreadID tid
)
712 panic("hwrei: Unimplemented");
719 InOrderCPU::simPalCheck(int palFunc
, ThreadID tid
)
721 panic("simPalCheck: Unimplemented");
728 InOrderCPU::getInterrupts()
730 // Check if there are any outstanding interrupts
731 return interrupts
->getInterrupt(threadContexts
[0]);
736 InOrderCPU::processInterrupts(Fault interrupt
)
738 // Check for interrupts here. For now can copy the code that
739 // exists within isa_fullsys_traits.hh. Also assume that thread 0
740 // is the one that handles the interrupts.
741 // @todo: Possibly consolidate the interrupt checking code.
742 // @todo: Allow other threads to handle interrupts.
744 assert(interrupt
!= NoFault
);
745 interrupts
->updateIntrInfo(threadContexts
[0]);
747 DPRINTF(InOrderCPU
, "Interrupt %s being handled\n", interrupt
->name());
749 // Note: Context ID ok here? Impl. of FS mode needs to revisit this
750 trap(interrupt
, threadContexts
[0]->contextId(), dummyBufferInst
);
755 InOrderCPU::updateMemPorts()
757 // Update all ThreadContext's memory ports (Functional/Virtual
759 ThreadID size
= thread
.size();
760 for (ThreadID i
= 0; i
< size
; ++i
)
761 thread
[i
]->connectMemPorts(thread
[i
]->getTC());
766 InOrderCPU::trap(Fault fault
, ThreadID tid
, DynInstPtr inst
, int delay
)
768 //@ Squash Pipeline during TRAP
769 scheduleCpuEvent(Trap
, fault
, tid
, inst
, delay
);
773 InOrderCPU::trapCPU(Fault fault
, ThreadID tid
, DynInstPtr inst
)
775 fault
->invoke(tcBase(tid
), inst
->staticInst
);
779 InOrderCPU::squashFromMemStall(DynInstPtr inst
, ThreadID tid
, int delay
)
781 scheduleCpuEvent(SquashFromMemStall
, NoFault
, tid
, inst
, delay
);
786 InOrderCPU::squashDueToMemStall(int stage_num
, InstSeqNum seq_num
,
789 DPRINTF(InOrderCPU
, "Squashing Pipeline Stages Due to Memory Stall...\n");
791 // Squash all instructions in each stage including
792 // instruction that caused the squash (seq_num - 1)
793 // NOTE: The stage bandwidth needs to be cleared so thats why
794 // the stalling instruction is squashed as well. The stalled
795 // instruction is previously placed in another intermediate buffer
796 // while it's stall is being handled.
797 InstSeqNum squash_seq_num
= seq_num
- 1;
799 for (int stNum
=stage_num
; stNum
>= 0 ; stNum
--) {
800 pipelineStage
[stNum
]->squashDueToMemStall(squash_seq_num
, tid
);
805 InOrderCPU::scheduleCpuEvent(CPUEventType c_event
, Fault fault
,
806 ThreadID tid
, DynInstPtr inst
,
807 unsigned delay
, unsigned event_pri_offset
)
809 CPUEvent
*cpu_event
= new CPUEvent(this, c_event
, fault
, tid
, inst
,
812 Tick sked_tick
= nextCycle(curTick() + ticks(delay
));
814 DPRINTF(InOrderCPU
, "Scheduling CPU Event (%s) for cycle %i, [tid:%i].\n",
815 eventNames
[c_event
], curTick() + delay
, tid
);
816 schedule(cpu_event
, sked_tick
);
818 cpu_event
->process();
819 cpuEventRemoveList
.push(cpu_event
);
822 // Broadcast event to the Resource Pool
823 // Need to reset tid just in case this is a dummy instruction
825 resPool
->scheduleEvent(c_event
, inst
, 0, 0, tid
);
829 InOrderCPU::isThreadActive(ThreadID tid
)
831 list
<ThreadID
>::iterator isActive
=
832 std::find(activeThreads
.begin(), activeThreads
.end(), tid
);
834 return (isActive
!= activeThreads
.end());
838 InOrderCPU::isThreadReady(ThreadID tid
)
840 list
<ThreadID
>::iterator isReady
=
841 std::find(readyThreads
.begin(), readyThreads
.end(), tid
);
843 return (isReady
!= readyThreads
.end());
847 InOrderCPU::isThreadSuspended(ThreadID tid
)
849 list
<ThreadID
>::iterator isSuspended
=
850 std::find(suspendedThreads
.begin(), suspendedThreads
.end(), tid
);
852 return (isSuspended
!= suspendedThreads
.end());
856 InOrderCPU::activateNextReadyThread()
858 if (readyThreads
.size() >= 1) {
859 ThreadID ready_tid
= readyThreads
.front();
861 // Activate in Pipeline
862 activateThread(ready_tid
);
864 // Activate in Resource Pool
865 resPool
->activateAll(ready_tid
);
867 list
<ThreadID
>::iterator ready_it
=
868 std::find(readyThreads
.begin(), readyThreads
.end(), ready_tid
);
869 readyThreads
.erase(ready_it
);
872 "Attempting to activate new thread, but No Ready Threads to"
875 "Unable to switch to next active thread.\n");
880 InOrderCPU::activateThread(ThreadID tid
)
882 if (isThreadSuspended(tid
)) {
884 "Removing [tid:%i] from suspended threads list.\n", tid
);
886 list
<ThreadID
>::iterator susp_it
=
887 std::find(suspendedThreads
.begin(), suspendedThreads
.end(),
889 suspendedThreads
.erase(susp_it
);
892 if (threadModel
== SwitchOnCacheMiss
&&
893 numActiveThreads() == 1) {
895 "Ignoring activation of [tid:%i], since [tid:%i] is "
896 "already running.\n", tid
, activeThreadId());
898 DPRINTF(InOrderCPU
,"Placing [tid:%i] on ready threads list\n",
901 readyThreads
.push_back(tid
);
903 } else if (!isThreadActive(tid
)) {
905 "Adding [tid:%i] to active threads list.\n", tid
);
906 activeThreads
.push_back(tid
);
908 activateThreadInPipeline(tid
);
910 thread
[tid
]->lastActivate
= curTick();
912 tcBase(tid
)->setStatus(ThreadContext::Active
);
921 InOrderCPU::activateThreadInPipeline(ThreadID tid
)
923 for (int stNum
=0; stNum
< NumStages
; stNum
++) {
924 pipelineStage
[stNum
]->activateThread(tid
);
929 InOrderCPU::deactivateContext(ThreadID tid
, int delay
)
931 DPRINTF(InOrderCPU
,"[tid:%i]: Deactivating ...\n", tid
);
933 scheduleCpuEvent(DeactivateThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
935 // Be sure to signal that there's some activity so the CPU doesn't
936 // deschedule itself.
937 activityRec
.activity();
943 InOrderCPU::deactivateThread(ThreadID tid
)
945 DPRINTF(InOrderCPU
, "[tid:%i]: Calling deactivate thread.\n", tid
);
947 if (isThreadActive(tid
)) {
948 DPRINTF(InOrderCPU
,"[tid:%i]: Removing from active threads list\n",
950 list
<ThreadID
>::iterator thread_it
=
951 std::find(activeThreads
.begin(), activeThreads
.end(), tid
);
953 removePipelineStalls(*thread_it
);
955 activeThreads
.erase(thread_it
);
957 // Ideally, this should be triggered from the
958 // suspendContext/Thread functions
959 tcBase(tid
)->setStatus(ThreadContext::Suspended
);
962 assert(!isThreadActive(tid
));
966 InOrderCPU::removePipelineStalls(ThreadID tid
)
968 DPRINTF(InOrderCPU
,"[tid:%i]: Removing all pipeline stalls\n",
971 for (int stNum
= 0; stNum
< NumStages
; stNum
++) {
972 pipelineStage
[stNum
]->removeStalls(tid
);
978 InOrderCPU::updateThreadPriority()
980 if (activeThreads
.size() > 1)
982 //DEFAULT TO ROUND ROBIN SCHEME
983 //e.g. Move highest priority to end of thread list
984 list
<ThreadID
>::iterator list_begin
= activeThreads
.begin();
985 list
<ThreadID
>::iterator list_end
= activeThreads
.end();
987 unsigned high_thread
= *list_begin
;
989 activeThreads
.erase(list_begin
);
991 activeThreads
.push_back(high_thread
);
996 InOrderCPU::tickThreadStats()
998 /** Keep track of cycles that each thread is active */
999 list
<ThreadID
>::iterator thread_it
= activeThreads
.begin();
1000 while (thread_it
!= activeThreads
.end()) {
1001 threadCycles
[*thread_it
]++;
1005 // Keep track of cycles where SMT is active
1006 if (activeThreads
.size() > 1) {
1012 InOrderCPU::activateContext(ThreadID tid
, int delay
)
1014 DPRINTF(InOrderCPU
,"[tid:%i]: Activating ...\n", tid
);
1017 scheduleCpuEvent(ActivateThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1019 // Be sure to signal that there's some activity so the CPU doesn't
1020 // deschedule itself.
1021 activityRec
.activity();
1027 InOrderCPU::activateNextReadyContext(int delay
)
1029 DPRINTF(InOrderCPU
,"Activating next ready thread\n");
1031 // NOTE: Add 5 to the event priority so that we always activate
1032 // threads after we've finished deactivating, squashing,etc.
1034 scheduleCpuEvent(ActivateNextReadyThread
, NoFault
, 0/*tid*/, dummyInst
[0],
1037 // Be sure to signal that there's some activity so the CPU doesn't
1038 // deschedule itself.
1039 activityRec
.activity();
1045 InOrderCPU::haltContext(ThreadID tid
, int delay
)
1047 DPRINTF(InOrderCPU
, "[tid:%i]: Calling Halt Context...\n", tid
);
1049 scheduleCpuEvent(HaltThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1051 activityRec
.activity();
1055 InOrderCPU::haltThread(ThreadID tid
)
1057 DPRINTF(InOrderCPU
, "[tid:%i]: Placing on Halted Threads List...\n", tid
);
1058 deactivateThread(tid
);
1059 squashThreadInPipeline(tid
);
1060 haltedThreads
.push_back(tid
);
1062 tcBase(tid
)->setStatus(ThreadContext::Halted
);
1064 if (threadModel
== SwitchOnCacheMiss
) {
1065 activateNextReadyContext();
1070 InOrderCPU::suspendContext(ThreadID tid
, int delay
)
1072 scheduleCpuEvent(SuspendThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1076 InOrderCPU::suspendThread(ThreadID tid
)
1078 DPRINTF(InOrderCPU
, "[tid:%i]: Placing on Suspended Threads List...\n",
1080 deactivateThread(tid
);
1081 suspendedThreads
.push_back(tid
);
1082 thread
[tid
]->lastSuspend
= curTick();
1084 tcBase(tid
)->setStatus(ThreadContext::Suspended
);
1088 InOrderCPU::squashThreadInPipeline(ThreadID tid
)
1090 //Squash all instructions in each stage
1091 for (int stNum
=NumStages
- 1; stNum
>= 0 ; stNum
--) {
1092 pipelineStage
[stNum
]->squash(0 /*seq_num*/, tid
);
1097 InOrderCPU::getPipeStage(int stage_num
)
1099 return pipelineStage
[stage_num
];
1103 InOrderCPU::readIntReg(int reg_idx
, ThreadID tid
)
1105 return intRegs
[tid
][reg_idx
];
1109 InOrderCPU::readFloatReg(int reg_idx
, ThreadID tid
)
1111 return floatRegs
.f
[tid
][reg_idx
];
1115 InOrderCPU::readFloatRegBits(int reg_idx
, ThreadID tid
)
1117 return floatRegs
.i
[tid
][reg_idx
];
1121 InOrderCPU::setIntReg(int reg_idx
, uint64_t val
, ThreadID tid
)
1123 intRegs
[tid
][reg_idx
] = val
;
1128 InOrderCPU::setFloatReg(int reg_idx
, FloatReg val
, ThreadID tid
)
1130 floatRegs
.f
[tid
][reg_idx
] = val
;
1135 InOrderCPU::setFloatRegBits(int reg_idx
, FloatRegBits val
, ThreadID tid
)
1137 floatRegs
.i
[tid
][reg_idx
] = val
;
1141 InOrderCPU::readRegOtherThread(unsigned reg_idx
, ThreadID tid
)
1143 // If Default value is set, then retrieve target thread
1144 if (tid
== InvalidThreadID
) {
1145 tid
= TheISA::getTargetThread(tcBase(tid
));
1148 if (reg_idx
< FP_Base_DepTag
) {
1149 // Integer Register File
1150 return readIntReg(reg_idx
, tid
);
1151 } else if (reg_idx
< Ctrl_Base_DepTag
) {
1152 // Float Register File
1153 reg_idx
-= FP_Base_DepTag
;
1154 return readFloatRegBits(reg_idx
, tid
);
1156 reg_idx
-= Ctrl_Base_DepTag
;
1157 return readMiscReg(reg_idx
, tid
); // Misc. Register File
1161 InOrderCPU::setRegOtherThread(unsigned reg_idx
, const MiscReg
&val
,
1164 // If Default value is set, then retrieve target thread
1165 if (tid
== InvalidThreadID
) {
1166 tid
= TheISA::getTargetThread(tcBase(tid
));
1169 if (reg_idx
< FP_Base_DepTag
) { // Integer Register File
1170 setIntReg(reg_idx
, val
, tid
);
1171 } else if (reg_idx
< Ctrl_Base_DepTag
) { // Float Register File
1172 reg_idx
-= FP_Base_DepTag
;
1173 setFloatRegBits(reg_idx
, val
, tid
);
1175 reg_idx
-= Ctrl_Base_DepTag
;
1176 setMiscReg(reg_idx
, val
, tid
); // Misc. Register File
1181 InOrderCPU::readMiscRegNoEffect(int misc_reg
, ThreadID tid
)
1183 return isa
[tid
].readMiscRegNoEffect(misc_reg
);
1187 InOrderCPU::readMiscReg(int misc_reg
, ThreadID tid
)
1189 return isa
[tid
].readMiscReg(misc_reg
, tcBase(tid
));
1193 InOrderCPU::setMiscRegNoEffect(int misc_reg
, const MiscReg
&val
, ThreadID tid
)
1195 isa
[tid
].setMiscRegNoEffect(misc_reg
, val
);
1199 InOrderCPU::setMiscReg(int misc_reg
, const MiscReg
&val
, ThreadID tid
)
1201 isa
[tid
].setMiscReg(misc_reg
, val
, tcBase(tid
));
1206 InOrderCPU::addInst(DynInstPtr
&inst
)
1208 ThreadID tid
= inst
->readTid();
1210 instList
[tid
].push_back(inst
);
1212 return --(instList
[tid
].end());
1216 InOrderCPU::updateContextSwitchStats()
1218 // Set Average Stat Here, then reset to 0
1219 instsPerCtxtSwitch
= instsPerSwitch
;
1225 InOrderCPU::instDone(DynInstPtr inst
, ThreadID tid
)
1227 // Set the CPU's PCs - This contributes to the precise state of the CPU
1228 // which can be used when restoring a thread to the CPU after after any
1229 // type of context switching activity (fork, exception, etc.)
1230 pcState(inst
->pcState(), tid
);
1232 if (inst
->isControl()) {
1233 thread
[tid
]->lastGradIsBranch
= true;
1234 thread
[tid
]->lastBranchPC
= inst
->pcState();
1235 TheISA::advancePC(thread
[tid
]->lastBranchPC
, inst
->staticInst
);
1237 thread
[tid
]->lastGradIsBranch
= false;
1241 // Finalize Trace Data For Instruction
1242 if (inst
->traceData
) {
1243 //inst->traceData->setCycle(curTick());
1244 inst
->traceData
->setFetchSeq(inst
->seqNum
);
1245 //inst->traceData->setCPSeq(cpu->tcBase(tid)->numInst);
1246 inst
->traceData
->dump();
1247 delete inst
->traceData
;
1248 inst
->traceData
= NULL
;
1251 // Increment active thread's instruction count
1254 // Increment thread-state's instruction count
1255 thread
[tid
]->numInst
++;
1257 // Increment thread-state's instruction stats
1258 thread
[tid
]->numInsts
++;
1260 // Count committed insts per thread stats
1261 committedInsts
[tid
]++;
1263 // Count total insts committed stat
1264 totalCommittedInsts
++;
1266 // Count SMT-committed insts per thread stat
1267 if (numActiveThreads() > 1) {
1268 smtCommittedInsts
[tid
]++;
1271 // Instruction-Mix Stats
1272 if (inst
->isLoad()) {
1274 } else if (inst
->isStore()) {
1276 } else if (inst
->isControl()) {
1278 } else if (inst
->isNop()) {
1280 } else if (inst
->isNonSpeculative()) {
1282 } else if (inst
->isInteger()) {
1284 } else if (inst
->isFloating()) {
1288 // Check for instruction-count-based events.
1289 comInstEventQueue
[tid
]->serviceEvents(thread
[tid
]->numInst
);
1291 // Broadcast to other resources an instruction
1292 // has been completed
1293 resPool
->scheduleEvent((CPUEventType
)ResourcePool::InstGraduated
, inst
,
1296 // Finally, remove instruction from CPU
1300 // currently unused function, but substitute repetitive code w/this function
1303 InOrderCPU::addToRemoveList(DynInstPtr
&inst
)
1305 removeInstsThisCycle
= true;
1306 if (!inst
->isRemoveList()) {
1307 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1308 "[sn:%lli] to remove list\n",
1309 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1310 inst
->setRemoveList();
1311 removeList
.push(inst
->getInstListIt());
1313 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i] PC %s "
1314 "[sn:%lli], already remove list\n",
1315 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1321 InOrderCPU::removeInst(DynInstPtr
&inst
)
1323 DPRINTF(InOrderCPU
, "Removing graduated instruction [tid:%i] PC %s "
1325 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1327 removeInstsThisCycle
= true;
1329 // Remove the instruction.
1330 if (!inst
->isRemoveList()) {
1331 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1332 "[sn:%lli] to remove list\n",
1333 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1334 inst
->setRemoveList();
1335 removeList
.push(inst
->getInstListIt());
1337 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i] PC %s "
1338 "[sn:%lli], already on remove list\n",
1339 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1345 InOrderCPU::removeInstsUntil(const InstSeqNum
&seq_num
, ThreadID tid
)
1347 //assert(!instList[tid].empty());
1349 removeInstsThisCycle
= true;
1351 ListIt inst_iter
= instList
[tid
].end();
1355 DPRINTF(InOrderCPU
, "Squashing instructions from CPU instruction "
1356 "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1357 tid
, seq_num
, (*inst_iter
)->seqNum
);
1359 while ((*inst_iter
)->seqNum
> seq_num
) {
1361 bool break_loop
= (inst_iter
== instList
[tid
].begin());
1363 squashInstIt(inst_iter
, tid
);
1374 InOrderCPU::squashInstIt(const ListIt
&instIt
, ThreadID tid
)
1376 if ((*instIt
)->threadNumber
== tid
) {
1377 DPRINTF(InOrderCPU
, "Squashing instruction, "
1378 "[tid:%i] [sn:%lli] PC %s\n",
1379 (*instIt
)->threadNumber
,
1381 (*instIt
)->pcState());
1383 (*instIt
)->setSquashed();
1385 if (!(*instIt
)->isRemoveList()) {
1386 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1387 "[sn:%lli] to remove list\n",
1388 (*instIt
)->threadNumber
, (*instIt
)->pcState(),
1390 (*instIt
)->setRemoveList();
1391 removeList
.push(instIt
);
1393 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i]"
1394 " PC %s [sn:%lli], already on remove list\n",
1395 (*instIt
)->threadNumber
, (*instIt
)->pcState(),
1405 InOrderCPU::cleanUpRemovedInsts()
1407 while (!removeList
.empty()) {
1408 DPRINTF(InOrderCPU
, "Removing instruction, "
1409 "[tid:%i] [sn:%lli] PC %s\n",
1410 (*removeList
.front())->threadNumber
,
1411 (*removeList
.front())->seqNum
,
1412 (*removeList
.front())->pcState());
1414 DynInstPtr inst
= *removeList
.front();
1415 ThreadID tid
= inst
->threadNumber
;
1417 // Remove From Register Dependency Map, If Necessary
1418 archRegDepMap
[(*removeList
.front())->threadNumber
].
1419 remove((*removeList
.front()));
1422 // Clear if Non-Speculative
1423 if (inst
->staticInst
&&
1424 inst
->seqNum
== nonSpecSeqNum
[tid
] &&
1425 nonSpecInstActive
[tid
] == true) {
1426 nonSpecInstActive
[tid
] = false;
1429 instList
[tid
].erase(removeList
.front());
1434 removeInstsThisCycle
= false;
1438 InOrderCPU::cleanUpRemovedEvents()
1440 while (!cpuEventRemoveList
.empty()) {
1441 Event
*cpu_event
= cpuEventRemoveList
.front();
1442 cpuEventRemoveList
.pop();
1449 InOrderCPU::dumpInsts()
1453 ListIt inst_list_it
= instList
[0].begin();
1455 cprintf("Dumping Instruction List\n");
1457 while (inst_list_it
!= instList
[0].end()) {
1458 cprintf("Instruction:%i\nPC:%s\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1460 num
, (*inst_list_it
)->pcState(),
1461 (*inst_list_it
)->threadNumber
,
1462 (*inst_list_it
)->seqNum
, (*inst_list_it
)->isIssued(),
1463 (*inst_list_it
)->isSquashed());
1470 InOrderCPU::wakeCPU()
1472 if (/*activityRec.active() || */tickEvent
.scheduled()) {
1473 DPRINTF(Activity
, "CPU already running.\n");
1477 DPRINTF(Activity
, "Waking up CPU\n");
1479 Tick extra_cycles
= tickToCycles((curTick() - 1) - lastRunningCycle
);
1481 idleCycles
+= extra_cycles
;
1482 for (int stage_num
= 0; stage_num
< NumStages
; stage_num
++) {
1483 pipelineStage
[stage_num
]->idleCycles
+= extra_cycles
;
1486 numCycles
+= extra_cycles
;
1488 schedule(&tickEvent
, nextCycle(curTick()));
1494 InOrderCPU::wakeup()
1496 if (thread
[0]->status() != ThreadContext::Suspended
)
1501 DPRINTF(Quiesce
, "Suspended Processor woken\n");
1502 threadContexts
[0]->activate();
1508 InOrderCPU::syscall(int64_t callnum
, ThreadID tid
)
1510 DPRINTF(InOrderCPU
, "[tid:%i] Executing syscall().\n\n", tid
);
1512 DPRINTF(Activity
,"Activity: syscall() called.\n");
1514 // Temporarily increase this by one to account for the syscall
1516 ++(this->thread
[tid
]->funcExeInst
);
1518 // Execute the actual syscall.
1519 this->thread
[tid
]->syscall(callnum
);
1521 // Decrease funcExeInst by one as the normal commit will handle
1523 --(this->thread
[tid
]->funcExeInst
);
1525 // Clear Non-Speculative Block Variable
1526 nonSpecInstActive
[tid
] = false;
1531 InOrderCPU::getITBPtr()
1533 CacheUnit
*itb_res
=
1534 dynamic_cast<CacheUnit
*>(resPool
->getResource(fetchPortIdx
));
1535 return itb_res
->tlb();
1540 InOrderCPU::getDTBPtr()
1542 CacheUnit
*dtb_res
=
1543 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1544 return dtb_res
->tlb();
1548 InOrderCPU::read(DynInstPtr inst
, Addr addr
,
1549 uint8_t *data
, unsigned size
, unsigned flags
)
1551 //@TODO: Generalize name "CacheUnit" to "MemUnit" just in case
1552 // you want to run w/out caches?
1553 CacheUnit
*cache_res
=
1554 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1556 return cache_res
->read(inst
, addr
, data
, size
, flags
);
1560 InOrderCPU::write(DynInstPtr inst
, uint8_t *data
, unsigned size
,
1561 Addr addr
, unsigned flags
, uint64_t *write_res
)
1563 //@TODO: Generalize name "CacheUnit" to "MemUnit" just in case
1564 // you want to run w/out caches?
1565 CacheUnit
*cache_res
=
1566 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1567 return cache_res
->write(inst
, data
, size
, addr
, flags
, write_res
);