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