base.cc revision 9986
19651SAndreas.Sandberg@ARM.com/*
29651SAndreas.Sandberg@ARM.com * Copyright (c) 2012 ARM Limited
39651SAndreas.Sandberg@ARM.com * All rights reserved
49651SAndreas.Sandberg@ARM.com *
59651SAndreas.Sandberg@ARM.com * The license below extends only to copyright in the software and shall
69651SAndreas.Sandberg@ARM.com * not be construed as granting a license to any other intellectual
79651SAndreas.Sandberg@ARM.com * property including but not limited to intellectual property relating
89651SAndreas.Sandberg@ARM.com * to a hardware implementation of the functionality of the software
99651SAndreas.Sandberg@ARM.com * licensed hereunder.  You may use the software subject to the license
109651SAndreas.Sandberg@ARM.com * terms below provided that you ensure that this notice is replicated
119651SAndreas.Sandberg@ARM.com * unmodified and in its entirety in all distributions of the software,
129651SAndreas.Sandberg@ARM.com * modified or unmodified, in source code or in binary form.
139651SAndreas.Sandberg@ARM.com *
149651SAndreas.Sandberg@ARM.com * Redistribution and use in source and binary forms, with or without
159651SAndreas.Sandberg@ARM.com * modification, are permitted provided that the following conditions are
169651SAndreas.Sandberg@ARM.com * met: redistributions of source code must retain the above copyright
179651SAndreas.Sandberg@ARM.com * notice, this list of conditions and the following disclaimer;
189651SAndreas.Sandberg@ARM.com * redistributions in binary form must reproduce the above copyright
199651SAndreas.Sandberg@ARM.com * notice, this list of conditions and the following disclaimer in the
209651SAndreas.Sandberg@ARM.com * documentation and/or other materials provided with the distribution;
219651SAndreas.Sandberg@ARM.com * neither the name of the copyright holders nor the names of its
229651SAndreas.Sandberg@ARM.com * contributors may be used to endorse or promote products derived from
239651SAndreas.Sandberg@ARM.com * this software without specific prior written permission.
249651SAndreas.Sandberg@ARM.com *
259651SAndreas.Sandberg@ARM.com * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
269651SAndreas.Sandberg@ARM.com * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
279651SAndreas.Sandberg@ARM.com * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
289651SAndreas.Sandberg@ARM.com * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
299651SAndreas.Sandberg@ARM.com * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
309651SAndreas.Sandberg@ARM.com * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
319651SAndreas.Sandberg@ARM.com * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
329651SAndreas.Sandberg@ARM.com * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
339651SAndreas.Sandberg@ARM.com * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
349651SAndreas.Sandberg@ARM.com * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
359651SAndreas.Sandberg@ARM.com * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
369651SAndreas.Sandberg@ARM.com *
379651SAndreas.Sandberg@ARM.com * Authors: Andreas Sandberg
389651SAndreas.Sandberg@ARM.com */
399651SAndreas.Sandberg@ARM.com
409651SAndreas.Sandberg@ARM.com#include <linux/kvm.h>
419651SAndreas.Sandberg@ARM.com#include <sys/ioctl.h>
429651SAndreas.Sandberg@ARM.com#include <sys/mman.h>
439651SAndreas.Sandberg@ARM.com#include <unistd.h>
449651SAndreas.Sandberg@ARM.com
459651SAndreas.Sandberg@ARM.com#include <cerrno>
469651SAndreas.Sandberg@ARM.com#include <csignal>
479651SAndreas.Sandberg@ARM.com#include <ostream>
489651SAndreas.Sandberg@ARM.com
499760Sandreas@sandberg.pp.se#include "arch/mmapped_ipr.hh"
509651SAndreas.Sandberg@ARM.com#include "arch/utility.hh"
519651SAndreas.Sandberg@ARM.com#include "cpu/kvm/base.hh"
529683Sandreas@sandberg.pp.se#include "debug/Checkpoint.hh"
539753Sandreas@sandberg.pp.se#include "debug/Drain.hh"
549651SAndreas.Sandberg@ARM.com#include "debug/Kvm.hh"
559651SAndreas.Sandberg@ARM.com#include "debug/KvmIO.hh"
569651SAndreas.Sandberg@ARM.com#include "debug/KvmRun.hh"
579651SAndreas.Sandberg@ARM.com#include "params/BaseKvmCPU.hh"
589651SAndreas.Sandberg@ARM.com#include "sim/process.hh"
599651SAndreas.Sandberg@ARM.com#include "sim/system.hh"
609651SAndreas.Sandberg@ARM.com
619753Sandreas@sandberg.pp.se#include <signal.h>
629753Sandreas@sandberg.pp.se
639651SAndreas.Sandberg@ARM.com/* Used by some KVM macros */
649651SAndreas.Sandberg@ARM.com#define PAGE_SIZE pageSize
659651SAndreas.Sandberg@ARM.com
669651SAndreas.Sandberg@ARM.comvolatile bool timerOverflowed = false;
679651SAndreas.Sandberg@ARM.com
689651SAndreas.Sandberg@ARM.comBaseKvmCPU::BaseKvmCPU(BaseKvmCPUParams *params)
699651SAndreas.Sandberg@ARM.com    : BaseCPU(params),
709651SAndreas.Sandberg@ARM.com      vm(*params->kvmVM),
719651SAndreas.Sandberg@ARM.com      _status(Idle),
729651SAndreas.Sandberg@ARM.com      dataPort(name() + ".dcache_port", this),
739651SAndreas.Sandberg@ARM.com      instPort(name() + ".icache_port", this),
749652SAndreas.Sandberg@ARM.com      threadContextDirty(true),
759652SAndreas.Sandberg@ARM.com      kvmStateDirty(false),
769651SAndreas.Sandberg@ARM.com      vcpuID(vm.allocVCPUID()), vcpuFD(-1), vcpuMMapSize(0),
779651SAndreas.Sandberg@ARM.com      _kvmRun(NULL), mmioRing(NULL),
789651SAndreas.Sandberg@ARM.com      pageSize(sysconf(_SC_PAGE_SIZE)),
799651SAndreas.Sandberg@ARM.com      tickEvent(*this),
809892Sandreas@sandberg.pp.se      activeInstPeriod(0),
819655SAndreas.Sandberg@ARM.com      perfControlledByTimer(params->usePerfOverflow),
829752Sandreas@sandberg.pp.se      hostFactor(params->hostFactor),
839753Sandreas@sandberg.pp.se      drainManager(NULL),
849752Sandreas@sandberg.pp.se      ctrInsts(0)
859651SAndreas.Sandberg@ARM.com{
869651SAndreas.Sandberg@ARM.com    if (pageSize == -1)
879651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to determine host page size (%i)\n",
889651SAndreas.Sandberg@ARM.com              errno);
899651SAndreas.Sandberg@ARM.com
909651SAndreas.Sandberg@ARM.com    thread = new SimpleThread(this, 0, params->system,
919651SAndreas.Sandberg@ARM.com                              params->itb, params->dtb, params->isa[0]);
929651SAndreas.Sandberg@ARM.com    thread->setStatus(ThreadContext::Halted);
939651SAndreas.Sandberg@ARM.com    tc = thread->getTC();
949651SAndreas.Sandberg@ARM.com    threadContexts.push_back(tc);
959651SAndreas.Sandberg@ARM.com
969651SAndreas.Sandberg@ARM.com    setupCounters();
979651SAndreas.Sandberg@ARM.com
989655SAndreas.Sandberg@ARM.com    if (params->usePerfOverflow)
999655SAndreas.Sandberg@ARM.com        runTimer.reset(new PerfKvmTimer(hwCycles,
1009655SAndreas.Sandberg@ARM.com                                        KVM_TIMER_SIGNAL,
1019655SAndreas.Sandberg@ARM.com                                        params->hostFactor,
1029754Sandreas@sandberg.pp.se                                        params->hostFreq));
1039655SAndreas.Sandberg@ARM.com    else
1049655SAndreas.Sandberg@ARM.com        runTimer.reset(new PosixKvmTimer(KVM_TIMER_SIGNAL, CLOCK_MONOTONIC,
1059655SAndreas.Sandberg@ARM.com                                         params->hostFactor,
1069754Sandreas@sandberg.pp.se                                         params->hostFreq));
1079651SAndreas.Sandberg@ARM.com}
1089651SAndreas.Sandberg@ARM.com
1099651SAndreas.Sandberg@ARM.comBaseKvmCPU::~BaseKvmCPU()
1109651SAndreas.Sandberg@ARM.com{
1119651SAndreas.Sandberg@ARM.com    if (_kvmRun)
1129651SAndreas.Sandberg@ARM.com        munmap(_kvmRun, vcpuMMapSize);
1139651SAndreas.Sandberg@ARM.com    close(vcpuFD);
1149651SAndreas.Sandberg@ARM.com}
1159651SAndreas.Sandberg@ARM.com
1169651SAndreas.Sandberg@ARM.comvoid
1179651SAndreas.Sandberg@ARM.comBaseKvmCPU::init()
1189651SAndreas.Sandberg@ARM.com{
1199651SAndreas.Sandberg@ARM.com    BaseCPU::init();
1209651SAndreas.Sandberg@ARM.com
1219651SAndreas.Sandberg@ARM.com    if (numThreads != 1)
1229651SAndreas.Sandberg@ARM.com        fatal("KVM: Multithreading not supported");
1239651SAndreas.Sandberg@ARM.com
1249651SAndreas.Sandberg@ARM.com    tc->initMemProxies(tc);
1259651SAndreas.Sandberg@ARM.com
1269651SAndreas.Sandberg@ARM.com    // initialize CPU, including PC
1279651SAndreas.Sandberg@ARM.com    if (FullSystem && !switchedOut())
1289651SAndreas.Sandberg@ARM.com        TheISA::initCPU(tc, tc->contextId());
1299651SAndreas.Sandberg@ARM.com
1309651SAndreas.Sandberg@ARM.com    mmio_req.setThreadContext(tc->contextId(), 0);
1319651SAndreas.Sandberg@ARM.com}
1329651SAndreas.Sandberg@ARM.com
1339651SAndreas.Sandberg@ARM.comvoid
1349651SAndreas.Sandberg@ARM.comBaseKvmCPU::startup()
1359651SAndreas.Sandberg@ARM.com{
1369690Sandreas@sandberg.pp.se    const BaseKvmCPUParams * const p(
1379690Sandreas@sandberg.pp.se        dynamic_cast<const BaseKvmCPUParams *>(params()));
1389690Sandreas@sandberg.pp.se
1399651SAndreas.Sandberg@ARM.com    Kvm &kvm(vm.kvm);
1409651SAndreas.Sandberg@ARM.com
1419651SAndreas.Sandberg@ARM.com    BaseCPU::startup();
1429651SAndreas.Sandberg@ARM.com
1439651SAndreas.Sandberg@ARM.com    assert(vcpuFD == -1);
1449651SAndreas.Sandberg@ARM.com
1459651SAndreas.Sandberg@ARM.com    // Tell the VM that a CPU is about to start.
1469651SAndreas.Sandberg@ARM.com    vm.cpuStartup();
1479651SAndreas.Sandberg@ARM.com
1489651SAndreas.Sandberg@ARM.com    // We can't initialize KVM CPUs in BaseKvmCPU::init() since we are
1499651SAndreas.Sandberg@ARM.com    // not guaranteed that the parent KVM VM has initialized at that
1509651SAndreas.Sandberg@ARM.com    // point. Initialize virtual CPUs here instead.
1519651SAndreas.Sandberg@ARM.com    vcpuFD = vm.createVCPU(vcpuID);
1529651SAndreas.Sandberg@ARM.com
1539753Sandreas@sandberg.pp.se    // Setup signal handlers. This has to be done after the vCPU is
1549753Sandreas@sandberg.pp.se    // created since it manipulates the vCPU signal mask.
1559753Sandreas@sandberg.pp.se    setupSignalHandler();
1569753Sandreas@sandberg.pp.se
1579651SAndreas.Sandberg@ARM.com    // Map the KVM run structure */
1589651SAndreas.Sandberg@ARM.com    vcpuMMapSize = kvm.getVCPUMMapSize();
1599651SAndreas.Sandberg@ARM.com    _kvmRun = (struct kvm_run *)mmap(0, vcpuMMapSize,
1609651SAndreas.Sandberg@ARM.com                                     PROT_READ | PROT_WRITE, MAP_SHARED,
1619651SAndreas.Sandberg@ARM.com                                     vcpuFD, 0);
1629651SAndreas.Sandberg@ARM.com    if (_kvmRun == MAP_FAILED)
1639651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to map run data structure\n");
1649651SAndreas.Sandberg@ARM.com
1659651SAndreas.Sandberg@ARM.com    // Setup a pointer to the MMIO ring buffer if coalesced MMIO is
1669651SAndreas.Sandberg@ARM.com    // available. The offset into the KVM's communication page is
1679651SAndreas.Sandberg@ARM.com    // provided by the coalesced MMIO capability.
1689651SAndreas.Sandberg@ARM.com    int mmioOffset(kvm.capCoalescedMMIO());
1699690Sandreas@sandberg.pp.se    if (!p->useCoalescedMMIO) {
1709690Sandreas@sandberg.pp.se        inform("KVM: Coalesced MMIO disabled by config.\n");
1719690Sandreas@sandberg.pp.se    } else if (mmioOffset) {
1729651SAndreas.Sandberg@ARM.com        inform("KVM: Coalesced IO available\n");
1739651SAndreas.Sandberg@ARM.com        mmioRing = (struct kvm_coalesced_mmio_ring *)(
1749651SAndreas.Sandberg@ARM.com            (char *)_kvmRun + (mmioOffset * pageSize));
1759651SAndreas.Sandberg@ARM.com    } else {
1769651SAndreas.Sandberg@ARM.com        inform("KVM: Coalesced not supported by host OS\n");
1779651SAndreas.Sandberg@ARM.com    }
1789732Sandreas@sandberg.pp.se
1799732Sandreas@sandberg.pp.se    thread->startup();
1809651SAndreas.Sandberg@ARM.com}
1819651SAndreas.Sandberg@ARM.com
1829651SAndreas.Sandberg@ARM.comvoid
1839651SAndreas.Sandberg@ARM.comBaseKvmCPU::regStats()
1849651SAndreas.Sandberg@ARM.com{
1859651SAndreas.Sandberg@ARM.com    using namespace Stats;
1869651SAndreas.Sandberg@ARM.com
1879651SAndreas.Sandberg@ARM.com    BaseCPU::regStats();
1889651SAndreas.Sandberg@ARM.com
1899684Sandreas@sandberg.pp.se    numInsts
1909684Sandreas@sandberg.pp.se        .name(name() + ".committedInsts")
1919684Sandreas@sandberg.pp.se        .desc("Number of instructions committed")
1929684Sandreas@sandberg.pp.se        ;
1939684Sandreas@sandberg.pp.se
1949651SAndreas.Sandberg@ARM.com    numVMExits
1959651SAndreas.Sandberg@ARM.com        .name(name() + ".numVMExits")
1969651SAndreas.Sandberg@ARM.com        .desc("total number of KVM exits")
1979651SAndreas.Sandberg@ARM.com        ;
1989651SAndreas.Sandberg@ARM.com
1999755Sandreas@sandberg.pp.se    numVMHalfEntries
2009755Sandreas@sandberg.pp.se        .name(name() + ".numVMHalfEntries")
2019755Sandreas@sandberg.pp.se        .desc("number of KVM entries to finalize pending operations")
2029755Sandreas@sandberg.pp.se        ;
2039755Sandreas@sandberg.pp.se
2049755Sandreas@sandberg.pp.se    numExitSignal
2059755Sandreas@sandberg.pp.se        .name(name() + ".numExitSignal")
2069755Sandreas@sandberg.pp.se        .desc("exits due to signal delivery")
2079755Sandreas@sandberg.pp.se        ;
2089755Sandreas@sandberg.pp.se
2099651SAndreas.Sandberg@ARM.com    numMMIO
2109651SAndreas.Sandberg@ARM.com        .name(name() + ".numMMIO")
2119651SAndreas.Sandberg@ARM.com        .desc("number of VM exits due to memory mapped IO")
2129651SAndreas.Sandberg@ARM.com        ;
2139651SAndreas.Sandberg@ARM.com
2149651SAndreas.Sandberg@ARM.com    numCoalescedMMIO
2159651SAndreas.Sandberg@ARM.com        .name(name() + ".numCoalescedMMIO")
2169651SAndreas.Sandberg@ARM.com        .desc("number of coalesced memory mapped IO requests")
2179651SAndreas.Sandberg@ARM.com        ;
2189651SAndreas.Sandberg@ARM.com
2199651SAndreas.Sandberg@ARM.com    numIO
2209651SAndreas.Sandberg@ARM.com        .name(name() + ".numIO")
2219651SAndreas.Sandberg@ARM.com        .desc("number of VM exits due to legacy IO")
2229651SAndreas.Sandberg@ARM.com        ;
2239651SAndreas.Sandberg@ARM.com
2249651SAndreas.Sandberg@ARM.com    numHalt
2259651SAndreas.Sandberg@ARM.com        .name(name() + ".numHalt")
2269651SAndreas.Sandberg@ARM.com        .desc("number of VM exits due to wait for interrupt instructions")
2279651SAndreas.Sandberg@ARM.com        ;
2289651SAndreas.Sandberg@ARM.com
2299651SAndreas.Sandberg@ARM.com    numInterrupts
2309651SAndreas.Sandberg@ARM.com        .name(name() + ".numInterrupts")
2319651SAndreas.Sandberg@ARM.com        .desc("number of interrupts delivered")
2329651SAndreas.Sandberg@ARM.com        ;
2339651SAndreas.Sandberg@ARM.com
2349651SAndreas.Sandberg@ARM.com    numHypercalls
2359651SAndreas.Sandberg@ARM.com        .name(name() + ".numHypercalls")
2369651SAndreas.Sandberg@ARM.com        .desc("number of hypercalls")
2379651SAndreas.Sandberg@ARM.com        ;
2389651SAndreas.Sandberg@ARM.com}
2399651SAndreas.Sandberg@ARM.com
2409651SAndreas.Sandberg@ARM.comvoid
2419651SAndreas.Sandberg@ARM.comBaseKvmCPU::serializeThread(std::ostream &os, ThreadID tid)
2429651SAndreas.Sandberg@ARM.com{
2439683Sandreas@sandberg.pp.se    if (DTRACE(Checkpoint)) {
2449683Sandreas@sandberg.pp.se        DPRINTF(Checkpoint, "KVM: Serializing thread %i:\n", tid);
2459683Sandreas@sandberg.pp.se        dump();
2469683Sandreas@sandberg.pp.se    }
2479683Sandreas@sandberg.pp.se
2489651SAndreas.Sandberg@ARM.com    assert(tid == 0);
2499651SAndreas.Sandberg@ARM.com    assert(_status == Idle);
2509651SAndreas.Sandberg@ARM.com    thread->serialize(os);
2519651SAndreas.Sandberg@ARM.com}
2529651SAndreas.Sandberg@ARM.com
2539651SAndreas.Sandberg@ARM.comvoid
2549651SAndreas.Sandberg@ARM.comBaseKvmCPU::unserializeThread(Checkpoint *cp, const std::string &section,
2559651SAndreas.Sandberg@ARM.com                              ThreadID tid)
2569651SAndreas.Sandberg@ARM.com{
2579683Sandreas@sandberg.pp.se    DPRINTF(Checkpoint, "KVM: Unserialize thread %i:\n", tid);
2589683Sandreas@sandberg.pp.se
2599651SAndreas.Sandberg@ARM.com    assert(tid == 0);
2609651SAndreas.Sandberg@ARM.com    assert(_status == Idle);
2619651SAndreas.Sandberg@ARM.com    thread->unserialize(cp, section);
2629652SAndreas.Sandberg@ARM.com    threadContextDirty = true;
2639651SAndreas.Sandberg@ARM.com}
2649651SAndreas.Sandberg@ARM.com
2659651SAndreas.Sandberg@ARM.comunsigned int
2669651SAndreas.Sandberg@ARM.comBaseKvmCPU::drain(DrainManager *dm)
2679651SAndreas.Sandberg@ARM.com{
2689651SAndreas.Sandberg@ARM.com    if (switchedOut())
2699651SAndreas.Sandberg@ARM.com        return 0;
2709651SAndreas.Sandberg@ARM.com
2719753Sandreas@sandberg.pp.se    DPRINTF(Drain, "BaseKvmCPU::drain\n");
2729753Sandreas@sandberg.pp.se    switch (_status) {
2739753Sandreas@sandberg.pp.se      case Running:
2749753Sandreas@sandberg.pp.se        // The base KVM code is normally ready when it is in the
2759753Sandreas@sandberg.pp.se        // Running state, but the architecture specific code might be
2769753Sandreas@sandberg.pp.se        // of a different opinion. This may happen when the CPU been
2779753Sandreas@sandberg.pp.se        // notified of an event that hasn't been accepted by the vCPU
2789753Sandreas@sandberg.pp.se        // yet.
2799753Sandreas@sandberg.pp.se        if (!archIsDrained()) {
2809753Sandreas@sandberg.pp.se            drainManager = dm;
2819753Sandreas@sandberg.pp.se            return 1;
2829753Sandreas@sandberg.pp.se        }
2839651SAndreas.Sandberg@ARM.com
2849753Sandreas@sandberg.pp.se        // The state of the CPU is consistent, so we don't need to do
2859753Sandreas@sandberg.pp.se        // anything special to drain it. We simply de-schedule the
2869753Sandreas@sandberg.pp.se        // tick event and enter the Idle state to prevent nasty things
2879753Sandreas@sandberg.pp.se        // like MMIOs from happening.
2889753Sandreas@sandberg.pp.se        if (tickEvent.scheduled())
2899753Sandreas@sandberg.pp.se            deschedule(tickEvent);
2909753Sandreas@sandberg.pp.se        _status = Idle;
2919651SAndreas.Sandberg@ARM.com
2929753Sandreas@sandberg.pp.se        /** FALLTHROUGH */
2939753Sandreas@sandberg.pp.se      case Idle:
2949753Sandreas@sandberg.pp.se        // Idle, no need to drain
2959753Sandreas@sandberg.pp.se        assert(!tickEvent.scheduled());
2969753Sandreas@sandberg.pp.se
2979753Sandreas@sandberg.pp.se        // Sync the thread context here since we'll need it when we
2989753Sandreas@sandberg.pp.se        // switch CPUs or checkpoint the CPU.
2999753Sandreas@sandberg.pp.se        syncThreadContext();
3009753Sandreas@sandberg.pp.se
3019753Sandreas@sandberg.pp.se        return 0;
3029753Sandreas@sandberg.pp.se
3039753Sandreas@sandberg.pp.se      case RunningServiceCompletion:
3049753Sandreas@sandberg.pp.se        // The CPU has just requested a service that was handled in
3059753Sandreas@sandberg.pp.se        // the RunningService state, but the results have still not
3069753Sandreas@sandberg.pp.se        // been reported to the CPU. Now, we /could/ probably just
3079753Sandreas@sandberg.pp.se        // update the register state ourselves instead of letting KVM
3089753Sandreas@sandberg.pp.se        // handle it, but that would be tricky. Instead, we enter KVM
3099753Sandreas@sandberg.pp.se        // and let it do its stuff.
3109753Sandreas@sandberg.pp.se        drainManager = dm;
3119753Sandreas@sandberg.pp.se
3129753Sandreas@sandberg.pp.se        DPRINTF(Drain, "KVM CPU is waiting for service completion, "
3139753Sandreas@sandberg.pp.se                "requesting drain.\n");
3149753Sandreas@sandberg.pp.se        return 1;
3159753Sandreas@sandberg.pp.se
3169753Sandreas@sandberg.pp.se      case RunningService:
3179753Sandreas@sandberg.pp.se        // We need to drain since the CPU is waiting for service (e.g., MMIOs)
3189753Sandreas@sandberg.pp.se        drainManager = dm;
3199753Sandreas@sandberg.pp.se
3209753Sandreas@sandberg.pp.se        DPRINTF(Drain, "KVM CPU is waiting for service, requesting drain.\n");
3219753Sandreas@sandberg.pp.se        return 1;
3229753Sandreas@sandberg.pp.se
3239753Sandreas@sandberg.pp.se      default:
3249753Sandreas@sandberg.pp.se        panic("KVM: Unhandled CPU state in drain()\n");
3259753Sandreas@sandberg.pp.se        return 0;
3269753Sandreas@sandberg.pp.se    }
3279651SAndreas.Sandberg@ARM.com}
3289651SAndreas.Sandberg@ARM.com
3299651SAndreas.Sandberg@ARM.comvoid
3309651SAndreas.Sandberg@ARM.comBaseKvmCPU::drainResume()
3319651SAndreas.Sandberg@ARM.com{
3329651SAndreas.Sandberg@ARM.com    assert(!tickEvent.scheduled());
3339651SAndreas.Sandberg@ARM.com
3349651SAndreas.Sandberg@ARM.com    // We might have been switched out. In that case, we don't need to
3359651SAndreas.Sandberg@ARM.com    // do anything.
3369651SAndreas.Sandberg@ARM.com    if (switchedOut())
3379651SAndreas.Sandberg@ARM.com        return;
3389651SAndreas.Sandberg@ARM.com
3399651SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "drainResume\n");
3409651SAndreas.Sandberg@ARM.com    verifyMemoryMode();
3419651SAndreas.Sandberg@ARM.com
3429651SAndreas.Sandberg@ARM.com    // The tick event is de-scheduled as a part of the draining
3439651SAndreas.Sandberg@ARM.com    // process. Re-schedule it if the thread context is active.
3449651SAndreas.Sandberg@ARM.com    if (tc->status() == ThreadContext::Active) {
3459651SAndreas.Sandberg@ARM.com        schedule(tickEvent, nextCycle());
3469651SAndreas.Sandberg@ARM.com        _status = Running;
3479651SAndreas.Sandberg@ARM.com    } else {
3489651SAndreas.Sandberg@ARM.com        _status = Idle;
3499651SAndreas.Sandberg@ARM.com    }
3509651SAndreas.Sandberg@ARM.com}
3519651SAndreas.Sandberg@ARM.com
3529651SAndreas.Sandberg@ARM.comvoid
3539651SAndreas.Sandberg@ARM.comBaseKvmCPU::switchOut()
3549651SAndreas.Sandberg@ARM.com{
3559652SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "switchOut\n");
3569652SAndreas.Sandberg@ARM.com
3579651SAndreas.Sandberg@ARM.com    BaseCPU::switchOut();
3589651SAndreas.Sandberg@ARM.com
3599651SAndreas.Sandberg@ARM.com    // We should have drained prior to executing a switchOut, which
3609651SAndreas.Sandberg@ARM.com    // means that the tick event shouldn't be scheduled and the CPU is
3619651SAndreas.Sandberg@ARM.com    // idle.
3629651SAndreas.Sandberg@ARM.com    assert(!tickEvent.scheduled());
3639651SAndreas.Sandberg@ARM.com    assert(_status == Idle);
3649651SAndreas.Sandberg@ARM.com}
3659651SAndreas.Sandberg@ARM.com
3669651SAndreas.Sandberg@ARM.comvoid
3679651SAndreas.Sandberg@ARM.comBaseKvmCPU::takeOverFrom(BaseCPU *cpu)
3689651SAndreas.Sandberg@ARM.com{
3699651SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "takeOverFrom\n");
3709651SAndreas.Sandberg@ARM.com
3719651SAndreas.Sandberg@ARM.com    BaseCPU::takeOverFrom(cpu);
3729651SAndreas.Sandberg@ARM.com
3739651SAndreas.Sandberg@ARM.com    // We should have drained prior to executing a switchOut, which
3749651SAndreas.Sandberg@ARM.com    // means that the tick event shouldn't be scheduled and the CPU is
3759651SAndreas.Sandberg@ARM.com    // idle.
3769651SAndreas.Sandberg@ARM.com    assert(!tickEvent.scheduled());
3779651SAndreas.Sandberg@ARM.com    assert(_status == Idle);
3789651SAndreas.Sandberg@ARM.com    assert(threadContexts.size() == 1);
3799651SAndreas.Sandberg@ARM.com
3809753Sandreas@sandberg.pp.se    // Force an update of the KVM state here instead of flagging the
3819753Sandreas@sandberg.pp.se    // TC as dirty. This is not ideal from a performance point of
3829753Sandreas@sandberg.pp.se    // view, but it makes debugging easier as it allows meaningful KVM
3839753Sandreas@sandberg.pp.se    // state to be dumped before and after a takeover.
3849753Sandreas@sandberg.pp.se    updateKvmState();
3859753Sandreas@sandberg.pp.se    threadContextDirty = false;
3869651SAndreas.Sandberg@ARM.com}
3879651SAndreas.Sandberg@ARM.com
3889651SAndreas.Sandberg@ARM.comvoid
3899651SAndreas.Sandberg@ARM.comBaseKvmCPU::verifyMemoryMode() const
3909651SAndreas.Sandberg@ARM.com{
3919651SAndreas.Sandberg@ARM.com    if (!(system->isAtomicMode() && system->bypassCaches())) {
3929651SAndreas.Sandberg@ARM.com        fatal("The KVM-based CPUs requires the memory system to be in the "
3939651SAndreas.Sandberg@ARM.com              "'atomic_noncaching' mode.\n");
3949651SAndreas.Sandberg@ARM.com    }
3959651SAndreas.Sandberg@ARM.com}
3969651SAndreas.Sandberg@ARM.com
3979651SAndreas.Sandberg@ARM.comvoid
3989651SAndreas.Sandberg@ARM.comBaseKvmCPU::wakeup()
3999651SAndreas.Sandberg@ARM.com{
4009651SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "wakeup()\n");
4019651SAndreas.Sandberg@ARM.com
4029651SAndreas.Sandberg@ARM.com    if (thread->status() != ThreadContext::Suspended)
4039651SAndreas.Sandberg@ARM.com        return;
4049651SAndreas.Sandberg@ARM.com
4059651SAndreas.Sandberg@ARM.com    thread->activate();
4069651SAndreas.Sandberg@ARM.com}
4079651SAndreas.Sandberg@ARM.com
4089651SAndreas.Sandberg@ARM.comvoid
4099651SAndreas.Sandberg@ARM.comBaseKvmCPU::activateContext(ThreadID thread_num, Cycles delay)
4109651SAndreas.Sandberg@ARM.com{
4119651SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "ActivateContext %d (%d cycles)\n", thread_num, delay);
4129651SAndreas.Sandberg@ARM.com
4139651SAndreas.Sandberg@ARM.com    assert(thread_num == 0);
4149651SAndreas.Sandberg@ARM.com    assert(thread);
4159651SAndreas.Sandberg@ARM.com
4169651SAndreas.Sandberg@ARM.com    assert(_status == Idle);
4179651SAndreas.Sandberg@ARM.com    assert(!tickEvent.scheduled());
4189651SAndreas.Sandberg@ARM.com
4199754Sandreas@sandberg.pp.se    numCycles += ticksToCycles(thread->lastActivate - thread->lastSuspend);
4209651SAndreas.Sandberg@ARM.com
4219651SAndreas.Sandberg@ARM.com    schedule(tickEvent, clockEdge(delay));
4229651SAndreas.Sandberg@ARM.com    _status = Running;
4239651SAndreas.Sandberg@ARM.com}
4249651SAndreas.Sandberg@ARM.com
4259651SAndreas.Sandberg@ARM.com
4269651SAndreas.Sandberg@ARM.comvoid
4279651SAndreas.Sandberg@ARM.comBaseKvmCPU::suspendContext(ThreadID thread_num)
4289651SAndreas.Sandberg@ARM.com{
4299651SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "SuspendContext %d\n", thread_num);
4309651SAndreas.Sandberg@ARM.com
4319651SAndreas.Sandberg@ARM.com    assert(thread_num == 0);
4329651SAndreas.Sandberg@ARM.com    assert(thread);
4339651SAndreas.Sandberg@ARM.com
4349651SAndreas.Sandberg@ARM.com    if (_status == Idle)
4359651SAndreas.Sandberg@ARM.com        return;
4369651SAndreas.Sandberg@ARM.com
4379651SAndreas.Sandberg@ARM.com    assert(_status == Running);
4389651SAndreas.Sandberg@ARM.com
4399651SAndreas.Sandberg@ARM.com    // The tick event may no be scheduled if the quest has requested
4409651SAndreas.Sandberg@ARM.com    // the monitor to wait for interrupts. The normal CPU models can
4419651SAndreas.Sandberg@ARM.com    // get their tick events descheduled by quiesce instructions, but
4429651SAndreas.Sandberg@ARM.com    // that can't happen here.
4439651SAndreas.Sandberg@ARM.com    if (tickEvent.scheduled())
4449651SAndreas.Sandberg@ARM.com        deschedule(tickEvent);
4459651SAndreas.Sandberg@ARM.com
4469651SAndreas.Sandberg@ARM.com    _status = Idle;
4479651SAndreas.Sandberg@ARM.com}
4489651SAndreas.Sandberg@ARM.com
4499651SAndreas.Sandberg@ARM.comvoid
4509651SAndreas.Sandberg@ARM.comBaseKvmCPU::deallocateContext(ThreadID thread_num)
4519651SAndreas.Sandberg@ARM.com{
4529651SAndreas.Sandberg@ARM.com    // for now, these are equivalent
4539651SAndreas.Sandberg@ARM.com    suspendContext(thread_num);
4549651SAndreas.Sandberg@ARM.com}
4559651SAndreas.Sandberg@ARM.com
4569651SAndreas.Sandberg@ARM.comvoid
4579651SAndreas.Sandberg@ARM.comBaseKvmCPU::haltContext(ThreadID thread_num)
4589651SAndreas.Sandberg@ARM.com{
4599651SAndreas.Sandberg@ARM.com    // for now, these are equivalent
4609651SAndreas.Sandberg@ARM.com    suspendContext(thread_num);
4619651SAndreas.Sandberg@ARM.com}
4629651SAndreas.Sandberg@ARM.com
4639652SAndreas.Sandberg@ARM.comThreadContext *
4649652SAndreas.Sandberg@ARM.comBaseKvmCPU::getContext(int tn)
4659652SAndreas.Sandberg@ARM.com{
4669652SAndreas.Sandberg@ARM.com    assert(tn == 0);
4679652SAndreas.Sandberg@ARM.com    syncThreadContext();
4689652SAndreas.Sandberg@ARM.com    return tc;
4699652SAndreas.Sandberg@ARM.com}
4709652SAndreas.Sandberg@ARM.com
4719652SAndreas.Sandberg@ARM.com
4729651SAndreas.Sandberg@ARM.comCounter
4739651SAndreas.Sandberg@ARM.comBaseKvmCPU::totalInsts() const
4749651SAndreas.Sandberg@ARM.com{
4759752Sandreas@sandberg.pp.se    return ctrInsts;
4769651SAndreas.Sandberg@ARM.com}
4779651SAndreas.Sandberg@ARM.com
4789651SAndreas.Sandberg@ARM.comCounter
4799651SAndreas.Sandberg@ARM.comBaseKvmCPU::totalOps() const
4809651SAndreas.Sandberg@ARM.com{
4819651SAndreas.Sandberg@ARM.com    hack_once("Pretending totalOps is equivalent to totalInsts()\n");
4829752Sandreas@sandberg.pp.se    return ctrInsts;
4839651SAndreas.Sandberg@ARM.com}
4849651SAndreas.Sandberg@ARM.com
4859651SAndreas.Sandberg@ARM.comvoid
4869651SAndreas.Sandberg@ARM.comBaseKvmCPU::dump()
4879651SAndreas.Sandberg@ARM.com{
4889651SAndreas.Sandberg@ARM.com    inform("State dumping not implemented.");
4899651SAndreas.Sandberg@ARM.com}
4909651SAndreas.Sandberg@ARM.com
4919651SAndreas.Sandberg@ARM.comvoid
4929651SAndreas.Sandberg@ARM.comBaseKvmCPU::tick()
4939651SAndreas.Sandberg@ARM.com{
4949753Sandreas@sandberg.pp.se    Tick delay(0);
4959753Sandreas@sandberg.pp.se    assert(_status != Idle);
4969651SAndreas.Sandberg@ARM.com
4979651SAndreas.Sandberg@ARM.com    switch (_status) {
4989753Sandreas@sandberg.pp.se      case RunningService:
4999753Sandreas@sandberg.pp.se        // handleKvmExit() will determine the next state of the CPU
5009753Sandreas@sandberg.pp.se        delay = handleKvmExit();
5019753Sandreas@sandberg.pp.se
5029753Sandreas@sandberg.pp.se        if (tryDrain())
5039753Sandreas@sandberg.pp.se            _status = Idle;
5049651SAndreas.Sandberg@ARM.com        break;
5059651SAndreas.Sandberg@ARM.com
5069753Sandreas@sandberg.pp.se      case RunningServiceCompletion:
5079753Sandreas@sandberg.pp.se      case Running: {
5089983Sstever@gmail.com          EventQueue *q = curEventQueue();
5099983Sstever@gmail.com          Tick ticksToExecute(q->nextTick() - curTick());
5109753Sandreas@sandberg.pp.se
5119753Sandreas@sandberg.pp.se          // We might need to update the KVM state.
5129753Sandreas@sandberg.pp.se          syncKvmState();
5139753Sandreas@sandberg.pp.se
5149892Sandreas@sandberg.pp.se          // Setup any pending instruction count breakpoints using
5159892Sandreas@sandberg.pp.se          // PerfEvent.
5169892Sandreas@sandberg.pp.se          setupInstStop();
5179892Sandreas@sandberg.pp.se
5189753Sandreas@sandberg.pp.se          DPRINTF(KvmRun, "Entering KVM...\n");
5199753Sandreas@sandberg.pp.se          if (drainManager) {
5209753Sandreas@sandberg.pp.se              // Force an immediate exit from KVM after completing
5219753Sandreas@sandberg.pp.se              // pending operations. The architecture-specific code
5229753Sandreas@sandberg.pp.se              // takes care to run until it is in a state where it can
5239753Sandreas@sandberg.pp.se              // safely be drained.
5249753Sandreas@sandberg.pp.se              delay = kvmRunDrain();
5259753Sandreas@sandberg.pp.se          } else {
5269753Sandreas@sandberg.pp.se              delay = kvmRun(ticksToExecute);
5279753Sandreas@sandberg.pp.se          }
5289753Sandreas@sandberg.pp.se
5299753Sandreas@sandberg.pp.se          // Entering into KVM implies that we'll have to reload the thread
5309753Sandreas@sandberg.pp.se          // context from KVM if we want to access it. Flag the KVM state as
5319753Sandreas@sandberg.pp.se          // dirty with respect to the cached thread context.
5329753Sandreas@sandberg.pp.se          kvmStateDirty = true;
5339753Sandreas@sandberg.pp.se
5349753Sandreas@sandberg.pp.se          // Enter into the RunningService state unless the
5359753Sandreas@sandberg.pp.se          // simulation was stopped by a timer.
5369755Sandreas@sandberg.pp.se          if (_kvmRun->exit_reason !=  KVM_EXIT_INTR) {
5379753Sandreas@sandberg.pp.se              _status = RunningService;
5389755Sandreas@sandberg.pp.se          } else {
5399755Sandreas@sandberg.pp.se              ++numExitSignal;
5409753Sandreas@sandberg.pp.se              _status = Running;
5419755Sandreas@sandberg.pp.se          }
5429753Sandreas@sandberg.pp.se
5439904Sandreas@sandberg.pp.se          // Service any pending instruction events. The vCPU should
5449904Sandreas@sandberg.pp.se          // have exited in time for the event using the instruction
5459904Sandreas@sandberg.pp.se          // counter configured by setupInstStop().
5469904Sandreas@sandberg.pp.se          comInstEventQueue[0]->serviceEvents(ctrInsts);
5479904Sandreas@sandberg.pp.se          system->instEventQueue.serviceEvents(system->totalNumInsts);
5489904Sandreas@sandberg.pp.se
5499753Sandreas@sandberg.pp.se          if (tryDrain())
5509753Sandreas@sandberg.pp.se              _status = Idle;
5519753Sandreas@sandberg.pp.se      } break;
5529753Sandreas@sandberg.pp.se
5539651SAndreas.Sandberg@ARM.com      default:
5549753Sandreas@sandberg.pp.se        panic("BaseKvmCPU entered tick() in an illegal state (%i)\n",
5559753Sandreas@sandberg.pp.se              _status);
5569651SAndreas.Sandberg@ARM.com    }
5579753Sandreas@sandberg.pp.se
5589753Sandreas@sandberg.pp.se    // Schedule a new tick if we are still running
5599753Sandreas@sandberg.pp.se    if (_status != Idle)
5609753Sandreas@sandberg.pp.se        schedule(tickEvent, clockEdge(ticksToCycles(delay)));
5619753Sandreas@sandberg.pp.se}
5629753Sandreas@sandberg.pp.se
5639753Sandreas@sandberg.pp.seTick
5649753Sandreas@sandberg.pp.seBaseKvmCPU::kvmRunDrain()
5659753Sandreas@sandberg.pp.se{
5669753Sandreas@sandberg.pp.se    // By default, the only thing we need to drain is a pending IO
5679753Sandreas@sandberg.pp.se    // operation which assumes that we are in the
5689753Sandreas@sandberg.pp.se    // RunningServiceCompletion state.
5699753Sandreas@sandberg.pp.se    assert(_status == RunningServiceCompletion);
5709753Sandreas@sandberg.pp.se
5719753Sandreas@sandberg.pp.se    // Deliver the data from the pending IO operation and immediately
5729753Sandreas@sandberg.pp.se    // exit.
5739753Sandreas@sandberg.pp.se    return kvmRun(0);
5749651SAndreas.Sandberg@ARM.com}
5759651SAndreas.Sandberg@ARM.com
5769735Sandreas@sandberg.pp.seuint64_t
5779735Sandreas@sandberg.pp.seBaseKvmCPU::getHostCycles() const
5789735Sandreas@sandberg.pp.se{
5799735Sandreas@sandberg.pp.se    return hwCycles.read();
5809735Sandreas@sandberg.pp.se}
5819735Sandreas@sandberg.pp.se
5829651SAndreas.Sandberg@ARM.comTick
5839651SAndreas.Sandberg@ARM.comBaseKvmCPU::kvmRun(Tick ticks)
5849651SAndreas.Sandberg@ARM.com{
5859753Sandreas@sandberg.pp.se    Tick ticksExecuted;
5869651SAndreas.Sandberg@ARM.com    DPRINTF(KvmRun, "KVM: Executing for %i ticks\n", ticks);
5879651SAndreas.Sandberg@ARM.com    timerOverflowed = false;
5889655SAndreas.Sandberg@ARM.com
5899753Sandreas@sandberg.pp.se    if (ticks == 0) {
5909753Sandreas@sandberg.pp.se        // Settings ticks == 0 is a special case which causes an entry
5919753Sandreas@sandberg.pp.se        // into KVM that finishes pending operations (e.g., IO) and
5929753Sandreas@sandberg.pp.se        // then immediately exits.
5939753Sandreas@sandberg.pp.se        DPRINTF(KvmRun, "KVM: Delivering IO without full guest entry\n");
5949735Sandreas@sandberg.pp.se
5959755Sandreas@sandberg.pp.se        ++numVMHalfEntries;
5969755Sandreas@sandberg.pp.se
5979753Sandreas@sandberg.pp.se        // This signal is always masked while we are executing in gem5
5989753Sandreas@sandberg.pp.se        // and gets unmasked temporarily as soon as we enter into
5999753Sandreas@sandberg.pp.se        // KVM. See setSignalMask() and setupSignalHandler().
6009753Sandreas@sandberg.pp.se        raise(KVM_TIMER_SIGNAL);
6019655SAndreas.Sandberg@ARM.com
6029753Sandreas@sandberg.pp.se        // Enter into KVM. KVM will check for signals after completing
6039753Sandreas@sandberg.pp.se        // pending operations (IO). Since the KVM_TIMER_SIGNAL is
6049753Sandreas@sandberg.pp.se        // pending, this forces an immediate exit into gem5 again. We
6059753Sandreas@sandberg.pp.se        // don't bother to setup timers since this shouldn't actually
6069753Sandreas@sandberg.pp.se        // execute any code in the guest.
6079753Sandreas@sandberg.pp.se        ioctlRun();
6089753Sandreas@sandberg.pp.se
6099753Sandreas@sandberg.pp.se        // We always execute at least one cycle to prevent the
6109753Sandreas@sandberg.pp.se        // BaseKvmCPU::tick() to be rescheduled on the same tick
6119753Sandreas@sandberg.pp.se        // twice.
6129753Sandreas@sandberg.pp.se        ticksExecuted = clockPeriod();
6139753Sandreas@sandberg.pp.se    } else {
6149753Sandreas@sandberg.pp.se        if (ticks < runTimer->resolution()) {
6159753Sandreas@sandberg.pp.se            DPRINTF(KvmRun, "KVM: Adjusting tick count (%i -> %i)\n",
6169753Sandreas@sandberg.pp.se                    ticks, runTimer->resolution());
6179753Sandreas@sandberg.pp.se            ticks = runTimer->resolution();
6189753Sandreas@sandberg.pp.se        }
6199753Sandreas@sandberg.pp.se
6209753Sandreas@sandberg.pp.se        // Get hardware statistics after synchronizing contexts. The KVM
6219753Sandreas@sandberg.pp.se        // state update might affect guest cycle counters.
6229753Sandreas@sandberg.pp.se        uint64_t baseCycles(getHostCycles());
6239753Sandreas@sandberg.pp.se        uint64_t baseInstrs(hwInstructions.read());
6249753Sandreas@sandberg.pp.se
6259753Sandreas@sandberg.pp.se        // Arm the run timer and start the cycle timer if it isn't
6269753Sandreas@sandberg.pp.se        // controlled by the overflow timer. Starting/stopping the cycle
6279753Sandreas@sandberg.pp.se        // timer automatically starts the other perf timers as they are in
6289753Sandreas@sandberg.pp.se        // the same counter group.
6299753Sandreas@sandberg.pp.se        runTimer->arm(ticks);
6309753Sandreas@sandberg.pp.se        if (!perfControlledByTimer)
6319753Sandreas@sandberg.pp.se            hwCycles.start();
6329753Sandreas@sandberg.pp.se
6339753Sandreas@sandberg.pp.se        ioctlRun();
6349753Sandreas@sandberg.pp.se
6359753Sandreas@sandberg.pp.se        runTimer->disarm();
6369753Sandreas@sandberg.pp.se        if (!perfControlledByTimer)
6379753Sandreas@sandberg.pp.se            hwCycles.stop();
6389753Sandreas@sandberg.pp.se
6399753Sandreas@sandberg.pp.se        // The timer signal may have been delivered after we exited
6409753Sandreas@sandberg.pp.se        // from KVM. It will be pending in that case since it is
6419753Sandreas@sandberg.pp.se        // masked when we aren't executing in KVM. Discard it to make
6429753Sandreas@sandberg.pp.se        // sure we don't deliver it immediately next time we try to
6439753Sandreas@sandberg.pp.se        // enter into KVM.
6449753Sandreas@sandberg.pp.se        discardPendingSignal(KVM_TIMER_SIGNAL);
6459892Sandreas@sandberg.pp.se        discardPendingSignal(KVM_INST_SIGNAL);
6469753Sandreas@sandberg.pp.se
6479753Sandreas@sandberg.pp.se        const uint64_t hostCyclesExecuted(getHostCycles() - baseCycles);
6489753Sandreas@sandberg.pp.se        const uint64_t simCyclesExecuted(hostCyclesExecuted * hostFactor);
6499753Sandreas@sandberg.pp.se        const uint64_t instsExecuted(hwInstructions.read() - baseInstrs);
6509753Sandreas@sandberg.pp.se        ticksExecuted = runTimer->ticksFromHostCycles(hostCyclesExecuted);
6519753Sandreas@sandberg.pp.se
6529753Sandreas@sandberg.pp.se        if (ticksExecuted < ticks &&
6539753Sandreas@sandberg.pp.se            timerOverflowed &&
6549753Sandreas@sandberg.pp.se            _kvmRun->exit_reason == KVM_EXIT_INTR) {
6559753Sandreas@sandberg.pp.se            // TODO: We should probably do something clever here...
6569753Sandreas@sandberg.pp.se            warn("KVM: Early timer event, requested %i ticks but got %i ticks.\n",
6579753Sandreas@sandberg.pp.se                 ticks, ticksExecuted);
6589753Sandreas@sandberg.pp.se        }
6599753Sandreas@sandberg.pp.se
6609753Sandreas@sandberg.pp.se        /* Update statistics */
6619753Sandreas@sandberg.pp.se        numCycles += simCyclesExecuted;;
6629753Sandreas@sandberg.pp.se        numInsts += instsExecuted;
6639753Sandreas@sandberg.pp.se        ctrInsts += instsExecuted;
6649753Sandreas@sandberg.pp.se        system->totalNumInsts += instsExecuted;
6659753Sandreas@sandberg.pp.se
6669753Sandreas@sandberg.pp.se        DPRINTF(KvmRun,
6679753Sandreas@sandberg.pp.se                "KVM: Executed %i instructions in %i cycles "
6689753Sandreas@sandberg.pp.se                "(%i ticks, sim cycles: %i).\n",
6699753Sandreas@sandberg.pp.se                instsExecuted, hostCyclesExecuted, ticksExecuted, simCyclesExecuted);
6709651SAndreas.Sandberg@ARM.com    }
6719655SAndreas.Sandberg@ARM.com
6729651SAndreas.Sandberg@ARM.com    ++numVMExits;
6739651SAndreas.Sandberg@ARM.com
6749651SAndreas.Sandberg@ARM.com    return ticksExecuted + flushCoalescedMMIO();
6759651SAndreas.Sandberg@ARM.com}
6769651SAndreas.Sandberg@ARM.com
6779651SAndreas.Sandberg@ARM.comvoid
6789651SAndreas.Sandberg@ARM.comBaseKvmCPU::kvmNonMaskableInterrupt()
6799651SAndreas.Sandberg@ARM.com{
6809651SAndreas.Sandberg@ARM.com    ++numInterrupts;
6819651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_NMI) == -1)
6829651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to deliver NMI to virtual CPU\n");
6839651SAndreas.Sandberg@ARM.com}
6849651SAndreas.Sandberg@ARM.com
6859651SAndreas.Sandberg@ARM.comvoid
6869651SAndreas.Sandberg@ARM.comBaseKvmCPU::kvmInterrupt(const struct kvm_interrupt &interrupt)
6879651SAndreas.Sandberg@ARM.com{
6889651SAndreas.Sandberg@ARM.com    ++numInterrupts;
6899651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_INTERRUPT, (void *)&interrupt) == -1)
6909651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to deliver interrupt to virtual CPU\n");
6919651SAndreas.Sandberg@ARM.com}
6929651SAndreas.Sandberg@ARM.com
6939651SAndreas.Sandberg@ARM.comvoid
6949651SAndreas.Sandberg@ARM.comBaseKvmCPU::getRegisters(struct kvm_regs &regs) const
6959651SAndreas.Sandberg@ARM.com{
6969651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_GET_REGS, &regs) == -1)
6979651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to get guest registers\n");
6989651SAndreas.Sandberg@ARM.com}
6999651SAndreas.Sandberg@ARM.com
7009651SAndreas.Sandberg@ARM.comvoid
7019651SAndreas.Sandberg@ARM.comBaseKvmCPU::setRegisters(const struct kvm_regs &regs)
7029651SAndreas.Sandberg@ARM.com{
7039651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_SET_REGS, (void *)&regs) == -1)
7049651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to set guest registers\n");
7059651SAndreas.Sandberg@ARM.com}
7069651SAndreas.Sandberg@ARM.com
7079651SAndreas.Sandberg@ARM.comvoid
7089651SAndreas.Sandberg@ARM.comBaseKvmCPU::getSpecialRegisters(struct kvm_sregs &regs) const
7099651SAndreas.Sandberg@ARM.com{
7109651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_GET_SREGS, &regs) == -1)
7119651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to get guest special registers\n");
7129651SAndreas.Sandberg@ARM.com}
7139651SAndreas.Sandberg@ARM.com
7149651SAndreas.Sandberg@ARM.comvoid
7159651SAndreas.Sandberg@ARM.comBaseKvmCPU::setSpecialRegisters(const struct kvm_sregs &regs)
7169651SAndreas.Sandberg@ARM.com{
7179651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_SET_SREGS, (void *)&regs) == -1)
7189651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to set guest special registers\n");
7199651SAndreas.Sandberg@ARM.com}
7209651SAndreas.Sandberg@ARM.com
7219651SAndreas.Sandberg@ARM.comvoid
7229651SAndreas.Sandberg@ARM.comBaseKvmCPU::getFPUState(struct kvm_fpu &state) const
7239651SAndreas.Sandberg@ARM.com{
7249651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_GET_FPU, &state) == -1)
7259651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to get guest FPU state\n");
7269651SAndreas.Sandberg@ARM.com}
7279651SAndreas.Sandberg@ARM.com
7289651SAndreas.Sandberg@ARM.comvoid
7299651SAndreas.Sandberg@ARM.comBaseKvmCPU::setFPUState(const struct kvm_fpu &state)
7309651SAndreas.Sandberg@ARM.com{
7319651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_SET_FPU, (void *)&state) == -1)
7329651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to set guest FPU state\n");
7339651SAndreas.Sandberg@ARM.com}
7349651SAndreas.Sandberg@ARM.com
7359651SAndreas.Sandberg@ARM.com
7369651SAndreas.Sandberg@ARM.comvoid
7379651SAndreas.Sandberg@ARM.comBaseKvmCPU::setOneReg(uint64_t id, const void *addr)
7389651SAndreas.Sandberg@ARM.com{
7399651SAndreas.Sandberg@ARM.com#ifdef KVM_SET_ONE_REG
7409651SAndreas.Sandberg@ARM.com    struct kvm_one_reg reg;
7419651SAndreas.Sandberg@ARM.com    reg.id = id;
7429651SAndreas.Sandberg@ARM.com    reg.addr = (uint64_t)addr;
7439651SAndreas.Sandberg@ARM.com
7449651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_SET_ONE_REG, &reg) == -1) {
7459651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to set register (0x%x) value (errno: %i)\n",
7469651SAndreas.Sandberg@ARM.com              id, errno);
7479651SAndreas.Sandberg@ARM.com    }
7489651SAndreas.Sandberg@ARM.com#else
7499651SAndreas.Sandberg@ARM.com    panic("KVM_SET_ONE_REG is unsupported on this platform.\n");
7509651SAndreas.Sandberg@ARM.com#endif
7519651SAndreas.Sandberg@ARM.com}
7529651SAndreas.Sandberg@ARM.com
7539651SAndreas.Sandberg@ARM.comvoid
7549651SAndreas.Sandberg@ARM.comBaseKvmCPU::getOneReg(uint64_t id, void *addr) const
7559651SAndreas.Sandberg@ARM.com{
7569651SAndreas.Sandberg@ARM.com#ifdef KVM_GET_ONE_REG
7579651SAndreas.Sandberg@ARM.com    struct kvm_one_reg reg;
7589651SAndreas.Sandberg@ARM.com    reg.id = id;
7599651SAndreas.Sandberg@ARM.com    reg.addr = (uint64_t)addr;
7609651SAndreas.Sandberg@ARM.com
7619651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_GET_ONE_REG, &reg) == -1) {
7629651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to get register (0x%x) value (errno: %i)\n",
7639651SAndreas.Sandberg@ARM.com              id, errno);
7649651SAndreas.Sandberg@ARM.com    }
7659651SAndreas.Sandberg@ARM.com#else
7669651SAndreas.Sandberg@ARM.com    panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
7679651SAndreas.Sandberg@ARM.com#endif
7689651SAndreas.Sandberg@ARM.com}
7699651SAndreas.Sandberg@ARM.com
7709651SAndreas.Sandberg@ARM.comstd::string
7719651SAndreas.Sandberg@ARM.comBaseKvmCPU::getAndFormatOneReg(uint64_t id) const
7729651SAndreas.Sandberg@ARM.com{
7739651SAndreas.Sandberg@ARM.com#ifdef KVM_GET_ONE_REG
7749651SAndreas.Sandberg@ARM.com    std::ostringstream ss;
7759651SAndreas.Sandberg@ARM.com
7769651SAndreas.Sandberg@ARM.com    ss.setf(std::ios::hex, std::ios::basefield);
7779651SAndreas.Sandberg@ARM.com    ss.setf(std::ios::showbase);
7789651SAndreas.Sandberg@ARM.com#define HANDLE_INTTYPE(len)                      \
7799651SAndreas.Sandberg@ARM.com    case KVM_REG_SIZE_U ## len: {                \
7809651SAndreas.Sandberg@ARM.com        uint ## len ## _t value;                 \
7819651SAndreas.Sandberg@ARM.com        getOneReg(id, &value);                   \
7829651SAndreas.Sandberg@ARM.com        ss << value;                             \
7839651SAndreas.Sandberg@ARM.com    }  break
7849651SAndreas.Sandberg@ARM.com
7859651SAndreas.Sandberg@ARM.com#define HANDLE_ARRAY(len)                       \
7869651SAndreas.Sandberg@ARM.com    case KVM_REG_SIZE_U ## len: {               \
7879651SAndreas.Sandberg@ARM.com        uint8_t value[len / 8];                 \
7889651SAndreas.Sandberg@ARM.com        getOneReg(id, value);                   \
7899651SAndreas.Sandberg@ARM.com        ss << "[" << value[0];                  \
7909651SAndreas.Sandberg@ARM.com        for (int i = 1; i < len  / 8; ++i)      \
7919651SAndreas.Sandberg@ARM.com            ss << ", " << value[i];             \
7929651SAndreas.Sandberg@ARM.com        ss << "]";                              \
7939651SAndreas.Sandberg@ARM.com      } break
7949651SAndreas.Sandberg@ARM.com
7959651SAndreas.Sandberg@ARM.com    switch (id & KVM_REG_SIZE_MASK) {
7969651SAndreas.Sandberg@ARM.com        HANDLE_INTTYPE(8);
7979651SAndreas.Sandberg@ARM.com        HANDLE_INTTYPE(16);
7989651SAndreas.Sandberg@ARM.com        HANDLE_INTTYPE(32);
7999651SAndreas.Sandberg@ARM.com        HANDLE_INTTYPE(64);
8009651SAndreas.Sandberg@ARM.com        HANDLE_ARRAY(128);
8019651SAndreas.Sandberg@ARM.com        HANDLE_ARRAY(256);
8029651SAndreas.Sandberg@ARM.com        HANDLE_ARRAY(512);
8039651SAndreas.Sandberg@ARM.com        HANDLE_ARRAY(1024);
8049651SAndreas.Sandberg@ARM.com      default:
8059651SAndreas.Sandberg@ARM.com        ss << "??";
8069651SAndreas.Sandberg@ARM.com    }
8079651SAndreas.Sandberg@ARM.com
8089651SAndreas.Sandberg@ARM.com#undef HANDLE_INTTYPE
8099651SAndreas.Sandberg@ARM.com#undef HANDLE_ARRAY
8109651SAndreas.Sandberg@ARM.com
8119651SAndreas.Sandberg@ARM.com    return ss.str();
8129651SAndreas.Sandberg@ARM.com#else
8139651SAndreas.Sandberg@ARM.com    panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
8149651SAndreas.Sandberg@ARM.com#endif
8159651SAndreas.Sandberg@ARM.com}
8169651SAndreas.Sandberg@ARM.com
8179652SAndreas.Sandberg@ARM.comvoid
8189652SAndreas.Sandberg@ARM.comBaseKvmCPU::syncThreadContext()
8199652SAndreas.Sandberg@ARM.com{
8209652SAndreas.Sandberg@ARM.com    if (!kvmStateDirty)
8219652SAndreas.Sandberg@ARM.com        return;
8229652SAndreas.Sandberg@ARM.com
8239652SAndreas.Sandberg@ARM.com    assert(!threadContextDirty);
8249652SAndreas.Sandberg@ARM.com
8259652SAndreas.Sandberg@ARM.com    updateThreadContext();
8269652SAndreas.Sandberg@ARM.com    kvmStateDirty = false;
8279652SAndreas.Sandberg@ARM.com}
8289652SAndreas.Sandberg@ARM.com
8299652SAndreas.Sandberg@ARM.comvoid
8309652SAndreas.Sandberg@ARM.comBaseKvmCPU::syncKvmState()
8319652SAndreas.Sandberg@ARM.com{
8329652SAndreas.Sandberg@ARM.com    if (!threadContextDirty)
8339652SAndreas.Sandberg@ARM.com        return;
8349652SAndreas.Sandberg@ARM.com
8359652SAndreas.Sandberg@ARM.com    assert(!kvmStateDirty);
8369652SAndreas.Sandberg@ARM.com
8379652SAndreas.Sandberg@ARM.com    updateKvmState();
8389652SAndreas.Sandberg@ARM.com    threadContextDirty = false;
8399652SAndreas.Sandberg@ARM.com}
8409652SAndreas.Sandberg@ARM.com
8419651SAndreas.Sandberg@ARM.comTick
8429651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExit()
8439651SAndreas.Sandberg@ARM.com{
8449651SAndreas.Sandberg@ARM.com    DPRINTF(KvmRun, "handleKvmExit (exit_reason: %i)\n", _kvmRun->exit_reason);
8459753Sandreas@sandberg.pp.se    assert(_status == RunningService);
8469651SAndreas.Sandberg@ARM.com
8479753Sandreas@sandberg.pp.se    // Switch into the running state by default. Individual handlers
8489753Sandreas@sandberg.pp.se    // can override this.
8499753Sandreas@sandberg.pp.se    _status = Running;
8509651SAndreas.Sandberg@ARM.com    switch (_kvmRun->exit_reason) {
8519651SAndreas.Sandberg@ARM.com      case KVM_EXIT_UNKNOWN:
8529651SAndreas.Sandberg@ARM.com        return handleKvmExitUnknown();
8539651SAndreas.Sandberg@ARM.com
8549651SAndreas.Sandberg@ARM.com      case KVM_EXIT_EXCEPTION:
8559651SAndreas.Sandberg@ARM.com        return handleKvmExitException();
8569651SAndreas.Sandberg@ARM.com
8579651SAndreas.Sandberg@ARM.com      case KVM_EXIT_IO:
8589753Sandreas@sandberg.pp.se        _status = RunningServiceCompletion;
8599651SAndreas.Sandberg@ARM.com        ++numIO;
8609651SAndreas.Sandberg@ARM.com        return handleKvmExitIO();
8619651SAndreas.Sandberg@ARM.com
8629651SAndreas.Sandberg@ARM.com      case KVM_EXIT_HYPERCALL:
8639651SAndreas.Sandberg@ARM.com        ++numHypercalls;
8649651SAndreas.Sandberg@ARM.com        return handleKvmExitHypercall();
8659651SAndreas.Sandberg@ARM.com
8669651SAndreas.Sandberg@ARM.com      case KVM_EXIT_HLT:
8679651SAndreas.Sandberg@ARM.com        /* The guest has halted and is waiting for interrupts */
8689651SAndreas.Sandberg@ARM.com        DPRINTF(Kvm, "handleKvmExitHalt\n");
8699651SAndreas.Sandberg@ARM.com        ++numHalt;
8709651SAndreas.Sandberg@ARM.com
8719651SAndreas.Sandberg@ARM.com        // Suspend the thread until the next interrupt arrives
8729651SAndreas.Sandberg@ARM.com        thread->suspend();
8739651SAndreas.Sandberg@ARM.com
8749651SAndreas.Sandberg@ARM.com        // This is actually ignored since the thread is suspended.
8759651SAndreas.Sandberg@ARM.com        return 0;
8769651SAndreas.Sandberg@ARM.com
8779651SAndreas.Sandberg@ARM.com      case KVM_EXIT_MMIO:
8789753Sandreas@sandberg.pp.se        _status = RunningServiceCompletion;
8799651SAndreas.Sandberg@ARM.com        /* Service memory mapped IO requests */
8809651SAndreas.Sandberg@ARM.com        DPRINTF(KvmIO, "KVM: Handling MMIO (w: %u, addr: 0x%x, len: %u)\n",
8819651SAndreas.Sandberg@ARM.com                _kvmRun->mmio.is_write,
8829651SAndreas.Sandberg@ARM.com                _kvmRun->mmio.phys_addr, _kvmRun->mmio.len);
8839651SAndreas.Sandberg@ARM.com
8849651SAndreas.Sandberg@ARM.com        ++numMMIO;
8859651SAndreas.Sandberg@ARM.com        return doMMIOAccess(_kvmRun->mmio.phys_addr, _kvmRun->mmio.data,
8869651SAndreas.Sandberg@ARM.com                            _kvmRun->mmio.len, _kvmRun->mmio.is_write);
8879651SAndreas.Sandberg@ARM.com
8889651SAndreas.Sandberg@ARM.com      case KVM_EXIT_IRQ_WINDOW_OPEN:
8899651SAndreas.Sandberg@ARM.com        return handleKvmExitIRQWindowOpen();
8909651SAndreas.Sandberg@ARM.com
8919651SAndreas.Sandberg@ARM.com      case KVM_EXIT_FAIL_ENTRY:
8929651SAndreas.Sandberg@ARM.com        return handleKvmExitFailEntry();
8939651SAndreas.Sandberg@ARM.com
8949651SAndreas.Sandberg@ARM.com      case KVM_EXIT_INTR:
8959651SAndreas.Sandberg@ARM.com        /* KVM was interrupted by a signal, restart it in the next
8969651SAndreas.Sandberg@ARM.com         * tick. */
8979651SAndreas.Sandberg@ARM.com        return 0;
8989651SAndreas.Sandberg@ARM.com
8999651SAndreas.Sandberg@ARM.com      case KVM_EXIT_INTERNAL_ERROR:
9009651SAndreas.Sandberg@ARM.com        panic("KVM: Internal error (suberror: %u)\n",
9019651SAndreas.Sandberg@ARM.com              _kvmRun->internal.suberror);
9029651SAndreas.Sandberg@ARM.com
9039651SAndreas.Sandberg@ARM.com      default:
9049689Sandreas@sandberg.pp.se        dump();
9059651SAndreas.Sandberg@ARM.com        panic("KVM: Unexpected exit (exit_reason: %u)\n", _kvmRun->exit_reason);
9069651SAndreas.Sandberg@ARM.com    }
9079651SAndreas.Sandberg@ARM.com}
9089651SAndreas.Sandberg@ARM.com
9099651SAndreas.Sandberg@ARM.comTick
9109651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitIO()
9119651SAndreas.Sandberg@ARM.com{
9129651SAndreas.Sandberg@ARM.com    panic("KVM: Unhandled guest IO (dir: %i, size: %i, port: 0x%x, count: %i)\n",
9139651SAndreas.Sandberg@ARM.com          _kvmRun->io.direction, _kvmRun->io.size,
9149651SAndreas.Sandberg@ARM.com          _kvmRun->io.port, _kvmRun->io.count);
9159651SAndreas.Sandberg@ARM.com}
9169651SAndreas.Sandberg@ARM.com
9179651SAndreas.Sandberg@ARM.comTick
9189651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitHypercall()
9199651SAndreas.Sandberg@ARM.com{
9209651SAndreas.Sandberg@ARM.com    panic("KVM: Unhandled hypercall\n");
9219651SAndreas.Sandberg@ARM.com}
9229651SAndreas.Sandberg@ARM.com
9239651SAndreas.Sandberg@ARM.comTick
9249651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitIRQWindowOpen()
9259651SAndreas.Sandberg@ARM.com{
9269651SAndreas.Sandberg@ARM.com    warn("KVM: Unhandled IRQ window.\n");
9279651SAndreas.Sandberg@ARM.com    return 0;
9289651SAndreas.Sandberg@ARM.com}
9299651SAndreas.Sandberg@ARM.com
9309651SAndreas.Sandberg@ARM.com
9319651SAndreas.Sandberg@ARM.comTick
9329651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitUnknown()
9339651SAndreas.Sandberg@ARM.com{
9349689Sandreas@sandberg.pp.se    dump();
9359651SAndreas.Sandberg@ARM.com    panic("KVM: Unknown error when starting vCPU (hw reason: 0x%llx)\n",
9369651SAndreas.Sandberg@ARM.com          _kvmRun->hw.hardware_exit_reason);
9379651SAndreas.Sandberg@ARM.com}
9389651SAndreas.Sandberg@ARM.com
9399651SAndreas.Sandberg@ARM.comTick
9409651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitException()
9419651SAndreas.Sandberg@ARM.com{
9429689Sandreas@sandberg.pp.se    dump();
9439651SAndreas.Sandberg@ARM.com    panic("KVM: Got exception when starting vCPU "
9449651SAndreas.Sandberg@ARM.com          "(exception: %u, error_code: %u)\n",
9459651SAndreas.Sandberg@ARM.com          _kvmRun->ex.exception, _kvmRun->ex.error_code);
9469651SAndreas.Sandberg@ARM.com}
9479651SAndreas.Sandberg@ARM.com
9489651SAndreas.Sandberg@ARM.comTick
9499651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitFailEntry()
9509651SAndreas.Sandberg@ARM.com{
9519689Sandreas@sandberg.pp.se    dump();
9529651SAndreas.Sandberg@ARM.com    panic("KVM: Failed to enter virtualized mode (hw reason: 0x%llx)\n",
9539651SAndreas.Sandberg@ARM.com          _kvmRun->fail_entry.hardware_entry_failure_reason);
9549651SAndreas.Sandberg@ARM.com}
9559651SAndreas.Sandberg@ARM.com
9569651SAndreas.Sandberg@ARM.comTick
9579651SAndreas.Sandberg@ARM.comBaseKvmCPU::doMMIOAccess(Addr paddr, void *data, int size, bool write)
9589651SAndreas.Sandberg@ARM.com{
9599760Sandreas@sandberg.pp.se    ThreadContext *tc(thread->getTC());
9609760Sandreas@sandberg.pp.se    syncThreadContext();
9619760Sandreas@sandberg.pp.se
9629682Sandreas@sandberg.pp.se    mmio_req.setPhys(paddr, size, Request::UNCACHEABLE, dataMasterId());
9639760Sandreas@sandberg.pp.se    // Some architectures do need to massage physical addresses a bit
9649760Sandreas@sandberg.pp.se    // before they are inserted into the memory system. This enables
9659760Sandreas@sandberg.pp.se    // APIC accesses on x86 and m5ops where supported through a MMIO
9669760Sandreas@sandberg.pp.se    // interface.
9679760Sandreas@sandberg.pp.se    BaseTLB::Mode tlb_mode(write ? BaseTLB::Write : BaseTLB::Read);
9689760Sandreas@sandberg.pp.se    Fault fault(tc->getDTBPtr()->finalizePhysical(&mmio_req, tc, tlb_mode));
9699760Sandreas@sandberg.pp.se    if (fault != NoFault)
9709760Sandreas@sandberg.pp.se        warn("Finalization of MMIO address failed: %s\n", fault->name());
9719760Sandreas@sandberg.pp.se
9729651SAndreas.Sandberg@ARM.com
9739651SAndreas.Sandberg@ARM.com    const MemCmd cmd(write ? MemCmd::WriteReq : MemCmd::ReadReq);
9749651SAndreas.Sandberg@ARM.com    Packet pkt(&mmio_req, cmd);
9759651SAndreas.Sandberg@ARM.com    pkt.dataStatic(data);
9769760Sandreas@sandberg.pp.se
9779760Sandreas@sandberg.pp.se    if (mmio_req.isMmappedIpr()) {
9789882Sandreas@sandberg.pp.se        const Cycles ipr_delay(write ?
9799882Sandreas@sandberg.pp.se                             TheISA::handleIprWrite(tc, &pkt) :
9809882Sandreas@sandberg.pp.se                             TheISA::handleIprRead(tc, &pkt));
9819925Sandreas@sandberg.pp.se        return clockPeriod() * ipr_delay;
9829760Sandreas@sandberg.pp.se    } else {
9839760Sandreas@sandberg.pp.se        return dataPort.sendAtomic(&pkt);
9849760Sandreas@sandberg.pp.se    }
9859651SAndreas.Sandberg@ARM.com}
9869651SAndreas.Sandberg@ARM.com
9879753Sandreas@sandberg.pp.sevoid
9889753Sandreas@sandberg.pp.seBaseKvmCPU::setSignalMask(const sigset_t *mask)
9899753Sandreas@sandberg.pp.se{
9909753Sandreas@sandberg.pp.se    std::unique_ptr<struct kvm_signal_mask> kvm_mask;
9919753Sandreas@sandberg.pp.se
9929753Sandreas@sandberg.pp.se    if (mask) {
9939753Sandreas@sandberg.pp.se        kvm_mask.reset((struct kvm_signal_mask *)operator new(
9949753Sandreas@sandberg.pp.se                           sizeof(struct kvm_signal_mask) + sizeof(*mask)));
9959753Sandreas@sandberg.pp.se        // The kernel and the user-space headers have different ideas
9969753Sandreas@sandberg.pp.se        // about the size of sigset_t. This seems like a massive hack,
9979753Sandreas@sandberg.pp.se        // but is actually what qemu does.
9989753Sandreas@sandberg.pp.se        assert(sizeof(*mask) >= 8);
9999753Sandreas@sandberg.pp.se        kvm_mask->len = 8;
10009753Sandreas@sandberg.pp.se        memcpy(kvm_mask->sigset, mask, kvm_mask->len);
10019753Sandreas@sandberg.pp.se    }
10029753Sandreas@sandberg.pp.se
10039753Sandreas@sandberg.pp.se    if (ioctl(KVM_SET_SIGNAL_MASK, (void *)kvm_mask.get()) == -1)
10049753Sandreas@sandberg.pp.se        panic("KVM: Failed to set vCPU signal mask (errno: %i)\n",
10059753Sandreas@sandberg.pp.se              errno);
10069753Sandreas@sandberg.pp.se}
10079753Sandreas@sandberg.pp.se
10089651SAndreas.Sandberg@ARM.comint
10099651SAndreas.Sandberg@ARM.comBaseKvmCPU::ioctl(int request, long p1) const
10109651SAndreas.Sandberg@ARM.com{
10119651SAndreas.Sandberg@ARM.com    if (vcpuFD == -1)
10129651SAndreas.Sandberg@ARM.com        panic("KVM: CPU ioctl called before initialization\n");
10139651SAndreas.Sandberg@ARM.com
10149651SAndreas.Sandberg@ARM.com    return ::ioctl(vcpuFD, request, p1);
10159651SAndreas.Sandberg@ARM.com}
10169651SAndreas.Sandberg@ARM.com
10179651SAndreas.Sandberg@ARM.comTick
10189651SAndreas.Sandberg@ARM.comBaseKvmCPU::flushCoalescedMMIO()
10199651SAndreas.Sandberg@ARM.com{
10209651SAndreas.Sandberg@ARM.com    if (!mmioRing)
10219651SAndreas.Sandberg@ARM.com        return 0;
10229651SAndreas.Sandberg@ARM.com
10239651SAndreas.Sandberg@ARM.com    DPRINTF(KvmIO, "KVM: Flushing the coalesced MMIO ring buffer\n");
10249651SAndreas.Sandberg@ARM.com
10259651SAndreas.Sandberg@ARM.com    // TODO: We might need to do synchronization when we start to
10269651SAndreas.Sandberg@ARM.com    // support multiple CPUs
10279651SAndreas.Sandberg@ARM.com    Tick ticks(0);
10289651SAndreas.Sandberg@ARM.com    while (mmioRing->first != mmioRing->last) {
10299651SAndreas.Sandberg@ARM.com        struct kvm_coalesced_mmio &ent(
10309651SAndreas.Sandberg@ARM.com            mmioRing->coalesced_mmio[mmioRing->first]);
10319651SAndreas.Sandberg@ARM.com
10329651SAndreas.Sandberg@ARM.com        DPRINTF(KvmIO, "KVM: Handling coalesced MMIO (addr: 0x%x, len: %u)\n",
10339651SAndreas.Sandberg@ARM.com                ent.phys_addr, ent.len);
10349651SAndreas.Sandberg@ARM.com
10359651SAndreas.Sandberg@ARM.com        ++numCoalescedMMIO;
10369651SAndreas.Sandberg@ARM.com        ticks += doMMIOAccess(ent.phys_addr, ent.data, ent.len, true);
10379651SAndreas.Sandberg@ARM.com
10389651SAndreas.Sandberg@ARM.com        mmioRing->first = (mmioRing->first + 1) % KVM_COALESCED_MMIO_MAX;
10399651SAndreas.Sandberg@ARM.com    }
10409651SAndreas.Sandberg@ARM.com
10419651SAndreas.Sandberg@ARM.com    return ticks;
10429651SAndreas.Sandberg@ARM.com}
10439651SAndreas.Sandberg@ARM.com
10449892Sandreas@sandberg.pp.se/**
10459892Sandreas@sandberg.pp.se * Cycle timer overflow when running in KVM. Forces the KVM syscall to
10469892Sandreas@sandberg.pp.se * exit with EINTR and allows us to run the event queue.
10479892Sandreas@sandberg.pp.se */
10489892Sandreas@sandberg.pp.sestatic void
10499892Sandreas@sandberg.pp.seonTimerOverflow(int signo, siginfo_t *si, void *data)
10509892Sandreas@sandberg.pp.se{
10519892Sandreas@sandberg.pp.se    timerOverflowed = true;
10529892Sandreas@sandberg.pp.se}
10539892Sandreas@sandberg.pp.se
10549892Sandreas@sandberg.pp.se/**
10559892Sandreas@sandberg.pp.se * Instruction counter overflow when running in KVM. Forces the KVM
10569892Sandreas@sandberg.pp.se * syscall to exit with EINTR and allows us to handle instruction
10579892Sandreas@sandberg.pp.se * count events.
10589892Sandreas@sandberg.pp.se */
10599892Sandreas@sandberg.pp.sestatic void
10609892Sandreas@sandberg.pp.seonInstEvent(int signo, siginfo_t *si, void *data)
10619892Sandreas@sandberg.pp.se{
10629892Sandreas@sandberg.pp.se}
10639892Sandreas@sandberg.pp.se
10649651SAndreas.Sandberg@ARM.comvoid
10659651SAndreas.Sandberg@ARM.comBaseKvmCPU::setupSignalHandler()
10669651SAndreas.Sandberg@ARM.com{
10679651SAndreas.Sandberg@ARM.com    struct sigaction sa;
10689651SAndreas.Sandberg@ARM.com
10699651SAndreas.Sandberg@ARM.com    memset(&sa, 0, sizeof(sa));
10709651SAndreas.Sandberg@ARM.com    sa.sa_sigaction = onTimerOverflow;
10719651SAndreas.Sandberg@ARM.com    sa.sa_flags = SA_SIGINFO | SA_RESTART;
10729651SAndreas.Sandberg@ARM.com    if (sigaction(KVM_TIMER_SIGNAL, &sa, NULL) == -1)
10739892Sandreas@sandberg.pp.se        panic("KVM: Failed to setup vCPU timer signal handler\n");
10749892Sandreas@sandberg.pp.se
10759892Sandreas@sandberg.pp.se    memset(&sa, 0, sizeof(sa));
10769892Sandreas@sandberg.pp.se    sa.sa_sigaction = onInstEvent;
10779892Sandreas@sandberg.pp.se    sa.sa_flags = SA_SIGINFO | SA_RESTART;
10789892Sandreas@sandberg.pp.se    if (sigaction(KVM_INST_SIGNAL, &sa, NULL) == -1)
10799892Sandreas@sandberg.pp.se        panic("KVM: Failed to setup vCPU instruction signal handler\n");
10809753Sandreas@sandberg.pp.se
10819753Sandreas@sandberg.pp.se    sigset_t sigset;
10829753Sandreas@sandberg.pp.se    if (sigprocmask(SIG_BLOCK, NULL, &sigset) == -1)
10839753Sandreas@sandberg.pp.se        panic("KVM: Failed get signal mask\n");
10849753Sandreas@sandberg.pp.se
10859753Sandreas@sandberg.pp.se    // Request KVM to setup the same signal mask as we're currently
10869753Sandreas@sandberg.pp.se    // running with. We'll sometimes need to mask the KVM_TIMER_SIGNAL
10879753Sandreas@sandberg.pp.se    // to cause immediate exits from KVM after servicing IO
10889753Sandreas@sandberg.pp.se    // requests. See kvmRun().
10899753Sandreas@sandberg.pp.se    setSignalMask(&sigset);
10909753Sandreas@sandberg.pp.se
10919892Sandreas@sandberg.pp.se    // Mask our control signals so they aren't delivered unless we're
10929753Sandreas@sandberg.pp.se    // actually executing inside KVM.
10939753Sandreas@sandberg.pp.se    sigaddset(&sigset, KVM_TIMER_SIGNAL);
10949892Sandreas@sandberg.pp.se    sigaddset(&sigset, KVM_INST_SIGNAL);
10959753Sandreas@sandberg.pp.se    if (sigprocmask(SIG_SETMASK, &sigset, NULL) == -1)
10969892Sandreas@sandberg.pp.se        panic("KVM: Failed mask the KVM control signals\n");
10979753Sandreas@sandberg.pp.se}
10989753Sandreas@sandberg.pp.se
10999753Sandreas@sandberg.pp.sebool
11009753Sandreas@sandberg.pp.seBaseKvmCPU::discardPendingSignal(int signum) const
11019753Sandreas@sandberg.pp.se{
11029753Sandreas@sandberg.pp.se    int discardedSignal;
11039753Sandreas@sandberg.pp.se
11049753Sandreas@sandberg.pp.se    // Setting the timeout to zero causes sigtimedwait to return
11059753Sandreas@sandberg.pp.se    // immediately.
11069753Sandreas@sandberg.pp.se    struct timespec timeout;
11079753Sandreas@sandberg.pp.se    timeout.tv_sec = 0;
11089753Sandreas@sandberg.pp.se    timeout.tv_nsec = 0;
11099753Sandreas@sandberg.pp.se
11109753Sandreas@sandberg.pp.se    sigset_t sigset;
11119753Sandreas@sandberg.pp.se    sigemptyset(&sigset);
11129753Sandreas@sandberg.pp.se    sigaddset(&sigset, signum);
11139753Sandreas@sandberg.pp.se
11149753Sandreas@sandberg.pp.se    do {
11159753Sandreas@sandberg.pp.se        discardedSignal = sigtimedwait(&sigset, NULL, &timeout);
11169753Sandreas@sandberg.pp.se    } while (discardedSignal == -1 && errno == EINTR);
11179753Sandreas@sandberg.pp.se
11189753Sandreas@sandberg.pp.se    if (discardedSignal == signum)
11199753Sandreas@sandberg.pp.se        return true;
11209753Sandreas@sandberg.pp.se    else if (discardedSignal == -1 && errno == EAGAIN)
11219753Sandreas@sandberg.pp.se        return false;
11229753Sandreas@sandberg.pp.se    else
11239753Sandreas@sandberg.pp.se        panic("Unexpected return value from sigtimedwait: %i (errno: %i)\n",
11249753Sandreas@sandberg.pp.se              discardedSignal, errno);
11259651SAndreas.Sandberg@ARM.com}
11269651SAndreas.Sandberg@ARM.com
11279651SAndreas.Sandberg@ARM.comvoid
11289651SAndreas.Sandberg@ARM.comBaseKvmCPU::setupCounters()
11299651SAndreas.Sandberg@ARM.com{
11309651SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "Attaching cycle counter...\n");
11319651SAndreas.Sandberg@ARM.com    PerfKvmCounterConfig cfgCycles(PERF_TYPE_HARDWARE,
11329651SAndreas.Sandberg@ARM.com                                PERF_COUNT_HW_CPU_CYCLES);
11339651SAndreas.Sandberg@ARM.com    cfgCycles.disabled(true)
11349651SAndreas.Sandberg@ARM.com        .pinned(true);
11359655SAndreas.Sandberg@ARM.com
11369986Sandreas@sandberg.pp.se    // Try to exclude the host. We set both exclude_hv and
11379986Sandreas@sandberg.pp.se    // exclude_host since different architectures use slightly
11389986Sandreas@sandberg.pp.se    // different APIs in the kernel.
11399986Sandreas@sandberg.pp.se    cfgCycles.exclude_hv(true)
11409986Sandreas@sandberg.pp.se        .exclude_host(true);
11419986Sandreas@sandberg.pp.se
11429655SAndreas.Sandberg@ARM.com    if (perfControlledByTimer) {
11439655SAndreas.Sandberg@ARM.com        // We need to configure the cycles counter to send overflows
11449655SAndreas.Sandberg@ARM.com        // since we are going to use it to trigger timer signals that
11459655SAndreas.Sandberg@ARM.com        // trap back into m5 from KVM. In practice, this means that we
11469655SAndreas.Sandberg@ARM.com        // need to set some non-zero sample period that gets
11479655SAndreas.Sandberg@ARM.com        // overridden when the timer is armed.
11489655SAndreas.Sandberg@ARM.com        cfgCycles.wakeupEvents(1)
11499655SAndreas.Sandberg@ARM.com            .samplePeriod(42);
11509655SAndreas.Sandberg@ARM.com    }
11519655SAndreas.Sandberg@ARM.com
11529651SAndreas.Sandberg@ARM.com    hwCycles.attach(cfgCycles,
11539651SAndreas.Sandberg@ARM.com                    0); // TID (0 => currentThread)
11549651SAndreas.Sandberg@ARM.com
11559892Sandreas@sandberg.pp.se    setupInstCounter();
11569651SAndreas.Sandberg@ARM.com}
11579753Sandreas@sandberg.pp.se
11589753Sandreas@sandberg.pp.sebool
11599753Sandreas@sandberg.pp.seBaseKvmCPU::tryDrain()
11609753Sandreas@sandberg.pp.se{
11619753Sandreas@sandberg.pp.se    if (!drainManager)
11629753Sandreas@sandberg.pp.se        return false;
11639753Sandreas@sandberg.pp.se
11649753Sandreas@sandberg.pp.se    if (!archIsDrained()) {
11659753Sandreas@sandberg.pp.se        DPRINTF(Drain, "tryDrain: Architecture code is not ready.\n");
11669753Sandreas@sandberg.pp.se        return false;
11679753Sandreas@sandberg.pp.se    }
11689753Sandreas@sandberg.pp.se
11699753Sandreas@sandberg.pp.se    if (_status == Idle || _status == Running) {
11709753Sandreas@sandberg.pp.se        DPRINTF(Drain,
11719753Sandreas@sandberg.pp.se                "tryDrain: CPU transitioned into the Idle state, drain done\n");
11729753Sandreas@sandberg.pp.se        drainManager->signalDrainDone();
11739753Sandreas@sandberg.pp.se        drainManager = NULL;
11749753Sandreas@sandberg.pp.se        return true;
11759753Sandreas@sandberg.pp.se    } else {
11769753Sandreas@sandberg.pp.se        DPRINTF(Drain, "tryDrain: CPU not ready.\n");
11779753Sandreas@sandberg.pp.se        return false;
11789753Sandreas@sandberg.pp.se    }
11799753Sandreas@sandberg.pp.se}
11809753Sandreas@sandberg.pp.se
11819753Sandreas@sandberg.pp.sevoid
11829753Sandreas@sandberg.pp.seBaseKvmCPU::ioctlRun()
11839753Sandreas@sandberg.pp.se{
11849753Sandreas@sandberg.pp.se    if (ioctl(KVM_RUN) == -1) {
11859753Sandreas@sandberg.pp.se        if (errno != EINTR)
11869753Sandreas@sandberg.pp.se            panic("KVM: Failed to start virtual CPU (errno: %i)\n",
11879753Sandreas@sandberg.pp.se                  errno);
11889753Sandreas@sandberg.pp.se    }
11899753Sandreas@sandberg.pp.se}
11909892Sandreas@sandberg.pp.se
11919892Sandreas@sandberg.pp.sevoid
11929892Sandreas@sandberg.pp.seBaseKvmCPU::setupInstStop()
11939892Sandreas@sandberg.pp.se{
11949892Sandreas@sandberg.pp.se    if (comInstEventQueue[0]->empty()) {
11959892Sandreas@sandberg.pp.se        setupInstCounter(0);
11969892Sandreas@sandberg.pp.se    } else {
11979892Sandreas@sandberg.pp.se        const uint64_t next(comInstEventQueue[0]->nextTick());
11989892Sandreas@sandberg.pp.se
11999892Sandreas@sandberg.pp.se        assert(next > ctrInsts);
12009892Sandreas@sandberg.pp.se        setupInstCounter(next - ctrInsts);
12019892Sandreas@sandberg.pp.se    }
12029892Sandreas@sandberg.pp.se}
12039892Sandreas@sandberg.pp.se
12049892Sandreas@sandberg.pp.sevoid
12059892Sandreas@sandberg.pp.seBaseKvmCPU::setupInstCounter(uint64_t period)
12069892Sandreas@sandberg.pp.se{
12079892Sandreas@sandberg.pp.se    // No need to do anything if we aren't attaching for the first
12089892Sandreas@sandberg.pp.se    // time or the period isn't changing.
12099892Sandreas@sandberg.pp.se    if (period == activeInstPeriod && hwInstructions.attached())
12109892Sandreas@sandberg.pp.se        return;
12119892Sandreas@sandberg.pp.se
12129892Sandreas@sandberg.pp.se    PerfKvmCounterConfig cfgInstructions(PERF_TYPE_HARDWARE,
12139892Sandreas@sandberg.pp.se                                         PERF_COUNT_HW_INSTRUCTIONS);
12149892Sandreas@sandberg.pp.se
12159986Sandreas@sandberg.pp.se    // Try to exclude the host. We set both exclude_hv and
12169986Sandreas@sandberg.pp.se    // exclude_host since different architectures use slightly
12179986Sandreas@sandberg.pp.se    // different APIs in the kernel.
12189986Sandreas@sandberg.pp.se    cfgInstructions.exclude_hv(true)
12199986Sandreas@sandberg.pp.se        .exclude_host(true);
12209986Sandreas@sandberg.pp.se
12219892Sandreas@sandberg.pp.se    if (period) {
12229892Sandreas@sandberg.pp.se        // Setup a sampling counter if that has been requested.
12239892Sandreas@sandberg.pp.se        cfgInstructions.wakeupEvents(1)
12249892Sandreas@sandberg.pp.se            .samplePeriod(period);
12259892Sandreas@sandberg.pp.se    }
12269892Sandreas@sandberg.pp.se
12279892Sandreas@sandberg.pp.se    // We need to detach and re-attach the counter to reliably change
12289892Sandreas@sandberg.pp.se    // sampling settings. See PerfKvmCounter::period() for details.
12299892Sandreas@sandberg.pp.se    if (hwInstructions.attached())
12309892Sandreas@sandberg.pp.se        hwInstructions.detach();
12319892Sandreas@sandberg.pp.se    assert(hwCycles.attached());
12329892Sandreas@sandberg.pp.se    hwInstructions.attach(cfgInstructions,
12339892Sandreas@sandberg.pp.se                          0, // TID (0 => currentThread)
12349892Sandreas@sandberg.pp.se                          hwCycles);
12359892Sandreas@sandberg.pp.se
12369892Sandreas@sandberg.pp.se    if (period)
12379892Sandreas@sandberg.pp.se        hwInstructions.enableSignals(KVM_INST_SIGNAL);
12389892Sandreas@sandberg.pp.se
12399892Sandreas@sandberg.pp.se    activeInstPeriod = period;
12409892Sandreas@sandberg.pp.se}
1241