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