1/*
2 * Copyright (c) 2011-2012,2016-2017 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 "cpu/base.hh"
49
50#include <iostream>
51#include <sstream>
52#include <string>
53
54#include "arch/tlb.hh"
55#include "base/cprintf.hh"
56#include "base/loader/symtab.hh"
57#include "base/misc.hh"
58#include "base/output.hh"
59#include "base/trace.hh"
60#include "cpu/checker/cpu.hh"
61#include "cpu/cpuevent.hh"
62#include "cpu/profile.hh"
63#include "cpu/thread_context.hh"
64#include "debug/Mwait.hh"
65#include "debug/SyscallVerbose.hh"
66#include "mem/page_table.hh"
67#include "params/BaseCPU.hh"
68#include "sim/clocked_object.hh"
69#include "sim/full_system.hh"
70#include "sim/process.hh"
71#include "sim/sim_events.hh"
72#include "sim/sim_exit.hh"
73#include "sim/system.hh"
74
75// Hack
76#include "sim/stat_control.hh"
77
78using namespace std;
79
80vector<BaseCPU *> BaseCPU::cpuList;
81
82// This variable reflects the max number of threads in any CPU. Be
83// careful to only use it once all the CPUs that you care about have
84// been initialized
85int maxThreadsPerCPU = 1;
86
87CPUProgressEvent::CPUProgressEvent(BaseCPU *_cpu, Tick ival)
88 : Event(Event::Progress_Event_Pri), _interval(ival), lastNumInst(0),
89 cpu(_cpu), _repeatEvent(true)
90{
91 if (_interval)
92 cpu->schedule(this, curTick() + _interval);
93}
94
95void
96CPUProgressEvent::process()
97{
98 Counter temp = cpu->totalOps();
99
100 if (_repeatEvent)
101 cpu->schedule(this, curTick() + _interval);
102
103 if (cpu->switchedOut()) {
104 return;
105 }
106
107#ifndef NDEBUG
108 double ipc = double(temp - lastNumInst) / (_interval / cpu->clockPeriod());
109
110 DPRINTFN("%s progress event, total committed:%i, progress insts committed: "
111 "%lli, IPC: %0.8d\n", cpu->name(), temp, temp - lastNumInst,
112 ipc);
113 ipc = 0.0;
114#else
115 cprintf("%lli: %s progress event, total committed:%i, progress insts "
116 "committed: %lli\n", curTick(), cpu->name(), temp,
117 temp - lastNumInst);
118#endif
119 lastNumInst = temp;
120}
121
122const char *
123CPUProgressEvent::description() const
124{
125 return "CPU Progress";
126}
127
128BaseCPU::BaseCPU(Params *p, bool is_checker)
129 : MemObject(p), instCnt(0), _cpuId(p->cpu_id), _socketId(p->socket_id),
130 _instMasterId(p->system->getMasterId(name() + ".inst")),
131 _dataMasterId(p->system->getMasterId(name() + ".data")),
132 _taskId(ContextSwitchTaskId::Unknown), _pid(invldPid),
133 _switchedOut(p->switched_out), _cacheLineSize(p->system->cacheLineSize()),
134 interrupts(p->interrupts), profileEvent(NULL),
135 numThreads(p->numThreads), system(p->system),
136 functionTraceStream(nullptr), currentFunctionStart(0),
137 currentFunctionEnd(0), functionEntryTick(0),
138 addressMonitor(p->numThreads),
139 syscallRetryLatency(p->syscallRetryLatency),
140 pwrGatingLatency(p->pwr_gating_latency),
141 powerGatingOnIdle(p->power_gating_on_idle),
142 enterPwrGatingEvent([this]{ enterPwrGating(); }, name())
143{
144 // if Python did not provide a valid ID, do it here
145 if (_cpuId == -1 ) {
146 _cpuId = cpuList.size();
147 }
148
149 // add self to global list of CPUs
150 cpuList.push_back(this);
151
152 DPRINTF(SyscallVerbose, "Constructing CPU with id %d, socket id %d\n",
153 _cpuId, _socketId);
154
155 if (numThreads > maxThreadsPerCPU)
156 maxThreadsPerCPU = numThreads;
157
158 // allocate per-thread instruction-based event queues
159 comInstEventQueue = new EventQueue *[numThreads];
160 for (ThreadID tid = 0; tid < numThreads; ++tid)
161 comInstEventQueue[tid] =
162 new EventQueue("instruction-based event queue");
163
164 //
165 // set up instruction-count-based termination events, if any
166 //
167 if (p->max_insts_any_thread != 0) {
168 const char *cause = "a thread reached the max instruction count";
169 for (ThreadID tid = 0; tid < numThreads; ++tid)
170 scheduleInstStop(tid, p->max_insts_any_thread, cause);
171 }
172
173 // Set up instruction-count-based termination events for SimPoints
174 // Typically, there are more than one action points.
175 // Simulation.py is responsible to take the necessary actions upon
176 // exitting the simulation loop.
177 if (!p->simpoint_start_insts.empty()) {
178 const char *cause = "simpoint starting point found";
179 for (size_t i = 0; i < p->simpoint_start_insts.size(); ++i)
180 scheduleInstStop(0, p->simpoint_start_insts[i], cause);
181 }
182
183 if (p->max_insts_all_threads != 0) {
184 const char *cause = "all threads reached the max instruction count";
185
186 // allocate & initialize shared downcounter: each event will
187 // decrement this when triggered; simulation will terminate
188 // when counter reaches 0
189 int *counter = new int;
190 *counter = numThreads;
191 for (ThreadID tid = 0; tid < numThreads; ++tid) {
192 Event *event = new CountedExitEvent(cause, *counter);
193 comInstEventQueue[tid]->schedule(event, p->max_insts_all_threads);
194 }
195 }
196
197 // allocate per-thread load-based event queues
198 comLoadEventQueue = new EventQueue *[numThreads];
199 for (ThreadID tid = 0; tid < numThreads; ++tid)
200 comLoadEventQueue[tid] = new EventQueue("load-based event queue");
201
202 //
203 // set up instruction-count-based termination events, if any
204 //
205 if (p->max_loads_any_thread != 0) {
206 const char *cause = "a thread reached the max load count";
207 for (ThreadID tid = 0; tid < numThreads; ++tid)
208 scheduleLoadStop(tid, p->max_loads_any_thread, cause);
209 }
210
211 if (p->max_loads_all_threads != 0) {
212 const char *cause = "all threads reached the max load count";
213 // allocate & initialize shared downcounter: each event will
214 // decrement this when triggered; simulation will terminate
215 // when counter reaches 0
216 int *counter = new int;
217 *counter = numThreads;
218 for (ThreadID tid = 0; tid < numThreads; ++tid) {
219 Event *event = new CountedExitEvent(cause, *counter);
220 comLoadEventQueue[tid]->schedule(event, p->max_loads_all_threads);
221 }
222 }
223
224 functionTracingEnabled = false;
225 if (p->function_trace) {
226 const string fname = csprintf("ftrace.%s", name());
227 functionTraceStream = simout.findOrCreate(fname)->stream();
228
229 currentFunctionStart = currentFunctionEnd = 0;
230 functionEntryTick = p->function_trace_start;
231
232 if (p->function_trace_start == 0) {
233 functionTracingEnabled = true;
234 } else {
235 Event *event = new EventFunctionWrapper(
236 [this]{ enableFunctionTrace(); }, name(), true);
237 schedule(event, p->function_trace_start);
238 }
239 }
240
241 // The interrupts should always be present unless this CPU is
242 // switched in later or in case it is a checker CPU
243 if (!params()->switched_out && !is_checker) {
244 fatal_if(interrupts.size() != numThreads,
245 "CPU %s has %i interrupt controllers, but is expecting one "
246 "per thread (%i)\n",
247 name(), interrupts.size(), numThreads);
248 for (ThreadID tid = 0; tid < numThreads; tid++)
249 interrupts[tid]->setCPU(this);
250 }
251
252 if (FullSystem) {
253 if (params()->profile)
254 profileEvent = new EventFunctionWrapper(
255 [this]{ processProfileEvent(); },
256 name());
257 }
258 tracer = params()->tracer;
259
260 if (params()->isa.size() != numThreads) {
261 fatal("Number of ISAs (%i) assigned to the CPU does not equal number "
262 "of threads (%i).\n", params()->isa.size(), numThreads);
263 }
264}
265
266void
267BaseCPU::enableFunctionTrace()
268{
269 functionTracingEnabled = true;
270}
271
272BaseCPU::~BaseCPU()
273{
274 delete profileEvent;
275 delete[] comLoadEventQueue;
276 delete[] comInstEventQueue;
277}
278
279void
280BaseCPU::armMonitor(ThreadID tid, Addr address)
281{
282 assert(tid < numThreads);
283 AddressMonitor &monitor = addressMonitor[tid];
284
285 monitor.armed = true;
286 monitor.vAddr = address;
287 monitor.pAddr = 0x0;
288 DPRINTF(Mwait,"[tid:%d] Armed monitor (vAddr=0x%lx)\n", tid, address);
289}
290
291bool
292BaseCPU::mwait(ThreadID tid, PacketPtr pkt)
293{
294 assert(tid < numThreads);
295 AddressMonitor &monitor = addressMonitor[tid];
296
297 if (!monitor.gotWakeup) {
298 int block_size = cacheLineSize();
299 uint64_t mask = ~((uint64_t)(block_size - 1));
300
301 assert(pkt->req->hasPaddr());
302 monitor.pAddr = pkt->getAddr() & mask;
303 monitor.waiting = true;
304
305 DPRINTF(Mwait,"[tid:%d] mwait called (vAddr=0x%lx, "
306 "line's paddr=0x%lx)\n", tid, monitor.vAddr, monitor.pAddr);
307 return true;
308 } else {
309 monitor.gotWakeup = false;
310 return false;
311 }
312}
313
314void
315BaseCPU::mwaitAtomic(ThreadID tid, ThreadContext *tc, TheISA::TLB *dtb)
316{
317 assert(tid < numThreads);
318 AddressMonitor &monitor = addressMonitor[tid];
319
320 Request req;
321 Addr addr = monitor.vAddr;
322 int block_size = cacheLineSize();
323 uint64_t mask = ~((uint64_t)(block_size - 1));
324 int size = block_size;
325
326 //The address of the next line if it crosses a cache line boundary.
327 Addr secondAddr = roundDown(addr + size - 1, block_size);
328
329 if (secondAddr > addr)
330 size = secondAddr - addr;
331
332 req.setVirt(0, addr, size, 0x0, dataMasterId(), tc->instAddr());
333
334 // translate to physical address
335 Fault fault = dtb->translateAtomic(&req, tc, BaseTLB::Read);
336 assert(fault == NoFault);
337
338 monitor.pAddr = req.getPaddr() & mask;
339 monitor.waiting = true;
340
341 DPRINTF(Mwait,"[tid:%d] mwait called (vAddr=0x%lx, line's paddr=0x%lx)\n",
342 tid, monitor.vAddr, monitor.pAddr);
343}
344
345void
346BaseCPU::init()
347{
348 if (!params()->switched_out) {
349 registerThreadContexts();
350
351 verifyMemoryMode();
352 }
353}
354
355void
356BaseCPU::startup()
357{
358 if (FullSystem) {
359 if (!params()->switched_out && profileEvent)
360 schedule(profileEvent, curTick());
361 }
362
363 if (params()->progress_interval) {
364 new CPUProgressEvent(this, params()->progress_interval);
365 }
366
367 if (_switchedOut)
368 ClockedObject::pwrState(Enums::PwrState::OFF);
369
370 // Assumption CPU start to operate instantaneously without any latency
371 if (ClockedObject::pwrState() == Enums::PwrState::UNDEFINED)
372 ClockedObject::pwrState(Enums::PwrState::ON);
373
374}
375
376ProbePoints::PMUUPtr
377BaseCPU::pmuProbePoint(const char *name)
378{
379 ProbePoints::PMUUPtr ptr;
380 ptr.reset(new ProbePoints::PMU(getProbeManager(), name));
381
382 return ptr;
383}
384
385void
386BaseCPU::regProbePoints()
387{
388 ppCycles = pmuProbePoint("Cycles");
389
390 ppRetiredInsts = pmuProbePoint("RetiredInsts");
391 ppRetiredLoads = pmuProbePoint("RetiredLoads");
392 ppRetiredStores = pmuProbePoint("RetiredStores");
393 ppRetiredBranches = pmuProbePoint("RetiredBranches");
394}
395
396void
397BaseCPU::probeInstCommit(const StaticInstPtr &inst)
398{
399 if (!inst->isMicroop() || inst->isLastMicroop())
400 ppRetiredInsts->notify(1);
401
402
403 if (inst->isLoad())
404 ppRetiredLoads->notify(1);
405
406 if (inst->isStore())
407 ppRetiredStores->notify(1);
408
409 if (inst->isControl())
410 ppRetiredBranches->notify(1);
411}
412
413void
414BaseCPU::regStats()
415{
416 MemObject::regStats();
417
418 using namespace Stats;
419
420 numCycles
421 .name(name() + ".numCycles")
422 .desc("number of cpu cycles simulated")
423 ;
424
425 numWorkItemsStarted
426 .name(name() + ".numWorkItemsStarted")
427 .desc("number of work items this cpu started")
428 ;
429
430 numWorkItemsCompleted
431 .name(name() + ".numWorkItemsCompleted")
432 .desc("number of work items this cpu completed")
433 ;
434
435 int size = threadContexts.size();
436 if (size > 1) {
437 for (int i = 0; i < size; ++i) {
438 stringstream namestr;
439 ccprintf(namestr, "%s.ctx%d", name(), i);
440 threadContexts[i]->regStats(namestr.str());
441 }
442 } else if (size == 1)
443 threadContexts[0]->regStats(name());
444}
445
446BaseMasterPort &
447BaseCPU::getMasterPort(const string &if_name, PortID idx)
448{
449 // Get the right port based on name. This applies to all the
450 // subclasses of the base CPU and relies on their implementation
451 // of getDataPort and getInstPort. In all cases there methods
452 // return a MasterPort pointer.
453 if (if_name == "dcache_port")
454 return getDataPort();
455 else if (if_name == "icache_port")
456 return getInstPort();
457 else
458 return MemObject::getMasterPort(if_name, idx);
459}
460
461void
462BaseCPU::registerThreadContexts()
463{
464 assert(system->multiThread || numThreads == 1);
465
466 ThreadID size = threadContexts.size();
467 for (ThreadID tid = 0; tid < size; ++tid) {
468 ThreadContext *tc = threadContexts[tid];
469
470 if (system->multiThread) {
471 tc->setContextId(system->registerThreadContext(tc));
472 } else {
473 tc->setContextId(system->registerThreadContext(tc, _cpuId));
474 }
475
476 if (!FullSystem)
477 tc->getProcessPtr()->assignThreadContext(tc->contextId());
478 }
479}
480
481void
482BaseCPU::deschedulePowerGatingEvent()
483{
484 if (enterPwrGatingEvent.scheduled()){
485 deschedule(enterPwrGatingEvent);
486 }
487}
488
489void
490BaseCPU::schedulePowerGatingEvent()
491{
492 for (auto tc : threadContexts) {
493 if (tc->status() == ThreadContext::Active)
494 return;
495 }
496
496 if (ClockedObject::pwrState() == Enums::PwrState::CLK_GATED) {
497 if (ClockedObject::pwrState() == Enums::PwrState::CLK_GATED &&
498 powerGatingOnIdle) {
499 assert(!enterPwrGatingEvent.scheduled());
500 // Schedule a power gating event when clock gated for the specified
501 // amount of time
502 schedule(enterPwrGatingEvent, clockEdge(pwrGatingLatency));
503 }
504}
505
506int
507BaseCPU::findContext(ThreadContext *tc)
508{
509 ThreadID size = threadContexts.size();
510 for (ThreadID tid = 0; tid < size; ++tid) {
511 if (tc == threadContexts[tid])
512 return tid;
513 }
514 return 0;
515}
516
517void
518BaseCPU::activateContext(ThreadID thread_num)
519{
520 // Squash enter power gating event while cpu gets activated
521 if (enterPwrGatingEvent.scheduled())
522 deschedule(enterPwrGatingEvent);
523
524 // For any active thread running, update CPU power state to active (ON)
525 ClockedObject::pwrState(Enums::PwrState::ON);
526}
527
528void
529BaseCPU::suspendContext(ThreadID thread_num)
530{
531 // Check if all threads are suspended
532 for (auto t : threadContexts) {
533 if (t->status() != ThreadContext::Suspended) {
534 return;
535 }
536 }
537
538 // All CPU threads suspended, enter lower power state for the CPU
539 ClockedObject::pwrState(Enums::PwrState::CLK_GATED);
540
539 //Schedule power gating event when clock gated for a configurable cycles
540 schedule(enterPwrGatingEvent, clockEdge(pwrGatingLatency));
541 // If pwrGatingLatency is set to 0 then this mechanism is disabled
542 if (powerGatingOnIdle) {
543 // Schedule power gating event when clock gated for pwrGatingLatency
544 // cycles
545 schedule(enterPwrGatingEvent, clockEdge(pwrGatingLatency));
546 }
547}
548
549void
550BaseCPU::enterPwrGating(void)
551{
552 ClockedObject::pwrState(Enums::PwrState::OFF);
553}
554
555void
556BaseCPU::switchOut()
557{
558 assert(!_switchedOut);
559 _switchedOut = true;
560 if (profileEvent && profileEvent->scheduled())
561 deschedule(profileEvent);
562
563 // Flush all TLBs in the CPU to avoid having stale translations if
564 // it gets switched in later.
565 flushTLBs();
566
567 // Go to the power gating state
568 ClockedObject::pwrState(Enums::PwrState::OFF);
569}
570
571void
572BaseCPU::takeOverFrom(BaseCPU *oldCPU)
573{
574 assert(threadContexts.size() == oldCPU->threadContexts.size());
575 assert(_cpuId == oldCPU->cpuId());
576 assert(_switchedOut);
577 assert(oldCPU != this);
578 _pid = oldCPU->getPid();
579 _taskId = oldCPU->taskId();
580 // Take over the power state of the switchedOut CPU
581 ClockedObject::pwrState(oldCPU->pwrState());
582 _switchedOut = false;
583
584 ThreadID size = threadContexts.size();
585 for (ThreadID i = 0; i < size; ++i) {
586 ThreadContext *newTC = threadContexts[i];
587 ThreadContext *oldTC = oldCPU->threadContexts[i];
588
589 newTC->takeOverFrom(oldTC);
590
591 CpuEvent::replaceThreadContext(oldTC, newTC);
592
593 assert(newTC->contextId() == oldTC->contextId());
594 assert(newTC->threadId() == oldTC->threadId());
595 system->replaceThreadContext(newTC, newTC->contextId());
596
597 /* This code no longer works since the zero register (e.g.,
598 * r31 on Alpha) doesn't necessarily contain zero at this
599 * point.
600 if (DTRACE(Context))
601 ThreadContext::compare(oldTC, newTC);
602 */
603
604 BaseMasterPort *old_itb_port = oldTC->getITBPtr()->getMasterPort();
605 BaseMasterPort *old_dtb_port = oldTC->getDTBPtr()->getMasterPort();
606 BaseMasterPort *new_itb_port = newTC->getITBPtr()->getMasterPort();
607 BaseMasterPort *new_dtb_port = newTC->getDTBPtr()->getMasterPort();
608
609 // Move over any table walker ports if they exist
610 if (new_itb_port) {
611 assert(!new_itb_port->isConnected());
612 assert(old_itb_port);
613 assert(old_itb_port->isConnected());
614 BaseSlavePort &slavePort = old_itb_port->getSlavePort();
615 old_itb_port->unbind();
616 new_itb_port->bind(slavePort);
617 }
618 if (new_dtb_port) {
619 assert(!new_dtb_port->isConnected());
620 assert(old_dtb_port);
621 assert(old_dtb_port->isConnected());
622 BaseSlavePort &slavePort = old_dtb_port->getSlavePort();
623 old_dtb_port->unbind();
624 new_dtb_port->bind(slavePort);
625 }
626 newTC->getITBPtr()->takeOverFrom(oldTC->getITBPtr());
627 newTC->getDTBPtr()->takeOverFrom(oldTC->getDTBPtr());
628
629 // Checker whether or not we have to transfer CheckerCPU
630 // objects over in the switch
631 CheckerCPU *oldChecker = oldTC->getCheckerCpuPtr();
632 CheckerCPU *newChecker = newTC->getCheckerCpuPtr();
633 if (oldChecker && newChecker) {
634 BaseMasterPort *old_checker_itb_port =
635 oldChecker->getITBPtr()->getMasterPort();
636 BaseMasterPort *old_checker_dtb_port =
637 oldChecker->getDTBPtr()->getMasterPort();
638 BaseMasterPort *new_checker_itb_port =
639 newChecker->getITBPtr()->getMasterPort();
640 BaseMasterPort *new_checker_dtb_port =
641 newChecker->getDTBPtr()->getMasterPort();
642
643 newChecker->getITBPtr()->takeOverFrom(oldChecker->getITBPtr());
644 newChecker->getDTBPtr()->takeOverFrom(oldChecker->getDTBPtr());
645
646 // Move over any table walker ports if they exist for checker
647 if (new_checker_itb_port) {
648 assert(!new_checker_itb_port->isConnected());
649 assert(old_checker_itb_port);
650 assert(old_checker_itb_port->isConnected());
651 BaseSlavePort &slavePort =
652 old_checker_itb_port->getSlavePort();
653 old_checker_itb_port->unbind();
654 new_checker_itb_port->bind(slavePort);
655 }
656 if (new_checker_dtb_port) {
657 assert(!new_checker_dtb_port->isConnected());
658 assert(old_checker_dtb_port);
659 assert(old_checker_dtb_port->isConnected());
660 BaseSlavePort &slavePort =
661 old_checker_dtb_port->getSlavePort();
662 old_checker_dtb_port->unbind();
663 new_checker_dtb_port->bind(slavePort);
664 }
665 }
666 }
667
668 interrupts = oldCPU->interrupts;
669 for (ThreadID tid = 0; tid < numThreads; tid++) {
670 interrupts[tid]->setCPU(this);
671 }
672 oldCPU->interrupts.clear();
673
674 if (FullSystem) {
675 for (ThreadID i = 0; i < size; ++i)
676 threadContexts[i]->profileClear();
677
678 if (profileEvent)
679 schedule(profileEvent, curTick());
680 }
681
682 // All CPUs have an instruction and a data port, and the new CPU's
683 // ports are dangling while the old CPU has its ports connected
684 // already. Unbind the old CPU and then bind the ports of the one
685 // we are switching to.
686 assert(!getInstPort().isConnected());
687 assert(oldCPU->getInstPort().isConnected());
688 BaseSlavePort &inst_peer_port = oldCPU->getInstPort().getSlavePort();
689 oldCPU->getInstPort().unbind();
690 getInstPort().bind(inst_peer_port);
691
692 assert(!getDataPort().isConnected());
693 assert(oldCPU->getDataPort().isConnected());
694 BaseSlavePort &data_peer_port = oldCPU->getDataPort().getSlavePort();
695 oldCPU->getDataPort().unbind();
696 getDataPort().bind(data_peer_port);
697}
698
699void
700BaseCPU::flushTLBs()
701{
702 for (ThreadID i = 0; i < threadContexts.size(); ++i) {
703 ThreadContext &tc(*threadContexts[i]);
704 CheckerCPU *checker(tc.getCheckerCpuPtr());
705
706 tc.getITBPtr()->flushAll();
707 tc.getDTBPtr()->flushAll();
708 if (checker) {
709 checker->getITBPtr()->flushAll();
710 checker->getDTBPtr()->flushAll();
711 }
712 }
713}
714
715void
716BaseCPU::processProfileEvent()
717{
718 ThreadID size = threadContexts.size();
719
720 for (ThreadID i = 0; i < size; ++i)
721 threadContexts[i]->profileSample();
722
723 schedule(profileEvent, curTick() + params()->profile);
724}
725
726void
727BaseCPU::serialize(CheckpointOut &cp) const
728{
729 SERIALIZE_SCALAR(instCnt);
730
731 if (!_switchedOut) {
732 /* Unlike _pid, _taskId is not serialized, as they are dynamically
733 * assigned unique ids that are only meaningful for the duration of
734 * a specific run. We will need to serialize the entire taskMap in
735 * system. */
736 SERIALIZE_SCALAR(_pid);
737
738 // Serialize the threads, this is done by the CPU implementation.
739 for (ThreadID i = 0; i < numThreads; ++i) {
740 ScopedCheckpointSection sec(cp, csprintf("xc.%i", i));
741 interrupts[i]->serialize(cp);
742 serializeThread(cp, i);
743 }
744 }
745}
746
747void
748BaseCPU::unserialize(CheckpointIn &cp)
749{
750 UNSERIALIZE_SCALAR(instCnt);
751
752 if (!_switchedOut) {
753 UNSERIALIZE_SCALAR(_pid);
754
755 // Unserialize the threads, this is done by the CPU implementation.
756 for (ThreadID i = 0; i < numThreads; ++i) {
757 ScopedCheckpointSection sec(cp, csprintf("xc.%i", i));
758 interrupts[i]->unserialize(cp);
759 unserializeThread(cp, i);
760 }
761 }
762}
763
764void
765BaseCPU::scheduleInstStop(ThreadID tid, Counter insts, const char *cause)
766{
767 const Tick now(comInstEventQueue[tid]->getCurTick());
768 Event *event(new LocalSimLoopExitEvent(cause, 0));
769
770 comInstEventQueue[tid]->schedule(event, now + insts);
771}
772
773uint64_t
774BaseCPU::getCurrentInstCount(ThreadID tid)
775{
776 return Tick(comInstEventQueue[tid]->getCurTick());
777}
778
779AddressMonitor::AddressMonitor() {
780 armed = false;
781 waiting = false;
782 gotWakeup = false;
783}
784
785bool AddressMonitor::doMonitor(PacketPtr pkt) {
786 assert(pkt->req->hasPaddr());
787 if (armed && waiting) {
788 if (pAddr == pkt->getAddr()) {
789 DPRINTF(Mwait,"pAddr=0x%lx invalidated: waking up core\n",
790 pkt->getAddr());
791 waiting = false;
792 return true;
793 }
794 }
795 return false;
796}
797
798void
799BaseCPU::scheduleLoadStop(ThreadID tid, Counter loads, const char *cause)
800{
801 const Tick now(comLoadEventQueue[tid]->getCurTick());
802 Event *event(new LocalSimLoopExitEvent(cause, 0));
803
804 comLoadEventQueue[tid]->schedule(event, now + loads);
805}
806
807
808void
809BaseCPU::traceFunctionsInternal(Addr pc)
810{
811 if (!debugSymbolTable)
812 return;
813
814 // if pc enters different function, print new function symbol and
815 // update saved range. Otherwise do nothing.
816 if (pc < currentFunctionStart || pc >= currentFunctionEnd) {
817 string sym_str;
818 bool found = debugSymbolTable->findNearestSymbol(pc, sym_str,
819 currentFunctionStart,
820 currentFunctionEnd);
821
822 if (!found) {
823 // no symbol found: use addr as label
824 sym_str = csprintf("0x%x", pc);
825 currentFunctionStart = pc;
826 currentFunctionEnd = pc + 1;
827 }
828
829 ccprintf(*functionTraceStream, " (%d)\n%d: %s",
830 curTick() - functionEntryTick, curTick(), sym_str);
831 functionEntryTick = curTick();
832 }
833}
834
835bool
836BaseCPU::waitForRemoteGDB() const
837{
838 return params()->wait_for_remote_gdb;
839}