2 * Copyright (c) 2012 ARM Limited
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.
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.
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.
37 * Authors: Andreas Sandberg
40 #include <linux/kvm.h>
41 #include <sys/ioctl.h>
49 #include "arch/utility.hh"
50 #include "cpu/kvm/base.hh"
51 #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"
59 /* Used by some KVM macros */
60 #define PAGE_SIZE pageSize
62 volatile bool timerOverflowed
= false;
65 onTimerOverflow(int signo
, siginfo_t
*si
, void *data
)
67 timerOverflowed
= true;
70 BaseKvmCPU::BaseKvmCPU(BaseKvmCPUParams
*params
)
74 dataPort(name() + ".dcache_port", this),
75 instPort(name() + ".icache_port", this),
76 threadContextDirty(true),
78 vcpuID(vm
.allocVCPUID()), vcpuFD(-1), vcpuMMapSize(0),
79 _kvmRun(NULL
), mmioRing(NULL
),
80 pageSize(sysconf(_SC_PAGE_SIZE
)),
82 perfControlledByTimer(params
->usePerfOverflow
),
83 hostFactor(params
->hostFactor
)
86 panic("KVM: Failed to determine host page size (%i)\n",
89 thread
= new SimpleThread(this, 0, params
->system
,
90 params
->itb
, params
->dtb
, params
->isa
[0]);
91 thread
->setStatus(ThreadContext::Halted
);
93 threadContexts
.push_back(tc
);
98 if (params
->usePerfOverflow
)
99 runTimer
.reset(new PerfKvmTimer(hwCycles
,
104 runTimer
.reset(new PosixKvmTimer(KVM_TIMER_SIGNAL
, CLOCK_MONOTONIC
,
109 BaseKvmCPU::~BaseKvmCPU()
112 munmap(_kvmRun
, vcpuMMapSize
);
122 fatal("KVM: Multithreading not supported");
124 tc
->initMemProxies(tc
);
126 // initialize CPU, including PC
127 if (FullSystem
&& !switchedOut())
128 TheISA::initCPU(tc
, tc
->contextId());
130 mmio_req
.setThreadContext(tc
->contextId(), 0);
134 BaseKvmCPU::startup()
140 assert(vcpuFD
== -1);
142 // Tell the VM that a CPU is about to start.
145 // We can't initialize KVM CPUs in BaseKvmCPU::init() since we are
146 // not guaranteed that the parent KVM VM has initialized at that
147 // point. Initialize virtual CPUs here instead.
148 vcpuFD
= vm
.createVCPU(vcpuID
);
150 // Map the KVM run structure */
151 vcpuMMapSize
= kvm
.getVCPUMMapSize();
152 _kvmRun
= (struct kvm_run
*)mmap(0, vcpuMMapSize
,
153 PROT_READ
| PROT_WRITE
, MAP_SHARED
,
155 if (_kvmRun
== MAP_FAILED
)
156 panic("KVM: Failed to map run data structure\n");
158 // Setup a pointer to the MMIO ring buffer if coalesced MMIO is
159 // available. The offset into the KVM's communication page is
160 // provided by the coalesced MMIO capability.
161 int mmioOffset(kvm
.capCoalescedMMIO());
163 inform("KVM: Coalesced IO available\n");
164 mmioRing
= (struct kvm_coalesced_mmio_ring
*)(
165 (char *)_kvmRun
+ (mmioOffset
* pageSize
));
167 inform("KVM: Coalesced not supported by host OS\n");
172 BaseKvmCPU::regStats()
174 using namespace Stats
;
179 .name(name() + ".numVMExits")
180 .desc("total number of KVM exits")
184 .name(name() + ".numMMIO")
185 .desc("number of VM exits due to memory mapped IO")
189 .name(name() + ".numCoalescedMMIO")
190 .desc("number of coalesced memory mapped IO requests")
194 .name(name() + ".numIO")
195 .desc("number of VM exits due to legacy IO")
199 .name(name() + ".numHalt")
200 .desc("number of VM exits due to wait for interrupt instructions")
204 .name(name() + ".numInterrupts")
205 .desc("number of interrupts delivered")
209 .name(name() + ".numHypercalls")
210 .desc("number of hypercalls")
215 BaseKvmCPU::serializeThread(std::ostream
&os
, ThreadID tid
)
217 if (DTRACE(Checkpoint
)) {
218 DPRINTF(Checkpoint
, "KVM: Serializing thread %i:\n", tid
);
222 // Update the thread context so we have something to serialize.
226 assert(_status
== Idle
);
227 thread
->serialize(os
);
231 BaseKvmCPU::unserializeThread(Checkpoint
*cp
, const std::string
§ion
,
234 DPRINTF(Checkpoint
, "KVM: Unserialize thread %i:\n", tid
);
237 assert(_status
== Idle
);
238 thread
->unserialize(cp
, section
);
239 threadContextDirty
= true;
243 BaseKvmCPU::drain(DrainManager
*dm
)
248 DPRINTF(Kvm
, "drain\n");
250 // De-schedule the tick event so we don't insert any more MMIOs
251 // into the system while it is draining.
252 if (tickEvent
.scheduled())
253 deschedule(tickEvent
);
260 BaseKvmCPU::drainResume()
262 assert(!tickEvent
.scheduled());
264 // We might have been switched out. In that case, we don't need to
269 DPRINTF(Kvm
, "drainResume\n");
272 // The tick event is de-scheduled as a part of the draining
273 // process. Re-schedule it if the thread context is active.
274 if (tc
->status() == ThreadContext::Active
) {
275 schedule(tickEvent
, nextCycle());
283 BaseKvmCPU::switchOut()
285 DPRINTF(Kvm
, "switchOut\n");
287 // Make sure to update the thread context in case, the new CPU
288 // will need to access it.
291 BaseCPU::switchOut();
293 // We should have drained prior to executing a switchOut, which
294 // means that the tick event shouldn't be scheduled and the CPU is
296 assert(!tickEvent
.scheduled());
297 assert(_status
== Idle
);
301 BaseKvmCPU::takeOverFrom(BaseCPU
*cpu
)
303 DPRINTF(Kvm
, "takeOverFrom\n");
305 BaseCPU::takeOverFrom(cpu
);
307 // We should have drained prior to executing a switchOut, which
308 // means that the tick event shouldn't be scheduled and the CPU is
310 assert(!tickEvent
.scheduled());
311 assert(_status
== Idle
);
312 assert(threadContexts
.size() == 1);
314 // The BaseCPU updated the thread context, make sure that we
315 // synchronize next time we enter start the CPU.
316 threadContextDirty
= true;
320 BaseKvmCPU::verifyMemoryMode() const
322 if (!(system
->isAtomicMode() && system
->bypassCaches())) {
323 fatal("The KVM-based CPUs requires the memory system to be in the "
324 "'atomic_noncaching' mode.\n");
331 DPRINTF(Kvm
, "wakeup()\n");
333 if (thread
->status() != ThreadContext::Suspended
)
340 BaseKvmCPU::activateContext(ThreadID thread_num
, Cycles delay
)
342 DPRINTF(Kvm
, "ActivateContext %d (%d cycles)\n", thread_num
, delay
);
344 assert(thread_num
== 0);
347 assert(_status
== Idle
);
348 assert(!tickEvent
.scheduled());
350 numCycles
+= ticksToCycles(thread
->lastActivate
- thread
->lastSuspend
)
353 schedule(tickEvent
, clockEdge(delay
));
359 BaseKvmCPU::suspendContext(ThreadID thread_num
)
361 DPRINTF(Kvm
, "SuspendContext %d\n", thread_num
);
363 assert(thread_num
== 0);
369 assert(_status
== Running
);
371 // The tick event may no be scheduled if the quest has requested
372 // the monitor to wait for interrupts. The normal CPU models can
373 // get their tick events descheduled by quiesce instructions, but
374 // that can't happen here.
375 if (tickEvent
.scheduled())
376 deschedule(tickEvent
);
382 BaseKvmCPU::deallocateContext(ThreadID thread_num
)
384 // for now, these are equivalent
385 suspendContext(thread_num
);
389 BaseKvmCPU::haltContext(ThreadID thread_num
)
391 // for now, these are equivalent
392 suspendContext(thread_num
);
396 BaseKvmCPU::getContext(int tn
)
405 BaseKvmCPU::totalInsts() const
407 return hwInstructions
.read();
411 BaseKvmCPU::totalOps() const
413 hack_once("Pretending totalOps is equivalent to totalInsts()\n");
414 return hwInstructions
.read();
420 inform("State dumping not implemented.");
426 assert(_status
== Running
);
428 DPRINTF(KvmRun
, "Entering KVM...\n");
430 Tick
ticksToExecute(mainEventQueue
.nextTick() - curTick());
431 Tick
ticksExecuted(kvmRun(ticksToExecute
));
433 Tick
delay(ticksExecuted
+ handleKvmExit());
437 schedule(tickEvent
, clockEdge(ticksToCycles(delay
)));
441 /* The CPU is halted or waiting for an interrupt from a
442 * device. Don't start it. */
448 BaseKvmCPU::kvmRun(Tick ticks
)
450 uint64_t baseCycles(hwCycles
.read());
451 uint64_t baseInstrs(hwInstructions
.read());
453 // We might need to update the KVM state.
455 // Entering into KVM implies that we'll have to reload the thread
456 // context from KVM if we want to access it. Flag the KVM state as
457 // dirty with respect to the cached thread context.
458 kvmStateDirty
= true;
460 if (ticks
< runTimer
->resolution()) {
461 DPRINTF(KvmRun
, "KVM: Adjusting tick count (%i -> %i)\n",
462 ticks
, runTimer
->resolution());
463 ticks
= runTimer
->resolution();
466 DPRINTF(KvmRun
, "KVM: Executing for %i ticks\n", ticks
);
467 timerOverflowed
= false;
469 // Arm the run timer and start the cycle timer if it isn't
470 // controlled by the overflow timer. Starting/stopping the cycle
471 // timer automatically starts the other perf timers as they are in
472 // the same counter group.
473 runTimer
->arm(ticks
);
474 if (!perfControlledByTimer
)
477 if (ioctl(KVM_RUN
) == -1) {
479 panic("KVM: Failed to start virtual CPU (errno: %i)\n",
484 if (!perfControlledByTimer
)
488 uint64_t cyclesExecuted(hwCycles
.read() - baseCycles
);
489 Tick
ticksExecuted(runTimer
->ticksFromHostCycles(cyclesExecuted
));
491 if (ticksExecuted
< ticks
&&
493 _kvmRun
->exit_reason
== KVM_EXIT_INTR
) {
494 // TODO: We should probably do something clever here...
495 warn("KVM: Early timer event, requested %i ticks but got %i ticks.\n",
496 ticks
, ticksExecuted
);
499 numCycles
+= cyclesExecuted
* hostFactor
;
502 DPRINTF(KvmRun
, "KVM: Executed %i instructions in %i cycles (%i ticks, sim cycles: %i).\n",
503 hwInstructions
.read() - baseInstrs
,
506 cyclesExecuted
* hostFactor
);
508 return ticksExecuted
+ flushCoalescedMMIO();
512 BaseKvmCPU::kvmNonMaskableInterrupt()
515 if (ioctl(KVM_NMI
) == -1)
516 panic("KVM: Failed to deliver NMI to virtual CPU\n");
520 BaseKvmCPU::kvmInterrupt(const struct kvm_interrupt
&interrupt
)
523 if (ioctl(KVM_INTERRUPT
, (void *)&interrupt
) == -1)
524 panic("KVM: Failed to deliver interrupt to virtual CPU\n");
528 BaseKvmCPU::getRegisters(struct kvm_regs
®s
) const
530 if (ioctl(KVM_GET_REGS
, ®s
) == -1)
531 panic("KVM: Failed to get guest registers\n");
535 BaseKvmCPU::setRegisters(const struct kvm_regs
®s
)
537 if (ioctl(KVM_SET_REGS
, (void *)®s
) == -1)
538 panic("KVM: Failed to set guest registers\n");
542 BaseKvmCPU::getSpecialRegisters(struct kvm_sregs
®s
) const
544 if (ioctl(KVM_GET_SREGS
, ®s
) == -1)
545 panic("KVM: Failed to get guest special registers\n");
549 BaseKvmCPU::setSpecialRegisters(const struct kvm_sregs
®s
)
551 if (ioctl(KVM_SET_SREGS
, (void *)®s
) == -1)
552 panic("KVM: Failed to set guest special registers\n");
556 BaseKvmCPU::getFPUState(struct kvm_fpu
&state
) const
558 if (ioctl(KVM_GET_FPU
, &state
) == -1)
559 panic("KVM: Failed to get guest FPU state\n");
563 BaseKvmCPU::setFPUState(const struct kvm_fpu
&state
)
565 if (ioctl(KVM_SET_FPU
, (void *)&state
) == -1)
566 panic("KVM: Failed to set guest FPU state\n");
571 BaseKvmCPU::setOneReg(uint64_t id
, const void *addr
)
573 #ifdef KVM_SET_ONE_REG
574 struct kvm_one_reg reg
;
576 reg
.addr
= (uint64_t)addr
;
578 if (ioctl(KVM_SET_ONE_REG
, ®
) == -1) {
579 panic("KVM: Failed to set register (0x%x) value (errno: %i)\n",
583 panic("KVM_SET_ONE_REG is unsupported on this platform.\n");
588 BaseKvmCPU::getOneReg(uint64_t id
, void *addr
) const
590 #ifdef KVM_GET_ONE_REG
591 struct kvm_one_reg reg
;
593 reg
.addr
= (uint64_t)addr
;
595 if (ioctl(KVM_GET_ONE_REG
, ®
) == -1) {
596 panic("KVM: Failed to get register (0x%x) value (errno: %i)\n",
600 panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
605 BaseKvmCPU::getAndFormatOneReg(uint64_t id
) const
607 #ifdef KVM_GET_ONE_REG
608 std::ostringstream ss
;
610 ss
.setf(std::ios::hex
, std::ios::basefield
);
611 ss
.setf(std::ios::showbase
);
612 #define HANDLE_INTTYPE(len) \
613 case KVM_REG_SIZE_U ## len: { \
614 uint ## len ## _t value; \
615 getOneReg(id, &value); \
619 #define HANDLE_ARRAY(len) \
620 case KVM_REG_SIZE_U ## len: { \
621 uint8_t value[len / 8]; \
622 getOneReg(id, value); \
623 ss << "[" << value[0]; \
624 for (int i = 1; i < len / 8; ++i) \
625 ss << ", " << value[i]; \
629 switch (id
& KVM_REG_SIZE_MASK
) {
642 #undef HANDLE_INTTYPE
647 panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
652 BaseKvmCPU::syncThreadContext()
657 assert(!threadContextDirty
);
659 updateThreadContext();
660 kvmStateDirty
= false;
664 BaseKvmCPU::syncKvmState()
666 if (!threadContextDirty
)
669 assert(!kvmStateDirty
);
672 threadContextDirty
= false;
676 BaseKvmCPU::handleKvmExit()
678 DPRINTF(KvmRun
, "handleKvmExit (exit_reason: %i)\n", _kvmRun
->exit_reason
);
680 switch (_kvmRun
->exit_reason
) {
681 case KVM_EXIT_UNKNOWN
:
682 return handleKvmExitUnknown();
684 case KVM_EXIT_EXCEPTION
:
685 return handleKvmExitException();
689 return handleKvmExitIO();
691 case KVM_EXIT_HYPERCALL
:
693 return handleKvmExitHypercall();
696 /* The guest has halted and is waiting for interrupts */
697 DPRINTF(Kvm
, "handleKvmExitHalt\n");
700 // Suspend the thread until the next interrupt arrives
703 // This is actually ignored since the thread is suspended.
707 /* Service memory mapped IO requests */
708 DPRINTF(KvmIO
, "KVM: Handling MMIO (w: %u, addr: 0x%x, len: %u)\n",
709 _kvmRun
->mmio
.is_write
,
710 _kvmRun
->mmio
.phys_addr
, _kvmRun
->mmio
.len
);
713 return doMMIOAccess(_kvmRun
->mmio
.phys_addr
, _kvmRun
->mmio
.data
,
714 _kvmRun
->mmio
.len
, _kvmRun
->mmio
.is_write
);
716 case KVM_EXIT_IRQ_WINDOW_OPEN
:
717 return handleKvmExitIRQWindowOpen();
719 case KVM_EXIT_FAIL_ENTRY
:
720 return handleKvmExitFailEntry();
723 /* KVM was interrupted by a signal, restart it in the next
727 case KVM_EXIT_INTERNAL_ERROR
:
728 panic("KVM: Internal error (suberror: %u)\n",
729 _kvmRun
->internal
.suberror
);
732 panic("KVM: Unexpected exit (exit_reason: %u)\n", _kvmRun
->exit_reason
);
737 BaseKvmCPU::handleKvmExitIO()
739 panic("KVM: Unhandled guest IO (dir: %i, size: %i, port: 0x%x, count: %i)\n",
740 _kvmRun
->io
.direction
, _kvmRun
->io
.size
,
741 _kvmRun
->io
.port
, _kvmRun
->io
.count
);
745 BaseKvmCPU::handleKvmExitHypercall()
747 panic("KVM: Unhandled hypercall\n");
751 BaseKvmCPU::handleKvmExitIRQWindowOpen()
753 warn("KVM: Unhandled IRQ window.\n");
759 BaseKvmCPU::handleKvmExitUnknown()
761 panic("KVM: Unknown error when starting vCPU (hw reason: 0x%llx)\n",
762 _kvmRun
->hw
.hardware_exit_reason
);
766 BaseKvmCPU::handleKvmExitException()
768 panic("KVM: Got exception when starting vCPU "
769 "(exception: %u, error_code: %u)\n",
770 _kvmRun
->ex
.exception
, _kvmRun
->ex
.error_code
);
774 BaseKvmCPU::handleKvmExitFailEntry()
776 panic("KVM: Failed to enter virtualized mode (hw reason: 0x%llx)\n",
777 _kvmRun
->fail_entry
.hardware_entry_failure_reason
);
781 BaseKvmCPU::doMMIOAccess(Addr paddr
, void *data
, int size
, bool write
)
783 mmio_req
.setPhys(paddr
, size
, Request::UNCACHEABLE
, dataMasterId());
785 const MemCmd
cmd(write
? MemCmd::WriteReq
: MemCmd::ReadReq
);
786 Packet
pkt(&mmio_req
, cmd
);
787 pkt
.dataStatic(data
);
788 return dataPort
.sendAtomic(&pkt
);
792 BaseKvmCPU::ioctl(int request
, long p1
) const
795 panic("KVM: CPU ioctl called before initialization\n");
797 return ::ioctl(vcpuFD
, request
, p1
);
801 BaseKvmCPU::flushCoalescedMMIO()
806 DPRINTF(KvmIO
, "KVM: Flushing the coalesced MMIO ring buffer\n");
808 // TODO: We might need to do synchronization when we start to
809 // support multiple CPUs
811 while (mmioRing
->first
!= mmioRing
->last
) {
812 struct kvm_coalesced_mmio
&ent(
813 mmioRing
->coalesced_mmio
[mmioRing
->first
]);
815 DPRINTF(KvmIO
, "KVM: Handling coalesced MMIO (addr: 0x%x, len: %u)\n",
816 ent
.phys_addr
, ent
.len
);
819 ticks
+= doMMIOAccess(ent
.phys_addr
, ent
.data
, ent
.len
, true);
821 mmioRing
->first
= (mmioRing
->first
+ 1) % KVM_COALESCED_MMIO_MAX
;
828 BaseKvmCPU::setupSignalHandler()
832 memset(&sa
, 0, sizeof(sa
));
833 sa
.sa_sigaction
= onTimerOverflow
;
834 sa
.sa_flags
= SA_SIGINFO
| SA_RESTART
;
835 if (sigaction(KVM_TIMER_SIGNAL
, &sa
, NULL
) == -1)
836 panic("KVM: Failed to setup vCPU signal handler\n");
840 BaseKvmCPU::setupCounters()
842 DPRINTF(Kvm
, "Attaching cycle counter...\n");
843 PerfKvmCounterConfig
cfgCycles(PERF_TYPE_HARDWARE
,
844 PERF_COUNT_HW_CPU_CYCLES
);
845 cfgCycles
.disabled(true)
848 if (perfControlledByTimer
) {
849 // We need to configure the cycles counter to send overflows
850 // since we are going to use it to trigger timer signals that
851 // trap back into m5 from KVM. In practice, this means that we
852 // need to set some non-zero sample period that gets
853 // overridden when the timer is armed.
854 cfgCycles
.wakeupEvents(1)
858 hwCycles
.attach(cfgCycles
,
859 0); // TID (0 => currentThread)
861 DPRINTF(Kvm
, "Attaching instruction counter...\n");
862 PerfKvmCounterConfig
cfgInstructions(PERF_TYPE_HARDWARE
,
863 PERF_COUNT_HW_INSTRUCTIONS
);
864 hwInstructions
.attach(cfgInstructions
,
865 0, // TID (0 => currentThread)