base.cc revision 13784
18745Sgblack@eecs.umich.edu/*
28745Sgblack@eecs.umich.edu * Copyright (c) 2011-2012,2016-2017 ARM Limited
38745Sgblack@eecs.umich.edu * All rights reserved
48745Sgblack@eecs.umich.edu *
58745Sgblack@eecs.umich.edu * The license below extends only to copyright in the software and shall
68745Sgblack@eecs.umich.edu * not be construed as granting a license to any other intellectual
78745Sgblack@eecs.umich.edu * property including but not limited to intellectual property relating
88745Sgblack@eecs.umich.edu * to a hardware implementation of the functionality of the software
98745Sgblack@eecs.umich.edu * licensed hereunder.  You may use the software subject to the license
108745Sgblack@eecs.umich.edu * terms below provided that you ensure that this notice is replicated
118745Sgblack@eecs.umich.edu * unmodified and in its entirety in all distributions of the software,
128745Sgblack@eecs.umich.edu * modified or unmodified, in source code or in binary form.
138745Sgblack@eecs.umich.edu *
148745Sgblack@eecs.umich.edu * Copyright (c) 2002-2005 The Regents of The University of Michigan
158745Sgblack@eecs.umich.edu * Copyright (c) 2011 Regents of the University of California
168745Sgblack@eecs.umich.edu * Copyright (c) 2013 Advanced Micro Devices, Inc.
178745Sgblack@eecs.umich.edu * Copyright (c) 2013 Mark D. Hill and David A. Wood
188745Sgblack@eecs.umich.edu * All rights reserved.
198745Sgblack@eecs.umich.edu *
208745Sgblack@eecs.umich.edu * Redistribution and use in source and binary forms, with or without
218745Sgblack@eecs.umich.edu * modification, are permitted provided that the following conditions are
228745Sgblack@eecs.umich.edu * met: redistributions of source code must retain the above copyright
238745Sgblack@eecs.umich.edu * notice, this list of conditions and the following disclaimer;
248745Sgblack@eecs.umich.edu * redistributions in binary form must reproduce the above copyright
258745Sgblack@eecs.umich.edu * notice, this list of conditions and the following disclaimer in the
268745Sgblack@eecs.umich.edu * documentation and/or other materials provided with the distribution;
278745Sgblack@eecs.umich.edu * neither the name of the copyright holders nor the names of its
288745Sgblack@eecs.umich.edu * contributors may be used to endorse or promote products derived from
298745Sgblack@eecs.umich.edu * this software without specific prior written permission.
308745Sgblack@eecs.umich.edu *
318745Sgblack@eecs.umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
328745Sgblack@eecs.umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
338745Sgblack@eecs.umich.edu * 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/generic/tlb.hh"
55#include "base/cprintf.hh"
56#include "base/loader/symtab.hh"
57#include "base/logging.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(this, "inst")),
131      _dataMasterId(p->system->getMasterId(this, "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      previousCycle(0), previousState(CPU_STATE_SLEEP),
137      functionTraceStream(nullptr), currentFunctionStart(0),
138      currentFunctionEnd(0), functionEntryTick(0),
139      addressMonitor(p->numThreads),
140      syscallRetryLatency(p->syscallRetryLatency),
141      pwrGatingLatency(p->pwr_gating_latency),
142      powerGatingOnIdle(p->power_gating_on_idle),
143      enterPwrGatingEvent([this]{ enterPwrGating(); }, name())
144{
145    // if Python did not provide a valid ID, do it here
146    if (_cpuId == -1 ) {
147        _cpuId = cpuList.size();
148    }
149
150    // add self to global list of CPUs
151    cpuList.push_back(this);
152
153    DPRINTF(SyscallVerbose, "Constructing CPU with id %d, socket id %d\n",
154                _cpuId, _socketId);
155
156    if (numThreads > maxThreadsPerCPU)
157        maxThreadsPerCPU = numThreads;
158
159    // allocate per-thread instruction-based event queues
160    comInstEventQueue = new EventQueue *[numThreads];
161    for (ThreadID tid = 0; tid < numThreads; ++tid)
162        comInstEventQueue[tid] =
163            new EventQueue("instruction-based event queue");
164
165    //
166    // set up instruction-count-based termination events, if any
167    //
168    if (p->max_insts_any_thread != 0) {
169        const char *cause = "a thread reached the max instruction count";
170        for (ThreadID tid = 0; tid < numThreads; ++tid)
171            scheduleInstStop(tid, p->max_insts_any_thread, cause);
172    }
173
174    // Set up instruction-count-based termination events for SimPoints
175    // Typically, there are more than one action points.
176    // Simulation.py is responsible to take the necessary actions upon
177    // exitting the simulation loop.
178    if (!p->simpoint_start_insts.empty()) {
179        const char *cause = "simpoint starting point found";
180        for (size_t i = 0; i < p->simpoint_start_insts.size(); ++i)
181            scheduleInstStop(0, p->simpoint_start_insts[i], cause);
182    }
183
184    if (p->max_insts_all_threads != 0) {
185        const char *cause = "all threads reached the max instruction count";
186
187        // allocate & initialize shared downcounter: each event will
188        // decrement this when triggered; simulation will terminate
189        // when counter reaches 0
190        int *counter = new int;
191        *counter = numThreads;
192        for (ThreadID tid = 0; tid < numThreads; ++tid) {
193            Event *event = new CountedExitEvent(cause, *counter);
194            comInstEventQueue[tid]->schedule(event, p->max_insts_all_threads);
195        }
196    }
197
198    // allocate per-thread load-based event queues
199    comLoadEventQueue = new EventQueue *[numThreads];
200    for (ThreadID tid = 0; tid < numThreads; ++tid)
201        comLoadEventQueue[tid] = new EventQueue("load-based event queue");
202
203    //
204    // set up instruction-count-based termination events, if any
205    //
206    if (p->max_loads_any_thread != 0) {
207        const char *cause = "a thread reached the max load count";
208        for (ThreadID tid = 0; tid < numThreads; ++tid)
209            scheduleLoadStop(tid, p->max_loads_any_thread, cause);
210    }
211
212    if (p->max_loads_all_threads != 0) {
213        const char *cause = "all threads reached the max load count";
214        // allocate & initialize shared downcounter: each event will
215        // decrement this when triggered; simulation will terminate
216        // when counter reaches 0
217        int *counter = new int;
218        *counter = numThreads;
219        for (ThreadID tid = 0; tid < numThreads; ++tid) {
220            Event *event = new CountedExitEvent(cause, *counter);
221            comLoadEventQueue[tid]->schedule(event, p->max_loads_all_threads);
222        }
223    }
224
225    functionTracingEnabled = false;
226    if (p->function_trace) {
227        const string fname = csprintf("ftrace.%s", name());
228        functionTraceStream = simout.findOrCreate(fname)->stream();
229
230        currentFunctionStart = currentFunctionEnd = 0;
231        functionEntryTick = p->function_trace_start;
232
233        if (p->function_trace_start == 0) {
234            functionTracingEnabled = true;
235        } else {
236            Event *event = new EventFunctionWrapper(
237                [this]{ enableFunctionTrace(); }, name(), true);
238            schedule(event, p->function_trace_start);
239        }
240    }
241
242    // The interrupts should always be present unless this CPU is
243    // switched in later or in case it is a checker CPU
244    if (!params()->switched_out && !is_checker) {
245        fatal_if(interrupts.size() != numThreads,
246                 "CPU %s has %i interrupt controllers, but is expecting one "
247                 "per thread (%i)\n",
248                 name(), interrupts.size(), numThreads);
249        for (ThreadID tid = 0; tid < numThreads; tid++)
250            interrupts[tid]->setCPU(this);
251    }
252
253    if (FullSystem) {
254        if (params()->profile)
255            profileEvent = new EventFunctionWrapper(
256                [this]{ processProfileEvent(); },
257                name());
258    }
259    tracer = params()->tracer;
260
261    if (params()->isa.size() != numThreads) {
262        fatal("Number of ISAs (%i) assigned to the CPU does not equal number "
263              "of threads (%i).\n", params()->isa.size(), numThreads);
264    }
265}
266
267void
268BaseCPU::enableFunctionTrace()
269{
270    functionTracingEnabled = true;
271}
272
273BaseCPU::~BaseCPU()
274{
275    delete profileEvent;
276    delete[] comLoadEventQueue;
277    delete[] comInstEventQueue;
278}
279
280void
281BaseCPU::armMonitor(ThreadID tid, Addr address)
282{
283    assert(tid < numThreads);
284    AddressMonitor &monitor = addressMonitor[tid];
285
286    monitor.armed = true;
287    monitor.vAddr = address;
288    monitor.pAddr = 0x0;
289    DPRINTF(Mwait,"[tid:%d] Armed monitor (vAddr=0x%lx)\n", tid, address);
290}
291
292bool
293BaseCPU::mwait(ThreadID tid, PacketPtr pkt)
294{
295    assert(tid < numThreads);
296    AddressMonitor &monitor = addressMonitor[tid];
297
298    if (!monitor.gotWakeup) {
299        int block_size = cacheLineSize();
300        uint64_t mask = ~((uint64_t)(block_size - 1));
301
302        assert(pkt->req->hasPaddr());
303        monitor.pAddr = pkt->getAddr() & mask;
304        monitor.waiting = true;
305
306        DPRINTF(Mwait,"[tid:%d] mwait called (vAddr=0x%lx, "
307                "line's paddr=0x%lx)\n", tid, monitor.vAddr, monitor.pAddr);
308        return true;
309    } else {
310        monitor.gotWakeup = false;
311        return false;
312    }
313}
314
315void
316BaseCPU::mwaitAtomic(ThreadID tid, ThreadContext *tc, BaseTLB *dtb)
317{
318    assert(tid < numThreads);
319    AddressMonitor &monitor = addressMonitor[tid];
320
321    RequestPtr req = std::make_shared<Request>();
322
323    Addr addr = monitor.vAddr;
324    int block_size = cacheLineSize();
325    uint64_t mask = ~((uint64_t)(block_size - 1));
326    int size = block_size;
327
328    //The address of the next line if it crosses a cache line boundary.
329    Addr secondAddr = roundDown(addr + size - 1, block_size);
330
331    if (secondAddr > addr)
332        size = secondAddr - addr;
333
334    req->setVirt(0, addr, size, 0x0, dataMasterId(), tc->instAddr());
335
336    // translate to physical address
337    Fault fault = dtb->translateAtomic(req, tc, BaseTLB::Read);
338    assert(fault == NoFault);
339
340    monitor.pAddr = req->getPaddr() & mask;
341    monitor.waiting = true;
342
343    DPRINTF(Mwait,"[tid:%d] mwait called (vAddr=0x%lx, line's paddr=0x%lx)\n",
344            tid, monitor.vAddr, monitor.pAddr);
345}
346
347void
348BaseCPU::init()
349{
350    if (!params()->switched_out) {
351        registerThreadContexts();
352
353        verifyMemoryMode();
354    }
355}
356
357void
358BaseCPU::startup()
359{
360    if (FullSystem) {
361        if (!params()->switched_out && profileEvent)
362            schedule(profileEvent, curTick());
363    }
364
365    if (params()->progress_interval) {
366        new CPUProgressEvent(this, params()->progress_interval);
367    }
368
369    if (_switchedOut)
370        ClockedObject::pwrState(Enums::PwrState::OFF);
371
372    // Assumption CPU start to operate instantaneously without any latency
373    if (ClockedObject::pwrState() == Enums::PwrState::UNDEFINED)
374        ClockedObject::pwrState(Enums::PwrState::ON);
375
376}
377
378ProbePoints::PMUUPtr
379BaseCPU::pmuProbePoint(const char *name)
380{
381    ProbePoints::PMUUPtr ptr;
382    ptr.reset(new ProbePoints::PMU(getProbeManager(), name));
383
384    return ptr;
385}
386
387void
388BaseCPU::regProbePoints()
389{
390    ppAllCycles = pmuProbePoint("Cycles");
391    ppActiveCycles = pmuProbePoint("ActiveCycles");
392
393    ppRetiredInsts = pmuProbePoint("RetiredInsts");
394    ppRetiredLoads = pmuProbePoint("RetiredLoads");
395    ppRetiredStores = pmuProbePoint("RetiredStores");
396    ppRetiredBranches = pmuProbePoint("RetiredBranches");
397
398    ppSleeping = new ProbePointArg<bool>(this->getProbeManager(),
399                                         "Sleeping");
400}
401
402void
403BaseCPU::probeInstCommit(const StaticInstPtr &inst)
404{
405    if (!inst->isMicroop() || inst->isLastMicroop())
406        ppRetiredInsts->notify(1);
407
408
409    if (inst->isLoad())
410        ppRetiredLoads->notify(1);
411
412    if (inst->isStore() || inst->isAtomic())
413        ppRetiredStores->notify(1);
414
415    if (inst->isControl())
416        ppRetiredBranches->notify(1);
417}
418
419void
420BaseCPU::regStats()
421{
422    MemObject::regStats();
423
424    using namespace Stats;
425
426    numCycles
427        .name(name() + ".numCycles")
428        .desc("number of cpu cycles simulated")
429        ;
430
431    numWorkItemsStarted
432        .name(name() + ".numWorkItemsStarted")
433        .desc("number of work items this cpu started")
434        ;
435
436    numWorkItemsCompleted
437        .name(name() + ".numWorkItemsCompleted")
438        .desc("number of work items this cpu completed")
439        ;
440
441    int size = threadContexts.size();
442    if (size > 1) {
443        for (int i = 0; i < size; ++i) {
444            stringstream namestr;
445            ccprintf(namestr, "%s.ctx%d", name(), i);
446            threadContexts[i]->regStats(namestr.str());
447        }
448    } else if (size == 1)
449        threadContexts[0]->regStats(name());
450}
451
452Port &
453BaseCPU::getPort(const string &if_name, PortID idx)
454{
455    // Get the right port based on name. This applies to all the
456    // subclasses of the base CPU and relies on their implementation
457    // of getDataPort and getInstPort.
458    if (if_name == "dcache_port")
459        return getDataPort();
460    else if (if_name == "icache_port")
461        return getInstPort();
462    else
463        return MemObject::getPort(if_name, idx);
464}
465
466void
467BaseCPU::registerThreadContexts()
468{
469    assert(system->multiThread || numThreads == 1);
470
471    ThreadID size = threadContexts.size();
472    for (ThreadID tid = 0; tid < size; ++tid) {
473        ThreadContext *tc = threadContexts[tid];
474
475        if (system->multiThread) {
476            tc->setContextId(system->registerThreadContext(tc));
477        } else {
478            tc->setContextId(system->registerThreadContext(tc, _cpuId));
479        }
480
481        if (!FullSystem)
482            tc->getProcessPtr()->assignThreadContext(tc->contextId());
483    }
484}
485
486void
487BaseCPU::deschedulePowerGatingEvent()
488{
489    if (enterPwrGatingEvent.scheduled()){
490        deschedule(enterPwrGatingEvent);
491    }
492}
493
494void
495BaseCPU::schedulePowerGatingEvent()
496{
497    for (auto tc : threadContexts) {
498        if (tc->status() == ThreadContext::Active)
499            return;
500    }
501
502    if (ClockedObject::pwrState() == Enums::PwrState::CLK_GATED &&
503        powerGatingOnIdle) {
504        assert(!enterPwrGatingEvent.scheduled());
505        // Schedule a power gating event when clock gated for the specified
506        // amount of time
507        schedule(enterPwrGatingEvent, clockEdge(pwrGatingLatency));
508    }
509}
510
511int
512BaseCPU::findContext(ThreadContext *tc)
513{
514    ThreadID size = threadContexts.size();
515    for (ThreadID tid = 0; tid < size; ++tid) {
516        if (tc == threadContexts[tid])
517            return tid;
518    }
519    return 0;
520}
521
522void
523BaseCPU::activateContext(ThreadID thread_num)
524{
525    // Squash enter power gating event while cpu gets activated
526    if (enterPwrGatingEvent.scheduled())
527        deschedule(enterPwrGatingEvent);
528    // For any active thread running, update CPU power state to active (ON)
529    ClockedObject::pwrState(Enums::PwrState::ON);
530
531    updateCycleCounters(CPU_STATE_WAKEUP);
532}
533
534void
535BaseCPU::suspendContext(ThreadID thread_num)
536{
537    // Check if all threads are suspended
538    for (auto t : threadContexts) {
539        if (t->status() != ThreadContext::Suspended) {
540            return;
541        }
542    }
543
544    // All CPU thread are suspended, update cycle count
545    updateCycleCounters(CPU_STATE_SLEEP);
546
547    // All CPU threads suspended, enter lower power state for the CPU
548    ClockedObject::pwrState(Enums::PwrState::CLK_GATED);
549
550    // If pwrGatingLatency is set to 0 then this mechanism is disabled
551    if (powerGatingOnIdle) {
552        // Schedule power gating event when clock gated for pwrGatingLatency
553        // cycles
554        schedule(enterPwrGatingEvent, clockEdge(pwrGatingLatency));
555    }
556}
557
558void
559BaseCPU::haltContext(ThreadID thread_num)
560{
561    updateCycleCounters(BaseCPU::CPU_STATE_SLEEP);
562}
563
564void
565BaseCPU::enterPwrGating(void)
566{
567    ClockedObject::pwrState(Enums::PwrState::OFF);
568}
569
570void
571BaseCPU::switchOut()
572{
573    assert(!_switchedOut);
574    _switchedOut = true;
575    if (profileEvent && profileEvent->scheduled())
576        deschedule(profileEvent);
577
578    // Flush all TLBs in the CPU to avoid having stale translations if
579    // it gets switched in later.
580    flushTLBs();
581
582    // Go to the power gating state
583    ClockedObject::pwrState(Enums::PwrState::OFF);
584}
585
586void
587BaseCPU::takeOverFrom(BaseCPU *oldCPU)
588{
589    assert(threadContexts.size() == oldCPU->threadContexts.size());
590    assert(_cpuId == oldCPU->cpuId());
591    assert(_switchedOut);
592    assert(oldCPU != this);
593    _pid = oldCPU->getPid();
594    _taskId = oldCPU->taskId();
595    // Take over the power state of the switchedOut CPU
596    ClockedObject::pwrState(oldCPU->pwrState());
597
598    previousState = oldCPU->previousState;
599    previousCycle = oldCPU->previousCycle;
600
601    _switchedOut = false;
602
603    ThreadID size = threadContexts.size();
604    for (ThreadID i = 0; i < size; ++i) {
605        ThreadContext *newTC = threadContexts[i];
606        ThreadContext *oldTC = oldCPU->threadContexts[i];
607
608        newTC->takeOverFrom(oldTC);
609
610        CpuEvent::replaceThreadContext(oldTC, newTC);
611
612        assert(newTC->contextId() == oldTC->contextId());
613        assert(newTC->threadId() == oldTC->threadId());
614        system->replaceThreadContext(newTC, newTC->contextId());
615
616        /* This code no longer works since the zero register (e.g.,
617         * r31 on Alpha) doesn't necessarily contain zero at this
618         * point.
619           if (DTRACE(Context))
620            ThreadContext::compare(oldTC, newTC);
621        */
622
623        Port *old_itb_port = oldTC->getITBPtr()->getTableWalkerPort();
624        Port *old_dtb_port = oldTC->getDTBPtr()->getTableWalkerPort();
625        Port *new_itb_port = newTC->getITBPtr()->getTableWalkerPort();
626        Port *new_dtb_port = newTC->getDTBPtr()->getTableWalkerPort();
627
628        // Move over any table walker ports if they exist
629        if (new_itb_port) {
630            assert(!new_itb_port->isConnected());
631            assert(old_itb_port);
632            assert(old_itb_port->isConnected());
633            auto &slavePort =
634                dynamic_cast<BaseMasterPort *>(old_itb_port)->getSlavePort();
635            old_itb_port->unbind();
636            new_itb_port->bind(slavePort);
637        }
638        if (new_dtb_port) {
639            assert(!new_dtb_port->isConnected());
640            assert(old_dtb_port);
641            assert(old_dtb_port->isConnected());
642            auto &slavePort =
643                dynamic_cast<BaseMasterPort *>(old_dtb_port)->getSlavePort();
644            old_dtb_port->unbind();
645            new_dtb_port->bind(slavePort);
646        }
647        newTC->getITBPtr()->takeOverFrom(oldTC->getITBPtr());
648        newTC->getDTBPtr()->takeOverFrom(oldTC->getDTBPtr());
649
650        // Checker whether or not we have to transfer CheckerCPU
651        // objects over in the switch
652        CheckerCPU *oldChecker = oldTC->getCheckerCpuPtr();
653        CheckerCPU *newChecker = newTC->getCheckerCpuPtr();
654        if (oldChecker && newChecker) {
655            Port *old_checker_itb_port =
656                oldChecker->getITBPtr()->getTableWalkerPort();
657            Port *old_checker_dtb_port =
658                oldChecker->getDTBPtr()->getTableWalkerPort();
659            Port *new_checker_itb_port =
660                newChecker->getITBPtr()->getTableWalkerPort();
661            Port *new_checker_dtb_port =
662                newChecker->getDTBPtr()->getTableWalkerPort();
663
664            newChecker->getITBPtr()->takeOverFrom(oldChecker->getITBPtr());
665            newChecker->getDTBPtr()->takeOverFrom(oldChecker->getDTBPtr());
666
667            // Move over any table walker ports if they exist for checker
668            if (new_checker_itb_port) {
669                assert(!new_checker_itb_port->isConnected());
670                assert(old_checker_itb_port);
671                assert(old_checker_itb_port->isConnected());
672                auto &slavePort =
673                    dynamic_cast<BaseMasterPort *>(old_checker_itb_port)->
674                    getSlavePort();
675                old_checker_itb_port->unbind();
676                new_checker_itb_port->bind(slavePort);
677            }
678            if (new_checker_dtb_port) {
679                assert(!new_checker_dtb_port->isConnected());
680                assert(old_checker_dtb_port);
681                assert(old_checker_dtb_port->isConnected());
682                auto &slavePort =
683                    dynamic_cast<BaseMasterPort *>(old_checker_dtb_port)->
684                    getSlavePort();
685                old_checker_dtb_port->unbind();
686                new_checker_dtb_port->bind(slavePort);
687            }
688        }
689    }
690
691    interrupts = oldCPU->interrupts;
692    for (ThreadID tid = 0; tid < numThreads; tid++) {
693        interrupts[tid]->setCPU(this);
694    }
695    oldCPU->interrupts.clear();
696
697    if (FullSystem) {
698        for (ThreadID i = 0; i < size; ++i)
699            threadContexts[i]->profileClear();
700
701        if (profileEvent)
702            schedule(profileEvent, curTick());
703    }
704
705    // All CPUs have an instruction and a data port, and the new CPU's
706    // ports are dangling while the old CPU has its ports connected
707    // already. Unbind the old CPU and then bind the ports of the one
708    // we are switching to.
709    assert(!getInstPort().isConnected());
710    assert(oldCPU->getInstPort().isConnected());
711    auto &inst_peer_port =
712        dynamic_cast<BaseMasterPort &>(oldCPU->getInstPort()).getSlavePort();
713    oldCPU->getInstPort().unbind();
714    getInstPort().bind(inst_peer_port);
715
716    assert(!getDataPort().isConnected());
717    assert(oldCPU->getDataPort().isConnected());
718    auto &data_peer_port =
719        dynamic_cast<BaseMasterPort &>(oldCPU->getDataPort()).getSlavePort();
720    oldCPU->getDataPort().unbind();
721    getDataPort().bind(data_peer_port);
722}
723
724void
725BaseCPU::flushTLBs()
726{
727    for (ThreadID i = 0; i < threadContexts.size(); ++i) {
728        ThreadContext &tc(*threadContexts[i]);
729        CheckerCPU *checker(tc.getCheckerCpuPtr());
730
731        tc.getITBPtr()->flushAll();
732        tc.getDTBPtr()->flushAll();
733        if (checker) {
734            checker->getITBPtr()->flushAll();
735            checker->getDTBPtr()->flushAll();
736        }
737    }
738}
739
740void
741BaseCPU::processProfileEvent()
742{
743    ThreadID size = threadContexts.size();
744
745    for (ThreadID i = 0; i < size; ++i)
746        threadContexts[i]->profileSample();
747
748    schedule(profileEvent, curTick() + params()->profile);
749}
750
751void
752BaseCPU::serialize(CheckpointOut &cp) const
753{
754    SERIALIZE_SCALAR(instCnt);
755
756    if (!_switchedOut) {
757        /* Unlike _pid, _taskId is not serialized, as they are dynamically
758         * assigned unique ids that are only meaningful for the duration of
759         * a specific run. We will need to serialize the entire taskMap in
760         * system. */
761        SERIALIZE_SCALAR(_pid);
762
763        // Serialize the threads, this is done by the CPU implementation.
764        for (ThreadID i = 0; i < numThreads; ++i) {
765            ScopedCheckpointSection sec(cp, csprintf("xc.%i", i));
766            interrupts[i]->serialize(cp);
767            serializeThread(cp, i);
768        }
769    }
770}
771
772void
773BaseCPU::unserialize(CheckpointIn &cp)
774{
775    UNSERIALIZE_SCALAR(instCnt);
776
777    if (!_switchedOut) {
778        UNSERIALIZE_SCALAR(_pid);
779
780        // Unserialize the threads, this is done by the CPU implementation.
781        for (ThreadID i = 0; i < numThreads; ++i) {
782            ScopedCheckpointSection sec(cp, csprintf("xc.%i", i));
783            interrupts[i]->unserialize(cp);
784            unserializeThread(cp, i);
785        }
786    }
787}
788
789void
790BaseCPU::scheduleInstStop(ThreadID tid, Counter insts, const char *cause)
791{
792    const Tick now(comInstEventQueue[tid]->getCurTick());
793    Event *event(new LocalSimLoopExitEvent(cause, 0));
794
795    comInstEventQueue[tid]->schedule(event, now + insts);
796}
797
798uint64_t
799BaseCPU::getCurrentInstCount(ThreadID tid)
800{
801    return Tick(comInstEventQueue[tid]->getCurTick());
802}
803
804AddressMonitor::AddressMonitor() {
805    armed = false;
806    waiting = false;
807    gotWakeup = false;
808}
809
810bool AddressMonitor::doMonitor(PacketPtr pkt) {
811    assert(pkt->req->hasPaddr());
812    if (armed && waiting) {
813        if (pAddr == pkt->getAddr()) {
814            DPRINTF(Mwait,"pAddr=0x%lx invalidated: waking up core\n",
815                    pkt->getAddr());
816            waiting = false;
817            return true;
818        }
819    }
820    return false;
821}
822
823void
824BaseCPU::scheduleLoadStop(ThreadID tid, Counter loads, const char *cause)
825{
826    const Tick now(comLoadEventQueue[tid]->getCurTick());
827    Event *event(new LocalSimLoopExitEvent(cause, 0));
828
829    comLoadEventQueue[tid]->schedule(event, now + loads);
830}
831
832
833void
834BaseCPU::traceFunctionsInternal(Addr pc)
835{
836    if (!debugSymbolTable)
837        return;
838
839    // if pc enters different function, print new function symbol and
840    // update saved range.  Otherwise do nothing.
841    if (pc < currentFunctionStart || pc >= currentFunctionEnd) {
842        string sym_str;
843        bool found = debugSymbolTable->findNearestSymbol(pc, sym_str,
844                                                         currentFunctionStart,
845                                                         currentFunctionEnd);
846
847        if (!found) {
848            // no symbol found: use addr as label
849            sym_str = csprintf("0x%x", pc);
850            currentFunctionStart = pc;
851            currentFunctionEnd = pc + 1;
852        }
853
854        ccprintf(*functionTraceStream, " (%d)\n%d: %s",
855                 curTick() - functionEntryTick, curTick(), sym_str);
856        functionEntryTick = curTick();
857    }
858}
859
860bool
861BaseCPU::waitForRemoteGDB() const
862{
863    return params()->wait_for_remote_gdb;
864}
865