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"
79 #include "vmm_lapic.h"
88 * (a) allocated when vcpu is created
89 * (i) initialized when vcpu is created and when it is reinitialized
90 * (o) initialized the first time the vcpu is created
91 * (x) initialized before use
94 struct mtx mtx; /* (o) protects 'state' and 'hostcpu' */
95 enum vcpu_state state; /* (o) vcpu state */
96 int hostcpu; /* (o) vcpu's host cpu */
97 struct vlapic *vlapic; /* (i) APIC device model */
98 enum x2apic_state x2apic_state; /* (i) APIC mode */
99 uint64_t exitintinfo; /* (i) events pending at VM exit */
100 int nmi_pending; /* (i) NMI pending */
101 int extint_pending; /* (i) INTR pending */
102 struct vm_exception exception; /* (x) exception collateral */
103 int exception_pending; /* (i) exception pending */
104 struct savefpu *guestfpu; /* (a,i) guest fpu state */
105 uint64_t guest_xcr0; /* (i) guest %xcr0 register */
106 void *stats; /* (a,i) statistics */
107 struct vm_exit exitinfo; /* (x) exit reason and collateral */
110 #define vcpu_lock_initialized(v) mtx_initialized(&((v)->mtx))
111 #define vcpu_lock_init(v) mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
112 #define vcpu_lock(v) mtx_lock_spin(&((v)->mtx))
113 #define vcpu_unlock(v) mtx_unlock_spin(&((v)->mtx))
114 #define vcpu_assert_locked(v) mtx_assert(&((v)->mtx), MA_OWNED)
122 #define VM_MAX_MEMORY_SEGMENTS 2
126 * (o) initialized the first time the VM is created
127 * (i) initialized when VM is created and when it is reinitialized
128 * (x) initialized before use
131 void *cookie; /* (i) cpu-specific data */
132 void *iommu; /* (x) iommu-specific data */
133 struct vhpet *vhpet; /* (i) virtual HPET */
134 struct vioapic *vioapic; /* (i) virtual ioapic */
135 struct vatpic *vatpic; /* (i) virtual atpic */
136 struct vatpit *vatpit; /* (i) virtual atpit */
137 volatile cpuset_t active_cpus; /* (i) active vcpus */
138 int suspend; /* (i) stop VM execution */
139 volatile cpuset_t suspended_cpus; /* (i) suspended vcpus */
140 volatile cpuset_t halted_cpus; /* (x) cpus in a hard halt */
141 cpuset_t rendezvous_req_cpus; /* (x) rendezvous requested */
142 cpuset_t rendezvous_done_cpus; /* (x) rendezvous finished */
143 void *rendezvous_arg; /* (x) rendezvous func/arg */
144 vm_rendezvous_func_t rendezvous_func;
145 struct mtx rendezvous_mtx; /* (o) rendezvous lock */
146 int num_mem_segs; /* (o) guest memory segments */
147 struct mem_seg mem_segs[VM_MAX_MEMORY_SEGMENTS];
148 struct vmspace *vmspace; /* (o) guest's address space */
149 char name[VM_MAX_NAMELEN]; /* (o) virtual machine name */
150 struct vcpu vcpu[VM_MAXCPU]; /* (i) guest vcpus */
153 static int vmm_initialized;
155 static struct vmm_ops *ops;
156 #define VMM_INIT(num) (ops != NULL ? (*ops->init)(num) : 0)
157 #define VMM_CLEANUP() (ops != NULL ? (*ops->cleanup)() : 0)
158 #define VMM_RESUME() (ops != NULL ? (*ops->resume)() : 0)
160 #define VMINIT(vm, pmap) (ops != NULL ? (*ops->vminit)(vm, pmap): NULL)
161 #define VMRUN(vmi, vcpu, rip, pmap, rptr, sptr) \
162 (ops != NULL ? (*ops->vmrun)(vmi, vcpu, rip, pmap, rptr, sptr) : ENXIO)
163 #define VMCLEANUP(vmi) (ops != NULL ? (*ops->vmcleanup)(vmi) : NULL)
164 #define VMSPACE_ALLOC(min, max) \
165 (ops != NULL ? (*ops->vmspace_alloc)(min, max) : NULL)
166 #define VMSPACE_FREE(vmspace) \
167 (ops != NULL ? (*ops->vmspace_free)(vmspace) : ENXIO)
168 #define VMGETREG(vmi, vcpu, num, retval) \
169 (ops != NULL ? (*ops->vmgetreg)(vmi, vcpu, num, retval) : ENXIO)
170 #define VMSETREG(vmi, vcpu, num, val) \
171 (ops != NULL ? (*ops->vmsetreg)(vmi, vcpu, num, val) : ENXIO)
172 #define VMGETDESC(vmi, vcpu, num, desc) \
173 (ops != NULL ? (*ops->vmgetdesc)(vmi, vcpu, num, desc) : ENXIO)
174 #define VMSETDESC(vmi, vcpu, num, desc) \
175 (ops != NULL ? (*ops->vmsetdesc)(vmi, vcpu, num, desc) : ENXIO)
176 #define VMGETCAP(vmi, vcpu, num, retval) \
177 (ops != NULL ? (*ops->vmgetcap)(vmi, vcpu, num, retval) : ENXIO)
178 #define VMSETCAP(vmi, vcpu, num, val) \
179 (ops != NULL ? (*ops->vmsetcap)(vmi, vcpu, num, val) : ENXIO)
180 #define VLAPIC_INIT(vmi, vcpu) \
181 (ops != NULL ? (*ops->vlapic_init)(vmi, vcpu) : NULL)
182 #define VLAPIC_CLEANUP(vmi, vlapic) \
183 (ops != NULL ? (*ops->vlapic_cleanup)(vmi, vlapic) : NULL)
185 #define fpu_start_emulating() load_cr0(rcr0() | CR0_TS)
186 #define fpu_stop_emulating() clts()
188 static MALLOC_DEFINE(M_VM, "vm", "vm");
191 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
193 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW, NULL, NULL);
196 * Halt the guest if all vcpus are executing a HLT instruction with
197 * interrupts disabled.
199 static int halt_detection_enabled = 1;
200 SYSCTL_INT(_hw_vmm, OID_AUTO, halt_detection, CTLFLAG_RDTUN,
201 &halt_detection_enabled, 0,
202 "Halt VM if all vcpus execute HLT with interrupts disabled");
204 static int vmm_ipinum;
205 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
206 "IPI vector used for vcpu notifications");
209 vcpu_cleanup(struct vm *vm, int i, bool destroy)
211 struct vcpu *vcpu = &vm->vcpu[i];
213 VLAPIC_CLEANUP(vm->cookie, vcpu->vlapic);
215 vmm_stat_free(vcpu->stats);
216 fpu_save_area_free(vcpu->guestfpu);
221 vcpu_init(struct vm *vm, int vcpu_id, bool create)
225 KASSERT(vcpu_id >= 0 && vcpu_id < VM_MAXCPU,
226 ("vcpu_init: invalid vcpu %d", vcpu_id));
228 vcpu = &vm->vcpu[vcpu_id];
231 KASSERT(!vcpu_lock_initialized(vcpu), ("vcpu %d already "
232 "initialized", vcpu_id));
233 vcpu_lock_init(vcpu);
234 vcpu->state = VCPU_IDLE;
235 vcpu->hostcpu = NOCPU;
236 vcpu->guestfpu = fpu_save_area_alloc();
237 vcpu->stats = vmm_stat_alloc();
240 vcpu->vlapic = VLAPIC_INIT(vm->cookie, vcpu_id);
241 vm_set_x2apic_state(vm, vcpu_id, X2APIC_DISABLED);
242 vcpu->exitintinfo = 0;
243 vcpu->nmi_pending = 0;
244 vcpu->extint_pending = 0;
245 vcpu->exception_pending = 0;
246 vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
247 fpu_save_area_reset(vcpu->guestfpu);
248 vmm_stat_init(vcpu->stats);
252 vm_exitinfo(struct vm *vm, int cpuid)
256 if (cpuid < 0 || cpuid >= VM_MAXCPU)
257 panic("vm_exitinfo: invalid cpuid %d", cpuid);
259 vcpu = &vm->vcpu[cpuid];
261 return (&vcpu->exitinfo);
275 vmm_host_state_init();
277 vmm_ipinum = vmm_ipi_alloc();
279 vmm_ipinum = IPI_AST;
281 error = vmm_mem_init();
286 ops = &vmm_ops_intel;
287 else if (vmm_is_amd())
292 vmm_resume_p = vmm_resume;
294 return (VMM_INIT(vmm_ipinum));
298 vmm_handler(module_t mod, int what, void *arg)
305 if (ppt_avail_devices() > 0)
312 error = vmmdev_cleanup();
316 if (vmm_ipinum != IPI_AST)
317 vmm_ipi_free(vmm_ipinum);
318 error = VMM_CLEANUP();
320 * Something bad happened - prevent new
321 * VMs from being created
334 static moduledata_t vmm_kmod = {
341 * vmm initialization has the following dependencies:
343 * - iommu initialization must happen after the pci passthru driver has had
344 * a chance to attach to any passthru devices (after SI_SUB_CONFIGURE).
346 * - VT-x initialization requires smp_rendezvous() and therefore must happen
347 * after SMP is fully functional (after SI_SUB_SMP).
349 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
350 MODULE_VERSION(vmm, 1);
353 vm_init(struct vm *vm, bool create)
357 vm->cookie = VMINIT(vm, vmspace_pmap(vm->vmspace));
359 vm->vioapic = vioapic_init(vm);
360 vm->vhpet = vhpet_init(vm);
361 vm->vatpic = vatpic_init(vm);
362 vm->vatpit = vatpit_init(vm);
364 CPU_ZERO(&vm->active_cpus);
367 CPU_ZERO(&vm->suspended_cpus);
369 for (i = 0; i < VM_MAXCPU; i++)
370 vcpu_init(vm, i, create);
374 vm_create(const char *name, struct vm **retvm)
377 struct vmspace *vmspace;
380 * If vmm.ko could not be successfully initialized then don't attempt
381 * to create the virtual machine.
383 if (!vmm_initialized)
386 if (name == NULL || strlen(name) >= VM_MAX_NAMELEN)
389 vmspace = VMSPACE_ALLOC(VM_MIN_ADDRESS, VM_MAXUSER_ADDRESS);
393 vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
394 strcpy(vm->name, name);
395 vm->num_mem_segs = 0;
396 vm->vmspace = vmspace;
397 mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
406 vm_free_mem_seg(struct vm *vm, struct mem_seg *seg)
409 if (seg->object != NULL)
410 vmm_mem_free(vm->vmspace, seg->gpa, seg->len);
412 bzero(seg, sizeof(*seg));
416 vm_cleanup(struct vm *vm, bool destroy)
420 ppt_unassign_all(vm);
422 if (vm->iommu != NULL)
423 iommu_destroy_domain(vm->iommu);
425 vatpit_cleanup(vm->vatpit);
426 vhpet_cleanup(vm->vhpet);
427 vatpic_cleanup(vm->vatpic);
428 vioapic_cleanup(vm->vioapic);
430 for (i = 0; i < VM_MAXCPU; i++)
431 vcpu_cleanup(vm, i, destroy);
433 VMCLEANUP(vm->cookie);
436 for (i = 0; i < vm->num_mem_segs; i++)
437 vm_free_mem_seg(vm, &vm->mem_segs[i]);
439 vm->num_mem_segs = 0;
441 VMSPACE_FREE(vm->vmspace);
447 vm_destroy(struct vm *vm)
449 vm_cleanup(vm, true);
454 vm_reinit(struct vm *vm)
459 * A virtual machine can be reset only if all vcpus are suspended.
461 if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
462 vm_cleanup(vm, false);
473 vm_name(struct vm *vm)
479 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
483 if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
490 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
493 vmm_mmio_free(vm->vmspace, gpa, len);
498 vm_mem_allocated(struct vm *vm, vm_paddr_t gpa)
501 vm_paddr_t gpabase, gpalimit;
503 for (i = 0; i < vm->num_mem_segs; i++) {
504 gpabase = vm->mem_segs[i].gpa;
505 gpalimit = gpabase + vm->mem_segs[i].len;
506 if (gpa >= gpabase && gpa < gpalimit)
507 return (TRUE); /* 'gpa' is regular memory */
510 if (ppt_is_mmio(vm, gpa))
511 return (TRUE); /* 'gpa' is pci passthru mmio */
517 vm_malloc(struct vm *vm, vm_paddr_t gpa, size_t len)
519 int available, allocated;
524 if ((gpa & PAGE_MASK) || (len & PAGE_MASK) || len == 0)
527 available = allocated = 0;
529 while (g < gpa + len) {
530 if (vm_mem_allocated(vm, g))
539 * If there are some allocated and some available pages in the address
540 * range then it is an error.
542 if (allocated && available)
546 * If the entire address range being requested has already been
547 * allocated then there isn't anything more to do.
549 if (allocated && available == 0)
552 if (vm->num_mem_segs >= VM_MAX_MEMORY_SEGMENTS)
555 seg = &vm->mem_segs[vm->num_mem_segs];
557 if ((object = vmm_mem_alloc(vm->vmspace, gpa, len)) == NULL)
562 seg->object = object;
571 vm_maxmem(struct vm *vm)
574 vm_paddr_t gpa, maxmem;
577 for (i = 0; i < vm->num_mem_segs; i++) {
578 gpa = vm->mem_segs[i].gpa + vm->mem_segs[i].len;
586 vm_gpa_unwire(struct vm *vm)
591 for (i = 0; i < vm->num_mem_segs; i++) {
592 seg = &vm->mem_segs[i];
596 rv = vm_map_unwire(&vm->vmspace->vm_map,
597 seg->gpa, seg->gpa + seg->len,
598 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
599 KASSERT(rv == KERN_SUCCESS, ("vm(%s) memory segment "
600 "%#lx/%ld could not be unwired: %d",
601 vm_name(vm), seg->gpa, seg->len, rv));
608 vm_gpa_wire(struct vm *vm)
613 for (i = 0; i < vm->num_mem_segs; i++) {
614 seg = &vm->mem_segs[i];
619 rv = vm_map_wire(&vm->vmspace->vm_map,
620 seg->gpa, seg->gpa + seg->len,
621 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
622 if (rv != KERN_SUCCESS)
628 if (i < vm->num_mem_segs) {
630 * Undo the wiring before returning an error.
640 vm_iommu_modify(struct vm *vm, boolean_t map)
645 void *vp, *cookie, *host_domain;
648 host_domain = iommu_host_domain();
650 for (i = 0; i < vm->num_mem_segs; i++) {
651 seg = &vm->mem_segs[i];
652 KASSERT(seg->wired, ("vm(%s) memory segment %#lx/%ld not wired",
653 vm_name(vm), seg->gpa, seg->len));
656 while (gpa < seg->gpa + seg->len) {
657 vp = vm_gpa_hold(vm, gpa, PAGE_SIZE, VM_PROT_WRITE,
659 KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
662 vm_gpa_release(cookie);
664 hpa = DMAP_TO_PHYS((uintptr_t)vp);
666 iommu_create_mapping(vm->iommu, gpa, hpa, sz);
667 iommu_remove_mapping(host_domain, hpa, sz);
669 iommu_remove_mapping(vm->iommu, gpa, sz);
670 iommu_create_mapping(host_domain, hpa, hpa, sz);
678 * Invalidate the cached translations associated with the domain
679 * from which pages were removed.
682 iommu_invalidate_tlb(host_domain);
684 iommu_invalidate_tlb(vm->iommu);
687 #define vm_iommu_unmap(vm) vm_iommu_modify((vm), FALSE)
688 #define vm_iommu_map(vm) vm_iommu_modify((vm), TRUE)
691 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
695 error = ppt_unassign_device(vm, bus, slot, func);
699 if (ppt_assigned_devices(vm) == 0) {
707 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
713 * Virtual machines with pci passthru devices get special treatment:
714 * - the guest physical memory is wired
715 * - the iommu is programmed to do the 'gpa' to 'hpa' translation
717 * We need to do this before the first pci passthru device is attached.
719 if (ppt_assigned_devices(vm) == 0) {
720 KASSERT(vm->iommu == NULL,
721 ("vm_assign_pptdev: iommu must be NULL"));
722 maxaddr = vm_maxmem(vm);
723 vm->iommu = iommu_create_domain(maxaddr);
725 error = vm_gpa_wire(vm);
732 error = ppt_assign_device(vm, bus, slot, func);
737 vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
743 pageoff = gpa & PAGE_MASK;
744 if (len > PAGE_SIZE - pageoff)
745 panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
747 count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
748 trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
752 return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
760 vm_gpa_release(void *cookie)
762 vm_page_t m = cookie;
770 vm_gpabase2memseg(struct vm *vm, vm_paddr_t gpabase,
771 struct vm_memory_segment *seg)
775 for (i = 0; i < vm->num_mem_segs; i++) {
776 if (gpabase == vm->mem_segs[i].gpa) {
777 seg->gpa = vm->mem_segs[i].gpa;
778 seg->len = vm->mem_segs[i].len;
779 seg->wired = vm->mem_segs[i].wired;
787 vm_get_memobj(struct vm *vm, vm_paddr_t gpa, size_t len,
788 vm_offset_t *offset, struct vm_object **object)
795 for (i = 0; i < vm->num_mem_segs; i++) {
796 if ((seg_obj = vm->mem_segs[i].object) == NULL)
799 seg_gpa = vm->mem_segs[i].gpa;
800 seg_len = vm->mem_segs[i].len;
802 if (gpa >= seg_gpa && gpa < seg_gpa + seg_len) {
803 *offset = gpa - seg_gpa;
805 vm_object_reference(seg_obj);
814 vm_get_register(struct vm *vm, int vcpu, int reg, uint64_t *retval)
817 if (vcpu < 0 || vcpu >= VM_MAXCPU)
820 if (reg >= VM_REG_LAST)
823 return (VMGETREG(vm->cookie, vcpu, reg, retval));
827 vm_set_register(struct vm *vm, int vcpu, int reg, uint64_t val)
830 if (vcpu < 0 || vcpu >= VM_MAXCPU)
833 if (reg >= VM_REG_LAST)
836 return (VMSETREG(vm->cookie, vcpu, reg, val));
840 is_descriptor_table(int reg)
844 case VM_REG_GUEST_IDTR:
845 case VM_REG_GUEST_GDTR:
853 is_segment_register(int reg)
857 case VM_REG_GUEST_ES:
858 case VM_REG_GUEST_CS:
859 case VM_REG_GUEST_SS:
860 case VM_REG_GUEST_DS:
861 case VM_REG_GUEST_FS:
862 case VM_REG_GUEST_GS:
863 case VM_REG_GUEST_TR:
864 case VM_REG_GUEST_LDTR:
872 vm_get_seg_desc(struct vm *vm, int vcpu, int reg,
873 struct seg_desc *desc)
876 if (vcpu < 0 || vcpu >= VM_MAXCPU)
879 if (!is_segment_register(reg) && !is_descriptor_table(reg))
882 return (VMGETDESC(vm->cookie, vcpu, reg, desc));
886 vm_set_seg_desc(struct vm *vm, int vcpu, int reg,
887 struct seg_desc *desc)
889 if (vcpu < 0 || vcpu >= VM_MAXCPU)
892 if (!is_segment_register(reg) && !is_descriptor_table(reg))
895 return (VMSETDESC(vm->cookie, vcpu, reg, desc));
899 restore_guest_fpustate(struct vcpu *vcpu)
902 /* flush host state to the pcb */
905 /* restore guest FPU state */
906 fpu_stop_emulating();
907 fpurestore(vcpu->guestfpu);
909 /* restore guest XCR0 if XSAVE is enabled in the host */
910 if (rcr4() & CR4_XSAVE)
911 load_xcr(0, vcpu->guest_xcr0);
914 * The FPU is now "dirty" with the guest's state so turn on emulation
915 * to trap any access to the FPU by the host.
917 fpu_start_emulating();
921 save_guest_fpustate(struct vcpu *vcpu)
924 if ((rcr0() & CR0_TS) == 0)
925 panic("fpu emulation not enabled in host!");
927 /* save guest XCR0 and restore host XCR0 */
928 if (rcr4() & CR4_XSAVE) {
929 vcpu->guest_xcr0 = rxcr(0);
930 load_xcr(0, vmm_get_host_xcr0());
933 /* save guest FPU state */
934 fpu_stop_emulating();
935 fpusave(vcpu->guestfpu);
936 fpu_start_emulating();
939 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
942 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate,
947 vcpu_assert_locked(vcpu);
950 * State transitions from the vmmdev_ioctl() must always begin from
951 * the VCPU_IDLE state. This guarantees that there is only a single
952 * ioctl() operating on a vcpu at any point.
955 while (vcpu->state != VCPU_IDLE)
956 msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
958 KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
962 if (vcpu->state == VCPU_RUNNING) {
963 KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
964 "mismatch for running vcpu", curcpu, vcpu->hostcpu));
966 KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
967 "vcpu that is not running", vcpu->hostcpu));
971 * The following state transitions are allowed:
972 * IDLE -> FROZEN -> IDLE
973 * FROZEN -> RUNNING -> FROZEN
974 * FROZEN -> SLEEPING -> FROZEN
976 switch (vcpu->state) {
980 error = (newstate != VCPU_FROZEN);
983 error = (newstate == VCPU_FROZEN);
993 vcpu->state = newstate;
994 if (newstate == VCPU_RUNNING)
995 vcpu->hostcpu = curcpu;
997 vcpu->hostcpu = NOCPU;
999 if (newstate == VCPU_IDLE)
1000 wakeup(&vcpu->state);
1006 vcpu_require_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
1010 if ((error = vcpu_set_state(vm, vcpuid, newstate, false)) != 0)
1011 panic("Error %d setting state to %d\n", error, newstate);
1015 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
1019 if ((error = vcpu_set_state_locked(vcpu, newstate, false)) != 0)
1020 panic("Error %d setting state to %d", error, newstate);
1024 vm_set_rendezvous_func(struct vm *vm, vm_rendezvous_func_t func)
1027 KASSERT(mtx_owned(&vm->rendezvous_mtx), ("rendezvous_mtx not locked"));
1030 * Update 'rendezvous_func' and execute a write memory barrier to
1031 * ensure that it is visible across all host cpus. This is not needed
1032 * for correctness but it does ensure that all the vcpus will notice
1033 * that the rendezvous is requested immediately.
1035 vm->rendezvous_func = func;
1039 #define RENDEZVOUS_CTR0(vm, vcpuid, fmt) \
1042 VCPU_CTR0(vm, vcpuid, fmt); \
1048 vm_handle_rendezvous(struct vm *vm, int vcpuid)
1051 KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
1052 ("vm_handle_rendezvous: invalid vcpuid %d", vcpuid));
1054 mtx_lock(&vm->rendezvous_mtx);
1055 while (vm->rendezvous_func != NULL) {
1056 /* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
1057 CPU_AND(&vm->rendezvous_req_cpus, &vm->active_cpus);
1060 CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
1061 !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
1062 VCPU_CTR0(vm, vcpuid, "Calling rendezvous func");
1063 (*vm->rendezvous_func)(vm, vcpuid, vm->rendezvous_arg);
1064 CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
1066 if (CPU_CMP(&vm->rendezvous_req_cpus,
1067 &vm->rendezvous_done_cpus) == 0) {
1068 VCPU_CTR0(vm, vcpuid, "Rendezvous completed");
1069 vm_set_rendezvous_func(vm, NULL);
1070 wakeup(&vm->rendezvous_func);
1073 RENDEZVOUS_CTR0(vm, vcpuid, "Wait for rendezvous completion");
1074 mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
1077 mtx_unlock(&vm->rendezvous_mtx);
1081 * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1084 vm_handle_hlt(struct vm *vm, int vcpuid, bool intr_disabled, bool *retu)
1088 int error, t, vcpu_halted, vm_halted;
1090 KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1092 vcpu = &vm->vcpu[vcpuid];
1097 * The typical way to halt a cpu is to execute: "sti; hlt"
1099 * STI sets RFLAGS.IF to enable interrupts. However, the processor
1100 * remains in an "interrupt shadow" for an additional instruction
1101 * following the STI. This guarantees that "sti; hlt" sequence is
1102 * atomic and a pending interrupt will be recognized after the HLT.
1104 * After the HLT emulation is done the vcpu is no longer in an
1105 * interrupt shadow and a pending interrupt can be injected on
1106 * the next entry into the guest.
1108 error = vm_set_register(vm, vcpuid, VM_REG_GUEST_INTR_SHADOW, 0);
1109 KASSERT(error == 0, ("%s: error %d clearing interrupt shadow",
1115 * Do a final check for pending NMI or interrupts before
1116 * really putting this thread to sleep. Also check for
1117 * software events that would cause this vcpu to wakeup.
1119 * These interrupts/events could have happened after the
1120 * vcpu returned from VMRUN() and before it acquired the
1123 if (vm->rendezvous_func != NULL || vm->suspend)
1125 if (vm_nmi_pending(vm, vcpuid))
1127 if (!intr_disabled) {
1128 if (vm_extint_pending(vm, vcpuid) ||
1129 vlapic_pending_intr(vcpu->vlapic, NULL)) {
1134 /* Don't go to sleep if the vcpu thread needs to yield */
1135 if (vcpu_should_yield(vm, vcpuid))
1139 * Some Linux guests implement "halt" by having all vcpus
1140 * execute HLT with interrupts disabled. 'halted_cpus' keeps
1141 * track of the vcpus that have entered this state. When all
1142 * vcpus enter the halted state the virtual machine is halted.
1144 if (intr_disabled) {
1146 VCPU_CTR0(vm, vcpuid, "Halted");
1147 if (!vcpu_halted && halt_detection_enabled) {
1149 CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1151 if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1160 vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1162 * XXX msleep_spin() cannot be interrupted by signals so
1163 * wake up periodically to check pending signals.
1165 msleep_spin(vcpu, &vcpu->mtx, wmesg, hz);
1166 vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1167 vmm_stat_incr(vm, vcpuid, VCPU_IDLE_TICKS, ticks - t);
1171 CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1176 vm_suspend(vm, VM_SUSPEND_HALT);
1182 vm_handle_paging(struct vm *vm, int vcpuid, bool *retu)
1187 struct vm_exit *vme;
1189 vcpu = &vm->vcpu[vcpuid];
1190 vme = &vcpu->exitinfo;
1192 ftype = vme->u.paging.fault_type;
1193 KASSERT(ftype == VM_PROT_READ ||
1194 ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1195 ("vm_handle_paging: invalid fault_type %d", ftype));
1197 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1198 rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1199 vme->u.paging.gpa, ftype);
1204 map = &vm->vmspace->vm_map;
1205 rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL);
1207 VCPU_CTR3(vm, vcpuid, "vm_handle_paging rv = %d, gpa = %#lx, "
1208 "ftype = %d", rv, vme->u.paging.gpa, ftype);
1210 if (rv != KERN_SUCCESS)
1213 /* restart execution at the faulting instruction */
1214 vme->inst_length = 0;
1220 vm_handle_inst_emul(struct vm *vm, int vcpuid, bool *retu)
1224 struct vm_exit *vme;
1226 struct vm_guest_paging *paging;
1227 mem_region_read_t mread;
1228 mem_region_write_t mwrite;
1229 enum vm_cpu_mode cpu_mode;
1232 vcpu = &vm->vcpu[vcpuid];
1233 vme = &vcpu->exitinfo;
1235 gla = vme->u.inst_emul.gla;
1236 gpa = vme->u.inst_emul.gpa;
1237 cs_d = vme->u.inst_emul.cs_d;
1238 vie = &vme->u.inst_emul.vie;
1239 paging = &vme->u.inst_emul.paging;
1240 cpu_mode = paging->cpu_mode;
1244 /* Fetch, decode and emulate the faulting instruction */
1245 error = vmm_fetch_instruction(vm, vcpuid, paging, vme->rip,
1246 vme->inst_length, vie);
1248 return (0); /* Resume guest to handle page fault */
1249 else if (error == -1)
1251 else if (error != 0)
1252 panic("%s: vmm_fetch_instruction error %d", __func__, error);
1254 if (vmm_decode_instruction(vm, vcpuid, gla, cpu_mode, cs_d, vie) != 0)
1257 /* return to userland unless this is an in-kernel emulated device */
1258 if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1259 mread = lapic_mmio_read;
1260 mwrite = lapic_mmio_write;
1261 } else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1262 mread = vioapic_mmio_read;
1263 mwrite = vioapic_mmio_write;
1264 } else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1265 mread = vhpet_mmio_read;
1266 mwrite = vhpet_mmio_write;
1272 error = vmm_emulate_instruction(vm, vcpuid, gpa, vie, paging,
1273 mread, mwrite, retu);
1279 vm_handle_suspend(struct vm *vm, int vcpuid, bool *retu)
1285 vcpu = &vm->vcpu[vcpuid];
1287 CPU_SET_ATOMIC(vcpuid, &vm->suspended_cpus);
1290 * Wait until all 'active_cpus' have suspended themselves.
1292 * Since a VM may be suspended at any time including when one or
1293 * more vcpus are doing a rendezvous we need to call the rendezvous
1294 * handler while we are waiting to prevent a deadlock.
1298 if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1299 VCPU_CTR0(vm, vcpuid, "All vcpus suspended");
1303 if (vm->rendezvous_func == NULL) {
1304 VCPU_CTR0(vm, vcpuid, "Sleeping during suspend");
1305 vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1306 msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1307 vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1309 VCPU_CTR0(vm, vcpuid, "Rendezvous during suspend");
1311 vm_handle_rendezvous(vm, vcpuid);
1318 * Wakeup the other sleeping vcpus and return to userspace.
1320 for (i = 0; i < VM_MAXCPU; i++) {
1321 if (CPU_ISSET(i, &vm->suspended_cpus)) {
1322 vcpu_notify_event(vm, i, false);
1331 vm_suspend(struct vm *vm, enum vm_suspend_how how)
1335 if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
1338 if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
1339 VM_CTR2(vm, "virtual machine already suspended %d/%d",
1344 VM_CTR1(vm, "virtual machine successfully suspended %d", how);
1347 * Notify all active vcpus that they are now suspended.
1349 for (i = 0; i < VM_MAXCPU; i++) {
1350 if (CPU_ISSET(i, &vm->active_cpus))
1351 vcpu_notify_event(vm, i, false);
1358 vm_exit_suspended(struct vm *vm, int vcpuid, uint64_t rip)
1360 struct vm_exit *vmexit;
1362 KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
1363 ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
1365 vmexit = vm_exitinfo(vm, vcpuid);
1367 vmexit->inst_length = 0;
1368 vmexit->exitcode = VM_EXITCODE_SUSPENDED;
1369 vmexit->u.suspended.how = vm->suspend;
1373 vm_exit_rendezvous(struct vm *vm, int vcpuid, uint64_t rip)
1375 struct vm_exit *vmexit;
1377 KASSERT(vm->rendezvous_func != NULL, ("rendezvous not in progress"));
1379 vmexit = vm_exitinfo(vm, vcpuid);
1381 vmexit->inst_length = 0;
1382 vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1383 vmm_stat_incr(vm, vcpuid, VMEXIT_RENDEZVOUS, 1);
1387 vm_exit_astpending(struct vm *vm, int vcpuid, uint64_t rip)
1389 struct vm_exit *vmexit;
1391 vmexit = vm_exitinfo(vm, vcpuid);
1393 vmexit->inst_length = 0;
1394 vmexit->exitcode = VM_EXITCODE_BOGUS;
1395 vmm_stat_incr(vm, vcpuid, VMEXIT_ASTPENDING, 1);
1399 vm_run(struct vm *vm, struct vm_run *vmrun)
1404 uint64_t tscval, rip;
1405 struct vm_exit *vme;
1406 bool retu, intr_disabled;
1410 vcpuid = vmrun->cpuid;
1412 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1415 if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1418 if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1421 rptr = &vm->rendezvous_func;
1422 sptr = &vm->suspend;
1423 pmap = vmspace_pmap(vm->vmspace);
1424 vcpu = &vm->vcpu[vcpuid];
1425 vme = &vcpu->exitinfo;
1430 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1431 ("vm_run: absurd pm_active"));
1435 pcb = PCPU_GET(curpcb);
1436 set_pcb_flags(pcb, PCB_FULL_IRET);
1438 restore_guest_fpustate(vcpu);
1440 vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
1441 error = VMRUN(vm->cookie, vcpuid, rip, pmap, rptr, sptr);
1442 vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
1444 save_guest_fpustate(vcpu);
1446 vmm_stat_incr(vm, vcpuid, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1452 switch (vme->exitcode) {
1453 case VM_EXITCODE_SUSPENDED:
1454 error = vm_handle_suspend(vm, vcpuid, &retu);
1456 case VM_EXITCODE_IOAPIC_EOI:
1457 vioapic_process_eoi(vm, vcpuid,
1458 vme->u.ioapic_eoi.vector);
1460 case VM_EXITCODE_RENDEZVOUS:
1461 vm_handle_rendezvous(vm, vcpuid);
1464 case VM_EXITCODE_HLT:
1465 intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1466 error = vm_handle_hlt(vm, vcpuid, intr_disabled, &retu);
1468 case VM_EXITCODE_PAGING:
1469 error = vm_handle_paging(vm, vcpuid, &retu);
1471 case VM_EXITCODE_INST_EMUL:
1472 error = vm_handle_inst_emul(vm, vcpuid, &retu);
1474 case VM_EXITCODE_INOUT:
1475 case VM_EXITCODE_INOUT_STR:
1476 error = vm_handle_inout(vm, vcpuid, vme, &retu);
1479 retu = true; /* handled in userland */
1484 if (error == 0 && retu == false) {
1485 rip = vme->rip + vme->inst_length;
1489 /* copy the exit information */
1490 bcopy(vme, &vmrun->vm_exit, sizeof(struct vm_exit));
1495 vm_exit_intinfo(struct vm *vm, int vcpuid, uint64_t info)
1500 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1503 vcpu = &vm->vcpu[vcpuid];
1505 if (info & VM_INTINFO_VALID) {
1506 type = info & VM_INTINFO_TYPE;
1507 vector = info & 0xff;
1508 if (type == VM_INTINFO_NMI && vector != IDT_NMI)
1510 if (type == VM_INTINFO_HWEXCEPTION && vector >= 32)
1512 if (info & VM_INTINFO_RSVD)
1517 VCPU_CTR2(vm, vcpuid, "%s: info1(%#lx)", __func__, info);
1518 vcpu->exitintinfo = info;
1528 #define IDT_VE 20 /* Virtualization Exception (Intel specific) */
1530 static enum exc_class
1531 exception_class(uint64_t info)
1535 KASSERT(info & VM_INTINFO_VALID, ("intinfo must be valid: %#lx", info));
1536 type = info & VM_INTINFO_TYPE;
1537 vector = info & 0xff;
1539 /* Table 6-4, "Interrupt and Exception Classes", Intel SDM, Vol 3 */
1541 case VM_INTINFO_HWINTR:
1542 case VM_INTINFO_SWINTR:
1543 case VM_INTINFO_NMI:
1544 return (EXC_BENIGN);
1547 * Hardware exception.
1549 * SVM and VT-x use identical type values to represent NMI,
1550 * hardware interrupt and software interrupt.
1552 * SVM uses type '3' for all exceptions. VT-x uses type '3'
1553 * for exceptions except #BP and #OF. #BP and #OF use a type
1554 * value of '5' or '6'. Therefore we don't check for explicit
1555 * values of 'type' to classify 'intinfo' into a hardware
1564 return (EXC_PAGEFAULT);
1570 return (EXC_CONTRIBUTORY);
1572 return (EXC_BENIGN);
1577 nested_fault(struct vm *vm, int vcpuid, uint64_t info1, uint64_t info2,
1580 enum exc_class exc1, exc2;
1583 KASSERT(info1 & VM_INTINFO_VALID, ("info1 %#lx is not valid", info1));
1584 KASSERT(info2 & VM_INTINFO_VALID, ("info2 %#lx is not valid", info2));
1587 * If an exception occurs while attempting to call the double-fault
1588 * handler the processor enters shutdown mode (aka triple fault).
1590 type1 = info1 & VM_INTINFO_TYPE;
1591 vector1 = info1 & 0xff;
1592 if (type1 == VM_INTINFO_HWEXCEPTION && vector1 == IDT_DF) {
1593 VCPU_CTR2(vm, vcpuid, "triple fault: info1(%#lx), info2(%#lx)",
1595 vm_suspend(vm, VM_SUSPEND_TRIPLEFAULT);
1601 * Table 6-5 "Conditions for Generating a Double Fault", Intel SDM, Vol3
1603 exc1 = exception_class(info1);
1604 exc2 = exception_class(info2);
1605 if ((exc1 == EXC_CONTRIBUTORY && exc2 == EXC_CONTRIBUTORY) ||
1606 (exc1 == EXC_PAGEFAULT && exc2 != EXC_BENIGN)) {
1607 /* Convert nested fault into a double fault. */
1609 *retinfo |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1610 *retinfo |= VM_INTINFO_DEL_ERRCODE;
1612 /* Handle exceptions serially */
1619 vcpu_exception_intinfo(struct vcpu *vcpu)
1623 if (vcpu->exception_pending) {
1624 info = vcpu->exception.vector & 0xff;
1625 info |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1626 if (vcpu->exception.error_code_valid) {
1627 info |= VM_INTINFO_DEL_ERRCODE;
1628 info |= (uint64_t)vcpu->exception.error_code << 32;
1635 vm_entry_intinfo(struct vm *vm, int vcpuid, uint64_t *retinfo)
1638 uint64_t info1, info2;
1641 KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU, ("invalid vcpu %d", vcpuid));
1643 vcpu = &vm->vcpu[vcpuid];
1645 info1 = vcpu->exitintinfo;
1646 vcpu->exitintinfo = 0;
1649 if (vcpu->exception_pending) {
1650 info2 = vcpu_exception_intinfo(vcpu);
1651 vcpu->exception_pending = 0;
1652 VCPU_CTR2(vm, vcpuid, "Exception %d delivered: %#lx",
1653 vcpu->exception.vector, info2);
1656 if ((info1 & VM_INTINFO_VALID) && (info2 & VM_INTINFO_VALID)) {
1657 valid = nested_fault(vm, vcpuid, info1, info2, retinfo);
1658 } else if (info1 & VM_INTINFO_VALID) {
1661 } else if (info2 & VM_INTINFO_VALID) {
1669 VCPU_CTR4(vm, vcpuid, "%s: info1(%#lx), info2(%#lx), "
1670 "retinfo(%#lx)", __func__, info1, info2, *retinfo);
1677 vm_get_intinfo(struct vm *vm, int vcpuid, uint64_t *info1, uint64_t *info2)
1681 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1684 vcpu = &vm->vcpu[vcpuid];
1685 *info1 = vcpu->exitintinfo;
1686 *info2 = vcpu_exception_intinfo(vcpu);
1691 vm_inject_exception(struct vm *vm, int vcpuid, struct vm_exception *exception)
1695 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1698 if (exception->vector < 0 || exception->vector >= 32)
1702 * A double fault exception should never be injected directly into
1703 * the guest. It is a derived exception that results from specific
1704 * combinations of nested faults.
1706 if (exception->vector == IDT_DF)
1709 vcpu = &vm->vcpu[vcpuid];
1711 if (vcpu->exception_pending) {
1712 VCPU_CTR2(vm, vcpuid, "Unable to inject exception %d due to "
1713 "pending exception %d", exception->vector,
1714 vcpu->exception.vector);
1718 vcpu->exception_pending = 1;
1719 vcpu->exception = *exception;
1720 VCPU_CTR1(vm, vcpuid, "Exception %d pending", exception->vector);
1725 vm_inject_fault(void *vmarg, int vcpuid, int vector, int errcode_valid,
1728 struct vm_exception exception;
1729 struct vm_exit *vmexit;
1735 exception.vector = vector;
1736 exception.error_code = errcode;
1737 exception.error_code_valid = errcode_valid;
1738 error = vm_inject_exception(vm, vcpuid, &exception);
1739 KASSERT(error == 0, ("vm_inject_exception error %d", error));
1742 * A fault-like exception allows the instruction to be restarted
1743 * after the exception handler returns.
1745 * By setting the inst_length to 0 we ensure that the instruction
1746 * pointer remains at the faulting instruction.
1748 vmexit = vm_exitinfo(vm, vcpuid);
1749 vmexit->inst_length = 0;
1753 vm_inject_pf(void *vmarg, int vcpuid, int error_code, uint64_t cr2)
1759 VCPU_CTR2(vm, vcpuid, "Injecting page fault: error_code %#x, cr2 %#lx",
1762 error = vm_set_register(vm, vcpuid, VM_REG_GUEST_CR2, cr2);
1763 KASSERT(error == 0, ("vm_set_register(cr2) error %d", error));
1765 vm_inject_fault(vm, vcpuid, IDT_PF, 1, error_code);
1768 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
1771 vm_inject_nmi(struct vm *vm, int vcpuid)
1775 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1778 vcpu = &vm->vcpu[vcpuid];
1780 vcpu->nmi_pending = 1;
1781 vcpu_notify_event(vm, vcpuid, false);
1786 vm_nmi_pending(struct vm *vm, int vcpuid)
1790 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1791 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1793 vcpu = &vm->vcpu[vcpuid];
1795 return (vcpu->nmi_pending);
1799 vm_nmi_clear(struct vm *vm, int vcpuid)
1803 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1804 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1806 vcpu = &vm->vcpu[vcpuid];
1808 if (vcpu->nmi_pending == 0)
1809 panic("vm_nmi_clear: inconsistent nmi_pending state");
1811 vcpu->nmi_pending = 0;
1812 vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
1815 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
1818 vm_inject_extint(struct vm *vm, int vcpuid)
1822 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1825 vcpu = &vm->vcpu[vcpuid];
1827 vcpu->extint_pending = 1;
1828 vcpu_notify_event(vm, vcpuid, false);
1833 vm_extint_pending(struct vm *vm, int vcpuid)
1837 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1838 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1840 vcpu = &vm->vcpu[vcpuid];
1842 return (vcpu->extint_pending);
1846 vm_extint_clear(struct vm *vm, int vcpuid)
1850 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1851 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1853 vcpu = &vm->vcpu[vcpuid];
1855 if (vcpu->extint_pending == 0)
1856 panic("vm_extint_clear: inconsistent extint_pending state");
1858 vcpu->extint_pending = 0;
1859 vmm_stat_incr(vm, vcpuid, VCPU_EXTINT_COUNT, 1);
1863 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
1865 if (vcpu < 0 || vcpu >= VM_MAXCPU)
1868 if (type < 0 || type >= VM_CAP_MAX)
1871 return (VMGETCAP(vm->cookie, vcpu, type, retval));
1875 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
1877 if (vcpu < 0 || vcpu >= VM_MAXCPU)
1880 if (type < 0 || type >= VM_CAP_MAX)
1883 return (VMSETCAP(vm->cookie, vcpu, type, val));
1887 vm_lapic(struct vm *vm, int cpu)
1889 return (vm->vcpu[cpu].vlapic);
1893 vm_ioapic(struct vm *vm)
1896 return (vm->vioapic);
1900 vm_hpet(struct vm *vm)
1907 vmm_is_pptdev(int bus, int slot, int func)
1911 char *val, *cp, *cp2;
1915 * The length of an environment variable is limited to 128 bytes which
1916 * puts an upper limit on the number of passthru devices that may be
1917 * specified using a single environment variable.
1919 * Work around this by scanning multiple environment variable
1920 * names instead of a single one - yuck!
1922 const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
1924 /* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
1926 for (i = 0; names[i] != NULL && !found; i++) {
1927 cp = val = getenv(names[i]);
1928 while (cp != NULL && *cp != '\0') {
1929 if ((cp2 = strchr(cp, ' ')) != NULL)
1932 n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
1933 if (n == 3 && bus == b && slot == s && func == f) {
1949 vm_iommu_domain(struct vm *vm)
1956 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate,
1962 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1963 panic("vm_set_run_state: invalid vcpuid %d", vcpuid);
1965 vcpu = &vm->vcpu[vcpuid];
1968 error = vcpu_set_state_locked(vcpu, newstate, from_idle);
1975 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
1978 enum vcpu_state state;
1980 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1981 panic("vm_get_run_state: invalid vcpuid %d", vcpuid);
1983 vcpu = &vm->vcpu[vcpuid];
1986 state = vcpu->state;
1987 if (hostcpu != NULL)
1988 *hostcpu = vcpu->hostcpu;
1995 vm_activate_cpu(struct vm *vm, int vcpuid)
1998 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2001 if (CPU_ISSET(vcpuid, &vm->active_cpus))
2004 VCPU_CTR0(vm, vcpuid, "activated");
2005 CPU_SET_ATOMIC(vcpuid, &vm->active_cpus);
2010 vm_active_cpus(struct vm *vm)
2013 return (vm->active_cpus);
2017 vm_suspended_cpus(struct vm *vm)
2020 return (vm->suspended_cpus);
2024 vcpu_stats(struct vm *vm, int vcpuid)
2027 return (vm->vcpu[vcpuid].stats);
2031 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
2033 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2036 *state = vm->vcpu[vcpuid].x2apic_state;
2042 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
2044 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2047 if (state >= X2APIC_STATE_LAST)
2050 vm->vcpu[vcpuid].x2apic_state = state;
2052 vlapic_set_x2apic_state(vm, vcpuid, state);
2058 * This function is called to ensure that a vcpu "sees" a pending event
2059 * as soon as possible:
2060 * - If the vcpu thread is sleeping then it is woken up.
2061 * - If the vcpu is running on a different host_cpu then an IPI will be directed
2062 * to the host_cpu to cause the vcpu to trap into the hypervisor.
2065 vcpu_notify_event(struct vm *vm, int vcpuid, bool lapic_intr)
2070 vcpu = &vm->vcpu[vcpuid];
2073 hostcpu = vcpu->hostcpu;
2074 if (vcpu->state == VCPU_RUNNING) {
2075 KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
2076 if (hostcpu != curcpu) {
2078 vlapic_post_intr(vcpu->vlapic, hostcpu,
2081 ipi_cpu(hostcpu, vmm_ipinum);
2085 * If the 'vcpu' is running on 'curcpu' then it must
2086 * be sending a notification to itself (e.g. SELF_IPI).
2087 * The pending event will be picked up when the vcpu
2088 * transitions back to guest context.
2092 KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
2093 "with hostcpu %d", vcpu->state, hostcpu));
2094 if (vcpu->state == VCPU_SLEEPING)
2101 vm_get_vmspace(struct vm *vm)
2104 return (vm->vmspace);
2108 vm_apicid2vcpuid(struct vm *vm, int apicid)
2111 * XXX apic id is assumed to be numerically identical to vcpu id
2117 vm_smp_rendezvous(struct vm *vm, int vcpuid, cpuset_t dest,
2118 vm_rendezvous_func_t func, void *arg)
2123 * Enforce that this function is called without any locks
2125 WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
2126 KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
2127 ("vm_smp_rendezvous: invalid vcpuid %d", vcpuid));
2130 mtx_lock(&vm->rendezvous_mtx);
2131 if (vm->rendezvous_func != NULL) {
2133 * If a rendezvous is already in progress then we need to
2134 * call the rendezvous handler in case this 'vcpuid' is one
2135 * of the targets of the rendezvous.
2137 RENDEZVOUS_CTR0(vm, vcpuid, "Rendezvous already in progress");
2138 mtx_unlock(&vm->rendezvous_mtx);
2139 vm_handle_rendezvous(vm, vcpuid);
2142 KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
2143 "rendezvous is still in progress"));
2145 RENDEZVOUS_CTR0(vm, vcpuid, "Initiating rendezvous");
2146 vm->rendezvous_req_cpus = dest;
2147 CPU_ZERO(&vm->rendezvous_done_cpus);
2148 vm->rendezvous_arg = arg;
2149 vm_set_rendezvous_func(vm, func);
2150 mtx_unlock(&vm->rendezvous_mtx);
2153 * Wake up any sleeping vcpus and trigger a VM-exit in any running
2154 * vcpus so they handle the rendezvous as soon as possible.
2156 for (i = 0; i < VM_MAXCPU; i++) {
2157 if (CPU_ISSET(i, &dest))
2158 vcpu_notify_event(vm, i, false);
2161 vm_handle_rendezvous(vm, vcpuid);
2165 vm_atpic(struct vm *vm)
2167 return (vm->vatpic);
2171 vm_atpit(struct vm *vm)
2173 return (vm->vatpit);
2177 vm_segment_name(int seg)
2179 static enum vm_reg_name seg_names[] = {
2188 KASSERT(seg >= 0 && seg < nitems(seg_names),
2189 ("%s: invalid segment encoding %d", __func__, seg));
2190 return (seg_names[seg]);
2194 vm_copy_teardown(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo,
2199 for (idx = 0; idx < num_copyinfo; idx++) {
2200 if (copyinfo[idx].cookie != NULL)
2201 vm_gpa_release(copyinfo[idx].cookie);
2203 bzero(copyinfo, num_copyinfo * sizeof(struct vm_copyinfo));
2207 vm_copy_setup(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
2208 uint64_t gla, size_t len, int prot, struct vm_copyinfo *copyinfo,
2211 int error, idx, nused;
2212 size_t n, off, remaining;
2216 bzero(copyinfo, sizeof(struct vm_copyinfo) * num_copyinfo);
2220 while (remaining > 0) {
2221 KASSERT(nused < num_copyinfo, ("insufficient vm_copyinfo"));
2222 error = vmm_gla2gpa(vm, vcpuid, paging, gla, prot, &gpa);
2225 off = gpa & PAGE_MASK;
2226 n = min(remaining, PAGE_SIZE - off);
2227 copyinfo[nused].gpa = gpa;
2228 copyinfo[nused].len = n;
2234 for (idx = 0; idx < nused; idx++) {
2235 hva = vm_gpa_hold(vm, copyinfo[idx].gpa, copyinfo[idx].len,
2239 copyinfo[idx].hva = hva;
2240 copyinfo[idx].cookie = cookie;
2244 vm_copy_teardown(vm, vcpuid, copyinfo, num_copyinfo);
2252 vm_copyin(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo, void *kaddr,
2261 bcopy(copyinfo[idx].hva, dst, copyinfo[idx].len);
2262 len -= copyinfo[idx].len;
2263 dst += copyinfo[idx].len;
2269 vm_copyout(struct vm *vm, int vcpuid, const void *kaddr,
2270 struct vm_copyinfo *copyinfo, size_t len)
2278 bcopy(src, copyinfo[idx].hva, copyinfo[idx].len);
2279 len -= copyinfo[idx].len;
2280 src += copyinfo[idx].len;
2286 * Return the amount of in-use and wired memory for the VM. Since
2287 * these are global stats, only return the values with for vCPU 0
2289 VMM_STAT_DECLARE(VMM_MEM_RESIDENT);
2290 VMM_STAT_DECLARE(VMM_MEM_WIRED);
2293 vm_get_rescnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2297 vmm_stat_set(vm, vcpu, VMM_MEM_RESIDENT,
2298 PAGE_SIZE * vmspace_resident_count(vm->vmspace));
2303 vm_get_wiredcnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2307 vmm_stat_set(vm, vcpu, VMM_MEM_WIRED,
2308 PAGE_SIZE * pmap_wired_count(vmspace_pmap(vm->vmspace)));
2312 VMM_STAT_FUNC(VMM_MEM_RESIDENT, "Resident memory", vm_get_rescnt);
2313 VMM_STAT_FUNC(VMM_MEM_WIRED, "Wired memory", vm_get_wiredcnt);