base.cc revision 10553
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.comBaseKvmCPU::BaseKvmCPU(BaseKvmCPUParams *params)
679651SAndreas.Sandberg@ARM.com    : BaseCPU(params),
689651SAndreas.Sandberg@ARM.com      vm(*params->kvmVM),
699651SAndreas.Sandberg@ARM.com      _status(Idle),
709651SAndreas.Sandberg@ARM.com      dataPort(name() + ".dcache_port", this),
719651SAndreas.Sandberg@ARM.com      instPort(name() + ".icache_port", this),
729652SAndreas.Sandberg@ARM.com      threadContextDirty(true),
739652SAndreas.Sandberg@ARM.com      kvmStateDirty(false),
749651SAndreas.Sandberg@ARM.com      vcpuID(vm.allocVCPUID()), vcpuFD(-1), vcpuMMapSize(0),
759651SAndreas.Sandberg@ARM.com      _kvmRun(NULL), mmioRing(NULL),
769651SAndreas.Sandberg@ARM.com      pageSize(sysconf(_SC_PAGE_SIZE)),
779651SAndreas.Sandberg@ARM.com      tickEvent(*this),
789892Sandreas@sandberg.pp.se      activeInstPeriod(0),
799655SAndreas.Sandberg@ARM.com      perfControlledByTimer(params->usePerfOverflow),
809752Sandreas@sandberg.pp.se      hostFactor(params->hostFactor),
819753Sandreas@sandberg.pp.se      drainManager(NULL),
829752Sandreas@sandberg.pp.se      ctrInsts(0)
839651SAndreas.Sandberg@ARM.com{
849651SAndreas.Sandberg@ARM.com    if (pageSize == -1)
859651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to determine host page size (%i)\n",
869651SAndreas.Sandberg@ARM.com              errno);
879651SAndreas.Sandberg@ARM.com
8810553Salexandru.dutu@amd.com    if (FullSystem)
8910553Salexandru.dutu@amd.com        thread = new SimpleThread(this, 0, params->system, params->itb, params->dtb,
9010553Salexandru.dutu@amd.com                                  params->isa[0]);
9110553Salexandru.dutu@amd.com    else
9210553Salexandru.dutu@amd.com        thread = new SimpleThread(this, /* thread_num */ 0, params->system,
9310553Salexandru.dutu@amd.com                                  params->workload[0], params->itb,
9410553Salexandru.dutu@amd.com                                  params->dtb, params->isa[0]);
9510553Salexandru.dutu@amd.com
969651SAndreas.Sandberg@ARM.com    thread->setStatus(ThreadContext::Halted);
979651SAndreas.Sandberg@ARM.com    tc = thread->getTC();
989651SAndreas.Sandberg@ARM.com    threadContexts.push_back(tc);
999651SAndreas.Sandberg@ARM.com}
1009651SAndreas.Sandberg@ARM.com
1019651SAndreas.Sandberg@ARM.comBaseKvmCPU::~BaseKvmCPU()
1029651SAndreas.Sandberg@ARM.com{
1039651SAndreas.Sandberg@ARM.com    if (_kvmRun)
1049651SAndreas.Sandberg@ARM.com        munmap(_kvmRun, vcpuMMapSize);
1059651SAndreas.Sandberg@ARM.com    close(vcpuFD);
1069651SAndreas.Sandberg@ARM.com}
1079651SAndreas.Sandberg@ARM.com
1089651SAndreas.Sandberg@ARM.comvoid
1099651SAndreas.Sandberg@ARM.comBaseKvmCPU::init()
1109651SAndreas.Sandberg@ARM.com{
1119651SAndreas.Sandberg@ARM.com    BaseCPU::init();
1129651SAndreas.Sandberg@ARM.com
1139651SAndreas.Sandberg@ARM.com    if (numThreads != 1)
1149651SAndreas.Sandberg@ARM.com        fatal("KVM: Multithreading not supported");
1159651SAndreas.Sandberg@ARM.com
1169651SAndreas.Sandberg@ARM.com    tc->initMemProxies(tc);
1179651SAndreas.Sandberg@ARM.com
1189651SAndreas.Sandberg@ARM.com    // initialize CPU, including PC
1199651SAndreas.Sandberg@ARM.com    if (FullSystem && !switchedOut())
1209651SAndreas.Sandberg@ARM.com        TheISA::initCPU(tc, tc->contextId());
1219651SAndreas.Sandberg@ARM.com
1229651SAndreas.Sandberg@ARM.com    mmio_req.setThreadContext(tc->contextId(), 0);
1239651SAndreas.Sandberg@ARM.com}
1249651SAndreas.Sandberg@ARM.com
1259651SAndreas.Sandberg@ARM.comvoid
1269651SAndreas.Sandberg@ARM.comBaseKvmCPU::startup()
1279651SAndreas.Sandberg@ARM.com{
1289690Sandreas@sandberg.pp.se    const BaseKvmCPUParams * const p(
1299690Sandreas@sandberg.pp.se        dynamic_cast<const BaseKvmCPUParams *>(params()));
1309690Sandreas@sandberg.pp.se
1319651SAndreas.Sandberg@ARM.com    Kvm &kvm(vm.kvm);
1329651SAndreas.Sandberg@ARM.com
1339651SAndreas.Sandberg@ARM.com    BaseCPU::startup();
1349651SAndreas.Sandberg@ARM.com
1359651SAndreas.Sandberg@ARM.com    assert(vcpuFD == -1);
1369651SAndreas.Sandberg@ARM.com
1379651SAndreas.Sandberg@ARM.com    // Tell the VM that a CPU is about to start.
1389651SAndreas.Sandberg@ARM.com    vm.cpuStartup();
1399651SAndreas.Sandberg@ARM.com
1409651SAndreas.Sandberg@ARM.com    // We can't initialize KVM CPUs in BaseKvmCPU::init() since we are
1419651SAndreas.Sandberg@ARM.com    // not guaranteed that the parent KVM VM has initialized at that
1429651SAndreas.Sandberg@ARM.com    // point. Initialize virtual CPUs here instead.
1439651SAndreas.Sandberg@ARM.com    vcpuFD = vm.createVCPU(vcpuID);
1449651SAndreas.Sandberg@ARM.com
1459651SAndreas.Sandberg@ARM.com    // Map the KVM run structure */
1469651SAndreas.Sandberg@ARM.com    vcpuMMapSize = kvm.getVCPUMMapSize();
1479651SAndreas.Sandberg@ARM.com    _kvmRun = (struct kvm_run *)mmap(0, vcpuMMapSize,
1489651SAndreas.Sandberg@ARM.com                                     PROT_READ | PROT_WRITE, MAP_SHARED,
1499651SAndreas.Sandberg@ARM.com                                     vcpuFD, 0);
1509651SAndreas.Sandberg@ARM.com    if (_kvmRun == MAP_FAILED)
1519651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to map run data structure\n");
1529651SAndreas.Sandberg@ARM.com
1539651SAndreas.Sandberg@ARM.com    // Setup a pointer to the MMIO ring buffer if coalesced MMIO is
1549651SAndreas.Sandberg@ARM.com    // available. The offset into the KVM's communication page is
1559651SAndreas.Sandberg@ARM.com    // provided by the coalesced MMIO capability.
1569651SAndreas.Sandberg@ARM.com    int mmioOffset(kvm.capCoalescedMMIO());
1579690Sandreas@sandberg.pp.se    if (!p->useCoalescedMMIO) {
1589690Sandreas@sandberg.pp.se        inform("KVM: Coalesced MMIO disabled by config.\n");
1599690Sandreas@sandberg.pp.se    } else if (mmioOffset) {
1609651SAndreas.Sandberg@ARM.com        inform("KVM: Coalesced IO available\n");
1619651SAndreas.Sandberg@ARM.com        mmioRing = (struct kvm_coalesced_mmio_ring *)(
1629651SAndreas.Sandberg@ARM.com            (char *)_kvmRun + (mmioOffset * pageSize));
1639651SAndreas.Sandberg@ARM.com    } else {
1649651SAndreas.Sandberg@ARM.com        inform("KVM: Coalesced not supported by host OS\n");
1659651SAndreas.Sandberg@ARM.com    }
1669732Sandreas@sandberg.pp.se
1679732Sandreas@sandberg.pp.se    thread->startup();
16810073Sandreas@sandberg.pp.se
16910073Sandreas@sandberg.pp.se    Event *startupEvent(
17010073Sandreas@sandberg.pp.se        new EventWrapper<BaseKvmCPU,
17110073Sandreas@sandberg.pp.se                         &BaseKvmCPU::startupThread>(this, true));
17210073Sandreas@sandberg.pp.se    schedule(startupEvent, curTick());
17310073Sandreas@sandberg.pp.se}
17410073Sandreas@sandberg.pp.se
17510073Sandreas@sandberg.pp.sevoid
17610073Sandreas@sandberg.pp.seBaseKvmCPU::startupThread()
17710073Sandreas@sandberg.pp.se{
17810073Sandreas@sandberg.pp.se    // Do thread-specific initialization. We need to setup signal
17910073Sandreas@sandberg.pp.se    // delivery for counters and timers from within the thread that
18010073Sandreas@sandberg.pp.se    // will execute the event queue to ensure that signals are
18110073Sandreas@sandberg.pp.se    // delivered to the right threads.
18210073Sandreas@sandberg.pp.se    const BaseKvmCPUParams * const p(
18310073Sandreas@sandberg.pp.se        dynamic_cast<const BaseKvmCPUParams *>(params()));
18410073Sandreas@sandberg.pp.se
18510114Sandreas@sandberg.pp.se    vcpuThread = pthread_self();
18610114Sandreas@sandberg.pp.se
18710098Sandreas@sandberg.pp.se    // Setup signal handlers. This has to be done after the vCPU is
18810098Sandreas@sandberg.pp.se    // created since it manipulates the vCPU signal mask.
18910098Sandreas@sandberg.pp.se    setupSignalHandler();
19010098Sandreas@sandberg.pp.se
19110073Sandreas@sandberg.pp.se    setupCounters();
19210073Sandreas@sandberg.pp.se
19310073Sandreas@sandberg.pp.se    if (p->usePerfOverflow)
19410073Sandreas@sandberg.pp.se        runTimer.reset(new PerfKvmTimer(hwCycles,
19510114Sandreas@sandberg.pp.se                                        KVM_KICK_SIGNAL,
19610073Sandreas@sandberg.pp.se                                        p->hostFactor,
19710073Sandreas@sandberg.pp.se                                        p->hostFreq));
19810073Sandreas@sandberg.pp.se    else
19910114Sandreas@sandberg.pp.se        runTimer.reset(new PosixKvmTimer(KVM_KICK_SIGNAL, CLOCK_MONOTONIC,
20010073Sandreas@sandberg.pp.se                                         p->hostFactor,
20110073Sandreas@sandberg.pp.se                                         p->hostFreq));
20210073Sandreas@sandberg.pp.se
2039651SAndreas.Sandberg@ARM.com}
2049651SAndreas.Sandberg@ARM.com
2059651SAndreas.Sandberg@ARM.comvoid
2069651SAndreas.Sandberg@ARM.comBaseKvmCPU::regStats()
2079651SAndreas.Sandberg@ARM.com{
2089651SAndreas.Sandberg@ARM.com    using namespace Stats;
2099651SAndreas.Sandberg@ARM.com
2109651SAndreas.Sandberg@ARM.com    BaseCPU::regStats();
2119651SAndreas.Sandberg@ARM.com
2129684Sandreas@sandberg.pp.se    numInsts
2139684Sandreas@sandberg.pp.se        .name(name() + ".committedInsts")
2149684Sandreas@sandberg.pp.se        .desc("Number of instructions committed")
2159684Sandreas@sandberg.pp.se        ;
2169684Sandreas@sandberg.pp.se
2179651SAndreas.Sandberg@ARM.com    numVMExits
2189651SAndreas.Sandberg@ARM.com        .name(name() + ".numVMExits")
2199651SAndreas.Sandberg@ARM.com        .desc("total number of KVM exits")
2209651SAndreas.Sandberg@ARM.com        ;
2219651SAndreas.Sandberg@ARM.com
2229755Sandreas@sandberg.pp.se    numVMHalfEntries
2239755Sandreas@sandberg.pp.se        .name(name() + ".numVMHalfEntries")
2249755Sandreas@sandberg.pp.se        .desc("number of KVM entries to finalize pending operations")
2259755Sandreas@sandberg.pp.se        ;
2269755Sandreas@sandberg.pp.se
2279755Sandreas@sandberg.pp.se    numExitSignal
2289755Sandreas@sandberg.pp.se        .name(name() + ".numExitSignal")
2299755Sandreas@sandberg.pp.se        .desc("exits due to signal delivery")
2309755Sandreas@sandberg.pp.se        ;
2319755Sandreas@sandberg.pp.se
2329651SAndreas.Sandberg@ARM.com    numMMIO
2339651SAndreas.Sandberg@ARM.com        .name(name() + ".numMMIO")
2349651SAndreas.Sandberg@ARM.com        .desc("number of VM exits due to memory mapped IO")
2359651SAndreas.Sandberg@ARM.com        ;
2369651SAndreas.Sandberg@ARM.com
2379651SAndreas.Sandberg@ARM.com    numCoalescedMMIO
2389651SAndreas.Sandberg@ARM.com        .name(name() + ".numCoalescedMMIO")
2399651SAndreas.Sandberg@ARM.com        .desc("number of coalesced memory mapped IO requests")
2409651SAndreas.Sandberg@ARM.com        ;
2419651SAndreas.Sandberg@ARM.com
2429651SAndreas.Sandberg@ARM.com    numIO
2439651SAndreas.Sandberg@ARM.com        .name(name() + ".numIO")
2449651SAndreas.Sandberg@ARM.com        .desc("number of VM exits due to legacy IO")
2459651SAndreas.Sandberg@ARM.com        ;
2469651SAndreas.Sandberg@ARM.com
2479651SAndreas.Sandberg@ARM.com    numHalt
2489651SAndreas.Sandberg@ARM.com        .name(name() + ".numHalt")
2499651SAndreas.Sandberg@ARM.com        .desc("number of VM exits due to wait for interrupt instructions")
2509651SAndreas.Sandberg@ARM.com        ;
2519651SAndreas.Sandberg@ARM.com
2529651SAndreas.Sandberg@ARM.com    numInterrupts
2539651SAndreas.Sandberg@ARM.com        .name(name() + ".numInterrupts")
2549651SAndreas.Sandberg@ARM.com        .desc("number of interrupts delivered")
2559651SAndreas.Sandberg@ARM.com        ;
2569651SAndreas.Sandberg@ARM.com
2579651SAndreas.Sandberg@ARM.com    numHypercalls
2589651SAndreas.Sandberg@ARM.com        .name(name() + ".numHypercalls")
2599651SAndreas.Sandberg@ARM.com        .desc("number of hypercalls")
2609651SAndreas.Sandberg@ARM.com        ;
2619651SAndreas.Sandberg@ARM.com}
2629651SAndreas.Sandberg@ARM.com
2639651SAndreas.Sandberg@ARM.comvoid
2649651SAndreas.Sandberg@ARM.comBaseKvmCPU::serializeThread(std::ostream &os, ThreadID tid)
2659651SAndreas.Sandberg@ARM.com{
2669683Sandreas@sandberg.pp.se    if (DTRACE(Checkpoint)) {
2679683Sandreas@sandberg.pp.se        DPRINTF(Checkpoint, "KVM: Serializing thread %i:\n", tid);
2689683Sandreas@sandberg.pp.se        dump();
2699683Sandreas@sandberg.pp.se    }
2709683Sandreas@sandberg.pp.se
2719651SAndreas.Sandberg@ARM.com    assert(tid == 0);
2729651SAndreas.Sandberg@ARM.com    assert(_status == Idle);
2739651SAndreas.Sandberg@ARM.com    thread->serialize(os);
2749651SAndreas.Sandberg@ARM.com}
2759651SAndreas.Sandberg@ARM.com
2769651SAndreas.Sandberg@ARM.comvoid
2779651SAndreas.Sandberg@ARM.comBaseKvmCPU::unserializeThread(Checkpoint *cp, const std::string &section,
2789651SAndreas.Sandberg@ARM.com                              ThreadID tid)
2799651SAndreas.Sandberg@ARM.com{
2809683Sandreas@sandberg.pp.se    DPRINTF(Checkpoint, "KVM: Unserialize thread %i:\n", tid);
2819683Sandreas@sandberg.pp.se
2829651SAndreas.Sandberg@ARM.com    assert(tid == 0);
2839651SAndreas.Sandberg@ARM.com    assert(_status == Idle);
2849651SAndreas.Sandberg@ARM.com    thread->unserialize(cp, section);
2859652SAndreas.Sandberg@ARM.com    threadContextDirty = true;
2869651SAndreas.Sandberg@ARM.com}
2879651SAndreas.Sandberg@ARM.com
2889651SAndreas.Sandberg@ARM.comunsigned int
2899651SAndreas.Sandberg@ARM.comBaseKvmCPU::drain(DrainManager *dm)
2909651SAndreas.Sandberg@ARM.com{
2919651SAndreas.Sandberg@ARM.com    if (switchedOut())
2929651SAndreas.Sandberg@ARM.com        return 0;
2939651SAndreas.Sandberg@ARM.com
2949753Sandreas@sandberg.pp.se    DPRINTF(Drain, "BaseKvmCPU::drain\n");
2959753Sandreas@sandberg.pp.se    switch (_status) {
2969753Sandreas@sandberg.pp.se      case Running:
2979753Sandreas@sandberg.pp.se        // The base KVM code is normally ready when it is in the
2989753Sandreas@sandberg.pp.se        // Running state, but the architecture specific code might be
2999753Sandreas@sandberg.pp.se        // of a different opinion. This may happen when the CPU been
3009753Sandreas@sandberg.pp.se        // notified of an event that hasn't been accepted by the vCPU
3019753Sandreas@sandberg.pp.se        // yet.
3029753Sandreas@sandberg.pp.se        if (!archIsDrained()) {
3039753Sandreas@sandberg.pp.se            drainManager = dm;
3049753Sandreas@sandberg.pp.se            return 1;
3059753Sandreas@sandberg.pp.se        }
3069651SAndreas.Sandberg@ARM.com
3079753Sandreas@sandberg.pp.se        // The state of the CPU is consistent, so we don't need to do
3089753Sandreas@sandberg.pp.se        // anything special to drain it. We simply de-schedule the
3099753Sandreas@sandberg.pp.se        // tick event and enter the Idle state to prevent nasty things
3109753Sandreas@sandberg.pp.se        // like MMIOs from happening.
3119753Sandreas@sandberg.pp.se        if (tickEvent.scheduled())
3129753Sandreas@sandberg.pp.se            deschedule(tickEvent);
3139753Sandreas@sandberg.pp.se        _status = Idle;
3149651SAndreas.Sandberg@ARM.com
3159753Sandreas@sandberg.pp.se        /** FALLTHROUGH */
3169753Sandreas@sandberg.pp.se      case Idle:
3179753Sandreas@sandberg.pp.se        // Idle, no need to drain
3189753Sandreas@sandberg.pp.se        assert(!tickEvent.scheduled());
3199753Sandreas@sandberg.pp.se
3209753Sandreas@sandberg.pp.se        // Sync the thread context here since we'll need it when we
3219753Sandreas@sandberg.pp.se        // switch CPUs or checkpoint the CPU.
3229753Sandreas@sandberg.pp.se        syncThreadContext();
3239753Sandreas@sandberg.pp.se
3249753Sandreas@sandberg.pp.se        return 0;
3259753Sandreas@sandberg.pp.se
3269753Sandreas@sandberg.pp.se      case RunningServiceCompletion:
3279753Sandreas@sandberg.pp.se        // The CPU has just requested a service that was handled in
3289753Sandreas@sandberg.pp.se        // the RunningService state, but the results have still not
3299753Sandreas@sandberg.pp.se        // been reported to the CPU. Now, we /could/ probably just
3309753Sandreas@sandberg.pp.se        // update the register state ourselves instead of letting KVM
3319753Sandreas@sandberg.pp.se        // handle it, but that would be tricky. Instead, we enter KVM
3329753Sandreas@sandberg.pp.se        // and let it do its stuff.
3339753Sandreas@sandberg.pp.se        drainManager = dm;
3349753Sandreas@sandberg.pp.se
3359753Sandreas@sandberg.pp.se        DPRINTF(Drain, "KVM CPU is waiting for service completion, "
3369753Sandreas@sandberg.pp.se                "requesting drain.\n");
3379753Sandreas@sandberg.pp.se        return 1;
3389753Sandreas@sandberg.pp.se
3399753Sandreas@sandberg.pp.se      case RunningService:
3409753Sandreas@sandberg.pp.se        // We need to drain since the CPU is waiting for service (e.g., MMIOs)
3419753Sandreas@sandberg.pp.se        drainManager = dm;
3429753Sandreas@sandberg.pp.se
3439753Sandreas@sandberg.pp.se        DPRINTF(Drain, "KVM CPU is waiting for service, requesting drain.\n");
3449753Sandreas@sandberg.pp.se        return 1;
3459753Sandreas@sandberg.pp.se
3469753Sandreas@sandberg.pp.se      default:
3479753Sandreas@sandberg.pp.se        panic("KVM: Unhandled CPU state in drain()\n");
3489753Sandreas@sandberg.pp.se        return 0;
3499753Sandreas@sandberg.pp.se    }
3509651SAndreas.Sandberg@ARM.com}
3519651SAndreas.Sandberg@ARM.com
3529651SAndreas.Sandberg@ARM.comvoid
3539651SAndreas.Sandberg@ARM.comBaseKvmCPU::drainResume()
3549651SAndreas.Sandberg@ARM.com{
3559651SAndreas.Sandberg@ARM.com    assert(!tickEvent.scheduled());
3569651SAndreas.Sandberg@ARM.com
3579651SAndreas.Sandberg@ARM.com    // We might have been switched out. In that case, we don't need to
3589651SAndreas.Sandberg@ARM.com    // do anything.
3599651SAndreas.Sandberg@ARM.com    if (switchedOut())
3609651SAndreas.Sandberg@ARM.com        return;
3619651SAndreas.Sandberg@ARM.com
3629651SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "drainResume\n");
3639651SAndreas.Sandberg@ARM.com    verifyMemoryMode();
3649651SAndreas.Sandberg@ARM.com
3659651SAndreas.Sandberg@ARM.com    // The tick event is de-scheduled as a part of the draining
3669651SAndreas.Sandberg@ARM.com    // process. Re-schedule it if the thread context is active.
3679651SAndreas.Sandberg@ARM.com    if (tc->status() == ThreadContext::Active) {
3689651SAndreas.Sandberg@ARM.com        schedule(tickEvent, nextCycle());
3699651SAndreas.Sandberg@ARM.com        _status = Running;
3709651SAndreas.Sandberg@ARM.com    } else {
3719651SAndreas.Sandberg@ARM.com        _status = Idle;
3729651SAndreas.Sandberg@ARM.com    }
3739651SAndreas.Sandberg@ARM.com}
3749651SAndreas.Sandberg@ARM.com
3759651SAndreas.Sandberg@ARM.comvoid
3769651SAndreas.Sandberg@ARM.comBaseKvmCPU::switchOut()
3779651SAndreas.Sandberg@ARM.com{
3789652SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "switchOut\n");
3799652SAndreas.Sandberg@ARM.com
3809651SAndreas.Sandberg@ARM.com    BaseCPU::switchOut();
3819651SAndreas.Sandberg@ARM.com
3829651SAndreas.Sandberg@ARM.com    // We should have drained prior to executing a switchOut, which
3839651SAndreas.Sandberg@ARM.com    // means that the tick event shouldn't be scheduled and the CPU is
3849651SAndreas.Sandberg@ARM.com    // idle.
3859651SAndreas.Sandberg@ARM.com    assert(!tickEvent.scheduled());
3869651SAndreas.Sandberg@ARM.com    assert(_status == Idle);
3879651SAndreas.Sandberg@ARM.com}
3889651SAndreas.Sandberg@ARM.com
3899651SAndreas.Sandberg@ARM.comvoid
3909651SAndreas.Sandberg@ARM.comBaseKvmCPU::takeOverFrom(BaseCPU *cpu)
3919651SAndreas.Sandberg@ARM.com{
3929651SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "takeOverFrom\n");
3939651SAndreas.Sandberg@ARM.com
3949651SAndreas.Sandberg@ARM.com    BaseCPU::takeOverFrom(cpu);
3959651SAndreas.Sandberg@ARM.com
3969651SAndreas.Sandberg@ARM.com    // We should have drained prior to executing a switchOut, which
3979651SAndreas.Sandberg@ARM.com    // means that the tick event shouldn't be scheduled and the CPU is
3989651SAndreas.Sandberg@ARM.com    // idle.
3999651SAndreas.Sandberg@ARM.com    assert(!tickEvent.scheduled());
4009651SAndreas.Sandberg@ARM.com    assert(_status == Idle);
4019651SAndreas.Sandberg@ARM.com    assert(threadContexts.size() == 1);
4029651SAndreas.Sandberg@ARM.com
4039753Sandreas@sandberg.pp.se    // Force an update of the KVM state here instead of flagging the
4049753Sandreas@sandberg.pp.se    // TC as dirty. This is not ideal from a performance point of
4059753Sandreas@sandberg.pp.se    // view, but it makes debugging easier as it allows meaningful KVM
4069753Sandreas@sandberg.pp.se    // state to be dumped before and after a takeover.
4079753Sandreas@sandberg.pp.se    updateKvmState();
4089753Sandreas@sandberg.pp.se    threadContextDirty = false;
4099651SAndreas.Sandberg@ARM.com}
4109651SAndreas.Sandberg@ARM.com
4119651SAndreas.Sandberg@ARM.comvoid
4129651SAndreas.Sandberg@ARM.comBaseKvmCPU::verifyMemoryMode() const
4139651SAndreas.Sandberg@ARM.com{
4149651SAndreas.Sandberg@ARM.com    if (!(system->isAtomicMode() && system->bypassCaches())) {
4159651SAndreas.Sandberg@ARM.com        fatal("The KVM-based CPUs requires the memory system to be in the "
4169651SAndreas.Sandberg@ARM.com              "'atomic_noncaching' mode.\n");
4179651SAndreas.Sandberg@ARM.com    }
4189651SAndreas.Sandberg@ARM.com}
4199651SAndreas.Sandberg@ARM.com
4209651SAndreas.Sandberg@ARM.comvoid
4219651SAndreas.Sandberg@ARM.comBaseKvmCPU::wakeup()
4229651SAndreas.Sandberg@ARM.com{
4239651SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "wakeup()\n");
42410157Sandreas@sandberg.pp.se    // This method might have been called from another
42510157Sandreas@sandberg.pp.se    // context. Migrate to this SimObject's event queue when
42610157Sandreas@sandberg.pp.se    // delivering the wakeup signal.
42710157Sandreas@sandberg.pp.se    EventQueue::ScopedMigration migrate(eventQueue());
42810157Sandreas@sandberg.pp.se
42910157Sandreas@sandberg.pp.se    // Kick the vCPU to get it to come out of KVM.
43010157Sandreas@sandberg.pp.se    kick();
4319651SAndreas.Sandberg@ARM.com
4329651SAndreas.Sandberg@ARM.com    if (thread->status() != ThreadContext::Suspended)
4339651SAndreas.Sandberg@ARM.com        return;
4349651SAndreas.Sandberg@ARM.com
4359651SAndreas.Sandberg@ARM.com    thread->activate();
4369651SAndreas.Sandberg@ARM.com}
4379651SAndreas.Sandberg@ARM.com
4389651SAndreas.Sandberg@ARM.comvoid
43910407Smitch.hayenga@arm.comBaseKvmCPU::activateContext(ThreadID thread_num)
4409651SAndreas.Sandberg@ARM.com{
44110407Smitch.hayenga@arm.com    DPRINTF(Kvm, "ActivateContext %d\n", thread_num);
4429651SAndreas.Sandberg@ARM.com
4439651SAndreas.Sandberg@ARM.com    assert(thread_num == 0);
4449651SAndreas.Sandberg@ARM.com    assert(thread);
4459651SAndreas.Sandberg@ARM.com
4469651SAndreas.Sandberg@ARM.com    assert(_status == Idle);
4479651SAndreas.Sandberg@ARM.com    assert(!tickEvent.scheduled());
4489651SAndreas.Sandberg@ARM.com
4499754Sandreas@sandberg.pp.se    numCycles += ticksToCycles(thread->lastActivate - thread->lastSuspend);
4509651SAndreas.Sandberg@ARM.com
45110407Smitch.hayenga@arm.com    schedule(tickEvent, clockEdge(Cycles(0)));
4529651SAndreas.Sandberg@ARM.com    _status = Running;
4539651SAndreas.Sandberg@ARM.com}
4549651SAndreas.Sandberg@ARM.com
4559651SAndreas.Sandberg@ARM.com
4569651SAndreas.Sandberg@ARM.comvoid
4579651SAndreas.Sandberg@ARM.comBaseKvmCPU::suspendContext(ThreadID thread_num)
4589651SAndreas.Sandberg@ARM.com{
4599651SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "SuspendContext %d\n", thread_num);
4609651SAndreas.Sandberg@ARM.com
4619651SAndreas.Sandberg@ARM.com    assert(thread_num == 0);
4629651SAndreas.Sandberg@ARM.com    assert(thread);
4639651SAndreas.Sandberg@ARM.com
4649651SAndreas.Sandberg@ARM.com    if (_status == Idle)
4659651SAndreas.Sandberg@ARM.com        return;
4669651SAndreas.Sandberg@ARM.com
46710553Salexandru.dutu@amd.com    assert(_status == Running || _status == RunningServiceCompletion);
4689651SAndreas.Sandberg@ARM.com
4699651SAndreas.Sandberg@ARM.com    // The tick event may no be scheduled if the quest has requested
4709651SAndreas.Sandberg@ARM.com    // the monitor to wait for interrupts. The normal CPU models can
4719651SAndreas.Sandberg@ARM.com    // get their tick events descheduled by quiesce instructions, but
4729651SAndreas.Sandberg@ARM.com    // that can't happen here.
4739651SAndreas.Sandberg@ARM.com    if (tickEvent.scheduled())
4749651SAndreas.Sandberg@ARM.com        deschedule(tickEvent);
4759651SAndreas.Sandberg@ARM.com
4769651SAndreas.Sandberg@ARM.com    _status = Idle;
4779651SAndreas.Sandberg@ARM.com}
4789651SAndreas.Sandberg@ARM.com
4799651SAndreas.Sandberg@ARM.comvoid
4809651SAndreas.Sandberg@ARM.comBaseKvmCPU::deallocateContext(ThreadID thread_num)
4819651SAndreas.Sandberg@ARM.com{
4829651SAndreas.Sandberg@ARM.com    // for now, these are equivalent
4839651SAndreas.Sandberg@ARM.com    suspendContext(thread_num);
4849651SAndreas.Sandberg@ARM.com}
4859651SAndreas.Sandberg@ARM.com
4869651SAndreas.Sandberg@ARM.comvoid
4879651SAndreas.Sandberg@ARM.comBaseKvmCPU::haltContext(ThreadID thread_num)
4889651SAndreas.Sandberg@ARM.com{
4899651SAndreas.Sandberg@ARM.com    // for now, these are equivalent
4909651SAndreas.Sandberg@ARM.com    suspendContext(thread_num);
4919651SAndreas.Sandberg@ARM.com}
4929651SAndreas.Sandberg@ARM.com
4939652SAndreas.Sandberg@ARM.comThreadContext *
4949652SAndreas.Sandberg@ARM.comBaseKvmCPU::getContext(int tn)
4959652SAndreas.Sandberg@ARM.com{
4969652SAndreas.Sandberg@ARM.com    assert(tn == 0);
4979652SAndreas.Sandberg@ARM.com    syncThreadContext();
4989652SAndreas.Sandberg@ARM.com    return tc;
4999652SAndreas.Sandberg@ARM.com}
5009652SAndreas.Sandberg@ARM.com
5019652SAndreas.Sandberg@ARM.com
5029651SAndreas.Sandberg@ARM.comCounter
5039651SAndreas.Sandberg@ARM.comBaseKvmCPU::totalInsts() const
5049651SAndreas.Sandberg@ARM.com{
5059752Sandreas@sandberg.pp.se    return ctrInsts;
5069651SAndreas.Sandberg@ARM.com}
5079651SAndreas.Sandberg@ARM.com
5089651SAndreas.Sandberg@ARM.comCounter
5099651SAndreas.Sandberg@ARM.comBaseKvmCPU::totalOps() const
5109651SAndreas.Sandberg@ARM.com{
5119651SAndreas.Sandberg@ARM.com    hack_once("Pretending totalOps is equivalent to totalInsts()\n");
5129752Sandreas@sandberg.pp.se    return ctrInsts;
5139651SAndreas.Sandberg@ARM.com}
5149651SAndreas.Sandberg@ARM.com
5159651SAndreas.Sandberg@ARM.comvoid
5169651SAndreas.Sandberg@ARM.comBaseKvmCPU::dump()
5179651SAndreas.Sandberg@ARM.com{
5189651SAndreas.Sandberg@ARM.com    inform("State dumping not implemented.");
5199651SAndreas.Sandberg@ARM.com}
5209651SAndreas.Sandberg@ARM.com
5219651SAndreas.Sandberg@ARM.comvoid
5229651SAndreas.Sandberg@ARM.comBaseKvmCPU::tick()
5239651SAndreas.Sandberg@ARM.com{
5249753Sandreas@sandberg.pp.se    Tick delay(0);
5259753Sandreas@sandberg.pp.se    assert(_status != Idle);
5269651SAndreas.Sandberg@ARM.com
5279651SAndreas.Sandberg@ARM.com    switch (_status) {
5289753Sandreas@sandberg.pp.se      case RunningService:
5299753Sandreas@sandberg.pp.se        // handleKvmExit() will determine the next state of the CPU
5309753Sandreas@sandberg.pp.se        delay = handleKvmExit();
5319753Sandreas@sandberg.pp.se
5329753Sandreas@sandberg.pp.se        if (tryDrain())
5339753Sandreas@sandberg.pp.se            _status = Idle;
5349651SAndreas.Sandberg@ARM.com        break;
5359651SAndreas.Sandberg@ARM.com
5369753Sandreas@sandberg.pp.se      case RunningServiceCompletion:
5379753Sandreas@sandberg.pp.se      case Running: {
5389983Sstever@gmail.com          EventQueue *q = curEventQueue();
5399983Sstever@gmail.com          Tick ticksToExecute(q->nextTick() - curTick());
5409753Sandreas@sandberg.pp.se
5419753Sandreas@sandberg.pp.se          // We might need to update the KVM state.
5429753Sandreas@sandberg.pp.se          syncKvmState();
5439753Sandreas@sandberg.pp.se
5449892Sandreas@sandberg.pp.se          // Setup any pending instruction count breakpoints using
5459892Sandreas@sandberg.pp.se          // PerfEvent.
5469892Sandreas@sandberg.pp.se          setupInstStop();
5479892Sandreas@sandberg.pp.se
5489753Sandreas@sandberg.pp.se          DPRINTF(KvmRun, "Entering KVM...\n");
5499753Sandreas@sandberg.pp.se          if (drainManager) {
5509753Sandreas@sandberg.pp.se              // Force an immediate exit from KVM after completing
5519753Sandreas@sandberg.pp.se              // pending operations. The architecture-specific code
5529753Sandreas@sandberg.pp.se              // takes care to run until it is in a state where it can
5539753Sandreas@sandberg.pp.se              // safely be drained.
5549753Sandreas@sandberg.pp.se              delay = kvmRunDrain();
5559753Sandreas@sandberg.pp.se          } else {
5569753Sandreas@sandberg.pp.se              delay = kvmRun(ticksToExecute);
5579753Sandreas@sandberg.pp.se          }
5589753Sandreas@sandberg.pp.se
55910112Sandreas@sandberg.pp.se          // The CPU might have been suspended before entering into
56010112Sandreas@sandberg.pp.se          // KVM. Assume that the CPU was suspended /before/ entering
56110112Sandreas@sandberg.pp.se          // into KVM and skip the exit handling.
56210112Sandreas@sandberg.pp.se          if (_status == Idle)
56310112Sandreas@sandberg.pp.se              break;
56410112Sandreas@sandberg.pp.se
5659753Sandreas@sandberg.pp.se          // Entering into KVM implies that we'll have to reload the thread
5669753Sandreas@sandberg.pp.se          // context from KVM if we want to access it. Flag the KVM state as
5679753Sandreas@sandberg.pp.se          // dirty with respect to the cached thread context.
5689753Sandreas@sandberg.pp.se          kvmStateDirty = true;
5699753Sandreas@sandberg.pp.se
5709753Sandreas@sandberg.pp.se          // Enter into the RunningService state unless the
5719753Sandreas@sandberg.pp.se          // simulation was stopped by a timer.
5729755Sandreas@sandberg.pp.se          if (_kvmRun->exit_reason !=  KVM_EXIT_INTR) {
5739753Sandreas@sandberg.pp.se              _status = RunningService;
5749755Sandreas@sandberg.pp.se          } else {
5759755Sandreas@sandberg.pp.se              ++numExitSignal;
5769753Sandreas@sandberg.pp.se              _status = Running;
5779755Sandreas@sandberg.pp.se          }
5789753Sandreas@sandberg.pp.se
5799904Sandreas@sandberg.pp.se          // Service any pending instruction events. The vCPU should
5809904Sandreas@sandberg.pp.se          // have exited in time for the event using the instruction
5819904Sandreas@sandberg.pp.se          // counter configured by setupInstStop().
5829904Sandreas@sandberg.pp.se          comInstEventQueue[0]->serviceEvents(ctrInsts);
5839904Sandreas@sandberg.pp.se          system->instEventQueue.serviceEvents(system->totalNumInsts);
5849904Sandreas@sandberg.pp.se
5859753Sandreas@sandberg.pp.se          if (tryDrain())
5869753Sandreas@sandberg.pp.se              _status = Idle;
5879753Sandreas@sandberg.pp.se      } break;
5889753Sandreas@sandberg.pp.se
5899651SAndreas.Sandberg@ARM.com      default:
5909753Sandreas@sandberg.pp.se        panic("BaseKvmCPU entered tick() in an illegal state (%i)\n",
5919753Sandreas@sandberg.pp.se              _status);
5929651SAndreas.Sandberg@ARM.com    }
5939753Sandreas@sandberg.pp.se
5949753Sandreas@sandberg.pp.se    // Schedule a new tick if we are still running
5959753Sandreas@sandberg.pp.se    if (_status != Idle)
5969753Sandreas@sandberg.pp.se        schedule(tickEvent, clockEdge(ticksToCycles(delay)));
5979753Sandreas@sandberg.pp.se}
5989753Sandreas@sandberg.pp.se
5999753Sandreas@sandberg.pp.seTick
6009753Sandreas@sandberg.pp.seBaseKvmCPU::kvmRunDrain()
6019753Sandreas@sandberg.pp.se{
6029753Sandreas@sandberg.pp.se    // By default, the only thing we need to drain is a pending IO
6039753Sandreas@sandberg.pp.se    // operation which assumes that we are in the
6049753Sandreas@sandberg.pp.se    // RunningServiceCompletion state.
6059753Sandreas@sandberg.pp.se    assert(_status == RunningServiceCompletion);
6069753Sandreas@sandberg.pp.se
6079753Sandreas@sandberg.pp.se    // Deliver the data from the pending IO operation and immediately
6089753Sandreas@sandberg.pp.se    // exit.
6099753Sandreas@sandberg.pp.se    return kvmRun(0);
6109651SAndreas.Sandberg@ARM.com}
6119651SAndreas.Sandberg@ARM.com
6129735Sandreas@sandberg.pp.seuint64_t
6139735Sandreas@sandberg.pp.seBaseKvmCPU::getHostCycles() const
6149735Sandreas@sandberg.pp.se{
6159735Sandreas@sandberg.pp.se    return hwCycles.read();
6169735Sandreas@sandberg.pp.se}
6179735Sandreas@sandberg.pp.se
6189651SAndreas.Sandberg@ARM.comTick
6199651SAndreas.Sandberg@ARM.comBaseKvmCPU::kvmRun(Tick ticks)
6209651SAndreas.Sandberg@ARM.com{
6219753Sandreas@sandberg.pp.se    Tick ticksExecuted;
6229651SAndreas.Sandberg@ARM.com    DPRINTF(KvmRun, "KVM: Executing for %i ticks\n", ticks);
6239655SAndreas.Sandberg@ARM.com
6249753Sandreas@sandberg.pp.se    if (ticks == 0) {
6259753Sandreas@sandberg.pp.se        // Settings ticks == 0 is a special case which causes an entry
6269753Sandreas@sandberg.pp.se        // into KVM that finishes pending operations (e.g., IO) and
6279753Sandreas@sandberg.pp.se        // then immediately exits.
6289753Sandreas@sandberg.pp.se        DPRINTF(KvmRun, "KVM: Delivering IO without full guest entry\n");
6299735Sandreas@sandberg.pp.se
6309755Sandreas@sandberg.pp.se        ++numVMHalfEntries;
6319755Sandreas@sandberg.pp.se
63210114Sandreas@sandberg.pp.se        // Send a KVM_KICK_SIGNAL to the vCPU thread (i.e., this
63310114Sandreas@sandberg.pp.se        // thread). The KVM control signal is masked while executing
63410114Sandreas@sandberg.pp.se        // in gem5 and gets unmasked temporarily as when entering
6359753Sandreas@sandberg.pp.se        // KVM. See setSignalMask() and setupSignalHandler().
63610114Sandreas@sandberg.pp.se        kick();
6379655SAndreas.Sandberg@ARM.com
63810114Sandreas@sandberg.pp.se        // Start the vCPU. KVM will check for signals after completing
63910114Sandreas@sandberg.pp.se        // pending operations (IO). Since the KVM_KICK_SIGNAL is
64010114Sandreas@sandberg.pp.se        // pending, this forces an immediate exit to gem5 again. We
6419753Sandreas@sandberg.pp.se        // don't bother to setup timers since this shouldn't actually
64210114Sandreas@sandberg.pp.se        // execute any code (other than completing half-executed IO
64310114Sandreas@sandberg.pp.se        // instructions) in the guest.
6449753Sandreas@sandberg.pp.se        ioctlRun();
6459753Sandreas@sandberg.pp.se
6469753Sandreas@sandberg.pp.se        // We always execute at least one cycle to prevent the
6479753Sandreas@sandberg.pp.se        // BaseKvmCPU::tick() to be rescheduled on the same tick
6489753Sandreas@sandberg.pp.se        // twice.
6499753Sandreas@sandberg.pp.se        ticksExecuted = clockPeriod();
6509753Sandreas@sandberg.pp.se    } else {
65110157Sandreas@sandberg.pp.se        // This method is executed as a result of a tick event. That
65210157Sandreas@sandberg.pp.se        // means that the event queue will be locked when entering the
65310157Sandreas@sandberg.pp.se        // method. We temporarily unlock the event queue to allow
65410157Sandreas@sandberg.pp.se        // other threads to steal control of this thread to inject
65510157Sandreas@sandberg.pp.se        // interrupts. They will typically lock the queue and then
65610157Sandreas@sandberg.pp.se        // force an exit from KVM by kicking the vCPU.
65710157Sandreas@sandberg.pp.se        EventQueue::ScopedRelease release(curEventQueue());
65810157Sandreas@sandberg.pp.se
6599753Sandreas@sandberg.pp.se        if (ticks < runTimer->resolution()) {
6609753Sandreas@sandberg.pp.se            DPRINTF(KvmRun, "KVM: Adjusting tick count (%i -> %i)\n",
6619753Sandreas@sandberg.pp.se                    ticks, runTimer->resolution());
6629753Sandreas@sandberg.pp.se            ticks = runTimer->resolution();
6639753Sandreas@sandberg.pp.se        }
6649753Sandreas@sandberg.pp.se
6659753Sandreas@sandberg.pp.se        // Get hardware statistics after synchronizing contexts. The KVM
6669753Sandreas@sandberg.pp.se        // state update might affect guest cycle counters.
6679753Sandreas@sandberg.pp.se        uint64_t baseCycles(getHostCycles());
6689753Sandreas@sandberg.pp.se        uint64_t baseInstrs(hwInstructions.read());
6699753Sandreas@sandberg.pp.se
6709753Sandreas@sandberg.pp.se        // Arm the run timer and start the cycle timer if it isn't
6719753Sandreas@sandberg.pp.se        // controlled by the overflow timer. Starting/stopping the cycle
6729753Sandreas@sandberg.pp.se        // timer automatically starts the other perf timers as they are in
6739753Sandreas@sandberg.pp.se        // the same counter group.
6749753Sandreas@sandberg.pp.se        runTimer->arm(ticks);
6759753Sandreas@sandberg.pp.se        if (!perfControlledByTimer)
6769753Sandreas@sandberg.pp.se            hwCycles.start();
6779753Sandreas@sandberg.pp.se
6789753Sandreas@sandberg.pp.se        ioctlRun();
6799753Sandreas@sandberg.pp.se
6809753Sandreas@sandberg.pp.se        runTimer->disarm();
6819753Sandreas@sandberg.pp.se        if (!perfControlledByTimer)
6829753Sandreas@sandberg.pp.se            hwCycles.stop();
6839753Sandreas@sandberg.pp.se
68410114Sandreas@sandberg.pp.se        // The control signal may have been delivered after we exited
6859753Sandreas@sandberg.pp.se        // from KVM. It will be pending in that case since it is
6869753Sandreas@sandberg.pp.se        // masked when we aren't executing in KVM. Discard it to make
6879753Sandreas@sandberg.pp.se        // sure we don't deliver it immediately next time we try to
6889753Sandreas@sandberg.pp.se        // enter into KVM.
68910114Sandreas@sandberg.pp.se        discardPendingSignal(KVM_KICK_SIGNAL);
6909753Sandreas@sandberg.pp.se
6919753Sandreas@sandberg.pp.se        const uint64_t hostCyclesExecuted(getHostCycles() - baseCycles);
6929753Sandreas@sandberg.pp.se        const uint64_t simCyclesExecuted(hostCyclesExecuted * hostFactor);
6939753Sandreas@sandberg.pp.se        const uint64_t instsExecuted(hwInstructions.read() - baseInstrs);
6949753Sandreas@sandberg.pp.se        ticksExecuted = runTimer->ticksFromHostCycles(hostCyclesExecuted);
6959753Sandreas@sandberg.pp.se
6969753Sandreas@sandberg.pp.se        /* Update statistics */
6979753Sandreas@sandberg.pp.se        numCycles += simCyclesExecuted;;
6989753Sandreas@sandberg.pp.se        numInsts += instsExecuted;
6999753Sandreas@sandberg.pp.se        ctrInsts += instsExecuted;
7009753Sandreas@sandberg.pp.se        system->totalNumInsts += instsExecuted;
7019753Sandreas@sandberg.pp.se
7029753Sandreas@sandberg.pp.se        DPRINTF(KvmRun,
7039753Sandreas@sandberg.pp.se                "KVM: Executed %i instructions in %i cycles "
7049753Sandreas@sandberg.pp.se                "(%i ticks, sim cycles: %i).\n",
7059753Sandreas@sandberg.pp.se                instsExecuted, hostCyclesExecuted, ticksExecuted, simCyclesExecuted);
7069651SAndreas.Sandberg@ARM.com    }
7079655SAndreas.Sandberg@ARM.com
7089651SAndreas.Sandberg@ARM.com    ++numVMExits;
7099651SAndreas.Sandberg@ARM.com
7109651SAndreas.Sandberg@ARM.com    return ticksExecuted + flushCoalescedMMIO();
7119651SAndreas.Sandberg@ARM.com}
7129651SAndreas.Sandberg@ARM.com
7139651SAndreas.Sandberg@ARM.comvoid
7149651SAndreas.Sandberg@ARM.comBaseKvmCPU::kvmNonMaskableInterrupt()
7159651SAndreas.Sandberg@ARM.com{
7169651SAndreas.Sandberg@ARM.com    ++numInterrupts;
7179651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_NMI) == -1)
7189651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to deliver NMI to virtual CPU\n");
7199651SAndreas.Sandberg@ARM.com}
7209651SAndreas.Sandberg@ARM.com
7219651SAndreas.Sandberg@ARM.comvoid
7229651SAndreas.Sandberg@ARM.comBaseKvmCPU::kvmInterrupt(const struct kvm_interrupt &interrupt)
7239651SAndreas.Sandberg@ARM.com{
7249651SAndreas.Sandberg@ARM.com    ++numInterrupts;
7259651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_INTERRUPT, (void *)&interrupt) == -1)
7269651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to deliver interrupt to virtual CPU\n");
7279651SAndreas.Sandberg@ARM.com}
7289651SAndreas.Sandberg@ARM.com
7299651SAndreas.Sandberg@ARM.comvoid
7309651SAndreas.Sandberg@ARM.comBaseKvmCPU::getRegisters(struct kvm_regs &regs) const
7319651SAndreas.Sandberg@ARM.com{
7329651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_GET_REGS, &regs) == -1)
7339651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to get guest registers\n");
7349651SAndreas.Sandberg@ARM.com}
7359651SAndreas.Sandberg@ARM.com
7369651SAndreas.Sandberg@ARM.comvoid
7379651SAndreas.Sandberg@ARM.comBaseKvmCPU::setRegisters(const struct kvm_regs &regs)
7389651SAndreas.Sandberg@ARM.com{
7399651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_SET_REGS, (void *)&regs) == -1)
7409651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to set guest registers\n");
7419651SAndreas.Sandberg@ARM.com}
7429651SAndreas.Sandberg@ARM.com
7439651SAndreas.Sandberg@ARM.comvoid
7449651SAndreas.Sandberg@ARM.comBaseKvmCPU::getSpecialRegisters(struct kvm_sregs &regs) const
7459651SAndreas.Sandberg@ARM.com{
7469651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_GET_SREGS, &regs) == -1)
7479651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to get guest special registers\n");
7489651SAndreas.Sandberg@ARM.com}
7499651SAndreas.Sandberg@ARM.com
7509651SAndreas.Sandberg@ARM.comvoid
7519651SAndreas.Sandberg@ARM.comBaseKvmCPU::setSpecialRegisters(const struct kvm_sregs &regs)
7529651SAndreas.Sandberg@ARM.com{
7539651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_SET_SREGS, (void *)&regs) == -1)
7549651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to set guest special registers\n");
7559651SAndreas.Sandberg@ARM.com}
7569651SAndreas.Sandberg@ARM.com
7579651SAndreas.Sandberg@ARM.comvoid
7589651SAndreas.Sandberg@ARM.comBaseKvmCPU::getFPUState(struct kvm_fpu &state) const
7599651SAndreas.Sandberg@ARM.com{
7609651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_GET_FPU, &state) == -1)
7619651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to get guest FPU state\n");
7629651SAndreas.Sandberg@ARM.com}
7639651SAndreas.Sandberg@ARM.com
7649651SAndreas.Sandberg@ARM.comvoid
7659651SAndreas.Sandberg@ARM.comBaseKvmCPU::setFPUState(const struct kvm_fpu &state)
7669651SAndreas.Sandberg@ARM.com{
7679651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_SET_FPU, (void *)&state) == -1)
7689651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to set guest FPU state\n");
7699651SAndreas.Sandberg@ARM.com}
7709651SAndreas.Sandberg@ARM.com
7719651SAndreas.Sandberg@ARM.com
7729651SAndreas.Sandberg@ARM.comvoid
7739651SAndreas.Sandberg@ARM.comBaseKvmCPU::setOneReg(uint64_t id, const void *addr)
7749651SAndreas.Sandberg@ARM.com{
7759651SAndreas.Sandberg@ARM.com#ifdef KVM_SET_ONE_REG
7769651SAndreas.Sandberg@ARM.com    struct kvm_one_reg reg;
7779651SAndreas.Sandberg@ARM.com    reg.id = id;
7789651SAndreas.Sandberg@ARM.com    reg.addr = (uint64_t)addr;
7799651SAndreas.Sandberg@ARM.com
7809651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_SET_ONE_REG, &reg) == -1) {
7819651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to set register (0x%x) value (errno: %i)\n",
7829651SAndreas.Sandberg@ARM.com              id, errno);
7839651SAndreas.Sandberg@ARM.com    }
7849651SAndreas.Sandberg@ARM.com#else
7859651SAndreas.Sandberg@ARM.com    panic("KVM_SET_ONE_REG is unsupported on this platform.\n");
7869651SAndreas.Sandberg@ARM.com#endif
7879651SAndreas.Sandberg@ARM.com}
7889651SAndreas.Sandberg@ARM.com
7899651SAndreas.Sandberg@ARM.comvoid
7909651SAndreas.Sandberg@ARM.comBaseKvmCPU::getOneReg(uint64_t id, void *addr) const
7919651SAndreas.Sandberg@ARM.com{
7929651SAndreas.Sandberg@ARM.com#ifdef KVM_GET_ONE_REG
7939651SAndreas.Sandberg@ARM.com    struct kvm_one_reg reg;
7949651SAndreas.Sandberg@ARM.com    reg.id = id;
7959651SAndreas.Sandberg@ARM.com    reg.addr = (uint64_t)addr;
7969651SAndreas.Sandberg@ARM.com
7979651SAndreas.Sandberg@ARM.com    if (ioctl(KVM_GET_ONE_REG, &reg) == -1) {
7989651SAndreas.Sandberg@ARM.com        panic("KVM: Failed to get register (0x%x) value (errno: %i)\n",
7999651SAndreas.Sandberg@ARM.com              id, errno);
8009651SAndreas.Sandberg@ARM.com    }
8019651SAndreas.Sandberg@ARM.com#else
8029651SAndreas.Sandberg@ARM.com    panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
8039651SAndreas.Sandberg@ARM.com#endif
8049651SAndreas.Sandberg@ARM.com}
8059651SAndreas.Sandberg@ARM.com
8069651SAndreas.Sandberg@ARM.comstd::string
8079651SAndreas.Sandberg@ARM.comBaseKvmCPU::getAndFormatOneReg(uint64_t id) const
8089651SAndreas.Sandberg@ARM.com{
8099651SAndreas.Sandberg@ARM.com#ifdef KVM_GET_ONE_REG
8109651SAndreas.Sandberg@ARM.com    std::ostringstream ss;
8119651SAndreas.Sandberg@ARM.com
8129651SAndreas.Sandberg@ARM.com    ss.setf(std::ios::hex, std::ios::basefield);
8139651SAndreas.Sandberg@ARM.com    ss.setf(std::ios::showbase);
8149651SAndreas.Sandberg@ARM.com#define HANDLE_INTTYPE(len)                      \
8159651SAndreas.Sandberg@ARM.com    case KVM_REG_SIZE_U ## len: {                \
8169651SAndreas.Sandberg@ARM.com        uint ## len ## _t value;                 \
8179651SAndreas.Sandberg@ARM.com        getOneReg(id, &value);                   \
8189651SAndreas.Sandberg@ARM.com        ss << value;                             \
8199651SAndreas.Sandberg@ARM.com    }  break
8209651SAndreas.Sandberg@ARM.com
8219651SAndreas.Sandberg@ARM.com#define HANDLE_ARRAY(len)                       \
8229651SAndreas.Sandberg@ARM.com    case KVM_REG_SIZE_U ## len: {               \
8239651SAndreas.Sandberg@ARM.com        uint8_t value[len / 8];                 \
8249651SAndreas.Sandberg@ARM.com        getOneReg(id, value);                   \
8259651SAndreas.Sandberg@ARM.com        ss << "[" << value[0];                  \
8269651SAndreas.Sandberg@ARM.com        for (int i = 1; i < len  / 8; ++i)      \
8279651SAndreas.Sandberg@ARM.com            ss << ", " << value[i];             \
8289651SAndreas.Sandberg@ARM.com        ss << "]";                              \
8299651SAndreas.Sandberg@ARM.com      } break
8309651SAndreas.Sandberg@ARM.com
8319651SAndreas.Sandberg@ARM.com    switch (id & KVM_REG_SIZE_MASK) {
8329651SAndreas.Sandberg@ARM.com        HANDLE_INTTYPE(8);
8339651SAndreas.Sandberg@ARM.com        HANDLE_INTTYPE(16);
8349651SAndreas.Sandberg@ARM.com        HANDLE_INTTYPE(32);
8359651SAndreas.Sandberg@ARM.com        HANDLE_INTTYPE(64);
8369651SAndreas.Sandberg@ARM.com        HANDLE_ARRAY(128);
8379651SAndreas.Sandberg@ARM.com        HANDLE_ARRAY(256);
8389651SAndreas.Sandberg@ARM.com        HANDLE_ARRAY(512);
8399651SAndreas.Sandberg@ARM.com        HANDLE_ARRAY(1024);
8409651SAndreas.Sandberg@ARM.com      default:
8419651SAndreas.Sandberg@ARM.com        ss << "??";
8429651SAndreas.Sandberg@ARM.com    }
8439651SAndreas.Sandberg@ARM.com
8449651SAndreas.Sandberg@ARM.com#undef HANDLE_INTTYPE
8459651SAndreas.Sandberg@ARM.com#undef HANDLE_ARRAY
8469651SAndreas.Sandberg@ARM.com
8479651SAndreas.Sandberg@ARM.com    return ss.str();
8489651SAndreas.Sandberg@ARM.com#else
8499651SAndreas.Sandberg@ARM.com    panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
8509651SAndreas.Sandberg@ARM.com#endif
8519651SAndreas.Sandberg@ARM.com}
8529651SAndreas.Sandberg@ARM.com
8539652SAndreas.Sandberg@ARM.comvoid
8549652SAndreas.Sandberg@ARM.comBaseKvmCPU::syncThreadContext()
8559652SAndreas.Sandberg@ARM.com{
8569652SAndreas.Sandberg@ARM.com    if (!kvmStateDirty)
8579652SAndreas.Sandberg@ARM.com        return;
8589652SAndreas.Sandberg@ARM.com
8599652SAndreas.Sandberg@ARM.com    assert(!threadContextDirty);
8609652SAndreas.Sandberg@ARM.com
8619652SAndreas.Sandberg@ARM.com    updateThreadContext();
8629652SAndreas.Sandberg@ARM.com    kvmStateDirty = false;
8639652SAndreas.Sandberg@ARM.com}
8649652SAndreas.Sandberg@ARM.com
8659652SAndreas.Sandberg@ARM.comvoid
8669652SAndreas.Sandberg@ARM.comBaseKvmCPU::syncKvmState()
8679652SAndreas.Sandberg@ARM.com{
8689652SAndreas.Sandberg@ARM.com    if (!threadContextDirty)
8699652SAndreas.Sandberg@ARM.com        return;
8709652SAndreas.Sandberg@ARM.com
8719652SAndreas.Sandberg@ARM.com    assert(!kvmStateDirty);
8729652SAndreas.Sandberg@ARM.com
8739652SAndreas.Sandberg@ARM.com    updateKvmState();
8749652SAndreas.Sandberg@ARM.com    threadContextDirty = false;
8759652SAndreas.Sandberg@ARM.com}
8769652SAndreas.Sandberg@ARM.com
8779651SAndreas.Sandberg@ARM.comTick
8789651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExit()
8799651SAndreas.Sandberg@ARM.com{
8809651SAndreas.Sandberg@ARM.com    DPRINTF(KvmRun, "handleKvmExit (exit_reason: %i)\n", _kvmRun->exit_reason);
8819753Sandreas@sandberg.pp.se    assert(_status == RunningService);
8829651SAndreas.Sandberg@ARM.com
8839753Sandreas@sandberg.pp.se    // Switch into the running state by default. Individual handlers
8849753Sandreas@sandberg.pp.se    // can override this.
8859753Sandreas@sandberg.pp.se    _status = Running;
8869651SAndreas.Sandberg@ARM.com    switch (_kvmRun->exit_reason) {
8879651SAndreas.Sandberg@ARM.com      case KVM_EXIT_UNKNOWN:
8889651SAndreas.Sandberg@ARM.com        return handleKvmExitUnknown();
8899651SAndreas.Sandberg@ARM.com
8909651SAndreas.Sandberg@ARM.com      case KVM_EXIT_EXCEPTION:
8919651SAndreas.Sandberg@ARM.com        return handleKvmExitException();
8929651SAndreas.Sandberg@ARM.com
8939651SAndreas.Sandberg@ARM.com      case KVM_EXIT_IO:
8949753Sandreas@sandberg.pp.se        _status = RunningServiceCompletion;
8959651SAndreas.Sandberg@ARM.com        ++numIO;
8969651SAndreas.Sandberg@ARM.com        return handleKvmExitIO();
8979651SAndreas.Sandberg@ARM.com
8989651SAndreas.Sandberg@ARM.com      case KVM_EXIT_HYPERCALL:
8999651SAndreas.Sandberg@ARM.com        ++numHypercalls;
9009651SAndreas.Sandberg@ARM.com        return handleKvmExitHypercall();
9019651SAndreas.Sandberg@ARM.com
9029651SAndreas.Sandberg@ARM.com      case KVM_EXIT_HLT:
9039651SAndreas.Sandberg@ARM.com        /* The guest has halted and is waiting for interrupts */
9049651SAndreas.Sandberg@ARM.com        DPRINTF(Kvm, "handleKvmExitHalt\n");
9059651SAndreas.Sandberg@ARM.com        ++numHalt;
9069651SAndreas.Sandberg@ARM.com
9079651SAndreas.Sandberg@ARM.com        // Suspend the thread until the next interrupt arrives
9089651SAndreas.Sandberg@ARM.com        thread->suspend();
9099651SAndreas.Sandberg@ARM.com
9109651SAndreas.Sandberg@ARM.com        // This is actually ignored since the thread is suspended.
9119651SAndreas.Sandberg@ARM.com        return 0;
9129651SAndreas.Sandberg@ARM.com
9139651SAndreas.Sandberg@ARM.com      case KVM_EXIT_MMIO:
9149753Sandreas@sandberg.pp.se        _status = RunningServiceCompletion;
9159651SAndreas.Sandberg@ARM.com        /* Service memory mapped IO requests */
9169651SAndreas.Sandberg@ARM.com        DPRINTF(KvmIO, "KVM: Handling MMIO (w: %u, addr: 0x%x, len: %u)\n",
9179651SAndreas.Sandberg@ARM.com                _kvmRun->mmio.is_write,
9189651SAndreas.Sandberg@ARM.com                _kvmRun->mmio.phys_addr, _kvmRun->mmio.len);
9199651SAndreas.Sandberg@ARM.com
9209651SAndreas.Sandberg@ARM.com        ++numMMIO;
9219651SAndreas.Sandberg@ARM.com        return doMMIOAccess(_kvmRun->mmio.phys_addr, _kvmRun->mmio.data,
9229651SAndreas.Sandberg@ARM.com                            _kvmRun->mmio.len, _kvmRun->mmio.is_write);
9239651SAndreas.Sandberg@ARM.com
9249651SAndreas.Sandberg@ARM.com      case KVM_EXIT_IRQ_WINDOW_OPEN:
9259651SAndreas.Sandberg@ARM.com        return handleKvmExitIRQWindowOpen();
9269651SAndreas.Sandberg@ARM.com
9279651SAndreas.Sandberg@ARM.com      case KVM_EXIT_FAIL_ENTRY:
9289651SAndreas.Sandberg@ARM.com        return handleKvmExitFailEntry();
9299651SAndreas.Sandberg@ARM.com
9309651SAndreas.Sandberg@ARM.com      case KVM_EXIT_INTR:
9319651SAndreas.Sandberg@ARM.com        /* KVM was interrupted by a signal, restart it in the next
9329651SAndreas.Sandberg@ARM.com         * tick. */
9339651SAndreas.Sandberg@ARM.com        return 0;
9349651SAndreas.Sandberg@ARM.com
9359651SAndreas.Sandberg@ARM.com      case KVM_EXIT_INTERNAL_ERROR:
9369651SAndreas.Sandberg@ARM.com        panic("KVM: Internal error (suberror: %u)\n",
9379651SAndreas.Sandberg@ARM.com              _kvmRun->internal.suberror);
9389651SAndreas.Sandberg@ARM.com
9399651SAndreas.Sandberg@ARM.com      default:
9409689Sandreas@sandberg.pp.se        dump();
9419651SAndreas.Sandberg@ARM.com        panic("KVM: Unexpected exit (exit_reason: %u)\n", _kvmRun->exit_reason);
9429651SAndreas.Sandberg@ARM.com    }
9439651SAndreas.Sandberg@ARM.com}
9449651SAndreas.Sandberg@ARM.com
9459651SAndreas.Sandberg@ARM.comTick
9469651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitIO()
9479651SAndreas.Sandberg@ARM.com{
9489651SAndreas.Sandberg@ARM.com    panic("KVM: Unhandled guest IO (dir: %i, size: %i, port: 0x%x, count: %i)\n",
9499651SAndreas.Sandberg@ARM.com          _kvmRun->io.direction, _kvmRun->io.size,
9509651SAndreas.Sandberg@ARM.com          _kvmRun->io.port, _kvmRun->io.count);
9519651SAndreas.Sandberg@ARM.com}
9529651SAndreas.Sandberg@ARM.com
9539651SAndreas.Sandberg@ARM.comTick
9549651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitHypercall()
9559651SAndreas.Sandberg@ARM.com{
9569651SAndreas.Sandberg@ARM.com    panic("KVM: Unhandled hypercall\n");
9579651SAndreas.Sandberg@ARM.com}
9589651SAndreas.Sandberg@ARM.com
9599651SAndreas.Sandberg@ARM.comTick
9609651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitIRQWindowOpen()
9619651SAndreas.Sandberg@ARM.com{
9629651SAndreas.Sandberg@ARM.com    warn("KVM: Unhandled IRQ window.\n");
9639651SAndreas.Sandberg@ARM.com    return 0;
9649651SAndreas.Sandberg@ARM.com}
9659651SAndreas.Sandberg@ARM.com
9669651SAndreas.Sandberg@ARM.com
9679651SAndreas.Sandberg@ARM.comTick
9689651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitUnknown()
9699651SAndreas.Sandberg@ARM.com{
9709689Sandreas@sandberg.pp.se    dump();
9719651SAndreas.Sandberg@ARM.com    panic("KVM: Unknown error when starting vCPU (hw reason: 0x%llx)\n",
9729651SAndreas.Sandberg@ARM.com          _kvmRun->hw.hardware_exit_reason);
9739651SAndreas.Sandberg@ARM.com}
9749651SAndreas.Sandberg@ARM.com
9759651SAndreas.Sandberg@ARM.comTick
9769651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitException()
9779651SAndreas.Sandberg@ARM.com{
9789689Sandreas@sandberg.pp.se    dump();
9799651SAndreas.Sandberg@ARM.com    panic("KVM: Got exception when starting vCPU "
9809651SAndreas.Sandberg@ARM.com          "(exception: %u, error_code: %u)\n",
9819651SAndreas.Sandberg@ARM.com          _kvmRun->ex.exception, _kvmRun->ex.error_code);
9829651SAndreas.Sandberg@ARM.com}
9839651SAndreas.Sandberg@ARM.com
9849651SAndreas.Sandberg@ARM.comTick
9859651SAndreas.Sandberg@ARM.comBaseKvmCPU::handleKvmExitFailEntry()
9869651SAndreas.Sandberg@ARM.com{
9879689Sandreas@sandberg.pp.se    dump();
9889651SAndreas.Sandberg@ARM.com    panic("KVM: Failed to enter virtualized mode (hw reason: 0x%llx)\n",
9899651SAndreas.Sandberg@ARM.com          _kvmRun->fail_entry.hardware_entry_failure_reason);
9909651SAndreas.Sandberg@ARM.com}
9919651SAndreas.Sandberg@ARM.com
9929651SAndreas.Sandberg@ARM.comTick
9939651SAndreas.Sandberg@ARM.comBaseKvmCPU::doMMIOAccess(Addr paddr, void *data, int size, bool write)
9949651SAndreas.Sandberg@ARM.com{
9959760Sandreas@sandberg.pp.se    ThreadContext *tc(thread->getTC());
9969760Sandreas@sandberg.pp.se    syncThreadContext();
9979760Sandreas@sandberg.pp.se
9989682Sandreas@sandberg.pp.se    mmio_req.setPhys(paddr, size, Request::UNCACHEABLE, dataMasterId());
9999760Sandreas@sandberg.pp.se    // Some architectures do need to massage physical addresses a bit
10009760Sandreas@sandberg.pp.se    // before they are inserted into the memory system. This enables
10019760Sandreas@sandberg.pp.se    // APIC accesses on x86 and m5ops where supported through a MMIO
10029760Sandreas@sandberg.pp.se    // interface.
10039760Sandreas@sandberg.pp.se    BaseTLB::Mode tlb_mode(write ? BaseTLB::Write : BaseTLB::Read);
10049760Sandreas@sandberg.pp.se    Fault fault(tc->getDTBPtr()->finalizePhysical(&mmio_req, tc, tlb_mode));
10059760Sandreas@sandberg.pp.se    if (fault != NoFault)
10069760Sandreas@sandberg.pp.se        warn("Finalization of MMIO address failed: %s\n", fault->name());
10079760Sandreas@sandberg.pp.se
10089651SAndreas.Sandberg@ARM.com
10099651SAndreas.Sandberg@ARM.com    const MemCmd cmd(write ? MemCmd::WriteReq : MemCmd::ReadReq);
10109651SAndreas.Sandberg@ARM.com    Packet pkt(&mmio_req, cmd);
10119651SAndreas.Sandberg@ARM.com    pkt.dataStatic(data);
10129760Sandreas@sandberg.pp.se
10139760Sandreas@sandberg.pp.se    if (mmio_req.isMmappedIpr()) {
101410157Sandreas@sandberg.pp.se        // We currently assume that there is no need to migrate to a
101510157Sandreas@sandberg.pp.se        // different event queue when doing IPRs. Currently, IPRs are
101610157Sandreas@sandberg.pp.se        // only used for m5ops, so it should be a valid assumption.
10179882Sandreas@sandberg.pp.se        const Cycles ipr_delay(write ?
10189882Sandreas@sandberg.pp.se                             TheISA::handleIprWrite(tc, &pkt) :
10199882Sandreas@sandberg.pp.se                             TheISA::handleIprRead(tc, &pkt));
102010553Salexandru.dutu@amd.com        threadContextDirty = true;
10219925Sandreas@sandberg.pp.se        return clockPeriod() * ipr_delay;
10229760Sandreas@sandberg.pp.se    } else {
102310157Sandreas@sandberg.pp.se        // Temporarily lock and migrate to the event queue of the
102410157Sandreas@sandberg.pp.se        // VM. This queue is assumed to "own" all devices we need to
102510157Sandreas@sandberg.pp.se        // access if running in multi-core mode.
102610157Sandreas@sandberg.pp.se        EventQueue::ScopedMigration migrate(vm.eventQueue());
102710157Sandreas@sandberg.pp.se
10289760Sandreas@sandberg.pp.se        return dataPort.sendAtomic(&pkt);
10299760Sandreas@sandberg.pp.se    }
10309651SAndreas.Sandberg@ARM.com}
10319651SAndreas.Sandberg@ARM.com
10329753Sandreas@sandberg.pp.sevoid
10339753Sandreas@sandberg.pp.seBaseKvmCPU::setSignalMask(const sigset_t *mask)
10349753Sandreas@sandberg.pp.se{
10359753Sandreas@sandberg.pp.se    std::unique_ptr<struct kvm_signal_mask> kvm_mask;
10369753Sandreas@sandberg.pp.se
10379753Sandreas@sandberg.pp.se    if (mask) {
10389753Sandreas@sandberg.pp.se        kvm_mask.reset((struct kvm_signal_mask *)operator new(
10399753Sandreas@sandberg.pp.se                           sizeof(struct kvm_signal_mask) + sizeof(*mask)));
10409753Sandreas@sandberg.pp.se        // The kernel and the user-space headers have different ideas
10419753Sandreas@sandberg.pp.se        // about the size of sigset_t. This seems like a massive hack,
10429753Sandreas@sandberg.pp.se        // but is actually what qemu does.
10439753Sandreas@sandberg.pp.se        assert(sizeof(*mask) >= 8);
10449753Sandreas@sandberg.pp.se        kvm_mask->len = 8;
10459753Sandreas@sandberg.pp.se        memcpy(kvm_mask->sigset, mask, kvm_mask->len);
10469753Sandreas@sandberg.pp.se    }
10479753Sandreas@sandberg.pp.se
10489753Sandreas@sandberg.pp.se    if (ioctl(KVM_SET_SIGNAL_MASK, (void *)kvm_mask.get()) == -1)
10499753Sandreas@sandberg.pp.se        panic("KVM: Failed to set vCPU signal mask (errno: %i)\n",
10509753Sandreas@sandberg.pp.se              errno);
10519753Sandreas@sandberg.pp.se}
10529753Sandreas@sandberg.pp.se
10539651SAndreas.Sandberg@ARM.comint
10549651SAndreas.Sandberg@ARM.comBaseKvmCPU::ioctl(int request, long p1) const
10559651SAndreas.Sandberg@ARM.com{
10569651SAndreas.Sandberg@ARM.com    if (vcpuFD == -1)
10579651SAndreas.Sandberg@ARM.com        panic("KVM: CPU ioctl called before initialization\n");
10589651SAndreas.Sandberg@ARM.com
10599651SAndreas.Sandberg@ARM.com    return ::ioctl(vcpuFD, request, p1);
10609651SAndreas.Sandberg@ARM.com}
10619651SAndreas.Sandberg@ARM.com
10629651SAndreas.Sandberg@ARM.comTick
10639651SAndreas.Sandberg@ARM.comBaseKvmCPU::flushCoalescedMMIO()
10649651SAndreas.Sandberg@ARM.com{
10659651SAndreas.Sandberg@ARM.com    if (!mmioRing)
10669651SAndreas.Sandberg@ARM.com        return 0;
10679651SAndreas.Sandberg@ARM.com
10689651SAndreas.Sandberg@ARM.com    DPRINTF(KvmIO, "KVM: Flushing the coalesced MMIO ring buffer\n");
10699651SAndreas.Sandberg@ARM.com
10709651SAndreas.Sandberg@ARM.com    // TODO: We might need to do synchronization when we start to
10719651SAndreas.Sandberg@ARM.com    // support multiple CPUs
10729651SAndreas.Sandberg@ARM.com    Tick ticks(0);
10739651SAndreas.Sandberg@ARM.com    while (mmioRing->first != mmioRing->last) {
10749651SAndreas.Sandberg@ARM.com        struct kvm_coalesced_mmio &ent(
10759651SAndreas.Sandberg@ARM.com            mmioRing->coalesced_mmio[mmioRing->first]);
10769651SAndreas.Sandberg@ARM.com
10779651SAndreas.Sandberg@ARM.com        DPRINTF(KvmIO, "KVM: Handling coalesced MMIO (addr: 0x%x, len: %u)\n",
10789651SAndreas.Sandberg@ARM.com                ent.phys_addr, ent.len);
10799651SAndreas.Sandberg@ARM.com
10809651SAndreas.Sandberg@ARM.com        ++numCoalescedMMIO;
10819651SAndreas.Sandberg@ARM.com        ticks += doMMIOAccess(ent.phys_addr, ent.data, ent.len, true);
10829651SAndreas.Sandberg@ARM.com
10839651SAndreas.Sandberg@ARM.com        mmioRing->first = (mmioRing->first + 1) % KVM_COALESCED_MMIO_MAX;
10849651SAndreas.Sandberg@ARM.com    }
10859651SAndreas.Sandberg@ARM.com
10869651SAndreas.Sandberg@ARM.com    return ticks;
10879651SAndreas.Sandberg@ARM.com}
10889651SAndreas.Sandberg@ARM.com
10899892Sandreas@sandberg.pp.se/**
109010114Sandreas@sandberg.pp.se * Dummy handler for KVM kick signals.
109110073Sandreas@sandberg.pp.se *
109210114Sandreas@sandberg.pp.se * @note This function is usually not called since the kernel doesn't
109310073Sandreas@sandberg.pp.se * seem to deliver signals when the signal is only unmasked when
109410073Sandreas@sandberg.pp.se * running in KVM. This doesn't matter though since we are only
109510073Sandreas@sandberg.pp.se * interested in getting KVM to exit, which happens as expected. See
109610073Sandreas@sandberg.pp.se * setupSignalHandler() and kvmRun() for details about KVM signal
109710073Sandreas@sandberg.pp.se * handling.
10989892Sandreas@sandberg.pp.se */
10999892Sandreas@sandberg.pp.sestatic void
110010114Sandreas@sandberg.pp.seonKickSignal(int signo, siginfo_t *si, void *data)
11019892Sandreas@sandberg.pp.se{
11029892Sandreas@sandberg.pp.se}
11039892Sandreas@sandberg.pp.se
11049651SAndreas.Sandberg@ARM.comvoid
11059651SAndreas.Sandberg@ARM.comBaseKvmCPU::setupSignalHandler()
11069651SAndreas.Sandberg@ARM.com{
11079651SAndreas.Sandberg@ARM.com    struct sigaction sa;
11089651SAndreas.Sandberg@ARM.com
11099651SAndreas.Sandberg@ARM.com    memset(&sa, 0, sizeof(sa));
111010114Sandreas@sandberg.pp.se    sa.sa_sigaction = onKickSignal;
11119651SAndreas.Sandberg@ARM.com    sa.sa_flags = SA_SIGINFO | SA_RESTART;
111210114Sandreas@sandberg.pp.se    if (sigaction(KVM_KICK_SIGNAL, &sa, NULL) == -1)
11139892Sandreas@sandberg.pp.se        panic("KVM: Failed to setup vCPU timer signal handler\n");
11149892Sandreas@sandberg.pp.se
11159753Sandreas@sandberg.pp.se    sigset_t sigset;
111610073Sandreas@sandberg.pp.se    if (pthread_sigmask(SIG_BLOCK, NULL, &sigset) == -1)
11179753Sandreas@sandberg.pp.se        panic("KVM: Failed get signal mask\n");
11189753Sandreas@sandberg.pp.se
11199753Sandreas@sandberg.pp.se    // Request KVM to setup the same signal mask as we're currently
112010114Sandreas@sandberg.pp.se    // running with except for the KVM control signal. We'll sometimes
112110114Sandreas@sandberg.pp.se    // need to raise the KVM_KICK_SIGNAL to cause immediate exits from
112210114Sandreas@sandberg.pp.se    // KVM after servicing IO requests. See kvmRun().
112310114Sandreas@sandberg.pp.se    sigdelset(&sigset, KVM_KICK_SIGNAL);
11249753Sandreas@sandberg.pp.se    setSignalMask(&sigset);
11259753Sandreas@sandberg.pp.se
11269892Sandreas@sandberg.pp.se    // Mask our control signals so they aren't delivered unless we're
11279753Sandreas@sandberg.pp.se    // actually executing inside KVM.
112810114Sandreas@sandberg.pp.se    sigaddset(&sigset, KVM_KICK_SIGNAL);
112910073Sandreas@sandberg.pp.se    if (pthread_sigmask(SIG_SETMASK, &sigset, NULL) == -1)
11309892Sandreas@sandberg.pp.se        panic("KVM: Failed mask the KVM control signals\n");
11319753Sandreas@sandberg.pp.se}
11329753Sandreas@sandberg.pp.se
11339753Sandreas@sandberg.pp.sebool
11349753Sandreas@sandberg.pp.seBaseKvmCPU::discardPendingSignal(int signum) const
11359753Sandreas@sandberg.pp.se{
11369753Sandreas@sandberg.pp.se    int discardedSignal;
11379753Sandreas@sandberg.pp.se
11389753Sandreas@sandberg.pp.se    // Setting the timeout to zero causes sigtimedwait to return
11399753Sandreas@sandberg.pp.se    // immediately.
11409753Sandreas@sandberg.pp.se    struct timespec timeout;
11419753Sandreas@sandberg.pp.se    timeout.tv_sec = 0;
11429753Sandreas@sandberg.pp.se    timeout.tv_nsec = 0;
11439753Sandreas@sandberg.pp.se
11449753Sandreas@sandberg.pp.se    sigset_t sigset;
11459753Sandreas@sandberg.pp.se    sigemptyset(&sigset);
11469753Sandreas@sandberg.pp.se    sigaddset(&sigset, signum);
11479753Sandreas@sandberg.pp.se
11489753Sandreas@sandberg.pp.se    do {
11499753Sandreas@sandberg.pp.se        discardedSignal = sigtimedwait(&sigset, NULL, &timeout);
11509753Sandreas@sandberg.pp.se    } while (discardedSignal == -1 && errno == EINTR);
11519753Sandreas@sandberg.pp.se
11529753Sandreas@sandberg.pp.se    if (discardedSignal == signum)
11539753Sandreas@sandberg.pp.se        return true;
11549753Sandreas@sandberg.pp.se    else if (discardedSignal == -1 && errno == EAGAIN)
11559753Sandreas@sandberg.pp.se        return false;
11569753Sandreas@sandberg.pp.se    else
11579753Sandreas@sandberg.pp.se        panic("Unexpected return value from sigtimedwait: %i (errno: %i)\n",
11589753Sandreas@sandberg.pp.se              discardedSignal, errno);
11599651SAndreas.Sandberg@ARM.com}
11609651SAndreas.Sandberg@ARM.com
11619651SAndreas.Sandberg@ARM.comvoid
11629651SAndreas.Sandberg@ARM.comBaseKvmCPU::setupCounters()
11639651SAndreas.Sandberg@ARM.com{
11649651SAndreas.Sandberg@ARM.com    DPRINTF(Kvm, "Attaching cycle counter...\n");
11659651SAndreas.Sandberg@ARM.com    PerfKvmCounterConfig cfgCycles(PERF_TYPE_HARDWARE,
11669651SAndreas.Sandberg@ARM.com                                PERF_COUNT_HW_CPU_CYCLES);
11679651SAndreas.Sandberg@ARM.com    cfgCycles.disabled(true)
11689651SAndreas.Sandberg@ARM.com        .pinned(true);
11699655SAndreas.Sandberg@ARM.com
11709986Sandreas@sandberg.pp.se    // Try to exclude the host. We set both exclude_hv and
11719986Sandreas@sandberg.pp.se    // exclude_host since different architectures use slightly
11729986Sandreas@sandberg.pp.se    // different APIs in the kernel.
11739986Sandreas@sandberg.pp.se    cfgCycles.exclude_hv(true)
11749986Sandreas@sandberg.pp.se        .exclude_host(true);
11759986Sandreas@sandberg.pp.se
11769655SAndreas.Sandberg@ARM.com    if (perfControlledByTimer) {
11779655SAndreas.Sandberg@ARM.com        // We need to configure the cycles counter to send overflows
11789655SAndreas.Sandberg@ARM.com        // since we are going to use it to trigger timer signals that
11799655SAndreas.Sandberg@ARM.com        // trap back into m5 from KVM. In practice, this means that we
11809655SAndreas.Sandberg@ARM.com        // need to set some non-zero sample period that gets
11819655SAndreas.Sandberg@ARM.com        // overridden when the timer is armed.
11829655SAndreas.Sandberg@ARM.com        cfgCycles.wakeupEvents(1)
11839655SAndreas.Sandberg@ARM.com            .samplePeriod(42);
11849655SAndreas.Sandberg@ARM.com    }
11859655SAndreas.Sandberg@ARM.com
11869651SAndreas.Sandberg@ARM.com    hwCycles.attach(cfgCycles,
11879651SAndreas.Sandberg@ARM.com                    0); // TID (0 => currentThread)
11889651SAndreas.Sandberg@ARM.com
11899892Sandreas@sandberg.pp.se    setupInstCounter();
11909651SAndreas.Sandberg@ARM.com}
11919753Sandreas@sandberg.pp.se
11929753Sandreas@sandberg.pp.sebool
11939753Sandreas@sandberg.pp.seBaseKvmCPU::tryDrain()
11949753Sandreas@sandberg.pp.se{
11959753Sandreas@sandberg.pp.se    if (!drainManager)
11969753Sandreas@sandberg.pp.se        return false;
11979753Sandreas@sandberg.pp.se
11989753Sandreas@sandberg.pp.se    if (!archIsDrained()) {
11999753Sandreas@sandberg.pp.se        DPRINTF(Drain, "tryDrain: Architecture code is not ready.\n");
12009753Sandreas@sandberg.pp.se        return false;
12019753Sandreas@sandberg.pp.se    }
12029753Sandreas@sandberg.pp.se
12039753Sandreas@sandberg.pp.se    if (_status == Idle || _status == Running) {
12049753Sandreas@sandberg.pp.se        DPRINTF(Drain,
12059753Sandreas@sandberg.pp.se                "tryDrain: CPU transitioned into the Idle state, drain done\n");
12069753Sandreas@sandberg.pp.se        drainManager->signalDrainDone();
12079753Sandreas@sandberg.pp.se        drainManager = NULL;
12089753Sandreas@sandberg.pp.se        return true;
12099753Sandreas@sandberg.pp.se    } else {
12109753Sandreas@sandberg.pp.se        DPRINTF(Drain, "tryDrain: CPU not ready.\n");
12119753Sandreas@sandberg.pp.se        return false;
12129753Sandreas@sandberg.pp.se    }
12139753Sandreas@sandberg.pp.se}
12149753Sandreas@sandberg.pp.se
12159753Sandreas@sandberg.pp.sevoid
12169753Sandreas@sandberg.pp.seBaseKvmCPU::ioctlRun()
12179753Sandreas@sandberg.pp.se{
12189753Sandreas@sandberg.pp.se    if (ioctl(KVM_RUN) == -1) {
12199753Sandreas@sandberg.pp.se        if (errno != EINTR)
12209753Sandreas@sandberg.pp.se            panic("KVM: Failed to start virtual CPU (errno: %i)\n",
12219753Sandreas@sandberg.pp.se                  errno);
12229753Sandreas@sandberg.pp.se    }
12239753Sandreas@sandberg.pp.se}
12249892Sandreas@sandberg.pp.se
12259892Sandreas@sandberg.pp.sevoid
12269892Sandreas@sandberg.pp.seBaseKvmCPU::setupInstStop()
12279892Sandreas@sandberg.pp.se{
12289892Sandreas@sandberg.pp.se    if (comInstEventQueue[0]->empty()) {
12299892Sandreas@sandberg.pp.se        setupInstCounter(0);
12309892Sandreas@sandberg.pp.se    } else {
12319892Sandreas@sandberg.pp.se        const uint64_t next(comInstEventQueue[0]->nextTick());
12329892Sandreas@sandberg.pp.se
12339892Sandreas@sandberg.pp.se        assert(next > ctrInsts);
12349892Sandreas@sandberg.pp.se        setupInstCounter(next - ctrInsts);
12359892Sandreas@sandberg.pp.se    }
12369892Sandreas@sandberg.pp.se}
12379892Sandreas@sandberg.pp.se
12389892Sandreas@sandberg.pp.sevoid
12399892Sandreas@sandberg.pp.seBaseKvmCPU::setupInstCounter(uint64_t period)
12409892Sandreas@sandberg.pp.se{
12419892Sandreas@sandberg.pp.se    // No need to do anything if we aren't attaching for the first
12429892Sandreas@sandberg.pp.se    // time or the period isn't changing.
12439892Sandreas@sandberg.pp.se    if (period == activeInstPeriod && hwInstructions.attached())
12449892Sandreas@sandberg.pp.se        return;
12459892Sandreas@sandberg.pp.se
12469892Sandreas@sandberg.pp.se    PerfKvmCounterConfig cfgInstructions(PERF_TYPE_HARDWARE,
12479892Sandreas@sandberg.pp.se                                         PERF_COUNT_HW_INSTRUCTIONS);
12489892Sandreas@sandberg.pp.se
12499986Sandreas@sandberg.pp.se    // Try to exclude the host. We set both exclude_hv and
12509986Sandreas@sandberg.pp.se    // exclude_host since different architectures use slightly
12519986Sandreas@sandberg.pp.se    // different APIs in the kernel.
12529986Sandreas@sandberg.pp.se    cfgInstructions.exclude_hv(true)
12539986Sandreas@sandberg.pp.se        .exclude_host(true);
12549986Sandreas@sandberg.pp.se
12559892Sandreas@sandberg.pp.se    if (period) {
12569892Sandreas@sandberg.pp.se        // Setup a sampling counter if that has been requested.
12579892Sandreas@sandberg.pp.se        cfgInstructions.wakeupEvents(1)
12589892Sandreas@sandberg.pp.se            .samplePeriod(period);
12599892Sandreas@sandberg.pp.se    }
12609892Sandreas@sandberg.pp.se
12619892Sandreas@sandberg.pp.se    // We need to detach and re-attach the counter to reliably change
12629892Sandreas@sandberg.pp.se    // sampling settings. See PerfKvmCounter::period() for details.
12639892Sandreas@sandberg.pp.se    if (hwInstructions.attached())
12649892Sandreas@sandberg.pp.se        hwInstructions.detach();
12659892Sandreas@sandberg.pp.se    assert(hwCycles.attached());
12669892Sandreas@sandberg.pp.se    hwInstructions.attach(cfgInstructions,
12679892Sandreas@sandberg.pp.se                          0, // TID (0 => currentThread)
12689892Sandreas@sandberg.pp.se                          hwCycles);
12699892Sandreas@sandberg.pp.se
12709892Sandreas@sandberg.pp.se    if (period)
127110114Sandreas@sandberg.pp.se        hwInstructions.enableSignals(KVM_KICK_SIGNAL);
12729892Sandreas@sandberg.pp.se
12739892Sandreas@sandberg.pp.se    activeInstPeriod = period;
12749892Sandreas@sandberg.pp.se}
1275