365b2f18a190f983149412c349f2d597bcc87898
[gem5.git] / src / cpu / inorder / cpu.cc
1 /*
2 * Copyright (c) 2007 MIPS Technologies, Inc.
3 * All rights reserved.
4 *
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.
15 *
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.
27 *
28 * Authors: Korey Sewell
29 *
30 */
31
32 #include <algorithm>
33
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"
59
60 #if FULL_SYSTEM
61 #include "cpu/quiesce_event.hh"
62 #include "sim/system.hh"
63 #endif
64
65 #if THE_ISA == ALPHA_ISA
66 #include "arch/alpha/osfpal.hh"
67 #endif
68
69 using namespace std;
70 using namespace TheISA;
71 using namespace ThePipeline;
72
73 InOrderCPU::TickEvent::TickEvent(InOrderCPU *c)
74 : Event(CPU_Tick_Pri), cpu(c)
75 { }
76
77
78 void
79 InOrderCPU::TickEvent::process()
80 {
81 cpu->tick();
82 }
83
84
85 const char *
86 InOrderCPU::TickEvent::description()
87 {
88 return "InOrderCPU tick event";
89 }
90
91 InOrderCPU::CPUEvent::CPUEvent(InOrderCPU *_cpu, CPUEventType e_type,
92 Fault fault, ThreadID _tid, DynInstPtr inst,
93 CPUEventPri event_pri)
94 : Event(event_pri), cpu(_cpu)
95 {
96 setEvent(e_type, fault, _tid, inst);
97 }
98
99
100 std::string InOrderCPU::eventNames[NumCPUEvents] =
101 {
102 "ActivateThread",
103 "ActivateNextReadyThread",
104 "DeactivateThread",
105 "HaltThread",
106 "SuspendThread",
107 "Trap",
108 "Syscall",
109 "SquashFromMemStall",
110 "UpdatePCs"
111 };
112
113 void
114 InOrderCPU::CPUEvent::process()
115 {
116 switch (cpuEventType)
117 {
118 case ActivateThread:
119 cpu->activateThread(tid);
120 cpu->resPool->activateThread(tid);
121 break;
122
123 case ActivateNextReadyThread:
124 cpu->activateNextReadyThread();
125 break;
126
127 case DeactivateThread:
128 cpu->deactivateThread(tid);
129 cpu->resPool->deactivateThread(tid);
130 break;
131
132 case HaltThread:
133 cpu->haltThread(tid);
134 cpu->resPool->deactivateThread(tid);
135 break;
136
137 case SuspendThread:
138 cpu->suspendThread(tid);
139 cpu->resPool->suspendThread(tid);
140 break;
141
142 case SquashFromMemStall:
143 cpu->squashDueToMemStall(inst->squashingStage, inst->seqNum, tid);
144 cpu->resPool->squashDueToMemStall(inst, inst->squashingStage,
145 inst->seqNum, tid);
146 break;
147
148 case Trap:
149 DPRINTF(InOrderCPU, "Trapping CPU\n");
150 cpu->trap(fault, tid, inst);
151 cpu->resPool->trap(fault, tid, inst);
152 break;
153
154 #if !FULL_SYSTEM
155 case Syscall:
156 cpu->syscall(inst->syscallNum, tid);
157 cpu->resPool->trap(fault, tid, inst);
158 break;
159 #endif
160 default:
161 fatal("Unrecognized Event Type %s", eventNames[cpuEventType]);
162 }
163
164 cpu->cpuEventRemoveList.push(this);
165 }
166
167
168
169 const char *
170 InOrderCPU::CPUEvent::description()
171 {
172 return "InOrderCPU event";
173 }
174
175 void
176 InOrderCPU::CPUEvent::scheduleEvent(int delay)
177 {
178 assert(!scheduled() || squashed());
179 cpu->reschedule(this, cpu->nextCycle(curTick() + cpu->ticks(delay)), true);
180 }
181
182 void
183 InOrderCPU::CPUEvent::unscheduleEvent()
184 {
185 if (scheduled())
186 squash();
187 }
188
189 InOrderCPU::InOrderCPU(Params *params)
190 : BaseCPU(params),
191 cpu_id(params->cpu_id),
192 coreType("default"),
193 _status(Idle),
194 tickEvent(this),
195 stageWidth(params->stageWidth),
196 timeBuffer(2 , 2),
197 removeInstsThisCycle(false),
198 activityRec(params->name, NumStages, 10, params->activity),
199 #if FULL_SYSTEM
200 system(params->system),
201 #endif // FULL_SYSTEM
202 #ifdef DEBUG
203 cpuEventNum(0),
204 resReqCount(0),
205 #endif // DEBUG
206 drainCount(0),
207 deferRegistration(false/*params->deferRegistration*/),
208 stageTracing(params->stageTracing),
209 lastRunningCycle(0),
210 instsPerSwitch(0)
211 {
212 ThreadID active_threads;
213 cpu_params = params;
214
215 resPool = new ResourcePool(this, params);
216
217 // Resize for Multithreading CPUs
218 thread.resize(numThreads);
219
220 #if FULL_SYSTEM
221 active_threads = 1;
222 #else
223 active_threads = params->workload.size();
224
225 if (active_threads > MaxThreads) {
226 panic("Workload Size too large. Increase the 'MaxThreads'"
227 "in your InOrder implementation or "
228 "edit your workload size.");
229 }
230
231
232 if (active_threads > 1) {
233 threadModel = (InOrderCPU::ThreadModel) params->threadModel;
234
235 if (threadModel == SMT) {
236 DPRINTF(InOrderCPU, "Setting Thread Model to SMT.\n");
237 } else if (threadModel == SwitchOnCacheMiss) {
238 DPRINTF(InOrderCPU, "Setting Thread Model to "
239 "Switch On Cache Miss\n");
240 }
241
242 } else {
243 threadModel = Single;
244 }
245
246
247
248 #endif
249
250 // Bind the fetch & data ports from the resource pool.
251 fetchPortIdx = resPool->getPortIdx(params->fetchMemPort);
252 if (fetchPortIdx == 0) {
253 fatal("Unable to find port to fetch instructions from.\n");
254 }
255
256 dataPortIdx = resPool->getPortIdx(params->dataMemPort);
257 if (dataPortIdx == 0) {
258 fatal("Unable to find port for data.\n");
259 }
260
261 for (ThreadID tid = 0; tid < numThreads; ++tid) {
262 pc[tid].set(0);
263 lastCommittedPC[tid].set(0);
264
265 #if FULL_SYSTEM
266 // SMT is not supported in FS mode yet.
267 assert(numThreads == 1);
268 thread[tid] = new Thread(this, 0);
269 #else
270 if (tid < (ThreadID)params->workload.size()) {
271 DPRINTF(InOrderCPU, "Workload[%i] process is %#x\n",
272 tid, params->workload[tid]->prog_fname);
273 thread[tid] =
274 new Thread(this, tid, params->workload[tid]);
275 } else {
276 //Allocate Empty thread so M5 can use later
277 //when scheduling threads to CPU
278 Process* dummy_proc = params->workload[0];
279 thread[tid] = new Thread(this, tid, dummy_proc);
280 }
281
282 // Eventually set this with parameters...
283 asid[tid] = tid;
284 #endif
285
286 // Setup the TC that will serve as the interface to the threads/CPU.
287 InOrderThreadContext *tc = new InOrderThreadContext;
288 tc->cpu = this;
289 tc->thread = thread[tid];
290
291 #if FULL_SYSTEM
292 // Setup quiesce event.
293 this->thread[tid]->quiesceEvent = new EndQuiesceEvent(tc);
294 #endif
295
296 // Give the thread the TC.
297 thread[tid]->tc = tc;
298 thread[tid]->setFuncExeInst(0);
299 globalSeqNum[tid] = 1;
300
301 // Add the TC to the CPU's list of TC's.
302 this->threadContexts.push_back(tc);
303 }
304
305 // Initialize TimeBuffer Stage Queues
306 for (int stNum=0; stNum < NumStages - 1; stNum++) {
307 stageQueue[stNum] = new StageQueue(NumStages, NumStages);
308 stageQueue[stNum]->id(stNum);
309 }
310
311
312 // Set Up Pipeline Stages
313 for (int stNum=0; stNum < NumStages; stNum++) {
314 if (stNum == 0)
315 pipelineStage[stNum] = new FirstStage(params, stNum);
316 else
317 pipelineStage[stNum] = new PipelineStage(params, stNum);
318
319 pipelineStage[stNum]->setCPU(this);
320 pipelineStage[stNum]->setActiveThreads(&activeThreads);
321 pipelineStage[stNum]->setTimeBuffer(&timeBuffer);
322
323 // Take Care of 1st/Nth stages
324 if (stNum > 0)
325 pipelineStage[stNum]->setPrevStageQueue(stageQueue[stNum - 1]);
326 if (stNum < NumStages - 1)
327 pipelineStage[stNum]->setNextStageQueue(stageQueue[stNum]);
328 }
329
330 // Initialize thread specific variables
331 for (ThreadID tid = 0; tid < numThreads; tid++) {
332 archRegDepMap[tid].setCPU(this);
333
334 nonSpecInstActive[tid] = false;
335 nonSpecSeqNum[tid] = 0;
336
337 squashSeqNum[tid] = MaxAddr;
338 lastSquashCycle[tid] = 0;
339
340 memset(intRegs[tid], 0, sizeof(intRegs[tid]));
341 memset(floatRegs.i[tid], 0, sizeof(floatRegs.i[tid]));
342 isa[tid].clear();
343
344 // Define dummy instructions and resource requests to be used.
345 dummyInst[tid] = new InOrderDynInst(this,
346 thread[tid],
347 0,
348 tid,
349 asid[tid]);
350
351 dummyReq[tid] = new ResourceRequest(resPool->getResource(0));
352
353 #if FULL_SYSTEM
354 // Use this dummy inst to force squashing behind every instruction
355 // in pipeline
356 dummyTrapInst[tid] = new InOrderDynInst(this, NULL, 0, 0, 0);
357 dummyTrapInst[tid]->seqNum = 0;
358 dummyTrapInst[tid]->squashSeqNum = 0;
359 dummyTrapInst[tid]->setTid(tid);
360 #endif
361
362 }
363
364 dummyReqInst = new InOrderDynInst(this, NULL, 0, 0, 0);
365 dummyReqInst->setSquashed();
366 dummyReqInst->resetInstCount();
367
368 dummyBufferInst = new InOrderDynInst(this, NULL, 0, 0, 0);
369 dummyBufferInst->setSquashed();
370 dummyBufferInst->resetInstCount();
371
372 endOfSkedIt = skedCache.end();
373 frontEndSked = createFrontEndSked();
374 faultSked = createFaultSked();
375
376 lastRunningCycle = curTick();
377
378 lockAddr = 0;
379 lockFlag = false;
380
381 // Schedule First Tick Event, CPU will reschedule itself from here on out.
382 scheduleTickEvent(0);
383 }
384
385 InOrderCPU::~InOrderCPU()
386 {
387 delete resPool;
388
389 SkedCacheIt sked_it = skedCache.begin();
390 SkedCacheIt sked_end = skedCache.end();
391
392 while (sked_it != sked_end) {
393 delete (*sked_it).second;
394 sked_it++;
395 }
396 skedCache.clear();
397 }
398
399 m5::hash_map<InOrderCPU::SkedID, ThePipeline::RSkedPtr> InOrderCPU::skedCache;
400
401 RSkedPtr
402 InOrderCPU::createFrontEndSked()
403 {
404 RSkedPtr res_sked = new ResourceSked();
405 int stage_num = 0;
406 StageScheduler F(res_sked, stage_num++);
407 StageScheduler D(res_sked, stage_num++);
408
409 // FETCH
410 F.needs(FetchSeq, FetchSeqUnit::AssignNextPC);
411 F.needs(ICache, FetchUnit::InitiateFetch);
412
413 // DECODE
414 D.needs(ICache, FetchUnit::CompleteFetch);
415 D.needs(Decode, DecodeUnit::DecodeInst);
416 D.needs(BPred, BranchPredictor::PredictBranch);
417 D.needs(FetchSeq, FetchSeqUnit::UpdateTargetPC);
418
419
420 DPRINTF(SkedCache, "Resource Sked created for instruction Front End\n");
421
422 return res_sked;
423 }
424
425 RSkedPtr
426 InOrderCPU::createFaultSked()
427 {
428 RSkedPtr res_sked = new ResourceSked();
429 StageScheduler W(res_sked, NumStages - 1);
430 W.needs(Grad, GraduationUnit::CheckFault);
431 DPRINTF(SkedCache, "Resource Sked created for instruction Faults\n");
432 return res_sked;
433 }
434
435 RSkedPtr
436 InOrderCPU::createBackEndSked(DynInstPtr inst)
437 {
438 RSkedPtr res_sked = lookupSked(inst);
439 if (res_sked != NULL) {
440 DPRINTF(SkedCache, "Found %s in sked cache.\n",
441 inst->instName());
442 return res_sked;
443 } else {
444 res_sked = new ResourceSked();
445 }
446
447 int stage_num = ThePipeline::BackEndStartStage;
448 StageScheduler X(res_sked, stage_num++);
449 StageScheduler M(res_sked, stage_num++);
450 StageScheduler W(res_sked, stage_num++);
451
452 if (!inst->staticInst) {
453 warn_once("Static Instruction Object Not Set. Can't Create"
454 " Back End Schedule");
455 return NULL;
456 }
457
458 // EXECUTE
459 X.needs(RegManager, UseDefUnit::MarkDestRegs);
460 for (int idx=0; idx < inst->numSrcRegs(); idx++) {
461 if (!idx || !inst->isStore()) {
462 X.needs(RegManager, UseDefUnit::ReadSrcReg, idx);
463 }
464 }
465
466 //@todo: schedule non-spec insts to operate on this cycle
467 // as long as all previous insts are done
468 if ( inst->isNonSpeculative() ) {
469 // skip execution of non speculative insts until later
470 } else if ( inst->isMemRef() ) {
471 if ( inst->isLoad() ) {
472 X.needs(AGEN, AGENUnit::GenerateAddr);
473 }
474 } else if (inst->opClass() == IntMultOp || inst->opClass() == IntDivOp) {
475 X.needs(MDU, MultDivUnit::StartMultDiv);
476 } else {
477 X.needs(ExecUnit, ExecutionUnit::ExecuteInst);
478 }
479
480 // MEMORY
481 if (!inst->isNonSpeculative()) {
482 if (inst->opClass() == IntMultOp || inst->opClass() == IntDivOp) {
483 M.needs(MDU, MultDivUnit::EndMultDiv);
484 }
485
486 if ( inst->isLoad() ) {
487 M.needs(DCache, CacheUnit::InitiateReadData);
488 if (inst->splitInst)
489 M.needs(DCache, CacheUnit::InitSecondSplitRead);
490 } else if ( inst->isStore() ) {
491 for (int i = 1; i < inst->numSrcRegs(); i++ ) {
492 M.needs(RegManager, UseDefUnit::ReadSrcReg, i);
493 }
494 M.needs(AGEN, AGENUnit::GenerateAddr);
495 M.needs(DCache, CacheUnit::InitiateWriteData);
496 if (inst->splitInst)
497 M.needs(DCache, CacheUnit::InitSecondSplitWrite);
498 }
499 }
500
501 // WRITEBACK
502 if (!inst->isNonSpeculative()) {
503 if ( inst->isLoad() ) {
504 W.needs(DCache, CacheUnit::CompleteReadData);
505 if (inst->splitInst)
506 W.needs(DCache, CacheUnit::CompleteSecondSplitRead);
507 } else if ( inst->isStore() ) {
508 W.needs(DCache, CacheUnit::CompleteWriteData);
509 if (inst->splitInst)
510 W.needs(DCache, CacheUnit::CompleteSecondSplitWrite);
511 }
512 } else {
513 // Finally, Execute Speculative Data
514 if (inst->isMemRef()) {
515 if (inst->isLoad()) {
516 W.needs(AGEN, AGENUnit::GenerateAddr);
517 W.needs(DCache, CacheUnit::InitiateReadData);
518 if (inst->splitInst)
519 W.needs(DCache, CacheUnit::InitSecondSplitRead);
520 W.needs(DCache, CacheUnit::CompleteReadData);
521 if (inst->splitInst)
522 W.needs(DCache, CacheUnit::CompleteSecondSplitRead);
523 } else if (inst->isStore()) {
524 if ( inst->numSrcRegs() >= 2 ) {
525 W.needs(RegManager, UseDefUnit::ReadSrcReg, 1);
526 }
527 W.needs(AGEN, AGENUnit::GenerateAddr);
528 W.needs(DCache, CacheUnit::InitiateWriteData);
529 if (inst->splitInst)
530 W.needs(DCache, CacheUnit::InitSecondSplitWrite);
531 W.needs(DCache, CacheUnit::CompleteWriteData);
532 if (inst->splitInst)
533 W.needs(DCache, CacheUnit::CompleteSecondSplitWrite);
534 }
535 } else {
536 W.needs(ExecUnit, ExecutionUnit::ExecuteInst);
537 }
538 }
539
540 W.needs(Grad, GraduationUnit::CheckFault);
541
542 for (int idx=0; idx < inst->numDestRegs(); idx++) {
543 W.needs(RegManager, UseDefUnit::WriteDestReg, idx);
544 }
545
546 if (inst->isControl())
547 W.needs(BPred, BranchPredictor::UpdatePredictor);
548
549 W.needs(Grad, GraduationUnit::GraduateInst);
550
551 // Insert Back Schedule into our cache of
552 // resource schedules
553 addToSkedCache(inst, res_sked);
554
555 DPRINTF(SkedCache, "Back End Sked Created for instruction: %s (%08p)\n",
556 inst->instName(), inst->getMachInst());
557 res_sked->print();
558
559 return res_sked;
560 }
561
562 void
563 InOrderCPU::regStats()
564 {
565 /* Register the Resource Pool's stats here.*/
566 resPool->regStats();
567
568 /* Register for each Pipeline Stage */
569 for (int stage_num=0; stage_num < ThePipeline::NumStages; stage_num++) {
570 pipelineStage[stage_num]->regStats();
571 }
572
573 /* Register any of the InOrderCPU's stats here.*/
574 instsPerCtxtSwitch
575 .name(name() + ".instsPerContextSwitch")
576 .desc("Instructions Committed Per Context Switch")
577 .prereq(instsPerCtxtSwitch);
578
579 numCtxtSwitches
580 .name(name() + ".contextSwitches")
581 .desc("Number of context switches");
582
583 comLoads
584 .name(name() + ".comLoads")
585 .desc("Number of Load instructions committed");
586
587 comStores
588 .name(name() + ".comStores")
589 .desc("Number of Store instructions committed");
590
591 comBranches
592 .name(name() + ".comBranches")
593 .desc("Number of Branches instructions committed");
594
595 comNops
596 .name(name() + ".comNops")
597 .desc("Number of Nop instructions committed");
598
599 comNonSpec
600 .name(name() + ".comNonSpec")
601 .desc("Number of Non-Speculative instructions committed");
602
603 comInts
604 .name(name() + ".comInts")
605 .desc("Number of Integer instructions committed");
606
607 comFloats
608 .name(name() + ".comFloats")
609 .desc("Number of Floating Point instructions committed");
610
611 timesIdled
612 .name(name() + ".timesIdled")
613 .desc("Number of times that the entire CPU went into an idle state and"
614 " unscheduled itself")
615 .prereq(timesIdled);
616
617 idleCycles
618 .name(name() + ".idleCycles")
619 .desc("Number of cycles cpu's stages were not processed");
620
621 runCycles
622 .name(name() + ".runCycles")
623 .desc("Number of cycles cpu stages are processed.");
624
625 activity
626 .name(name() + ".activity")
627 .desc("Percentage of cycles cpu is active")
628 .precision(6);
629 activity = (runCycles / numCycles) * 100;
630
631 threadCycles
632 .init(numThreads)
633 .name(name() + ".threadCycles")
634 .desc("Total Number of Cycles A Thread Was Active in CPU (Per-Thread)");
635
636 smtCycles
637 .name(name() + ".smtCycles")
638 .desc("Total number of cycles that the CPU was in SMT-mode");
639
640 committedInsts
641 .init(numThreads)
642 .name(name() + ".committedInsts")
643 .desc("Number of Instructions Simulated (Per-Thread)");
644
645 smtCommittedInsts
646 .init(numThreads)
647 .name(name() + ".smtCommittedInsts")
648 .desc("Number of SMT Instructions Simulated (Per-Thread)");
649
650 totalCommittedInsts
651 .name(name() + ".committedInsts_total")
652 .desc("Number of Instructions Simulated (Total)");
653
654 cpi
655 .name(name() + ".cpi")
656 .desc("CPI: Cycles Per Instruction (Per-Thread)")
657 .precision(6);
658 cpi = numCycles / committedInsts;
659
660 smtCpi
661 .name(name() + ".smt_cpi")
662 .desc("CPI: Total SMT-CPI")
663 .precision(6);
664 smtCpi = smtCycles / smtCommittedInsts;
665
666 totalCpi
667 .name(name() + ".cpi_total")
668 .desc("CPI: Total CPI of All Threads")
669 .precision(6);
670 totalCpi = numCycles / totalCommittedInsts;
671
672 ipc
673 .name(name() + ".ipc")
674 .desc("IPC: Instructions Per Cycle (Per-Thread)")
675 .precision(6);
676 ipc = committedInsts / numCycles;
677
678 smtIpc
679 .name(name() + ".smt_ipc")
680 .desc("IPC: Total SMT-IPC")
681 .precision(6);
682 smtIpc = smtCommittedInsts / smtCycles;
683
684 totalIpc
685 .name(name() + ".ipc_total")
686 .desc("IPC: Total IPC of All Threads")
687 .precision(6);
688 totalIpc = totalCommittedInsts / numCycles;
689
690 BaseCPU::regStats();
691 }
692
693
694 void
695 InOrderCPU::tick()
696 {
697 DPRINTF(InOrderCPU, "\n\nInOrderCPU: Ticking main, InOrderCPU.\n");
698
699 ++numCycles;
700
701 bool pipes_idle = true;
702
703 //Tick each of the stages
704 for (int stNum=NumStages - 1; stNum >= 0 ; stNum--) {
705 pipelineStage[stNum]->tick();
706
707 pipes_idle = pipes_idle && pipelineStage[stNum]->idle;
708 }
709
710 checkForInterrupts();
711
712 if (pipes_idle)
713 idleCycles++;
714 else
715 runCycles++;
716
717 // Now advance the time buffers one tick
718 timeBuffer.advance();
719 for (int sqNum=0; sqNum < NumStages - 1; sqNum++) {
720 stageQueue[sqNum]->advance();
721 }
722 activityRec.advance();
723
724 // Any squashed events, or insts then remove them now
725 cleanUpRemovedEvents();
726 cleanUpRemovedInsts();
727
728 // Re-schedule CPU for this cycle
729 if (!tickEvent.scheduled()) {
730 if (_status == SwitchedOut) {
731 // increment stat
732 lastRunningCycle = curTick();
733 } else if (!activityRec.active()) {
734 DPRINTF(InOrderCPU, "sleeping CPU.\n");
735 lastRunningCycle = curTick();
736 timesIdled++;
737 } else {
738 //Tick next_tick = curTick() + cycles(1);
739 //tickEvent.schedule(next_tick);
740 schedule(&tickEvent, nextCycle(curTick() + 1));
741 DPRINTF(InOrderCPU, "Scheduled CPU for next tick @ %i.\n",
742 nextCycle(curTick() + 1));
743 }
744 }
745
746 tickThreadStats();
747 updateThreadPriority();
748 }
749
750
751 void
752 InOrderCPU::init()
753 {
754 if (!deferRegistration) {
755 registerThreadContexts();
756 }
757
758 // Set inSyscall so that the CPU doesn't squash when initially
759 // setting up registers.
760 for (ThreadID tid = 0; tid < numThreads; ++tid)
761 thread[tid]->inSyscall = true;
762
763 #if FULL_SYSTEM
764 for (ThreadID tid = 0; tid < numThreads; tid++) {
765 ThreadContext *src_tc = threadContexts[tid];
766 TheISA::initCPU(src_tc, src_tc->contextId());
767 }
768 #endif
769
770 // Clear inSyscall.
771 for (ThreadID tid = 0; tid < numThreads; ++tid)
772 thread[tid]->inSyscall = false;
773
774 // Call Initializiation Routine for Resource Pool
775 resPool->init();
776 }
777
778 Port*
779 InOrderCPU::getPort(const std::string &if_name, int idx)
780 {
781 return resPool->getPort(if_name, idx);
782 }
783
784 #if FULL_SYSTEM
785 Fault
786 InOrderCPU::hwrei(ThreadID tid)
787 {
788 #if THE_ISA == ALPHA_ISA
789 // Need to clear the lock flag upon returning from an interrupt.
790 setMiscRegNoEffect(AlphaISA::MISCREG_LOCKFLAG, false, tid);
791
792 thread[tid]->kernelStats->hwrei();
793 // FIXME: XXX check for interrupts? XXX
794 #endif
795
796 return NoFault;
797 }
798
799
800 bool
801 InOrderCPU::simPalCheck(int palFunc, ThreadID tid)
802 {
803 #if THE_ISA == ALPHA_ISA
804 if (this->thread[tid]->kernelStats)
805 this->thread[tid]->kernelStats->callpal(palFunc,
806 this->threadContexts[tid]);
807
808 switch (palFunc) {
809 case PAL::halt:
810 halt();
811 if (--System::numSystemsRunning == 0)
812 exitSimLoop("all cpus halted");
813 break;
814
815 case PAL::bpt:
816 case PAL::bugchk:
817 if (this->system->breakpoint())
818 return false;
819 break;
820 }
821 #endif
822 return true;
823 }
824
825 void
826 InOrderCPU::checkForInterrupts()
827 {
828 for (int i = 0; i < threadContexts.size(); i++) {
829 ThreadContext *tc = threadContexts[i];
830
831 if (interrupts->checkInterrupts(tc)) {
832 Fault interrupt = interrupts->getInterrupt(tc);
833
834 if (interrupt != NoFault) {
835 DPRINTF(Interrupt, "Processing Intterupt for [tid:%i].\n",
836 tc->threadId());
837
838 ThreadID tid = tc->threadId();
839 interrupts->updateIntrInfo(tc);
840
841 // Squash from Last Stage in Pipeline
842 unsigned last_stage = NumStages - 1;
843 dummyTrapInst[tid]->squashingStage = last_stage;
844 pipelineStage[last_stage]->setupSquash(dummyTrapInst[tid],
845 tid);
846
847 // By default, setupSquash will always squash from stage + 1
848 pipelineStage[BackEndStartStage - 1]->setupSquash(dummyTrapInst[tid],
849 tid);
850
851 // Schedule Squash Through-out Resource Pool
852 resPool->scheduleEvent(
853 (InOrderCPU::CPUEventType)ResourcePool::SquashAll,
854 dummyTrapInst[tid], 0);
855
856 // Finally, Setup Trap to happen at end of cycle
857 trapContext(interrupt, tid, dummyTrapInst[tid]);
858 }
859 }
860 }
861 }
862
863 Fault
864 InOrderCPU::getInterrupts()
865 {
866 // Check if there are any outstanding interrupts
867 return interrupts->getInterrupt(threadContexts[0]);
868 }
869
870
871 void
872 InOrderCPU::processInterrupts(Fault interrupt)
873 {
874 // Check for interrupts here. For now can copy the code that
875 // exists within isa_fullsys_traits.hh. Also assume that thread 0
876 // is the one that handles the interrupts.
877 // @todo: Possibly consolidate the interrupt checking code.
878 // @todo: Allow other threads to handle interrupts.
879
880 assert(interrupt != NoFault);
881 interrupts->updateIntrInfo(threadContexts[0]);
882
883 DPRINTF(InOrderCPU, "Interrupt %s being handled\n", interrupt->name());
884
885 // Note: Context ID ok here? Impl. of FS mode needs to revisit this
886 trap(interrupt, threadContexts[0]->contextId(), dummyBufferInst);
887 }
888
889
890 void
891 InOrderCPU::updateMemPorts()
892 {
893 // Update all ThreadContext's memory ports (Functional/Virtual
894 // Ports)
895 ThreadID size = thread.size();
896 for (ThreadID i = 0; i < size; ++i)
897 thread[i]->connectMemPorts(thread[i]->getTC());
898 }
899 #endif
900
901 void
902 InOrderCPU::trapContext(Fault fault, ThreadID tid, DynInstPtr inst, int delay)
903 {
904 scheduleCpuEvent(Trap, fault, tid, inst, delay);
905 }
906
907 void
908 InOrderCPU::trap(Fault fault, ThreadID tid, DynInstPtr inst)
909 {
910 fault->invoke(tcBase(tid), inst->staticInst);
911 removePipelineStalls(tid);
912 }
913
914 void
915 InOrderCPU::squashFromMemStall(DynInstPtr inst, ThreadID tid, int delay)
916 {
917 scheduleCpuEvent(SquashFromMemStall, NoFault, tid, inst, delay);
918 }
919
920
921 void
922 InOrderCPU::squashDueToMemStall(int stage_num, InstSeqNum seq_num,
923 ThreadID tid)
924 {
925 DPRINTF(InOrderCPU, "Squashing Pipeline Stages Due to Memory Stall...\n");
926
927 // Squash all instructions in each stage including
928 // instruction that caused the squash (seq_num - 1)
929 // NOTE: The stage bandwidth needs to be cleared so thats why
930 // the stalling instruction is squashed as well. The stalled
931 // instruction is previously placed in another intermediate buffer
932 // while it's stall is being handled.
933 InstSeqNum squash_seq_num = seq_num - 1;
934
935 for (int stNum=stage_num; stNum >= 0 ; stNum--) {
936 pipelineStage[stNum]->squashDueToMemStall(squash_seq_num, tid);
937 }
938 }
939
940 void
941 InOrderCPU::scheduleCpuEvent(CPUEventType c_event, Fault fault,
942 ThreadID tid, DynInstPtr inst,
943 unsigned delay, CPUEventPri event_pri)
944 {
945 CPUEvent *cpu_event = new CPUEvent(this, c_event, fault, tid, inst,
946 event_pri);
947
948 Tick sked_tick = nextCycle(curTick() + ticks(delay));
949 if (delay >= 0) {
950 DPRINTF(InOrderCPU, "Scheduling CPU Event (%s) for cycle %i, [tid:%i].\n",
951 eventNames[c_event], curTick() + delay, tid);
952 schedule(cpu_event, sked_tick);
953 } else {
954 cpu_event->process();
955 cpuEventRemoveList.push(cpu_event);
956 }
957
958 // Broadcast event to the Resource Pool
959 // Need to reset tid just in case this is a dummy instruction
960 inst->setTid(tid);
961 resPool->scheduleEvent(c_event, inst, 0, 0, tid);
962 }
963
964 bool
965 InOrderCPU::isThreadActive(ThreadID tid)
966 {
967 list<ThreadID>::iterator isActive =
968 std::find(activeThreads.begin(), activeThreads.end(), tid);
969
970 return (isActive != activeThreads.end());
971 }
972
973 bool
974 InOrderCPU::isThreadReady(ThreadID tid)
975 {
976 list<ThreadID>::iterator isReady =
977 std::find(readyThreads.begin(), readyThreads.end(), tid);
978
979 return (isReady != readyThreads.end());
980 }
981
982 bool
983 InOrderCPU::isThreadSuspended(ThreadID tid)
984 {
985 list<ThreadID>::iterator isSuspended =
986 std::find(suspendedThreads.begin(), suspendedThreads.end(), tid);
987
988 return (isSuspended != suspendedThreads.end());
989 }
990
991 void
992 InOrderCPU::activateNextReadyThread()
993 {
994 if (readyThreads.size() >= 1) {
995 ThreadID ready_tid = readyThreads.front();
996
997 // Activate in Pipeline
998 activateThread(ready_tid);
999
1000 // Activate in Resource Pool
1001 resPool->activateThread(ready_tid);
1002
1003 list<ThreadID>::iterator ready_it =
1004 std::find(readyThreads.begin(), readyThreads.end(), ready_tid);
1005 readyThreads.erase(ready_it);
1006 } else {
1007 DPRINTF(InOrderCPU,
1008 "Attempting to activate new thread, but No Ready Threads to"
1009 "activate.\n");
1010 DPRINTF(InOrderCPU,
1011 "Unable to switch to next active thread.\n");
1012 }
1013 }
1014
1015 void
1016 InOrderCPU::activateThread(ThreadID tid)
1017 {
1018 if (isThreadSuspended(tid)) {
1019 DPRINTF(InOrderCPU,
1020 "Removing [tid:%i] from suspended threads list.\n", tid);
1021
1022 list<ThreadID>::iterator susp_it =
1023 std::find(suspendedThreads.begin(), suspendedThreads.end(),
1024 tid);
1025 suspendedThreads.erase(susp_it);
1026 }
1027
1028 if (threadModel == SwitchOnCacheMiss &&
1029 numActiveThreads() == 1) {
1030 DPRINTF(InOrderCPU,
1031 "Ignoring activation of [tid:%i], since [tid:%i] is "
1032 "already running.\n", tid, activeThreadId());
1033
1034 DPRINTF(InOrderCPU,"Placing [tid:%i] on ready threads list\n",
1035 tid);
1036
1037 readyThreads.push_back(tid);
1038
1039 } else if (!isThreadActive(tid)) {
1040 DPRINTF(InOrderCPU,
1041 "Adding [tid:%i] to active threads list.\n", tid);
1042 activeThreads.push_back(tid);
1043
1044 activateThreadInPipeline(tid);
1045
1046 thread[tid]->lastActivate = curTick();
1047
1048 tcBase(tid)->setStatus(ThreadContext::Active);
1049
1050 wakeCPU();
1051
1052 numCtxtSwitches++;
1053 }
1054 }
1055
1056 void
1057 InOrderCPU::activateThreadInPipeline(ThreadID tid)
1058 {
1059 for (int stNum=0; stNum < NumStages; stNum++) {
1060 pipelineStage[stNum]->activateThread(tid);
1061 }
1062 }
1063
1064 void
1065 InOrderCPU::deactivateContext(ThreadID tid, int delay)
1066 {
1067 DPRINTF(InOrderCPU,"[tid:%i]: Deactivating ...\n", tid);
1068
1069 scheduleCpuEvent(DeactivateThread, NoFault, tid, dummyInst[tid], delay);
1070
1071 // Be sure to signal that there's some activity so the CPU doesn't
1072 // deschedule itself.
1073 activityRec.activity();
1074
1075 _status = Running;
1076 }
1077
1078 void
1079 InOrderCPU::deactivateThread(ThreadID tid)
1080 {
1081 DPRINTF(InOrderCPU, "[tid:%i]: Calling deactivate thread.\n", tid);
1082
1083 if (isThreadActive(tid)) {
1084 DPRINTF(InOrderCPU,"[tid:%i]: Removing from active threads list\n",
1085 tid);
1086 list<ThreadID>::iterator thread_it =
1087 std::find(activeThreads.begin(), activeThreads.end(), tid);
1088
1089 removePipelineStalls(*thread_it);
1090
1091 activeThreads.erase(thread_it);
1092
1093 // Ideally, this should be triggered from the
1094 // suspendContext/Thread functions
1095 tcBase(tid)->setStatus(ThreadContext::Suspended);
1096 }
1097
1098 assert(!isThreadActive(tid));
1099 }
1100
1101 void
1102 InOrderCPU::removePipelineStalls(ThreadID tid)
1103 {
1104 DPRINTF(InOrderCPU,"[tid:%i]: Removing all pipeline stalls\n",
1105 tid);
1106
1107 for (int stNum = 0; stNum < NumStages ; stNum++) {
1108 pipelineStage[stNum]->removeStalls(tid);
1109 }
1110
1111 }
1112
1113 void
1114 InOrderCPU::updateThreadPriority()
1115 {
1116 if (activeThreads.size() > 1)
1117 {
1118 //DEFAULT TO ROUND ROBIN SCHEME
1119 //e.g. Move highest priority to end of thread list
1120 list<ThreadID>::iterator list_begin = activeThreads.begin();
1121 list<ThreadID>::iterator list_end = activeThreads.end();
1122
1123 unsigned high_thread = *list_begin;
1124
1125 activeThreads.erase(list_begin);
1126
1127 activeThreads.push_back(high_thread);
1128 }
1129 }
1130
1131 inline void
1132 InOrderCPU::tickThreadStats()
1133 {
1134 /** Keep track of cycles that each thread is active */
1135 list<ThreadID>::iterator thread_it = activeThreads.begin();
1136 while (thread_it != activeThreads.end()) {
1137 threadCycles[*thread_it]++;
1138 thread_it++;
1139 }
1140
1141 // Keep track of cycles where SMT is active
1142 if (activeThreads.size() > 1) {
1143 smtCycles++;
1144 }
1145 }
1146
1147 void
1148 InOrderCPU::activateContext(ThreadID tid, int delay)
1149 {
1150 DPRINTF(InOrderCPU,"[tid:%i]: Activating ...\n", tid);
1151
1152
1153 scheduleCpuEvent(ActivateThread, NoFault, tid, dummyInst[tid], delay);
1154
1155 // Be sure to signal that there's some activity so the CPU doesn't
1156 // deschedule itself.
1157 activityRec.activity();
1158
1159 _status = Running;
1160 }
1161
1162 void
1163 InOrderCPU::activateNextReadyContext(int delay)
1164 {
1165 DPRINTF(InOrderCPU,"Activating next ready thread\n");
1166
1167 scheduleCpuEvent(ActivateNextReadyThread, NoFault, 0/*tid*/, dummyInst[0],
1168 delay, ActivateNextReadyThread_Pri);
1169
1170 // Be sure to signal that there's some activity so the CPU doesn't
1171 // deschedule itself.
1172 activityRec.activity();
1173
1174 _status = Running;
1175 }
1176
1177 void
1178 InOrderCPU::haltContext(ThreadID tid, int delay)
1179 {
1180 DPRINTF(InOrderCPU, "[tid:%i]: Calling Halt Context...\n", tid);
1181
1182 scheduleCpuEvent(HaltThread, NoFault, tid, dummyInst[tid], delay);
1183
1184 activityRec.activity();
1185 }
1186
1187 void
1188 InOrderCPU::haltThread(ThreadID tid)
1189 {
1190 DPRINTF(InOrderCPU, "[tid:%i]: Placing on Halted Threads List...\n", tid);
1191 deactivateThread(tid);
1192 squashThreadInPipeline(tid);
1193 haltedThreads.push_back(tid);
1194
1195 tcBase(tid)->setStatus(ThreadContext::Halted);
1196
1197 if (threadModel == SwitchOnCacheMiss) {
1198 activateNextReadyContext();
1199 }
1200 }
1201
1202 void
1203 InOrderCPU::suspendContext(ThreadID tid, int delay)
1204 {
1205 scheduleCpuEvent(SuspendThread, NoFault, tid, dummyInst[tid], delay);
1206 }
1207
1208 void
1209 InOrderCPU::suspendThread(ThreadID tid)
1210 {
1211 DPRINTF(InOrderCPU, "[tid:%i]: Placing on Suspended Threads List...\n",
1212 tid);
1213 deactivateThread(tid);
1214 suspendedThreads.push_back(tid);
1215 thread[tid]->lastSuspend = curTick();
1216
1217 tcBase(tid)->setStatus(ThreadContext::Suspended);
1218 }
1219
1220 void
1221 InOrderCPU::squashThreadInPipeline(ThreadID tid)
1222 {
1223 //Squash all instructions in each stage
1224 for (int stNum=NumStages - 1; stNum >= 0 ; stNum--) {
1225 pipelineStage[stNum]->squash(0 /*seq_num*/, tid);
1226 }
1227 }
1228
1229 PipelineStage*
1230 InOrderCPU::getPipeStage(int stage_num)
1231 {
1232 return pipelineStage[stage_num];
1233 }
1234
1235
1236 RegIndex
1237 InOrderCPU::flattenRegIdx(RegIndex reg_idx, RegType &reg_type, ThreadID tid)
1238 {
1239 if (reg_idx < FP_Base_DepTag) {
1240 reg_type = IntType;
1241 return isa[tid].flattenIntIndex(reg_idx);
1242 } else if (reg_idx < Ctrl_Base_DepTag) {
1243 reg_type = FloatType;
1244 reg_idx -= FP_Base_DepTag;
1245 return isa[tid].flattenFloatIndex(reg_idx);
1246 } else {
1247 reg_type = MiscType;
1248 return reg_idx - TheISA::Ctrl_Base_DepTag;
1249 }
1250 }
1251
1252 uint64_t
1253 InOrderCPU::readIntReg(RegIndex reg_idx, ThreadID tid)
1254 {
1255 DPRINTF(IntRegs, "[tid:%i]: Reading Int. Reg %i as %x\n",
1256 tid, reg_idx, intRegs[tid][reg_idx]);
1257
1258 return intRegs[tid][reg_idx];
1259 }
1260
1261 FloatReg
1262 InOrderCPU::readFloatReg(RegIndex reg_idx, ThreadID tid)
1263 {
1264 DPRINTF(FloatRegs, "[tid:%i]: Reading Float Reg %i as %x, %08f\n",
1265 tid, reg_idx, floatRegs.i[tid][reg_idx], floatRegs.f[tid][reg_idx]);
1266
1267 return floatRegs.f[tid][reg_idx];
1268 }
1269
1270 FloatRegBits
1271 InOrderCPU::readFloatRegBits(RegIndex reg_idx, ThreadID tid)
1272 {
1273 DPRINTF(FloatRegs, "[tid:%i]: Reading Float Reg %i as %x, %08f\n",
1274 tid, reg_idx, floatRegs.i[tid][reg_idx], floatRegs.f[tid][reg_idx]);
1275
1276 return floatRegs.i[tid][reg_idx];
1277 }
1278
1279 void
1280 InOrderCPU::setIntReg(RegIndex reg_idx, uint64_t val, ThreadID tid)
1281 {
1282 if (reg_idx == TheISA::ZeroReg) {
1283 DPRINTF(IntRegs, "[tid:%i]: Ignoring Setting of ISA-ZeroReg "
1284 "(Int. Reg %i) to %x\n", tid, reg_idx, val);
1285 return;
1286 } else {
1287 DPRINTF(IntRegs, "[tid:%i]: Setting Int. Reg %i to %x\n",
1288 tid, reg_idx, val);
1289
1290 intRegs[tid][reg_idx] = val;
1291 }
1292 }
1293
1294
1295 void
1296 InOrderCPU::setFloatReg(RegIndex reg_idx, FloatReg val, ThreadID tid)
1297 {
1298 floatRegs.f[tid][reg_idx] = val;
1299 DPRINTF(FloatRegs, "[tid:%i]: Setting Float. Reg %i bits to "
1300 "%x, %08f\n",
1301 tid, reg_idx,
1302 floatRegs.i[tid][reg_idx],
1303 floatRegs.f[tid][reg_idx]);
1304 }
1305
1306
1307 void
1308 InOrderCPU::setFloatRegBits(RegIndex reg_idx, FloatRegBits val, ThreadID tid)
1309 {
1310 floatRegs.i[tid][reg_idx] = val;
1311 DPRINTF(FloatRegs, "[tid:%i]: Setting Float. Reg %i bits to "
1312 "%x, %08f\n",
1313 tid, reg_idx,
1314 floatRegs.i[tid][reg_idx],
1315 floatRegs.f[tid][reg_idx]);
1316 }
1317
1318 uint64_t
1319 InOrderCPU::readRegOtherThread(unsigned reg_idx, ThreadID tid)
1320 {
1321 // If Default value is set, then retrieve target thread
1322 if (tid == InvalidThreadID) {
1323 tid = TheISA::getTargetThread(tcBase(tid));
1324 }
1325
1326 if (reg_idx < FP_Base_DepTag) {
1327 // Integer Register File
1328 return readIntReg(reg_idx, tid);
1329 } else if (reg_idx < Ctrl_Base_DepTag) {
1330 // Float Register File
1331 reg_idx -= FP_Base_DepTag;
1332 return readFloatRegBits(reg_idx, tid);
1333 } else {
1334 reg_idx -= Ctrl_Base_DepTag;
1335 return readMiscReg(reg_idx, tid); // Misc. Register File
1336 }
1337 }
1338 void
1339 InOrderCPU::setRegOtherThread(unsigned reg_idx, const MiscReg &val,
1340 ThreadID tid)
1341 {
1342 // If Default value is set, then retrieve target thread
1343 if (tid == InvalidThreadID) {
1344 tid = TheISA::getTargetThread(tcBase(tid));
1345 }
1346
1347 if (reg_idx < FP_Base_DepTag) { // Integer Register File
1348 setIntReg(reg_idx, val, tid);
1349 } else if (reg_idx < Ctrl_Base_DepTag) { // Float Register File
1350 reg_idx -= FP_Base_DepTag;
1351 setFloatRegBits(reg_idx, val, tid);
1352 } else {
1353 reg_idx -= Ctrl_Base_DepTag;
1354 setMiscReg(reg_idx, val, tid); // Misc. Register File
1355 }
1356 }
1357
1358 MiscReg
1359 InOrderCPU::readMiscRegNoEffect(int misc_reg, ThreadID tid)
1360 {
1361 return isa[tid].readMiscRegNoEffect(misc_reg);
1362 }
1363
1364 MiscReg
1365 InOrderCPU::readMiscReg(int misc_reg, ThreadID tid)
1366 {
1367 DPRINTF(InOrderCPU, "MiscReg: %i\n", misc_reg);
1368 DPRINTF(InOrderCPU, "tid: %i\n", tid);
1369 DPRINTF(InOrderCPU, "tcBase: %x\n", tcBase(tid));
1370 DPRINTF(InOrderCPU, "isa-tid: %x\n", &isa[tid]);
1371
1372 return isa[tid].readMiscReg(misc_reg, tcBase(tid));
1373 }
1374
1375 void
1376 InOrderCPU::setMiscRegNoEffect(int misc_reg, const MiscReg &val, ThreadID tid)
1377 {
1378 isa[tid].setMiscRegNoEffect(misc_reg, val);
1379 }
1380
1381 void
1382 InOrderCPU::setMiscReg(int misc_reg, const MiscReg &val, ThreadID tid)
1383 {
1384 isa[tid].setMiscReg(misc_reg, val, tcBase(tid));
1385 }
1386
1387
1388 InOrderCPU::ListIt
1389 InOrderCPU::addInst(DynInstPtr inst)
1390 {
1391 ThreadID tid = inst->readTid();
1392
1393 instList[tid].push_back(inst);
1394
1395 return --(instList[tid].end());
1396 }
1397
1398 InOrderCPU::ListIt
1399 InOrderCPU::findInst(InstSeqNum seq_num, ThreadID tid)
1400 {
1401 ListIt it = instList[tid].begin();
1402 ListIt end = instList[tid].end();
1403
1404 while (it != end) {
1405 if ((*it)->seqNum == seq_num)
1406 return it;
1407 else if ((*it)->seqNum > seq_num)
1408 break;
1409
1410 it++;
1411 }
1412
1413 return instList[tid].end();
1414 }
1415
1416 void
1417 InOrderCPU::updateContextSwitchStats()
1418 {
1419 // Set Average Stat Here, then reset to 0
1420 instsPerCtxtSwitch = instsPerSwitch;
1421 instsPerSwitch = 0;
1422 }
1423
1424
1425 void
1426 InOrderCPU::instDone(DynInstPtr inst, ThreadID tid)
1427 {
1428 // Set the nextPC to be fetched if this is the last instruction
1429 // committed
1430 // ========
1431 // This contributes to the precise state of the CPU
1432 // which can be used when restoring a thread to the CPU after after any
1433 // type of context switching activity (fork, exception, etc.)
1434 TheISA::PCState comm_pc = inst->pcState();
1435 lastCommittedPC[tid] = comm_pc;
1436 TheISA::advancePC(comm_pc, inst->staticInst);
1437 pcState(comm_pc, tid);
1438
1439 //@todo: may be unnecessary with new-ISA-specific branch handling code
1440 if (inst->isControl()) {
1441 thread[tid]->lastGradIsBranch = true;
1442 thread[tid]->lastBranchPC = inst->pcState();
1443 TheISA::advancePC(thread[tid]->lastBranchPC, inst->staticInst);
1444 } else {
1445 thread[tid]->lastGradIsBranch = false;
1446 }
1447
1448
1449 // Finalize Trace Data For Instruction
1450 if (inst->traceData) {
1451 //inst->traceData->setCycle(curTick());
1452 inst->traceData->setFetchSeq(inst->seqNum);
1453 //inst->traceData->setCPSeq(cpu->tcBase(tid)->numInst);
1454 inst->traceData->dump();
1455 delete inst->traceData;
1456 inst->traceData = NULL;
1457 }
1458
1459 // Increment active thread's instruction count
1460 instsPerSwitch++;
1461
1462 // Increment thread-state's instruction count
1463 thread[tid]->numInst++;
1464
1465 // Increment thread-state's instruction stats
1466 thread[tid]->numInsts++;
1467
1468 // Count committed insts per thread stats
1469 committedInsts[tid]++;
1470
1471 // Count total insts committed stat
1472 totalCommittedInsts++;
1473
1474 // Count SMT-committed insts per thread stat
1475 if (numActiveThreads() > 1) {
1476 smtCommittedInsts[tid]++;
1477 }
1478
1479 // Instruction-Mix Stats
1480 if (inst->isLoad()) {
1481 comLoads++;
1482 } else if (inst->isStore()) {
1483 comStores++;
1484 } else if (inst->isControl()) {
1485 comBranches++;
1486 } else if (inst->isNop()) {
1487 comNops++;
1488 } else if (inst->isNonSpeculative()) {
1489 comNonSpec++;
1490 } else if (inst->isInteger()) {
1491 comInts++;
1492 } else if (inst->isFloating()) {
1493 comFloats++;
1494 }
1495
1496 // Check for instruction-count-based events.
1497 comInstEventQueue[tid]->serviceEvents(thread[tid]->numInst);
1498
1499 // Finally, remove instruction from CPU
1500 removeInst(inst);
1501 }
1502
1503 // currently unused function, but substitute repetitive code w/this function
1504 // call
1505 void
1506 InOrderCPU::addToRemoveList(DynInstPtr inst)
1507 {
1508 removeInstsThisCycle = true;
1509 if (!inst->isRemoveList()) {
1510 DPRINTF(InOrderCPU, "Pushing instruction [tid:%i] PC %s "
1511 "[sn:%lli] to remove list\n",
1512 inst->threadNumber, inst->pcState(), inst->seqNum);
1513 inst->setRemoveList();
1514 removeList.push(inst->getInstListIt());
1515 } else {
1516 DPRINTF(InOrderCPU, "Ignoring instruction removal for [tid:%i] PC %s "
1517 "[sn:%lli], already remove list\n",
1518 inst->threadNumber, inst->pcState(), inst->seqNum);
1519 }
1520
1521 }
1522
1523 void
1524 InOrderCPU::removeInst(DynInstPtr inst)
1525 {
1526 DPRINTF(InOrderCPU, "Removing graduated instruction [tid:%i] PC %s "
1527 "[sn:%lli]\n",
1528 inst->threadNumber, inst->pcState(), inst->seqNum);
1529
1530 removeInstsThisCycle = true;
1531
1532 // Remove the instruction.
1533 if (!inst->isRemoveList()) {
1534 DPRINTF(InOrderCPU, "Pushing instruction [tid:%i] PC %s "
1535 "[sn:%lli] to remove list\n",
1536 inst->threadNumber, inst->pcState(), inst->seqNum);
1537 inst->setRemoveList();
1538 removeList.push(inst->getInstListIt());
1539 } else {
1540 DPRINTF(InOrderCPU, "Ignoring instruction removal for [tid:%i] PC %s "
1541 "[sn:%lli], already on remove list\n",
1542 inst->threadNumber, inst->pcState(), inst->seqNum);
1543 }
1544
1545 }
1546
1547 void
1548 InOrderCPU::removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid)
1549 {
1550 //assert(!instList[tid].empty());
1551
1552 removeInstsThisCycle = true;
1553
1554 ListIt inst_iter = instList[tid].end();
1555
1556 inst_iter--;
1557
1558 DPRINTF(InOrderCPU, "Squashing instructions from CPU instruction "
1559 "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1560 tid, seq_num, (*inst_iter)->seqNum);
1561
1562 while ((*inst_iter)->seqNum > seq_num) {
1563
1564 bool break_loop = (inst_iter == instList[tid].begin());
1565
1566 squashInstIt(inst_iter, tid);
1567
1568 inst_iter--;
1569
1570 if (break_loop)
1571 break;
1572 }
1573 }
1574
1575
1576 inline void
1577 InOrderCPU::squashInstIt(const ListIt inst_it, ThreadID tid)
1578 {
1579 DynInstPtr inst = (*inst_it);
1580 if (inst->threadNumber == tid) {
1581 DPRINTF(InOrderCPU, "Squashing instruction, "
1582 "[tid:%i] [sn:%lli] PC %s\n",
1583 inst->threadNumber,
1584 inst->seqNum,
1585 inst->pcState());
1586
1587 inst->setSquashed();
1588 archRegDepMap[tid].remove(inst);
1589
1590 if (!inst->isRemoveList()) {
1591 DPRINTF(InOrderCPU, "Pushing instruction [tid:%i] PC %s "
1592 "[sn:%lli] to remove list\n",
1593 inst->threadNumber, inst->pcState(),
1594 inst->seqNum);
1595 inst->setRemoveList();
1596 removeList.push(inst_it);
1597 } else {
1598 DPRINTF(InOrderCPU, "Ignoring instruction removal for [tid:%i]"
1599 " PC %s [sn:%lli], already on remove list\n",
1600 inst->threadNumber, inst->pcState(),
1601 inst->seqNum);
1602 }
1603
1604 }
1605
1606 }
1607
1608
1609 void
1610 InOrderCPU::cleanUpRemovedInsts()
1611 {
1612 while (!removeList.empty()) {
1613 DPRINTF(InOrderCPU, "Removing instruction, "
1614 "[tid:%i] [sn:%lli] PC %s\n",
1615 (*removeList.front())->threadNumber,
1616 (*removeList.front())->seqNum,
1617 (*removeList.front())->pcState());
1618
1619 DynInstPtr inst = *removeList.front();
1620 ThreadID tid = inst->threadNumber;
1621
1622 // Remove From Register Dependency Map, If Necessary
1623 // archRegDepMap[tid].remove(inst);
1624
1625 // Clear if Non-Speculative
1626 if (inst->staticInst &&
1627 inst->seqNum == nonSpecSeqNum[tid] &&
1628 nonSpecInstActive[tid] == true) {
1629 nonSpecInstActive[tid] = false;
1630 }
1631
1632 inst->onInstList = false;
1633
1634 instList[tid].erase(removeList.front());
1635
1636 removeList.pop();
1637 }
1638
1639 removeInstsThisCycle = false;
1640 }
1641
1642 void
1643 InOrderCPU::cleanUpRemovedEvents()
1644 {
1645 while (!cpuEventRemoveList.empty()) {
1646 Event *cpu_event = cpuEventRemoveList.front();
1647 cpuEventRemoveList.pop();
1648 delete cpu_event;
1649 }
1650 }
1651
1652
1653 void
1654 InOrderCPU::dumpInsts()
1655 {
1656 int num = 0;
1657
1658 ListIt inst_list_it = instList[0].begin();
1659
1660 cprintf("Dumping Instruction List\n");
1661
1662 while (inst_list_it != instList[0].end()) {
1663 cprintf("Instruction:%i\nPC:%s\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1664 "Squashed:%i\n\n",
1665 num, (*inst_list_it)->pcState(),
1666 (*inst_list_it)->threadNumber,
1667 (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1668 (*inst_list_it)->isSquashed());
1669 inst_list_it++;
1670 ++num;
1671 }
1672 }
1673
1674 void
1675 InOrderCPU::wakeCPU()
1676 {
1677 if (/*activityRec.active() || */tickEvent.scheduled()) {
1678 DPRINTF(Activity, "CPU already running.\n");
1679 return;
1680 }
1681
1682 DPRINTF(Activity, "Waking up CPU\n");
1683
1684 Tick extra_cycles = tickToCycles((curTick() - 1) - lastRunningCycle);
1685
1686 idleCycles += extra_cycles;
1687 for (int stage_num = 0; stage_num < NumStages; stage_num++) {
1688 pipelineStage[stage_num]->idleCycles += extra_cycles;
1689 }
1690
1691 numCycles += extra_cycles;
1692
1693 schedule(&tickEvent, nextCycle(curTick()));
1694 }
1695
1696 #if FULL_SYSTEM
1697 // Lots of copied full system code...place into BaseCPU class?
1698 void
1699 InOrderCPU::wakeup()
1700 {
1701 if (thread[0]->status() != ThreadContext::Suspended)
1702 return;
1703
1704 wakeCPU();
1705
1706 DPRINTF(Quiesce, "Suspended Processor woken\n");
1707 threadContexts[0]->activate();
1708 }
1709 #endif
1710
1711 #if !FULL_SYSTEM
1712 void
1713 InOrderCPU::syscallContext(Fault fault, ThreadID tid, DynInstPtr inst, int delay)
1714 {
1715 //@todo: squash behind syscall
1716 scheduleCpuEvent(Syscall, fault, tid, inst, delay, Syscall_Pri);
1717 }
1718
1719 void
1720 InOrderCPU::syscall(int64_t callnum, ThreadID tid)
1721 {
1722 DPRINTF(InOrderCPU, "[tid:%i] Executing syscall().\n\n", tid);
1723
1724 DPRINTF(Activity,"Activity: syscall() called.\n");
1725
1726 // Temporarily increase this by one to account for the syscall
1727 // instruction.
1728 ++(this->thread[tid]->funcExeInst);
1729
1730 // Execute the actual syscall.
1731 this->thread[tid]->syscall(callnum);
1732
1733 // Decrease funcExeInst by one as the normal commit will handle
1734 // incrementing it.
1735 --(this->thread[tid]->funcExeInst);
1736
1737 // Clear Non-Speculative Block Variable
1738 nonSpecInstActive[tid] = false;
1739 }
1740 #endif
1741
1742 TheISA::TLB*
1743 InOrderCPU::getITBPtr()
1744 {
1745 CacheUnit *itb_res =
1746 dynamic_cast<CacheUnit*>(resPool->getResource(fetchPortIdx));
1747 return itb_res->tlb();
1748 }
1749
1750
1751 TheISA::TLB*
1752 InOrderCPU::getDTBPtr()
1753 {
1754 CacheUnit *dtb_res =
1755 dynamic_cast<CacheUnit*>(resPool->getResource(dataPortIdx));
1756 return dtb_res->tlb();
1757 }
1758
1759 Fault
1760 InOrderCPU::read(DynInstPtr inst, Addr addr,
1761 uint8_t *data, unsigned size, unsigned flags)
1762 {
1763 //@TODO: Generalize name "CacheUnit" to "MemUnit" just in case
1764 // you want to run w/out caches?
1765 CacheUnit *cache_res =
1766 dynamic_cast<CacheUnit*>(resPool->getResource(dataPortIdx));
1767
1768 return cache_res->read(inst, addr, data, size, flags);
1769 }
1770
1771 Fault
1772 InOrderCPU::write(DynInstPtr inst, uint8_t *data, unsigned size,
1773 Addr addr, unsigned flags, uint64_t *write_res)
1774 {
1775 //@TODO: Generalize name "CacheUnit" to "MemUnit" just in case
1776 // you want to run w/out caches?
1777 CacheUnit *cache_res =
1778 dynamic_cast<CacheUnit*>(resPool->getResource(dataPortIdx));
1779 return cache_res->write(inst, data, size, addr, flags, write_res);
1780 }