2 * Copyright (c) 2011 NetApp, Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/module.h>
36 #include <sys/sysctl.h>
37 #include <sys/malloc.h>
40 #include <sys/mutex.h>
42 #include <sys/rwlock.h>
43 #include <sys/sched.h>
45 #include <sys/systm.h>
48 #include <vm/vm_object.h>
49 #include <vm/vm_page.h>
51 #include <vm/vm_map.h>
52 #include <vm/vm_extern.h>
53 #include <vm/vm_param.h>
55 #include <machine/cpu.h>
56 #include <machine/vm.h>
57 #include <machine/pcb.h>
58 #include <machine/smp.h>
60 #include <x86/apicreg.h>
61 #include <machine/vmparam.h>
63 #include <machine/vmm.h>
64 #include <machine/vmm_dev.h>
65 #include <machine/vmm_instruction_emul.h>
67 #include "vmm_ioport.h"
80 #include "vmm_lapic.h"
89 * (a) allocated when vcpu is created
90 * (i) initialized when vcpu is created and when it is reinitialized
91 * (o) initialized the first time the vcpu is created
92 * (x) initialized before use
95 struct mtx mtx; /* (o) protects 'state' and 'hostcpu' */
96 enum vcpu_state state; /* (o) vcpu state */
97 int hostcpu; /* (o) vcpu's host cpu */
98 struct vlapic *vlapic; /* (i) APIC device model */
99 enum x2apic_state x2apic_state; /* (i) APIC mode */
100 uint64_t exitintinfo; /* (i) events pending at VM exit */
101 int nmi_pending; /* (i) NMI pending */
102 int extint_pending; /* (i) INTR pending */
103 struct vm_exception exception; /* (x) exception collateral */
104 int exception_pending; /* (i) exception pending */
105 struct savefpu *guestfpu; /* (a,i) guest fpu state */
106 uint64_t guest_xcr0; /* (i) guest %xcr0 register */
107 void *stats; /* (a,i) statistics */
108 uint64_t guest_msrs[VMM_MSR_NUM]; /* (i) emulated MSRs */
109 struct vm_exit exitinfo; /* (x) exit reason and collateral */
112 #define vcpu_lock_initialized(v) mtx_initialized(&((v)->mtx))
113 #define vcpu_lock_init(v) mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
114 #define vcpu_lock(v) mtx_lock_spin(&((v)->mtx))
115 #define vcpu_unlock(v) mtx_unlock_spin(&((v)->mtx))
116 #define vcpu_assert_locked(v) mtx_assert(&((v)->mtx), MA_OWNED)
124 #define VM_MAX_MEMORY_SEGMENTS 2
128 * (o) initialized the first time the VM is created
129 * (i) initialized when VM is created and when it is reinitialized
130 * (x) initialized before use
133 void *cookie; /* (i) cpu-specific data */
134 void *iommu; /* (x) iommu-specific data */
135 struct vhpet *vhpet; /* (i) virtual HPET */
136 struct vioapic *vioapic; /* (i) virtual ioapic */
137 struct vatpic *vatpic; /* (i) virtual atpic */
138 struct vatpit *vatpit; /* (i) virtual atpit */
139 volatile cpuset_t active_cpus; /* (i) active vcpus */
140 int suspend; /* (i) stop VM execution */
141 volatile cpuset_t suspended_cpus; /* (i) suspended vcpus */
142 volatile cpuset_t halted_cpus; /* (x) cpus in a hard halt */
143 cpuset_t rendezvous_req_cpus; /* (x) rendezvous requested */
144 cpuset_t rendezvous_done_cpus; /* (x) rendezvous finished */
145 void *rendezvous_arg; /* (x) rendezvous func/arg */
146 vm_rendezvous_func_t rendezvous_func;
147 struct mtx rendezvous_mtx; /* (o) rendezvous lock */
148 int num_mem_segs; /* (o) guest memory segments */
149 struct mem_seg mem_segs[VM_MAX_MEMORY_SEGMENTS];
150 struct vmspace *vmspace; /* (o) guest's address space */
151 char name[VM_MAX_NAMELEN]; /* (o) virtual machine name */
152 struct vcpu vcpu[VM_MAXCPU]; /* (i) guest vcpus */
155 static int vmm_initialized;
157 static struct vmm_ops *ops;
158 #define VMM_INIT(num) (ops != NULL ? (*ops->init)(num) : 0)
159 #define VMM_CLEANUP() (ops != NULL ? (*ops->cleanup)() : 0)
160 #define VMM_RESUME() (ops != NULL ? (*ops->resume)() : 0)
162 #define VMINIT(vm, pmap) (ops != NULL ? (*ops->vminit)(vm, pmap): NULL)
163 #define VMRUN(vmi, vcpu, rip, pmap, rptr, sptr) \
164 (ops != NULL ? (*ops->vmrun)(vmi, vcpu, rip, pmap, rptr, sptr) : ENXIO)
165 #define VMCLEANUP(vmi) (ops != NULL ? (*ops->vmcleanup)(vmi) : NULL)
166 #define VMSPACE_ALLOC(min, max) \
167 (ops != NULL ? (*ops->vmspace_alloc)(min, max) : NULL)
168 #define VMSPACE_FREE(vmspace) \
169 (ops != NULL ? (*ops->vmspace_free)(vmspace) : ENXIO)
170 #define VMGETREG(vmi, vcpu, num, retval) \
171 (ops != NULL ? (*ops->vmgetreg)(vmi, vcpu, num, retval) : ENXIO)
172 #define VMSETREG(vmi, vcpu, num, val) \
173 (ops != NULL ? (*ops->vmsetreg)(vmi, vcpu, num, val) : ENXIO)
174 #define VMGETDESC(vmi, vcpu, num, desc) \
175 (ops != NULL ? (*ops->vmgetdesc)(vmi, vcpu, num, desc) : ENXIO)
176 #define VMSETDESC(vmi, vcpu, num, desc) \
177 (ops != NULL ? (*ops->vmsetdesc)(vmi, vcpu, num, desc) : ENXIO)
178 #define VMGETCAP(vmi, vcpu, num, retval) \
179 (ops != NULL ? (*ops->vmgetcap)(vmi, vcpu, num, retval) : ENXIO)
180 #define VMSETCAP(vmi, vcpu, num, val) \
181 (ops != NULL ? (*ops->vmsetcap)(vmi, vcpu, num, val) : ENXIO)
182 #define VLAPIC_INIT(vmi, vcpu) \
183 (ops != NULL ? (*ops->vlapic_init)(vmi, vcpu) : NULL)
184 #define VLAPIC_CLEANUP(vmi, vlapic) \
185 (ops != NULL ? (*ops->vlapic_cleanup)(vmi, vlapic) : NULL)
187 #define fpu_start_emulating() load_cr0(rcr0() | CR0_TS)
188 #define fpu_stop_emulating() clts()
190 static MALLOC_DEFINE(M_VM, "vm", "vm");
191 CTASSERT(VMM_MSR_NUM <= 64); /* msr_mask can keep track of up to 64 msrs */
194 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
196 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW, NULL, NULL);
199 * Halt the guest if all vcpus are executing a HLT instruction with
200 * interrupts disabled.
202 static int halt_detection_enabled = 1;
203 SYSCTL_INT(_hw_vmm, OID_AUTO, halt_detection, CTLFLAG_RDTUN,
204 &halt_detection_enabled, 0,
205 "Halt VM if all vcpus execute HLT with interrupts disabled");
207 static int vmm_ipinum;
208 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
209 "IPI vector used for vcpu notifications");
212 vcpu_cleanup(struct vm *vm, int i, bool destroy)
214 struct vcpu *vcpu = &vm->vcpu[i];
216 VLAPIC_CLEANUP(vm->cookie, vcpu->vlapic);
218 vmm_stat_free(vcpu->stats);
219 fpu_save_area_free(vcpu->guestfpu);
224 vcpu_init(struct vm *vm, int vcpu_id, bool create)
228 KASSERT(vcpu_id >= 0 && vcpu_id < VM_MAXCPU,
229 ("vcpu_init: invalid vcpu %d", vcpu_id));
231 vcpu = &vm->vcpu[vcpu_id];
234 KASSERT(!vcpu_lock_initialized(vcpu), ("vcpu %d already "
235 "initialized", vcpu_id));
236 vcpu_lock_init(vcpu);
237 vcpu->state = VCPU_IDLE;
238 vcpu->hostcpu = NOCPU;
239 vcpu->guestfpu = fpu_save_area_alloc();
240 vcpu->stats = vmm_stat_alloc();
243 vcpu->vlapic = VLAPIC_INIT(vm->cookie, vcpu_id);
244 vm_set_x2apic_state(vm, vcpu_id, X2APIC_DISABLED);
245 vcpu->exitintinfo = 0;
246 vcpu->nmi_pending = 0;
247 vcpu->extint_pending = 0;
248 vcpu->exception_pending = 0;
249 vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
250 fpu_save_area_reset(vcpu->guestfpu);
251 vmm_stat_init(vcpu->stats);
252 guest_msrs_init(vm, vcpu_id);
256 vm_exitinfo(struct vm *vm, int cpuid)
260 if (cpuid < 0 || cpuid >= VM_MAXCPU)
261 panic("vm_exitinfo: invalid cpuid %d", cpuid);
263 vcpu = &vm->vcpu[cpuid];
265 return (&vcpu->exitinfo);
279 vmm_host_state_init();
281 vmm_ipinum = vmm_ipi_alloc();
283 vmm_ipinum = IPI_AST;
285 error = vmm_mem_init();
290 ops = &vmm_ops_intel;
291 else if (vmm_is_amd())
297 vmm_resume_p = vmm_resume;
299 return (VMM_INIT(vmm_ipinum));
303 vmm_handler(module_t mod, int what, void *arg)
310 if (ppt_avail_devices() > 0)
317 error = vmmdev_cleanup();
321 if (vmm_ipinum != IPI_AST)
322 vmm_ipi_free(vmm_ipinum);
323 error = VMM_CLEANUP();
325 * Something bad happened - prevent new
326 * VMs from being created
339 static moduledata_t vmm_kmod = {
346 * vmm initialization has the following dependencies:
348 * - iommu initialization must happen after the pci passthru driver has had
349 * a chance to attach to any passthru devices (after SI_SUB_CONFIGURE).
351 * - VT-x initialization requires smp_rendezvous() and therefore must happen
352 * after SMP is fully functional (after SI_SUB_SMP).
354 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
355 MODULE_VERSION(vmm, 1);
358 vm_init(struct vm *vm, bool create)
362 vm->cookie = VMINIT(vm, vmspace_pmap(vm->vmspace));
364 vm->vioapic = vioapic_init(vm);
365 vm->vhpet = vhpet_init(vm);
366 vm->vatpic = vatpic_init(vm);
367 vm->vatpit = vatpit_init(vm);
369 CPU_ZERO(&vm->active_cpus);
372 CPU_ZERO(&vm->suspended_cpus);
374 for (i = 0; i < VM_MAXCPU; i++)
375 vcpu_init(vm, i, create);
379 vm_create(const char *name, struct vm **retvm)
382 struct vmspace *vmspace;
385 * If vmm.ko could not be successfully initialized then don't attempt
386 * to create the virtual machine.
388 if (!vmm_initialized)
391 if (name == NULL || strlen(name) >= VM_MAX_NAMELEN)
394 vmspace = VMSPACE_ALLOC(VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS);
398 vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
399 strcpy(vm->name, name);
400 vm->num_mem_segs = 0;
401 vm->vmspace = vmspace;
402 mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
411 vm_free_mem_seg(struct vm *vm, struct mem_seg *seg)
414 if (seg->object != NULL)
415 vmm_mem_free(vm->vmspace, seg->gpa, seg->len);
417 bzero(seg, sizeof(*seg));
421 vm_cleanup(struct vm *vm, bool destroy)
425 ppt_unassign_all(vm);
427 if (vm->iommu != NULL)
428 iommu_destroy_domain(vm->iommu);
430 vatpit_cleanup(vm->vatpit);
431 vhpet_cleanup(vm->vhpet);
432 vatpic_cleanup(vm->vatpic);
433 vioapic_cleanup(vm->vioapic);
435 for (i = 0; i < VM_MAXCPU; i++)
436 vcpu_cleanup(vm, i, destroy);
438 VMCLEANUP(vm->cookie);
441 for (i = 0; i < vm->num_mem_segs; i++)
442 vm_free_mem_seg(vm, &vm->mem_segs[i]);
444 vm->num_mem_segs = 0;
446 VMSPACE_FREE(vm->vmspace);
452 vm_destroy(struct vm *vm)
454 vm_cleanup(vm, true);
459 vm_reinit(struct vm *vm)
464 * A virtual machine can be reset only if all vcpus are suspended.
466 if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
467 vm_cleanup(vm, false);
478 vm_name(struct vm *vm)
484 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
488 if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
495 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
498 vmm_mmio_free(vm->vmspace, gpa, len);
503 vm_mem_allocated(struct vm *vm, vm_paddr_t gpa)
506 vm_paddr_t gpabase, gpalimit;
508 for (i = 0; i < vm->num_mem_segs; i++) {
509 gpabase = vm->mem_segs[i].gpa;
510 gpalimit = gpabase + vm->mem_segs[i].len;
511 if (gpa >= gpabase && gpa < gpalimit)
512 return (TRUE); /* 'gpa' is regular memory */
515 if (ppt_is_mmio(vm, gpa))
516 return (TRUE); /* 'gpa' is pci passthru mmio */
522 vm_malloc(struct vm *vm, vm_paddr_t gpa, size_t len)
524 int available, allocated;
529 if ((gpa & PAGE_MASK) || (len & PAGE_MASK) || len == 0)
532 available = allocated = 0;
534 while (g < gpa + len) {
535 if (vm_mem_allocated(vm, g))
544 * If there are some allocated and some available pages in the address
545 * range then it is an error.
547 if (allocated && available)
551 * If the entire address range being requested has already been
552 * allocated then there isn't anything more to do.
554 if (allocated && available == 0)
557 if (vm->num_mem_segs >= VM_MAX_MEMORY_SEGMENTS)
560 seg = &vm->mem_segs[vm->num_mem_segs];
562 if ((object = vmm_mem_alloc(vm->vmspace, gpa, len)) == NULL)
567 seg->object = object;
576 vm_maxmem(struct vm *vm)
579 vm_paddr_t gpa, maxmem;
582 for (i = 0; i < vm->num_mem_segs; i++) {
583 gpa = vm->mem_segs[i].gpa + vm->mem_segs[i].len;
591 vm_gpa_unwire(struct vm *vm)
596 for (i = 0; i < vm->num_mem_segs; i++) {
597 seg = &vm->mem_segs[i];
601 rv = vm_map_unwire(&vm->vmspace->vm_map,
602 seg->gpa, seg->gpa + seg->len,
603 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
604 KASSERT(rv == KERN_SUCCESS, ("vm(%s) memory segment "
605 "%#lx/%ld could not be unwired: %d",
606 vm_name(vm), seg->gpa, seg->len, rv));
613 vm_gpa_wire(struct vm *vm)
618 for (i = 0; i < vm->num_mem_segs; i++) {
619 seg = &vm->mem_segs[i];
624 rv = vm_map_wire(&vm->vmspace->vm_map,
625 seg->gpa, seg->gpa + seg->len,
626 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
627 if (rv != KERN_SUCCESS)
633 if (i < vm->num_mem_segs) {
635 * Undo the wiring before returning an error.
645 vm_iommu_modify(struct vm *vm, boolean_t map)
650 void *vp, *cookie, *host_domain;
653 host_domain = iommu_host_domain();
655 for (i = 0; i < vm->num_mem_segs; i++) {
656 seg = &vm->mem_segs[i];
657 KASSERT(seg->wired, ("vm(%s) memory segment %#lx/%ld not wired",
658 vm_name(vm), seg->gpa, seg->len));
661 while (gpa < seg->gpa + seg->len) {
662 vp = vm_gpa_hold(vm, gpa, PAGE_SIZE, VM_PROT_WRITE,
664 KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
667 vm_gpa_release(cookie);
669 hpa = DMAP_TO_PHYS((uintptr_t)vp);
671 iommu_create_mapping(vm->iommu, gpa, hpa, sz);
672 iommu_remove_mapping(host_domain, hpa, sz);
674 iommu_remove_mapping(vm->iommu, gpa, sz);
675 iommu_create_mapping(host_domain, hpa, hpa, sz);
683 * Invalidate the cached translations associated with the domain
684 * from which pages were removed.
687 iommu_invalidate_tlb(host_domain);
689 iommu_invalidate_tlb(vm->iommu);
692 #define vm_iommu_unmap(vm) vm_iommu_modify((vm), FALSE)
693 #define vm_iommu_map(vm) vm_iommu_modify((vm), TRUE)
696 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
700 error = ppt_unassign_device(vm, bus, slot, func);
704 if (ppt_assigned_devices(vm) == 0) {
712 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
718 * Virtual machines with pci passthru devices get special treatment:
719 * - the guest physical memory is wired
720 * - the iommu is programmed to do the 'gpa' to 'hpa' translation
722 * We need to do this before the first pci passthru device is attached.
724 if (ppt_assigned_devices(vm) == 0) {
725 KASSERT(vm->iommu == NULL,
726 ("vm_assign_pptdev: iommu must be NULL"));
727 maxaddr = vm_maxmem(vm);
728 vm->iommu = iommu_create_domain(maxaddr);
730 error = vm_gpa_wire(vm);
737 error = ppt_assign_device(vm, bus, slot, func);
742 vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
748 pageoff = gpa & PAGE_MASK;
749 if (len > PAGE_SIZE - pageoff)
750 panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
752 count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
753 trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
757 return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
765 vm_gpa_release(void *cookie)
767 vm_page_t m = cookie;
775 vm_gpabase2memseg(struct vm *vm, vm_paddr_t gpabase,
776 struct vm_memory_segment *seg)
780 for (i = 0; i < vm->num_mem_segs; i++) {
781 if (gpabase == vm->mem_segs[i].gpa) {
782 seg->gpa = vm->mem_segs[i].gpa;
783 seg->len = vm->mem_segs[i].len;
784 seg->wired = vm->mem_segs[i].wired;
792 vm_get_memobj(struct vm *vm, vm_paddr_t gpa, size_t len,
793 vm_offset_t *offset, struct vm_object **object)
800 for (i = 0; i < vm->num_mem_segs; i++) {
801 if ((seg_obj = vm->mem_segs[i].object) == NULL)
804 seg_gpa = vm->mem_segs[i].gpa;
805 seg_len = vm->mem_segs[i].len;
807 if (gpa >= seg_gpa && gpa < seg_gpa + seg_len) {
808 *offset = gpa - seg_gpa;
810 vm_object_reference(seg_obj);
819 vm_get_register(struct vm *vm, int vcpu, int reg, uint64_t *retval)
822 if (vcpu < 0 || vcpu >= VM_MAXCPU)
825 if (reg >= VM_REG_LAST)
828 return (VMGETREG(vm->cookie, vcpu, reg, retval));
832 vm_set_register(struct vm *vm, int vcpu, int reg, uint64_t val)
835 if (vcpu < 0 || vcpu >= VM_MAXCPU)
838 if (reg >= VM_REG_LAST)
841 return (VMSETREG(vm->cookie, vcpu, reg, val));
845 is_descriptor_table(int reg)
849 case VM_REG_GUEST_IDTR:
850 case VM_REG_GUEST_GDTR:
858 is_segment_register(int reg)
862 case VM_REG_GUEST_ES:
863 case VM_REG_GUEST_CS:
864 case VM_REG_GUEST_SS:
865 case VM_REG_GUEST_DS:
866 case VM_REG_GUEST_FS:
867 case VM_REG_GUEST_GS:
868 case VM_REG_GUEST_TR:
869 case VM_REG_GUEST_LDTR:
877 vm_get_seg_desc(struct vm *vm, int vcpu, int reg,
878 struct seg_desc *desc)
881 if (vcpu < 0 || vcpu >= VM_MAXCPU)
884 if (!is_segment_register(reg) && !is_descriptor_table(reg))
887 return (VMGETDESC(vm->cookie, vcpu, reg, desc));
891 vm_set_seg_desc(struct vm *vm, int vcpu, int reg,
892 struct seg_desc *desc)
894 if (vcpu < 0 || vcpu >= VM_MAXCPU)
897 if (!is_segment_register(reg) && !is_descriptor_table(reg))
900 return (VMSETDESC(vm->cookie, vcpu, reg, desc));
904 restore_guest_fpustate(struct vcpu *vcpu)
907 /* flush host state to the pcb */
910 /* restore guest FPU state */
911 fpu_stop_emulating();
912 fpurestore(vcpu->guestfpu);
914 /* restore guest XCR0 if XSAVE is enabled in the host */
915 if (rcr4() & CR4_XSAVE)
916 load_xcr(0, vcpu->guest_xcr0);
919 * The FPU is now "dirty" with the guest's state so turn on emulation
920 * to trap any access to the FPU by the host.
922 fpu_start_emulating();
926 save_guest_fpustate(struct vcpu *vcpu)
929 if ((rcr0() & CR0_TS) == 0)
930 panic("fpu emulation not enabled in host!");
932 /* save guest XCR0 and restore host XCR0 */
933 if (rcr4() & CR4_XSAVE) {
934 vcpu->guest_xcr0 = rxcr(0);
935 load_xcr(0, vmm_get_host_xcr0());
938 /* save guest FPU state */
939 fpu_stop_emulating();
940 fpusave(vcpu->guestfpu);
941 fpu_start_emulating();
944 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
947 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate,
952 vcpu_assert_locked(vcpu);
955 * State transitions from the vmmdev_ioctl() must always begin from
956 * the VCPU_IDLE state. This guarantees that there is only a single
957 * ioctl() operating on a vcpu at any point.
960 while (vcpu->state != VCPU_IDLE)
961 msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
963 KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
967 if (vcpu->state == VCPU_RUNNING) {
968 KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
969 "mismatch for running vcpu", curcpu, vcpu->hostcpu));
971 KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
972 "vcpu that is not running", vcpu->hostcpu));
976 * The following state transitions are allowed:
977 * IDLE -> FROZEN -> IDLE
978 * FROZEN -> RUNNING -> FROZEN
979 * FROZEN -> SLEEPING -> FROZEN
981 switch (vcpu->state) {
985 error = (newstate != VCPU_FROZEN);
988 error = (newstate == VCPU_FROZEN);
998 vcpu->state = newstate;
999 if (newstate == VCPU_RUNNING)
1000 vcpu->hostcpu = curcpu;
1002 vcpu->hostcpu = NOCPU;
1004 if (newstate == VCPU_IDLE)
1005 wakeup(&vcpu->state);
1011 vcpu_require_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
1015 if ((error = vcpu_set_state(vm, vcpuid, newstate, false)) != 0)
1016 panic("Error %d setting state to %d\n", error, newstate);
1020 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
1024 if ((error = vcpu_set_state_locked(vcpu, newstate, false)) != 0)
1025 panic("Error %d setting state to %d", error, newstate);
1029 vm_set_rendezvous_func(struct vm *vm, vm_rendezvous_func_t func)
1032 KASSERT(mtx_owned(&vm->rendezvous_mtx), ("rendezvous_mtx not locked"));
1035 * Update 'rendezvous_func' and execute a write memory barrier to
1036 * ensure that it is visible across all host cpus. This is not needed
1037 * for correctness but it does ensure that all the vcpus will notice
1038 * that the rendezvous is requested immediately.
1040 vm->rendezvous_func = func;
1044 #define RENDEZVOUS_CTR0(vm, vcpuid, fmt) \
1047 VCPU_CTR0(vm, vcpuid, fmt); \
1053 vm_handle_rendezvous(struct vm *vm, int vcpuid)
1056 KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
1057 ("vm_handle_rendezvous: invalid vcpuid %d", vcpuid));
1059 mtx_lock(&vm->rendezvous_mtx);
1060 while (vm->rendezvous_func != NULL) {
1061 /* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
1062 CPU_AND(&vm->rendezvous_req_cpus, &vm->active_cpus);
1065 CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
1066 !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
1067 VCPU_CTR0(vm, vcpuid, "Calling rendezvous func");
1068 (*vm->rendezvous_func)(vm, vcpuid, vm->rendezvous_arg);
1069 CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
1071 if (CPU_CMP(&vm->rendezvous_req_cpus,
1072 &vm->rendezvous_done_cpus) == 0) {
1073 VCPU_CTR0(vm, vcpuid, "Rendezvous completed");
1074 vm_set_rendezvous_func(vm, NULL);
1075 wakeup(&vm->rendezvous_func);
1078 RENDEZVOUS_CTR0(vm, vcpuid, "Wait for rendezvous completion");
1079 mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
1082 mtx_unlock(&vm->rendezvous_mtx);
1086 * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1089 vm_handle_hlt(struct vm *vm, int vcpuid, bool intr_disabled, bool *retu)
1093 int error, t, vcpu_halted, vm_halted;
1095 KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1097 vcpu = &vm->vcpu[vcpuid];
1102 * The typical way to halt a cpu is to execute: "sti; hlt"
1104 * STI sets RFLAGS.IF to enable interrupts. However, the processor
1105 * remains in an "interrupt shadow" for an additional instruction
1106 * following the STI. This guarantees that "sti; hlt" sequence is
1107 * atomic and a pending interrupt will be recognized after the HLT.
1109 * After the HLT emulation is done the vcpu is no longer in an
1110 * interrupt shadow and a pending interrupt can be injected on
1111 * the next entry into the guest.
1113 error = vm_set_register(vm, vcpuid, VM_REG_GUEST_INTR_SHADOW, 0);
1114 KASSERT(error == 0, ("%s: error %d clearing interrupt shadow",
1120 * Do a final check for pending NMI or interrupts before
1121 * really putting this thread to sleep. Also check for
1122 * software events that would cause this vcpu to wakeup.
1124 * These interrupts/events could have happened after the
1125 * vcpu returned from VMRUN() and before it acquired the
1128 if (vm->rendezvous_func != NULL || vm->suspend)
1130 if (vm_nmi_pending(vm, vcpuid))
1132 if (!intr_disabled) {
1133 if (vm_extint_pending(vm, vcpuid) ||
1134 vlapic_pending_intr(vcpu->vlapic, NULL)) {
1139 /* Don't go to sleep if the vcpu thread needs to yield */
1140 if (vcpu_should_yield(vm, vcpuid))
1144 * Some Linux guests implement "halt" by having all vcpus
1145 * execute HLT with interrupts disabled. 'halted_cpus' keeps
1146 * track of the vcpus that have entered this state. When all
1147 * vcpus enter the halted state the virtual machine is halted.
1149 if (intr_disabled) {
1151 VCPU_CTR0(vm, vcpuid, "Halted");
1152 if (!vcpu_halted && halt_detection_enabled) {
1154 CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1156 if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1165 vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1167 * XXX msleep_spin() cannot be interrupted by signals so
1168 * wake up periodically to check pending signals.
1170 msleep_spin(vcpu, &vcpu->mtx, wmesg, hz);
1171 vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1172 vmm_stat_incr(vm, vcpuid, VCPU_IDLE_TICKS, ticks - t);
1176 CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1181 vm_suspend(vm, VM_SUSPEND_HALT);
1187 vm_handle_paging(struct vm *vm, int vcpuid, bool *retu)
1192 struct vm_exit *vme;
1194 vcpu = &vm->vcpu[vcpuid];
1195 vme = &vcpu->exitinfo;
1197 ftype = vme->u.paging.fault_type;
1198 KASSERT(ftype == VM_PROT_READ ||
1199 ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1200 ("vm_handle_paging: invalid fault_type %d", ftype));
1202 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1203 rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1204 vme->u.paging.gpa, ftype);
1209 map = &vm->vmspace->vm_map;
1210 rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL);
1212 VCPU_CTR3(vm, vcpuid, "vm_handle_paging rv = %d, gpa = %#lx, "
1213 "ftype = %d", rv, vme->u.paging.gpa, ftype);
1215 if (rv != KERN_SUCCESS)
1218 /* restart execution at the faulting instruction */
1219 vme->inst_length = 0;
1225 vm_handle_inst_emul(struct vm *vm, int vcpuid, bool *retu)
1229 struct vm_exit *vme;
1231 struct vm_guest_paging *paging;
1232 mem_region_read_t mread;
1233 mem_region_write_t mwrite;
1234 enum vm_cpu_mode cpu_mode;
1237 vcpu = &vm->vcpu[vcpuid];
1238 vme = &vcpu->exitinfo;
1240 gla = vme->u.inst_emul.gla;
1241 gpa = vme->u.inst_emul.gpa;
1242 cs_d = vme->u.inst_emul.cs_d;
1243 vie = &vme->u.inst_emul.vie;
1244 paging = &vme->u.inst_emul.paging;
1245 cpu_mode = paging->cpu_mode;
1249 /* Fetch, decode and emulate the faulting instruction */
1250 error = vmm_fetch_instruction(vm, vcpuid, paging, vme->rip,
1251 vme->inst_length, vie);
1253 return (0); /* Resume guest to handle page fault */
1254 else if (error == -1)
1256 else if (error != 0)
1257 panic("%s: vmm_fetch_instruction error %d", __func__, error);
1259 if (vmm_decode_instruction(vm, vcpuid, gla, cpu_mode, cs_d, vie) != 0)
1262 /* return to userland unless this is an in-kernel emulated device */
1263 if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1264 mread = lapic_mmio_read;
1265 mwrite = lapic_mmio_write;
1266 } else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1267 mread = vioapic_mmio_read;
1268 mwrite = vioapic_mmio_write;
1269 } else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1270 mread = vhpet_mmio_read;
1271 mwrite = vhpet_mmio_write;
1277 error = vmm_emulate_instruction(vm, vcpuid, gpa, vie, paging,
1278 mread, mwrite, retu);
1284 vm_handle_suspend(struct vm *vm, int vcpuid, bool *retu)
1290 vcpu = &vm->vcpu[vcpuid];
1292 CPU_SET_ATOMIC(vcpuid, &vm->suspended_cpus);
1295 * Wait until all 'active_cpus' have suspended themselves.
1297 * Since a VM may be suspended at any time including when one or
1298 * more vcpus are doing a rendezvous we need to call the rendezvous
1299 * handler while we are waiting to prevent a deadlock.
1303 if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1304 VCPU_CTR0(vm, vcpuid, "All vcpus suspended");
1308 if (vm->rendezvous_func == NULL) {
1309 VCPU_CTR0(vm, vcpuid, "Sleeping during suspend");
1310 vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1311 msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1312 vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1314 VCPU_CTR0(vm, vcpuid, "Rendezvous during suspend");
1316 vm_handle_rendezvous(vm, vcpuid);
1323 * Wakeup the other sleeping vcpus and return to userspace.
1325 for (i = 0; i < VM_MAXCPU; i++) {
1326 if (CPU_ISSET(i, &vm->suspended_cpus)) {
1327 vcpu_notify_event(vm, i, false);
1336 vm_suspend(struct vm *vm, enum vm_suspend_how how)
1340 if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
1343 if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
1344 VM_CTR2(vm, "virtual machine already suspended %d/%d",
1349 VM_CTR1(vm, "virtual machine successfully suspended %d", how);
1352 * Notify all active vcpus that they are now suspended.
1354 for (i = 0; i < VM_MAXCPU; i++) {
1355 if (CPU_ISSET(i, &vm->active_cpus))
1356 vcpu_notify_event(vm, i, false);
1363 vm_exit_suspended(struct vm *vm, int vcpuid, uint64_t rip)
1365 struct vm_exit *vmexit;
1367 KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
1368 ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
1370 vmexit = vm_exitinfo(vm, vcpuid);
1372 vmexit->inst_length = 0;
1373 vmexit->exitcode = VM_EXITCODE_SUSPENDED;
1374 vmexit->u.suspended.how = vm->suspend;
1378 vm_exit_rendezvous(struct vm *vm, int vcpuid, uint64_t rip)
1380 struct vm_exit *vmexit;
1382 KASSERT(vm->rendezvous_func != NULL, ("rendezvous not in progress"));
1384 vmexit = vm_exitinfo(vm, vcpuid);
1386 vmexit->inst_length = 0;
1387 vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1388 vmm_stat_incr(vm, vcpuid, VMEXIT_RENDEZVOUS, 1);
1392 vm_exit_astpending(struct vm *vm, int vcpuid, uint64_t rip)
1394 struct vm_exit *vmexit;
1396 vmexit = vm_exitinfo(vm, vcpuid);
1398 vmexit->inst_length = 0;
1399 vmexit->exitcode = VM_EXITCODE_BOGUS;
1400 vmm_stat_incr(vm, vcpuid, VMEXIT_ASTPENDING, 1);
1404 vm_run(struct vm *vm, struct vm_run *vmrun)
1409 uint64_t tscval, rip;
1410 struct vm_exit *vme;
1411 bool retu, intr_disabled;
1415 vcpuid = vmrun->cpuid;
1417 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1420 if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1423 if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1426 rptr = &vm->rendezvous_func;
1427 sptr = &vm->suspend;
1428 pmap = vmspace_pmap(vm->vmspace);
1429 vcpu = &vm->vcpu[vcpuid];
1430 vme = &vcpu->exitinfo;
1435 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1436 ("vm_run: absurd pm_active"));
1440 pcb = PCPU_GET(curpcb);
1441 set_pcb_flags(pcb, PCB_FULL_IRET);
1443 restore_guest_msrs(vm, vcpuid);
1444 restore_guest_fpustate(vcpu);
1446 vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
1447 error = VMRUN(vm->cookie, vcpuid, rip, pmap, rptr, sptr);
1448 vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
1450 save_guest_fpustate(vcpu);
1451 restore_host_msrs(vm, vcpuid);
1453 vmm_stat_incr(vm, vcpuid, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1459 switch (vme->exitcode) {
1460 case VM_EXITCODE_SUSPENDED:
1461 error = vm_handle_suspend(vm, vcpuid, &retu);
1463 case VM_EXITCODE_IOAPIC_EOI:
1464 vioapic_process_eoi(vm, vcpuid,
1465 vme->u.ioapic_eoi.vector);
1467 case VM_EXITCODE_RENDEZVOUS:
1468 vm_handle_rendezvous(vm, vcpuid);
1471 case VM_EXITCODE_HLT:
1472 intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1473 error = vm_handle_hlt(vm, vcpuid, intr_disabled, &retu);
1475 case VM_EXITCODE_PAGING:
1476 error = vm_handle_paging(vm, vcpuid, &retu);
1478 case VM_EXITCODE_INST_EMUL:
1479 error = vm_handle_inst_emul(vm, vcpuid, &retu);
1481 case VM_EXITCODE_INOUT:
1482 case VM_EXITCODE_INOUT_STR:
1483 error = vm_handle_inout(vm, vcpuid, vme, &retu);
1486 retu = true; /* handled in userland */
1491 if (error == 0 && retu == false) {
1492 rip = vme->rip + vme->inst_length;
1496 /* copy the exit information */
1497 bcopy(vme, &vmrun->vm_exit, sizeof(struct vm_exit));
1502 vm_exit_intinfo(struct vm *vm, int vcpuid, uint64_t info)
1507 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1510 vcpu = &vm->vcpu[vcpuid];
1512 if (info & VM_INTINFO_VALID) {
1513 type = info & VM_INTINFO_TYPE;
1514 vector = info & 0xff;
1515 if (type == VM_INTINFO_NMI && vector != IDT_NMI)
1517 if (type == VM_INTINFO_HWEXCEPTION && vector >= 32)
1519 if (info & VM_INTINFO_RSVD)
1524 VCPU_CTR2(vm, vcpuid, "%s: info1(%#lx)", __func__, info);
1525 vcpu->exitintinfo = info;
1535 #define IDT_VE 20 /* Virtualization Exception (Intel specific) */
1537 static enum exc_class
1538 exception_class(uint64_t info)
1542 KASSERT(info & VM_INTINFO_VALID, ("intinfo must be valid: %#lx", info));
1543 type = info & VM_INTINFO_TYPE;
1544 vector = info & 0xff;
1546 /* Table 6-4, "Interrupt and Exception Classes", Intel SDM, Vol 3 */
1548 case VM_INTINFO_HWINTR:
1549 case VM_INTINFO_SWINTR:
1550 case VM_INTINFO_NMI:
1551 return (EXC_BENIGN);
1554 * Hardware exception.
1556 * SVM and VT-x use identical type values to represent NMI,
1557 * hardware interrupt and software interrupt.
1559 * SVM uses type '3' for all exceptions. VT-x uses type '3'
1560 * for exceptions except #BP and #OF. #BP and #OF use a type
1561 * value of '5' or '6'. Therefore we don't check for explicit
1562 * values of 'type' to classify 'intinfo' into a hardware
1571 return (EXC_PAGEFAULT);
1577 return (EXC_CONTRIBUTORY);
1579 return (EXC_BENIGN);
1584 nested_fault(struct vm *vm, int vcpuid, uint64_t info1, uint64_t info2,
1587 enum exc_class exc1, exc2;
1590 KASSERT(info1 & VM_INTINFO_VALID, ("info1 %#lx is not valid", info1));
1591 KASSERT(info2 & VM_INTINFO_VALID, ("info2 %#lx is not valid", info2));
1594 * If an exception occurs while attempting to call the double-fault
1595 * handler the processor enters shutdown mode (aka triple fault).
1597 type1 = info1 & VM_INTINFO_TYPE;
1598 vector1 = info1 & 0xff;
1599 if (type1 == VM_INTINFO_HWEXCEPTION && vector1 == IDT_DF) {
1600 VCPU_CTR2(vm, vcpuid, "triple fault: info1(%#lx), info2(%#lx)",
1602 vm_suspend(vm, VM_SUSPEND_TRIPLEFAULT);
1608 * Table 6-5 "Conditions for Generating a Double Fault", Intel SDM, Vol3
1610 exc1 = exception_class(info1);
1611 exc2 = exception_class(info2);
1612 if ((exc1 == EXC_CONTRIBUTORY && exc2 == EXC_CONTRIBUTORY) ||
1613 (exc1 == EXC_PAGEFAULT && exc2 != EXC_BENIGN)) {
1614 /* Convert nested fault into a double fault. */
1616 *retinfo |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1617 *retinfo |= VM_INTINFO_DEL_ERRCODE;
1619 /* Handle exceptions serially */
1626 vcpu_exception_intinfo(struct vcpu *vcpu)
1630 if (vcpu->exception_pending) {
1631 info = vcpu->exception.vector & 0xff;
1632 info |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1633 if (vcpu->exception.error_code_valid) {
1634 info |= VM_INTINFO_DEL_ERRCODE;
1635 info |= (uint64_t)vcpu->exception.error_code << 32;
1642 vm_entry_intinfo(struct vm *vm, int vcpuid, uint64_t *retinfo)
1645 uint64_t info1, info2;
1648 KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU, ("invalid vcpu %d", vcpuid));
1650 vcpu = &vm->vcpu[vcpuid];
1652 info1 = vcpu->exitintinfo;
1653 vcpu->exitintinfo = 0;
1656 if (vcpu->exception_pending) {
1657 info2 = vcpu_exception_intinfo(vcpu);
1658 vcpu->exception_pending = 0;
1659 VCPU_CTR2(vm, vcpuid, "Exception %d delivered: %#lx",
1660 vcpu->exception.vector, info2);
1663 if ((info1 & VM_INTINFO_VALID) && (info2 & VM_INTINFO_VALID)) {
1664 valid = nested_fault(vm, vcpuid, info1, info2, retinfo);
1665 } else if (info1 & VM_INTINFO_VALID) {
1668 } else if (info2 & VM_INTINFO_VALID) {
1676 VCPU_CTR4(vm, vcpuid, "%s: info1(%#lx), info2(%#lx), "
1677 "retinfo(%#lx)", __func__, info1, info2, *retinfo);
1684 vm_get_intinfo(struct vm *vm, int vcpuid, uint64_t *info1, uint64_t *info2)
1688 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1691 vcpu = &vm->vcpu[vcpuid];
1692 *info1 = vcpu->exitintinfo;
1693 *info2 = vcpu_exception_intinfo(vcpu);
1698 vm_inject_exception(struct vm *vm, int vcpuid, struct vm_exception *exception)
1702 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1705 if (exception->vector < 0 || exception->vector >= 32)
1709 * A double fault exception should never be injected directly into
1710 * the guest. It is a derived exception that results from specific
1711 * combinations of nested faults.
1713 if (exception->vector == IDT_DF)
1716 vcpu = &vm->vcpu[vcpuid];
1718 if (vcpu->exception_pending) {
1719 VCPU_CTR2(vm, vcpuid, "Unable to inject exception %d due to "
1720 "pending exception %d", exception->vector,
1721 vcpu->exception.vector);
1725 vcpu->exception_pending = 1;
1726 vcpu->exception = *exception;
1727 VCPU_CTR1(vm, vcpuid, "Exception %d pending", exception->vector);
1732 vm_inject_fault(void *vmarg, int vcpuid, int vector, int errcode_valid,
1735 struct vm_exception exception;
1736 struct vm_exit *vmexit;
1742 exception.vector = vector;
1743 exception.error_code = errcode;
1744 exception.error_code_valid = errcode_valid;
1745 error = vm_inject_exception(vm, vcpuid, &exception);
1746 KASSERT(error == 0, ("vm_inject_exception error %d", error));
1749 * A fault-like exception allows the instruction to be restarted
1750 * after the exception handler returns.
1752 * By setting the inst_length to 0 we ensure that the instruction
1753 * pointer remains at the faulting instruction.
1755 vmexit = vm_exitinfo(vm, vcpuid);
1756 vmexit->inst_length = 0;
1760 vm_inject_pf(void *vmarg, int vcpuid, int error_code, uint64_t cr2)
1766 VCPU_CTR2(vm, vcpuid, "Injecting page fault: error_code %#x, cr2 %#lx",
1769 error = vm_set_register(vm, vcpuid, VM_REG_GUEST_CR2, cr2);
1770 KASSERT(error == 0, ("vm_set_register(cr2) error %d", error));
1772 vm_inject_fault(vm, vcpuid, IDT_PF, 1, error_code);
1775 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
1778 vm_inject_nmi(struct vm *vm, int vcpuid)
1782 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1785 vcpu = &vm->vcpu[vcpuid];
1787 vcpu->nmi_pending = 1;
1788 vcpu_notify_event(vm, vcpuid, false);
1793 vm_nmi_pending(struct vm *vm, int vcpuid)
1797 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1798 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1800 vcpu = &vm->vcpu[vcpuid];
1802 return (vcpu->nmi_pending);
1806 vm_nmi_clear(struct vm *vm, int vcpuid)
1810 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1811 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1813 vcpu = &vm->vcpu[vcpuid];
1815 if (vcpu->nmi_pending == 0)
1816 panic("vm_nmi_clear: inconsistent nmi_pending state");
1818 vcpu->nmi_pending = 0;
1819 vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
1822 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
1825 vm_inject_extint(struct vm *vm, int vcpuid)
1829 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1832 vcpu = &vm->vcpu[vcpuid];
1834 vcpu->extint_pending = 1;
1835 vcpu_notify_event(vm, vcpuid, false);
1840 vm_extint_pending(struct vm *vm, int vcpuid)
1844 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1845 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1847 vcpu = &vm->vcpu[vcpuid];
1849 return (vcpu->extint_pending);
1853 vm_extint_clear(struct vm *vm, int vcpuid)
1857 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1858 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1860 vcpu = &vm->vcpu[vcpuid];
1862 if (vcpu->extint_pending == 0)
1863 panic("vm_extint_clear: inconsistent extint_pending state");
1865 vcpu->extint_pending = 0;
1866 vmm_stat_incr(vm, vcpuid, VCPU_EXTINT_COUNT, 1);
1870 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
1872 if (vcpu < 0 || vcpu >= VM_MAXCPU)
1875 if (type < 0 || type >= VM_CAP_MAX)
1878 return (VMGETCAP(vm->cookie, vcpu, type, retval));
1882 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
1884 if (vcpu < 0 || vcpu >= VM_MAXCPU)
1887 if (type < 0 || type >= VM_CAP_MAX)
1890 return (VMSETCAP(vm->cookie, vcpu, type, val));
1894 vm_guest_msrs(struct vm *vm, int cpu)
1896 return (vm->vcpu[cpu].guest_msrs);
1900 vm_lapic(struct vm *vm, int cpu)
1902 return (vm->vcpu[cpu].vlapic);
1906 vm_ioapic(struct vm *vm)
1909 return (vm->vioapic);
1913 vm_hpet(struct vm *vm)
1920 vmm_is_pptdev(int bus, int slot, int func)
1924 char *val, *cp, *cp2;
1928 * The length of an environment variable is limited to 128 bytes which
1929 * puts an upper limit on the number of passthru devices that may be
1930 * specified using a single environment variable.
1932 * Work around this by scanning multiple environment variable
1933 * names instead of a single one - yuck!
1935 const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
1937 /* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
1939 for (i = 0; names[i] != NULL && !found; i++) {
1940 cp = val = getenv(names[i]);
1941 while (cp != NULL && *cp != '\0') {
1942 if ((cp2 = strchr(cp, ' ')) != NULL)
1945 n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
1946 if (n == 3 && bus == b && slot == s && func == f) {
1962 vm_iommu_domain(struct vm *vm)
1969 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate,
1975 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1976 panic("vm_set_run_state: invalid vcpuid %d", vcpuid);
1978 vcpu = &vm->vcpu[vcpuid];
1981 error = vcpu_set_state_locked(vcpu, newstate, from_idle);
1988 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
1991 enum vcpu_state state;
1993 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1994 panic("vm_get_run_state: invalid vcpuid %d", vcpuid);
1996 vcpu = &vm->vcpu[vcpuid];
1999 state = vcpu->state;
2000 if (hostcpu != NULL)
2001 *hostcpu = vcpu->hostcpu;
2008 vm_activate_cpu(struct vm *vm, int vcpuid)
2011 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2014 if (CPU_ISSET(vcpuid, &vm->active_cpus))
2017 VCPU_CTR0(vm, vcpuid, "activated");
2018 CPU_SET_ATOMIC(vcpuid, &vm->active_cpus);
2023 vm_active_cpus(struct vm *vm)
2026 return (vm->active_cpus);
2030 vm_suspended_cpus(struct vm *vm)
2033 return (vm->suspended_cpus);
2037 vcpu_stats(struct vm *vm, int vcpuid)
2040 return (vm->vcpu[vcpuid].stats);
2044 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
2046 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2049 *state = vm->vcpu[vcpuid].x2apic_state;
2055 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
2057 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2060 if (state >= X2APIC_STATE_LAST)
2063 vm->vcpu[vcpuid].x2apic_state = state;
2065 vlapic_set_x2apic_state(vm, vcpuid, state);
2071 * This function is called to ensure that a vcpu "sees" a pending event
2072 * as soon as possible:
2073 * - If the vcpu thread is sleeping then it is woken up.
2074 * - If the vcpu is running on a different host_cpu then an IPI will be directed
2075 * to the host_cpu to cause the vcpu to trap into the hypervisor.
2078 vcpu_notify_event(struct vm *vm, int vcpuid, bool lapic_intr)
2083 vcpu = &vm->vcpu[vcpuid];
2086 hostcpu = vcpu->hostcpu;
2087 if (vcpu->state == VCPU_RUNNING) {
2088 KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
2089 if (hostcpu != curcpu) {
2091 vlapic_post_intr(vcpu->vlapic, hostcpu,
2094 ipi_cpu(hostcpu, vmm_ipinum);
2098 * If the 'vcpu' is running on 'curcpu' then it must
2099 * be sending a notification to itself (e.g. SELF_IPI).
2100 * The pending event will be picked up when the vcpu
2101 * transitions back to guest context.
2105 KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
2106 "with hostcpu %d", vcpu->state, hostcpu));
2107 if (vcpu->state == VCPU_SLEEPING)
2114 vm_get_vmspace(struct vm *vm)
2117 return (vm->vmspace);
2121 vm_apicid2vcpuid(struct vm *vm, int apicid)
2124 * XXX apic id is assumed to be numerically identical to vcpu id
2130 vm_smp_rendezvous(struct vm *vm, int vcpuid, cpuset_t dest,
2131 vm_rendezvous_func_t func, void *arg)
2136 * Enforce that this function is called without any locks
2138 WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
2139 KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
2140 ("vm_smp_rendezvous: invalid vcpuid %d", vcpuid));
2143 mtx_lock(&vm->rendezvous_mtx);
2144 if (vm->rendezvous_func != NULL) {
2146 * If a rendezvous is already in progress then we need to
2147 * call the rendezvous handler in case this 'vcpuid' is one
2148 * of the targets of the rendezvous.
2150 RENDEZVOUS_CTR0(vm, vcpuid, "Rendezvous already in progress");
2151 mtx_unlock(&vm->rendezvous_mtx);
2152 vm_handle_rendezvous(vm, vcpuid);
2155 KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
2156 "rendezvous is still in progress"));
2158 RENDEZVOUS_CTR0(vm, vcpuid, "Initiating rendezvous");
2159 vm->rendezvous_req_cpus = dest;
2160 CPU_ZERO(&vm->rendezvous_done_cpus);
2161 vm->rendezvous_arg = arg;
2162 vm_set_rendezvous_func(vm, func);
2163 mtx_unlock(&vm->rendezvous_mtx);
2166 * Wake up any sleeping vcpus and trigger a VM-exit in any running
2167 * vcpus so they handle the rendezvous as soon as possible.
2169 for (i = 0; i < VM_MAXCPU; i++) {
2170 if (CPU_ISSET(i, &dest))
2171 vcpu_notify_event(vm, i, false);
2174 vm_handle_rendezvous(vm, vcpuid);
2178 vm_atpic(struct vm *vm)
2180 return (vm->vatpic);
2184 vm_atpit(struct vm *vm)
2186 return (vm->vatpit);
2190 vm_segment_name(int seg)
2192 static enum vm_reg_name seg_names[] = {
2201 KASSERT(seg >= 0 && seg < nitems(seg_names),
2202 ("%s: invalid segment encoding %d", __func__, seg));
2203 return (seg_names[seg]);
2207 vm_copy_teardown(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo,
2212 for (idx = 0; idx < num_copyinfo; idx++) {
2213 if (copyinfo[idx].cookie != NULL)
2214 vm_gpa_release(copyinfo[idx].cookie);
2216 bzero(copyinfo, num_copyinfo * sizeof(struct vm_copyinfo));
2220 vm_copy_setup(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
2221 uint64_t gla, size_t len, int prot, struct vm_copyinfo *copyinfo,
2224 int error, idx, nused;
2225 size_t n, off, remaining;
2229 bzero(copyinfo, sizeof(struct vm_copyinfo) * num_copyinfo);
2233 while (remaining > 0) {
2234 KASSERT(nused < num_copyinfo, ("insufficient vm_copyinfo"));
2235 error = vmm_gla2gpa(vm, vcpuid, paging, gla, prot, &gpa);
2238 off = gpa & PAGE_MASK;
2239 n = min(remaining, PAGE_SIZE - off);
2240 copyinfo[nused].gpa = gpa;
2241 copyinfo[nused].len = n;
2247 for (idx = 0; idx < nused; idx++) {
2248 hva = vm_gpa_hold(vm, copyinfo[idx].gpa, copyinfo[idx].len,
2252 copyinfo[idx].hva = hva;
2253 copyinfo[idx].cookie = cookie;
2257 vm_copy_teardown(vm, vcpuid, copyinfo, num_copyinfo);
2265 vm_copyin(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo, void *kaddr,
2274 bcopy(copyinfo[idx].hva, dst, copyinfo[idx].len);
2275 len -= copyinfo[idx].len;
2276 dst += copyinfo[idx].len;
2282 vm_copyout(struct vm *vm, int vcpuid, const void *kaddr,
2283 struct vm_copyinfo *copyinfo, size_t len)
2291 bcopy(src, copyinfo[idx].hva, copyinfo[idx].len);
2292 len -= copyinfo[idx].len;
2293 src += copyinfo[idx].len;
2299 * Return the amount of in-use and wired memory for the VM. Since
2300 * these are global stats, only return the values with for vCPU 0
2302 VMM_STAT_DECLARE(VMM_MEM_RESIDENT);
2303 VMM_STAT_DECLARE(VMM_MEM_WIRED);
2306 vm_get_rescnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2310 vmm_stat_set(vm, vcpu, VMM_MEM_RESIDENT,
2311 PAGE_SIZE * vmspace_resident_count(vm->vmspace));
2316 vm_get_wiredcnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2320 vmm_stat_set(vm, vcpu, VMM_MEM_WIRED,
2321 PAGE_SIZE * pmap_wired_count(vmspace_pmap(vm->vmspace)));
2325 VMM_STAT_FUNC(VMM_MEM_RESIDENT, "Resident memory", vm_get_rescnt);
2326 VMM_STAT_FUNC(VMM_MEM_WIRED, "Wired memory", vm_get_wiredcnt);