mem: Use shared_ptr for Ruby Message classes
[gem5.git] / src / cpu / base.cc
1 /*
2 * Copyright (c) 2011-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) 2002-2005 The Regents of The University of Michigan
15 * Copyright (c) 2011 Regents of the University of California
16 * Copyright (c) 2013 Advanced Micro Devices, Inc.
17 * Copyright (c) 2013 Mark D. Hill and David A. Wood
18 * All rights reserved.
19 *
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions are
22 * met: redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer;
24 * redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution;
27 * neither the name of the copyright holders nor the names of its
28 * contributors may be used to endorse or promote products derived from
29 * this software without specific prior written permission.
30 *
31 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 *
43 * Authors: Steve Reinhardt
44 * Nathan Binkert
45 * Rick Strong
46 */
47
48 #include <iostream>
49 #include <sstream>
50 #include <string>
51
52 #include "arch/tlb.hh"
53 #include "base/loader/symtab.hh"
54 #include "base/cprintf.hh"
55 #include "base/misc.hh"
56 #include "base/output.hh"
57 #include "base/trace.hh"
58 #include "cpu/base.hh"
59 #include "cpu/checker/cpu.hh"
60 #include "cpu/cpuevent.hh"
61 #include "cpu/profile.hh"
62 #include "cpu/thread_context.hh"
63 #include "debug/SyscallVerbose.hh"
64 #include "params/BaseCPU.hh"
65 #include "sim/full_system.hh"
66 #include "sim/process.hh"
67 #include "sim/sim_events.hh"
68 #include "sim/sim_exit.hh"
69 #include "sim/system.hh"
70
71 // Hack
72 #include "sim/stat_control.hh"
73
74 using namespace std;
75
76 vector<BaseCPU *> BaseCPU::cpuList;
77
78 // This variable reflects the max number of threads in any CPU. Be
79 // careful to only use it once all the CPUs that you care about have
80 // been initialized
81 int maxThreadsPerCPU = 1;
82
83 CPUProgressEvent::CPUProgressEvent(BaseCPU *_cpu, Tick ival)
84 : Event(Event::Progress_Event_Pri), _interval(ival), lastNumInst(0),
85 cpu(_cpu), _repeatEvent(true)
86 {
87 if (_interval)
88 cpu->schedule(this, curTick() + _interval);
89 }
90
91 void
92 CPUProgressEvent::process()
93 {
94 Counter temp = cpu->totalOps();
95 #ifndef NDEBUG
96 double ipc = double(temp - lastNumInst) / (_interval / cpu->clockPeriod());
97
98 DPRINTFN("%s progress event, total committed:%i, progress insts committed: "
99 "%lli, IPC: %0.8d\n", cpu->name(), temp, temp - lastNumInst,
100 ipc);
101 ipc = 0.0;
102 #else
103 cprintf("%lli: %s progress event, total committed:%i, progress insts "
104 "committed: %lli\n", curTick(), cpu->name(), temp,
105 temp - lastNumInst);
106 #endif
107 lastNumInst = temp;
108
109 if (_repeatEvent)
110 cpu->schedule(this, curTick() + _interval);
111 }
112
113 const char *
114 CPUProgressEvent::description() const
115 {
116 return "CPU Progress";
117 }
118
119 BaseCPU::BaseCPU(Params *p, bool is_checker)
120 : MemObject(p), instCnt(0), _cpuId(p->cpu_id), _socketId(p->socket_id),
121 _instMasterId(p->system->getMasterId(name() + ".inst")),
122 _dataMasterId(p->system->getMasterId(name() + ".data")),
123 _taskId(ContextSwitchTaskId::Unknown), _pid(Request::invldPid),
124 _switchedOut(p->switched_out), _cacheLineSize(p->system->cacheLineSize()),
125 interrupts(p->interrupts), profileEvent(NULL),
126 numThreads(p->numThreads), system(p->system)
127 {
128 // if Python did not provide a valid ID, do it here
129 if (_cpuId == -1 ) {
130 _cpuId = cpuList.size();
131 }
132
133 // add self to global list of CPUs
134 cpuList.push_back(this);
135
136 DPRINTF(SyscallVerbose, "Constructing CPU with id %d, socket id %d\n",
137 _cpuId, _socketId);
138
139 if (numThreads > maxThreadsPerCPU)
140 maxThreadsPerCPU = numThreads;
141
142 // allocate per-thread instruction-based event queues
143 comInstEventQueue = new EventQueue *[numThreads];
144 for (ThreadID tid = 0; tid < numThreads; ++tid)
145 comInstEventQueue[tid] =
146 new EventQueue("instruction-based event queue");
147
148 //
149 // set up instruction-count-based termination events, if any
150 //
151 if (p->max_insts_any_thread != 0) {
152 const char *cause = "a thread reached the max instruction count";
153 for (ThreadID tid = 0; tid < numThreads; ++tid)
154 scheduleInstStop(tid, p->max_insts_any_thread, cause);
155 }
156
157 // Set up instruction-count-based termination events for SimPoints
158 // Typically, there are more than one action points.
159 // Simulation.py is responsible to take the necessary actions upon
160 // exitting the simulation loop.
161 if (!p->simpoint_start_insts.empty()) {
162 const char *cause = "simpoint starting point found";
163 for (size_t i = 0; i < p->simpoint_start_insts.size(); ++i)
164 scheduleInstStop(0, p->simpoint_start_insts[i], cause);
165 }
166
167 if (p->max_insts_all_threads != 0) {
168 const char *cause = "all threads reached the max instruction count";
169
170 // allocate & initialize shared downcounter: each event will
171 // decrement this when triggered; simulation will terminate
172 // when counter reaches 0
173 int *counter = new int;
174 *counter = numThreads;
175 for (ThreadID tid = 0; tid < numThreads; ++tid) {
176 Event *event = new CountedExitEvent(cause, *counter);
177 comInstEventQueue[tid]->schedule(event, p->max_insts_all_threads);
178 }
179 }
180
181 // allocate per-thread load-based event queues
182 comLoadEventQueue = new EventQueue *[numThreads];
183 for (ThreadID tid = 0; tid < numThreads; ++tid)
184 comLoadEventQueue[tid] = new EventQueue("load-based event queue");
185
186 //
187 // set up instruction-count-based termination events, if any
188 //
189 if (p->max_loads_any_thread != 0) {
190 const char *cause = "a thread reached the max load count";
191 for (ThreadID tid = 0; tid < numThreads; ++tid)
192 scheduleLoadStop(tid, p->max_loads_any_thread, cause);
193 }
194
195 if (p->max_loads_all_threads != 0) {
196 const char *cause = "all threads reached the max load count";
197 // allocate & initialize shared downcounter: each event will
198 // decrement this when triggered; simulation will terminate
199 // when counter reaches 0
200 int *counter = new int;
201 *counter = numThreads;
202 for (ThreadID tid = 0; tid < numThreads; ++tid) {
203 Event *event = new CountedExitEvent(cause, *counter);
204 comLoadEventQueue[tid]->schedule(event, p->max_loads_all_threads);
205 }
206 }
207
208 functionTracingEnabled = false;
209 if (p->function_trace) {
210 const string fname = csprintf("ftrace.%s", name());
211 functionTraceStream = simout.find(fname);
212 if (!functionTraceStream)
213 functionTraceStream = simout.create(fname);
214
215 currentFunctionStart = currentFunctionEnd = 0;
216 functionEntryTick = p->function_trace_start;
217
218 if (p->function_trace_start == 0) {
219 functionTracingEnabled = true;
220 } else {
221 typedef EventWrapper<BaseCPU, &BaseCPU::enableFunctionTrace> wrap;
222 Event *event = new wrap(this, true);
223 schedule(event, p->function_trace_start);
224 }
225 }
226
227 // The interrupts should always be present unless this CPU is
228 // switched in later or in case it is a checker CPU
229 if (!params()->switched_out && !is_checker) {
230 if (interrupts) {
231 interrupts->setCPU(this);
232 } else {
233 fatal("CPU %s has no interrupt controller.\n"
234 "Ensure createInterruptController() is called.\n", name());
235 }
236 }
237
238 if (FullSystem) {
239 if (params()->profile)
240 profileEvent = new ProfileEvent(this, params()->profile);
241 }
242 tracer = params()->tracer;
243
244 if (params()->isa.size() != numThreads) {
245 fatal("Number of ISAs (%i) assigned to the CPU does not equal number "
246 "of threads (%i).\n", params()->isa.size(), numThreads);
247 }
248 }
249
250 void
251 BaseCPU::enableFunctionTrace()
252 {
253 functionTracingEnabled = true;
254 }
255
256 BaseCPU::~BaseCPU()
257 {
258 delete profileEvent;
259 delete[] comLoadEventQueue;
260 delete[] comInstEventQueue;
261 }
262
263 void
264 BaseCPU::init()
265 {
266 if (!params()->switched_out) {
267 registerThreadContexts();
268
269 verifyMemoryMode();
270 }
271 }
272
273 void
274 BaseCPU::startup()
275 {
276 if (FullSystem) {
277 if (!params()->switched_out && profileEvent)
278 schedule(profileEvent, curTick());
279 }
280
281 if (params()->progress_interval) {
282 new CPUProgressEvent(this, params()->progress_interval);
283 }
284 }
285
286 ProbePoints::PMUUPtr
287 BaseCPU::pmuProbePoint(const char *name)
288 {
289 ProbePoints::PMUUPtr ptr;
290 ptr.reset(new ProbePoints::PMU(getProbeManager(), name));
291
292 return ptr;
293 }
294
295 void
296 BaseCPU::regProbePoints()
297 {
298 ppCycles = pmuProbePoint("Cycles");
299
300 ppRetiredInsts = pmuProbePoint("RetiredInsts");
301 ppRetiredLoads = pmuProbePoint("RetiredLoads");
302 ppRetiredStores = pmuProbePoint("RetiredStores");
303 ppRetiredBranches = pmuProbePoint("RetiredBranches");
304 }
305
306 void
307 BaseCPU::probeInstCommit(const StaticInstPtr &inst)
308 {
309 if (!inst->isMicroop() || inst->isLastMicroop())
310 ppRetiredInsts->notify(1);
311
312
313 if (inst->isLoad())
314 ppRetiredLoads->notify(1);
315
316 if (inst->isStore())
317 ppRetiredLoads->notify(1);
318
319 if (inst->isControl())
320 ppRetiredBranches->notify(1);
321 }
322
323 void
324 BaseCPU::regStats()
325 {
326 using namespace Stats;
327
328 numCycles
329 .name(name() + ".numCycles")
330 .desc("number of cpu cycles simulated")
331 ;
332
333 numWorkItemsStarted
334 .name(name() + ".numWorkItemsStarted")
335 .desc("number of work items this cpu started")
336 ;
337
338 numWorkItemsCompleted
339 .name(name() + ".numWorkItemsCompleted")
340 .desc("number of work items this cpu completed")
341 ;
342
343 int size = threadContexts.size();
344 if (size > 1) {
345 for (int i = 0; i < size; ++i) {
346 stringstream namestr;
347 ccprintf(namestr, "%s.ctx%d", name(), i);
348 threadContexts[i]->regStats(namestr.str());
349 }
350 } else if (size == 1)
351 threadContexts[0]->regStats(name());
352 }
353
354 BaseMasterPort &
355 BaseCPU::getMasterPort(const string &if_name, PortID idx)
356 {
357 // Get the right port based on name. This applies to all the
358 // subclasses of the base CPU and relies on their implementation
359 // of getDataPort and getInstPort. In all cases there methods
360 // return a MasterPort pointer.
361 if (if_name == "dcache_port")
362 return getDataPort();
363 else if (if_name == "icache_port")
364 return getInstPort();
365 else
366 return MemObject::getMasterPort(if_name, idx);
367 }
368
369 void
370 BaseCPU::registerThreadContexts()
371 {
372 ThreadID size = threadContexts.size();
373 for (ThreadID tid = 0; tid < size; ++tid) {
374 ThreadContext *tc = threadContexts[tid];
375
376 /** This is so that contextId and cpuId match where there is a
377 * 1cpu:1context relationship. Otherwise, the order of registration
378 * could affect the assignment and cpu 1 could have context id 3, for
379 * example. We may even want to do something like this for SMT so that
380 * cpu 0 has the lowest thread contexts and cpu N has the highest, but
381 * I'll just do this for now
382 */
383 if (numThreads == 1)
384 tc->setContextId(system->registerThreadContext(tc, _cpuId));
385 else
386 tc->setContextId(system->registerThreadContext(tc));
387
388 if (!FullSystem)
389 tc->getProcessPtr()->assignThreadContext(tc->contextId());
390 }
391 }
392
393
394 int
395 BaseCPU::findContext(ThreadContext *tc)
396 {
397 ThreadID size = threadContexts.size();
398 for (ThreadID tid = 0; tid < size; ++tid) {
399 if (tc == threadContexts[tid])
400 return tid;
401 }
402 return 0;
403 }
404
405 void
406 BaseCPU::switchOut()
407 {
408 assert(!_switchedOut);
409 _switchedOut = true;
410 if (profileEvent && profileEvent->scheduled())
411 deschedule(profileEvent);
412
413 // Flush all TLBs in the CPU to avoid having stale translations if
414 // it gets switched in later.
415 flushTLBs();
416 }
417
418 void
419 BaseCPU::takeOverFrom(BaseCPU *oldCPU)
420 {
421 assert(threadContexts.size() == oldCPU->threadContexts.size());
422 assert(_cpuId == oldCPU->cpuId());
423 assert(_switchedOut);
424 assert(oldCPU != this);
425 _pid = oldCPU->getPid();
426 _taskId = oldCPU->taskId();
427 _switchedOut = false;
428
429 ThreadID size = threadContexts.size();
430 for (ThreadID i = 0; i < size; ++i) {
431 ThreadContext *newTC = threadContexts[i];
432 ThreadContext *oldTC = oldCPU->threadContexts[i];
433
434 newTC->takeOverFrom(oldTC);
435
436 CpuEvent::replaceThreadContext(oldTC, newTC);
437
438 assert(newTC->contextId() == oldTC->contextId());
439 assert(newTC->threadId() == oldTC->threadId());
440 system->replaceThreadContext(newTC, newTC->contextId());
441
442 /* This code no longer works since the zero register (e.g.,
443 * r31 on Alpha) doesn't necessarily contain zero at this
444 * point.
445 if (DTRACE(Context))
446 ThreadContext::compare(oldTC, newTC);
447 */
448
449 BaseMasterPort *old_itb_port = oldTC->getITBPtr()->getMasterPort();
450 BaseMasterPort *old_dtb_port = oldTC->getDTBPtr()->getMasterPort();
451 BaseMasterPort *new_itb_port = newTC->getITBPtr()->getMasterPort();
452 BaseMasterPort *new_dtb_port = newTC->getDTBPtr()->getMasterPort();
453
454 // Move over any table walker ports if they exist
455 if (new_itb_port) {
456 assert(!new_itb_port->isConnected());
457 assert(old_itb_port);
458 assert(old_itb_port->isConnected());
459 BaseSlavePort &slavePort = old_itb_port->getSlavePort();
460 old_itb_port->unbind();
461 new_itb_port->bind(slavePort);
462 }
463 if (new_dtb_port) {
464 assert(!new_dtb_port->isConnected());
465 assert(old_dtb_port);
466 assert(old_dtb_port->isConnected());
467 BaseSlavePort &slavePort = old_dtb_port->getSlavePort();
468 old_dtb_port->unbind();
469 new_dtb_port->bind(slavePort);
470 }
471 newTC->getITBPtr()->takeOverFrom(oldTC->getITBPtr());
472 newTC->getDTBPtr()->takeOverFrom(oldTC->getDTBPtr());
473
474 // Checker whether or not we have to transfer CheckerCPU
475 // objects over in the switch
476 CheckerCPU *oldChecker = oldTC->getCheckerCpuPtr();
477 CheckerCPU *newChecker = newTC->getCheckerCpuPtr();
478 if (oldChecker && newChecker) {
479 BaseMasterPort *old_checker_itb_port =
480 oldChecker->getITBPtr()->getMasterPort();
481 BaseMasterPort *old_checker_dtb_port =
482 oldChecker->getDTBPtr()->getMasterPort();
483 BaseMasterPort *new_checker_itb_port =
484 newChecker->getITBPtr()->getMasterPort();
485 BaseMasterPort *new_checker_dtb_port =
486 newChecker->getDTBPtr()->getMasterPort();
487
488 newChecker->getITBPtr()->takeOverFrom(oldChecker->getITBPtr());
489 newChecker->getDTBPtr()->takeOverFrom(oldChecker->getDTBPtr());
490
491 // Move over any table walker ports if they exist for checker
492 if (new_checker_itb_port) {
493 assert(!new_checker_itb_port->isConnected());
494 assert(old_checker_itb_port);
495 assert(old_checker_itb_port->isConnected());
496 BaseSlavePort &slavePort =
497 old_checker_itb_port->getSlavePort();
498 old_checker_itb_port->unbind();
499 new_checker_itb_port->bind(slavePort);
500 }
501 if (new_checker_dtb_port) {
502 assert(!new_checker_dtb_port->isConnected());
503 assert(old_checker_dtb_port);
504 assert(old_checker_dtb_port->isConnected());
505 BaseSlavePort &slavePort =
506 old_checker_dtb_port->getSlavePort();
507 old_checker_dtb_port->unbind();
508 new_checker_dtb_port->bind(slavePort);
509 }
510 }
511 }
512
513 interrupts = oldCPU->interrupts;
514 interrupts->setCPU(this);
515 oldCPU->interrupts = NULL;
516
517 if (FullSystem) {
518 for (ThreadID i = 0; i < size; ++i)
519 threadContexts[i]->profileClear();
520
521 if (profileEvent)
522 schedule(profileEvent, curTick());
523 }
524
525 // All CPUs have an instruction and a data port, and the new CPU's
526 // ports are dangling while the old CPU has its ports connected
527 // already. Unbind the old CPU and then bind the ports of the one
528 // we are switching to.
529 assert(!getInstPort().isConnected());
530 assert(oldCPU->getInstPort().isConnected());
531 BaseSlavePort &inst_peer_port = oldCPU->getInstPort().getSlavePort();
532 oldCPU->getInstPort().unbind();
533 getInstPort().bind(inst_peer_port);
534
535 assert(!getDataPort().isConnected());
536 assert(oldCPU->getDataPort().isConnected());
537 BaseSlavePort &data_peer_port = oldCPU->getDataPort().getSlavePort();
538 oldCPU->getDataPort().unbind();
539 getDataPort().bind(data_peer_port);
540 }
541
542 void
543 BaseCPU::flushTLBs()
544 {
545 for (ThreadID i = 0; i < threadContexts.size(); ++i) {
546 ThreadContext &tc(*threadContexts[i]);
547 CheckerCPU *checker(tc.getCheckerCpuPtr());
548
549 tc.getITBPtr()->flushAll();
550 tc.getDTBPtr()->flushAll();
551 if (checker) {
552 checker->getITBPtr()->flushAll();
553 checker->getDTBPtr()->flushAll();
554 }
555 }
556 }
557
558
559 BaseCPU::ProfileEvent::ProfileEvent(BaseCPU *_cpu, Tick _interval)
560 : cpu(_cpu), interval(_interval)
561 { }
562
563 void
564 BaseCPU::ProfileEvent::process()
565 {
566 ThreadID size = cpu->threadContexts.size();
567 for (ThreadID i = 0; i < size; ++i) {
568 ThreadContext *tc = cpu->threadContexts[i];
569 tc->profileSample();
570 }
571
572 cpu->schedule(this, curTick() + interval);
573 }
574
575 void
576 BaseCPU::serialize(std::ostream &os)
577 {
578 SERIALIZE_SCALAR(instCnt);
579
580 if (!_switchedOut) {
581 /* Unlike _pid, _taskId is not serialized, as they are dynamically
582 * assigned unique ids that are only meaningful for the duration of
583 * a specific run. We will need to serialize the entire taskMap in
584 * system. */
585 SERIALIZE_SCALAR(_pid);
586
587 interrupts->serialize(os);
588
589 // Serialize the threads, this is done by the CPU implementation.
590 for (ThreadID i = 0; i < numThreads; ++i) {
591 nameOut(os, csprintf("%s.xc.%i", name(), i));
592 serializeThread(os, i);
593 }
594 }
595 }
596
597 void
598 BaseCPU::unserialize(Checkpoint *cp, const std::string &section)
599 {
600 UNSERIALIZE_SCALAR(instCnt);
601
602 if (!_switchedOut) {
603 UNSERIALIZE_SCALAR(_pid);
604 interrupts->unserialize(cp, section);
605
606 // Unserialize the threads, this is done by the CPU implementation.
607 for (ThreadID i = 0; i < numThreads; ++i)
608 unserializeThread(cp, csprintf("%s.xc.%i", section, i), i);
609 }
610 }
611
612 void
613 BaseCPU::scheduleInstStop(ThreadID tid, Counter insts, const char *cause)
614 {
615 const Tick now(comInstEventQueue[tid]->getCurTick());
616 Event *event(new LocalSimLoopExitEvent(cause, 0));
617
618 comInstEventQueue[tid]->schedule(event, now + insts);
619 }
620
621 void
622 BaseCPU::scheduleLoadStop(ThreadID tid, Counter loads, const char *cause)
623 {
624 const Tick now(comLoadEventQueue[tid]->getCurTick());
625 Event *event(new LocalSimLoopExitEvent(cause, 0));
626
627 comLoadEventQueue[tid]->schedule(event, now + loads);
628 }
629
630
631 void
632 BaseCPU::traceFunctionsInternal(Addr pc)
633 {
634 if (!debugSymbolTable)
635 return;
636
637 // if pc enters different function, print new function symbol and
638 // update saved range. Otherwise do nothing.
639 if (pc < currentFunctionStart || pc >= currentFunctionEnd) {
640 string sym_str;
641 bool found = debugSymbolTable->findNearestSymbol(pc, sym_str,
642 currentFunctionStart,
643 currentFunctionEnd);
644
645 if (!found) {
646 // no symbol found: use addr as label
647 sym_str = csprintf("0x%x", pc);
648 currentFunctionStart = pc;
649 currentFunctionEnd = pc + 1;
650 }
651
652 ccprintf(*functionTraceStream, " (%d)\n%d: %s",
653 curTick() - functionEntryTick, curTick(), sym_str);
654 functionEntryTick = curTick();
655 }
656 }