base.cc revision 9892:0063c7dd18ec
13938Ssaidi@eecs.umich.edu/*
212225Sgiacomo.travaglini@arm.com * Copyright (c) 2012 ARM Limited
39419Sandreas.hansson@arm.com * All rights reserved
49419Sandreas.hansson@arm.com *
59419Sandreas.hansson@arm.com * The license below extends only to copyright in the software and shall
69419Sandreas.hansson@arm.com * not be construed as granting a license to any other intellectual
79419Sandreas.hansson@arm.com * property including but not limited to intellectual property relating
89419Sandreas.hansson@arm.com * to a hardware implementation of the functionality of the software
99419Sandreas.hansson@arm.com * licensed hereunder.  You may use the software subject to the license
109419Sandreas.hansson@arm.com * terms below provided that you ensure that this notice is replicated
119419Sandreas.hansson@arm.com * unmodified and in its entirety in all distributions of the software,
129419Sandreas.hansson@arm.com * modified or unmodified, in source code or in binary form.
139419Sandreas.hansson@arm.com *
143938Ssaidi@eecs.umich.edu * Redistribution and use in source and binary forms, with or without
153938Ssaidi@eecs.umich.edu * modification, are permitted provided that the following conditions are
163938Ssaidi@eecs.umich.edu * met: redistributions of source code must retain the above copyright
173938Ssaidi@eecs.umich.edu * notice, this list of conditions and the following disclaimer;
183938Ssaidi@eecs.umich.edu * redistributions in binary form must reproduce the above copyright
193938Ssaidi@eecs.umich.edu * notice, this list of conditions and the following disclaimer in the
203938Ssaidi@eecs.umich.edu * documentation and/or other materials provided with the distribution;
213938Ssaidi@eecs.umich.edu * neither the name of the copyright holders nor the names of its
223938Ssaidi@eecs.umich.edu * contributors may be used to endorse or promote products derived from
233938Ssaidi@eecs.umich.edu * this software without specific prior written permission.
243938Ssaidi@eecs.umich.edu *
253938Ssaidi@eecs.umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
263938Ssaidi@eecs.umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
273938Ssaidi@eecs.umich.edu * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
283938Ssaidi@eecs.umich.edu * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
293938Ssaidi@eecs.umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
303938Ssaidi@eecs.umich.edu * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
313938Ssaidi@eecs.umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
323938Ssaidi@eecs.umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
333938Ssaidi@eecs.umich.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
343938Ssaidi@eecs.umich.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
353938Ssaidi@eecs.umich.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
363938Ssaidi@eecs.umich.edu *
373938Ssaidi@eecs.umich.edu * Authors: Andreas Sandberg
383938Ssaidi@eecs.umich.edu */
393938Ssaidi@eecs.umich.edu
403938Ssaidi@eecs.umich.edu#include <linux/kvm.h>
413938Ssaidi@eecs.umich.edu#include <sys/ioctl.h>
423938Ssaidi@eecs.umich.edu#include <sys/mman.h>
433938Ssaidi@eecs.umich.edu#include <unistd.h>
443938Ssaidi@eecs.umich.edu
453938Ssaidi@eecs.umich.edu#include <cerrno>
4612225Sgiacomo.travaglini@arm.com#include <csignal>
4712225Sgiacomo.travaglini@arm.com#include <ostream>
489419Sandreas.hansson@arm.com
493938Ssaidi@eecs.umich.edu#include "arch/mmapped_ipr.hh"
5010291SAndreas.Sandberg@ARM.com#include "arch/utility.hh"
5110291SAndreas.Sandberg@ARM.com#include "cpu/kvm/base.hh"
5210291SAndreas.Sandberg@ARM.com#include "debug/Checkpoint.hh"
5310291SAndreas.Sandberg@ARM.com#include "debug/Drain.hh"
5410291SAndreas.Sandberg@ARM.com#include "debug/Kvm.hh"
5510291SAndreas.Sandberg@ARM.com#include "debug/KvmIO.hh"
5610686SAndreas.Sandberg@ARM.com#include "debug/KvmRun.hh"
5710686SAndreas.Sandberg@ARM.com#include "params/BaseKvmCPU.hh"
5810291SAndreas.Sandberg@ARM.com#include "sim/process.hh"
5910104Smitch.hayenga@arm.com#include "sim/system.hh"
6010104Smitch.hayenga@arm.com
6110291SAndreas.Sandberg@ARM.com#include <signal.h>
6210104Smitch.hayenga@arm.com
6310291SAndreas.Sandberg@ARM.com/* Used by some KVM macros */
643938Ssaidi@eecs.umich.edu#define PAGE_SIZE pageSize
653938Ssaidi@eecs.umich.edu
6612225Sgiacomo.travaglini@arm.comvolatile bool timerOverflowed = false;
6712225Sgiacomo.travaglini@arm.com
6812225Sgiacomo.travaglini@arm.comBaseKvmCPU::BaseKvmCPU(BaseKvmCPUParams *params)
6912225Sgiacomo.travaglini@arm.com    : BaseCPU(params),
7012225Sgiacomo.travaglini@arm.com      vm(*params->kvmVM),
7112225Sgiacomo.travaglini@arm.com      _status(Idle),
7212225Sgiacomo.travaglini@arm.com      dataPort(name() + ".dcache_port", this),
7312225Sgiacomo.travaglini@arm.com      instPort(name() + ".icache_port", this),
7412225Sgiacomo.travaglini@arm.com      threadContextDirty(true),
7512225Sgiacomo.travaglini@arm.com      kvmStateDirty(false),
7612225Sgiacomo.travaglini@arm.com      vcpuID(vm.allocVCPUID()), vcpuFD(-1), vcpuMMapSize(0),
7712225Sgiacomo.travaglini@arm.com      _kvmRun(NULL), mmioRing(NULL),
7812225Sgiacomo.travaglini@arm.com      pageSize(sysconf(_SC_PAGE_SIZE)),
7912225Sgiacomo.travaglini@arm.com      tickEvent(*this),
8012225Sgiacomo.travaglini@arm.com      activeInstPeriod(0),
8112225Sgiacomo.travaglini@arm.com      perfControlledByTimer(params->usePerfOverflow),
8212225Sgiacomo.travaglini@arm.com      hostFreq(params->hostFreq),
8312225Sgiacomo.travaglini@arm.com      hostFactor(params->hostFactor),
8412225Sgiacomo.travaglini@arm.com      drainManager(NULL),
8512225Sgiacomo.travaglini@arm.com      ctrInsts(0)
8612225Sgiacomo.travaglini@arm.com{
8712225Sgiacomo.travaglini@arm.com    if (pageSize == -1)
8812225Sgiacomo.travaglini@arm.com        panic("KVM: Failed to determine host page size (%i)\n",
8912225Sgiacomo.travaglini@arm.com              errno);
903938Ssaidi@eecs.umich.edu
91    thread = new SimpleThread(this, 0, params->system,
92                              params->itb, params->dtb, params->isa[0]);
93    thread->setStatus(ThreadContext::Halted);
94    tc = thread->getTC();
95    threadContexts.push_back(tc);
96
97    setupCounters();
98
99    if (params->usePerfOverflow)
100        runTimer.reset(new PerfKvmTimer(hwCycles,
101                                        KVM_TIMER_SIGNAL,
102                                        params->hostFactor,
103                                        params->hostFreq));
104    else
105        runTimer.reset(new PosixKvmTimer(KVM_TIMER_SIGNAL, CLOCK_MONOTONIC,
106                                         params->hostFactor,
107                                         params->hostFreq));
108}
109
110BaseKvmCPU::~BaseKvmCPU()
111{
112    if (_kvmRun)
113        munmap(_kvmRun, vcpuMMapSize);
114    close(vcpuFD);
115}
116
117void
118BaseKvmCPU::init()
119{
120    BaseCPU::init();
121
122    if (numThreads != 1)
123        fatal("KVM: Multithreading not supported");
124
125    tc->initMemProxies(tc);
126
127    // initialize CPU, including PC
128    if (FullSystem && !switchedOut())
129        TheISA::initCPU(tc, tc->contextId());
130
131    mmio_req.setThreadContext(tc->contextId(), 0);
132}
133
134void
135BaseKvmCPU::startup()
136{
137    const BaseKvmCPUParams * const p(
138        dynamic_cast<const BaseKvmCPUParams *>(params()));
139
140    Kvm &kvm(vm.kvm);
141
142    BaseCPU::startup();
143
144    assert(vcpuFD == -1);
145
146    // Tell the VM that a CPU is about to start.
147    vm.cpuStartup();
148
149    // We can't initialize KVM CPUs in BaseKvmCPU::init() since we are
150    // not guaranteed that the parent KVM VM has initialized at that
151    // point. Initialize virtual CPUs here instead.
152    vcpuFD = vm.createVCPU(vcpuID);
153
154    // Setup signal handlers. This has to be done after the vCPU is
155    // created since it manipulates the vCPU signal mask.
156    setupSignalHandler();
157
158    // Map the KVM run structure */
159    vcpuMMapSize = kvm.getVCPUMMapSize();
160    _kvmRun = (struct kvm_run *)mmap(0, vcpuMMapSize,
161                                     PROT_READ | PROT_WRITE, MAP_SHARED,
162                                     vcpuFD, 0);
163    if (_kvmRun == MAP_FAILED)
164        panic("KVM: Failed to map run data structure\n");
165
166    // Setup a pointer to the MMIO ring buffer if coalesced MMIO is
167    // available. The offset into the KVM's communication page is
168    // provided by the coalesced MMIO capability.
169    int mmioOffset(kvm.capCoalescedMMIO());
170    if (!p->useCoalescedMMIO) {
171        inform("KVM: Coalesced MMIO disabled by config.\n");
172    } else if (mmioOffset) {
173        inform("KVM: Coalesced IO available\n");
174        mmioRing = (struct kvm_coalesced_mmio_ring *)(
175            (char *)_kvmRun + (mmioOffset * pageSize));
176    } else {
177        inform("KVM: Coalesced not supported by host OS\n");
178    }
179
180    thread->startup();
181}
182
183void
184BaseKvmCPU::regStats()
185{
186    using namespace Stats;
187
188    BaseCPU::regStats();
189
190    numInsts
191        .name(name() + ".committedInsts")
192        .desc("Number of instructions committed")
193        ;
194
195    numVMExits
196        .name(name() + ".numVMExits")
197        .desc("total number of KVM exits")
198        ;
199
200    numVMHalfEntries
201        .name(name() + ".numVMHalfEntries")
202        .desc("number of KVM entries to finalize pending operations")
203        ;
204
205    numExitSignal
206        .name(name() + ".numExitSignal")
207        .desc("exits due to signal delivery")
208        ;
209
210    numMMIO
211        .name(name() + ".numMMIO")
212        .desc("number of VM exits due to memory mapped IO")
213        ;
214
215    numCoalescedMMIO
216        .name(name() + ".numCoalescedMMIO")
217        .desc("number of coalesced memory mapped IO requests")
218        ;
219
220    numIO
221        .name(name() + ".numIO")
222        .desc("number of VM exits due to legacy IO")
223        ;
224
225    numHalt
226        .name(name() + ".numHalt")
227        .desc("number of VM exits due to wait for interrupt instructions")
228        ;
229
230    numInterrupts
231        .name(name() + ".numInterrupts")
232        .desc("number of interrupts delivered")
233        ;
234
235    numHypercalls
236        .name(name() + ".numHypercalls")
237        .desc("number of hypercalls")
238        ;
239}
240
241void
242BaseKvmCPU::serializeThread(std::ostream &os, ThreadID tid)
243{
244    if (DTRACE(Checkpoint)) {
245        DPRINTF(Checkpoint, "KVM: Serializing thread %i:\n", tid);
246        dump();
247    }
248
249    assert(tid == 0);
250    assert(_status == Idle);
251    thread->serialize(os);
252}
253
254void
255BaseKvmCPU::unserializeThread(Checkpoint *cp, const std::string &section,
256                              ThreadID tid)
257{
258    DPRINTF(Checkpoint, "KVM: Unserialize thread %i:\n", tid);
259
260    assert(tid == 0);
261    assert(_status == Idle);
262    thread->unserialize(cp, section);
263    threadContextDirty = true;
264}
265
266unsigned int
267BaseKvmCPU::drain(DrainManager *dm)
268{
269    if (switchedOut())
270        return 0;
271
272    DPRINTF(Drain, "BaseKvmCPU::drain\n");
273    switch (_status) {
274      case Running:
275        // The base KVM code is normally ready when it is in the
276        // Running state, but the architecture specific code might be
277        // of a different opinion. This may happen when the CPU been
278        // notified of an event that hasn't been accepted by the vCPU
279        // yet.
280        if (!archIsDrained()) {
281            drainManager = dm;
282            return 1;
283        }
284
285        // The state of the CPU is consistent, so we don't need to do
286        // anything special to drain it. We simply de-schedule the
287        // tick event and enter the Idle state to prevent nasty things
288        // like MMIOs from happening.
289        if (tickEvent.scheduled())
290            deschedule(tickEvent);
291        _status = Idle;
292
293        /** FALLTHROUGH */
294      case Idle:
295        // Idle, no need to drain
296        assert(!tickEvent.scheduled());
297
298        // Sync the thread context here since we'll need it when we
299        // switch CPUs or checkpoint the CPU.
300        syncThreadContext();
301
302        return 0;
303
304      case RunningServiceCompletion:
305        // The CPU has just requested a service that was handled in
306        // the RunningService state, but the results have still not
307        // been reported to the CPU. Now, we /could/ probably just
308        // update the register state ourselves instead of letting KVM
309        // handle it, but that would be tricky. Instead, we enter KVM
310        // and let it do its stuff.
311        drainManager = dm;
312
313        DPRINTF(Drain, "KVM CPU is waiting for service completion, "
314                "requesting drain.\n");
315        return 1;
316
317      case RunningService:
318        // We need to drain since the CPU is waiting for service (e.g., MMIOs)
319        drainManager = dm;
320
321        DPRINTF(Drain, "KVM CPU is waiting for service, requesting drain.\n");
322        return 1;
323
324      default:
325        panic("KVM: Unhandled CPU state in drain()\n");
326        return 0;
327    }
328}
329
330void
331BaseKvmCPU::drainResume()
332{
333    assert(!tickEvent.scheduled());
334
335    // We might have been switched out. In that case, we don't need to
336    // do anything.
337    if (switchedOut())
338        return;
339
340    DPRINTF(Kvm, "drainResume\n");
341    verifyMemoryMode();
342
343    // The tick event is de-scheduled as a part of the draining
344    // process. Re-schedule it if the thread context is active.
345    if (tc->status() == ThreadContext::Active) {
346        schedule(tickEvent, nextCycle());
347        _status = Running;
348    } else {
349        _status = Idle;
350    }
351}
352
353void
354BaseKvmCPU::switchOut()
355{
356    DPRINTF(Kvm, "switchOut\n");
357
358    BaseCPU::switchOut();
359
360    // We should have drained prior to executing a switchOut, which
361    // means that the tick event shouldn't be scheduled and the CPU is
362    // idle.
363    assert(!tickEvent.scheduled());
364    assert(_status == Idle);
365}
366
367void
368BaseKvmCPU::takeOverFrom(BaseCPU *cpu)
369{
370    DPRINTF(Kvm, "takeOverFrom\n");
371
372    BaseCPU::takeOverFrom(cpu);
373
374    // We should have drained prior to executing a switchOut, which
375    // means that the tick event shouldn't be scheduled and the CPU is
376    // idle.
377    assert(!tickEvent.scheduled());
378    assert(_status == Idle);
379    assert(threadContexts.size() == 1);
380
381    // Force an update of the KVM state here instead of flagging the
382    // TC as dirty. This is not ideal from a performance point of
383    // view, but it makes debugging easier as it allows meaningful KVM
384    // state to be dumped before and after a takeover.
385    updateKvmState();
386    threadContextDirty = false;
387}
388
389void
390BaseKvmCPU::verifyMemoryMode() const
391{
392    if (!(system->isAtomicMode() && system->bypassCaches())) {
393        fatal("The KVM-based CPUs requires the memory system to be in the "
394              "'atomic_noncaching' mode.\n");
395    }
396}
397
398void
399BaseKvmCPU::wakeup()
400{
401    DPRINTF(Kvm, "wakeup()\n");
402
403    if (thread->status() != ThreadContext::Suspended)
404        return;
405
406    thread->activate();
407}
408
409void
410BaseKvmCPU::activateContext(ThreadID thread_num, Cycles delay)
411{
412    DPRINTF(Kvm, "ActivateContext %d (%d cycles)\n", thread_num, delay);
413
414    assert(thread_num == 0);
415    assert(thread);
416
417    assert(_status == Idle);
418    assert(!tickEvent.scheduled());
419
420    numCycles += ticksToCycles(thread->lastActivate - thread->lastSuspend);
421
422    schedule(tickEvent, clockEdge(delay));
423    _status = Running;
424}
425
426
427void
428BaseKvmCPU::suspendContext(ThreadID thread_num)
429{
430    DPRINTF(Kvm, "SuspendContext %d\n", thread_num);
431
432    assert(thread_num == 0);
433    assert(thread);
434
435    if (_status == Idle)
436        return;
437
438    assert(_status == Running);
439
440    // The tick event may no be scheduled if the quest has requested
441    // the monitor to wait for interrupts. The normal CPU models can
442    // get their tick events descheduled by quiesce instructions, but
443    // that can't happen here.
444    if (tickEvent.scheduled())
445        deschedule(tickEvent);
446
447    _status = Idle;
448}
449
450void
451BaseKvmCPU::deallocateContext(ThreadID thread_num)
452{
453    // for now, these are equivalent
454    suspendContext(thread_num);
455}
456
457void
458BaseKvmCPU::haltContext(ThreadID thread_num)
459{
460    // for now, these are equivalent
461    suspendContext(thread_num);
462}
463
464ThreadContext *
465BaseKvmCPU::getContext(int tn)
466{
467    assert(tn == 0);
468    syncThreadContext();
469    return tc;
470}
471
472
473Counter
474BaseKvmCPU::totalInsts() const
475{
476    return ctrInsts;
477}
478
479Counter
480BaseKvmCPU::totalOps() const
481{
482    hack_once("Pretending totalOps is equivalent to totalInsts()\n");
483    return ctrInsts;
484}
485
486void
487BaseKvmCPU::dump()
488{
489    inform("State dumping not implemented.");
490}
491
492void
493BaseKvmCPU::tick()
494{
495    Tick delay(0);
496    assert(_status != Idle);
497
498    switch (_status) {
499      case RunningService:
500        // handleKvmExit() will determine the next state of the CPU
501        delay = handleKvmExit();
502
503        if (tryDrain())
504            _status = Idle;
505        break;
506
507      case RunningServiceCompletion:
508      case Running: {
509          Tick ticksToExecute(mainEventQueue.nextTick() - curTick());
510
511          // We might need to update the KVM state.
512          syncKvmState();
513
514          // Setup any pending instruction count breakpoints using
515          // PerfEvent.
516          setupInstStop();
517
518          DPRINTF(KvmRun, "Entering KVM...\n");
519          if (drainManager) {
520              // Force an immediate exit from KVM after completing
521              // pending operations. The architecture-specific code
522              // takes care to run until it is in a state where it can
523              // safely be drained.
524              delay = kvmRunDrain();
525          } else {
526              delay = kvmRun(ticksToExecute);
527          }
528
529          // Entering into KVM implies that we'll have to reload the thread
530          // context from KVM if we want to access it. Flag the KVM state as
531          // dirty with respect to the cached thread context.
532          kvmStateDirty = true;
533
534          // Enter into the RunningService state unless the
535          // simulation was stopped by a timer.
536          if (_kvmRun->exit_reason !=  KVM_EXIT_INTR) {
537              _status = RunningService;
538          } else {
539              ++numExitSignal;
540              _status = Running;
541          }
542
543          if (tryDrain())
544              _status = Idle;
545      } break;
546
547      default:
548        panic("BaseKvmCPU entered tick() in an illegal state (%i)\n",
549              _status);
550    }
551
552    // Schedule a new tick if we are still running
553    if (_status != Idle)
554        schedule(tickEvent, clockEdge(ticksToCycles(delay)));
555}
556
557Tick
558BaseKvmCPU::kvmRunDrain()
559{
560    // By default, the only thing we need to drain is a pending IO
561    // operation which assumes that we are in the
562    // RunningServiceCompletion state.
563    assert(_status == RunningServiceCompletion);
564
565    // Deliver the data from the pending IO operation and immediately
566    // exit.
567    return kvmRun(0);
568}
569
570uint64_t
571BaseKvmCPU::getHostCycles() const
572{
573    return hwCycles.read();
574}
575
576Tick
577BaseKvmCPU::kvmRun(Tick ticks)
578{
579    Tick ticksExecuted;
580    DPRINTF(KvmRun, "KVM: Executing for %i ticks\n", ticks);
581    timerOverflowed = false;
582
583    if (ticks == 0) {
584        // Settings ticks == 0 is a special case which causes an entry
585        // into KVM that finishes pending operations (e.g., IO) and
586        // then immediately exits.
587        DPRINTF(KvmRun, "KVM: Delivering IO without full guest entry\n");
588
589        ++numVMHalfEntries;
590
591        // This signal is always masked while we are executing in gem5
592        // and gets unmasked temporarily as soon as we enter into
593        // KVM. See setSignalMask() and setupSignalHandler().
594        raise(KVM_TIMER_SIGNAL);
595
596        // Enter into KVM. KVM will check for signals after completing
597        // pending operations (IO). Since the KVM_TIMER_SIGNAL is
598        // pending, this forces an immediate exit into gem5 again. We
599        // don't bother to setup timers since this shouldn't actually
600        // execute any code in the guest.
601        ioctlRun();
602
603        // We always execute at least one cycle to prevent the
604        // BaseKvmCPU::tick() to be rescheduled on the same tick
605        // twice.
606        ticksExecuted = clockPeriod();
607    } else {
608        if (ticks < runTimer->resolution()) {
609            DPRINTF(KvmRun, "KVM: Adjusting tick count (%i -> %i)\n",
610                    ticks, runTimer->resolution());
611            ticks = runTimer->resolution();
612        }
613
614        // Get hardware statistics after synchronizing contexts. The KVM
615        // state update might affect guest cycle counters.
616        uint64_t baseCycles(getHostCycles());
617        uint64_t baseInstrs(hwInstructions.read());
618
619        // Arm the run timer and start the cycle timer if it isn't
620        // controlled by the overflow timer. Starting/stopping the cycle
621        // timer automatically starts the other perf timers as they are in
622        // the same counter group.
623        runTimer->arm(ticks);
624        if (!perfControlledByTimer)
625            hwCycles.start();
626
627        ioctlRun();
628
629        runTimer->disarm();
630        if (!perfControlledByTimer)
631            hwCycles.stop();
632
633        // The timer signal may have been delivered after we exited
634        // from KVM. It will be pending in that case since it is
635        // masked when we aren't executing in KVM. Discard it to make
636        // sure we don't deliver it immediately next time we try to
637        // enter into KVM.
638        discardPendingSignal(KVM_TIMER_SIGNAL);
639        discardPendingSignal(KVM_INST_SIGNAL);
640
641        const uint64_t hostCyclesExecuted(getHostCycles() - baseCycles);
642        const uint64_t simCyclesExecuted(hostCyclesExecuted * hostFactor);
643        const uint64_t instsExecuted(hwInstructions.read() - baseInstrs);
644        ticksExecuted = runTimer->ticksFromHostCycles(hostCyclesExecuted);
645
646        if (ticksExecuted < ticks &&
647            timerOverflowed &&
648            _kvmRun->exit_reason == KVM_EXIT_INTR) {
649            // TODO: We should probably do something clever here...
650            warn("KVM: Early timer event, requested %i ticks but got %i ticks.\n",
651                 ticks, ticksExecuted);
652        }
653
654        /* Update statistics */
655        numCycles += simCyclesExecuted;;
656        numInsts += instsExecuted;
657        ctrInsts += instsExecuted;
658        system->totalNumInsts += instsExecuted;
659
660        DPRINTF(KvmRun,
661                "KVM: Executed %i instructions in %i cycles "
662                "(%i ticks, sim cycles: %i).\n",
663                instsExecuted, hostCyclesExecuted, ticksExecuted, simCyclesExecuted);
664    }
665
666    ++numVMExits;
667
668    return ticksExecuted + flushCoalescedMMIO();
669}
670
671void
672BaseKvmCPU::kvmNonMaskableInterrupt()
673{
674    ++numInterrupts;
675    if (ioctl(KVM_NMI) == -1)
676        panic("KVM: Failed to deliver NMI to virtual CPU\n");
677}
678
679void
680BaseKvmCPU::kvmInterrupt(const struct kvm_interrupt &interrupt)
681{
682    ++numInterrupts;
683    if (ioctl(KVM_INTERRUPT, (void *)&interrupt) == -1)
684        panic("KVM: Failed to deliver interrupt to virtual CPU\n");
685}
686
687void
688BaseKvmCPU::getRegisters(struct kvm_regs &regs) const
689{
690    if (ioctl(KVM_GET_REGS, &regs) == -1)
691        panic("KVM: Failed to get guest registers\n");
692}
693
694void
695BaseKvmCPU::setRegisters(const struct kvm_regs &regs)
696{
697    if (ioctl(KVM_SET_REGS, (void *)&regs) == -1)
698        panic("KVM: Failed to set guest registers\n");
699}
700
701void
702BaseKvmCPU::getSpecialRegisters(struct kvm_sregs &regs) const
703{
704    if (ioctl(KVM_GET_SREGS, &regs) == -1)
705        panic("KVM: Failed to get guest special registers\n");
706}
707
708void
709BaseKvmCPU::setSpecialRegisters(const struct kvm_sregs &regs)
710{
711    if (ioctl(KVM_SET_SREGS, (void *)&regs) == -1)
712        panic("KVM: Failed to set guest special registers\n");
713}
714
715void
716BaseKvmCPU::getFPUState(struct kvm_fpu &state) const
717{
718    if (ioctl(KVM_GET_FPU, &state) == -1)
719        panic("KVM: Failed to get guest FPU state\n");
720}
721
722void
723BaseKvmCPU::setFPUState(const struct kvm_fpu &state)
724{
725    if (ioctl(KVM_SET_FPU, (void *)&state) == -1)
726        panic("KVM: Failed to set guest FPU state\n");
727}
728
729
730void
731BaseKvmCPU::setOneReg(uint64_t id, const void *addr)
732{
733#ifdef KVM_SET_ONE_REG
734    struct kvm_one_reg reg;
735    reg.id = id;
736    reg.addr = (uint64_t)addr;
737
738    if (ioctl(KVM_SET_ONE_REG, &reg) == -1) {
739        panic("KVM: Failed to set register (0x%x) value (errno: %i)\n",
740              id, errno);
741    }
742#else
743    panic("KVM_SET_ONE_REG is unsupported on this platform.\n");
744#endif
745}
746
747void
748BaseKvmCPU::getOneReg(uint64_t id, void *addr) const
749{
750#ifdef KVM_GET_ONE_REG
751    struct kvm_one_reg reg;
752    reg.id = id;
753    reg.addr = (uint64_t)addr;
754
755    if (ioctl(KVM_GET_ONE_REG, &reg) == -1) {
756        panic("KVM: Failed to get register (0x%x) value (errno: %i)\n",
757              id, errno);
758    }
759#else
760    panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
761#endif
762}
763
764std::string
765BaseKvmCPU::getAndFormatOneReg(uint64_t id) const
766{
767#ifdef KVM_GET_ONE_REG
768    std::ostringstream ss;
769
770    ss.setf(std::ios::hex, std::ios::basefield);
771    ss.setf(std::ios::showbase);
772#define HANDLE_INTTYPE(len)                      \
773    case KVM_REG_SIZE_U ## len: {                \
774        uint ## len ## _t value;                 \
775        getOneReg(id, &value);                   \
776        ss << value;                             \
777    }  break
778
779#define HANDLE_ARRAY(len)                       \
780    case KVM_REG_SIZE_U ## len: {               \
781        uint8_t value[len / 8];                 \
782        getOneReg(id, value);                   \
783        ss << "[" << value[0];                  \
784        for (int i = 1; i < len  / 8; ++i)      \
785            ss << ", " << value[i];             \
786        ss << "]";                              \
787      } break
788
789    switch (id & KVM_REG_SIZE_MASK) {
790        HANDLE_INTTYPE(8);
791        HANDLE_INTTYPE(16);
792        HANDLE_INTTYPE(32);
793        HANDLE_INTTYPE(64);
794        HANDLE_ARRAY(128);
795        HANDLE_ARRAY(256);
796        HANDLE_ARRAY(512);
797        HANDLE_ARRAY(1024);
798      default:
799        ss << "??";
800    }
801
802#undef HANDLE_INTTYPE
803#undef HANDLE_ARRAY
804
805    return ss.str();
806#else
807    panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
808#endif
809}
810
811void
812BaseKvmCPU::syncThreadContext()
813{
814    if (!kvmStateDirty)
815        return;
816
817    assert(!threadContextDirty);
818
819    updateThreadContext();
820    kvmStateDirty = false;
821}
822
823void
824BaseKvmCPU::syncKvmState()
825{
826    if (!threadContextDirty)
827        return;
828
829    assert(!kvmStateDirty);
830
831    updateKvmState();
832    threadContextDirty = false;
833}
834
835Tick
836BaseKvmCPU::handleKvmExit()
837{
838    DPRINTF(KvmRun, "handleKvmExit (exit_reason: %i)\n", _kvmRun->exit_reason);
839    assert(_status == RunningService);
840
841    // Switch into the running state by default. Individual handlers
842    // can override this.
843    _status = Running;
844    switch (_kvmRun->exit_reason) {
845      case KVM_EXIT_UNKNOWN:
846        return handleKvmExitUnknown();
847
848      case KVM_EXIT_EXCEPTION:
849        return handleKvmExitException();
850
851      case KVM_EXIT_IO:
852        _status = RunningServiceCompletion;
853        ++numIO;
854        return handleKvmExitIO();
855
856      case KVM_EXIT_HYPERCALL:
857        ++numHypercalls;
858        return handleKvmExitHypercall();
859
860      case KVM_EXIT_HLT:
861        /* The guest has halted and is waiting for interrupts */
862        DPRINTF(Kvm, "handleKvmExitHalt\n");
863        ++numHalt;
864
865        // Suspend the thread until the next interrupt arrives
866        thread->suspend();
867
868        // This is actually ignored since the thread is suspended.
869        return 0;
870
871      case KVM_EXIT_MMIO:
872        _status = RunningServiceCompletion;
873        /* Service memory mapped IO requests */
874        DPRINTF(KvmIO, "KVM: Handling MMIO (w: %u, addr: 0x%x, len: %u)\n",
875                _kvmRun->mmio.is_write,
876                _kvmRun->mmio.phys_addr, _kvmRun->mmio.len);
877
878        ++numMMIO;
879        return doMMIOAccess(_kvmRun->mmio.phys_addr, _kvmRun->mmio.data,
880                            _kvmRun->mmio.len, _kvmRun->mmio.is_write);
881
882      case KVM_EXIT_IRQ_WINDOW_OPEN:
883        return handleKvmExitIRQWindowOpen();
884
885      case KVM_EXIT_FAIL_ENTRY:
886        return handleKvmExitFailEntry();
887
888      case KVM_EXIT_INTR:
889        /* KVM was interrupted by a signal, restart it in the next
890         * tick. */
891        return 0;
892
893      case KVM_EXIT_INTERNAL_ERROR:
894        panic("KVM: Internal error (suberror: %u)\n",
895              _kvmRun->internal.suberror);
896
897      default:
898        dump();
899        panic("KVM: Unexpected exit (exit_reason: %u)\n", _kvmRun->exit_reason);
900    }
901}
902
903Tick
904BaseKvmCPU::handleKvmExitIO()
905{
906    panic("KVM: Unhandled guest IO (dir: %i, size: %i, port: 0x%x, count: %i)\n",
907          _kvmRun->io.direction, _kvmRun->io.size,
908          _kvmRun->io.port, _kvmRun->io.count);
909}
910
911Tick
912BaseKvmCPU::handleKvmExitHypercall()
913{
914    panic("KVM: Unhandled hypercall\n");
915}
916
917Tick
918BaseKvmCPU::handleKvmExitIRQWindowOpen()
919{
920    warn("KVM: Unhandled IRQ window.\n");
921    return 0;
922}
923
924
925Tick
926BaseKvmCPU::handleKvmExitUnknown()
927{
928    dump();
929    panic("KVM: Unknown error when starting vCPU (hw reason: 0x%llx)\n",
930          _kvmRun->hw.hardware_exit_reason);
931}
932
933Tick
934BaseKvmCPU::handleKvmExitException()
935{
936    dump();
937    panic("KVM: Got exception when starting vCPU "
938          "(exception: %u, error_code: %u)\n",
939          _kvmRun->ex.exception, _kvmRun->ex.error_code);
940}
941
942Tick
943BaseKvmCPU::handleKvmExitFailEntry()
944{
945    dump();
946    panic("KVM: Failed to enter virtualized mode (hw reason: 0x%llx)\n",
947          _kvmRun->fail_entry.hardware_entry_failure_reason);
948}
949
950Tick
951BaseKvmCPU::doMMIOAccess(Addr paddr, void *data, int size, bool write)
952{
953    ThreadContext *tc(thread->getTC());
954    syncThreadContext();
955
956    mmio_req.setPhys(paddr, size, Request::UNCACHEABLE, dataMasterId());
957    // Some architectures do need to massage physical addresses a bit
958    // before they are inserted into the memory system. This enables
959    // APIC accesses on x86 and m5ops where supported through a MMIO
960    // interface.
961    BaseTLB::Mode tlb_mode(write ? BaseTLB::Write : BaseTLB::Read);
962    Fault fault(tc->getDTBPtr()->finalizePhysical(&mmio_req, tc, tlb_mode));
963    if (fault != NoFault)
964        warn("Finalization of MMIO address failed: %s\n", fault->name());
965
966
967    const MemCmd cmd(write ? MemCmd::WriteReq : MemCmd::ReadReq);
968    Packet pkt(&mmio_req, cmd);
969    pkt.dataStatic(data);
970
971    if (mmio_req.isMmappedIpr()) {
972        const Cycles ipr_delay(write ?
973                             TheISA::handleIprWrite(tc, &pkt) :
974                             TheISA::handleIprRead(tc, &pkt));
975        return clockEdge(ipr_delay);
976    } else {
977        return dataPort.sendAtomic(&pkt);
978    }
979}
980
981void
982BaseKvmCPU::setSignalMask(const sigset_t *mask)
983{
984    std::unique_ptr<struct kvm_signal_mask> kvm_mask;
985
986    if (mask) {
987        kvm_mask.reset((struct kvm_signal_mask *)operator new(
988                           sizeof(struct kvm_signal_mask) + sizeof(*mask)));
989        // The kernel and the user-space headers have different ideas
990        // about the size of sigset_t. This seems like a massive hack,
991        // but is actually what qemu does.
992        assert(sizeof(*mask) >= 8);
993        kvm_mask->len = 8;
994        memcpy(kvm_mask->sigset, mask, kvm_mask->len);
995    }
996
997    if (ioctl(KVM_SET_SIGNAL_MASK, (void *)kvm_mask.get()) == -1)
998        panic("KVM: Failed to set vCPU signal mask (errno: %i)\n",
999              errno);
1000}
1001
1002int
1003BaseKvmCPU::ioctl(int request, long p1) const
1004{
1005    if (vcpuFD == -1)
1006        panic("KVM: CPU ioctl called before initialization\n");
1007
1008    return ::ioctl(vcpuFD, request, p1);
1009}
1010
1011Tick
1012BaseKvmCPU::flushCoalescedMMIO()
1013{
1014    if (!mmioRing)
1015        return 0;
1016
1017    DPRINTF(KvmIO, "KVM: Flushing the coalesced MMIO ring buffer\n");
1018
1019    // TODO: We might need to do synchronization when we start to
1020    // support multiple CPUs
1021    Tick ticks(0);
1022    while (mmioRing->first != mmioRing->last) {
1023        struct kvm_coalesced_mmio &ent(
1024            mmioRing->coalesced_mmio[mmioRing->first]);
1025
1026        DPRINTF(KvmIO, "KVM: Handling coalesced MMIO (addr: 0x%x, len: %u)\n",
1027                ent.phys_addr, ent.len);
1028
1029        ++numCoalescedMMIO;
1030        ticks += doMMIOAccess(ent.phys_addr, ent.data, ent.len, true);
1031
1032        mmioRing->first = (mmioRing->first + 1) % KVM_COALESCED_MMIO_MAX;
1033    }
1034
1035    return ticks;
1036}
1037
1038/**
1039 * Cycle timer overflow when running in KVM. Forces the KVM syscall to
1040 * exit with EINTR and allows us to run the event queue.
1041 */
1042static void
1043onTimerOverflow(int signo, siginfo_t *si, void *data)
1044{
1045    timerOverflowed = true;
1046}
1047
1048/**
1049 * Instruction counter overflow when running in KVM. Forces the KVM
1050 * syscall to exit with EINTR and allows us to handle instruction
1051 * count events.
1052 */
1053static void
1054onInstEvent(int signo, siginfo_t *si, void *data)
1055{
1056}
1057
1058void
1059BaseKvmCPU::setupSignalHandler()
1060{
1061    struct sigaction sa;
1062
1063    memset(&sa, 0, sizeof(sa));
1064    sa.sa_sigaction = onTimerOverflow;
1065    sa.sa_flags = SA_SIGINFO | SA_RESTART;
1066    if (sigaction(KVM_TIMER_SIGNAL, &sa, NULL) == -1)
1067        panic("KVM: Failed to setup vCPU timer signal handler\n");
1068
1069    memset(&sa, 0, sizeof(sa));
1070    sa.sa_sigaction = onInstEvent;
1071    sa.sa_flags = SA_SIGINFO | SA_RESTART;
1072    if (sigaction(KVM_INST_SIGNAL, &sa, NULL) == -1)
1073        panic("KVM: Failed to setup vCPU instruction signal handler\n");
1074
1075    sigset_t sigset;
1076    if (sigprocmask(SIG_BLOCK, NULL, &sigset) == -1)
1077        panic("KVM: Failed get signal mask\n");
1078
1079    // Request KVM to setup the same signal mask as we're currently
1080    // running with. We'll sometimes need to mask the KVM_TIMER_SIGNAL
1081    // to cause immediate exits from KVM after servicing IO
1082    // requests. See kvmRun().
1083    setSignalMask(&sigset);
1084
1085    // Mask our control signals so they aren't delivered unless we're
1086    // actually executing inside KVM.
1087    sigaddset(&sigset, KVM_TIMER_SIGNAL);
1088    sigaddset(&sigset, KVM_INST_SIGNAL);
1089    if (sigprocmask(SIG_SETMASK, &sigset, NULL) == -1)
1090        panic("KVM: Failed mask the KVM control signals\n");
1091}
1092
1093bool
1094BaseKvmCPU::discardPendingSignal(int signum) const
1095{
1096    int discardedSignal;
1097
1098    // Setting the timeout to zero causes sigtimedwait to return
1099    // immediately.
1100    struct timespec timeout;
1101    timeout.tv_sec = 0;
1102    timeout.tv_nsec = 0;
1103
1104    sigset_t sigset;
1105    sigemptyset(&sigset);
1106    sigaddset(&sigset, signum);
1107
1108    do {
1109        discardedSignal = sigtimedwait(&sigset, NULL, &timeout);
1110    } while (discardedSignal == -1 && errno == EINTR);
1111
1112    if (discardedSignal == signum)
1113        return true;
1114    else if (discardedSignal == -1 && errno == EAGAIN)
1115        return false;
1116    else
1117        panic("Unexpected return value from sigtimedwait: %i (errno: %i)\n",
1118              discardedSignal, errno);
1119}
1120
1121void
1122BaseKvmCPU::setupCounters()
1123{
1124    DPRINTF(Kvm, "Attaching cycle counter...\n");
1125    PerfKvmCounterConfig cfgCycles(PERF_TYPE_HARDWARE,
1126                                PERF_COUNT_HW_CPU_CYCLES);
1127    cfgCycles.disabled(true)
1128        .pinned(true);
1129
1130    if (perfControlledByTimer) {
1131        // We need to configure the cycles counter to send overflows
1132        // since we are going to use it to trigger timer signals that
1133        // trap back into m5 from KVM. In practice, this means that we
1134        // need to set some non-zero sample period that gets
1135        // overridden when the timer is armed.
1136        cfgCycles.wakeupEvents(1)
1137            .samplePeriod(42);
1138    }
1139
1140    hwCycles.attach(cfgCycles,
1141                    0); // TID (0 => currentThread)
1142
1143    setupInstCounter();
1144}
1145
1146bool
1147BaseKvmCPU::tryDrain()
1148{
1149    if (!drainManager)
1150        return false;
1151
1152    if (!archIsDrained()) {
1153        DPRINTF(Drain, "tryDrain: Architecture code is not ready.\n");
1154        return false;
1155    }
1156
1157    if (_status == Idle || _status == Running) {
1158        DPRINTF(Drain,
1159                "tryDrain: CPU transitioned into the Idle state, drain done\n");
1160        drainManager->signalDrainDone();
1161        drainManager = NULL;
1162        return true;
1163    } else {
1164        DPRINTF(Drain, "tryDrain: CPU not ready.\n");
1165        return false;
1166    }
1167}
1168
1169void
1170BaseKvmCPU::ioctlRun()
1171{
1172    if (ioctl(KVM_RUN) == -1) {
1173        if (errno != EINTR)
1174            panic("KVM: Failed to start virtual CPU (errno: %i)\n",
1175                  errno);
1176    }
1177}
1178
1179void
1180BaseKvmCPU::setupInstStop()
1181{
1182
1183    if (comInstEventQueue[0]->empty()) {
1184        setupInstCounter(0);
1185    } else {
1186        const uint64_t next(comInstEventQueue[0]->nextTick());
1187
1188        assert(next > ctrInsts);
1189        setupInstCounter(next - ctrInsts);
1190    }
1191}
1192
1193void
1194BaseKvmCPU::setupInstCounter(uint64_t period)
1195{
1196    // No need to do anything if we aren't attaching for the first
1197    // time or the period isn't changing.
1198    if (period == activeInstPeriod && hwInstructions.attached())
1199        return;
1200
1201    PerfKvmCounterConfig cfgInstructions(PERF_TYPE_HARDWARE,
1202                                         PERF_COUNT_HW_INSTRUCTIONS);
1203
1204    if (period) {
1205        // Setup a sampling counter if that has been requested.
1206        cfgInstructions.wakeupEvents(1)
1207            .samplePeriod(period);
1208    }
1209
1210    // We need to detach and re-attach the counter to reliably change
1211    // sampling settings. See PerfKvmCounter::period() for details.
1212    if (hwInstructions.attached())
1213        hwInstructions.detach();
1214    assert(hwCycles.attached());
1215    hwInstructions.attach(cfgInstructions,
1216                          0, // TID (0 => currentThread)
1217                          hwCycles);
1218
1219    if (period)
1220        hwInstructions.enableSignals(KVM_INST_SIGNAL);
1221
1222    activeInstPeriod = period;
1223}
1224