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