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