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