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/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"
63 /* Used by some KVM macros */
64 #define PAGE_SIZE pageSize
66 volatile bool timerOverflowed
= false;
68 BaseKvmCPU::BaseKvmCPU(BaseKvmCPUParams
*params
)
72 dataPort(name() + ".dcache_port", this),
73 instPort(name() + ".icache_port", this),
74 threadContextDirty(true),
76 vcpuID(vm
.allocVCPUID()), vcpuFD(-1), vcpuMMapSize(0),
77 _kvmRun(NULL
), mmioRing(NULL
),
78 pageSize(sysconf(_SC_PAGE_SIZE
)),
81 perfControlledByTimer(params
->usePerfOverflow
),
82 hostFreq(params
->hostFreq
),
83 hostFactor(params
->hostFactor
),
88 panic("KVM: Failed to determine host page size (%i)\n",
91 thread
= new SimpleThread(this, 0, params
->system
,
92 params
->itb
, params
->dtb
, params
->isa
[0]);
93 thread
->setStatus(ThreadContext::Halted
);
95 threadContexts
.push_back(tc
);
99 if (params
->usePerfOverflow
)
100 runTimer
.reset(new PerfKvmTimer(hwCycles
,
105 runTimer
.reset(new PosixKvmTimer(KVM_TIMER_SIGNAL
, CLOCK_MONOTONIC
,
110 BaseKvmCPU::~BaseKvmCPU()
113 munmap(_kvmRun
, vcpuMMapSize
);
123 fatal("KVM: Multithreading not supported");
125 tc
->initMemProxies(tc
);
127 // initialize CPU, including PC
128 if (FullSystem
&& !switchedOut())
129 TheISA::initCPU(tc
, tc
->contextId());
131 mmio_req
.setThreadContext(tc
->contextId(), 0);
135 BaseKvmCPU::startup()
137 const BaseKvmCPUParams
* const p(
138 dynamic_cast<const BaseKvmCPUParams
*>(params()));
144 assert(vcpuFD
== -1);
146 // Tell the VM that a CPU is about to start.
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
);
154 // Setup signal handlers. This has to be done after the vCPU is
155 // created since it manipulates the vCPU signal mask.
156 setupSignalHandler();
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
,
163 if (_kvmRun
== MAP_FAILED
)
164 panic("KVM: Failed to map run data structure\n");
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
));
177 inform("KVM: Coalesced not supported by host OS\n");
184 BaseKvmCPU::regStats()
186 using namespace Stats
;
191 .name(name() + ".committedInsts")
192 .desc("Number of instructions committed")
196 .name(name() + ".numVMExits")
197 .desc("total number of KVM exits")
201 .name(name() + ".numVMHalfEntries")
202 .desc("number of KVM entries to finalize pending operations")
206 .name(name() + ".numExitSignal")
207 .desc("exits due to signal delivery")
211 .name(name() + ".numMMIO")
212 .desc("number of VM exits due to memory mapped IO")
216 .name(name() + ".numCoalescedMMIO")
217 .desc("number of coalesced memory mapped IO requests")
221 .name(name() + ".numIO")
222 .desc("number of VM exits due to legacy IO")
226 .name(name() + ".numHalt")
227 .desc("number of VM exits due to wait for interrupt instructions")
231 .name(name() + ".numInterrupts")
232 .desc("number of interrupts delivered")
236 .name(name() + ".numHypercalls")
237 .desc("number of hypercalls")
242 BaseKvmCPU::serializeThread(std::ostream
&os
, ThreadID tid
)
244 if (DTRACE(Checkpoint
)) {
245 DPRINTF(Checkpoint
, "KVM: Serializing thread %i:\n", tid
);
250 assert(_status
== Idle
);
251 thread
->serialize(os
);
255 BaseKvmCPU::unserializeThread(Checkpoint
*cp
, const std::string
§ion
,
258 DPRINTF(Checkpoint
, "KVM: Unserialize thread %i:\n", tid
);
261 assert(_status
== Idle
);
262 thread
->unserialize(cp
, section
);
263 threadContextDirty
= true;
267 BaseKvmCPU::drain(DrainManager
*dm
)
272 DPRINTF(Drain
, "BaseKvmCPU::drain\n");
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
280 if (!archIsDrained()) {
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
);
295 // Idle, no need to drain
296 assert(!tickEvent
.scheduled());
298 // Sync the thread context here since we'll need it when we
299 // switch CPUs or checkpoint the CPU.
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.
313 DPRINTF(Drain
, "KVM CPU is waiting for service completion, "
314 "requesting drain.\n");
318 // We need to drain since the CPU is waiting for service (e.g., MMIOs)
321 DPRINTF(Drain
, "KVM CPU is waiting for service, requesting drain.\n");
325 panic("KVM: Unhandled CPU state in drain()\n");
331 BaseKvmCPU::drainResume()
333 assert(!tickEvent
.scheduled());
335 // We might have been switched out. In that case, we don't need to
340 DPRINTF(Kvm
, "drainResume\n");
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());
354 BaseKvmCPU::switchOut()
356 DPRINTF(Kvm
, "switchOut\n");
358 BaseCPU::switchOut();
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
363 assert(!tickEvent
.scheduled());
364 assert(_status
== Idle
);
368 BaseKvmCPU::takeOverFrom(BaseCPU
*cpu
)
370 DPRINTF(Kvm
, "takeOverFrom\n");
372 BaseCPU::takeOverFrom(cpu
);
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
377 assert(!tickEvent
.scheduled());
378 assert(_status
== Idle
);
379 assert(threadContexts
.size() == 1);
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.
386 threadContextDirty
= false;
390 BaseKvmCPU::verifyMemoryMode() const
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");
401 DPRINTF(Kvm
, "wakeup()\n");
403 if (thread
->status() != ThreadContext::Suspended
)
410 BaseKvmCPU::activateContext(ThreadID thread_num
, Cycles delay
)
412 DPRINTF(Kvm
, "ActivateContext %d (%d cycles)\n", thread_num
, delay
);
414 assert(thread_num
== 0);
417 assert(_status
== Idle
);
418 assert(!tickEvent
.scheduled());
420 numCycles
+= ticksToCycles(thread
->lastActivate
- thread
->lastSuspend
);
422 schedule(tickEvent
, clockEdge(delay
));
428 BaseKvmCPU::suspendContext(ThreadID thread_num
)
430 DPRINTF(Kvm
, "SuspendContext %d\n", thread_num
);
432 assert(thread_num
== 0);
438 assert(_status
== Running
);
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
);
451 BaseKvmCPU::deallocateContext(ThreadID thread_num
)
453 // for now, these are equivalent
454 suspendContext(thread_num
);
458 BaseKvmCPU::haltContext(ThreadID thread_num
)
460 // for now, these are equivalent
461 suspendContext(thread_num
);
465 BaseKvmCPU::getContext(int tn
)
474 BaseKvmCPU::totalInsts() const
480 BaseKvmCPU::totalOps() const
482 hack_once("Pretending totalOps is equivalent to totalInsts()\n");
489 inform("State dumping not implemented.");
496 assert(_status
!= Idle
);
500 // handleKvmExit() will determine the next state of the CPU
501 delay
= handleKvmExit();
507 case RunningServiceCompletion
:
509 EventQueue
*q
= curEventQueue();
510 Tick
ticksToExecute(q
->nextTick() - curTick());
512 // We might need to update the KVM state.
515 // Setup any pending instruction count breakpoints using
519 DPRINTF(KvmRun
, "Entering KVM...\n");
521 // Force an immediate exit from KVM after completing
522 // pending operations. The architecture-specific code
523 // takes care to run until it is in a state where it can
524 // safely be drained.
525 delay
= kvmRunDrain();
527 delay
= kvmRun(ticksToExecute
);
530 // Entering into KVM implies that we'll have to reload the thread
531 // context from KVM if we want to access it. Flag the KVM state as
532 // dirty with respect to the cached thread context.
533 kvmStateDirty
= true;
535 // Enter into the RunningService state unless the
536 // simulation was stopped by a timer.
537 if (_kvmRun
->exit_reason
!= KVM_EXIT_INTR
) {
538 _status
= RunningService
;
544 // Service any pending instruction events. The vCPU should
545 // have exited in time for the event using the instruction
546 // counter configured by setupInstStop().
547 comInstEventQueue
[0]->serviceEvents(ctrInsts
);
548 system
->instEventQueue
.serviceEvents(system
->totalNumInsts
);
555 panic("BaseKvmCPU entered tick() in an illegal state (%i)\n",
559 // Schedule a new tick if we are still running
561 schedule(tickEvent
, clockEdge(ticksToCycles(delay
)));
565 BaseKvmCPU::kvmRunDrain()
567 // By default, the only thing we need to drain is a pending IO
568 // operation which assumes that we are in the
569 // RunningServiceCompletion state.
570 assert(_status
== RunningServiceCompletion
);
572 // Deliver the data from the pending IO operation and immediately
578 BaseKvmCPU::getHostCycles() const
580 return hwCycles
.read();
584 BaseKvmCPU::kvmRun(Tick ticks
)
587 DPRINTF(KvmRun
, "KVM: Executing for %i ticks\n", ticks
);
588 timerOverflowed
= false;
591 // Settings ticks == 0 is a special case which causes an entry
592 // into KVM that finishes pending operations (e.g., IO) and
593 // then immediately exits.
594 DPRINTF(KvmRun
, "KVM: Delivering IO without full guest entry\n");
598 // This signal is always masked while we are executing in gem5
599 // and gets unmasked temporarily as soon as we enter into
600 // KVM. See setSignalMask() and setupSignalHandler().
601 raise(KVM_TIMER_SIGNAL
);
603 // Enter into KVM. KVM will check for signals after completing
604 // pending operations (IO). Since the KVM_TIMER_SIGNAL is
605 // pending, this forces an immediate exit into gem5 again. We
606 // don't bother to setup timers since this shouldn't actually
607 // execute any code in the guest.
610 // We always execute at least one cycle to prevent the
611 // BaseKvmCPU::tick() to be rescheduled on the same tick
613 ticksExecuted
= clockPeriod();
615 if (ticks
< runTimer
->resolution()) {
616 DPRINTF(KvmRun
, "KVM: Adjusting tick count (%i -> %i)\n",
617 ticks
, runTimer
->resolution());
618 ticks
= runTimer
->resolution();
621 // Get hardware statistics after synchronizing contexts. The KVM
622 // state update might affect guest cycle counters.
623 uint64_t baseCycles(getHostCycles());
624 uint64_t baseInstrs(hwInstructions
.read());
626 // Arm the run timer and start the cycle timer if it isn't
627 // controlled by the overflow timer. Starting/stopping the cycle
628 // timer automatically starts the other perf timers as they are in
629 // the same counter group.
630 runTimer
->arm(ticks
);
631 if (!perfControlledByTimer
)
637 if (!perfControlledByTimer
)
640 // The timer signal may have been delivered after we exited
641 // from KVM. It will be pending in that case since it is
642 // masked when we aren't executing in KVM. Discard it to make
643 // sure we don't deliver it immediately next time we try to
645 discardPendingSignal(KVM_TIMER_SIGNAL
);
646 discardPendingSignal(KVM_INST_SIGNAL
);
648 const uint64_t hostCyclesExecuted(getHostCycles() - baseCycles
);
649 const uint64_t simCyclesExecuted(hostCyclesExecuted
* hostFactor
);
650 const uint64_t instsExecuted(hwInstructions
.read() - baseInstrs
);
651 ticksExecuted
= runTimer
->ticksFromHostCycles(hostCyclesExecuted
);
653 if (ticksExecuted
< ticks
&&
655 _kvmRun
->exit_reason
== KVM_EXIT_INTR
) {
656 // TODO: We should probably do something clever here...
657 warn("KVM: Early timer event, requested %i ticks but got %i ticks.\n",
658 ticks
, ticksExecuted
);
661 /* Update statistics */
662 numCycles
+= simCyclesExecuted
;;
663 numInsts
+= instsExecuted
;
664 ctrInsts
+= instsExecuted
;
665 system
->totalNumInsts
+= instsExecuted
;
668 "KVM: Executed %i instructions in %i cycles "
669 "(%i ticks, sim cycles: %i).\n",
670 instsExecuted
, hostCyclesExecuted
, ticksExecuted
, simCyclesExecuted
);
675 return ticksExecuted
+ flushCoalescedMMIO();
679 BaseKvmCPU::kvmNonMaskableInterrupt()
682 if (ioctl(KVM_NMI
) == -1)
683 panic("KVM: Failed to deliver NMI to virtual CPU\n");
687 BaseKvmCPU::kvmInterrupt(const struct kvm_interrupt
&interrupt
)
690 if (ioctl(KVM_INTERRUPT
, (void *)&interrupt
) == -1)
691 panic("KVM: Failed to deliver interrupt to virtual CPU\n");
695 BaseKvmCPU::getRegisters(struct kvm_regs
®s
) const
697 if (ioctl(KVM_GET_REGS
, ®s
) == -1)
698 panic("KVM: Failed to get guest registers\n");
702 BaseKvmCPU::setRegisters(const struct kvm_regs
®s
)
704 if (ioctl(KVM_SET_REGS
, (void *)®s
) == -1)
705 panic("KVM: Failed to set guest registers\n");
709 BaseKvmCPU::getSpecialRegisters(struct kvm_sregs
®s
) const
711 if (ioctl(KVM_GET_SREGS
, ®s
) == -1)
712 panic("KVM: Failed to get guest special registers\n");
716 BaseKvmCPU::setSpecialRegisters(const struct kvm_sregs
®s
)
718 if (ioctl(KVM_SET_SREGS
, (void *)®s
) == -1)
719 panic("KVM: Failed to set guest special registers\n");
723 BaseKvmCPU::getFPUState(struct kvm_fpu
&state
) const
725 if (ioctl(KVM_GET_FPU
, &state
) == -1)
726 panic("KVM: Failed to get guest FPU state\n");
730 BaseKvmCPU::setFPUState(const struct kvm_fpu
&state
)
732 if (ioctl(KVM_SET_FPU
, (void *)&state
) == -1)
733 panic("KVM: Failed to set guest FPU state\n");
738 BaseKvmCPU::setOneReg(uint64_t id
, const void *addr
)
740 #ifdef KVM_SET_ONE_REG
741 struct kvm_one_reg reg
;
743 reg
.addr
= (uint64_t)addr
;
745 if (ioctl(KVM_SET_ONE_REG
, ®
) == -1) {
746 panic("KVM: Failed to set register (0x%x) value (errno: %i)\n",
750 panic("KVM_SET_ONE_REG is unsupported on this platform.\n");
755 BaseKvmCPU::getOneReg(uint64_t id
, void *addr
) const
757 #ifdef KVM_GET_ONE_REG
758 struct kvm_one_reg reg
;
760 reg
.addr
= (uint64_t)addr
;
762 if (ioctl(KVM_GET_ONE_REG
, ®
) == -1) {
763 panic("KVM: Failed to get register (0x%x) value (errno: %i)\n",
767 panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
772 BaseKvmCPU::getAndFormatOneReg(uint64_t id
) const
774 #ifdef KVM_GET_ONE_REG
775 std::ostringstream ss
;
777 ss
.setf(std::ios::hex
, std::ios::basefield
);
778 ss
.setf(std::ios::showbase
);
779 #define HANDLE_INTTYPE(len) \
780 case KVM_REG_SIZE_U ## len: { \
781 uint ## len ## _t value; \
782 getOneReg(id, &value); \
786 #define HANDLE_ARRAY(len) \
787 case KVM_REG_SIZE_U ## len: { \
788 uint8_t value[len / 8]; \
789 getOneReg(id, value); \
790 ss << "[" << value[0]; \
791 for (int i = 1; i < len / 8; ++i) \
792 ss << ", " << value[i]; \
796 switch (id
& KVM_REG_SIZE_MASK
) {
809 #undef HANDLE_INTTYPE
814 panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
819 BaseKvmCPU::syncThreadContext()
824 assert(!threadContextDirty
);
826 updateThreadContext();
827 kvmStateDirty
= false;
831 BaseKvmCPU::syncKvmState()
833 if (!threadContextDirty
)
836 assert(!kvmStateDirty
);
839 threadContextDirty
= false;
843 BaseKvmCPU::handleKvmExit()
845 DPRINTF(KvmRun
, "handleKvmExit (exit_reason: %i)\n", _kvmRun
->exit_reason
);
846 assert(_status
== RunningService
);
848 // Switch into the running state by default. Individual handlers
849 // can override this.
851 switch (_kvmRun
->exit_reason
) {
852 case KVM_EXIT_UNKNOWN
:
853 return handleKvmExitUnknown();
855 case KVM_EXIT_EXCEPTION
:
856 return handleKvmExitException();
859 _status
= RunningServiceCompletion
;
861 return handleKvmExitIO();
863 case KVM_EXIT_HYPERCALL
:
865 return handleKvmExitHypercall();
868 /* The guest has halted and is waiting for interrupts */
869 DPRINTF(Kvm
, "handleKvmExitHalt\n");
872 // Suspend the thread until the next interrupt arrives
875 // This is actually ignored since the thread is suspended.
879 _status
= RunningServiceCompletion
;
880 /* Service memory mapped IO requests */
881 DPRINTF(KvmIO
, "KVM: Handling MMIO (w: %u, addr: 0x%x, len: %u)\n",
882 _kvmRun
->mmio
.is_write
,
883 _kvmRun
->mmio
.phys_addr
, _kvmRun
->mmio
.len
);
886 return doMMIOAccess(_kvmRun
->mmio
.phys_addr
, _kvmRun
->mmio
.data
,
887 _kvmRun
->mmio
.len
, _kvmRun
->mmio
.is_write
);
889 case KVM_EXIT_IRQ_WINDOW_OPEN
:
890 return handleKvmExitIRQWindowOpen();
892 case KVM_EXIT_FAIL_ENTRY
:
893 return handleKvmExitFailEntry();
896 /* KVM was interrupted by a signal, restart it in the next
900 case KVM_EXIT_INTERNAL_ERROR
:
901 panic("KVM: Internal error (suberror: %u)\n",
902 _kvmRun
->internal
.suberror
);
906 panic("KVM: Unexpected exit (exit_reason: %u)\n", _kvmRun
->exit_reason
);
911 BaseKvmCPU::handleKvmExitIO()
913 panic("KVM: Unhandled guest IO (dir: %i, size: %i, port: 0x%x, count: %i)\n",
914 _kvmRun
->io
.direction
, _kvmRun
->io
.size
,
915 _kvmRun
->io
.port
, _kvmRun
->io
.count
);
919 BaseKvmCPU::handleKvmExitHypercall()
921 panic("KVM: Unhandled hypercall\n");
925 BaseKvmCPU::handleKvmExitIRQWindowOpen()
927 warn("KVM: Unhandled IRQ window.\n");
933 BaseKvmCPU::handleKvmExitUnknown()
936 panic("KVM: Unknown error when starting vCPU (hw reason: 0x%llx)\n",
937 _kvmRun
->hw
.hardware_exit_reason
);
941 BaseKvmCPU::handleKvmExitException()
944 panic("KVM: Got exception when starting vCPU "
945 "(exception: %u, error_code: %u)\n",
946 _kvmRun
->ex
.exception
, _kvmRun
->ex
.error_code
);
950 BaseKvmCPU::handleKvmExitFailEntry()
953 panic("KVM: Failed to enter virtualized mode (hw reason: 0x%llx)\n",
954 _kvmRun
->fail_entry
.hardware_entry_failure_reason
);
958 BaseKvmCPU::doMMIOAccess(Addr paddr
, void *data
, int size
, bool write
)
960 ThreadContext
*tc(thread
->getTC());
963 mmio_req
.setPhys(paddr
, size
, Request::UNCACHEABLE
, dataMasterId());
964 // Some architectures do need to massage physical addresses a bit
965 // before they are inserted into the memory system. This enables
966 // APIC accesses on x86 and m5ops where supported through a MMIO
968 BaseTLB::Mode
tlb_mode(write
? BaseTLB::Write
: BaseTLB::Read
);
969 Fault
fault(tc
->getDTBPtr()->finalizePhysical(&mmio_req
, tc
, tlb_mode
));
970 if (fault
!= NoFault
)
971 warn("Finalization of MMIO address failed: %s\n", fault
->name());
974 const MemCmd
cmd(write
? MemCmd::WriteReq
: MemCmd::ReadReq
);
975 Packet
pkt(&mmio_req
, cmd
);
976 pkt
.dataStatic(data
);
978 if (mmio_req
.isMmappedIpr()) {
979 const Cycles
ipr_delay(write
?
980 TheISA::handleIprWrite(tc
, &pkt
) :
981 TheISA::handleIprRead(tc
, &pkt
));
982 return clockPeriod() * ipr_delay
;
984 return dataPort
.sendAtomic(&pkt
);
989 BaseKvmCPU::setSignalMask(const sigset_t
*mask
)
991 std::unique_ptr
<struct kvm_signal_mask
> kvm_mask
;
994 kvm_mask
.reset((struct kvm_signal_mask
*)operator new(
995 sizeof(struct kvm_signal_mask
) + sizeof(*mask
)));
996 // The kernel and the user-space headers have different ideas
997 // about the size of sigset_t. This seems like a massive hack,
998 // but is actually what qemu does.
999 assert(sizeof(*mask
) >= 8);
1001 memcpy(kvm_mask
->sigset
, mask
, kvm_mask
->len
);
1004 if (ioctl(KVM_SET_SIGNAL_MASK
, (void *)kvm_mask
.get()) == -1)
1005 panic("KVM: Failed to set vCPU signal mask (errno: %i)\n",
1010 BaseKvmCPU::ioctl(int request
, long p1
) const
1013 panic("KVM: CPU ioctl called before initialization\n");
1015 return ::ioctl(vcpuFD
, request
, p1
);
1019 BaseKvmCPU::flushCoalescedMMIO()
1024 DPRINTF(KvmIO
, "KVM: Flushing the coalesced MMIO ring buffer\n");
1026 // TODO: We might need to do synchronization when we start to
1027 // support multiple CPUs
1029 while (mmioRing
->first
!= mmioRing
->last
) {
1030 struct kvm_coalesced_mmio
&ent(
1031 mmioRing
->coalesced_mmio
[mmioRing
->first
]);
1033 DPRINTF(KvmIO
, "KVM: Handling coalesced MMIO (addr: 0x%x, len: %u)\n",
1034 ent
.phys_addr
, ent
.len
);
1037 ticks
+= doMMIOAccess(ent
.phys_addr
, ent
.data
, ent
.len
, true);
1039 mmioRing
->first
= (mmioRing
->first
+ 1) % KVM_COALESCED_MMIO_MAX
;
1046 * Cycle timer overflow when running in KVM. Forces the KVM syscall to
1047 * exit with EINTR and allows us to run the event queue.
1050 onTimerOverflow(int signo
, siginfo_t
*si
, void *data
)
1052 timerOverflowed
= true;
1056 * Instruction counter overflow when running in KVM. Forces the KVM
1057 * syscall to exit with EINTR and allows us to handle instruction
1061 onInstEvent(int signo
, siginfo_t
*si
, void *data
)
1066 BaseKvmCPU::setupSignalHandler()
1068 struct sigaction sa
;
1070 memset(&sa
, 0, sizeof(sa
));
1071 sa
.sa_sigaction
= onTimerOverflow
;
1072 sa
.sa_flags
= SA_SIGINFO
| SA_RESTART
;
1073 if (sigaction(KVM_TIMER_SIGNAL
, &sa
, NULL
) == -1)
1074 panic("KVM: Failed to setup vCPU timer signal handler\n");
1076 memset(&sa
, 0, sizeof(sa
));
1077 sa
.sa_sigaction
= onInstEvent
;
1078 sa
.sa_flags
= SA_SIGINFO
| SA_RESTART
;
1079 if (sigaction(KVM_INST_SIGNAL
, &sa
, NULL
) == -1)
1080 panic("KVM: Failed to setup vCPU instruction signal handler\n");
1083 if (sigprocmask(SIG_BLOCK
, NULL
, &sigset
) == -1)
1084 panic("KVM: Failed get signal mask\n");
1086 // Request KVM to setup the same signal mask as we're currently
1087 // running with. We'll sometimes need to mask the KVM_TIMER_SIGNAL
1088 // to cause immediate exits from KVM after servicing IO
1089 // requests. See kvmRun().
1090 setSignalMask(&sigset
);
1092 // Mask our control signals so they aren't delivered unless we're
1093 // actually executing inside KVM.
1094 sigaddset(&sigset
, KVM_TIMER_SIGNAL
);
1095 sigaddset(&sigset
, KVM_INST_SIGNAL
);
1096 if (sigprocmask(SIG_SETMASK
, &sigset
, NULL
) == -1)
1097 panic("KVM: Failed mask the KVM control signals\n");
1101 BaseKvmCPU::discardPendingSignal(int signum
) const
1103 int discardedSignal
;
1105 // Setting the timeout to zero causes sigtimedwait to return
1107 struct timespec timeout
;
1109 timeout
.tv_nsec
= 0;
1112 sigemptyset(&sigset
);
1113 sigaddset(&sigset
, signum
);
1116 discardedSignal
= sigtimedwait(&sigset
, NULL
, &timeout
);
1117 } while (discardedSignal
== -1 && errno
== EINTR
);
1119 if (discardedSignal
== signum
)
1121 else if (discardedSignal
== -1 && errno
== EAGAIN
)
1124 panic("Unexpected return value from sigtimedwait: %i (errno: %i)\n",
1125 discardedSignal
, errno
);
1129 BaseKvmCPU::setupCounters()
1131 DPRINTF(Kvm
, "Attaching cycle counter...\n");
1132 PerfKvmCounterConfig
cfgCycles(PERF_TYPE_HARDWARE
,
1133 PERF_COUNT_HW_CPU_CYCLES
);
1134 cfgCycles
.disabled(true)
1137 if (perfControlledByTimer
) {
1138 // We need to configure the cycles counter to send overflows
1139 // since we are going to use it to trigger timer signals that
1140 // trap back into m5 from KVM. In practice, this means that we
1141 // need to set some non-zero sample period that gets
1142 // overridden when the timer is armed.
1143 cfgCycles
.wakeupEvents(1)
1147 hwCycles
.attach(cfgCycles
,
1148 0); // TID (0 => currentThread)
1154 BaseKvmCPU::tryDrain()
1159 if (!archIsDrained()) {
1160 DPRINTF(Drain
, "tryDrain: Architecture code is not ready.\n");
1164 if (_status
== Idle
|| _status
== Running
) {
1166 "tryDrain: CPU transitioned into the Idle state, drain done\n");
1167 drainManager
->signalDrainDone();
1168 drainManager
= NULL
;
1171 DPRINTF(Drain
, "tryDrain: CPU not ready.\n");
1177 BaseKvmCPU::ioctlRun()
1179 if (ioctl(KVM_RUN
) == -1) {
1181 panic("KVM: Failed to start virtual CPU (errno: %i)\n",
1187 BaseKvmCPU::setupInstStop()
1189 if (comInstEventQueue
[0]->empty()) {
1190 setupInstCounter(0);
1192 const uint64_t next(comInstEventQueue
[0]->nextTick());
1194 assert(next
> ctrInsts
);
1195 setupInstCounter(next
- ctrInsts
);
1200 BaseKvmCPU::setupInstCounter(uint64_t period
)
1202 // No need to do anything if we aren't attaching for the first
1203 // time or the period isn't changing.
1204 if (period
== activeInstPeriod
&& hwInstructions
.attached())
1207 PerfKvmCounterConfig
cfgInstructions(PERF_TYPE_HARDWARE
,
1208 PERF_COUNT_HW_INSTRUCTIONS
);
1211 // Setup a sampling counter if that has been requested.
1212 cfgInstructions
.wakeupEvents(1)
1213 .samplePeriod(period
);
1216 // We need to detach and re-attach the counter to reliably change
1217 // sampling settings. See PerfKvmCounter::period() for details.
1218 if (hwInstructions
.attached())
1219 hwInstructions
.detach();
1220 assert(hwCycles
.attached());
1221 hwInstructions
.attach(cfgInstructions
,
1222 0, // TID (0 => currentThread)
1226 hwInstructions
.enableSignals(KVM_INST_SIGNAL
);
1228 activeInstPeriod
= period
;