base.cc revision 9735:fb040456eb46
12689Sktlim@umich.edu/*
22689Sktlim@umich.edu * Copyright (c) 2012 ARM Limited
32689Sktlim@umich.edu * All rights reserved
42689Sktlim@umich.edu *
52689Sktlim@umich.edu * The license below extends only to copyright in the software and shall
62689Sktlim@umich.edu * not be construed as granting a license to any other intellectual
72689Sktlim@umich.edu * property including but not limited to intellectual property relating
82689Sktlim@umich.edu * to a hardware implementation of the functionality of the software
92689Sktlim@umich.edu * licensed hereunder.  You may use the software subject to the license
102689Sktlim@umich.edu * terms below provided that you ensure that this notice is replicated
112689Sktlim@umich.edu * unmodified and in its entirety in all distributions of the software,
122689Sktlim@umich.edu * modified or unmodified, in source code or in binary form.
132689Sktlim@umich.edu *
142689Sktlim@umich.edu * Redistribution and use in source and binary forms, with or without
152689Sktlim@umich.edu * modification, are permitted provided that the following conditions are
162689Sktlim@umich.edu * met: redistributions of source code must retain the above copyright
172689Sktlim@umich.edu * notice, this list of conditions and the following disclaimer;
182689Sktlim@umich.edu * redistributions in binary form must reproduce the above copyright
192689Sktlim@umich.edu * notice, this list of conditions and the following disclaimer in the
202689Sktlim@umich.edu * documentation and/or other materials provided with the distribution;
212689Sktlim@umich.edu * neither the name of the copyright holders nor the names of its
222689Sktlim@umich.edu * contributors may be used to endorse or promote products derived from
232689Sktlim@umich.edu * this software without specific prior written permission.
242689Sktlim@umich.edu *
252689Sktlim@umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
262689Sktlim@umich.edu * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
272689Sktlim@umich.edu * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
282689Sktlim@umich.edu * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
292689Sktlim@umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
302290SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
313368Sstever@eecs.umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
322680Sktlim@umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
332290SN/A * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
342290SN/A * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
352680Sktlim@umich.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
365606Snate@binkert.org *
372290SN/A * Authors: Andreas Sandberg
382290SN/A */
392290SN/A
402290SN/A#include <linux/kvm.h>
412290SN/A#include <sys/ioctl.h>
422290SN/A#include <sys/mman.h>
433368Sstever@eecs.umich.edu#include <unistd.h>
442680Sktlim@umich.edu
452290SN/A#include <cerrno>
462290SN/A#include <csignal>
472290SN/A#include <ostream>
485336Shines@cs.fsu.edu
492290SN/A#include "arch/utility.hh"
504873Sstever@eecs.umich.edu#include "cpu/kvm/base.hh"
512290SN/A#include "debug/Checkpoint.hh"
52#include "debug/Kvm.hh"
53#include "debug/KvmIO.hh"
54#include "debug/KvmRun.hh"
55#include "params/BaseKvmCPU.hh"
56#include "sim/process.hh"
57#include "sim/system.hh"
58
59/* Used by some KVM macros */
60#define PAGE_SIZE pageSize
61
62volatile bool timerOverflowed = false;
63
64static void
65onTimerOverflow(int signo, siginfo_t *si, void *data)
66{
67    timerOverflowed = true;
68}
69
70BaseKvmCPU::BaseKvmCPU(BaseKvmCPUParams *params)
71    : BaseCPU(params),
72      vm(*params->kvmVM),
73      _status(Idle),
74      dataPort(name() + ".dcache_port", this),
75      instPort(name() + ".icache_port", this),
76      threadContextDirty(true),
77      kvmStateDirty(false),
78      vcpuID(vm.allocVCPUID()), vcpuFD(-1), vcpuMMapSize(0),
79      _kvmRun(NULL), mmioRing(NULL),
80      pageSize(sysconf(_SC_PAGE_SIZE)),
81      tickEvent(*this),
82      perfControlledByTimer(params->usePerfOverflow),
83      hostFactor(params->hostFactor)
84{
85    if (pageSize == -1)
86        panic("KVM: Failed to determine host page size (%i)\n",
87              errno);
88
89    thread = new SimpleThread(this, 0, params->system,
90                              params->itb, params->dtb, params->isa[0]);
91    thread->setStatus(ThreadContext::Halted);
92    tc = thread->getTC();
93    threadContexts.push_back(tc);
94
95    setupCounters();
96    setupSignalHandler();
97
98    if (params->usePerfOverflow)
99        runTimer.reset(new PerfKvmTimer(hwCycles,
100                                        KVM_TIMER_SIGNAL,
101                                        params->hostFactor,
102                                        params->clock));
103    else
104        runTimer.reset(new PosixKvmTimer(KVM_TIMER_SIGNAL, CLOCK_MONOTONIC,
105                                         params->hostFactor,
106                                         params->clock));
107}
108
109BaseKvmCPU::~BaseKvmCPU()
110{
111    if (_kvmRun)
112        munmap(_kvmRun, vcpuMMapSize);
113    close(vcpuFD);
114}
115
116void
117BaseKvmCPU::init()
118{
119    BaseCPU::init();
120
121    if (numThreads != 1)
122        fatal("KVM: Multithreading not supported");
123
124    tc->initMemProxies(tc);
125
126    // initialize CPU, including PC
127    if (FullSystem && !switchedOut())
128        TheISA::initCPU(tc, tc->contextId());
129
130    mmio_req.setThreadContext(tc->contextId(), 0);
131}
132
133void
134BaseKvmCPU::startup()
135{
136    const BaseKvmCPUParams * const p(
137        dynamic_cast<const BaseKvmCPUParams *>(params()));
138
139    Kvm &kvm(vm.kvm);
140
141    BaseCPU::startup();
142
143    assert(vcpuFD == -1);
144
145    // Tell the VM that a CPU is about to start.
146    vm.cpuStartup();
147
148    // We can't initialize KVM CPUs in BaseKvmCPU::init() since we are
149    // not guaranteed that the parent KVM VM has initialized at that
150    // point. Initialize virtual CPUs here instead.
151    vcpuFD = vm.createVCPU(vcpuID);
152
153    // Map the KVM run structure */
154    vcpuMMapSize = kvm.getVCPUMMapSize();
155    _kvmRun = (struct kvm_run *)mmap(0, vcpuMMapSize,
156                                     PROT_READ | PROT_WRITE, MAP_SHARED,
157                                     vcpuFD, 0);
158    if (_kvmRun == MAP_FAILED)
159        panic("KVM: Failed to map run data structure\n");
160
161    // Setup a pointer to the MMIO ring buffer if coalesced MMIO is
162    // available. The offset into the KVM's communication page is
163    // provided by the coalesced MMIO capability.
164    int mmioOffset(kvm.capCoalescedMMIO());
165    if (!p->useCoalescedMMIO) {
166        inform("KVM: Coalesced MMIO disabled by config.\n");
167    } else if (mmioOffset) {
168        inform("KVM: Coalesced IO available\n");
169        mmioRing = (struct kvm_coalesced_mmio_ring *)(
170            (char *)_kvmRun + (mmioOffset * pageSize));
171    } else {
172        inform("KVM: Coalesced not supported by host OS\n");
173    }
174
175    thread->startup();
176}
177
178void
179BaseKvmCPU::regStats()
180{
181    using namespace Stats;
182
183    BaseCPU::regStats();
184
185    numInsts
186        .name(name() + ".committedInsts")
187        .desc("Number of instructions committed")
188        ;
189
190    numVMExits
191        .name(name() + ".numVMExits")
192        .desc("total number of KVM exits")
193        ;
194
195    numMMIO
196        .name(name() + ".numMMIO")
197        .desc("number of VM exits due to memory mapped IO")
198        ;
199
200    numCoalescedMMIO
201        .name(name() + ".numCoalescedMMIO")
202        .desc("number of coalesced memory mapped IO requests")
203        ;
204
205    numIO
206        .name(name() + ".numIO")
207        .desc("number of VM exits due to legacy IO")
208        ;
209
210    numHalt
211        .name(name() + ".numHalt")
212        .desc("number of VM exits due to wait for interrupt instructions")
213        ;
214
215    numInterrupts
216        .name(name() + ".numInterrupts")
217        .desc("number of interrupts delivered")
218        ;
219
220    numHypercalls
221        .name(name() + ".numHypercalls")
222        .desc("number of hypercalls")
223        ;
224}
225
226void
227BaseKvmCPU::serializeThread(std::ostream &os, ThreadID tid)
228{
229    if (DTRACE(Checkpoint)) {
230        DPRINTF(Checkpoint, "KVM: Serializing thread %i:\n", tid);
231        dump();
232    }
233
234    // Update the thread context so we have something to serialize.
235    syncThreadContext();
236
237    assert(tid == 0);
238    assert(_status == Idle);
239    thread->serialize(os);
240}
241
242void
243BaseKvmCPU::unserializeThread(Checkpoint *cp, const std::string &section,
244                              ThreadID tid)
245{
246    DPRINTF(Checkpoint, "KVM: Unserialize thread %i:\n", tid);
247
248    assert(tid == 0);
249    assert(_status == Idle);
250    thread->unserialize(cp, section);
251    threadContextDirty = true;
252}
253
254unsigned int
255BaseKvmCPU::drain(DrainManager *dm)
256{
257    if (switchedOut())
258        return 0;
259
260    DPRINTF(Kvm, "drain\n");
261
262    // De-schedule the tick event so we don't insert any more MMIOs
263    // into the system while it is draining.
264    if (tickEvent.scheduled())
265        deschedule(tickEvent);
266
267    _status = Idle;
268    return 0;
269}
270
271void
272BaseKvmCPU::drainResume()
273{
274    assert(!tickEvent.scheduled());
275
276    // We might have been switched out. In that case, we don't need to
277    // do anything.
278    if (switchedOut())
279        return;
280
281    DPRINTF(Kvm, "drainResume\n");
282    verifyMemoryMode();
283
284    // The tick event is de-scheduled as a part of the draining
285    // process. Re-schedule it if the thread context is active.
286    if (tc->status() == ThreadContext::Active) {
287        schedule(tickEvent, nextCycle());
288        _status = Running;
289    } else {
290        _status = Idle;
291    }
292}
293
294void
295BaseKvmCPU::switchOut()
296{
297    DPRINTF(Kvm, "switchOut\n");
298
299    // Make sure to update the thread context in case, the new CPU
300    // will need to access it.
301    syncThreadContext();
302
303    BaseCPU::switchOut();
304
305    // We should have drained prior to executing a switchOut, which
306    // means that the tick event shouldn't be scheduled and the CPU is
307    // idle.
308    assert(!tickEvent.scheduled());
309    assert(_status == Idle);
310}
311
312void
313BaseKvmCPU::takeOverFrom(BaseCPU *cpu)
314{
315    DPRINTF(Kvm, "takeOverFrom\n");
316
317    BaseCPU::takeOverFrom(cpu);
318
319    // We should have drained prior to executing a switchOut, which
320    // means that the tick event shouldn't be scheduled and the CPU is
321    // idle.
322    assert(!tickEvent.scheduled());
323    assert(_status == Idle);
324    assert(threadContexts.size() == 1);
325
326    // The BaseCPU updated the thread context, make sure that we
327    // synchronize next time we enter start the CPU.
328    threadContextDirty = true;
329}
330
331void
332BaseKvmCPU::verifyMemoryMode() const
333{
334    if (!(system->isAtomicMode() && system->bypassCaches())) {
335        fatal("The KVM-based CPUs requires the memory system to be in the "
336              "'atomic_noncaching' mode.\n");
337    }
338}
339
340void
341BaseKvmCPU::wakeup()
342{
343    DPRINTF(Kvm, "wakeup()\n");
344
345    if (thread->status() != ThreadContext::Suspended)
346        return;
347
348    thread->activate();
349}
350
351void
352BaseKvmCPU::activateContext(ThreadID thread_num, Cycles delay)
353{
354    DPRINTF(Kvm, "ActivateContext %d (%d cycles)\n", thread_num, delay);
355
356    assert(thread_num == 0);
357    assert(thread);
358
359    assert(_status == Idle);
360    assert(!tickEvent.scheduled());
361
362    numCycles += ticksToCycles(thread->lastActivate - thread->lastSuspend)
363        * hostFactor;
364
365    schedule(tickEvent, clockEdge(delay));
366    _status = Running;
367}
368
369
370void
371BaseKvmCPU::suspendContext(ThreadID thread_num)
372{
373    DPRINTF(Kvm, "SuspendContext %d\n", thread_num);
374
375    assert(thread_num == 0);
376    assert(thread);
377
378    if (_status == Idle)
379        return;
380
381    assert(_status == Running);
382
383    // The tick event may no be scheduled if the quest has requested
384    // the monitor to wait for interrupts. The normal CPU models can
385    // get their tick events descheduled by quiesce instructions, but
386    // that can't happen here.
387    if (tickEvent.scheduled())
388        deschedule(tickEvent);
389
390    _status = Idle;
391}
392
393void
394BaseKvmCPU::deallocateContext(ThreadID thread_num)
395{
396    // for now, these are equivalent
397    suspendContext(thread_num);
398}
399
400void
401BaseKvmCPU::haltContext(ThreadID thread_num)
402{
403    // for now, these are equivalent
404    suspendContext(thread_num);
405}
406
407ThreadContext *
408BaseKvmCPU::getContext(int tn)
409{
410    assert(tn == 0);
411    syncThreadContext();
412    return tc;
413}
414
415
416Counter
417BaseKvmCPU::totalInsts() const
418{
419    return hwInstructions.read();
420}
421
422Counter
423BaseKvmCPU::totalOps() const
424{
425    hack_once("Pretending totalOps is equivalent to totalInsts()\n");
426    return hwInstructions.read();
427}
428
429void
430BaseKvmCPU::dump()
431{
432    inform("State dumping not implemented.");
433}
434
435void
436BaseKvmCPU::tick()
437{
438    assert(_status == Running);
439
440    DPRINTF(KvmRun, "Entering KVM...\n");
441
442    Tick ticksToExecute(mainEventQueue.nextTick() - curTick());
443    Tick ticksExecuted(kvmRun(ticksToExecute));
444
445    Tick delay(ticksExecuted + handleKvmExit());
446
447    switch (_status) {
448      case Running:
449        schedule(tickEvent, clockEdge(ticksToCycles(delay)));
450        break;
451
452      default:
453        /* The CPU is halted or waiting for an interrupt from a
454         * device. Don't start it. */
455        break;
456    }
457}
458
459uint64_t
460BaseKvmCPU::getHostCycles() const
461{
462    return hwCycles.read();
463}
464
465Tick
466BaseKvmCPU::kvmRun(Tick ticks)
467{
468    // We might need to update the KVM state.
469    syncKvmState();
470    // Entering into KVM implies that we'll have to reload the thread
471    // context from KVM if we want to access it. Flag the KVM state as
472    // dirty with respect to the cached thread context.
473    kvmStateDirty = true;
474
475    if (ticks < runTimer->resolution()) {
476        DPRINTF(KvmRun, "KVM: Adjusting tick count (%i -> %i)\n",
477                ticks, runTimer->resolution());
478        ticks = runTimer->resolution();
479    }
480
481    DPRINTF(KvmRun, "KVM: Executing for %i ticks\n", ticks);
482    timerOverflowed = false;
483
484    // Get hardware statistics after synchronizing contexts. The KVM
485    // state update might affect guest cycle counters.
486    uint64_t baseCycles(getHostCycles());
487    uint64_t baseInstrs(hwInstructions.read());
488
489    // Arm the run timer and start the cycle timer if it isn't
490    // controlled by the overflow timer. Starting/stopping the cycle
491    // timer automatically starts the other perf timers as they are in
492    // the same counter group.
493    runTimer->arm(ticks);
494    if (!perfControlledByTimer)
495        hwCycles.start();
496
497    if (ioctl(KVM_RUN) == -1) {
498        if (errno != EINTR)
499            panic("KVM: Failed to start virtual CPU (errno: %i)\n",
500                  errno);
501    }
502
503    runTimer->disarm();
504    if (!perfControlledByTimer)
505        hwCycles.stop();
506
507
508    const uint64_t hostCyclesExecuted(getHostCycles() - baseCycles);
509    const uint64_t simCyclesExecuted(hostCyclesExecuted * hostFactor);
510    const uint64_t instsExecuted(hwInstructions.read() - baseInstrs);
511    const Tick ticksExecuted(runTimer->ticksFromHostCycles(hostCyclesExecuted));
512
513    if (ticksExecuted < ticks &&
514        timerOverflowed &&
515        _kvmRun->exit_reason == KVM_EXIT_INTR) {
516        // TODO: We should probably do something clever here...
517        warn("KVM: Early timer event, requested %i ticks but got %i ticks.\n",
518             ticks, ticksExecuted);
519    }
520
521    /* Update statistics */
522    numCycles += simCyclesExecuted;;
523    ++numVMExits;
524    numInsts += instsExecuted;
525
526    DPRINTF(KvmRun, "KVM: Executed %i instructions in %i cycles (%i ticks, sim cycles: %i).\n",
527            instsExecuted, hostCyclesExecuted, ticksExecuted, simCyclesExecuted);
528
529    return ticksExecuted + flushCoalescedMMIO();
530}
531
532void
533BaseKvmCPU::kvmNonMaskableInterrupt()
534{
535    ++numInterrupts;
536    if (ioctl(KVM_NMI) == -1)
537        panic("KVM: Failed to deliver NMI to virtual CPU\n");
538}
539
540void
541BaseKvmCPU::kvmInterrupt(const struct kvm_interrupt &interrupt)
542{
543    ++numInterrupts;
544    if (ioctl(KVM_INTERRUPT, (void *)&interrupt) == -1)
545        panic("KVM: Failed to deliver interrupt to virtual CPU\n");
546}
547
548void
549BaseKvmCPU::getRegisters(struct kvm_regs &regs) const
550{
551    if (ioctl(KVM_GET_REGS, &regs) == -1)
552        panic("KVM: Failed to get guest registers\n");
553}
554
555void
556BaseKvmCPU::setRegisters(const struct kvm_regs &regs)
557{
558    if (ioctl(KVM_SET_REGS, (void *)&regs) == -1)
559        panic("KVM: Failed to set guest registers\n");
560}
561
562void
563BaseKvmCPU::getSpecialRegisters(struct kvm_sregs &regs) const
564{
565    if (ioctl(KVM_GET_SREGS, &regs) == -1)
566        panic("KVM: Failed to get guest special registers\n");
567}
568
569void
570BaseKvmCPU::setSpecialRegisters(const struct kvm_sregs &regs)
571{
572    if (ioctl(KVM_SET_SREGS, (void *)&regs) == -1)
573        panic("KVM: Failed to set guest special registers\n");
574}
575
576void
577BaseKvmCPU::getFPUState(struct kvm_fpu &state) const
578{
579    if (ioctl(KVM_GET_FPU, &state) == -1)
580        panic("KVM: Failed to get guest FPU state\n");
581}
582
583void
584BaseKvmCPU::setFPUState(const struct kvm_fpu &state)
585{
586    if (ioctl(KVM_SET_FPU, (void *)&state) == -1)
587        panic("KVM: Failed to set guest FPU state\n");
588}
589
590
591void
592BaseKvmCPU::setOneReg(uint64_t id, const void *addr)
593{
594#ifdef KVM_SET_ONE_REG
595    struct kvm_one_reg reg;
596    reg.id = id;
597    reg.addr = (uint64_t)addr;
598
599    if (ioctl(KVM_SET_ONE_REG, &reg) == -1) {
600        panic("KVM: Failed to set register (0x%x) value (errno: %i)\n",
601              id, errno);
602    }
603#else
604    panic("KVM_SET_ONE_REG is unsupported on this platform.\n");
605#endif
606}
607
608void
609BaseKvmCPU::getOneReg(uint64_t id, void *addr) const
610{
611#ifdef KVM_GET_ONE_REG
612    struct kvm_one_reg reg;
613    reg.id = id;
614    reg.addr = (uint64_t)addr;
615
616    if (ioctl(KVM_GET_ONE_REG, &reg) == -1) {
617        panic("KVM: Failed to get register (0x%x) value (errno: %i)\n",
618              id, errno);
619    }
620#else
621    panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
622#endif
623}
624
625std::string
626BaseKvmCPU::getAndFormatOneReg(uint64_t id) const
627{
628#ifdef KVM_GET_ONE_REG
629    std::ostringstream ss;
630
631    ss.setf(std::ios::hex, std::ios::basefield);
632    ss.setf(std::ios::showbase);
633#define HANDLE_INTTYPE(len)                      \
634    case KVM_REG_SIZE_U ## len: {                \
635        uint ## len ## _t value;                 \
636        getOneReg(id, &value);                   \
637        ss << value;                             \
638    }  break
639
640#define HANDLE_ARRAY(len)                       \
641    case KVM_REG_SIZE_U ## len: {               \
642        uint8_t value[len / 8];                 \
643        getOneReg(id, value);                   \
644        ss << "[" << value[0];                  \
645        for (int i = 1; i < len  / 8; ++i)      \
646            ss << ", " << value[i];             \
647        ss << "]";                              \
648      } break
649
650    switch (id & KVM_REG_SIZE_MASK) {
651        HANDLE_INTTYPE(8);
652        HANDLE_INTTYPE(16);
653        HANDLE_INTTYPE(32);
654        HANDLE_INTTYPE(64);
655        HANDLE_ARRAY(128);
656        HANDLE_ARRAY(256);
657        HANDLE_ARRAY(512);
658        HANDLE_ARRAY(1024);
659      default:
660        ss << "??";
661    }
662
663#undef HANDLE_INTTYPE
664#undef HANDLE_ARRAY
665
666    return ss.str();
667#else
668    panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
669#endif
670}
671
672void
673BaseKvmCPU::syncThreadContext()
674{
675    if (!kvmStateDirty)
676        return;
677
678    assert(!threadContextDirty);
679
680    updateThreadContext();
681    kvmStateDirty = false;
682}
683
684void
685BaseKvmCPU::syncKvmState()
686{
687    if (!threadContextDirty)
688        return;
689
690    assert(!kvmStateDirty);
691
692    updateKvmState();
693    threadContextDirty = false;
694}
695
696Tick
697BaseKvmCPU::handleKvmExit()
698{
699    DPRINTF(KvmRun, "handleKvmExit (exit_reason: %i)\n", _kvmRun->exit_reason);
700
701    switch (_kvmRun->exit_reason) {
702      case KVM_EXIT_UNKNOWN:
703        return handleKvmExitUnknown();
704
705      case KVM_EXIT_EXCEPTION:
706        return handleKvmExitException();
707
708      case KVM_EXIT_IO:
709        ++numIO;
710        return handleKvmExitIO();
711
712      case KVM_EXIT_HYPERCALL:
713        ++numHypercalls;
714        return handleKvmExitHypercall();
715
716      case KVM_EXIT_HLT:
717        /* The guest has halted and is waiting for interrupts */
718        DPRINTF(Kvm, "handleKvmExitHalt\n");
719        ++numHalt;
720
721        // Suspend the thread until the next interrupt arrives
722        thread->suspend();
723
724        // This is actually ignored since the thread is suspended.
725        return 0;
726
727      case KVM_EXIT_MMIO:
728        /* Service memory mapped IO requests */
729        DPRINTF(KvmIO, "KVM: Handling MMIO (w: %u, addr: 0x%x, len: %u)\n",
730                _kvmRun->mmio.is_write,
731                _kvmRun->mmio.phys_addr, _kvmRun->mmio.len);
732
733        ++numMMIO;
734        return doMMIOAccess(_kvmRun->mmio.phys_addr, _kvmRun->mmio.data,
735                            _kvmRun->mmio.len, _kvmRun->mmio.is_write);
736
737      case KVM_EXIT_IRQ_WINDOW_OPEN:
738        return handleKvmExitIRQWindowOpen();
739
740      case KVM_EXIT_FAIL_ENTRY:
741        return handleKvmExitFailEntry();
742
743      case KVM_EXIT_INTR:
744        /* KVM was interrupted by a signal, restart it in the next
745         * tick. */
746        return 0;
747
748      case KVM_EXIT_INTERNAL_ERROR:
749        panic("KVM: Internal error (suberror: %u)\n",
750              _kvmRun->internal.suberror);
751
752      default:
753        dump();
754        panic("KVM: Unexpected exit (exit_reason: %u)\n", _kvmRun->exit_reason);
755    }
756}
757
758Tick
759BaseKvmCPU::handleKvmExitIO()
760{
761    panic("KVM: Unhandled guest IO (dir: %i, size: %i, port: 0x%x, count: %i)\n",
762          _kvmRun->io.direction, _kvmRun->io.size,
763          _kvmRun->io.port, _kvmRun->io.count);
764}
765
766Tick
767BaseKvmCPU::handleKvmExitHypercall()
768{
769    panic("KVM: Unhandled hypercall\n");
770}
771
772Tick
773BaseKvmCPU::handleKvmExitIRQWindowOpen()
774{
775    warn("KVM: Unhandled IRQ window.\n");
776    return 0;
777}
778
779
780Tick
781BaseKvmCPU::handleKvmExitUnknown()
782{
783    dump();
784    panic("KVM: Unknown error when starting vCPU (hw reason: 0x%llx)\n",
785          _kvmRun->hw.hardware_exit_reason);
786}
787
788Tick
789BaseKvmCPU::handleKvmExitException()
790{
791    dump();
792    panic("KVM: Got exception when starting vCPU "
793          "(exception: %u, error_code: %u)\n",
794          _kvmRun->ex.exception, _kvmRun->ex.error_code);
795}
796
797Tick
798BaseKvmCPU::handleKvmExitFailEntry()
799{
800    dump();
801    panic("KVM: Failed to enter virtualized mode (hw reason: 0x%llx)\n",
802          _kvmRun->fail_entry.hardware_entry_failure_reason);
803}
804
805Tick
806BaseKvmCPU::doMMIOAccess(Addr paddr, void *data, int size, bool write)
807{
808    mmio_req.setPhys(paddr, size, Request::UNCACHEABLE, dataMasterId());
809
810    const MemCmd cmd(write ? MemCmd::WriteReq : MemCmd::ReadReq);
811    Packet pkt(&mmio_req, cmd);
812    pkt.dataStatic(data);
813    return dataPort.sendAtomic(&pkt);
814}
815
816int
817BaseKvmCPU::ioctl(int request, long p1) const
818{
819    if (vcpuFD == -1)
820        panic("KVM: CPU ioctl called before initialization\n");
821
822    return ::ioctl(vcpuFD, request, p1);
823}
824
825Tick
826BaseKvmCPU::flushCoalescedMMIO()
827{
828    if (!mmioRing)
829        return 0;
830
831    DPRINTF(KvmIO, "KVM: Flushing the coalesced MMIO ring buffer\n");
832
833    // TODO: We might need to do synchronization when we start to
834    // support multiple CPUs
835    Tick ticks(0);
836    while (mmioRing->first != mmioRing->last) {
837        struct kvm_coalesced_mmio &ent(
838            mmioRing->coalesced_mmio[mmioRing->first]);
839
840        DPRINTF(KvmIO, "KVM: Handling coalesced MMIO (addr: 0x%x, len: %u)\n",
841                ent.phys_addr, ent.len);
842
843        ++numCoalescedMMIO;
844        ticks += doMMIOAccess(ent.phys_addr, ent.data, ent.len, true);
845
846        mmioRing->first = (mmioRing->first + 1) % KVM_COALESCED_MMIO_MAX;
847    }
848
849    return ticks;
850}
851
852void
853BaseKvmCPU::setupSignalHandler()
854{
855    struct sigaction sa;
856
857    memset(&sa, 0, sizeof(sa));
858    sa.sa_sigaction = onTimerOverflow;
859    sa.sa_flags = SA_SIGINFO | SA_RESTART;
860    if (sigaction(KVM_TIMER_SIGNAL, &sa, NULL) == -1)
861        panic("KVM: Failed to setup vCPU signal handler\n");
862}
863
864void
865BaseKvmCPU::setupCounters()
866{
867    DPRINTF(Kvm, "Attaching cycle counter...\n");
868    PerfKvmCounterConfig cfgCycles(PERF_TYPE_HARDWARE,
869                                PERF_COUNT_HW_CPU_CYCLES);
870    cfgCycles.disabled(true)
871        .pinned(true);
872
873    if (perfControlledByTimer) {
874        // We need to configure the cycles counter to send overflows
875        // since we are going to use it to trigger timer signals that
876        // trap back into m5 from KVM. In practice, this means that we
877        // need to set some non-zero sample period that gets
878        // overridden when the timer is armed.
879        cfgCycles.wakeupEvents(1)
880            .samplePeriod(42);
881    }
882
883    hwCycles.attach(cfgCycles,
884                    0); // TID (0 => currentThread)
885
886    DPRINTF(Kvm, "Attaching instruction counter...\n");
887    PerfKvmCounterConfig cfgInstructions(PERF_TYPE_HARDWARE,
888                                      PERF_COUNT_HW_INSTRUCTIONS);
889    hwInstructions.attach(cfgInstructions,
890                          0, // TID (0 => currentThread)
891                          hwCycles);
892}
893