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