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 "base/bigint.hh"
36 #include "config/full_system.hh"
37 #include "config/the_isa.hh"
38 #include "cpu/inorder/resources/resource_list.hh"
39 #include "cpu/inorder/cpu.hh"
40 #include "cpu/inorder/first_stage.hh"
41 #include "cpu/inorder/inorder_dyn_inst.hh"
42 #include "cpu/inorder/pipeline_traits.hh"
43 #include "cpu/inorder/resource_pool.hh"
44 #include "cpu/inorder/thread_context.hh"
45 #include "cpu/inorder/thread_state.hh"
46 #include "cpu/activity.hh"
47 #include "cpu/base.hh"
48 #include "cpu/exetrace.hh"
49 #include "cpu/simple_thread.hh"
50 #include "cpu/thread_context.hh"
51 #include "debug/Activity.hh"
52 #include "debug/InOrderCPU.hh"
53 #include "debug/RefCount.hh"
54 #include "debug/SkedCache.hh"
55 #include "mem/translating_port.hh"
56 #include "params/InOrderCPU.hh"
57 #include "sim/process.hh"
58 #include "sim/stat_control.hh"
61 #include "cpu/quiesce_event.hh"
62 #include "sim/system.hh"
65 #if THE_ISA == ALPHA_ISA
66 #include "arch/alpha/osfpal.hh"
70 using namespace TheISA
;
71 using namespace ThePipeline
;
73 InOrderCPU::TickEvent::TickEvent(InOrderCPU
*c
)
74 : Event(CPU_Tick_Pri
), cpu(c
)
79 InOrderCPU::TickEvent::process()
86 InOrderCPU::TickEvent::description()
88 return "InOrderCPU tick event";
91 InOrderCPU::CPUEvent::CPUEvent(InOrderCPU
*_cpu
, CPUEventType e_type
,
92 Fault fault
, ThreadID _tid
, DynInstPtr inst
,
93 unsigned event_pri_offset
)
94 : Event(Event::Priority((unsigned int)CPU_Tick_Pri
+ event_pri_offset
)),
97 setEvent(e_type
, fault
, _tid
, inst
);
101 std::string
InOrderCPU::eventNames
[NumCPUEvents
] =
104 "ActivateNextReadyThread",
110 "SquashFromMemStall",
115 InOrderCPU::CPUEvent::process()
117 switch (cpuEventType
)
120 cpu
->activateThread(tid
);
123 case ActivateNextReadyThread
:
124 cpu
->activateNextReadyThread();
127 case DeactivateThread
:
128 cpu
->deactivateThread(tid
);
132 cpu
->haltThread(tid
);
136 cpu
->suspendThread(tid
);
139 case SquashFromMemStall
:
140 cpu
->squashDueToMemStall(inst
->squashingStage
, inst
->seqNum
, tid
);
144 cpu
->trapCPU(fault
, tid
, inst
);
148 fatal("Unrecognized Event Type %s", eventNames
[cpuEventType
]);
151 cpu
->cpuEventRemoveList
.push(this);
157 InOrderCPU::CPUEvent::description()
159 return "InOrderCPU event";
163 InOrderCPU::CPUEvent::scheduleEvent(int delay
)
165 assert(!scheduled() || squashed());
166 cpu
->reschedule(this, cpu
->nextCycle(curTick() + cpu
->ticks(delay
)), true);
170 InOrderCPU::CPUEvent::unscheduleEvent()
176 InOrderCPU::InOrderCPU(Params
*params
)
178 cpu_id(params
->cpu_id
),
182 stageWidth(params
->stageWidth
),
184 removeInstsThisCycle(false),
185 activityRec(params
->name
, NumStages
, 10, params
->activity
),
187 system(params
->system
),
188 physmem(system
->physmem
),
189 #endif // FULL_SYSTEM
195 deferRegistration(false/*params->deferRegistration*/),
196 stageTracing(params
->stageTracing
),
199 ThreadID active_threads
;
202 resPool
= new ResourcePool(this, params
);
204 // Resize for Multithreading CPUs
205 thread
.resize(numThreads
);
210 active_threads
= params
->workload
.size();
212 if (active_threads
> MaxThreads
) {
213 panic("Workload Size too large. Increase the 'MaxThreads'"
214 "in your InOrder implementation or "
215 "edit your workload size.");
219 if (active_threads
> 1) {
220 threadModel
= (InOrderCPU::ThreadModel
) params
->threadModel
;
222 if (threadModel
== SMT
) {
223 DPRINTF(InOrderCPU
, "Setting Thread Model to SMT.\n");
224 } else if (threadModel
== SwitchOnCacheMiss
) {
225 DPRINTF(InOrderCPU
, "Setting Thread Model to "
226 "Switch On Cache Miss\n");
230 threadModel
= Single
;
237 // Bind the fetch & data ports from the resource pool.
238 fetchPortIdx
= resPool
->getPortIdx(params
->fetchMemPort
);
239 if (fetchPortIdx
== 0) {
240 fatal("Unable to find port to fetch instructions from.\n");
243 dataPortIdx
= resPool
->getPortIdx(params
->dataMemPort
);
244 if (dataPortIdx
== 0) {
245 fatal("Unable to find port for data.\n");
248 for (ThreadID tid
= 0; tid
< numThreads
; ++tid
) {
250 // SMT is not supported in FS mode yet.
251 assert(numThreads
== 1);
252 thread
[tid
] = new Thread(this, 0);
254 if (tid
< (ThreadID
)params
->workload
.size()) {
255 DPRINTF(InOrderCPU
, "Workload[%i] process is %#x\n",
256 tid
, params
->workload
[tid
]->prog_fname
);
258 new Thread(this, tid
, params
->workload
[tid
]);
260 //Allocate Empty thread so M5 can use later
261 //when scheduling threads to CPU
262 Process
* dummy_proc
= params
->workload
[0];
263 thread
[tid
] = new Thread(this, tid
, dummy_proc
);
266 // Eventually set this with parameters...
270 // Setup the TC that will serve as the interface to the threads/CPU.
271 InOrderThreadContext
*tc
= new InOrderThreadContext
;
273 tc
->thread
= thread
[tid
];
275 // Give the thread the TC.
276 thread
[tid
]->tc
= tc
;
277 thread
[tid
]->setFuncExeInst(0);
278 globalSeqNum
[tid
] = 1;
280 // Add the TC to the CPU's list of TC's.
281 this->threadContexts
.push_back(tc
);
284 // Initialize TimeBuffer Stage Queues
285 for (int stNum
=0; stNum
< NumStages
- 1; stNum
++) {
286 stageQueue
[stNum
] = new StageQueue(NumStages
, NumStages
);
287 stageQueue
[stNum
]->id(stNum
);
291 // Set Up Pipeline Stages
292 for (int stNum
=0; stNum
< NumStages
; stNum
++) {
294 pipelineStage
[stNum
] = new FirstStage(params
, stNum
);
296 pipelineStage
[stNum
] = new PipelineStage(params
, stNum
);
298 pipelineStage
[stNum
]->setCPU(this);
299 pipelineStage
[stNum
]->setActiveThreads(&activeThreads
);
300 pipelineStage
[stNum
]->setTimeBuffer(&timeBuffer
);
302 // Take Care of 1st/Nth stages
304 pipelineStage
[stNum
]->setPrevStageQueue(stageQueue
[stNum
- 1]);
305 if (stNum
< NumStages
- 1)
306 pipelineStage
[stNum
]->setNextStageQueue(stageQueue
[stNum
]);
309 // Initialize thread specific variables
310 for (ThreadID tid
= 0; tid
< numThreads
; tid
++) {
311 archRegDepMap
[tid
].setCPU(this);
313 nonSpecInstActive
[tid
] = false;
314 nonSpecSeqNum
[tid
] = 0;
316 squashSeqNum
[tid
] = MaxAddr
;
317 lastSquashCycle
[tid
] = 0;
319 memset(intRegs
[tid
], 0, sizeof(intRegs
[tid
]));
320 memset(floatRegs
.i
[tid
], 0, sizeof(floatRegs
.i
[tid
]));
323 // Define dummy instructions and resource requests to be used.
324 dummyInst
[tid
] = new InOrderDynInst(this,
330 dummyReq
[tid
] = new ResourceRequest(resPool
->getResource(0));
333 dummyReqInst
= new InOrderDynInst(this, NULL
, 0, 0, 0);
334 dummyReqInst
->setSquashed();
335 dummyReqInst
->resetInstCount();
337 dummyBufferInst
= new InOrderDynInst(this, NULL
, 0, 0, 0);
338 dummyBufferInst
->setSquashed();
339 dummyBufferInst
->resetInstCount();
341 endOfSkedIt
= skedCache
.end();
342 frontEndSked
= createFrontEndSked();
344 lastRunningCycle
= curTick();
346 // Reset CPU to reset state.
348 Fault resetFault
= new ResetFault();
349 resetFault
->invoke(tcBase());
353 // Schedule First Tick Event, CPU will reschedule itself from here on out.
354 scheduleTickEvent(0);
357 InOrderCPU::~InOrderCPU()
361 SkedCacheIt sked_it
= skedCache
.begin();
362 SkedCacheIt sked_end
= skedCache
.end();
364 while (sked_it
!= sked_end
) {
365 delete (*sked_it
).second
;
371 m5::hash_map
<InOrderCPU::SkedID
, ThePipeline::RSkedPtr
> InOrderCPU::skedCache
;
374 InOrderCPU::createFrontEndSked()
376 RSkedPtr res_sked
= new ResourceSked();
378 StageScheduler
F(res_sked
, stage_num
++);
379 StageScheduler
D(res_sked
, stage_num
++);
382 F
.needs(FetchSeq
, FetchSeqUnit::AssignNextPC
);
383 F
.needs(ICache
, FetchUnit::InitiateFetch
);
386 D
.needs(ICache
, FetchUnit::CompleteFetch
);
387 D
.needs(Decode
, DecodeUnit::DecodeInst
);
388 D
.needs(BPred
, BranchPredictor::PredictBranch
);
389 D
.needs(FetchSeq
, FetchSeqUnit::UpdateTargetPC
);
392 DPRINTF(SkedCache
, "Resource Sked created for instruction \"front_end\"\n");
398 InOrderCPU::createBackEndSked(DynInstPtr inst
)
400 RSkedPtr res_sked
= lookupSked(inst
);
401 if (res_sked
!= NULL
) {
402 DPRINTF(SkedCache
, "Found %s in sked cache.\n",
406 res_sked
= new ResourceSked();
409 int stage_num
= ThePipeline::BackEndStartStage
;
410 StageScheduler
X(res_sked
, stage_num
++);
411 StageScheduler
M(res_sked
, stage_num
++);
412 StageScheduler
W(res_sked
, stage_num
++);
414 if (!inst
->staticInst
) {
415 warn_once("Static Instruction Object Not Set. Can't Create"
416 " Back End Schedule");
421 for (int idx
=0; idx
< inst
->numSrcRegs(); idx
++) {
422 if (!idx
|| !inst
->isStore()) {
423 X
.needs(RegManager
, UseDefUnit::ReadSrcReg
, idx
);
427 if ( inst
->isNonSpeculative() ) {
428 // skip execution of non speculative insts until later
429 } else if ( inst
->isMemRef() ) {
430 if ( inst
->isLoad() ) {
431 X
.needs(AGEN
, AGENUnit::GenerateAddr
);
433 } else if (inst
->opClass() == IntMultOp
|| inst
->opClass() == IntDivOp
) {
434 X
.needs(MDU
, MultDivUnit::StartMultDiv
);
436 X
.needs(ExecUnit
, ExecutionUnit::ExecuteInst
);
439 if (inst
->opClass() == IntMultOp
|| inst
->opClass() == IntDivOp
) {
440 X
.needs(MDU
, MultDivUnit::EndMultDiv
);
444 if ( inst
->isLoad() ) {
445 M
.needs(DCache
, CacheUnit::InitiateReadData
);
446 } else if ( inst
->isStore() ) {
447 if ( inst
->numSrcRegs() >= 2 ) {
448 M
.needs(RegManager
, UseDefUnit::ReadSrcReg
, 1);
450 M
.needs(AGEN
, AGENUnit::GenerateAddr
);
451 M
.needs(DCache
, CacheUnit::InitiateWriteData
);
456 if ( inst
->isLoad() ) {
457 W
.needs(DCache
, CacheUnit::CompleteReadData
);
458 } else if ( inst
->isStore() ) {
459 W
.needs(DCache
, CacheUnit::CompleteWriteData
);
462 if ( inst
->isNonSpeculative() ) {
463 if ( inst
->isMemRef() ) fatal("Non-Speculative Memory Instruction");
464 W
.needs(ExecUnit
, ExecutionUnit::ExecuteInst
);
467 W
.needs(Grad
, GraduationUnit::GraduateInst
);
469 for (int idx
=0; idx
< inst
->numDestRegs(); idx
++) {
470 W
.needs(RegManager
, UseDefUnit::WriteDestReg
, idx
);
473 // Insert Back Schedule into our cache of
474 // resource schedules
475 addToSkedCache(inst
, res_sked
);
477 DPRINTF(SkedCache
, "Back End Sked Created for instruction: %s (%08p)\n",
478 inst
->instName(), inst
->getMachInst());
485 InOrderCPU::regStats()
487 /* Register the Resource Pool's stats here.*/
490 /* Register for each Pipeline Stage */
491 for (int stage_num
=0; stage_num
< ThePipeline::NumStages
; stage_num
++) {
492 pipelineStage
[stage_num
]->regStats();
495 /* Register any of the InOrderCPU's stats here.*/
497 .name(name() + ".instsPerContextSwitch")
498 .desc("Instructions Committed Per Context Switch")
499 .prereq(instsPerCtxtSwitch
);
502 .name(name() + ".contextSwitches")
503 .desc("Number of context switches");
506 .name(name() + ".comLoads")
507 .desc("Number of Load instructions committed");
510 .name(name() + ".comStores")
511 .desc("Number of Store instructions committed");
514 .name(name() + ".comBranches")
515 .desc("Number of Branches instructions committed");
518 .name(name() + ".comNops")
519 .desc("Number of Nop instructions committed");
522 .name(name() + ".comNonSpec")
523 .desc("Number of Non-Speculative instructions committed");
526 .name(name() + ".comInts")
527 .desc("Number of Integer instructions committed");
530 .name(name() + ".comFloats")
531 .desc("Number of Floating Point instructions committed");
534 .name(name() + ".timesIdled")
535 .desc("Number of times that the entire CPU went into an idle state and"
536 " unscheduled itself")
540 .name(name() + ".idleCycles")
541 .desc("Number of cycles cpu's stages were not processed");
544 .name(name() + ".runCycles")
545 .desc("Number of cycles cpu stages are processed.");
548 .name(name() + ".activity")
549 .desc("Percentage of cycles cpu is active")
551 activity
= (runCycles
/ numCycles
) * 100;
555 .name(name() + ".threadCycles")
556 .desc("Total Number of Cycles A Thread Was Active in CPU (Per-Thread)");
559 .name(name() + ".smtCycles")
560 .desc("Total number of cycles that the CPU was in SMT-mode");
564 .name(name() + ".committedInsts")
565 .desc("Number of Instructions Simulated (Per-Thread)");
569 .name(name() + ".smtCommittedInsts")
570 .desc("Number of SMT Instructions Simulated (Per-Thread)");
573 .name(name() + ".committedInsts_total")
574 .desc("Number of Instructions Simulated (Total)");
577 .name(name() + ".cpi")
578 .desc("CPI: Cycles Per Instruction (Per-Thread)")
580 cpi
= numCycles
/ committedInsts
;
583 .name(name() + ".smt_cpi")
584 .desc("CPI: Total SMT-CPI")
586 smtCpi
= smtCycles
/ smtCommittedInsts
;
589 .name(name() + ".cpi_total")
590 .desc("CPI: Total CPI of All Threads")
592 totalCpi
= numCycles
/ totalCommittedInsts
;
595 .name(name() + ".ipc")
596 .desc("IPC: Instructions Per Cycle (Per-Thread)")
598 ipc
= committedInsts
/ numCycles
;
601 .name(name() + ".smt_ipc")
602 .desc("IPC: Total SMT-IPC")
604 smtIpc
= smtCommittedInsts
/ smtCycles
;
607 .name(name() + ".ipc_total")
608 .desc("IPC: Total IPC of All Threads")
610 totalIpc
= totalCommittedInsts
/ numCycles
;
619 DPRINTF(InOrderCPU
, "\n\nInOrderCPU: Ticking main, InOrderCPU.\n");
623 bool pipes_idle
= true;
625 //Tick each of the stages
626 for (int stNum
=NumStages
- 1; stNum
>= 0 ; stNum
--) {
627 pipelineStage
[stNum
]->tick();
629 pipes_idle
= pipes_idle
&& pipelineStage
[stNum
]->idle
;
637 // Now advance the time buffers one tick
638 timeBuffer
.advance();
639 for (int sqNum
=0; sqNum
< NumStages
- 1; sqNum
++) {
640 stageQueue
[sqNum
]->advance();
642 activityRec
.advance();
644 // Any squashed events, or insts then remove them now
645 cleanUpRemovedEvents();
646 cleanUpRemovedInsts();
648 // Re-schedule CPU for this cycle
649 if (!tickEvent
.scheduled()) {
650 if (_status
== SwitchedOut
) {
652 lastRunningCycle
= curTick();
653 } else if (!activityRec
.active()) {
654 DPRINTF(InOrderCPU
, "sleeping CPU.\n");
655 lastRunningCycle
= curTick();
658 //Tick next_tick = curTick() + cycles(1);
659 //tickEvent.schedule(next_tick);
660 schedule(&tickEvent
, nextCycle(curTick() + 1));
661 DPRINTF(InOrderCPU
, "Scheduled CPU for next tick @ %i.\n",
662 nextCycle(curTick() + 1));
667 updateThreadPriority();
674 if (!deferRegistration
) {
675 registerThreadContexts();
678 // Set inSyscall so that the CPU doesn't squash when initially
679 // setting up registers.
680 for (ThreadID tid
= 0; tid
< numThreads
; ++tid
)
681 thread
[tid
]->inSyscall
= true;
684 for (ThreadID tid
= 0; tid
< numThreads
; tid
++) {
685 ThreadContext
*src_tc
= threadContexts
[tid
];
686 TheISA::initCPU(src_tc
, src_tc
->contextId());
691 for (ThreadID tid
= 0; tid
< numThreads
; ++tid
)
692 thread
[tid
]->inSyscall
= false;
694 // Call Initializiation Routine for Resource Pool
699 InOrderCPU::getPort(const std::string
&if_name
, int idx
)
701 return resPool
->getPort(if_name
, idx
);
706 InOrderCPU::hwrei(ThreadID tid
)
708 panic("hwrei: Unimplemented");
715 InOrderCPU::simPalCheck(int palFunc
, ThreadID tid
)
717 panic("simPalCheck: Unimplemented");
724 InOrderCPU::getInterrupts()
726 // Check if there are any outstanding interrupts
727 return interrupts
->getInterrupt(threadContexts
[0]);
732 InOrderCPU::processInterrupts(Fault interrupt
)
734 // Check for interrupts here. For now can copy the code that
735 // exists within isa_fullsys_traits.hh. Also assume that thread 0
736 // is the one that handles the interrupts.
737 // @todo: Possibly consolidate the interrupt checking code.
738 // @todo: Allow other threads to handle interrupts.
740 assert(interrupt
!= NoFault
);
741 interrupts
->updateIntrInfo(threadContexts
[0]);
743 DPRINTF(InOrderCPU
, "Interrupt %s being handled\n", interrupt
->name());
745 // Note: Context ID ok here? Impl. of FS mode needs to revisit this
746 trap(interrupt
, threadContexts
[0]->contextId(), dummyBufferInst
);
751 InOrderCPU::updateMemPorts()
753 // Update all ThreadContext's memory ports (Functional/Virtual
755 ThreadID size
= thread
.size();
756 for (ThreadID i
= 0; i
< size
; ++i
)
757 thread
[i
]->connectMemPorts(thread
[i
]->getTC());
762 InOrderCPU::trap(Fault fault
, ThreadID tid
, DynInstPtr inst
, int delay
)
764 //@ Squash Pipeline during TRAP
765 scheduleCpuEvent(Trap
, fault
, tid
, inst
, delay
);
769 InOrderCPU::trapCPU(Fault fault
, ThreadID tid
, DynInstPtr inst
)
771 fault
->invoke(tcBase(tid
), inst
->staticInst
);
775 InOrderCPU::squashFromMemStall(DynInstPtr inst
, ThreadID tid
, int delay
)
777 scheduleCpuEvent(SquashFromMemStall
, NoFault
, tid
, inst
, delay
);
782 InOrderCPU::squashDueToMemStall(int stage_num
, InstSeqNum seq_num
,
785 DPRINTF(InOrderCPU
, "Squashing Pipeline Stages Due to Memory Stall...\n");
787 // Squash all instructions in each stage including
788 // instruction that caused the squash (seq_num - 1)
789 // NOTE: The stage bandwidth needs to be cleared so thats why
790 // the stalling instruction is squashed as well. The stalled
791 // instruction is previously placed in another intermediate buffer
792 // while it's stall is being handled.
793 InstSeqNum squash_seq_num
= seq_num
- 1;
795 for (int stNum
=stage_num
; stNum
>= 0 ; stNum
--) {
796 pipelineStage
[stNum
]->squashDueToMemStall(squash_seq_num
, tid
);
801 InOrderCPU::scheduleCpuEvent(CPUEventType c_event
, Fault fault
,
802 ThreadID tid
, DynInstPtr inst
,
803 unsigned delay
, unsigned event_pri_offset
)
805 CPUEvent
*cpu_event
= new CPUEvent(this, c_event
, fault
, tid
, inst
,
808 Tick sked_tick
= nextCycle(curTick() + ticks(delay
));
810 DPRINTF(InOrderCPU
, "Scheduling CPU Event (%s) for cycle %i, [tid:%i].\n",
811 eventNames
[c_event
], curTick() + delay
, tid
);
812 schedule(cpu_event
, sked_tick
);
814 cpu_event
->process();
815 cpuEventRemoveList
.push(cpu_event
);
818 // Broadcast event to the Resource Pool
819 // Need to reset tid just in case this is a dummy instruction
821 resPool
->scheduleEvent(c_event
, inst
, 0, 0, tid
);
825 InOrderCPU::isThreadActive(ThreadID tid
)
827 list
<ThreadID
>::iterator isActive
=
828 std::find(activeThreads
.begin(), activeThreads
.end(), tid
);
830 return (isActive
!= activeThreads
.end());
834 InOrderCPU::isThreadReady(ThreadID tid
)
836 list
<ThreadID
>::iterator isReady
=
837 std::find(readyThreads
.begin(), readyThreads
.end(), tid
);
839 return (isReady
!= readyThreads
.end());
843 InOrderCPU::isThreadSuspended(ThreadID tid
)
845 list
<ThreadID
>::iterator isSuspended
=
846 std::find(suspendedThreads
.begin(), suspendedThreads
.end(), tid
);
848 return (isSuspended
!= suspendedThreads
.end());
852 InOrderCPU::activateNextReadyThread()
854 if (readyThreads
.size() >= 1) {
855 ThreadID ready_tid
= readyThreads
.front();
857 // Activate in Pipeline
858 activateThread(ready_tid
);
860 // Activate in Resource Pool
861 resPool
->activateAll(ready_tid
);
863 list
<ThreadID
>::iterator ready_it
=
864 std::find(readyThreads
.begin(), readyThreads
.end(), ready_tid
);
865 readyThreads
.erase(ready_it
);
868 "Attempting to activate new thread, but No Ready Threads to"
871 "Unable to switch to next active thread.\n");
876 InOrderCPU::activateThread(ThreadID tid
)
878 if (isThreadSuspended(tid
)) {
880 "Removing [tid:%i] from suspended threads list.\n", tid
);
882 list
<ThreadID
>::iterator susp_it
=
883 std::find(suspendedThreads
.begin(), suspendedThreads
.end(),
885 suspendedThreads
.erase(susp_it
);
888 if (threadModel
== SwitchOnCacheMiss
&&
889 numActiveThreads() == 1) {
891 "Ignoring activation of [tid:%i], since [tid:%i] is "
892 "already running.\n", tid
, activeThreadId());
894 DPRINTF(InOrderCPU
,"Placing [tid:%i] on ready threads list\n",
897 readyThreads
.push_back(tid
);
899 } else if (!isThreadActive(tid
)) {
901 "Adding [tid:%i] to active threads list.\n", tid
);
902 activeThreads
.push_back(tid
);
904 activateThreadInPipeline(tid
);
906 thread
[tid
]->lastActivate
= curTick();
908 tcBase(tid
)->setStatus(ThreadContext::Active
);
917 InOrderCPU::activateThreadInPipeline(ThreadID tid
)
919 for (int stNum
=0; stNum
< NumStages
; stNum
++) {
920 pipelineStage
[stNum
]->activateThread(tid
);
925 InOrderCPU::deactivateContext(ThreadID tid
, int delay
)
927 DPRINTF(InOrderCPU
,"[tid:%i]: Deactivating ...\n", tid
);
929 scheduleCpuEvent(DeactivateThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
931 // Be sure to signal that there's some activity so the CPU doesn't
932 // deschedule itself.
933 activityRec
.activity();
939 InOrderCPU::deactivateThread(ThreadID tid
)
941 DPRINTF(InOrderCPU
, "[tid:%i]: Calling deactivate thread.\n", tid
);
943 if (isThreadActive(tid
)) {
944 DPRINTF(InOrderCPU
,"[tid:%i]: Removing from active threads list\n",
946 list
<ThreadID
>::iterator thread_it
=
947 std::find(activeThreads
.begin(), activeThreads
.end(), tid
);
949 removePipelineStalls(*thread_it
);
951 activeThreads
.erase(thread_it
);
953 // Ideally, this should be triggered from the
954 // suspendContext/Thread functions
955 tcBase(tid
)->setStatus(ThreadContext::Suspended
);
958 assert(!isThreadActive(tid
));
962 InOrderCPU::removePipelineStalls(ThreadID tid
)
964 DPRINTF(InOrderCPU
,"[tid:%i]: Removing all pipeline stalls\n",
967 for (int stNum
= 0; stNum
< NumStages
; stNum
++) {
968 pipelineStage
[stNum
]->removeStalls(tid
);
974 InOrderCPU::updateThreadPriority()
976 if (activeThreads
.size() > 1)
978 //DEFAULT TO ROUND ROBIN SCHEME
979 //e.g. Move highest priority to end of thread list
980 list
<ThreadID
>::iterator list_begin
= activeThreads
.begin();
981 list
<ThreadID
>::iterator list_end
= activeThreads
.end();
983 unsigned high_thread
= *list_begin
;
985 activeThreads
.erase(list_begin
);
987 activeThreads
.push_back(high_thread
);
992 InOrderCPU::tickThreadStats()
994 /** Keep track of cycles that each thread is active */
995 list
<ThreadID
>::iterator thread_it
= activeThreads
.begin();
996 while (thread_it
!= activeThreads
.end()) {
997 threadCycles
[*thread_it
]++;
1001 // Keep track of cycles where SMT is active
1002 if (activeThreads
.size() > 1) {
1008 InOrderCPU::activateContext(ThreadID tid
, int delay
)
1010 DPRINTF(InOrderCPU
,"[tid:%i]: Activating ...\n", tid
);
1013 scheduleCpuEvent(ActivateThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1015 // Be sure to signal that there's some activity so the CPU doesn't
1016 // deschedule itself.
1017 activityRec
.activity();
1023 InOrderCPU::activateNextReadyContext(int delay
)
1025 DPRINTF(InOrderCPU
,"Activating next ready thread\n");
1027 // NOTE: Add 5 to the event priority so that we always activate
1028 // threads after we've finished deactivating, squashing,etc.
1030 scheduleCpuEvent(ActivateNextReadyThread
, NoFault
, 0/*tid*/, dummyInst
[0],
1033 // Be sure to signal that there's some activity so the CPU doesn't
1034 // deschedule itself.
1035 activityRec
.activity();
1041 InOrderCPU::haltContext(ThreadID tid
, int delay
)
1043 DPRINTF(InOrderCPU
, "[tid:%i]: Calling Halt Context...\n", tid
);
1045 scheduleCpuEvent(HaltThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1047 activityRec
.activity();
1051 InOrderCPU::haltThread(ThreadID tid
)
1053 DPRINTF(InOrderCPU
, "[tid:%i]: Placing on Halted Threads List...\n", tid
);
1054 deactivateThread(tid
);
1055 squashThreadInPipeline(tid
);
1056 haltedThreads
.push_back(tid
);
1058 tcBase(tid
)->setStatus(ThreadContext::Halted
);
1060 if (threadModel
== SwitchOnCacheMiss
) {
1061 activateNextReadyContext();
1066 InOrderCPU::suspendContext(ThreadID tid
, int delay
)
1068 scheduleCpuEvent(SuspendThread
, NoFault
, tid
, dummyInst
[tid
], delay
);
1072 InOrderCPU::suspendThread(ThreadID tid
)
1074 DPRINTF(InOrderCPU
, "[tid:%i]: Placing on Suspended Threads List...\n",
1076 deactivateThread(tid
);
1077 suspendedThreads
.push_back(tid
);
1078 thread
[tid
]->lastSuspend
= curTick();
1080 tcBase(tid
)->setStatus(ThreadContext::Suspended
);
1084 InOrderCPU::squashThreadInPipeline(ThreadID tid
)
1086 //Squash all instructions in each stage
1087 for (int stNum
=NumStages
- 1; stNum
>= 0 ; stNum
--) {
1088 pipelineStage
[stNum
]->squash(0 /*seq_num*/, tid
);
1093 InOrderCPU::getPipeStage(int stage_num
)
1095 return pipelineStage
[stage_num
];
1099 InOrderCPU::readIntReg(int reg_idx
, ThreadID tid
)
1101 return intRegs
[tid
][reg_idx
];
1105 InOrderCPU::readFloatReg(int reg_idx
, ThreadID tid
)
1107 return floatRegs
.f
[tid
][reg_idx
];
1111 InOrderCPU::readFloatRegBits(int reg_idx
, ThreadID tid
)
1113 return floatRegs
.i
[tid
][reg_idx
];
1117 InOrderCPU::setIntReg(int reg_idx
, uint64_t val
, ThreadID tid
)
1119 intRegs
[tid
][reg_idx
] = val
;
1124 InOrderCPU::setFloatReg(int reg_idx
, FloatReg val
, ThreadID tid
)
1126 floatRegs
.f
[tid
][reg_idx
] = val
;
1131 InOrderCPU::setFloatRegBits(int reg_idx
, FloatRegBits val
, ThreadID tid
)
1133 floatRegs
.i
[tid
][reg_idx
] = val
;
1137 InOrderCPU::readRegOtherThread(unsigned reg_idx
, ThreadID tid
)
1139 // If Default value is set, then retrieve target thread
1140 if (tid
== InvalidThreadID
) {
1141 tid
= TheISA::getTargetThread(tcBase(tid
));
1144 if (reg_idx
< FP_Base_DepTag
) {
1145 // Integer Register File
1146 return readIntReg(reg_idx
, tid
);
1147 } else if (reg_idx
< Ctrl_Base_DepTag
) {
1148 // Float Register File
1149 reg_idx
-= FP_Base_DepTag
;
1150 return readFloatRegBits(reg_idx
, tid
);
1152 reg_idx
-= Ctrl_Base_DepTag
;
1153 return readMiscReg(reg_idx
, tid
); // Misc. Register File
1157 InOrderCPU::setRegOtherThread(unsigned reg_idx
, const MiscReg
&val
,
1160 // If Default value is set, then retrieve target thread
1161 if (tid
== InvalidThreadID
) {
1162 tid
= TheISA::getTargetThread(tcBase(tid
));
1165 if (reg_idx
< FP_Base_DepTag
) { // Integer Register File
1166 setIntReg(reg_idx
, val
, tid
);
1167 } else if (reg_idx
< Ctrl_Base_DepTag
) { // Float Register File
1168 reg_idx
-= FP_Base_DepTag
;
1169 setFloatRegBits(reg_idx
, val
, tid
);
1171 reg_idx
-= Ctrl_Base_DepTag
;
1172 setMiscReg(reg_idx
, val
, tid
); // Misc. Register File
1177 InOrderCPU::readMiscRegNoEffect(int misc_reg
, ThreadID tid
)
1179 return isa
[tid
].readMiscRegNoEffect(misc_reg
);
1183 InOrderCPU::readMiscReg(int misc_reg
, ThreadID tid
)
1185 return isa
[tid
].readMiscReg(misc_reg
, tcBase(tid
));
1189 InOrderCPU::setMiscRegNoEffect(int misc_reg
, const MiscReg
&val
, ThreadID tid
)
1191 isa
[tid
].setMiscRegNoEffect(misc_reg
, val
);
1195 InOrderCPU::setMiscReg(int misc_reg
, const MiscReg
&val
, ThreadID tid
)
1197 isa
[tid
].setMiscReg(misc_reg
, val
, tcBase(tid
));
1202 InOrderCPU::addInst(DynInstPtr
&inst
)
1204 ThreadID tid
= inst
->readTid();
1206 instList
[tid
].push_back(inst
);
1208 return --(instList
[tid
].end());
1212 InOrderCPU::updateContextSwitchStats()
1214 // Set Average Stat Here, then reset to 0
1215 instsPerCtxtSwitch
= instsPerSwitch
;
1221 InOrderCPU::instDone(DynInstPtr inst
, ThreadID tid
)
1223 // Set the CPU's PCs - This contributes to the precise state of the CPU
1224 // which can be used when restoring a thread to the CPU after after any
1225 // type of context switching activity (fork, exception, etc.)
1226 pcState(inst
->pcState(), tid
);
1228 if (inst
->isControl()) {
1229 thread
[tid
]->lastGradIsBranch
= true;
1230 thread
[tid
]->lastBranchPC
= inst
->pcState();
1231 TheISA::advancePC(thread
[tid
]->lastBranchPC
, inst
->staticInst
);
1233 thread
[tid
]->lastGradIsBranch
= false;
1237 // Finalize Trace Data For Instruction
1238 if (inst
->traceData
) {
1239 //inst->traceData->setCycle(curTick());
1240 inst
->traceData
->setFetchSeq(inst
->seqNum
);
1241 //inst->traceData->setCPSeq(cpu->tcBase(tid)->numInst);
1242 inst
->traceData
->dump();
1243 delete inst
->traceData
;
1244 inst
->traceData
= NULL
;
1247 // Increment active thread's instruction count
1250 // Increment thread-state's instruction count
1251 thread
[tid
]->numInst
++;
1253 // Increment thread-state's instruction stats
1254 thread
[tid
]->numInsts
++;
1256 // Count committed insts per thread stats
1257 committedInsts
[tid
]++;
1259 // Count total insts committed stat
1260 totalCommittedInsts
++;
1262 // Count SMT-committed insts per thread stat
1263 if (numActiveThreads() > 1) {
1264 smtCommittedInsts
[tid
]++;
1267 // Instruction-Mix Stats
1268 if (inst
->isLoad()) {
1270 } else if (inst
->isStore()) {
1272 } else if (inst
->isControl()) {
1274 } else if (inst
->isNop()) {
1276 } else if (inst
->isNonSpeculative()) {
1278 } else if (inst
->isInteger()) {
1280 } else if (inst
->isFloating()) {
1284 // Check for instruction-count-based events.
1285 comInstEventQueue
[tid
]->serviceEvents(thread
[tid
]->numInst
);
1287 // Broadcast to other resources an instruction
1288 // has been completed
1289 resPool
->scheduleEvent((CPUEventType
)ResourcePool::InstGraduated
, inst
,
1292 // Finally, remove instruction from CPU
1296 // currently unused function, but substitute repetitive code w/this function
1299 InOrderCPU::addToRemoveList(DynInstPtr
&inst
)
1301 removeInstsThisCycle
= true;
1302 if (!inst
->isRemoveList()) {
1303 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1304 "[sn:%lli] to remove list\n",
1305 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1306 inst
->setRemoveList();
1307 removeList
.push(inst
->getInstListIt());
1309 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i] PC %s "
1310 "[sn:%lli], already remove list\n",
1311 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1317 InOrderCPU::removeInst(DynInstPtr
&inst
)
1319 DPRINTF(InOrderCPU
, "Removing graduated instruction [tid:%i] PC %s "
1321 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1323 removeInstsThisCycle
= true;
1325 // Remove the instruction.
1326 if (!inst
->isRemoveList()) {
1327 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1328 "[sn:%lli] to remove list\n",
1329 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1330 inst
->setRemoveList();
1331 removeList
.push(inst
->getInstListIt());
1333 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i] PC %s "
1334 "[sn:%lli], already on remove list\n",
1335 inst
->threadNumber
, inst
->pcState(), inst
->seqNum
);
1341 InOrderCPU::removeInstsUntil(const InstSeqNum
&seq_num
, ThreadID tid
)
1343 //assert(!instList[tid].empty());
1345 removeInstsThisCycle
= true;
1347 ListIt inst_iter
= instList
[tid
].end();
1351 DPRINTF(InOrderCPU
, "Squashing instructions from CPU instruction "
1352 "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1353 tid
, seq_num
, (*inst_iter
)->seqNum
);
1355 while ((*inst_iter
)->seqNum
> seq_num
) {
1357 bool break_loop
= (inst_iter
== instList
[tid
].begin());
1359 squashInstIt(inst_iter
, tid
);
1370 InOrderCPU::squashInstIt(const ListIt
&instIt
, ThreadID tid
)
1372 if ((*instIt
)->threadNumber
== tid
) {
1373 DPRINTF(InOrderCPU
, "Squashing instruction, "
1374 "[tid:%i] [sn:%lli] PC %s\n",
1375 (*instIt
)->threadNumber
,
1377 (*instIt
)->pcState());
1379 (*instIt
)->setSquashed();
1381 if (!(*instIt
)->isRemoveList()) {
1382 DPRINTF(InOrderCPU
, "Pushing instruction [tid:%i] PC %s "
1383 "[sn:%lli] to remove list\n",
1384 (*instIt
)->threadNumber
, (*instIt
)->pcState(),
1386 (*instIt
)->setRemoveList();
1387 removeList
.push(instIt
);
1389 DPRINTF(InOrderCPU
, "Ignoring instruction removal for [tid:%i]"
1390 " PC %s [sn:%lli], already on remove list\n",
1391 (*instIt
)->threadNumber
, (*instIt
)->pcState(),
1401 InOrderCPU::cleanUpRemovedInsts()
1403 while (!removeList
.empty()) {
1404 DPRINTF(InOrderCPU
, "Removing instruction, "
1405 "[tid:%i] [sn:%lli] PC %s\n",
1406 (*removeList
.front())->threadNumber
,
1407 (*removeList
.front())->seqNum
,
1408 (*removeList
.front())->pcState());
1410 DynInstPtr inst
= *removeList
.front();
1411 ThreadID tid
= inst
->threadNumber
;
1413 // Remove From Register Dependency Map, If Necessary
1414 archRegDepMap
[(*removeList
.front())->threadNumber
].
1415 remove((*removeList
.front()));
1418 // Clear if Non-Speculative
1419 if (inst
->staticInst
&&
1420 inst
->seqNum
== nonSpecSeqNum
[tid
] &&
1421 nonSpecInstActive
[tid
] == true) {
1422 nonSpecInstActive
[tid
] = false;
1425 instList
[tid
].erase(removeList
.front());
1430 removeInstsThisCycle
= false;
1434 InOrderCPU::cleanUpRemovedEvents()
1436 while (!cpuEventRemoveList
.empty()) {
1437 Event
*cpu_event
= cpuEventRemoveList
.front();
1438 cpuEventRemoveList
.pop();
1445 InOrderCPU::dumpInsts()
1449 ListIt inst_list_it
= instList
[0].begin();
1451 cprintf("Dumping Instruction List\n");
1453 while (inst_list_it
!= instList
[0].end()) {
1454 cprintf("Instruction:%i\nPC:%s\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1456 num
, (*inst_list_it
)->pcState(),
1457 (*inst_list_it
)->threadNumber
,
1458 (*inst_list_it
)->seqNum
, (*inst_list_it
)->isIssued(),
1459 (*inst_list_it
)->isSquashed());
1466 InOrderCPU::wakeCPU()
1468 if (/*activityRec.active() || */tickEvent
.scheduled()) {
1469 DPRINTF(Activity
, "CPU already running.\n");
1473 DPRINTF(Activity
, "Waking up CPU\n");
1475 Tick extra_cycles
= tickToCycles((curTick() - 1) - lastRunningCycle
);
1477 idleCycles
+= extra_cycles
;
1478 for (int stage_num
= 0; stage_num
< NumStages
; stage_num
++) {
1479 pipelineStage
[stage_num
]->idleCycles
+= extra_cycles
;
1482 numCycles
+= extra_cycles
;
1484 schedule(&tickEvent
, nextCycle(curTick()));
1490 InOrderCPU::wakeup()
1492 if (thread
[0]->status() != ThreadContext::Suspended
)
1497 DPRINTF(Quiesce
, "Suspended Processor woken\n");
1498 threadContexts
[0]->activate();
1504 InOrderCPU::syscall(int64_t callnum
, ThreadID tid
)
1506 DPRINTF(InOrderCPU
, "[tid:%i] Executing syscall().\n\n", tid
);
1508 DPRINTF(Activity
,"Activity: syscall() called.\n");
1510 // Temporarily increase this by one to account for the syscall
1512 ++(this->thread
[tid
]->funcExeInst
);
1514 // Execute the actual syscall.
1515 this->thread
[tid
]->syscall(callnum
);
1517 // Decrease funcExeInst by one as the normal commit will handle
1519 --(this->thread
[tid
]->funcExeInst
);
1521 // Clear Non-Speculative Block Variable
1522 nonSpecInstActive
[tid
] = false;
1527 InOrderCPU::getITBPtr()
1529 CacheUnit
*itb_res
=
1530 dynamic_cast<CacheUnit
*>(resPool
->getResource(fetchPortIdx
));
1531 return itb_res
->tlb();
1536 InOrderCPU::getDTBPtr()
1538 CacheUnit
*dtb_res
=
1539 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1540 return dtb_res
->tlb();
1544 InOrderCPU::read(DynInstPtr inst
, Addr addr
,
1545 uint8_t *data
, unsigned size
, unsigned flags
)
1547 //@TODO: Generalize name "CacheUnit" to "MemUnit" just in case
1548 // you want to run w/out caches?
1549 CacheUnit
*cache_res
=
1550 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1552 return cache_res
->read(inst
, addr
, data
, size
, flags
);
1556 InOrderCPU::write(DynInstPtr inst
, uint8_t *data
, unsigned size
,
1557 Addr addr
, unsigned flags
, uint64_t *write_res
)
1559 //@TODO: Generalize name "CacheUnit" to "MemUnit" just in case
1560 // you want to run w/out caches?
1561 CacheUnit
*cache_res
=
1562 dynamic_cast<CacheUnit
*>(resPool
->getResource(dataPortIdx
));
1563 return cache_res
->write(inst
, data
, size
, addr
, flags
, write_res
);