MEM: Separate snoops and normal memory requests/responses
[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 assert(pkt->isResponse());
94
95 if (pkt->isError())
96 DPRINTF(InOrderCachePort, "Got error packet back for address: %x\n",
97 pkt->getAddr());
98 else
99 cacheUnit->processCacheCompletion(pkt);
100
101 return true;
102 }
103
104 void
105 InOrderCPU::CachePort::recvRetry()
106 {
107 cacheUnit->recvRetry();
108 }
109
110 InOrderCPU::TickEvent::TickEvent(InOrderCPU *c)
111 : Event(CPU_Tick_Pri), cpu(c)
112 { }
113
114
115 void
116 InOrderCPU::TickEvent::process()
117 {
118 cpu->tick();
119 }
120
121
122 const char *
123 InOrderCPU::TickEvent::description() const
124 {
125 return "InOrderCPU tick event";
126 }
127
128 InOrderCPU::CPUEvent::CPUEvent(InOrderCPU *_cpu, CPUEventType e_type,
129 Fault fault, ThreadID _tid, DynInstPtr inst,
130 CPUEventPri event_pri)
131 : Event(event_pri), cpu(_cpu)
132 {
133 setEvent(e_type, fault, _tid, inst);
134 }
135
136
137 std::string InOrderCPU::eventNames[NumCPUEvents] =
138 {
139 "ActivateThread",
140 "ActivateNextReadyThread",
141 "DeactivateThread",
142 "HaltThread",
143 "SuspendThread",
144 "Trap",
145 "Syscall",
146 "SquashFromMemStall",
147 "UpdatePCs"
148 };
149
150 void
151 InOrderCPU::CPUEvent::process()
152 {
153 switch (cpuEventType)
154 {
155 case ActivateThread:
156 cpu->activateThread(tid);
157 cpu->resPool->activateThread(tid);
158 break;
159
160 case ActivateNextReadyThread:
161 cpu->activateNextReadyThread();
162 break;
163
164 case DeactivateThread:
165 cpu->deactivateThread(tid);
166 cpu->resPool->deactivateThread(tid);
167 break;
168
169 case HaltThread:
170 cpu->haltThread(tid);
171 cpu->resPool->deactivateThread(tid);
172 break;
173
174 case SuspendThread:
175 cpu->suspendThread(tid);
176 cpu->resPool->suspendThread(tid);
177 break;
178
179 case SquashFromMemStall:
180 cpu->squashDueToMemStall(inst->squashingStage, inst->seqNum, tid);
181 cpu->resPool->squashDueToMemStall(inst, inst->squashingStage,
182 inst->seqNum, tid);
183 break;
184
185 case Trap:
186 DPRINTF(InOrderCPU, "Trapping CPU\n");
187 cpu->trap(fault, tid, inst);
188 cpu->resPool->trap(fault, tid, inst);
189 cpu->trapPending[tid] = false;
190 break;
191
192 case Syscall:
193 cpu->syscall(inst->syscallNum, tid);
194 cpu->resPool->trap(fault, tid, inst);
195 break;
196
197 default:
198 fatal("Unrecognized Event Type %s", eventNames[cpuEventType]);
199 }
200
201 cpu->cpuEventRemoveList.push(this);
202 }
203
204
205
206 const char *
207 InOrderCPU::CPUEvent::description() const
208 {
209 return "InOrderCPU event";
210 }
211
212 void
213 InOrderCPU::CPUEvent::scheduleEvent(int delay)
214 {
215 assert(!scheduled() || squashed());
216 cpu->reschedule(this, cpu->nextCycle(curTick() + cpu->ticks(delay)), true);
217 }
218
219 void
220 InOrderCPU::CPUEvent::unscheduleEvent()
221 {
222 if (scheduled())
223 squash();
224 }
225
226 InOrderCPU::InOrderCPU(Params *params)
227 : BaseCPU(params),
228 cpu_id(params->cpu_id),
229 coreType("default"),
230 _status(Idle),
231 tickEvent(this),
232 stageWidth(params->stageWidth),
233 resPool(new ResourcePool(this, params)),
234 timeBuffer(2 , 2),
235 dataPort(resPool->getDataUnit()),
236 instPort(resPool->getInstUnit()),
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 deferRegistration(false/*params->deferRegistration*/),
246 stageTracing(params->stageTracing),
247 lastRunningCycle(0),
248 instsPerSwitch(0)
249 {
250 cpu_params = params;
251
252 // Resize for Multithreading CPUs
253 thread.resize(numThreads);
254
255 ThreadID active_threads = params->workload.size();
256 if (FullSystem) {
257 active_threads = 1;
258 } else {
259 active_threads = params->workload.size();
260
261 if (active_threads > MaxThreads) {
262 panic("Workload Size too large. Increase the 'MaxThreads'"
263 "in your InOrder implementation or "
264 "edit your workload size.");
265 }
266
267
268 if (active_threads > 1) {
269 threadModel = (InOrderCPU::ThreadModel) params->threadModel;
270
271 if (threadModel == SMT) {
272 DPRINTF(InOrderCPU, "Setting Thread Model to SMT.\n");
273 } else if (threadModel == SwitchOnCacheMiss) {
274 DPRINTF(InOrderCPU, "Setting Thread Model to "
275 "Switch On Cache Miss\n");
276 }
277
278 } else {
279 threadModel = Single;
280 }
281 }
282
283 for (ThreadID tid = 0; tid < numThreads; ++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]->prog_fname);
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->defer_registration && !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 = curTick();
406
407 lockAddr = 0;
408 lockFlag = false;
409
410 // Schedule First Tick Event, CPU will reschedule itself from here on out.
411 scheduleTickEvent(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 = curTick();
766 } else if (!activityRec.active()) {
767 DPRINTF(InOrderCPU, "sleeping CPU.\n");
768 lastRunningCycle = curTick();
769 timesIdled++;
770 } else {
771 //Tick next_tick = curTick() + cycles(1);
772 //tickEvent.schedule(next_tick);
773 schedule(&tickEvent, nextCycle(curTick() + 1));
774 DPRINTF(InOrderCPU, "Scheduled CPU for next tick @ %i.\n",
775 nextCycle(curTick() + 1));
776 }
777 }
778
779 tickThreadStats();
780 updateThreadPriority();
781 }
782
783
784 void
785 InOrderCPU::init()
786 {
787 BaseCPU::init();
788
789 for (ThreadID tid = 0; tid < numThreads; ++tid) {
790 // Set inSyscall so that the CPU doesn't squash when initially
791 // setting up registers.
792 thread[tid]->inSyscall = true;
793 // Initialise the ThreadContext's memory proxies
794 thread[tid]->initMemProxies(thread[tid]->getTC());
795 }
796
797 if (FullSystem) {
798 for (ThreadID tid = 0; tid < numThreads; tid++) {
799 ThreadContext *src_tc = threadContexts[tid];
800 TheISA::initCPU(src_tc, src_tc->contextId());
801 }
802 }
803
804 // Clear inSyscall.
805 for (ThreadID tid = 0; tid < numThreads; ++tid)
806 thread[tid]->inSyscall = false;
807
808 // Call Initializiation Routine for Resource Pool
809 resPool->init();
810 }
811
812 Fault
813 InOrderCPU::hwrei(ThreadID tid)
814 {
815 #if THE_ISA == ALPHA_ISA
816 // Need to clear the lock flag upon returning from an interrupt.
817 setMiscRegNoEffect(AlphaISA::MISCREG_LOCKFLAG, false, tid);
818
819 thread[tid]->kernelStats->hwrei();
820 // FIXME: XXX check for interrupts? XXX
821 #endif
822
823 return NoFault;
824 }
825
826
827 bool
828 InOrderCPU::simPalCheck(int palFunc, ThreadID tid)
829 {
830 #if THE_ISA == ALPHA_ISA
831 if (this->thread[tid]->kernelStats)
832 this->thread[tid]->kernelStats->callpal(palFunc,
833 this->threadContexts[tid]);
834
835 switch (palFunc) {
836 case PAL::halt:
837 halt();
838 if (--System::numSystemsRunning == 0)
839 exitSimLoop("all cpus halted");
840 break;
841
842 case PAL::bpt:
843 case PAL::bugchk:
844 if (this->system->breakpoint())
845 return false;
846 break;
847 }
848 #endif
849 return true;
850 }
851
852 void
853 InOrderCPU::checkForInterrupts()
854 {
855 for (int i = 0; i < threadContexts.size(); i++) {
856 ThreadContext *tc = threadContexts[i];
857
858 if (interrupts->checkInterrupts(tc)) {
859 Fault interrupt = interrupts->getInterrupt(tc);
860
861 if (interrupt != NoFault) {
862 DPRINTF(Interrupt, "Processing Intterupt for [tid:%i].\n",
863 tc->threadId());
864
865 ThreadID tid = tc->threadId();
866 interrupts->updateIntrInfo(tc);
867
868 // Squash from Last Stage in Pipeline
869 unsigned last_stage = NumStages - 1;
870 dummyTrapInst[tid]->squashingStage = last_stage;
871 pipelineStage[last_stage]->setupSquash(dummyTrapInst[tid],
872 tid);
873
874 // By default, setupSquash will always squash from stage + 1
875 pipelineStage[BackEndStartStage - 1]->setupSquash(dummyTrapInst[tid],
876 tid);
877
878 // Schedule Squash Through-out Resource Pool
879 resPool->scheduleEvent(
880 (InOrderCPU::CPUEventType)ResourcePool::SquashAll,
881 dummyTrapInst[tid], 0);
882
883 // Finally, Setup Trap to happen at end of cycle
884 trapContext(interrupt, tid, dummyTrapInst[tid]);
885 }
886 }
887 }
888 }
889
890 Fault
891 InOrderCPU::getInterrupts()
892 {
893 // Check if there are any outstanding interrupts
894 return interrupts->getInterrupt(threadContexts[0]);
895 }
896
897 void
898 InOrderCPU::processInterrupts(Fault interrupt)
899 {
900 // Check for interrupts here. For now can copy the code that
901 // exists within isa_fullsys_traits.hh. Also assume that thread 0
902 // is the one that handles the interrupts.
903 // @todo: Possibly consolidate the interrupt checking code.
904 // @todo: Allow other threads to handle interrupts.
905
906 assert(interrupt != NoFault);
907 interrupts->updateIntrInfo(threadContexts[0]);
908
909 DPRINTF(InOrderCPU, "Interrupt %s being handled\n", interrupt->name());
910
911 // Note: Context ID ok here? Impl. of FS mode needs to revisit this
912 trap(interrupt, threadContexts[0]->contextId(), dummyBufferInst);
913 }
914
915 void
916 InOrderCPU::trapContext(Fault fault, ThreadID tid, DynInstPtr inst, int delay)
917 {
918 scheduleCpuEvent(Trap, fault, tid, inst, delay);
919 trapPending[tid] = true;
920 }
921
922 void
923 InOrderCPU::trap(Fault fault, ThreadID tid, DynInstPtr inst)
924 {
925 fault->invoke(tcBase(tid), inst->staticInst);
926 removePipelineStalls(tid);
927 }
928
929 void
930 InOrderCPU::squashFromMemStall(DynInstPtr inst, ThreadID tid, int delay)
931 {
932 scheduleCpuEvent(SquashFromMemStall, NoFault, tid, inst, delay);
933 }
934
935
936 void
937 InOrderCPU::squashDueToMemStall(int stage_num, InstSeqNum seq_num,
938 ThreadID tid)
939 {
940 DPRINTF(InOrderCPU, "Squashing Pipeline Stages Due to Memory Stall...\n");
941
942 // Squash all instructions in each stage including
943 // instruction that caused the squash (seq_num - 1)
944 // NOTE: The stage bandwidth needs to be cleared so thats why
945 // the stalling instruction is squashed as well. The stalled
946 // instruction is previously placed in another intermediate buffer
947 // while it's stall is being handled.
948 InstSeqNum squash_seq_num = seq_num - 1;
949
950 for (int stNum=stage_num; stNum >= 0 ; stNum--) {
951 pipelineStage[stNum]->squashDueToMemStall(squash_seq_num, tid);
952 }
953 }
954
955 void
956 InOrderCPU::scheduleCpuEvent(CPUEventType c_event, Fault fault,
957 ThreadID tid, DynInstPtr inst,
958 unsigned delay, CPUEventPri event_pri)
959 {
960 CPUEvent *cpu_event = new CPUEvent(this, c_event, fault, tid, inst,
961 event_pri);
962
963 Tick sked_tick = nextCycle(curTick() + ticks(delay));
964 if (delay >= 0) {
965 DPRINTF(InOrderCPU, "Scheduling CPU Event (%s) for cycle %i, [tid:%i].\n",
966 eventNames[c_event], curTick() + delay, tid);
967 schedule(cpu_event, sked_tick);
968 } else {
969 cpu_event->process();
970 cpuEventRemoveList.push(cpu_event);
971 }
972
973 // Broadcast event to the Resource Pool
974 // Need to reset tid just in case this is a dummy instruction
975 inst->setTid(tid);
976 resPool->scheduleEvent(c_event, inst, 0, 0, tid);
977 }
978
979 bool
980 InOrderCPU::isThreadActive(ThreadID tid)
981 {
982 list<ThreadID>::iterator isActive =
983 std::find(activeThreads.begin(), activeThreads.end(), tid);
984
985 return (isActive != activeThreads.end());
986 }
987
988 bool
989 InOrderCPU::isThreadReady(ThreadID tid)
990 {
991 list<ThreadID>::iterator isReady =
992 std::find(readyThreads.begin(), readyThreads.end(), tid);
993
994 return (isReady != readyThreads.end());
995 }
996
997 bool
998 InOrderCPU::isThreadSuspended(ThreadID tid)
999 {
1000 list<ThreadID>::iterator isSuspended =
1001 std::find(suspendedThreads.begin(), suspendedThreads.end(), tid);
1002
1003 return (isSuspended != suspendedThreads.end());
1004 }
1005
1006 void
1007 InOrderCPU::activateNextReadyThread()
1008 {
1009 if (readyThreads.size() >= 1) {
1010 ThreadID ready_tid = readyThreads.front();
1011
1012 // Activate in Pipeline
1013 activateThread(ready_tid);
1014
1015 // Activate in Resource Pool
1016 resPool->activateThread(ready_tid);
1017
1018 list<ThreadID>::iterator ready_it =
1019 std::find(readyThreads.begin(), readyThreads.end(), ready_tid);
1020 readyThreads.erase(ready_it);
1021 } else {
1022 DPRINTF(InOrderCPU,
1023 "Attempting to activate new thread, but No Ready Threads to"
1024 "activate.\n");
1025 DPRINTF(InOrderCPU,
1026 "Unable to switch to next active thread.\n");
1027 }
1028 }
1029
1030 void
1031 InOrderCPU::activateThread(ThreadID tid)
1032 {
1033 if (isThreadSuspended(tid)) {
1034 DPRINTF(InOrderCPU,
1035 "Removing [tid:%i] from suspended threads list.\n", tid);
1036
1037 list<ThreadID>::iterator susp_it =
1038 std::find(suspendedThreads.begin(), suspendedThreads.end(),
1039 tid);
1040 suspendedThreads.erase(susp_it);
1041 }
1042
1043 if (threadModel == SwitchOnCacheMiss &&
1044 numActiveThreads() == 1) {
1045 DPRINTF(InOrderCPU,
1046 "Ignoring activation of [tid:%i], since [tid:%i] is "
1047 "already running.\n", tid, activeThreadId());
1048
1049 DPRINTF(InOrderCPU,"Placing [tid:%i] on ready threads list\n",
1050 tid);
1051
1052 readyThreads.push_back(tid);
1053
1054 } else if (!isThreadActive(tid)) {
1055 DPRINTF(InOrderCPU,
1056 "Adding [tid:%i] to active threads list.\n", tid);
1057 activeThreads.push_back(tid);
1058
1059 activateThreadInPipeline(tid);
1060
1061 thread[tid]->lastActivate = curTick();
1062
1063 tcBase(tid)->setStatus(ThreadContext::Active);
1064
1065 wakeCPU();
1066
1067 numCtxtSwitches++;
1068 }
1069 }
1070
1071 void
1072 InOrderCPU::activateThreadInPipeline(ThreadID tid)
1073 {
1074 for (int stNum=0; stNum < NumStages; stNum++) {
1075 pipelineStage[stNum]->activateThread(tid);
1076 }
1077 }
1078
1079 void
1080 InOrderCPU::deactivateContext(ThreadID tid, int delay)
1081 {
1082 DPRINTF(InOrderCPU,"[tid:%i]: Deactivating ...\n", tid);
1083
1084 scheduleCpuEvent(DeactivateThread, NoFault, tid, dummyInst[tid], delay);
1085
1086 // Be sure to signal that there's some activity so the CPU doesn't
1087 // deschedule itself.
1088 activityRec.activity();
1089
1090 _status = Running;
1091 }
1092
1093 void
1094 InOrderCPU::deactivateThread(ThreadID tid)
1095 {
1096 DPRINTF(InOrderCPU, "[tid:%i]: Calling deactivate thread.\n", tid);
1097
1098 if (isThreadActive(tid)) {
1099 DPRINTF(InOrderCPU,"[tid:%i]: Removing from active threads list\n",
1100 tid);
1101 list<ThreadID>::iterator thread_it =
1102 std::find(activeThreads.begin(), activeThreads.end(), tid);
1103
1104 removePipelineStalls(*thread_it);
1105
1106 activeThreads.erase(thread_it);
1107
1108 // Ideally, this should be triggered from the
1109 // suspendContext/Thread functions
1110 tcBase(tid)->setStatus(ThreadContext::Suspended);
1111 }
1112
1113 assert(!isThreadActive(tid));
1114 }
1115
1116 void
1117 InOrderCPU::removePipelineStalls(ThreadID tid)
1118 {
1119 DPRINTF(InOrderCPU,"[tid:%i]: Removing all pipeline stalls\n",
1120 tid);
1121
1122 for (int stNum = 0; stNum < NumStages ; stNum++) {
1123 pipelineStage[stNum]->removeStalls(tid);
1124 }
1125
1126 }
1127
1128 void
1129 InOrderCPU::updateThreadPriority()
1130 {
1131 if (activeThreads.size() > 1)
1132 {
1133 //DEFAULT TO ROUND ROBIN SCHEME
1134 //e.g. Move highest priority to end of thread list
1135 list<ThreadID>::iterator list_begin = activeThreads.begin();
1136
1137 unsigned high_thread = *list_begin;
1138
1139 activeThreads.erase(list_begin);
1140
1141 activeThreads.push_back(high_thread);
1142 }
1143 }
1144
1145 inline void
1146 InOrderCPU::tickThreadStats()
1147 {
1148 /** Keep track of cycles that each thread is active */
1149 list<ThreadID>::iterator thread_it = activeThreads.begin();
1150 while (thread_it != activeThreads.end()) {
1151 threadCycles[*thread_it]++;
1152 thread_it++;
1153 }
1154
1155 // Keep track of cycles where SMT is active
1156 if (activeThreads.size() > 1) {
1157 smtCycles++;
1158 }
1159 }
1160
1161 void
1162 InOrderCPU::activateContext(ThreadID tid, int delay)
1163 {
1164 DPRINTF(InOrderCPU,"[tid:%i]: Activating ...\n", tid);
1165
1166
1167 scheduleCpuEvent(ActivateThread, NoFault, tid, dummyInst[tid], delay);
1168
1169 // Be sure to signal that there's some activity so the CPU doesn't
1170 // deschedule itself.
1171 activityRec.activity();
1172
1173 _status = Running;
1174 }
1175
1176 void
1177 InOrderCPU::activateNextReadyContext(int delay)
1178 {
1179 DPRINTF(InOrderCPU,"Activating next ready thread\n");
1180
1181 scheduleCpuEvent(ActivateNextReadyThread, NoFault, 0/*tid*/, dummyInst[0],
1182 delay, ActivateNextReadyThread_Pri);
1183
1184 // Be sure to signal that there's some activity so the CPU doesn't
1185 // deschedule itself.
1186 activityRec.activity();
1187
1188 _status = Running;
1189 }
1190
1191 void
1192 InOrderCPU::haltContext(ThreadID tid)
1193 {
1194 DPRINTF(InOrderCPU, "[tid:%i]: Calling Halt Context...\n", tid);
1195
1196 scheduleCpuEvent(HaltThread, NoFault, tid, dummyInst[tid]);
1197
1198 activityRec.activity();
1199 }
1200
1201 void
1202 InOrderCPU::haltThread(ThreadID tid)
1203 {
1204 DPRINTF(InOrderCPU, "[tid:%i]: Placing on Halted Threads List...\n", tid);
1205 deactivateThread(tid);
1206 squashThreadInPipeline(tid);
1207 haltedThreads.push_back(tid);
1208
1209 tcBase(tid)->setStatus(ThreadContext::Halted);
1210
1211 if (threadModel == SwitchOnCacheMiss) {
1212 activateNextReadyContext();
1213 }
1214 }
1215
1216 void
1217 InOrderCPU::suspendContext(ThreadID tid)
1218 {
1219 scheduleCpuEvent(SuspendThread, NoFault, tid, dummyInst[tid]);
1220 }
1221
1222 void
1223 InOrderCPU::suspendThread(ThreadID tid)
1224 {
1225 DPRINTF(InOrderCPU, "[tid:%i]: Placing on Suspended Threads List...\n",
1226 tid);
1227 deactivateThread(tid);
1228 suspendedThreads.push_back(tid);
1229 thread[tid]->lastSuspend = curTick();
1230
1231 tcBase(tid)->setStatus(ThreadContext::Suspended);
1232 }
1233
1234 void
1235 InOrderCPU::squashThreadInPipeline(ThreadID tid)
1236 {
1237 //Squash all instructions in each stage
1238 for (int stNum=NumStages - 1; stNum >= 0 ; stNum--) {
1239 pipelineStage[stNum]->squash(0 /*seq_num*/, tid);
1240 }
1241 }
1242
1243 PipelineStage*
1244 InOrderCPU::getPipeStage(int stage_num)
1245 {
1246 return pipelineStage[stage_num];
1247 }
1248
1249
1250 RegIndex
1251 InOrderCPU::flattenRegIdx(RegIndex reg_idx, RegType &reg_type, ThreadID tid)
1252 {
1253 if (reg_idx < FP_Base_DepTag) {
1254 reg_type = IntType;
1255 return isa[tid].flattenIntIndex(reg_idx);
1256 } else if (reg_idx < Ctrl_Base_DepTag) {
1257 reg_type = FloatType;
1258 reg_idx -= FP_Base_DepTag;
1259 return isa[tid].flattenFloatIndex(reg_idx);
1260 } else {
1261 reg_type = MiscType;
1262 return reg_idx - TheISA::Ctrl_Base_DepTag;
1263 }
1264 }
1265
1266 uint64_t
1267 InOrderCPU::readIntReg(RegIndex reg_idx, ThreadID tid)
1268 {
1269 DPRINTF(IntRegs, "[tid:%i]: Reading Int. Reg %i as %x\n",
1270 tid, reg_idx, intRegs[tid][reg_idx]);
1271
1272 return intRegs[tid][reg_idx];
1273 }
1274
1275 FloatReg
1276 InOrderCPU::readFloatReg(RegIndex reg_idx, ThreadID tid)
1277 {
1278 DPRINTF(FloatRegs, "[tid:%i]: Reading Float Reg %i as %x, %08f\n",
1279 tid, reg_idx, floatRegs.i[tid][reg_idx], floatRegs.f[tid][reg_idx]);
1280
1281 return floatRegs.f[tid][reg_idx];
1282 }
1283
1284 FloatRegBits
1285 InOrderCPU::readFloatRegBits(RegIndex reg_idx, ThreadID tid)
1286 {
1287 DPRINTF(FloatRegs, "[tid:%i]: Reading Float Reg %i as %x, %08f\n",
1288 tid, reg_idx, floatRegs.i[tid][reg_idx], floatRegs.f[tid][reg_idx]);
1289
1290 return floatRegs.i[tid][reg_idx];
1291 }
1292
1293 void
1294 InOrderCPU::setIntReg(RegIndex reg_idx, uint64_t val, ThreadID tid)
1295 {
1296 if (reg_idx == TheISA::ZeroReg) {
1297 DPRINTF(IntRegs, "[tid:%i]: Ignoring Setting of ISA-ZeroReg "
1298 "(Int. Reg %i) to %x\n", tid, reg_idx, val);
1299 return;
1300 } else {
1301 DPRINTF(IntRegs, "[tid:%i]: Setting Int. Reg %i to %x\n",
1302 tid, reg_idx, val);
1303
1304 intRegs[tid][reg_idx] = val;
1305 }
1306 }
1307
1308
1309 void
1310 InOrderCPU::setFloatReg(RegIndex reg_idx, FloatReg val, ThreadID tid)
1311 {
1312 floatRegs.f[tid][reg_idx] = val;
1313 DPRINTF(FloatRegs, "[tid:%i]: Setting Float. Reg %i bits to "
1314 "%x, %08f\n",
1315 tid, reg_idx,
1316 floatRegs.i[tid][reg_idx],
1317 floatRegs.f[tid][reg_idx]);
1318 }
1319
1320
1321 void
1322 InOrderCPU::setFloatRegBits(RegIndex reg_idx, FloatRegBits val, ThreadID tid)
1323 {
1324 floatRegs.i[tid][reg_idx] = val;
1325 DPRINTF(FloatRegs, "[tid:%i]: Setting Float. Reg %i bits to "
1326 "%x, %08f\n",
1327 tid, reg_idx,
1328 floatRegs.i[tid][reg_idx],
1329 floatRegs.f[tid][reg_idx]);
1330 }
1331
1332 uint64_t
1333 InOrderCPU::readRegOtherThread(unsigned reg_idx, ThreadID tid)
1334 {
1335 // If Default value is set, then retrieve target thread
1336 if (tid == InvalidThreadID) {
1337 tid = TheISA::getTargetThread(tcBase(tid));
1338 }
1339
1340 if (reg_idx < FP_Base_DepTag) {
1341 // Integer Register File
1342 return readIntReg(reg_idx, tid);
1343 } else if (reg_idx < Ctrl_Base_DepTag) {
1344 // Float Register File
1345 reg_idx -= FP_Base_DepTag;
1346 return readFloatRegBits(reg_idx, tid);
1347 } else {
1348 reg_idx -= Ctrl_Base_DepTag;
1349 return readMiscReg(reg_idx, tid); // Misc. Register File
1350 }
1351 }
1352 void
1353 InOrderCPU::setRegOtherThread(unsigned reg_idx, const MiscReg &val,
1354 ThreadID tid)
1355 {
1356 // If Default value is set, then retrieve target thread
1357 if (tid == InvalidThreadID) {
1358 tid = TheISA::getTargetThread(tcBase(tid));
1359 }
1360
1361 if (reg_idx < FP_Base_DepTag) { // Integer Register File
1362 setIntReg(reg_idx, val, tid);
1363 } else if (reg_idx < Ctrl_Base_DepTag) { // Float Register File
1364 reg_idx -= FP_Base_DepTag;
1365 setFloatRegBits(reg_idx, val, tid);
1366 } else {
1367 reg_idx -= Ctrl_Base_DepTag;
1368 setMiscReg(reg_idx, val, tid); // Misc. Register File
1369 }
1370 }
1371
1372 MiscReg
1373 InOrderCPU::readMiscRegNoEffect(int misc_reg, ThreadID tid)
1374 {
1375 return isa[tid].readMiscRegNoEffect(misc_reg);
1376 }
1377
1378 MiscReg
1379 InOrderCPU::readMiscReg(int misc_reg, ThreadID tid)
1380 {
1381 return isa[tid].readMiscReg(misc_reg, tcBase(tid));
1382 }
1383
1384 void
1385 InOrderCPU::setMiscRegNoEffect(int misc_reg, const MiscReg &val, ThreadID tid)
1386 {
1387 isa[tid].setMiscRegNoEffect(misc_reg, val);
1388 }
1389
1390 void
1391 InOrderCPU::setMiscReg(int misc_reg, const MiscReg &val, ThreadID tid)
1392 {
1393 isa[tid].setMiscReg(misc_reg, val, tcBase(tid));
1394 }
1395
1396
1397 InOrderCPU::ListIt
1398 InOrderCPU::addInst(DynInstPtr inst)
1399 {
1400 ThreadID tid = inst->readTid();
1401
1402 instList[tid].push_back(inst);
1403
1404 return --(instList[tid].end());
1405 }
1406
1407 InOrderCPU::ListIt
1408 InOrderCPU::findInst(InstSeqNum seq_num, ThreadID tid)
1409 {
1410 ListIt it = instList[tid].begin();
1411 ListIt end = instList[tid].end();
1412
1413 while (it != end) {
1414 if ((*it)->seqNum == seq_num)
1415 return it;
1416 else if ((*it)->seqNum > seq_num)
1417 break;
1418
1419 it++;
1420 }
1421
1422 return instList[tid].end();
1423 }
1424
1425 void
1426 InOrderCPU::updateContextSwitchStats()
1427 {
1428 // Set Average Stat Here, then reset to 0
1429 instsPerCtxtSwitch = instsPerSwitch;
1430 instsPerSwitch = 0;
1431 }
1432
1433
1434 void
1435 InOrderCPU::instDone(DynInstPtr inst, ThreadID tid)
1436 {
1437 // Set the nextPC to be fetched if this is the last instruction
1438 // committed
1439 // ========
1440 // This contributes to the precise state of the CPU
1441 // which can be used when restoring a thread to the CPU after after any
1442 // type of context switching activity (fork, exception, etc.)
1443 TheISA::PCState comm_pc = inst->pcState();
1444 lastCommittedPC[tid] = comm_pc;
1445 TheISA::advancePC(comm_pc, inst->staticInst);
1446 pcState(comm_pc, tid);
1447
1448 //@todo: may be unnecessary with new-ISA-specific branch handling code
1449 if (inst->isControl()) {
1450 thread[tid]->lastGradIsBranch = true;
1451 thread[tid]->lastBranchPC = inst->pcState();
1452 TheISA::advancePC(thread[tid]->lastBranchPC, inst->staticInst);
1453 } else {
1454 thread[tid]->lastGradIsBranch = false;
1455 }
1456
1457
1458 // Finalize Trace Data For Instruction
1459 if (inst->traceData) {
1460 //inst->traceData->setCycle(curTick());
1461 inst->traceData->setFetchSeq(inst->seqNum);
1462 //inst->traceData->setCPSeq(cpu->tcBase(tid)->numInst);
1463 inst->traceData->dump();
1464 delete inst->traceData;
1465 inst->traceData = NULL;
1466 }
1467
1468 // Increment active thread's instruction count
1469 instsPerSwitch++;
1470
1471 // Increment thread-state's instruction count
1472 thread[tid]->numInst++;
1473 thread[tid]->numOp++;
1474
1475 // Increment thread-state's instruction stats
1476 thread[tid]->numInsts++;
1477 thread[tid]->numOps++;
1478
1479 // Count committed insts per thread stats
1480 if (!inst->isMicroop() || inst->isLastMicroop()) {
1481 committedInsts[tid]++;
1482
1483 // Count total insts committed stat
1484 totalCommittedInsts++;
1485 }
1486
1487 committedOps[tid]++;
1488
1489 // Count SMT-committed insts per thread stat
1490 if (numActiveThreads() > 1) {
1491 if (!inst->isMicroop() || inst->isLastMicroop())
1492 smtCommittedInsts[tid]++;
1493 }
1494
1495 // Instruction-Mix Stats
1496 if (inst->isLoad()) {
1497 comLoads++;
1498 } else if (inst->isStore()) {
1499 comStores++;
1500 } else if (inst->isControl()) {
1501 comBranches++;
1502 } else if (inst->isNop()) {
1503 comNops++;
1504 } else if (inst->isNonSpeculative()) {
1505 comNonSpec++;
1506 } else if (inst->isInteger()) {
1507 comInts++;
1508 } else if (inst->isFloating()) {
1509 comFloats++;
1510 }
1511
1512 // Check for instruction-count-based events.
1513 comInstEventQueue[tid]->serviceEvents(thread[tid]->numOp);
1514
1515 // Finally, remove instruction from CPU
1516 removeInst(inst);
1517 }
1518
1519 // currently unused function, but substitute repetitive code w/this function
1520 // call
1521 void
1522 InOrderCPU::addToRemoveList(DynInstPtr inst)
1523 {
1524 removeInstsThisCycle = true;
1525 if (!inst->isRemoveList()) {
1526 DPRINTF(InOrderCPU, "Pushing instruction [tid:%i] PC %s "
1527 "[sn:%lli] to remove list\n",
1528 inst->threadNumber, inst->pcState(), inst->seqNum);
1529 inst->setRemoveList();
1530 removeList.push(inst->getInstListIt());
1531 } else {
1532 DPRINTF(InOrderCPU, "Ignoring instruction removal for [tid:%i] PC %s "
1533 "[sn:%lli], already remove list\n",
1534 inst->threadNumber, inst->pcState(), inst->seqNum);
1535 }
1536
1537 }
1538
1539 void
1540 InOrderCPU::removeInst(DynInstPtr inst)
1541 {
1542 DPRINTF(InOrderCPU, "Removing graduated instruction [tid:%i] PC %s "
1543 "[sn:%lli]\n",
1544 inst->threadNumber, inst->pcState(), inst->seqNum);
1545
1546 removeInstsThisCycle = true;
1547
1548 // Remove the instruction.
1549 if (!inst->isRemoveList()) {
1550 DPRINTF(InOrderCPU, "Pushing instruction [tid:%i] PC %s "
1551 "[sn:%lli] to remove list\n",
1552 inst->threadNumber, inst->pcState(), inst->seqNum);
1553 inst->setRemoveList();
1554 removeList.push(inst->getInstListIt());
1555 } else {
1556 DPRINTF(InOrderCPU, "Ignoring instruction removal for [tid:%i] PC %s "
1557 "[sn:%lli], already on remove list\n",
1558 inst->threadNumber, inst->pcState(), inst->seqNum);
1559 }
1560
1561 }
1562
1563 void
1564 InOrderCPU::removeInstsUntil(const InstSeqNum &seq_num, ThreadID tid)
1565 {
1566 //assert(!instList[tid].empty());
1567
1568 removeInstsThisCycle = true;
1569
1570 ListIt inst_iter = instList[tid].end();
1571
1572 inst_iter--;
1573
1574 DPRINTF(InOrderCPU, "Squashing instructions from CPU instruction "
1575 "list that are from [tid:%i] and above [sn:%lli] (end=%lli).\n",
1576 tid, seq_num, (*inst_iter)->seqNum);
1577
1578 while ((*inst_iter)->seqNum > seq_num) {
1579
1580 bool break_loop = (inst_iter == instList[tid].begin());
1581
1582 squashInstIt(inst_iter, tid);
1583
1584 inst_iter--;
1585
1586 if (break_loop)
1587 break;
1588 }
1589 }
1590
1591
1592 inline void
1593 InOrderCPU::squashInstIt(const ListIt inst_it, ThreadID tid)
1594 {
1595 DynInstPtr inst = (*inst_it);
1596 if (inst->threadNumber == tid) {
1597 DPRINTF(InOrderCPU, "Squashing instruction, "
1598 "[tid:%i] [sn:%lli] PC %s\n",
1599 inst->threadNumber,
1600 inst->seqNum,
1601 inst->pcState());
1602
1603 inst->setSquashed();
1604 archRegDepMap[tid].remove(inst);
1605
1606 if (!inst->isRemoveList()) {
1607 DPRINTF(InOrderCPU, "Pushing instruction [tid:%i] PC %s "
1608 "[sn:%lli] to remove list\n",
1609 inst->threadNumber, inst->pcState(),
1610 inst->seqNum);
1611 inst->setRemoveList();
1612 removeList.push(inst_it);
1613 } else {
1614 DPRINTF(InOrderCPU, "Ignoring instruction removal for [tid:%i]"
1615 " PC %s [sn:%lli], already on remove list\n",
1616 inst->threadNumber, inst->pcState(),
1617 inst->seqNum);
1618 }
1619
1620 }
1621
1622 }
1623
1624
1625 void
1626 InOrderCPU::cleanUpRemovedInsts()
1627 {
1628 while (!removeList.empty()) {
1629 DPRINTF(InOrderCPU, "Removing instruction, "
1630 "[tid:%i] [sn:%lli] PC %s\n",
1631 (*removeList.front())->threadNumber,
1632 (*removeList.front())->seqNum,
1633 (*removeList.front())->pcState());
1634
1635 DynInstPtr inst = *removeList.front();
1636 ThreadID tid = inst->threadNumber;
1637
1638 // Remove From Register Dependency Map, If Necessary
1639 // archRegDepMap[tid].remove(inst);
1640
1641 // Clear if Non-Speculative
1642 if (inst->staticInst &&
1643 inst->seqNum == nonSpecSeqNum[tid] &&
1644 nonSpecInstActive[tid] == true) {
1645 nonSpecInstActive[tid] = false;
1646 }
1647
1648 inst->onInstList = false;
1649
1650 instList[tid].erase(removeList.front());
1651
1652 removeList.pop();
1653 }
1654
1655 removeInstsThisCycle = false;
1656 }
1657
1658 void
1659 InOrderCPU::cleanUpRemovedEvents()
1660 {
1661 while (!cpuEventRemoveList.empty()) {
1662 Event *cpu_event = cpuEventRemoveList.front();
1663 cpuEventRemoveList.pop();
1664 delete cpu_event;
1665 }
1666 }
1667
1668
1669 void
1670 InOrderCPU::dumpInsts()
1671 {
1672 int num = 0;
1673
1674 ListIt inst_list_it = instList[0].begin();
1675
1676 cprintf("Dumping Instruction List\n");
1677
1678 while (inst_list_it != instList[0].end()) {
1679 cprintf("Instruction:%i\nPC:%s\n[tid:%i]\n[sn:%lli]\nIssued:%i\n"
1680 "Squashed:%i\n\n",
1681 num, (*inst_list_it)->pcState(),
1682 (*inst_list_it)->threadNumber,
1683 (*inst_list_it)->seqNum, (*inst_list_it)->isIssued(),
1684 (*inst_list_it)->isSquashed());
1685 inst_list_it++;
1686 ++num;
1687 }
1688 }
1689
1690 void
1691 InOrderCPU::wakeCPU()
1692 {
1693 if (/*activityRec.active() || */tickEvent.scheduled()) {
1694 DPRINTF(Activity, "CPU already running.\n");
1695 return;
1696 }
1697
1698 DPRINTF(Activity, "Waking up CPU\n");
1699
1700 Tick extra_cycles = tickToCycles((curTick() - 1) - lastRunningCycle);
1701
1702 idleCycles += extra_cycles;
1703 for (int stage_num = 0; stage_num < NumStages; stage_num++) {
1704 pipelineStage[stage_num]->idleCycles += extra_cycles;
1705 }
1706
1707 numCycles += extra_cycles;
1708
1709 schedule(&tickEvent, nextCycle(curTick()));
1710 }
1711
1712 // Lots of copied full system code...place into BaseCPU class?
1713 void
1714 InOrderCPU::wakeup()
1715 {
1716 if (thread[0]->status() != ThreadContext::Suspended)
1717 return;
1718
1719 wakeCPU();
1720
1721 DPRINTF(Quiesce, "Suspended Processor woken\n");
1722 threadContexts[0]->activate();
1723 }
1724
1725 void
1726 InOrderCPU::syscallContext(Fault fault, ThreadID tid, DynInstPtr inst, int delay)
1727 {
1728 // Syscall must be non-speculative, so squash from last stage
1729 unsigned squash_stage = NumStages - 1;
1730 inst->setSquashInfo(squash_stage);
1731
1732 // Squash In Pipeline Stage
1733 pipelineStage[squash_stage]->setupSquash(inst, tid);
1734
1735 // Schedule Squash Through-out Resource Pool
1736 resPool->scheduleEvent(
1737 (InOrderCPU::CPUEventType)ResourcePool::SquashAll, inst, 0);
1738 scheduleCpuEvent(Syscall, fault, tid, inst, delay, Syscall_Pri);
1739 }
1740
1741 void
1742 InOrderCPU::syscall(int64_t callnum, ThreadID tid)
1743 {
1744 DPRINTF(InOrderCPU, "[tid:%i] Executing syscall().\n\n", tid);
1745
1746 DPRINTF(Activity,"Activity: syscall() called.\n");
1747
1748 // Temporarily increase this by one to account for the syscall
1749 // instruction.
1750 ++(this->thread[tid]->funcExeInst);
1751
1752 // Execute the actual syscall.
1753 this->thread[tid]->syscall(callnum);
1754
1755 // Decrease funcExeInst by one as the normal commit will handle
1756 // incrementing it.
1757 --(this->thread[tid]->funcExeInst);
1758
1759 // Clear Non-Speculative Block Variable
1760 nonSpecInstActive[tid] = false;
1761 }
1762
1763 TheISA::TLB*
1764 InOrderCPU::getITBPtr()
1765 {
1766 CacheUnit *itb_res = resPool->getInstUnit();
1767 return itb_res->tlb();
1768 }
1769
1770
1771 TheISA::TLB*
1772 InOrderCPU::getDTBPtr()
1773 {
1774 return resPool->getDataUnit()->tlb();
1775 }
1776
1777 Decoder *
1778 InOrderCPU::getDecoderPtr()
1779 {
1780 return &resPool->getInstUnit()->decoder;
1781 }
1782
1783 Fault
1784 InOrderCPU::read(DynInstPtr inst, Addr addr,
1785 uint8_t *data, unsigned size, unsigned flags)
1786 {
1787 return resPool->getDataUnit()->read(inst, addr, data, size, flags);
1788 }
1789
1790 Fault
1791 InOrderCPU::write(DynInstPtr inst, uint8_t *data, unsigned size,
1792 Addr addr, unsigned flags, uint64_t *write_res)
1793 {
1794 return resPool->getDataUnit()->write(inst, data, size, addr, flags,
1795 write_res);
1796 }