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/inorder/resources/resource_list.hh"
38 #include "cpu/inorder/cpu.hh"
39 #include "cpu/inorder/first_stage.hh"
40 #include "cpu/inorder/inorder_dyn_inst.hh"
41 #include "cpu/inorder/pipeline_traits.hh"
42 #include "cpu/inorder/resource_pool.hh"
43 #include "cpu/inorder/thread_context.hh"
44 #include "cpu/inorder/thread_state.hh"
45 #include "cpu/activity.hh"
46 #include "cpu/base.hh"
47 #include "cpu/exetrace.hh"
48 #include "cpu/simple_thread.hh"
49 #include "cpu/thread_context.hh"
50 #include "debug/Activity.hh"
51 #include "debug/InOrderCPU.hh"
52 #include "debug/RefCount.hh"
53 #include "debug/SkedCache.hh"
54 #include "mem/translating_port.hh"
55 #include "params/InOrderCPU.hh"
56 #include "sim/process.hh"
57 #include "sim/stat_control.hh"
60 #include "cpu/quiesce_event.hh"
61 #include "sim/system.hh"
64 #if THE_ISA == ALPHA_ISA
65 #include "arch/alpha/osfpal.hh"
69 using namespace TheISA
;
70 using namespace ThePipeline
;
72 InOrderCPU::TickEvent::TickEvent(InOrderCPU
*c
)
73 : Event(CPU_Tick_Pri
), cpu(c
)
78 InOrderCPU::TickEvent::process()
85 InOrderCPU::TickEvent::description()
87 return "InOrderCPU tick event";
90 InOrderCPU::CPUEvent::CPUEvent(InOrderCPU
*_cpu
, CPUEventType e_type
,
91 Fault fault
, ThreadID _tid
, DynInstPtr inst
,
92 unsigned event_pri_offset
)
93 : Event(Event::Priority((unsigned int)CPU_Tick_Pri
+ event_pri_offset
)),
96 setEvent(e_type
, fault
, _tid
, inst
);
100 std::string
InOrderCPU::eventNames
[NumCPUEvents
] =
103 "ActivateNextReadyThread",
109 "SquashFromMemStall",
114 InOrderCPU::CPUEvent::process()
116 switch (cpuEventType
)
119 cpu
->activateThread(tid
);
122 case ActivateNextReadyThread
:
123 cpu
->activateNextReadyThread();
126 case DeactivateThread
:
127 cpu
->deactivateThread(tid
);
131 cpu
->haltThread(tid
);
135 cpu
->suspendThread(tid
);
138 case SquashFromMemStall
:
139 cpu
->squashDueToMemStall(inst
->squashingStage
, inst
->seqNum
, tid
);
143 cpu
->trapCPU(fault
, tid
, inst
);
147 fatal("Unrecognized Event Type %s", eventNames
[cpuEventType
]);
150 cpu
->cpuEventRemoveList
.push(this);
156 InOrderCPU::CPUEvent::description()
158 return "InOrderCPU event";
162 InOrderCPU::CPUEvent::scheduleEvent(int delay
)
164 assert(!scheduled() || squashed());
165 cpu
->reschedule(this, cpu
->nextCycle(curTick() + cpu
->ticks(delay
)), true);
169 InOrderCPU::CPUEvent::unscheduleEvent()
175 InOrderCPU::InOrderCPU(Params
*params
)
177 cpu_id(params
->cpu_id
),
181 stageWidth(params
->stageWidth
),
183 removeInstsThisCycle(false),
184 activityRec(params
->name
, NumStages
, 10, params
->activity
),
186 system(params
->system
),
187 physmem(system
->physmem
),
188 #endif // FULL_SYSTEM
194 deferRegistration(false/*params->deferRegistration*/),
195 stageTracing(params
->stageTracing
),
198 ThreadID active_threads
;
201 resPool
= new ResourcePool(this, params
);
203 // Resize for Multithreading CPUs
204 thread
.resize(numThreads
);
209 active_threads
= params
->workload
.size();
211 if (active_threads
> MaxThreads
) {
212 panic("Workload Size too large. Increase the 'MaxThreads'"
213 "in your InOrder implementation or "
214 "edit your workload size.");
218 if (active_threads
> 1) {
219 threadModel
= (InOrderCPU::ThreadModel
) params
->threadModel
;
221 if (threadModel
== SMT
) {
222 DPRINTF(InOrderCPU
, "Setting Thread Model to SMT.\n");
223 } else if (threadModel
== SwitchOnCacheMiss
) {
224 DPRINTF(InOrderCPU
, "Setting Thread Model to "
225 "Switch On Cache Miss\n");
229 threadModel
= Single
;
236 // Bind the fetch & data ports from the resource pool.
237 fetchPortIdx
= resPool
->getPortIdx(params
->fetchMemPort
);
238 if (fetchPortIdx
== 0) {
239 fatal("Unable to find port to fetch instructions from.\n");
242 dataPortIdx
= resPool
->getPortIdx(params
->dataMemPort
);
243 if (dataPortIdx
== 0) {
244 fatal("Unable to find port for data.\n");
247 for (ThreadID tid
= 0; tid
< numThreads
; ++tid
) {
249 // SMT is not supported in FS mode yet.
250 assert(numThreads
== 1);
251 thread
[tid
] = new Thread(this, 0);
253 if (tid
< (ThreadID
)params
->workload
.size()) {
254 DPRINTF(InOrderCPU
, "Workload[%i] process is %#x\n",
255 tid
, params
->workload
[tid
]->prog_fname
);
257 new Thread(this, tid
, params
->workload
[tid
]);
259 //Allocate Empty thread so M5 can use later
260 //when scheduling threads to CPU
261 Process
* dummy_proc
= params
->workload
[0];
262 thread
[tid
] = new Thread(this, tid
, dummy_proc
);
265 // Eventually set this with parameters...
269 // Setup the TC that will serve as the interface to the threads/CPU.
270 InOrderThreadContext
*tc
= new InOrderThreadContext
;
272 tc
->thread
= thread
[tid
];
274 // Give the thread the TC.
275 thread
[tid
]->tc
= tc
;
276 thread
[tid
]->setFuncExeInst(0);
277 globalSeqNum
[tid
] = 1;
279 // Add the TC to the CPU's list of TC's.
280 this->threadContexts
.push_back(tc
);
283 // Initialize TimeBuffer Stage Queues
284 for (int stNum
=0; stNum
< NumStages
- 1; stNum
++) {
285 stageQueue
[stNum
] = new StageQueue(NumStages
, NumStages
);
286 stageQueue
[stNum
]->id(stNum
);
290 // Set Up Pipeline Stages
291 for (int stNum
=0; stNum
< NumStages
; stNum
++) {
293 pipelineStage
[stNum
] = new FirstStage(params
, stNum
);
295 pipelineStage
[stNum
] = new PipelineStage(params
, stNum
);
297 pipelineStage
[stNum
]->setCPU(this);
298 pipelineStage
[stNum
]->setActiveThreads(&activeThreads
);
299 pipelineStage
[stNum
]->setTimeBuffer(&timeBuffer
);
301 // Take Care of 1st/Nth stages
303 pipelineStage
[stNum
]->setPrevStageQueue(stageQueue
[stNum
- 1]);
304 if (stNum
< NumStages
- 1)
305 pipelineStage
[stNum
]->setNextStageQueue(stageQueue
[stNum
]);
308 // Initialize thread specific variables
309 for (ThreadID tid
= 0; tid
< numThreads
; tid
++) {
310 archRegDepMap
[tid
].setCPU(this);
312 nonSpecInstActive
[tid
] = false;
313 nonSpecSeqNum
[tid
] = 0;
315 squashSeqNum
[tid
] = MaxAddr
;
316 lastSquashCycle
[tid
] = 0;
318 memset(intRegs
[tid
], 0, sizeof(intRegs
[tid
]));
319 memset(floatRegs
.i
[tid
], 0, sizeof(floatRegs
.i
[tid
]));
322 // Define dummy instructions and resource requests to be used.
323 dummyInst
[tid
] = new InOrderDynInst(this,
329 dummyReq
[tid
] = new ResourceRequest(resPool
->getResource(0));
332 dummyReqInst
= new InOrderDynInst(this, NULL
, 0, 0, 0);
333 dummyReqInst
->setSquashed();
334 dummyReqInst
->resetInstCount();
336 dummyBufferInst
= new InOrderDynInst(this, NULL
, 0, 0, 0);
337 dummyBufferInst
->setSquashed();
338 dummyBufferInst
->resetInstCount();
340 endOfSkedIt
= skedCache
.end();
341 frontEndSked
= createFrontEndSked();
343 lastRunningCycle
= curTick();
345 // Reset CPU to reset state.
347 Fault resetFault
= new ResetFault();
348 resetFault
->invoke(tcBase());
352 // Schedule First Tick Event, CPU will reschedule itself from here on out.
353 scheduleTickEvent(0);
356 InOrderCPU::~InOrderCPU()
360 std::map
<SkedID
, ThePipeline::RSkedPtr
>::iterator sked_it
=
362 std::map
<SkedID
, ThePipeline::RSkedPtr
>::iterator sked_end
=
365 while (sked_it
!= sked_end
) {
366 delete (*sked_it
).second
;
372 std::map
<InOrderCPU::SkedID
, ThePipeline::RSkedPtr
> InOrderCPU::skedCache
;
375 InOrderCPU::createFrontEndSked()
377 RSkedPtr res_sked
= new ResourceSked();
379 StageScheduler
F(res_sked
, stage_num
++);
380 StageScheduler
D(res_sked
, stage_num
++);
383 F
.needs(FetchSeq
, FetchSeqUnit::AssignNextPC
);
384 F
.needs(ICache
, FetchUnit::InitiateFetch
);
387 D
.needs(ICache
, FetchUnit::CompleteFetch
);
388 D
.needs(Decode
, DecodeUnit::DecodeInst
);
389 D
.needs(BPred
, BranchPredictor::PredictBranch
);
390 D
.needs(FetchSeq
, FetchSeqUnit::UpdateTargetPC
);
393 DPRINTF(SkedCache
, "Resource Sked created for instruction \"front_end\"\n");
399 InOrderCPU::createBackEndSked(DynInstPtr inst
)
401 RSkedPtr res_sked
= lookupSked(inst
);
402 if (res_sked
!= NULL
) {
403 DPRINTF(SkedCache
, "Found %s in sked cache.\n",
407 res_sked
= new ResourceSked();
410 int stage_num
= ThePipeline::BackEndStartStage
;
411 StageScheduler
X(res_sked
, stage_num
++);
412 StageScheduler
M(res_sked
, stage_num
++);
413 StageScheduler
W(res_sked
, stage_num
++);
415 if (!inst
->staticInst
) {
416 warn_once("Static Instruction Object Not Set. Can't Create"
417 " Back End Schedule");
422 for (int idx
=0; idx
< inst
->numSrcRegs(); idx
++) {
423 if (!idx
|| !inst
->isStore()) {
424 X
.needs(RegManager
, UseDefUnit::ReadSrcReg
, idx
);
428 if ( inst
->isNonSpeculative() ) {
429 // skip execution of non speculative insts until later
430 } else if ( inst
->isMemRef() ) {
431 if ( inst
->isLoad() ) {
432 X
.needs(AGEN
, AGENUnit::GenerateAddr
);
434 } else if (inst
->opClass() == IntMultOp
|| inst
->opClass() == IntDivOp
) {
435 X
.needs(MDU
, MultDivUnit::StartMultDiv
);
437 X
.needs(ExecUnit
, ExecutionUnit::ExecuteInst
);
440 if (inst
->opClass() == IntMultOp
|| inst
->opClass() == IntDivOp
) {
441 X
.needs(MDU
, MultDivUnit::EndMultDiv
);
445 if ( inst
->isLoad() ) {
446 M
.needs(DCache
, CacheUnit::InitiateReadData
);
447 } else if ( inst
->isStore() ) {
448 if ( inst
->numSrcRegs() >= 2 ) {
449 M
.needs(RegManager
, UseDefUnit::ReadSrcReg
, 1);
451 M
.needs(AGEN
, AGENUnit::GenerateAddr
);
452 M
.needs(DCache
, CacheUnit::InitiateWriteData
);
457 if ( inst
->isLoad() ) {
458 W
.needs(DCache
, CacheUnit::CompleteReadData
);
459 } else if ( inst
->isStore() ) {
460 W
.needs(DCache
, CacheUnit::CompleteWriteData
);
463 if ( inst
->isNonSpeculative() ) {
464 if ( inst
->isMemRef() ) fatal("Non-Speculative Memory Instruction");
465 W
.needs(ExecUnit
, ExecutionUnit::ExecuteInst
);
468 W
.needs(Grad
, GraduationUnit::GraduateInst
);
470 for (int idx
=0; idx
< inst
->numDestRegs(); idx
++) {
471 W
.needs(RegManager
, UseDefUnit::WriteDestReg
, idx
);
474 // Insert Back Schedule into our cache of
475 // resource schedules
476 addToSkedCache(inst
, res_sked
);
478 DPRINTF(SkedCache
, "Back End Sked Created for instruction: %s (%08p)\n",
479 inst
->instName(), inst
->getMachInst());
486 InOrderCPU::regStats()
488 /* Register the Resource Pool's stats here.*/
491 /* Register for each Pipeline Stage */
492 for (int stage_num
=0; stage_num
< ThePipeline::NumStages
; stage_num
++) {
493 pipelineStage
[stage_num
]->regStats();
496 /* Register any of the InOrderCPU's stats here.*/
498 .name(name() + ".instsPerContextSwitch")
499 .desc("Instructions Committed Per Context Switch")
500 .prereq(instsPerCtxtSwitch
);
503 .name(name() + ".contextSwitches")
504 .desc("Number of context switches");
507 .name(name() + ".comLoads")
508 .desc("Number of Load instructions committed");
511 .name(name() + ".comStores")
512 .desc("Number of Store instructions committed");
515 .name(name() + ".comBranches")
516 .desc("Number of Branches instructions committed");
519 .name(name() + ".comNops")
520 .desc("Number of Nop instructions committed");
523 .name(name() + ".comNonSpec")
524 .desc("Number of Non-Speculative instructions committed");
527 .name(name() + ".comInts")
528 .desc("Number of Integer instructions committed");
531 .name(name() + ".comFloats")
532 .desc("Number of Floating Point instructions committed");
535 .name(name() + ".timesIdled")
536 .desc("Number of times that the entire CPU went into an idle state and"
537 " unscheduled itself")
541 .name(name() + ".idleCycles")
542 .desc("Number of cycles cpu's stages were not processed");
545 .name(name() + ".runCycles")
546 .desc("Number of cycles cpu stages are processed.");
549 .name(name() + ".activity")
550 .desc("Percentage of cycles cpu is active")
552 activity
= (runCycles
/ numCycles
) * 100;
556 .name(name() + ".threadCycles")
557 .desc("Total Number of Cycles A Thread Was Active in CPU (Per-Thread)");
560 .name(name() + ".smtCycles")
561 .desc("Total number of cycles that the CPU was in SMT-mode");
565 .name(name() + ".committedInsts")
566 .desc("Number of Instructions Simulated (Per-Thread)");
570 .name(name() + ".smtCommittedInsts")
571 .desc("Number of SMT Instructions Simulated (Per-Thread)");
574 .name(name() + ".committedInsts_total")
575 .desc("Number of Instructions Simulated (Total)");
578 .name(name() + ".cpi")
579 .desc("CPI: Cycles Per Instruction (Per-Thread)")
581 cpi
= numCycles
/ committedInsts
;
584 .name(name() + ".smt_cpi")
585 .desc("CPI: Total SMT-CPI")
587 smtCpi
= smtCycles
/ smtCommittedInsts
;
590 .name(name() + ".cpi_total")
591 .desc("CPI: Total CPI of All Threads")
593 totalCpi
= numCycles
/ totalCommittedInsts
;
596 .name(name() + ".ipc")
597 .desc("IPC: Instructions Per Cycle (Per-Thread)")
599 ipc
= committedInsts
/ numCycles
;
602 .name(name() + ".smt_ipc")
603 .desc("IPC: Total SMT-IPC")
605 smtIpc
= smtCommittedInsts
/ smtCycles
;
608 .name(name() + ".ipc_total")
609 .desc("IPC: Total IPC of All Threads")
611 totalIpc
= totalCommittedInsts
/ numCycles
;
620 DPRINTF(InOrderCPU
, "\n\nInOrderCPU: Ticking main, InOrderCPU.\n");
624 bool pipes_idle
= true;
626 //Tick each of the stages
627 for (int stNum
=NumStages
- 1; stNum
>= 0 ; stNum
--) {
628 pipelineStage
[stNum
]->tick();
630 pipes_idle
= pipes_idle
&& pipelineStage
[stNum
]->idle
;
638 // Now advance the time buffers one tick
639 timeBuffer
.advance();
640 for (int sqNum
=0; sqNum
< NumStages
- 1; sqNum
++) {
641 stageQueue
[sqNum
]->advance();
643 activityRec
.advance();
645 // Any squashed events, or insts then remove them now
646 cleanUpRemovedEvents();
647 cleanUpRemovedInsts();
649 // Re-schedule CPU for this cycle
650 if (!tickEvent
.scheduled()) {
651 if (_status
== SwitchedOut
) {
653 lastRunningCycle
= curTick();
654 } else if (!activityRec
.active()) {
655 DPRINTF(InOrderCPU
, "sleeping CPU.\n");
656 lastRunningCycle
= curTick();
659 //Tick next_tick = curTick() + cycles(1);
660 //tickEvent.schedule(next_tick);
661 schedule(&tickEvent
, nextCycle(curTick() + 1));
662 DPRINTF(InOrderCPU
, "Scheduled CPU for next tick @ %i.\n",
663 nextCycle(curTick() + 1));
668 updateThreadPriority();
675 if (!deferRegistration
) {
676 registerThreadContexts();
679 // Set inSyscall so that the CPU doesn't squash when initially
680 // setting up registers.
681 for (ThreadID tid
= 0; tid
< numThreads
; ++tid
)
682 thread
[tid
]->inSyscall
= true;
685 for (ThreadID tid
= 0; tid
< numThreads
; tid
++) {
686 ThreadContext
*src_tc
= threadContexts
[tid
];
687 TheISA::initCPU(src_tc
, src_tc
->contextId());
692 for (ThreadID tid
= 0; tid
< numThreads
; ++tid
)
693 thread
[tid
]->inSyscall
= false;
695 // Call Initializiation Routine for Resource Pool
700 InOrderCPU::getPort(const std::string
&if_name
, int idx
)
702 return resPool
->getPort(if_name
, idx
);
707 InOrderCPU::hwrei(ThreadID tid
)
709 panic("hwrei: Unimplemented");
716 InOrderCPU::simPalCheck(int palFunc
, ThreadID tid
)
718 panic("simPalCheck: Unimplemented");
725 InOrderCPU::getInterrupts()
727 // Check if there are any outstanding interrupts
728 return interrupts
->getInterrupt(threadContexts
[0]);
733 InOrderCPU::processInterrupts(Fault interrupt
)
735 // Check for interrupts here. For now can copy the code that
736 // exists within isa_fullsys_traits.hh. Also assume that thread 0
737 // is the one that handles the interrupts.
738 // @todo: Possibly consolidate the interrupt checking code.
739 // @todo: Allow other threads to handle interrupts.
741 assert(interrupt
!= NoFault
);
742 interrupts
->updateIntrInfo(threadContexts
[0]);
744 DPRINTF(InOrderCPU
, "Interrupt %s being handled\n", interrupt
->name());
746 // Note: Context ID ok here? Impl. of FS mode needs to revisit this
747 trap(interrupt
, threadContexts
[0]->contextId(), dummyBufferInst
);
752 InOrderCPU::updateMemPorts()
754 // Update all ThreadContext's memory ports (Functional/Virtual
756 ThreadID size
= thread
.size();
757 for (ThreadID i
= 0; i
< size
; ++i
)
758 thread
[i
]->connectMemPorts(thread
[i
]->getTC());
763 InOrderCPU::trap(Fault fault
, ThreadID tid
, DynInstPtr inst
, int delay
)
765 //@ Squash Pipeline during TRAP
766 scheduleCpuEvent(Trap
, fault
, tid
, inst
, delay
);
770 InOrderCPU::trapCPU(Fault fault
, ThreadID tid
, DynInstPtr inst
)
772 fault
->invoke(tcBase(tid
), inst
->staticInst
);
776 InOrderCPU::squashFromMemStall(DynInstPtr inst
, ThreadID tid
, int delay
)
778 scheduleCpuEvent(SquashFromMemStall
, NoFault
, tid
, inst
, delay
);
783 InOrderCPU::squashDueToMemStall(int stage_num
, InstSeqNum seq_num
,
786 DPRINTF(InOrderCPU
, "Squashing Pipeline Stages Due to Memory Stall...\n");
788 // Squash all instructions in each stage including
789 // instruction that caused the squash (seq_num - 1)
790 // NOTE: The stage bandwidth needs to be cleared so thats why
791 // the stalling instruction is squashed as well. The stalled
792 // instruction is previously placed in another intermediate buffer
793 // while it's stall is being handled.
794 InstSeqNum squash_seq_num
= seq_num
- 1;
796 for (int stNum
=stage_num
; stNum
>= 0 ; stNum
--) {
797 pipelineStage
[stNum
]->squashDueToMemStall(squash_seq_num
, tid
);
802 InOrderCPU::scheduleCpuEvent(CPUEventType c_event
, Fault fault
,
803 ThreadID tid
, DynInstPtr inst
,
804 unsigned delay
, unsigned event_pri_offset
)
806 CPUEvent
*cpu_event
= new CPUEvent(this, c_event
, fault
, tid
, inst
,
809 Tick sked_tick
= nextCycle(curTick() + ticks(delay
));
811 DPRINTF(InOrderCPU
, "Scheduling CPU Event (%s) for cycle %i, [tid:%i].\n",
812 eventNames
[c_event
], curTick() + delay
, tid
);
813 schedule(cpu_event
, sked_tick
);
815 cpu_event
->process();
816 cpuEventRemoveList
.push(cpu_event
);
819 // Broadcast event to the Resource Pool
820 // Need to reset tid just in case this is a dummy instruction
822 resPool
->scheduleEvent(c_event
, inst
, 0, 0, tid
);
826 InOrderCPU::isThreadActive(ThreadID tid
)
828 list
<ThreadID
>::iterator isActive
=
829 std::find(activeThreads
.begin(), activeThreads
.end(), tid
);
831 return (isActive
!= activeThreads
.end());
835 InOrderCPU::isThreadReady(ThreadID tid
)
837 list
<ThreadID
>::iterator isReady
=
838 std::find(readyThreads
.begin(), readyThreads
.end(), tid
);
840 return (isReady
!= readyThreads
.end());
844 InOrderCPU::isThreadSuspended(ThreadID tid
)
846 list
<ThreadID
>::iterator isSuspended
=
847 std::find(suspendedThreads
.begin(), suspendedThreads
.end(), tid
);
849 return (isSuspended
!= suspendedThreads
.end());
853 InOrderCPU::activateNextReadyThread()
855 if (readyThreads
.size() >= 1) {
856 ThreadID ready_tid
= readyThreads
.front();
858 // Activate in Pipeline
859 activateThread(ready_tid
);
861 // Activate in Resource Pool
862 resPool
->activateAll(ready_tid
);
864 list
<ThreadID
>::iterator ready_it
=
865 std::find(readyThreads
.begin(), readyThreads
.end(), ready_tid
);
866 readyThreads
.erase(ready_it
);
869 "Attempting to activate new thread, but No Ready Threads to"
872 "Unable to switch to next active thread.\n");
877 InOrderCPU::activateThread(ThreadID tid
)
879 if (isThreadSuspended(tid
)) {
881 "Removing [tid:%i] from suspended threads list.\n", tid
);
883 list
<ThreadID
>::iterator susp_it
=
884 std::find(suspendedThreads
.begin(), suspendedThreads
.end(),
886 suspendedThreads
.erase(susp_it
);
889 if (threadModel
== SwitchOnCacheMiss
&&
890 numActiveThreads() == 1) {
892 "Ignoring activation of [tid:%i], since [tid:%i] is "
893 "already running.\n", tid
, activeThreadId());
895 DPRINTF(InOrderCPU
,"Placing [tid:%i] on ready threads list\n",
898 readyThreads
.push_back(tid
);
900 } else if (!isThreadActive(tid
)) {
902 "Adding [tid:%i] to active threads list.\n", tid
);
903 activeThreads
.push_back(tid
);
905 activateThreadInPipeline(tid
);
907 thread
[tid
]->lastActivate
= curTick();
909 tcBase(tid
)->setStatus(ThreadContext::Active
);
918 InOrderCPU::activateThreadInPipeline(ThreadID tid
)
920 for (int stNum
=0; stNum
< NumStages
; stNum
++) {
921 pipelineStage
[stNum
]->activateThread(tid
);
926 InOrderCPU::deactivateContext(ThreadID tid
, int delay
)
928 DPRINTF(InOrderCPU
,"[tid:%i]: Deactivating ...\n", tid
);
930 scheduleCpuEvent(DeactivateThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
932 // Be sure to signal that there's some activity so the CPU doesn't
933 // deschedule itself.
934 activityRec
.activity();
940 InOrderCPU::deactivateThread(ThreadID tid
)
942 DPRINTF(InOrderCPU
, "[tid:%i]: Calling deactivate thread.\n", tid
);
944 if (isThreadActive(tid
)) {
945 DPRINTF(InOrderCPU
,"[tid:%i]: Removing from active threads list\n",
947 list
<ThreadID
>::iterator thread_it
=
948 std::find(activeThreads
.begin(), activeThreads
.end(), tid
);
950 removePipelineStalls(*thread_it
);
952 activeThreads
.erase(thread_it
);
954 // Ideally, this should be triggered from the
955 // suspendContext/Thread functions
956 tcBase(tid
)->setStatus(ThreadContext::Suspended
);
959 assert(!isThreadActive(tid
));
963 InOrderCPU::removePipelineStalls(ThreadID tid
)
965 DPRINTF(InOrderCPU
,"[tid:%i]: Removing all pipeline stalls\n",
968 for (int stNum
= 0; stNum
< NumStages
; stNum
++) {
969 pipelineStage
[stNum
]->removeStalls(tid
);
975 InOrderCPU::updateThreadPriority()
977 if (activeThreads
.size() > 1)
979 //DEFAULT TO ROUND ROBIN SCHEME
980 //e.g. Move highest priority to end of thread list
981 list
<ThreadID
>::iterator list_begin
= activeThreads
.begin();
982 list
<ThreadID
>::iterator list_end
= activeThreads
.end();
984 unsigned high_thread
= *list_begin
;
986 activeThreads
.erase(list_begin
);
988 activeThreads
.push_back(high_thread
);
993 InOrderCPU::tickThreadStats()
995 /** Keep track of cycles that each thread is active */
996 list
<ThreadID
>::iterator thread_it
= activeThreads
.begin();
997 while (thread_it
!= activeThreads
.end()) {
998 threadCycles
[*thread_it
]++;
1002 // Keep track of cycles where SMT is active
1003 if (activeThreads
.size() > 1) {
1009 InOrderCPU::activateContext(ThreadID tid
, int delay
)
1011 DPRINTF(InOrderCPU
,"[tid:%i]: Activating ...\n", tid
);
1014 scheduleCpuEvent(ActivateThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1016 // Be sure to signal that there's some activity so the CPU doesn't
1017 // deschedule itself.
1018 activityRec
.activity();
1024 InOrderCPU::activateNextReadyContext(int delay
)
1026 DPRINTF(InOrderCPU
,"Activating next ready thread\n");
1028 // NOTE: Add 5 to the event priority so that we always activate
1029 // threads after we've finished deactivating, squashing,etc.
1031 scheduleCpuEvent(ActivateNextReadyThread
, NoFault
, 0/*tid*/, dummyInst
[0],
1034 // Be sure to signal that there's some activity so the CPU doesn't
1035 // deschedule itself.
1036 activityRec
.activity();
1042 InOrderCPU::haltContext(ThreadID tid
, int delay
)
1044 DPRINTF(InOrderCPU
, "[tid:%i]: Calling Halt Context...\n", tid
);
1046 scheduleCpuEvent(HaltThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1048 activityRec
.activity();
1052 InOrderCPU::haltThread(ThreadID tid
)
1054 DPRINTF(InOrderCPU
, "[tid:%i]: Placing on Halted Threads List...\n", tid
);
1055 deactivateThread(tid
);
1056 squashThreadInPipeline(tid
);
1057 haltedThreads
.push_back(tid
);
1059 tcBase(tid
)->setStatus(ThreadContext::Halted
);
1061 if (threadModel
== SwitchOnCacheMiss
) {
1062 activateNextReadyContext();
1067 InOrderCPU::suspendContext(ThreadID tid
, int delay
)
1069 scheduleCpuEvent(SuspendThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1073 InOrderCPU::suspendThread(ThreadID tid
)
1075 DPRINTF(InOrderCPU
, "[tid:%i]: Placing on Suspended Threads List...\n",
1077 deactivateThread(tid
);
1078 suspendedThreads
.push_back(tid
);
1079 thread
[tid
]->lastSuspend
= curTick();
1081 tcBase(tid
)->setStatus(ThreadContext::Suspended
);
1085 InOrderCPU::squashThreadInPipeline(ThreadID tid
)
1087 //Squash all instructions in each stage
1088 for (int stNum
=NumStages
- 1; stNum
>= 0 ; stNum
--) {
1089 pipelineStage
[stNum
]->squash(0 /*seq_num*/, tid
);
1094 InOrderCPU::getPipeStage(int stage_num
)
1096 return pipelineStage
[stage_num
];
1100 InOrderCPU::readIntReg(int reg_idx
, ThreadID tid
)
1102 return intRegs
[tid
][reg_idx
];
1106 InOrderCPU::readFloatReg(int reg_idx
, ThreadID tid
)
1108 return floatRegs
.f
[tid
][reg_idx
];
1112 InOrderCPU::readFloatRegBits(int reg_idx
, ThreadID tid
)
1114 return floatRegs
.i
[tid
][reg_idx
];
1118 InOrderCPU::setIntReg(int reg_idx
, uint64_t val
, ThreadID tid
)
1120 intRegs
[tid
][reg_idx
] = val
;
1125 InOrderCPU::setFloatReg(int reg_idx
, FloatReg val
, ThreadID tid
)
1127 floatRegs
.f
[tid
][reg_idx
] = val
;
1132 InOrderCPU::setFloatRegBits(int reg_idx
, FloatRegBits val
, ThreadID tid
)
1134 floatRegs
.i
[tid
][reg_idx
] = val
;
1138 InOrderCPU::readRegOtherThread(unsigned reg_idx
, ThreadID tid
)
1140 // If Default value is set, then retrieve target thread
1141 if (tid
== InvalidThreadID
) {
1142 tid
= TheISA::getTargetThread(tcBase(tid
));
1145 if (reg_idx
< FP_Base_DepTag
) {
1146 // Integer Register File
1147 return readIntReg(reg_idx
, tid
);
1148 } else if (reg_idx
< Ctrl_Base_DepTag
) {
1149 // Float Register File
1150 reg_idx
-= FP_Base_DepTag
;
1151 return readFloatRegBits(reg_idx
, tid
);
1153 reg_idx
-= Ctrl_Base_DepTag
;
1154 return readMiscReg(reg_idx
, tid
); // Misc. Register File
1158 InOrderCPU::setRegOtherThread(unsigned reg_idx
, const MiscReg
&val
,
1161 // If Default value is set, then retrieve target thread
1162 if (tid
== InvalidThreadID
) {
1163 tid
= TheISA::getTargetThread(tcBase(tid
));
1166 if (reg_idx
< FP_Base_DepTag
) { // Integer Register File
1167 setIntReg(reg_idx
, val
, tid
);
1168 } else if (reg_idx
< Ctrl_Base_DepTag
) { // Float Register File
1169 reg_idx
-= FP_Base_DepTag
;
1170 setFloatRegBits(reg_idx
, val
, tid
);
1172 reg_idx
-= Ctrl_Base_DepTag
;
1173 setMiscReg(reg_idx
, val
, tid
); // Misc. Register File
1178 InOrderCPU::readMiscRegNoEffect(int misc_reg
, ThreadID tid
)
1180 return isa
[tid
].readMiscRegNoEffect(misc_reg
);
1184 InOrderCPU::readMiscReg(int misc_reg
, ThreadID tid
)
1186 return isa
[tid
].readMiscReg(misc_reg
, tcBase(tid
));
1190 InOrderCPU::setMiscRegNoEffect(int misc_reg
, const MiscReg
&val
, ThreadID tid
)
1192 isa
[tid
].setMiscRegNoEffect(misc_reg
, val
);
1196 InOrderCPU::setMiscReg(int misc_reg
, const MiscReg
&val
, ThreadID tid
)
1198 isa
[tid
].setMiscReg(misc_reg
, val
, tcBase(tid
));
1203 InOrderCPU::addInst(DynInstPtr
&inst
)
1205 ThreadID tid
= inst
->readTid();
1207 instList
[tid
].push_back(inst
);
1209 return --(instList
[tid
].end());
1213 InOrderCPU::updateContextSwitchStats()
1215 // Set Average Stat Here, then reset to 0
1216 instsPerCtxtSwitch
= instsPerSwitch
;
1222 InOrderCPU::instDone(DynInstPtr inst
, ThreadID tid
)
1224 // Set the CPU's PCs - This contributes to the precise state of the CPU
1225 // which can be used when restoring a thread to the CPU after after any
1226 // type of context switching activity (fork, exception, etc.)
1227 pcState(inst
->pcState(), tid
);
1229 if (inst
->isControl()) {
1230 thread
[tid
]->lastGradIsBranch
= true;
1231 thread
[tid
]->lastBranchPC
= inst
->pcState();
1232 TheISA::advancePC(thread
[tid
]->lastBranchPC
, inst
->staticInst
);
1234 thread
[tid
]->lastGradIsBranch
= false;
1238 // Finalize Trace Data For Instruction
1239 if (inst
->traceData
) {
1240 //inst->traceData->setCycle(curTick());
1241 inst
->traceData
->setFetchSeq(inst
->seqNum
);
1242 //inst->traceData->setCPSeq(cpu->tcBase(tid)->numInst);
1243 inst
->traceData
->dump();
1244 delete inst
->traceData
;
1245 inst
->traceData
= NULL
;
1248 // Increment active thread's instruction count
1251 // Increment thread-state's instruction count
1252 thread
[tid
]->numInst
++;
1254 // Increment thread-state's instruction stats
1255 thread
[tid
]->numInsts
++;
1257 // Count committed insts per thread stats
1258 committedInsts
[tid
]++;
1260 // Count total insts committed stat
1261 totalCommittedInsts
++;
1263 // Count SMT-committed insts per thread stat
1264 if (numActiveThreads() > 1) {
1265 smtCommittedInsts
[tid
]++;
1268 // Instruction-Mix Stats
1269 if (inst
->isLoad()) {
1271 } else if (inst
->isStore()) {
1273 } else if (inst
->isControl()) {
1275 } else if (inst
->isNop()) {
1277 } else if (inst
->isNonSpeculative()) {
1279 } else if (inst
->isInteger()) {
1281 } else if (inst
->isFloating()) {
1285 // Check for instruction-count-based events.
1286 comInstEventQueue
[tid
]->serviceEvents(thread
[tid
]->numInst
);
1288 // Broadcast to other resources an instruction
1289 // has been completed
1290 resPool
->scheduleEvent((CPUEventType
)ResourcePool::InstGraduated
, inst
,
1293 // Finally, remove instruction from CPU
1297 // currently unused function, but substitute repetitive code w/this function
1300 InOrderCPU::addToRemoveList(DynInstPtr
&inst
)
1302 removeInstsThisCycle
= true;
1303 if (!inst
->isRemoveList()) {
1304 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1305 "[sn:%lli] to remove list\n",
1306 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1307 inst
->setRemoveList();
1308 removeList
.push(inst
->getInstListIt());
1310 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i] PC %s "
1311 "[sn:%lli], already remove list\n",
1312 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1318 InOrderCPU::removeInst(DynInstPtr
&inst
)
1320 DPRINTF(InOrderCPU
, "Removing graduated instruction [tid:%i] PC %s "
1322 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1324 removeInstsThisCycle
= true;
1326 // Remove the instruction.
1327 if (!inst
->isRemoveList()) {
1328 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1329 "[sn:%lli] to remove list\n",
1330 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1331 inst
->setRemoveList();
1332 removeList
.push(inst
->getInstListIt());
1334 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i] PC %s "
1335 "[sn:%lli], already on remove list\n",
1336 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1342 InOrderCPU::removeInstsUntil(const InstSeqNum
&seq_num
, ThreadID tid
)
1344 //assert(!instList[tid].empty());
1346 removeInstsThisCycle
= true;
1348 ListIt inst_iter
= instList
[tid
].end();
1352 DPRINTF(InOrderCPU
, "Squashing instructions from CPU instruction "
1353 "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1354 tid
, seq_num
, (*inst_iter
)->seqNum
);
1356 while ((*inst_iter
)->seqNum
> seq_num
) {
1358 bool break_loop
= (inst_iter
== instList
[tid
].begin());
1360 squashInstIt(inst_iter
, tid
);
1371 InOrderCPU::squashInstIt(const ListIt
&instIt
, ThreadID tid
)
1373 if ((*instIt
)->threadNumber
== tid
) {
1374 DPRINTF(InOrderCPU
, "Squashing instruction, "
1375 "[tid:%i] [sn:%lli] PC %s\n",
1376 (*instIt
)->threadNumber
,
1378 (*instIt
)->pcState());
1380 (*instIt
)->setSquashed();
1382 if (!(*instIt
)->isRemoveList()) {
1383 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1384 "[sn:%lli] to remove list\n",
1385 (*instIt
)->threadNumber
, (*instIt
)->pcState(),
1387 (*instIt
)->setRemoveList();
1388 removeList
.push(instIt
);
1390 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i]"
1391 " PC %s [sn:%lli], already on remove list\n",
1392 (*instIt
)->threadNumber
, (*instIt
)->pcState(),
1402 InOrderCPU::cleanUpRemovedInsts()
1404 while (!removeList
.empty()) {
1405 DPRINTF(InOrderCPU
, "Removing instruction, "
1406 "[tid:%i] [sn:%lli] PC %s\n",
1407 (*removeList
.front())->threadNumber
,
1408 (*removeList
.front())->seqNum
,
1409 (*removeList
.front())->pcState());
1411 DynInstPtr inst
= *removeList
.front();
1412 ThreadID tid
= inst
->threadNumber
;
1414 // Remove From Register Dependency Map, If Necessary
1415 archRegDepMap
[(*removeList
.front())->threadNumber
].
1416 remove((*removeList
.front()));
1419 // Clear if Non-Speculative
1420 if (inst
->staticInst
&&
1421 inst
->seqNum
== nonSpecSeqNum
[tid
] &&
1422 nonSpecInstActive
[tid
] == true) {
1423 nonSpecInstActive
[tid
] = false;
1426 instList
[tid
].erase(removeList
.front());
1431 removeInstsThisCycle
= false;
1435 InOrderCPU::cleanUpRemovedEvents()
1437 while (!cpuEventRemoveList
.empty()) {
1438 Event
*cpu_event
= cpuEventRemoveList
.front();
1439 cpuEventRemoveList
.pop();
1446 InOrderCPU::dumpInsts()
1450 ListIt inst_list_it
= instList
[0].begin();
1452 cprintf("Dumping Instruction List\n");
1454 while (inst_list_it
!= instList
[0].end()) {
1455 cprintf("Instruction:%i\nPC:%s\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1457 num
, (*inst_list_it
)->pcState(),
1458 (*inst_list_it
)->threadNumber
,
1459 (*inst_list_it
)->seqNum
, (*inst_list_it
)->isIssued(),
1460 (*inst_list_it
)->isSquashed());
1467 InOrderCPU::wakeCPU()
1469 if (/*activityRec.active() || */tickEvent
.scheduled()) {
1470 DPRINTF(Activity
, "CPU already running.\n");
1474 DPRINTF(Activity
, "Waking up CPU\n");
1476 Tick extra_cycles
= tickToCycles((curTick() - 1) - lastRunningCycle
);
1478 idleCycles
+= extra_cycles
;
1479 for (int stage_num
= 0; stage_num
< NumStages
; stage_num
++) {
1480 pipelineStage
[stage_num
]->idleCycles
+= extra_cycles
;
1483 numCycles
+= extra_cycles
;
1485 schedule(&tickEvent
, nextCycle(curTick()));
1491 InOrderCPU::wakeup()
1493 if (thread
[0]->status() != ThreadContext::Suspended
)
1498 DPRINTF(Quiesce
, "Suspended Processor woken\n");
1499 threadContexts
[0]->activate();
1505 InOrderCPU::syscall(int64_t callnum
, ThreadID tid
)
1507 DPRINTF(InOrderCPU
, "[tid:%i] Executing syscall().\n\n", tid
);
1509 DPRINTF(Activity
,"Activity: syscall() called.\n");
1511 // Temporarily increase this by one to account for the syscall
1513 ++(this->thread
[tid
]->funcExeInst
);
1515 // Execute the actual syscall.
1516 this->thread
[tid
]->syscall(callnum
);
1518 // Decrease funcExeInst by one as the normal commit will handle
1520 --(this->thread
[tid
]->funcExeInst
);
1522 // Clear Non-Speculative Block Variable
1523 nonSpecInstActive
[tid
] = false;
1528 InOrderCPU::getITBPtr()
1530 CacheUnit
*itb_res
=
1531 dynamic_cast<CacheUnit
*>(resPool
->getResource(fetchPortIdx
));
1532 return itb_res
->tlb();
1537 InOrderCPU::getDTBPtr()
1539 CacheUnit
*dtb_res
=
1540 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1541 return dtb_res
->tlb();
1545 InOrderCPU::read(DynInstPtr inst
, Addr addr
,
1546 uint8_t *data
, unsigned size
, unsigned flags
)
1548 //@TODO: Generalize name "CacheUnit" to "MemUnit" just in case
1549 // you want to run w/out caches?
1550 CacheUnit
*cache_res
=
1551 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1553 return cache_res
->read(inst
, addr
, data
, size
, flags
);
1557 InOrderCPU::write(DynInstPtr inst
, uint8_t *data
, unsigned size
,
1558 Addr addr
, unsigned flags
, uint64_t *write_res
)
1560 //@TODO: Generalize name "CacheUnit" to "MemUnit" just in case
1561 // you want to run w/out caches?
1562 CacheUnit
*cache_res
=
1563 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1564 return cache_res
->write(inst
, data
, size
, addr
, flags
, write_res
);