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