2 * Copyright (c) 2012, 2015, 2017 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.
38 #include "cpu/kvm/base.hh"
40 #include <linux/kvm.h>
41 #include <sys/ioctl.h>
49 #include "arch/utility.hh"
50 #include "debug/Checkpoint.hh"
51 #include "debug/Drain.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 BaseKvmCPU::BaseKvmCPU(BaseKvmCPUParams
*params
)
64 vm(*params
->system
->getKvmVM()),
66 dataPort(name() + ".dcache_port", this),
67 instPort(name() + ".icache_port", this),
68 alwaysSyncTC(params
->alwaysSyncTC
),
69 threadContextDirty(true),
71 vcpuID(vm
.allocVCPUID()), vcpuFD(-1), vcpuMMapSize(0),
72 _kvmRun(NULL
), mmioRing(NULL
),
73 pageSize(sysconf(_SC_PAGE_SIZE
)),
74 tickEvent([this]{ tick(); }, "BaseKvmCPU tick",
75 false, Event::CPU_Tick_Pri
),
77 perfControlledByTimer(params
->usePerfOverflow
),
78 hostFactor(params
->hostFactor
),
82 panic("KVM: Failed to determine host page size (%i)\n",
86 thread
= new SimpleThread(this, 0, params
->system
, params
->itb
, params
->dtb
,
89 thread
= new SimpleThread(this, /* thread_num */ 0, params
->system
,
90 params
->workload
[0], params
->itb
,
91 params
->dtb
, params
->isa
[0]);
93 thread
->setStatus(ThreadContext::Halted
);
95 threadContexts
.push_back(tc
);
98 BaseKvmCPU::~BaseKvmCPU()
101 munmap(_kvmRun
, vcpuMMapSize
);
111 fatal("KVM: Multithreading not supported");
113 tc
->initMemProxies(tc
);
117 BaseKvmCPU::startup()
119 const BaseKvmCPUParams
* const p(
120 dynamic_cast<const BaseKvmCPUParams
*>(params()));
126 assert(vcpuFD
== -1);
128 // Tell the VM that a CPU is about to start.
131 // We can't initialize KVM CPUs in BaseKvmCPU::init() since we are
132 // not guaranteed that the parent KVM VM has initialized at that
133 // point. Initialize virtual CPUs here instead.
134 vcpuFD
= vm
.createVCPU(vcpuID
);
136 // Map the KVM run structure */
137 vcpuMMapSize
= kvm
.getVCPUMMapSize();
138 _kvmRun
= (struct kvm_run
*)mmap(0, vcpuMMapSize
,
139 PROT_READ
| PROT_WRITE
, MAP_SHARED
,
141 if (_kvmRun
== MAP_FAILED
)
142 panic("KVM: Failed to map run data structure\n");
144 // Setup a pointer to the MMIO ring buffer if coalesced MMIO is
145 // available. The offset into the KVM's communication page is
146 // provided by the coalesced MMIO capability.
147 int mmioOffset(kvm
.capCoalescedMMIO());
148 if (!p
->useCoalescedMMIO
) {
149 inform("KVM: Coalesced MMIO disabled by config.\n");
150 } else if (mmioOffset
) {
151 inform("KVM: Coalesced IO available\n");
152 mmioRing
= (struct kvm_coalesced_mmio_ring
*)(
153 (char *)_kvmRun
+ (mmioOffset
* pageSize
));
155 inform("KVM: Coalesced not supported by host OS\n");
161 new EventFunctionWrapper([this]{ startupThread(); }, name(), true));
162 schedule(startupEvent
, curTick());
166 BaseKvmCPU::KVMCpuPort::nextIOState() const
168 return (activeMMIOReqs
|| pendingMMIOPkts
.size())
169 ? RunningMMIOPending
: RunningServiceCompletion
;
173 BaseKvmCPU::KVMCpuPort::submitIO(PacketPtr pkt
)
175 if (cpu
->system
->isAtomicMode()) {
176 Tick delay
= sendAtomic(pkt
);
180 if (pendingMMIOPkts
.empty() && sendTimingReq(pkt
)) {
183 pendingMMIOPkts
.push(pkt
);
185 // Return value is irrelevant for timing-mode accesses.
191 BaseKvmCPU::KVMCpuPort::recvTimingResp(PacketPtr pkt
)
193 DPRINTF(KvmIO
, "KVM: Finished timing request\n");
198 // We can switch back into KVM when all pending and in-flight MMIO
199 // operations have completed.
200 if (!(activeMMIOReqs
|| pendingMMIOPkts
.size())) {
201 DPRINTF(KvmIO
, "KVM: Finished all outstanding timing requests\n");
202 cpu
->finishMMIOPending();
208 BaseKvmCPU::KVMCpuPort::recvReqRetry()
210 DPRINTF(KvmIO
, "KVM: Retry for timing request\n");
212 assert(pendingMMIOPkts
.size());
214 // Assuming that we can issue infinite requests this cycle is a bit
215 // unrealistic, but it's not worth modeling something more complex in
217 while (pendingMMIOPkts
.size() && sendTimingReq(pendingMMIOPkts
.front())) {
218 pendingMMIOPkts
.pop();
224 BaseKvmCPU::finishMMIOPending()
226 assert(_status
= RunningMMIOPending
);
227 assert(!tickEvent
.scheduled());
229 _status
= RunningServiceCompletion
;
230 schedule(tickEvent
, nextCycle());
234 BaseKvmCPU::startupThread()
236 // Do thread-specific initialization. We need to setup signal
237 // delivery for counters and timers from within the thread that
238 // will execute the event queue to ensure that signals are
239 // delivered to the right threads.
240 const BaseKvmCPUParams
* const p(
241 dynamic_cast<const BaseKvmCPUParams
*>(params()));
243 vcpuThread
= pthread_self();
245 // Setup signal handlers. This has to be done after the vCPU is
246 // created since it manipulates the vCPU signal mask.
247 setupSignalHandler();
251 if (p
->usePerfOverflow
)
252 runTimer
.reset(new PerfKvmTimer(hwCycles
,
257 runTimer
.reset(new PosixKvmTimer(KVM_KICK_SIGNAL
, CLOCK_MONOTONIC
,
264 BaseKvmCPU::regStats()
266 using namespace Stats
;
271 .name(name() + ".committedInsts")
272 .desc("Number of instructions committed")
276 .name(name() + ".numVMExits")
277 .desc("total number of KVM exits")
281 .name(name() + ".numVMHalfEntries")
282 .desc("number of KVM entries to finalize pending operations")
286 .name(name() + ".numExitSignal")
287 .desc("exits due to signal delivery")
291 .name(name() + ".numMMIO")
292 .desc("number of VM exits due to memory mapped IO")
296 .name(name() + ".numCoalescedMMIO")
297 .desc("number of coalesced memory mapped IO requests")
301 .name(name() + ".numIO")
302 .desc("number of VM exits due to legacy IO")
306 .name(name() + ".numHalt")
307 .desc("number of VM exits due to wait for interrupt instructions")
311 .name(name() + ".numInterrupts")
312 .desc("number of interrupts delivered")
316 .name(name() + ".numHypercalls")
317 .desc("number of hypercalls")
322 BaseKvmCPU::serializeThread(CheckpointOut
&cp
, ThreadID tid
) const
324 if (DTRACE(Checkpoint
)) {
325 DPRINTF(Checkpoint
, "KVM: Serializing thread %i:\n", tid
);
330 assert(_status
== Idle
);
331 thread
->serialize(cp
);
335 BaseKvmCPU::unserializeThread(CheckpointIn
&cp
, ThreadID tid
)
337 DPRINTF(Checkpoint
, "KVM: Unserialize thread %i:\n", tid
);
340 assert(_status
== Idle
);
341 thread
->unserialize(cp
);
342 threadContextDirty
= true;
349 return DrainState::Drained
;
351 DPRINTF(Drain
, "BaseKvmCPU::drain\n");
353 // The event queue won't be locked when calling drain since that's
354 // not done from an event. Lock the event queue here to make sure
355 // that scoped migrations continue to work if we need to
356 // synchronize the thread context.
357 std::lock_guard
<EventQueue
> lock(*this->eventQueue());
361 // The base KVM code is normally ready when it is in the
362 // Running state, but the architecture specific code might be
363 // of a different opinion. This may happen when the CPU been
364 // notified of an event that hasn't been accepted by the vCPU
366 if (!archIsDrained())
367 return DrainState::Draining
;
369 // The state of the CPU is consistent, so we don't need to do
370 // anything special to drain it. We simply de-schedule the
371 // tick event and enter the Idle state to prevent nasty things
372 // like MMIOs from happening.
373 if (tickEvent
.scheduled())
374 deschedule(tickEvent
);
379 // Idle, no need to drain
380 assert(!tickEvent
.scheduled());
382 // Sync the thread context here since we'll need it when we
383 // switch CPUs or checkpoint the CPU.
386 return DrainState::Drained
;
388 case RunningServiceCompletion
:
389 // The CPU has just requested a service that was handled in
390 // the RunningService state, but the results have still not
391 // been reported to the CPU. Now, we /could/ probably just
392 // update the register state ourselves instead of letting KVM
393 // handle it, but that would be tricky. Instead, we enter KVM
394 // and let it do its stuff.
395 DPRINTF(Drain
, "KVM CPU is waiting for service completion, "
396 "requesting drain.\n");
397 return DrainState::Draining
;
399 case RunningMMIOPending
:
400 // We need to drain since there are in-flight timing accesses
401 DPRINTF(Drain
, "KVM CPU is waiting for timing accesses to complete, "
402 "requesting drain.\n");
403 return DrainState::Draining
;
406 // We need to drain since the CPU is waiting for service (e.g., MMIOs)
407 DPRINTF(Drain
, "KVM CPU is waiting for service, requesting drain.\n");
408 return DrainState::Draining
;
411 panic("KVM: Unhandled CPU state in drain()\n");
412 return DrainState::Drained
;
417 BaseKvmCPU::drainResume()
419 assert(!tickEvent
.scheduled());
421 // We might have been switched out. In that case, we don't need to
426 DPRINTF(Kvm
, "drainResume\n");
429 // The tick event is de-scheduled as a part of the draining
430 // process. Re-schedule it if the thread context is active.
431 if (tc
->status() == ThreadContext::Active
) {
432 schedule(tickEvent
, nextCycle());
440 BaseKvmCPU::notifyFork()
442 // We should have drained prior to forking, which means that the
443 // tick event shouldn't be scheduled and the CPU is idle.
444 assert(!tickEvent
.scheduled());
445 assert(_status
== Idle
);
448 if (close(vcpuFD
) == -1)
449 warn("kvm CPU: notifyFork failed to close vcpuFD\n");
452 munmap(_kvmRun
, vcpuMMapSize
);
457 hwInstructions
.detach();
463 BaseKvmCPU::switchOut()
465 DPRINTF(Kvm
, "switchOut\n");
467 BaseCPU::switchOut();
469 // We should have drained prior to executing a switchOut, which
470 // means that the tick event shouldn't be scheduled and the CPU is
472 assert(!tickEvent
.scheduled());
473 assert(_status
== Idle
);
477 BaseKvmCPU::takeOverFrom(BaseCPU
*cpu
)
479 DPRINTF(Kvm
, "takeOverFrom\n");
481 BaseCPU::takeOverFrom(cpu
);
483 // We should have drained prior to executing a switchOut, which
484 // means that the tick event shouldn't be scheduled and the CPU is
486 assert(!tickEvent
.scheduled());
487 assert(_status
== Idle
);
488 assert(threadContexts
.size() == 1);
490 // Force an update of the KVM state here instead of flagging the
491 // TC as dirty. This is not ideal from a performance point of
492 // view, but it makes debugging easier as it allows meaningful KVM
493 // state to be dumped before and after a takeover.
495 threadContextDirty
= false;
499 BaseKvmCPU::verifyMemoryMode() const
501 if (!(system
->bypassCaches())) {
502 fatal("The KVM-based CPUs requires the memory system to be in the "
503 "'noncaching' mode.\n");
508 BaseKvmCPU::wakeup(ThreadID tid
)
510 DPRINTF(Kvm
, "wakeup()\n");
511 // This method might have been called from another
512 // context. Migrate to this SimObject's event queue when
513 // delivering the wakeup signal.
514 EventQueue::ScopedMigration
migrate(eventQueue());
516 // Kick the vCPU to get it to come out of KVM.
519 if (thread
->status() != ThreadContext::Suspended
)
526 BaseKvmCPU::activateContext(ThreadID thread_num
)
528 DPRINTF(Kvm
, "ActivateContext %d\n", thread_num
);
530 assert(thread_num
== 0);
533 assert(_status
== Idle
);
534 assert(!tickEvent
.scheduled());
536 numCycles
+= ticksToCycles(thread
->lastActivate
- thread
->lastSuspend
);
538 schedule(tickEvent
, clockEdge(Cycles(0)));
544 BaseKvmCPU::suspendContext(ThreadID thread_num
)
546 DPRINTF(Kvm
, "SuspendContext %d\n", thread_num
);
548 assert(thread_num
== 0);
554 assert(_status
== Running
|| _status
== RunningServiceCompletion
);
556 // The tick event may no be scheduled if the quest has requested
557 // the monitor to wait for interrupts. The normal CPU models can
558 // get their tick events descheduled by quiesce instructions, but
559 // that can't happen here.
560 if (tickEvent
.scheduled())
561 deschedule(tickEvent
);
567 BaseKvmCPU::deallocateContext(ThreadID thread_num
)
569 // for now, these are equivalent
570 suspendContext(thread_num
);
574 BaseKvmCPU::haltContext(ThreadID thread_num
)
576 // for now, these are equivalent
577 suspendContext(thread_num
);
578 updateCycleCounters(BaseCPU::CPU_STATE_SLEEP
);
582 BaseKvmCPU::getContext(int tn
)
591 BaseKvmCPU::totalInsts() const
597 BaseKvmCPU::totalOps() const
599 hack_once("Pretending totalOps is equivalent to totalInsts()\n");
604 BaseKvmCPU::dump() const
606 inform("State dumping not implemented.");
613 assert(_status
!= Idle
&& _status
!= RunningMMIOPending
);
617 // handleKvmExit() will determine the next state of the CPU
618 delay
= handleKvmExit();
624 case RunningServiceCompletion
:
626 auto &queue
= thread
->comInstEventQueue
;
627 const uint64_t nextInstEvent(
628 queue
.empty() ? MaxTick
: queue
.nextTick());
629 // Enter into KVM and complete pending IO instructions if we
630 // have an instruction event pending.
631 const Tick
ticksToExecute(
632 nextInstEvent
> ctrInsts
?
633 curEventQueue()->nextTick() - curTick() : 0);
636 threadContextDirty
= true;
638 // We might need to update the KVM state.
641 // Setup any pending instruction count breakpoints using
642 // PerfEvent if we are going to execute more than just an IO
644 if (ticksToExecute
> 0)
647 DPRINTF(KvmRun
, "Entering KVM...\n");
648 if (drainState() == DrainState::Draining
) {
649 // Force an immediate exit from KVM after completing
650 // pending operations. The architecture-specific code
651 // takes care to run until it is in a state where it can
652 // safely be drained.
653 delay
= kvmRunDrain();
655 delay
= kvmRun(ticksToExecute
);
658 // The CPU might have been suspended before entering into
659 // KVM. Assume that the CPU was suspended /before/ entering
660 // into KVM and skip the exit handling.
664 // Entering into KVM implies that we'll have to reload the thread
665 // context from KVM if we want to access it. Flag the KVM state as
666 // dirty with respect to the cached thread context.
667 kvmStateDirty
= true;
672 // Enter into the RunningService state unless the
673 // simulation was stopped by a timer.
674 if (_kvmRun
->exit_reason
!= KVM_EXIT_INTR
) {
675 _status
= RunningService
;
681 // Service any pending instruction events. The vCPU should
682 // have exited in time for the event using the instruction
683 // counter configured by setupInstStop().
684 queue
.serviceEvents(ctrInsts
);
691 panic("BaseKvmCPU entered tick() in an illegal state (%i)\n",
695 // Schedule a new tick if we are still running
696 if (_status
!= Idle
&& _status
!= RunningMMIOPending
)
697 schedule(tickEvent
, clockEdge(ticksToCycles(delay
)));
701 BaseKvmCPU::kvmRunDrain()
703 // By default, the only thing we need to drain is a pending IO
704 // operation which assumes that we are in the
705 // RunningServiceCompletion or RunningMMIOPending state.
706 assert(_status
== RunningServiceCompletion
||
707 _status
== RunningMMIOPending
);
709 // Deliver the data from the pending IO operation and immediately
715 BaseKvmCPU::getHostCycles() const
717 return hwCycles
.read();
721 BaseKvmCPU::kvmRun(Tick ticks
)
724 fatal_if(vcpuFD
== -1,
725 "Trying to run a KVM CPU in a forked child process. "
726 "This is not supported.\n");
727 DPRINTF(KvmRun
, "KVM: Executing for %i ticks\n", ticks
);
730 // Settings ticks == 0 is a special case which causes an entry
731 // into KVM that finishes pending operations (e.g., IO) and
732 // then immediately exits.
733 DPRINTF(KvmRun
, "KVM: Delivering IO without full guest entry\n");
737 // Send a KVM_KICK_SIGNAL to the vCPU thread (i.e., this
738 // thread). The KVM control signal is masked while executing
739 // in gem5 and gets unmasked temporarily as when entering
740 // KVM. See setSignalMask() and setupSignalHandler().
743 // Start the vCPU. KVM will check for signals after completing
744 // pending operations (IO). Since the KVM_KICK_SIGNAL is
745 // pending, this forces an immediate exit to gem5 again. We
746 // don't bother to setup timers since this shouldn't actually
747 // execute any code (other than completing half-executed IO
748 // instructions) in the guest.
751 // We always execute at least one cycle to prevent the
752 // BaseKvmCPU::tick() to be rescheduled on the same tick
754 ticksExecuted
= clockPeriod();
756 // This method is executed as a result of a tick event. That
757 // means that the event queue will be locked when entering the
758 // method. We temporarily unlock the event queue to allow
759 // other threads to steal control of this thread to inject
760 // interrupts. They will typically lock the queue and then
761 // force an exit from KVM by kicking the vCPU.
762 EventQueue::ScopedRelease
release(curEventQueue());
764 if (ticks
< runTimer
->resolution()) {
765 DPRINTF(KvmRun
, "KVM: Adjusting tick count (%i -> %i)\n",
766 ticks
, runTimer
->resolution());
767 ticks
= runTimer
->resolution();
770 // Get hardware statistics after synchronizing contexts. The KVM
771 // state update might affect guest cycle counters.
772 uint64_t baseCycles(getHostCycles());
773 uint64_t baseInstrs(hwInstructions
.read());
775 // Arm the run timer and start the cycle timer if it isn't
776 // controlled by the overflow timer. Starting/stopping the cycle
777 // timer automatically starts the other perf timers as they are in
778 // the same counter group.
779 runTimer
->arm(ticks
);
780 if (!perfControlledByTimer
)
786 if (!perfControlledByTimer
)
789 // The control signal may have been delivered after we exited
790 // from KVM. It will be pending in that case since it is
791 // masked when we aren't executing in KVM. Discard it to make
792 // sure we don't deliver it immediately next time we try to
794 discardPendingSignal(KVM_KICK_SIGNAL
);
796 const uint64_t hostCyclesExecuted(getHostCycles() - baseCycles
);
797 const uint64_t simCyclesExecuted(hostCyclesExecuted
* hostFactor
);
798 const uint64_t instsExecuted(hwInstructions
.read() - baseInstrs
);
799 ticksExecuted
= runTimer
->ticksFromHostCycles(hostCyclesExecuted
);
801 /* Update statistics */
802 numCycles
+= simCyclesExecuted
;;
803 numInsts
+= instsExecuted
;
804 ctrInsts
+= instsExecuted
;
805 system
->totalNumInsts
+= instsExecuted
;
808 "KVM: Executed %i instructions in %i cycles "
809 "(%i ticks, sim cycles: %i).\n",
810 instsExecuted
, hostCyclesExecuted
, ticksExecuted
, simCyclesExecuted
);
815 return ticksExecuted
+ flushCoalescedMMIO();
819 BaseKvmCPU::kvmNonMaskableInterrupt()
822 if (ioctl(KVM_NMI
) == -1)
823 panic("KVM: Failed to deliver NMI to virtual CPU\n");
827 BaseKvmCPU::kvmInterrupt(const struct kvm_interrupt
&interrupt
)
830 if (ioctl(KVM_INTERRUPT
, (void *)&interrupt
) == -1)
831 panic("KVM: Failed to deliver interrupt to virtual CPU\n");
835 BaseKvmCPU::getRegisters(struct kvm_regs
®s
) const
837 if (ioctl(KVM_GET_REGS
, ®s
) == -1)
838 panic("KVM: Failed to get guest registers\n");
842 BaseKvmCPU::setRegisters(const struct kvm_regs
®s
)
844 if (ioctl(KVM_SET_REGS
, (void *)®s
) == -1)
845 panic("KVM: Failed to set guest registers\n");
849 BaseKvmCPU::getSpecialRegisters(struct kvm_sregs
®s
) const
851 if (ioctl(KVM_GET_SREGS
, ®s
) == -1)
852 panic("KVM: Failed to get guest special registers\n");
856 BaseKvmCPU::setSpecialRegisters(const struct kvm_sregs
®s
)
858 if (ioctl(KVM_SET_SREGS
, (void *)®s
) == -1)
859 panic("KVM: Failed to set guest special registers\n");
863 BaseKvmCPU::getFPUState(struct kvm_fpu
&state
) const
865 if (ioctl(KVM_GET_FPU
, &state
) == -1)
866 panic("KVM: Failed to get guest FPU state\n");
870 BaseKvmCPU::setFPUState(const struct kvm_fpu
&state
)
872 if (ioctl(KVM_SET_FPU
, (void *)&state
) == -1)
873 panic("KVM: Failed to set guest FPU state\n");
878 BaseKvmCPU::setOneReg(uint64_t id
, const void *addr
)
880 #ifdef KVM_SET_ONE_REG
881 struct kvm_one_reg reg
;
883 reg
.addr
= (uint64_t)addr
;
885 if (ioctl(KVM_SET_ONE_REG
, ®
) == -1) {
886 panic("KVM: Failed to set register (0x%x) value (errno: %i)\n",
890 panic("KVM_SET_ONE_REG is unsupported on this platform.\n");
895 BaseKvmCPU::getOneReg(uint64_t id
, void *addr
) const
897 #ifdef KVM_GET_ONE_REG
898 struct kvm_one_reg reg
;
900 reg
.addr
= (uint64_t)addr
;
902 if (ioctl(KVM_GET_ONE_REG
, ®
) == -1) {
903 panic("KVM: Failed to get register (0x%x) value (errno: %i)\n",
907 panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
912 BaseKvmCPU::getAndFormatOneReg(uint64_t id
) const
914 #ifdef KVM_GET_ONE_REG
915 std::ostringstream ss
;
917 ss
.setf(std::ios::hex
, std::ios::basefield
);
918 ss
.setf(std::ios::showbase
);
919 #define HANDLE_INTTYPE(len) \
920 case KVM_REG_SIZE_U ## len: { \
921 uint ## len ## _t value; \
922 getOneReg(id, &value); \
926 #define HANDLE_ARRAY(len) \
927 case KVM_REG_SIZE_U ## len: { \
928 uint8_t value[len / 8]; \
929 getOneReg(id, value); \
930 ccprintf(ss, "[0x%x", value[0]); \
931 for (int i = 1; i < len / 8; ++i) \
932 ccprintf(ss, ", 0x%x", value[i]); \
936 switch (id
& KVM_REG_SIZE_MASK
) {
949 #undef HANDLE_INTTYPE
954 panic("KVM_GET_ONE_REG is unsupported on this platform.\n");
959 BaseKvmCPU::syncThreadContext()
964 assert(!threadContextDirty
);
966 updateThreadContext();
967 kvmStateDirty
= false;
971 BaseKvmCPU::syncKvmState()
973 if (!threadContextDirty
)
976 assert(!kvmStateDirty
);
979 threadContextDirty
= false;
983 BaseKvmCPU::handleKvmExit()
985 DPRINTF(KvmRun
, "handleKvmExit (exit_reason: %i)\n", _kvmRun
->exit_reason
);
986 assert(_status
== RunningService
);
988 // Switch into the running state by default. Individual handlers
989 // can override this.
991 switch (_kvmRun
->exit_reason
) {
992 case KVM_EXIT_UNKNOWN
:
993 return handleKvmExitUnknown();
995 case KVM_EXIT_EXCEPTION
:
996 return handleKvmExitException();
1001 Tick ticks
= handleKvmExitIO();
1002 _status
= dataPort
.nextIOState();
1006 case KVM_EXIT_HYPERCALL
:
1008 return handleKvmExitHypercall();
1011 /* The guest has halted and is waiting for interrupts */
1012 DPRINTF(Kvm
, "handleKvmExitHalt\n");
1015 // Suspend the thread until the next interrupt arrives
1018 // This is actually ignored since the thread is suspended.
1023 /* Service memory mapped IO requests */
1024 DPRINTF(KvmIO
, "KVM: Handling MMIO (w: %u, addr: 0x%x, len: %u)\n",
1025 _kvmRun
->mmio
.is_write
,
1026 _kvmRun
->mmio
.phys_addr
, _kvmRun
->mmio
.len
);
1029 Tick ticks
= doMMIOAccess(_kvmRun
->mmio
.phys_addr
, _kvmRun
->mmio
.data
,
1030 _kvmRun
->mmio
.len
, _kvmRun
->mmio
.is_write
);
1031 // doMMIOAccess could have triggered a suspend, in which case we don't
1032 // want to overwrite the _status.
1033 if (_status
!= Idle
)
1034 _status
= dataPort
.nextIOState();
1038 case KVM_EXIT_IRQ_WINDOW_OPEN
:
1039 return handleKvmExitIRQWindowOpen();
1041 case KVM_EXIT_FAIL_ENTRY
:
1042 return handleKvmExitFailEntry();
1045 /* KVM was interrupted by a signal, restart it in the next
1049 case KVM_EXIT_INTERNAL_ERROR
:
1050 panic("KVM: Internal error (suberror: %u)\n",
1051 _kvmRun
->internal
.suberror
);
1055 panic("KVM: Unexpected exit (exit_reason: %u)\n", _kvmRun
->exit_reason
);
1060 BaseKvmCPU::handleKvmExitIO()
1062 panic("KVM: Unhandled guest IO (dir: %i, size: %i, port: 0x%x, count: %i)\n",
1063 _kvmRun
->io
.direction
, _kvmRun
->io
.size
,
1064 _kvmRun
->io
.port
, _kvmRun
->io
.count
);
1068 BaseKvmCPU::handleKvmExitHypercall()
1070 panic("KVM: Unhandled hypercall\n");
1074 BaseKvmCPU::handleKvmExitIRQWindowOpen()
1076 warn("KVM: Unhandled IRQ window.\n");
1082 BaseKvmCPU::handleKvmExitUnknown()
1085 panic("KVM: Unknown error when starting vCPU (hw reason: 0x%llx)\n",
1086 _kvmRun
->hw
.hardware_exit_reason
);
1090 BaseKvmCPU::handleKvmExitException()
1093 panic("KVM: Got exception when starting vCPU "
1094 "(exception: %u, error_code: %u)\n",
1095 _kvmRun
->ex
.exception
, _kvmRun
->ex
.error_code
);
1099 BaseKvmCPU::handleKvmExitFailEntry()
1102 panic("KVM: Failed to enter virtualized mode (hw reason: 0x%llx)\n",
1103 _kvmRun
->fail_entry
.hardware_entry_failure_reason
);
1107 BaseKvmCPU::doMMIOAccess(Addr paddr
, void *data
, int size
, bool write
)
1109 ThreadContext
*tc(thread
->getTC());
1110 syncThreadContext();
1112 RequestPtr mmio_req
= std::make_shared
<Request
>(
1113 paddr
, size
, Request::UNCACHEABLE
, dataMasterId());
1115 mmio_req
->setContext(tc
->contextId());
1116 // Some architectures do need to massage physical addresses a bit
1117 // before they are inserted into the memory system. This enables
1118 // APIC accesses on x86 and m5ops where supported through a MMIO
1120 BaseTLB::Mode
tlb_mode(write
? BaseTLB::Write
: BaseTLB::Read
);
1121 Fault
fault(tc
->getDTBPtr()->finalizePhysical(mmio_req
, tc
, tlb_mode
));
1122 if (fault
!= NoFault
)
1123 warn("Finalization of MMIO address failed: %s\n", fault
->name());
1126 const MemCmd
cmd(write
? MemCmd::WriteReq
: MemCmd::ReadReq
);
1127 PacketPtr pkt
= new Packet(mmio_req
, cmd
);
1128 pkt
->dataStatic(data
);
1130 if (mmio_req
->isLocalAccess()) {
1131 // We currently assume that there is no need to migrate to a
1132 // different event queue when doing local accesses. Currently, they
1133 // are only used for m5ops, so it should be a valid assumption.
1134 const Cycles ipr_delay
= mmio_req
->localAccessor(tc
, pkt
);
1135 threadContextDirty
= true;
1137 return clockPeriod() * ipr_delay
;
1139 // Temporarily lock and migrate to the device event queue to
1140 // prevent races in multi-core mode.
1141 EventQueue::ScopedMigration
migrate(deviceEventQueue());
1143 return dataPort
.submitIO(pkt
);
1148 BaseKvmCPU::setSignalMask(const sigset_t
*mask
)
1150 std::unique_ptr
<struct kvm_signal_mask
> kvm_mask
;
1153 kvm_mask
.reset((struct kvm_signal_mask
*)operator new(
1154 sizeof(struct kvm_signal_mask
) + sizeof(*mask
)));
1155 // The kernel and the user-space headers have different ideas
1156 // about the size of sigset_t. This seems like a massive hack,
1157 // but is actually what qemu does.
1158 assert(sizeof(*mask
) >= 8);
1160 memcpy(kvm_mask
->sigset
, mask
, kvm_mask
->len
);
1163 if (ioctl(KVM_SET_SIGNAL_MASK
, (void *)kvm_mask
.get()) == -1)
1164 panic("KVM: Failed to set vCPU signal mask (errno: %i)\n",
1169 BaseKvmCPU::ioctl(int request
, long p1
) const
1172 panic("KVM: CPU ioctl called before initialization\n");
1174 return ::ioctl(vcpuFD
, request
, p1
);
1178 BaseKvmCPU::flushCoalescedMMIO()
1183 DPRINTF(KvmIO
, "KVM: Flushing the coalesced MMIO ring buffer\n");
1185 // TODO: We might need to do synchronization when we start to
1186 // support multiple CPUs
1188 while (mmioRing
->first
!= mmioRing
->last
) {
1189 struct kvm_coalesced_mmio
&ent(
1190 mmioRing
->coalesced_mmio
[mmioRing
->first
]);
1192 DPRINTF(KvmIO
, "KVM: Handling coalesced MMIO (addr: 0x%x, len: %u)\n",
1193 ent
.phys_addr
, ent
.len
);
1196 ticks
+= doMMIOAccess(ent
.phys_addr
, ent
.data
, ent
.len
, true);
1198 mmioRing
->first
= (mmioRing
->first
+ 1) % KVM_COALESCED_MMIO_MAX
;
1205 * Dummy handler for KVM kick signals.
1207 * @note This function is usually not called since the kernel doesn't
1208 * seem to deliver signals when the signal is only unmasked when
1209 * running in KVM. This doesn't matter though since we are only
1210 * interested in getting KVM to exit, which happens as expected. See
1211 * setupSignalHandler() and kvmRun() for details about KVM signal
1215 onKickSignal(int signo
, siginfo_t
*si
, void *data
)
1220 BaseKvmCPU::setupSignalHandler()
1222 struct sigaction sa
;
1224 memset(&sa
, 0, sizeof(sa
));
1225 sa
.sa_sigaction
= onKickSignal
;
1226 sa
.sa_flags
= SA_SIGINFO
| SA_RESTART
;
1227 if (sigaction(KVM_KICK_SIGNAL
, &sa
, NULL
) == -1)
1228 panic("KVM: Failed to setup vCPU timer signal handler\n");
1231 if (pthread_sigmask(SIG_BLOCK
, NULL
, &sigset
) == -1)
1232 panic("KVM: Failed get signal mask\n");
1234 // Request KVM to setup the same signal mask as we're currently
1235 // running with except for the KVM control signal. We'll sometimes
1236 // need to raise the KVM_KICK_SIGNAL to cause immediate exits from
1237 // KVM after servicing IO requests. See kvmRun().
1238 sigdelset(&sigset
, KVM_KICK_SIGNAL
);
1239 setSignalMask(&sigset
);
1241 // Mask our control signals so they aren't delivered unless we're
1242 // actually executing inside KVM.
1243 sigaddset(&sigset
, KVM_KICK_SIGNAL
);
1244 if (pthread_sigmask(SIG_SETMASK
, &sigset
, NULL
) == -1)
1245 panic("KVM: Failed mask the KVM control signals\n");
1249 BaseKvmCPU::discardPendingSignal(int signum
) const
1251 int discardedSignal
;
1253 // Setting the timeout to zero causes sigtimedwait to return
1255 struct timespec timeout
;
1257 timeout
.tv_nsec
= 0;
1260 sigemptyset(&sigset
);
1261 sigaddset(&sigset
, signum
);
1264 discardedSignal
= sigtimedwait(&sigset
, NULL
, &timeout
);
1265 } while (discardedSignal
== -1 && errno
== EINTR
);
1267 if (discardedSignal
== signum
)
1269 else if (discardedSignal
== -1 && errno
== EAGAIN
)
1272 panic("Unexpected return value from sigtimedwait: %i (errno: %i)\n",
1273 discardedSignal
, errno
);
1277 BaseKvmCPU::setupCounters()
1279 DPRINTF(Kvm
, "Attaching cycle counter...\n");
1280 PerfKvmCounterConfig
cfgCycles(PERF_TYPE_HARDWARE
,
1281 PERF_COUNT_HW_CPU_CYCLES
);
1282 cfgCycles
.disabled(true)
1285 // Try to exclude the host. We set both exclude_hv and
1286 // exclude_host since different architectures use slightly
1287 // different APIs in the kernel.
1288 cfgCycles
.exclude_hv(true)
1289 .exclude_host(true);
1291 if (perfControlledByTimer
) {
1292 // We need to configure the cycles counter to send overflows
1293 // since we are going to use it to trigger timer signals that
1294 // trap back into m5 from KVM. In practice, this means that we
1295 // need to set some non-zero sample period that gets
1296 // overridden when the timer is armed.
1297 cfgCycles
.wakeupEvents(1)
1301 hwCycles
.attach(cfgCycles
,
1302 0); // TID (0 => currentThread)
1308 BaseKvmCPU::tryDrain()
1310 if (drainState() != DrainState::Draining
)
1313 if (!archIsDrained()) {
1314 DPRINTF(Drain
, "tryDrain: Architecture code is not ready.\n");
1318 if (_status
== Idle
|| _status
== Running
) {
1320 "tryDrain: CPU transitioned into the Idle state, drain done\n");
1324 DPRINTF(Drain
, "tryDrain: CPU not ready.\n");
1330 BaseKvmCPU::ioctlRun()
1332 if (ioctl(KVM_RUN
) == -1) {
1334 panic("KVM: Failed to start virtual CPU (errno: %i)\n",
1340 BaseKvmCPU::setupInstStop()
1342 if (thread
->comInstEventQueue
.empty()) {
1343 setupInstCounter(0);
1345 Tick next
= thread
->comInstEventQueue
.nextTick();
1346 assert(next
> ctrInsts
);
1347 setupInstCounter(next
- ctrInsts
);
1352 BaseKvmCPU::setupInstCounter(uint64_t period
)
1354 // No need to do anything if we aren't attaching for the first
1355 // time or the period isn't changing.
1356 if (period
== activeInstPeriod
&& hwInstructions
.attached())
1359 PerfKvmCounterConfig
cfgInstructions(PERF_TYPE_HARDWARE
,
1360 PERF_COUNT_HW_INSTRUCTIONS
);
1362 // Try to exclude the host. We set both exclude_hv and
1363 // exclude_host since different architectures use slightly
1364 // different APIs in the kernel.
1365 cfgInstructions
.exclude_hv(true)
1366 .exclude_host(true);
1369 // Setup a sampling counter if that has been requested.
1370 cfgInstructions
.wakeupEvents(1)
1371 .samplePeriod(period
);
1374 // We need to detach and re-attach the counter to reliably change
1375 // sampling settings. See PerfKvmCounter::period() for details.
1376 if (hwInstructions
.attached())
1377 hwInstructions
.detach();
1378 assert(hwCycles
.attached());
1379 hwInstructions
.attach(cfgInstructions
,
1380 0, // TID (0 => currentThread)
1384 hwInstructions
.enableSignals(KVM_KICK_SIGNAL
);
1386 activeInstPeriod
= period
;