2 * Copyright 2014 Google, Inc.
3 * Copyright (c) 2012, 2015 ARM Limited
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder. You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions are
17 * met: redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer;
19 * redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution;
22 * neither the name of the copyright holders nor the names of its
23 * contributors may be used to endorse or promote products derived from
24 * this software without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
29 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
30 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
31 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 * Authors: Andreas Sandberg
41 #ifndef __CPU_KVM_KVMVM_HH__
42 #define __CPU_KVM_KVMVM_HH__
46 #include "base/addr_range.hh"
47 #include "sim/sim_object.hh"
49 // forward declarations
54 * @defgroup KvmInterrupts KVM Interrupt handling.
56 * These methods control interrupt delivery to the guest system.
60 * @defgroup KvmIoctl KVM low-level ioctl interface.
62 * These methods provide a low-level interface to the underlying KVM
67 * KVM parent interface
69 * The main Kvm object is used to provide functionality that is not
70 * specific to a VM or CPU. For example, it allows checking of the
71 * optional features and creation of VM containers.
82 /** Get the version of the KVM API implemented by the kernel. */
83 int getAPIVersion() const { return apiVersion; }
85 * Get the size of the MMAPed parameter area used to communicate
86 * vCPU parameters between the kernel and userspace. This area,
87 * amongst other things, contains the kvm_run data structure.
89 int getVCPUMMapSize() const { return vcpuMMapSize; }
92 /** Support for KvmVM::setUserMemoryRegion() */
93 bool capUserMemory() const;
94 /** Support for KvmVM::setTSSAddress() */
95 bool capSetTSSAddress() const;
96 /** Support for BaseKvmCPU::setCPUID2 and getSupportedCPUID(). */
97 bool capExtendedCPUID() const;
98 /** Support for BaseKvmCPU::kvmNonMaskableInterrupt(). */
99 bool capUserNMI() const;
102 * Check if coalesced MMIO is supported and which page in the
103 * MMAP'ed structure it stores requests in.
105 * @return Offset (in pages) into the mmap'ed vCPU area where the
106 * MMIO buffer is stored. 0 if unsupported.
108 int capCoalescedMMIO() const;
111 * Attempt to determine how many memory slots are available. If it can't
112 * be determined, this function returns 0.
114 int capNumMemSlots() const;
117 * Support for reading and writing single registers.
119 * @see BaseKvmCPU::getOneReg(), and BaseKvmCPU::setOneReg()
121 bool capOneReg() const;
124 * Support for creating an in-kernel IRQ chip model.
126 * @see KvmVM::createIRQChip()
128 bool capIRQChip() const;
130 /** Support for getting and setting the kvm_vcpu_events structure. */
131 bool capVCPUEvents() const;
133 /** Support for getting and setting the kvm_debugregs structure. */
134 bool capDebugRegs() const;
136 /** Support for getting and setting the x86 XCRs. */
137 bool capXCRs() const;
139 /** Support for getting and setting the kvm_xsave structure. */
140 bool capXSave() const;
143 #if defined(__i386__) || defined(__x86_64__)
144 public: // x86-specific
147 * @name X86-specific APIs
150 typedef std::vector<struct kvm_cpuid_entry2> CPUIDVector;
151 typedef std::vector<uint32_t> MSRIndexVector;
154 * Get the CPUID features supported by the hardware and Kvm.
156 * @note Requires capExtendedCPUID().
158 * @return False if the allocation is too small, true on success.
160 bool getSupportedCPUID(struct kvm_cpuid2 &cpuid) const;
163 * Get the CPUID features supported by the hardware and Kvm.
165 * @note Requires capExtendedCPUID().
167 * @note This method uses an internal cache to minimize the number
168 * of calls into the kernel.
170 * @return Reference to cached MSR index list.
172 const CPUIDVector &getSupportedCPUID() const;
175 * Get the MSRs supported by the hardware and Kvm.
177 * @return False if the allocation is too small, true on success.
179 bool getSupportedMSRs(struct kvm_msr_list &msrs) const;
182 * Get the MSRs supported by the hardware and Kvm.
184 * @note This method uses an internal cache to minimize the number
185 * of calls into the kernel.
187 * @return Reference to cached MSR index list.
189 const MSRIndexVector &getSupportedMSRs() const;
191 private: // x86-specific
192 /** Cached vector of supported CPUID entries. */
193 mutable CPUIDVector supportedCPUIDCache;
195 /** Cached vector of supported MSRs. */
196 mutable MSRIndexVector supportedMSRCache;
204 * Check for the presence of an extension to the KVM API.
206 * The return value depends on the extension, but is always zero
207 * if it is unsupported or positive otherwise. Some extensions use
208 * the return value provide additional data about the extension.
210 * @return 0 if the extension is unsupported, positive integer
213 int checkExtension(int extension) const;
216 * @addtogroup KvmIoctl
220 * Main VM ioctl interface.
222 * @param request KVM request
223 * @param p1 Optional request parameter
225 * @return -1 on error (error number in errno), ioctl dependent
228 int ioctl(int request, long p1) const;
229 int ioctl(int request, void *p1) const {
230 return ioctl(request, (long)p1);
232 int ioctl(int request) const {
233 return ioctl(request, 0L);
238 // This object is a singleton, so prevent instantiation.
243 // Prevent assignment
244 Kvm &operator=(const Kvm &kvm);
247 * Create a KVM Virtual Machine
249 * @return File descriptor pointing to the VM
253 /** KVM VM file descriptor */
255 /** KVM API version */
257 /** Size of the MMAPed vCPU parameter area. */
260 /** Singleton instance */
261 static Kvm *instance;
267 * A KVM VM container normally contains all the CPUs in a shared
268 * memory machine. The VM container handles things like physical
269 * memory and to some extent interrupts. Normally, the VM API is only
270 * used for interrupts when the PIC is emulated by the kernel, which
271 * is a feature we do not use. However, some architectures (notably
272 * ARM) use the VM interface to deliver interrupts to specific CPUs as
275 * VM initialization is a bit different from that of other
276 * SimObjects. When we initialize the VM, we discover all physical
277 * memory mappings in the system. Since AbstractMem::unserialize
278 * re-maps the guests memory, we need to make sure that this is done
279 * after the memory has been re-mapped, but before the vCPUs are
280 * initialized (KVM requires memory mappings to be setup before CPUs
281 * can be created). Normally, we would just initialize the VM in
282 * init() or startup(), however, we can not use init() since this is
283 * called before AbstractMem::unserialize() and we can not use
284 * startup() since it must be called before BaseKvmCPU::startup() and
285 * the simulator framework does not guarantee call order. We therefore
286 * call cpuStartup() from BaseKvmCPU::startup() instead and execute
287 * the initialization code once when the first CPU in the VM is
290 class KvmVM : public SimObject
292 friend class BaseKvmCPU;
295 KvmVM(KvmVMParams *params);
301 * Setup a shared three-page memory region used by the internals
302 * of KVM. This is currently only needed by x86 implementations.
304 * @param tss_address Physical address of the start of the TSS
306 void setTSSAddress(Addr tss_address);
310 * Request coalescing MMIO for a memory range.
312 * @param start Physical start address in guest
313 * @param size Size of the MMIO region
315 void coalesceMMIO(Addr start, int size);
318 * Request coalescing MMIO for a memory range.
320 * @param range Coalesced MMIO range
322 void coalesceMMIO(const AddrRange &range);
326 * @addtogroup KvmInterrupts
330 * Create an in-kernel interrupt controller
332 * @note This functionality depends on Kvm::capIRQChip().
334 void createIRQChip();
337 * Set the status of an IRQ line using KVM_IRQ_LINE.
339 * @note This ioctl is usually only used if the interrupt
340 * controller is emulated by the kernel (i.e., after calling
341 * createIRQChip()). Some architectures (e.g., ARM) use it instead
342 * of BaseKvmCPU::kvmInterrupt().
344 * @param irq Interrupt number
345 * @param high Line level (true for high, false for low)
347 void setIRQLine(uint32_t irq, bool high);
350 * Is in-kernel IRQ chip emulation enabled?
352 bool hasKernelIRQChip() const { return _hasKernelIRQChip; }
357 MemSlot(uint32_t _num) : num(_num)
366 * Allocate a memory slot within the VM.
368 const MemSlot allocMemSlot(uint64_t size);
371 * Setup a region of physical memory in the guest
373 * @param slot KVM memory slot ID returned by allocMemSlot
374 * @param host_addr Memory allocation backing the memory
375 * @param guest_addr Address in the guest
376 * @param flags Flags (see the KVM API documentation)
378 void setupMemSlot(const MemSlot slot, void *host_addr, Addr guest_addr,
382 * Disable a memory slot.
384 void disableMemSlot(const MemSlot slot);
387 * Free a previously allocated memory slot.
389 void freeMemSlot(const MemSlot slot);
392 * Create an in-kernel device model.
394 * @param type Device type (KVM_DEV_TYPE_xxx)
395 * @param flags Creation flags (KVM_CREATE_DEVICE_xxx)
396 * @return Device file descriptor
398 int createDevice(uint32_t type, uint32_t flags = 0);
400 /** Global KVM interface */
404 * Initialize system pointer. Invoked by system object.
406 void setSystem(System *s);
408 #if defined(__aarch64__)
409 public: // ARM-specific
411 * Ask the kernel for the preferred CPU target to simulate.
413 * When creating an ARM vCPU in Kvm, we need to initialize it with
414 * a call to BaseArmKvmCPU::kvmArmVCpuInit(). When calling this
415 * function, we need to know what type of CPU the host has. This
416 * call sets up the kvm_vcpu_init structure with the values the
419 * @param[out] target Target structure to initialize.
421 void kvmArmPreferredTarget(struct kvm_vcpu_init &target) const;
427 * VM CPU initialization code.
429 * This method is called from BaseKvmCPU::startup() when a CPU in
430 * the VM executes its BaseKvmCPU::startup() method. The first
431 * time method is executed on a VM, it calls the delayedStartup()
437 * Delayed initialization, executed once before the first CPU
440 * This method provides a way to do VM initialization once before
441 * the first CPU in a VM starts. It is needed since some resources
442 * (e.g., memory mappings) can change in the normal
443 * SimObject::startup() path. Since the call order of
444 * SimObject::startup() is not guaranteed, we simply defer some
445 * initialization until a CPU is about to start.
447 void delayedStartup();
452 * Setup a region of physical memory in the guest
454 * @param slot KVM memory slot ID (must be unique)
455 * @param host_addr Memory allocation backing the memory
456 * @param guest_addr Address in the guest
457 * @param len Size of the allocation in bytes
458 * @param flags Flags (see the KVM API documentation)
460 void setUserMemoryRegion(uint32_t slot,
461 void *host_addr, Addr guest_addr,
462 uint64_t len, uint32_t flags);
466 * Create a new vCPU within a VM.
468 * @param vcpuID ID of the new CPU within the VM.
469 * @return File descriptor referencing the CPU.
471 int createVCPU(long vcpuID);
474 * Allocate a new vCPU ID within the VM.
476 * The returned vCPU ID is guaranteed to be unique within the
477 * VM. New IDs are allocated sequentially starting from 0.
479 * @return ID of the new vCPU
484 * @addtogroup KvmIoctl
488 * KVM VM ioctl interface.
490 * @param request KVM VM request
491 * @param p1 Optional request parameter
493 * @return -1 on error (error number in errno), ioctl dependent
496 int ioctl(int request, long p1) const;
497 int ioctl(int request, void *p1) const {
498 return ioctl(request, (long)p1);
500 int ioctl(int request) const {
501 return ioctl(request, 0L);
507 KvmVM(const KvmVM &vm);
508 // Prevent assignment
509 KvmVM &operator=(const KvmVM &vm);
513 /** KVM VM file descriptor */
516 /** Has delayedStartup() already been called? */
519 /** Do we have in-kernel IRQ-chip emulation enabled? */
520 bool _hasKernelIRQChip;
522 /** Next unallocated vCPU ID */
526 * Structures tracking memory slots.
535 std::vector<MemorySlot> memorySlots;
536 uint32_t maxMemorySlot;