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 requests, events, or insts then remove them now
640 cleanUpRemovedReqs();
641 cleanUpRemovedEvents();
642 cleanUpRemovedInsts();
644 // Re-schedule CPU for this cycle
645 if (!tickEvent
.scheduled()) {
646 if (_status
== SwitchedOut
) {
648 lastRunningCycle
= curTick();
649 } else if (!activityRec
.active()) {
650 DPRINTF(InOrderCPU
, "sleeping CPU.\n");
651 lastRunningCycle
= curTick();
654 //Tick next_tick = curTick() + cycles(1);
655 //tickEvent.schedule(next_tick);
656 schedule(&tickEvent
, nextCycle(curTick() + 1));
657 DPRINTF(InOrderCPU
, "Scheduled CPU for next tick @ %i.\n",
658 nextCycle(curTick() + 1));
663 updateThreadPriority();
670 if (!deferRegistration
) {
671 registerThreadContexts();
674 // Set inSyscall so that the CPU doesn't squash when initially
675 // setting up registers.
676 for (ThreadID tid
= 0; tid
< numThreads
; ++tid
)
677 thread
[tid
]->inSyscall
= true;
680 for (ThreadID tid
= 0; tid
< numThreads
; tid
++) {
681 ThreadContext
*src_tc
= threadContexts
[tid
];
682 TheISA::initCPU(src_tc
, src_tc
->contextId());
687 for (ThreadID tid
= 0; tid
< numThreads
; ++tid
)
688 thread
[tid
]->inSyscall
= false;
690 // Call Initializiation Routine for Resource Pool
697 for (int i
= 0; i
< numThreads
; i
++) {
698 isa
[i
].reset(coreType
, numThreads
,
699 1/*numVirtProcs*/, dynamic_cast<BaseCPU
*>(this));
704 InOrderCPU::getPort(const std::string
&if_name
, int idx
)
706 return resPool
->getPort(if_name
, idx
);
711 InOrderCPU::hwrei(ThreadID tid
)
713 panic("hwrei: Unimplemented");
720 InOrderCPU::simPalCheck(int palFunc
, ThreadID tid
)
722 panic("simPalCheck: Unimplemented");
729 InOrderCPU::getInterrupts()
731 // Check if there are any outstanding interrupts
732 return interrupts
->getInterrupt(threadContexts
[0]);
737 InOrderCPU::processInterrupts(Fault interrupt
)
739 // Check for interrupts here. For now can copy the code that
740 // exists within isa_fullsys_traits.hh. Also assume that thread 0
741 // is the one that handles the interrupts.
742 // @todo: Possibly consolidate the interrupt checking code.
743 // @todo: Allow other threads to handle interrupts.
745 assert(interrupt
!= NoFault
);
746 interrupts
->updateIntrInfo(threadContexts
[0]);
748 DPRINTF(InOrderCPU
, "Interrupt %s being handled\n", interrupt
->name());
750 // Note: Context ID ok here? Impl. of FS mode needs to revisit this
751 trap(interrupt
, threadContexts
[0]->contextId(), dummyBufferInst
);
756 InOrderCPU::updateMemPorts()
758 // Update all ThreadContext's memory ports (Functional/Virtual
760 ThreadID size
= thread
.size();
761 for (ThreadID i
= 0; i
< size
; ++i
)
762 thread
[i
]->connectMemPorts(thread
[i
]->getTC());
767 InOrderCPU::trap(Fault fault
, ThreadID tid
, DynInstPtr inst
, int delay
)
769 //@ Squash Pipeline during TRAP
770 scheduleCpuEvent(Trap
, fault
, tid
, inst
, delay
);
774 InOrderCPU::trapCPU(Fault fault
, ThreadID tid
, DynInstPtr inst
)
776 fault
->invoke(tcBase(tid
), inst
->staticInst
);
780 InOrderCPU::squashFromMemStall(DynInstPtr inst
, ThreadID tid
, int delay
)
782 scheduleCpuEvent(SquashFromMemStall
, NoFault
, tid
, inst
, delay
);
787 InOrderCPU::squashDueToMemStall(int stage_num
, InstSeqNum seq_num
,
790 DPRINTF(InOrderCPU
, "Squashing Pipeline Stages Due to Memory Stall...\n");
792 // Squash all instructions in each stage including
793 // instruction that caused the squash (seq_num - 1)
794 // NOTE: The stage bandwidth needs to be cleared so thats why
795 // the stalling instruction is squashed as well. The stalled
796 // instruction is previously placed in another intermediate buffer
797 // while it's stall is being handled.
798 InstSeqNum squash_seq_num
= seq_num
- 1;
800 for (int stNum
=stage_num
; stNum
>= 0 ; stNum
--) {
801 pipelineStage
[stNum
]->squashDueToMemStall(squash_seq_num
, tid
);
806 InOrderCPU::scheduleCpuEvent(CPUEventType c_event
, Fault fault
,
807 ThreadID tid
, DynInstPtr inst
,
808 unsigned delay
, unsigned event_pri_offset
)
810 CPUEvent
*cpu_event
= new CPUEvent(this, c_event
, fault
, tid
, inst
,
813 Tick sked_tick
= nextCycle(curTick() + ticks(delay
));
815 DPRINTF(InOrderCPU
, "Scheduling CPU Event (%s) for cycle %i, [tid:%i].\n",
816 eventNames
[c_event
], curTick() + delay
, tid
);
817 schedule(cpu_event
, sked_tick
);
819 cpu_event
->process();
820 cpuEventRemoveList
.push(cpu_event
);
823 // Broadcast event to the Resource Pool
824 // Need to reset tid just in case this is a dummy instruction
826 resPool
->scheduleEvent(c_event
, inst
, 0, 0, tid
);
830 InOrderCPU::isThreadActive(ThreadID tid
)
832 list
<ThreadID
>::iterator isActive
=
833 std::find(activeThreads
.begin(), activeThreads
.end(), tid
);
835 return (isActive
!= activeThreads
.end());
839 InOrderCPU::isThreadReady(ThreadID tid
)
841 list
<ThreadID
>::iterator isReady
=
842 std::find(readyThreads
.begin(), readyThreads
.end(), tid
);
844 return (isReady
!= readyThreads
.end());
848 InOrderCPU::isThreadSuspended(ThreadID tid
)
850 list
<ThreadID
>::iterator isSuspended
=
851 std::find(suspendedThreads
.begin(), suspendedThreads
.end(), tid
);
853 return (isSuspended
!= suspendedThreads
.end());
857 InOrderCPU::activateNextReadyThread()
859 if (readyThreads
.size() >= 1) {
860 ThreadID ready_tid
= readyThreads
.front();
862 // Activate in Pipeline
863 activateThread(ready_tid
);
865 // Activate in Resource Pool
866 resPool
->activateAll(ready_tid
);
868 list
<ThreadID
>::iterator ready_it
=
869 std::find(readyThreads
.begin(), readyThreads
.end(), ready_tid
);
870 readyThreads
.erase(ready_it
);
873 "Attempting to activate new thread, but No Ready Threads to"
876 "Unable to switch to next active thread.\n");
881 InOrderCPU::activateThread(ThreadID tid
)
883 if (isThreadSuspended(tid
)) {
885 "Removing [tid:%i] from suspended threads list.\n", tid
);
887 list
<ThreadID
>::iterator susp_it
=
888 std::find(suspendedThreads
.begin(), suspendedThreads
.end(),
890 suspendedThreads
.erase(susp_it
);
893 if (threadModel
== SwitchOnCacheMiss
&&
894 numActiveThreads() == 1) {
896 "Ignoring activation of [tid:%i], since [tid:%i] is "
897 "already running.\n", tid
, activeThreadId());
899 DPRINTF(InOrderCPU
,"Placing [tid:%i] on ready threads list\n",
902 readyThreads
.push_back(tid
);
904 } else if (!isThreadActive(tid
)) {
906 "Adding [tid:%i] to active threads list.\n", tid
);
907 activeThreads
.push_back(tid
);
909 activateThreadInPipeline(tid
);
911 thread
[tid
]->lastActivate
= curTick();
913 tcBase(tid
)->setStatus(ThreadContext::Active
);
922 InOrderCPU::activateThreadInPipeline(ThreadID tid
)
924 for (int stNum
=0; stNum
< NumStages
; stNum
++) {
925 pipelineStage
[stNum
]->activateThread(tid
);
930 InOrderCPU::deactivateContext(ThreadID tid
, int delay
)
932 DPRINTF(InOrderCPU
,"[tid:%i]: Deactivating ...\n", tid
);
934 scheduleCpuEvent(DeactivateThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
936 // Be sure to signal that there's some activity so the CPU doesn't
937 // deschedule itself.
938 activityRec
.activity();
944 InOrderCPU::deactivateThread(ThreadID tid
)
946 DPRINTF(InOrderCPU
, "[tid:%i]: Calling deactivate thread.\n", tid
);
948 if (isThreadActive(tid
)) {
949 DPRINTF(InOrderCPU
,"[tid:%i]: Removing from active threads list\n",
951 list
<ThreadID
>::iterator thread_it
=
952 std::find(activeThreads
.begin(), activeThreads
.end(), tid
);
954 removePipelineStalls(*thread_it
);
956 activeThreads
.erase(thread_it
);
958 // Ideally, this should be triggered from the
959 // suspendContext/Thread functions
960 tcBase(tid
)->setStatus(ThreadContext::Suspended
);
963 assert(!isThreadActive(tid
));
967 InOrderCPU::removePipelineStalls(ThreadID tid
)
969 DPRINTF(InOrderCPU
,"[tid:%i]: Removing all pipeline stalls\n",
972 for (int stNum
= 0; stNum
< NumStages
; stNum
++) {
973 pipelineStage
[stNum
]->removeStalls(tid
);
979 InOrderCPU::updateThreadPriority()
981 if (activeThreads
.size() > 1)
983 //DEFAULT TO ROUND ROBIN SCHEME
984 //e.g. Move highest priority to end of thread list
985 list
<ThreadID
>::iterator list_begin
= activeThreads
.begin();
986 list
<ThreadID
>::iterator list_end
= activeThreads
.end();
988 unsigned high_thread
= *list_begin
;
990 activeThreads
.erase(list_begin
);
992 activeThreads
.push_back(high_thread
);
997 InOrderCPU::tickThreadStats()
999 /** Keep track of cycles that each thread is active */
1000 list
<ThreadID
>::iterator thread_it
= activeThreads
.begin();
1001 while (thread_it
!= activeThreads
.end()) {
1002 threadCycles
[*thread_it
]++;
1006 // Keep track of cycles where SMT is active
1007 if (activeThreads
.size() > 1) {
1013 InOrderCPU::activateContext(ThreadID tid
, int delay
)
1015 DPRINTF(InOrderCPU
,"[tid:%i]: Activating ...\n", tid
);
1018 scheduleCpuEvent(ActivateThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1020 // Be sure to signal that there's some activity so the CPU doesn't
1021 // deschedule itself.
1022 activityRec
.activity();
1028 InOrderCPU::activateNextReadyContext(int delay
)
1030 DPRINTF(InOrderCPU
,"Activating next ready thread\n");
1032 // NOTE: Add 5 to the event priority so that we always activate
1033 // threads after we've finished deactivating, squashing,etc.
1035 scheduleCpuEvent(ActivateNextReadyThread
, NoFault
, 0/*tid*/, dummyInst
[0],
1038 // Be sure to signal that there's some activity so the CPU doesn't
1039 // deschedule itself.
1040 activityRec
.activity();
1046 InOrderCPU::haltContext(ThreadID tid
, int delay
)
1048 DPRINTF(InOrderCPU
, "[tid:%i]: Calling Halt Context...\n", tid
);
1050 scheduleCpuEvent(HaltThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1052 activityRec
.activity();
1056 InOrderCPU::haltThread(ThreadID tid
)
1058 DPRINTF(InOrderCPU
, "[tid:%i]: Placing on Halted Threads List...\n", tid
);
1059 deactivateThread(tid
);
1060 squashThreadInPipeline(tid
);
1061 haltedThreads
.push_back(tid
);
1063 tcBase(tid
)->setStatus(ThreadContext::Halted
);
1065 if (threadModel
== SwitchOnCacheMiss
) {
1066 activateNextReadyContext();
1071 InOrderCPU::suspendContext(ThreadID tid
, int delay
)
1073 scheduleCpuEvent(SuspendThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1077 InOrderCPU::suspendThread(ThreadID tid
)
1079 DPRINTF(InOrderCPU
, "[tid:%i]: Placing on Suspended Threads List...\n",
1081 deactivateThread(tid
);
1082 suspendedThreads
.push_back(tid
);
1083 thread
[tid
]->lastSuspend
= curTick();
1085 tcBase(tid
)->setStatus(ThreadContext::Suspended
);
1089 InOrderCPU::squashThreadInPipeline(ThreadID tid
)
1091 //Squash all instructions in each stage
1092 for (int stNum
=NumStages
- 1; stNum
>= 0 ; stNum
--) {
1093 pipelineStage
[stNum
]->squash(0 /*seq_num*/, tid
);
1098 InOrderCPU::getPipeStage(int stage_num
)
1100 return pipelineStage
[stage_num
];
1104 InOrderCPU::readIntReg(int reg_idx
, ThreadID tid
)
1106 return intRegs
[tid
][reg_idx
];
1110 InOrderCPU::readFloatReg(int reg_idx
, ThreadID tid
)
1112 return floatRegs
.f
[tid
][reg_idx
];
1116 InOrderCPU::readFloatRegBits(int reg_idx
, ThreadID tid
)
1118 return floatRegs
.i
[tid
][reg_idx
];
1122 InOrderCPU::setIntReg(int reg_idx
, uint64_t val
, ThreadID tid
)
1124 intRegs
[tid
][reg_idx
] = val
;
1129 InOrderCPU::setFloatReg(int reg_idx
, FloatReg val
, ThreadID tid
)
1131 floatRegs
.f
[tid
][reg_idx
] = val
;
1136 InOrderCPU::setFloatRegBits(int reg_idx
, FloatRegBits val
, ThreadID tid
)
1138 floatRegs
.i
[tid
][reg_idx
] = val
;
1142 InOrderCPU::readRegOtherThread(unsigned reg_idx
, ThreadID tid
)
1144 // If Default value is set, then retrieve target thread
1145 if (tid
== InvalidThreadID
) {
1146 tid
= TheISA::getTargetThread(tcBase(tid
));
1149 if (reg_idx
< FP_Base_DepTag
) {
1150 // Integer Register File
1151 return readIntReg(reg_idx
, tid
);
1152 } else if (reg_idx
< Ctrl_Base_DepTag
) {
1153 // Float Register File
1154 reg_idx
-= FP_Base_DepTag
;
1155 return readFloatRegBits(reg_idx
, tid
);
1157 reg_idx
-= Ctrl_Base_DepTag
;
1158 return readMiscReg(reg_idx
, tid
); // Misc. Register File
1162 InOrderCPU::setRegOtherThread(unsigned reg_idx
, const MiscReg
&val
,
1165 // If Default value is set, then retrieve target thread
1166 if (tid
== InvalidThreadID
) {
1167 tid
= TheISA::getTargetThread(tcBase(tid
));
1170 if (reg_idx
< FP_Base_DepTag
) { // Integer Register File
1171 setIntReg(reg_idx
, val
, tid
);
1172 } else if (reg_idx
< Ctrl_Base_DepTag
) { // Float Register File
1173 reg_idx
-= FP_Base_DepTag
;
1174 setFloatRegBits(reg_idx
, val
, tid
);
1176 reg_idx
-= Ctrl_Base_DepTag
;
1177 setMiscReg(reg_idx
, val
, tid
); // Misc. Register File
1182 InOrderCPU::readMiscRegNoEffect(int misc_reg
, ThreadID tid
)
1184 return isa
[tid
].readMiscRegNoEffect(misc_reg
);
1188 InOrderCPU::readMiscReg(int misc_reg
, ThreadID tid
)
1190 return isa
[tid
].readMiscReg(misc_reg
, tcBase(tid
));
1194 InOrderCPU::setMiscRegNoEffect(int misc_reg
, const MiscReg
&val
, ThreadID tid
)
1196 isa
[tid
].setMiscRegNoEffect(misc_reg
, val
);
1200 InOrderCPU::setMiscReg(int misc_reg
, const MiscReg
&val
, ThreadID tid
)
1202 isa
[tid
].setMiscReg(misc_reg
, val
, tcBase(tid
));
1207 InOrderCPU::addInst(DynInstPtr
&inst
)
1209 ThreadID tid
= inst
->readTid();
1211 instList
[tid
].push_back(inst
);
1213 return --(instList
[tid
].end());
1217 InOrderCPU::updateContextSwitchStats()
1219 // Set Average Stat Here, then reset to 0
1220 instsPerCtxtSwitch
= instsPerSwitch
;
1226 InOrderCPU::instDone(DynInstPtr inst
, ThreadID tid
)
1228 // Set the CPU's PCs - This contributes to the precise state of the CPU
1229 // which can be used when restoring a thread to the CPU after after any
1230 // type of context switching activity (fork, exception, etc.)
1231 pcState(inst
->pcState(), tid
);
1233 if (inst
->isControl()) {
1234 thread
[tid
]->lastGradIsBranch
= true;
1235 thread
[tid
]->lastBranchPC
= inst
->pcState();
1236 TheISA::advancePC(thread
[tid
]->lastBranchPC
, inst
->staticInst
);
1238 thread
[tid
]->lastGradIsBranch
= false;
1242 // Finalize Trace Data For Instruction
1243 if (inst
->traceData
) {
1244 //inst->traceData->setCycle(curTick());
1245 inst
->traceData
->setFetchSeq(inst
->seqNum
);
1246 //inst->traceData->setCPSeq(cpu->tcBase(tid)->numInst);
1247 inst
->traceData
->dump();
1248 delete inst
->traceData
;
1249 inst
->traceData
= NULL
;
1252 // Increment active thread's instruction count
1255 // Increment thread-state's instruction count
1256 thread
[tid
]->numInst
++;
1258 // Increment thread-state's instruction stats
1259 thread
[tid
]->numInsts
++;
1261 // Count committed insts per thread stats
1262 committedInsts
[tid
]++;
1264 // Count total insts committed stat
1265 totalCommittedInsts
++;
1267 // Count SMT-committed insts per thread stat
1268 if (numActiveThreads() > 1) {
1269 smtCommittedInsts
[tid
]++;
1272 // Instruction-Mix Stats
1273 if (inst
->isLoad()) {
1275 } else if (inst
->isStore()) {
1277 } else if (inst
->isControl()) {
1279 } else if (inst
->isNop()) {
1281 } else if (inst
->isNonSpeculative()) {
1283 } else if (inst
->isInteger()) {
1285 } else if (inst
->isFloating()) {
1289 // Check for instruction-count-based events.
1290 comInstEventQueue
[tid
]->serviceEvents(thread
[tid
]->numInst
);
1292 // Broadcast to other resources an instruction
1293 // has been completed
1294 resPool
->scheduleEvent((CPUEventType
)ResourcePool::InstGraduated
, inst
,
1297 // Finally, remove instruction from CPU
1301 // currently unused function, but substitute repetitive code w/this function
1304 InOrderCPU::addToRemoveList(DynInstPtr
&inst
)
1306 removeInstsThisCycle
= true;
1307 if (!inst
->isRemoveList()) {
1308 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1309 "[sn:%lli] to remove list\n",
1310 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1311 inst
->setRemoveList();
1312 removeList
.push(inst
->getInstListIt());
1314 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i] PC %s "
1315 "[sn:%lli], already remove list\n",
1316 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1322 InOrderCPU::removeInst(DynInstPtr
&inst
)
1324 DPRINTF(InOrderCPU
, "Removing graduated instruction [tid:%i] PC %s "
1326 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1328 removeInstsThisCycle
= true;
1330 // Remove the instruction.
1331 if (!inst
->isRemoveList()) {
1332 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1333 "[sn:%lli] to remove list\n",
1334 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1335 inst
->setRemoveList();
1336 removeList
.push(inst
->getInstListIt());
1338 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i] PC %s "
1339 "[sn:%lli], already on remove list\n",
1340 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1346 InOrderCPU::removeInstsUntil(const InstSeqNum
&seq_num
, ThreadID tid
)
1348 //assert(!instList[tid].empty());
1350 removeInstsThisCycle
= true;
1352 ListIt inst_iter
= instList
[tid
].end();
1356 DPRINTF(InOrderCPU
, "Squashing instructions from CPU instruction "
1357 "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1358 tid
, seq_num
, (*inst_iter
)->seqNum
);
1360 while ((*inst_iter
)->seqNum
> seq_num
) {
1362 bool break_loop
= (inst_iter
== instList
[tid
].begin());
1364 squashInstIt(inst_iter
, tid
);
1375 InOrderCPU::squashInstIt(const ListIt
&instIt
, ThreadID tid
)
1377 if ((*instIt
)->threadNumber
== tid
) {
1378 DPRINTF(InOrderCPU
, "Squashing instruction, "
1379 "[tid:%i] [sn:%lli] PC %s\n",
1380 (*instIt
)->threadNumber
,
1382 (*instIt
)->pcState());
1384 (*instIt
)->setSquashed();
1386 if (!(*instIt
)->isRemoveList()) {
1387 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1388 "[sn:%lli] to remove list\n",
1389 (*instIt
)->threadNumber
, (*instIt
)->pcState(),
1391 (*instIt
)->setRemoveList();
1392 removeList
.push(instIt
);
1394 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i]"
1395 " PC %s [sn:%lli], already on remove list\n",
1396 (*instIt
)->threadNumber
, (*instIt
)->pcState(),
1406 InOrderCPU::cleanUpRemovedInsts()
1408 while (!removeList
.empty()) {
1409 DPRINTF(InOrderCPU
, "Removing instruction, "
1410 "[tid:%i] [sn:%lli] PC %s\n",
1411 (*removeList
.front())->threadNumber
,
1412 (*removeList
.front())->seqNum
,
1413 (*removeList
.front())->pcState());
1415 DynInstPtr inst
= *removeList
.front();
1416 ThreadID tid
= inst
->threadNumber
;
1418 // Make Sure Resource Schedule Is Emptied Out
1419 ThePipeline::ResSchedule
*inst_sched
= &inst
->resSched
;
1420 while (!inst_sched
->empty()) {
1421 ScheduleEntry
* sch_entry
= inst_sched
->top();
1426 // Remove From Register Dependency Map, If Necessary
1427 archRegDepMap
[(*removeList
.front())->threadNumber
].
1428 remove((*removeList
.front()));
1431 // Clear if Non-Speculative
1432 if (inst
->staticInst
&&
1433 inst
->seqNum
== nonSpecSeqNum
[tid
] &&
1434 nonSpecInstActive
[tid
] == true) {
1435 nonSpecInstActive
[tid
] = false;
1438 instList
[tid
].erase(removeList
.front());
1443 removeInstsThisCycle
= false;
1447 InOrderCPU::cleanUpRemovedReqs()
1449 while (!reqRemoveList
.empty()) {
1450 ResourceRequest
*res_req
= reqRemoveList
.front();
1452 DPRINTF(RefCount
, "[tid:%i] [sn:%lli]: Removing Request "
1453 "[stage_num:%i] [res:%s] [slot:%i] [completed:%i].\n",
1454 res_req
->inst
->threadNumber
,
1455 res_req
->inst
->seqNum
,
1456 res_req
->getStageNum(),
1457 res_req
->res
->name(),
1458 (res_req
->isCompleted()) ?
1459 res_req
->getComplSlot() : res_req
->getSlot(),
1460 res_req
->isCompleted());
1462 reqRemoveList
.pop();
1469 InOrderCPU::cleanUpRemovedEvents()
1471 while (!cpuEventRemoveList
.empty()) {
1472 Event
*cpu_event
= cpuEventRemoveList
.front();
1473 cpuEventRemoveList
.pop();
1480 InOrderCPU::dumpInsts()
1484 ListIt inst_list_it
= instList
[0].begin();
1486 cprintf("Dumping Instruction List\n");
1488 while (inst_list_it
!= instList
[0].end()) {
1489 cprintf("Instruction:%i\nPC:%s\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1491 num
, (*inst_list_it
)->pcState(),
1492 (*inst_list_it
)->threadNumber
,
1493 (*inst_list_it
)->seqNum
, (*inst_list_it
)->isIssued(),
1494 (*inst_list_it
)->isSquashed());
1501 InOrderCPU::wakeCPU()
1503 if (/*activityRec.active() || */tickEvent
.scheduled()) {
1504 DPRINTF(Activity
, "CPU already running.\n");
1508 DPRINTF(Activity
, "Waking up CPU\n");
1510 Tick extra_cycles
= tickToCycles((curTick() - 1) - lastRunningCycle
);
1512 idleCycles
+= extra_cycles
;
1513 for (int stage_num
= 0; stage_num
< NumStages
; stage_num
++) {
1514 pipelineStage
[stage_num
]->idleCycles
+= extra_cycles
;
1517 numCycles
+= extra_cycles
;
1519 schedule(&tickEvent
, nextCycle(curTick()));
1525 InOrderCPU::wakeup()
1527 if (thread
[0]->status() != ThreadContext::Suspended
)
1532 DPRINTF(Quiesce
, "Suspended Processor woken\n");
1533 threadContexts
[0]->activate();
1539 InOrderCPU::syscall(int64_t callnum
, ThreadID tid
)
1541 DPRINTF(InOrderCPU
, "[tid:%i] Executing syscall().\n\n", tid
);
1543 DPRINTF(Activity
,"Activity: syscall() called.\n");
1545 // Temporarily increase this by one to account for the syscall
1547 ++(this->thread
[tid
]->funcExeInst
);
1549 // Execute the actual syscall.
1550 this->thread
[tid
]->syscall(callnum
);
1552 // Decrease funcExeInst by one as the normal commit will handle
1554 --(this->thread
[tid
]->funcExeInst
);
1556 // Clear Non-Speculative Block Variable
1557 nonSpecInstActive
[tid
] = false;
1562 InOrderCPU::getITBPtr()
1564 CacheUnit
*itb_res
=
1565 dynamic_cast<CacheUnit
*>(resPool
->getResource(fetchPortIdx
));
1566 return itb_res
->tlb();
1571 InOrderCPU::getDTBPtr()
1573 CacheUnit
*dtb_res
=
1574 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1575 return dtb_res
->tlb();
1579 InOrderCPU::read(DynInstPtr inst
, Addr addr
,
1580 uint8_t *data
, unsigned size
, unsigned flags
)
1582 //@TODO: Generalize name "CacheUnit" to "MemUnit" just in case
1583 // you want to run w/out caches?
1584 CacheUnit
*cache_res
=
1585 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1587 return cache_res
->read(inst
, addr
, data
, size
, flags
);
1591 InOrderCPU::write(DynInstPtr inst
, uint8_t *data
, unsigned size
,
1592 Addr addr
, unsigned flags
, uint64_t *write_res
)
1594 //@TODO: Generalize name "CacheUnit" to "MemUnit" just in case
1595 // you want to run w/out caches?
1596 CacheUnit
*cache_res
=
1597 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1598 return cache_res
->write(inst
, data
, size
, addr
, flags
, write_res
);