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 int exception_pending; /* (i) exception pending */
104 int exc_vector; /* (x) exception collateral */
105 int exc_errcode_valid;
106 uint32_t exc_errcode;
107 struct savefpu *guestfpu; /* (a,i) guest fpu state */
108 uint64_t guest_xcr0; /* (i) guest %xcr0 register */
109 void *stats; /* (a,i) statistics */
110 struct vm_exit exitinfo; /* (x) exit reason and collateral */
111 uint64_t nextrip; /* (x) next instruction to execute */
114 #define vcpu_lock_initialized(v) mtx_initialized(&((v)->mtx))
115 #define vcpu_lock_init(v) mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
116 #define vcpu_lock(v) mtx_lock_spin(&((v)->mtx))
117 #define vcpu_unlock(v) mtx_unlock_spin(&((v)->mtx))
118 #define vcpu_assert_locked(v) mtx_assert(&((v)->mtx), MA_OWNED)
126 #define VM_MAX_MEMORY_SEGMENTS 2
130 * (o) initialized the first time the VM is created
131 * (i) initialized when VM is created and when it is reinitialized
132 * (x) initialized before use
135 void *cookie; /* (i) cpu-specific data */
136 void *iommu; /* (x) iommu-specific data */
137 struct vhpet *vhpet; /* (i) virtual HPET */
138 struct vioapic *vioapic; /* (i) virtual ioapic */
139 struct vatpic *vatpic; /* (i) virtual atpic */
140 struct vatpit *vatpit; /* (i) virtual atpit */
141 struct vpmtmr *vpmtmr; /* (i) virtual ACPI PM timer */
142 struct vrtc *vrtc; /* (o) virtual RTC */
143 volatile cpuset_t active_cpus; /* (i) active vcpus */
144 int suspend; /* (i) stop VM execution */
145 volatile cpuset_t suspended_cpus; /* (i) suspended vcpus */
146 volatile cpuset_t halted_cpus; /* (x) cpus in a hard halt */
147 cpuset_t rendezvous_req_cpus; /* (x) rendezvous requested */
148 cpuset_t rendezvous_done_cpus; /* (x) rendezvous finished */
149 void *rendezvous_arg; /* (x) rendezvous func/arg */
150 vm_rendezvous_func_t rendezvous_func;
151 struct mtx rendezvous_mtx; /* (o) rendezvous lock */
152 int num_mem_segs; /* (o) guest memory segments */
153 struct mem_seg mem_segs[VM_MAX_MEMORY_SEGMENTS];
154 struct vmspace *vmspace; /* (o) guest's address space */
155 char name[VM_MAX_NAMELEN]; /* (o) virtual machine name */
156 struct vcpu vcpu[VM_MAXCPU]; /* (i) guest vcpus */
159 static int vmm_initialized;
161 static struct vmm_ops *ops;
162 #define VMM_INIT(num) (ops != NULL ? (*ops->init)(num) : 0)
163 #define VMM_CLEANUP() (ops != NULL ? (*ops->cleanup)() : 0)
164 #define VMM_RESUME() (ops != NULL ? (*ops->resume)() : 0)
166 #define VMINIT(vm, pmap) (ops != NULL ? (*ops->vminit)(vm, pmap): NULL)
167 #define VMRUN(vmi, vcpu, rip, pmap, rptr, sptr) \
168 (ops != NULL ? (*ops->vmrun)(vmi, vcpu, rip, pmap, rptr, sptr) : ENXIO)
169 #define VMCLEANUP(vmi) (ops != NULL ? (*ops->vmcleanup)(vmi) : NULL)
170 #define VMSPACE_ALLOC(min, max) \
171 (ops != NULL ? (*ops->vmspace_alloc)(min, max) : NULL)
172 #define VMSPACE_FREE(vmspace) \
173 (ops != NULL ? (*ops->vmspace_free)(vmspace) : ENXIO)
174 #define VMGETREG(vmi, vcpu, num, retval) \
175 (ops != NULL ? (*ops->vmgetreg)(vmi, vcpu, num, retval) : ENXIO)
176 #define VMSETREG(vmi, vcpu, num, val) \
177 (ops != NULL ? (*ops->vmsetreg)(vmi, vcpu, num, val) : ENXIO)
178 #define VMGETDESC(vmi, vcpu, num, desc) \
179 (ops != NULL ? (*ops->vmgetdesc)(vmi, vcpu, num, desc) : ENXIO)
180 #define VMSETDESC(vmi, vcpu, num, desc) \
181 (ops != NULL ? (*ops->vmsetdesc)(vmi, vcpu, num, desc) : ENXIO)
182 #define VMGETCAP(vmi, vcpu, num, retval) \
183 (ops != NULL ? (*ops->vmgetcap)(vmi, vcpu, num, retval) : ENXIO)
184 #define VMSETCAP(vmi, vcpu, num, val) \
185 (ops != NULL ? (*ops->vmsetcap)(vmi, vcpu, num, val) : ENXIO)
186 #define VLAPIC_INIT(vmi, vcpu) \
187 (ops != NULL ? (*ops->vlapic_init)(vmi, vcpu) : NULL)
188 #define VLAPIC_CLEANUP(vmi, vlapic) \
189 (ops != NULL ? (*ops->vlapic_cleanup)(vmi, vlapic) : NULL)
191 #define fpu_start_emulating() load_cr0(rcr0() | CR0_TS)
192 #define fpu_stop_emulating() clts()
194 static MALLOC_DEFINE(M_VM, "vm", "vm");
197 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
199 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW, NULL, NULL);
202 * Halt the guest if all vcpus are executing a HLT instruction with
203 * interrupts disabled.
205 static int halt_detection_enabled = 1;
206 SYSCTL_INT(_hw_vmm, OID_AUTO, halt_detection, CTLFLAG_RDTUN,
207 &halt_detection_enabled, 0,
208 "Halt VM if all vcpus execute HLT with interrupts disabled");
210 static int vmm_ipinum;
211 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
212 "IPI vector used for vcpu notifications");
214 static int trace_guest_exceptions;
215 SYSCTL_INT(_hw_vmm, OID_AUTO, trace_guest_exceptions, CTLFLAG_RDTUN,
216 &trace_guest_exceptions, 0,
217 "Trap into hypervisor on all guest exceptions and reflect them back");
219 static int vmm_force_iommu = 0;
220 TUNABLE_INT("hw.vmm.force_iommu", &vmm_force_iommu);
221 SYSCTL_INT(_hw_vmm, OID_AUTO, force_iommu, CTLFLAG_RDTUN, &vmm_force_iommu, 0,
222 "Force use of I/O MMU even if no passthrough devices were found.");
225 vcpu_cleanup(struct vm *vm, int i, bool destroy)
227 struct vcpu *vcpu = &vm->vcpu[i];
229 VLAPIC_CLEANUP(vm->cookie, vcpu->vlapic);
231 vmm_stat_free(vcpu->stats);
232 fpu_save_area_free(vcpu->guestfpu);
237 vcpu_init(struct vm *vm, int vcpu_id, bool create)
241 KASSERT(vcpu_id >= 0 && vcpu_id < VM_MAXCPU,
242 ("vcpu_init: invalid vcpu %d", vcpu_id));
244 vcpu = &vm->vcpu[vcpu_id];
247 KASSERT(!vcpu_lock_initialized(vcpu), ("vcpu %d already "
248 "initialized", vcpu_id));
249 vcpu_lock_init(vcpu);
250 vcpu->state = VCPU_IDLE;
251 vcpu->hostcpu = NOCPU;
252 vcpu->guestfpu = fpu_save_area_alloc();
253 vcpu->stats = vmm_stat_alloc();
256 vcpu->vlapic = VLAPIC_INIT(vm->cookie, vcpu_id);
257 vm_set_x2apic_state(vm, vcpu_id, X2APIC_DISABLED);
258 vcpu->exitintinfo = 0;
259 vcpu->nmi_pending = 0;
260 vcpu->extint_pending = 0;
261 vcpu->exception_pending = 0;
262 vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
263 fpu_save_area_reset(vcpu->guestfpu);
264 vmm_stat_init(vcpu->stats);
268 vcpu_trace_exceptions(struct vm *vm, int vcpuid)
271 return (trace_guest_exceptions);
275 vm_exitinfo(struct vm *vm, int cpuid)
279 if (cpuid < 0 || cpuid >= VM_MAXCPU)
280 panic("vm_exitinfo: invalid cpuid %d", cpuid);
282 vcpu = &vm->vcpu[cpuid];
284 return (&vcpu->exitinfo);
298 vmm_host_state_init();
300 vmm_ipinum = lapic_ipi_alloc(&IDTVEC(justreturn));
302 vmm_ipinum = IPI_AST;
304 error = vmm_mem_init();
309 ops = &vmm_ops_intel;
310 else if (vmm_is_amd())
315 vmm_resume_p = vmm_resume;
317 return (VMM_INIT(vmm_ipinum));
321 vmm_handler(module_t mod, int what, void *arg)
328 if (vmm_force_iommu || ppt_avail_devices() > 0)
335 error = vmmdev_cleanup();
339 if (vmm_ipinum != IPI_AST)
340 lapic_ipi_free(vmm_ipinum);
341 error = VMM_CLEANUP();
343 * Something bad happened - prevent new
344 * VMs from being created
357 static moduledata_t vmm_kmod = {
364 * vmm initialization has the following dependencies:
366 * - iommu initialization must happen after the pci passthru driver has had
367 * a chance to attach to any passthru devices (after SI_SUB_CONFIGURE).
369 * - VT-x initialization requires smp_rendezvous() and therefore must happen
370 * after SMP is fully functional (after SI_SUB_SMP).
372 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
373 MODULE_VERSION(vmm, 1);
376 vm_init(struct vm *vm, bool create)
380 vm->cookie = VMINIT(vm, vmspace_pmap(vm->vmspace));
382 vm->vioapic = vioapic_init(vm);
383 vm->vhpet = vhpet_init(vm);
384 vm->vatpic = vatpic_init(vm);
385 vm->vatpit = vatpit_init(vm);
386 vm->vpmtmr = vpmtmr_init(vm);
388 vm->vrtc = vrtc_init(vm);
390 CPU_ZERO(&vm->active_cpus);
393 CPU_ZERO(&vm->suspended_cpus);
395 for (i = 0; i < VM_MAXCPU; i++)
396 vcpu_init(vm, i, create);
400 vm_create(const char *name, struct vm **retvm)
403 struct vmspace *vmspace;
406 * If vmm.ko could not be successfully initialized then don't attempt
407 * to create the virtual machine.
409 if (!vmm_initialized)
412 if (name == NULL || strlen(name) >= VM_MAX_NAMELEN)
415 vmspace = VMSPACE_ALLOC(0, VM_MAXUSER_ADDRESS);
419 vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
420 strcpy(vm->name, name);
421 vm->num_mem_segs = 0;
422 vm->vmspace = vmspace;
423 mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
432 vm_free_mem_seg(struct vm *vm, struct mem_seg *seg)
435 if (seg->object != NULL)
436 vmm_mem_free(vm->vmspace, seg->gpa, seg->len);
438 bzero(seg, sizeof(*seg));
442 vm_cleanup(struct vm *vm, bool destroy)
446 ppt_unassign_all(vm);
448 if (vm->iommu != NULL)
449 iommu_destroy_domain(vm->iommu);
452 vrtc_cleanup(vm->vrtc);
454 vrtc_reset(vm->vrtc);
455 vpmtmr_cleanup(vm->vpmtmr);
456 vatpit_cleanup(vm->vatpit);
457 vhpet_cleanup(vm->vhpet);
458 vatpic_cleanup(vm->vatpic);
459 vioapic_cleanup(vm->vioapic);
461 for (i = 0; i < VM_MAXCPU; i++)
462 vcpu_cleanup(vm, i, destroy);
464 VMCLEANUP(vm->cookie);
467 for (i = 0; i < vm->num_mem_segs; i++)
468 vm_free_mem_seg(vm, &vm->mem_segs[i]);
470 vm->num_mem_segs = 0;
472 VMSPACE_FREE(vm->vmspace);
478 vm_destroy(struct vm *vm)
480 vm_cleanup(vm, true);
485 vm_reinit(struct vm *vm)
490 * A virtual machine can be reset only if all vcpus are suspended.
492 if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
493 vm_cleanup(vm, false);
504 vm_name(struct vm *vm)
510 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
514 if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
521 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
524 vmm_mmio_free(vm->vmspace, gpa, len);
529 vm_mem_allocated(struct vm *vm, vm_paddr_t gpa)
532 vm_paddr_t gpabase, gpalimit;
534 for (i = 0; i < vm->num_mem_segs; i++) {
535 gpabase = vm->mem_segs[i].gpa;
536 gpalimit = gpabase + vm->mem_segs[i].len;
537 if (gpa >= gpabase && gpa < gpalimit)
538 return (TRUE); /* 'gpa' is regular memory */
541 if (ppt_is_mmio(vm, gpa))
542 return (TRUE); /* 'gpa' is pci passthru mmio */
548 vm_malloc(struct vm *vm, vm_paddr_t gpa, size_t len)
550 int available, allocated;
555 if ((gpa & PAGE_MASK) || (len & PAGE_MASK) || len == 0)
558 available = allocated = 0;
560 while (g < gpa + len) {
561 if (vm_mem_allocated(vm, g))
570 * If there are some allocated and some available pages in the address
571 * range then it is an error.
573 if (allocated && available)
577 * If the entire address range being requested has already been
578 * allocated then there isn't anything more to do.
580 if (allocated && available == 0)
583 if (vm->num_mem_segs >= VM_MAX_MEMORY_SEGMENTS)
586 seg = &vm->mem_segs[vm->num_mem_segs];
588 if ((object = vmm_mem_alloc(vm->vmspace, gpa, len)) == NULL)
593 seg->object = object;
602 vm_maxmem(struct vm *vm)
605 vm_paddr_t gpa, maxmem;
608 for (i = 0; i < vm->num_mem_segs; i++) {
609 gpa = vm->mem_segs[i].gpa + vm->mem_segs[i].len;
617 vm_gpa_unwire(struct vm *vm)
622 for (i = 0; i < vm->num_mem_segs; i++) {
623 seg = &vm->mem_segs[i];
627 rv = vm_map_unwire(&vm->vmspace->vm_map,
628 seg->gpa, seg->gpa + seg->len,
629 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
630 KASSERT(rv == KERN_SUCCESS, ("vm(%s) memory segment "
631 "%#lx/%ld could not be unwired: %d",
632 vm_name(vm), seg->gpa, seg->len, rv));
639 vm_gpa_wire(struct vm *vm)
644 for (i = 0; i < vm->num_mem_segs; i++) {
645 seg = &vm->mem_segs[i];
650 rv = vm_map_wire(&vm->vmspace->vm_map,
651 seg->gpa, seg->gpa + seg->len,
652 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
653 if (rv != KERN_SUCCESS)
659 if (i < vm->num_mem_segs) {
661 * Undo the wiring before returning an error.
671 vm_iommu_modify(struct vm *vm, boolean_t map)
676 void *vp, *cookie, *host_domain;
679 host_domain = iommu_host_domain();
681 for (i = 0; i < vm->num_mem_segs; i++) {
682 seg = &vm->mem_segs[i];
683 KASSERT(seg->wired, ("vm(%s) memory segment %#lx/%ld not wired",
684 vm_name(vm), seg->gpa, seg->len));
687 while (gpa < seg->gpa + seg->len) {
688 vp = vm_gpa_hold(vm, gpa, PAGE_SIZE, VM_PROT_WRITE,
690 KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
693 vm_gpa_release(cookie);
695 hpa = DMAP_TO_PHYS((uintptr_t)vp);
697 iommu_create_mapping(vm->iommu, gpa, hpa, sz);
698 iommu_remove_mapping(host_domain, hpa, sz);
700 iommu_remove_mapping(vm->iommu, gpa, sz);
701 iommu_create_mapping(host_domain, hpa, hpa, sz);
709 * Invalidate the cached translations associated with the domain
710 * from which pages were removed.
713 iommu_invalidate_tlb(host_domain);
715 iommu_invalidate_tlb(vm->iommu);
718 #define vm_iommu_unmap(vm) vm_iommu_modify((vm), FALSE)
719 #define vm_iommu_map(vm) vm_iommu_modify((vm), TRUE)
722 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
726 error = ppt_unassign_device(vm, bus, slot, func);
730 if (ppt_assigned_devices(vm) == 0) {
738 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
744 * Virtual machines with pci passthru devices get special treatment:
745 * - the guest physical memory is wired
746 * - the iommu is programmed to do the 'gpa' to 'hpa' translation
748 * We need to do this before the first pci passthru device is attached.
750 if (ppt_assigned_devices(vm) == 0) {
751 KASSERT(vm->iommu == NULL,
752 ("vm_assign_pptdev: iommu must be NULL"));
753 maxaddr = vm_maxmem(vm);
754 vm->iommu = iommu_create_domain(maxaddr);
756 error = vm_gpa_wire(vm);
763 error = ppt_assign_device(vm, bus, slot, func);
768 vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
774 pageoff = gpa & PAGE_MASK;
775 if (len > PAGE_SIZE - pageoff)
776 panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
778 count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
779 trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
783 return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
791 vm_gpa_release(void *cookie)
793 vm_page_t m = cookie;
801 vm_gpabase2memseg(struct vm *vm, vm_paddr_t gpabase,
802 struct vm_memory_segment *seg)
806 for (i = 0; i < vm->num_mem_segs; i++) {
807 if (gpabase == vm->mem_segs[i].gpa) {
808 seg->gpa = vm->mem_segs[i].gpa;
809 seg->len = vm->mem_segs[i].len;
810 seg->wired = vm->mem_segs[i].wired;
818 vm_get_memobj(struct vm *vm, vm_paddr_t gpa, size_t len,
819 vm_offset_t *offset, struct vm_object **object)
826 for (i = 0; i < vm->num_mem_segs; i++) {
827 if ((seg_obj = vm->mem_segs[i].object) == NULL)
830 seg_gpa = vm->mem_segs[i].gpa;
831 seg_len = vm->mem_segs[i].len;
833 if (gpa >= seg_gpa && gpa < seg_gpa + seg_len) {
834 *offset = gpa - seg_gpa;
836 vm_object_reference(seg_obj);
845 vm_get_register(struct vm *vm, int vcpu, int reg, uint64_t *retval)
848 if (vcpu < 0 || vcpu >= VM_MAXCPU)
851 if (reg >= VM_REG_LAST)
854 return (VMGETREG(vm->cookie, vcpu, reg, retval));
858 vm_set_register(struct vm *vm, int vcpuid, int reg, uint64_t val)
863 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
866 if (reg >= VM_REG_LAST)
869 error = VMSETREG(vm->cookie, vcpuid, reg, val);
870 if (error || reg != VM_REG_GUEST_RIP)
873 /* Set 'nextrip' to match the value of %rip */
874 VCPU_CTR1(vm, vcpuid, "Setting nextrip to %#lx", val);
875 vcpu = &vm->vcpu[vcpuid];
881 is_descriptor_table(int reg)
885 case VM_REG_GUEST_IDTR:
886 case VM_REG_GUEST_GDTR:
894 is_segment_register(int reg)
898 case VM_REG_GUEST_ES:
899 case VM_REG_GUEST_CS:
900 case VM_REG_GUEST_SS:
901 case VM_REG_GUEST_DS:
902 case VM_REG_GUEST_FS:
903 case VM_REG_GUEST_GS:
904 case VM_REG_GUEST_TR:
905 case VM_REG_GUEST_LDTR:
913 vm_get_seg_desc(struct vm *vm, int vcpu, int reg,
914 struct seg_desc *desc)
917 if (vcpu < 0 || vcpu >= VM_MAXCPU)
920 if (!is_segment_register(reg) && !is_descriptor_table(reg))
923 return (VMGETDESC(vm->cookie, vcpu, reg, desc));
927 vm_set_seg_desc(struct vm *vm, int vcpu, int reg,
928 struct seg_desc *desc)
930 if (vcpu < 0 || vcpu >= VM_MAXCPU)
933 if (!is_segment_register(reg) && !is_descriptor_table(reg))
936 return (VMSETDESC(vm->cookie, vcpu, reg, desc));
940 restore_guest_fpustate(struct vcpu *vcpu)
943 /* flush host state to the pcb */
946 /* restore guest FPU state */
947 fpu_stop_emulating();
948 fpurestore(vcpu->guestfpu);
950 /* restore guest XCR0 if XSAVE is enabled in the host */
951 if (rcr4() & CR4_XSAVE)
952 load_xcr(0, vcpu->guest_xcr0);
955 * The FPU is now "dirty" with the guest's state so turn on emulation
956 * to trap any access to the FPU by the host.
958 fpu_start_emulating();
962 save_guest_fpustate(struct vcpu *vcpu)
965 if ((rcr0() & CR0_TS) == 0)
966 panic("fpu emulation not enabled in host!");
968 /* save guest XCR0 and restore host XCR0 */
969 if (rcr4() & CR4_XSAVE) {
970 vcpu->guest_xcr0 = rxcr(0);
971 load_xcr(0, vmm_get_host_xcr0());
974 /* save guest FPU state */
975 fpu_stop_emulating();
976 fpusave(vcpu->guestfpu);
977 fpu_start_emulating();
980 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
983 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate,
988 vcpu_assert_locked(vcpu);
991 * State transitions from the vmmdev_ioctl() must always begin from
992 * the VCPU_IDLE state. This guarantees that there is only a single
993 * ioctl() operating on a vcpu at any point.
996 while (vcpu->state != VCPU_IDLE)
997 msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
999 KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
1000 "vcpu idle state"));
1003 if (vcpu->state == VCPU_RUNNING) {
1004 KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
1005 "mismatch for running vcpu", curcpu, vcpu->hostcpu));
1007 KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
1008 "vcpu that is not running", vcpu->hostcpu));
1012 * The following state transitions are allowed:
1013 * IDLE -> FROZEN -> IDLE
1014 * FROZEN -> RUNNING -> FROZEN
1015 * FROZEN -> SLEEPING -> FROZEN
1017 switch (vcpu->state) {
1021 error = (newstate != VCPU_FROZEN);
1024 error = (newstate == VCPU_FROZEN);
1034 vcpu->state = newstate;
1035 if (newstate == VCPU_RUNNING)
1036 vcpu->hostcpu = curcpu;
1038 vcpu->hostcpu = NOCPU;
1040 if (newstate == VCPU_IDLE)
1041 wakeup(&vcpu->state);
1047 vcpu_require_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
1051 if ((error = vcpu_set_state(vm, vcpuid, newstate, false)) != 0)
1052 panic("Error %d setting state to %d\n", error, newstate);
1056 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
1060 if ((error = vcpu_set_state_locked(vcpu, newstate, false)) != 0)
1061 panic("Error %d setting state to %d", error, newstate);
1065 vm_set_rendezvous_func(struct vm *vm, vm_rendezvous_func_t func)
1068 KASSERT(mtx_owned(&vm->rendezvous_mtx), ("rendezvous_mtx not locked"));
1071 * Update 'rendezvous_func' and execute a write memory barrier to
1072 * ensure that it is visible across all host cpus. This is not needed
1073 * for correctness but it does ensure that all the vcpus will notice
1074 * that the rendezvous is requested immediately.
1076 vm->rendezvous_func = func;
1080 #define RENDEZVOUS_CTR0(vm, vcpuid, fmt) \
1083 VCPU_CTR0(vm, vcpuid, fmt); \
1089 vm_handle_rendezvous(struct vm *vm, int vcpuid)
1092 KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
1093 ("vm_handle_rendezvous: invalid vcpuid %d", vcpuid));
1095 mtx_lock(&vm->rendezvous_mtx);
1096 while (vm->rendezvous_func != NULL) {
1097 /* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
1098 CPU_AND(&vm->rendezvous_req_cpus, &vm->active_cpus);
1101 CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
1102 !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
1103 VCPU_CTR0(vm, vcpuid, "Calling rendezvous func");
1104 (*vm->rendezvous_func)(vm, vcpuid, vm->rendezvous_arg);
1105 CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
1107 if (CPU_CMP(&vm->rendezvous_req_cpus,
1108 &vm->rendezvous_done_cpus) == 0) {
1109 VCPU_CTR0(vm, vcpuid, "Rendezvous completed");
1110 vm_set_rendezvous_func(vm, NULL);
1111 wakeup(&vm->rendezvous_func);
1114 RENDEZVOUS_CTR0(vm, vcpuid, "Wait for rendezvous completion");
1115 mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
1118 mtx_unlock(&vm->rendezvous_mtx);
1122 * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1125 vm_handle_hlt(struct vm *vm, int vcpuid, bool intr_disabled, bool *retu)
1129 int t, vcpu_halted, vm_halted;
1131 KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1133 vcpu = &vm->vcpu[vcpuid];
1140 * Do a final check for pending NMI or interrupts before
1141 * really putting this thread to sleep. Also check for
1142 * software events that would cause this vcpu to wakeup.
1144 * These interrupts/events could have happened after the
1145 * vcpu returned from VMRUN() and before it acquired the
1148 if (vm->rendezvous_func != NULL || vm->suspend)
1150 if (vm_nmi_pending(vm, vcpuid))
1152 if (!intr_disabled) {
1153 if (vm_extint_pending(vm, vcpuid) ||
1154 vlapic_pending_intr(vcpu->vlapic, NULL)) {
1159 /* Don't go to sleep if the vcpu thread needs to yield */
1160 if (vcpu_should_yield(vm, vcpuid))
1164 * Some Linux guests implement "halt" by having all vcpus
1165 * execute HLT with interrupts disabled. 'halted_cpus' keeps
1166 * track of the vcpus that have entered this state. When all
1167 * vcpus enter the halted state the virtual machine is halted.
1169 if (intr_disabled) {
1171 VCPU_CTR0(vm, vcpuid, "Halted");
1172 if (!vcpu_halted && halt_detection_enabled) {
1174 CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1176 if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1185 vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1187 * XXX msleep_spin() cannot be interrupted by signals so
1188 * wake up periodically to check pending signals.
1190 msleep_spin(vcpu, &vcpu->mtx, wmesg, hz);
1191 vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1192 vmm_stat_incr(vm, vcpuid, VCPU_IDLE_TICKS, ticks - t);
1196 CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1201 vm_suspend(vm, VM_SUSPEND_HALT);
1207 vm_handle_paging(struct vm *vm, int vcpuid, bool *retu)
1212 struct vm_exit *vme;
1214 vcpu = &vm->vcpu[vcpuid];
1215 vme = &vcpu->exitinfo;
1217 KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1218 __func__, vme->inst_length));
1220 ftype = vme->u.paging.fault_type;
1221 KASSERT(ftype == VM_PROT_READ ||
1222 ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1223 ("vm_handle_paging: invalid fault_type %d", ftype));
1225 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1226 rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1227 vme->u.paging.gpa, ftype);
1229 VCPU_CTR2(vm, vcpuid, "%s bit emulation for gpa %#lx",
1230 ftype == VM_PROT_READ ? "accessed" : "dirty",
1236 map = &vm->vmspace->vm_map;
1237 rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL);
1239 VCPU_CTR3(vm, vcpuid, "vm_handle_paging rv = %d, gpa = %#lx, "
1240 "ftype = %d", rv, vme->u.paging.gpa, ftype);
1242 if (rv != KERN_SUCCESS)
1249 vm_handle_inst_emul(struct vm *vm, int vcpuid, bool *retu)
1253 struct vm_exit *vme;
1254 uint64_t gla, gpa, cs_base;
1255 struct vm_guest_paging *paging;
1256 mem_region_read_t mread;
1257 mem_region_write_t mwrite;
1258 enum vm_cpu_mode cpu_mode;
1259 int cs_d, error, length;
1261 vcpu = &vm->vcpu[vcpuid];
1262 vme = &vcpu->exitinfo;
1264 gla = vme->u.inst_emul.gla;
1265 gpa = vme->u.inst_emul.gpa;
1266 cs_base = vme->u.inst_emul.cs_base;
1267 cs_d = vme->u.inst_emul.cs_d;
1268 vie = &vme->u.inst_emul.vie;
1269 paging = &vme->u.inst_emul.paging;
1270 cpu_mode = paging->cpu_mode;
1272 VCPU_CTR1(vm, vcpuid, "inst_emul fault accessing gpa %#lx", gpa);
1274 /* Fetch, decode and emulate the faulting instruction */
1275 if (vie->num_valid == 0) {
1277 * If the instruction length is not known then assume a
1278 * maximum size instruction.
1280 length = vme->inst_length ? vme->inst_length : VIE_INST_SIZE;
1281 error = vmm_fetch_instruction(vm, vcpuid, paging, vme->rip +
1282 cs_base, length, vie);
1285 * The instruction bytes have already been copied into 'vie'
1290 return (0); /* Resume guest to handle page fault */
1291 else if (error == -1)
1293 else if (error != 0)
1294 panic("%s: vmm_fetch_instruction error %d", __func__, error);
1296 if (vmm_decode_instruction(vm, vcpuid, gla, cpu_mode, cs_d, vie) != 0) {
1297 VCPU_CTR1(vm, vcpuid, "Error decoding instruction at %#lx",
1298 vme->rip + cs_base);
1299 *retu = true; /* dump instruction bytes in userspace */
1304 * If the instruction length was not specified then update it now
1305 * along with 'nextrip'.
1307 if (vme->inst_length == 0) {
1308 vme->inst_length = vie->num_processed;
1309 vcpu->nextrip += vie->num_processed;
1312 /* return to userland unless this is an in-kernel emulated device */
1313 if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1314 mread = lapic_mmio_read;
1315 mwrite = lapic_mmio_write;
1316 } else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1317 mread = vioapic_mmio_read;
1318 mwrite = vioapic_mmio_write;
1319 } else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1320 mread = vhpet_mmio_read;
1321 mwrite = vhpet_mmio_write;
1327 error = vmm_emulate_instruction(vm, vcpuid, gpa, vie, paging,
1328 mread, mwrite, retu);
1334 vm_handle_suspend(struct vm *vm, int vcpuid, bool *retu)
1340 vcpu = &vm->vcpu[vcpuid];
1342 CPU_SET_ATOMIC(vcpuid, &vm->suspended_cpus);
1345 * Wait until all 'active_cpus' have suspended themselves.
1347 * Since a VM may be suspended at any time including when one or
1348 * more vcpus are doing a rendezvous we need to call the rendezvous
1349 * handler while we are waiting to prevent a deadlock.
1353 if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1354 VCPU_CTR0(vm, vcpuid, "All vcpus suspended");
1358 if (vm->rendezvous_func == NULL) {
1359 VCPU_CTR0(vm, vcpuid, "Sleeping during suspend");
1360 vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1361 msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1362 vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1364 VCPU_CTR0(vm, vcpuid, "Rendezvous during suspend");
1366 vm_handle_rendezvous(vm, vcpuid);
1373 * Wakeup the other sleeping vcpus and return to userspace.
1375 for (i = 0; i < VM_MAXCPU; i++) {
1376 if (CPU_ISSET(i, &vm->suspended_cpus)) {
1377 vcpu_notify_event(vm, i, false);
1386 vm_suspend(struct vm *vm, enum vm_suspend_how how)
1390 if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
1393 if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
1394 VM_CTR2(vm, "virtual machine already suspended %d/%d",
1399 VM_CTR1(vm, "virtual machine successfully suspended %d", how);
1402 * Notify all active vcpus that they are now suspended.
1404 for (i = 0; i < VM_MAXCPU; i++) {
1405 if (CPU_ISSET(i, &vm->active_cpus))
1406 vcpu_notify_event(vm, i, false);
1413 vm_exit_suspended(struct vm *vm, int vcpuid, uint64_t rip)
1415 struct vm_exit *vmexit;
1417 KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
1418 ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
1420 vmexit = vm_exitinfo(vm, vcpuid);
1422 vmexit->inst_length = 0;
1423 vmexit->exitcode = VM_EXITCODE_SUSPENDED;
1424 vmexit->u.suspended.how = vm->suspend;
1428 vm_exit_rendezvous(struct vm *vm, int vcpuid, uint64_t rip)
1430 struct vm_exit *vmexit;
1432 KASSERT(vm->rendezvous_func != NULL, ("rendezvous not in progress"));
1434 vmexit = vm_exitinfo(vm, vcpuid);
1436 vmexit->inst_length = 0;
1437 vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1438 vmm_stat_incr(vm, vcpuid, VMEXIT_RENDEZVOUS, 1);
1442 vm_exit_astpending(struct vm *vm, int vcpuid, uint64_t rip)
1444 struct vm_exit *vmexit;
1446 vmexit = vm_exitinfo(vm, vcpuid);
1448 vmexit->inst_length = 0;
1449 vmexit->exitcode = VM_EXITCODE_BOGUS;
1450 vmm_stat_incr(vm, vcpuid, VMEXIT_ASTPENDING, 1);
1454 vm_run(struct vm *vm, struct vm_run *vmrun)
1460 struct vm_exit *vme;
1461 bool retu, intr_disabled;
1465 vcpuid = vmrun->cpuid;
1467 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1470 if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1473 if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1476 rptr = &vm->rendezvous_func;
1477 sptr = &vm->suspend;
1478 pmap = vmspace_pmap(vm->vmspace);
1479 vcpu = &vm->vcpu[vcpuid];
1480 vme = &vcpu->exitinfo;
1484 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1485 ("vm_run: absurd pm_active"));
1489 pcb = PCPU_GET(curpcb);
1490 set_pcb_flags(pcb, PCB_FULL_IRET);
1492 restore_guest_fpustate(vcpu);
1494 vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
1495 error = VMRUN(vm->cookie, vcpuid, vcpu->nextrip, pmap, rptr, sptr);
1496 vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
1498 save_guest_fpustate(vcpu);
1500 vmm_stat_incr(vm, vcpuid, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1506 vcpu->nextrip = vme->rip + vme->inst_length;
1507 switch (vme->exitcode) {
1508 case VM_EXITCODE_SUSPENDED:
1509 error = vm_handle_suspend(vm, vcpuid, &retu);
1511 case VM_EXITCODE_IOAPIC_EOI:
1512 vioapic_process_eoi(vm, vcpuid,
1513 vme->u.ioapic_eoi.vector);
1515 case VM_EXITCODE_RENDEZVOUS:
1516 vm_handle_rendezvous(vm, vcpuid);
1519 case VM_EXITCODE_HLT:
1520 intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1521 error = vm_handle_hlt(vm, vcpuid, intr_disabled, &retu);
1523 case VM_EXITCODE_PAGING:
1524 error = vm_handle_paging(vm, vcpuid, &retu);
1526 case VM_EXITCODE_INST_EMUL:
1527 error = vm_handle_inst_emul(vm, vcpuid, &retu);
1529 case VM_EXITCODE_INOUT:
1530 case VM_EXITCODE_INOUT_STR:
1531 error = vm_handle_inout(vm, vcpuid, vme, &retu);
1533 case VM_EXITCODE_MONITOR:
1534 case VM_EXITCODE_MWAIT:
1535 vm_inject_ud(vm, vcpuid);
1538 retu = true; /* handled in userland */
1543 if (error == 0 && retu == false)
1546 /* copy the exit information */
1547 bcopy(vme, &vmrun->vm_exit, sizeof(struct vm_exit));
1552 vm_restart_instruction(void *arg, int vcpuid)
1556 enum vcpu_state state;
1561 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1564 vcpu = &vm->vcpu[vcpuid];
1565 state = vcpu_get_state(vm, vcpuid, NULL);
1566 if (state == VCPU_RUNNING) {
1568 * When a vcpu is "running" the next instruction is determined
1569 * by adding 'rip' and 'inst_length' in the vcpu's 'exitinfo'.
1570 * Thus setting 'inst_length' to zero will cause the current
1571 * instruction to be restarted.
1573 vcpu->exitinfo.inst_length = 0;
1574 VCPU_CTR1(vm, vcpuid, "restarting instruction at %#lx by "
1575 "setting inst_length to zero", vcpu->exitinfo.rip);
1576 } else if (state == VCPU_FROZEN) {
1578 * When a vcpu is "frozen" it is outside the critical section
1579 * around VMRUN() and 'nextrip' points to the next instruction.
1580 * Thus instruction restart is achieved by setting 'nextrip'
1581 * to the vcpu's %rip.
1583 error = vm_get_register(vm, vcpuid, VM_REG_GUEST_RIP, &rip);
1584 KASSERT(!error, ("%s: error %d getting rip", __func__, error));
1585 VCPU_CTR2(vm, vcpuid, "restarting instruction by updating "
1586 "nextrip from %#lx to %#lx", vcpu->nextrip, rip);
1587 vcpu->nextrip = rip;
1589 panic("%s: invalid state %d", __func__, state);
1595 vm_exit_intinfo(struct vm *vm, int vcpuid, uint64_t info)
1600 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1603 vcpu = &vm->vcpu[vcpuid];
1605 if (info & VM_INTINFO_VALID) {
1606 type = info & VM_INTINFO_TYPE;
1607 vector = info & 0xff;
1608 if (type == VM_INTINFO_NMI && vector != IDT_NMI)
1610 if (type == VM_INTINFO_HWEXCEPTION && vector >= 32)
1612 if (info & VM_INTINFO_RSVD)
1617 VCPU_CTR2(vm, vcpuid, "%s: info1(%#lx)", __func__, info);
1618 vcpu->exitintinfo = info;
1628 #define IDT_VE 20 /* Virtualization Exception (Intel specific) */
1630 static enum exc_class
1631 exception_class(uint64_t info)
1635 KASSERT(info & VM_INTINFO_VALID, ("intinfo must be valid: %#lx", info));
1636 type = info & VM_INTINFO_TYPE;
1637 vector = info & 0xff;
1639 /* Table 6-4, "Interrupt and Exception Classes", Intel SDM, Vol 3 */
1641 case VM_INTINFO_HWINTR:
1642 case VM_INTINFO_SWINTR:
1643 case VM_INTINFO_NMI:
1644 return (EXC_BENIGN);
1647 * Hardware exception.
1649 * SVM and VT-x use identical type values to represent NMI,
1650 * hardware interrupt and software interrupt.
1652 * SVM uses type '3' for all exceptions. VT-x uses type '3'
1653 * for exceptions except #BP and #OF. #BP and #OF use a type
1654 * value of '5' or '6'. Therefore we don't check for explicit
1655 * values of 'type' to classify 'intinfo' into a hardware
1664 return (EXC_PAGEFAULT);
1670 return (EXC_CONTRIBUTORY);
1672 return (EXC_BENIGN);
1677 nested_fault(struct vm *vm, int vcpuid, uint64_t info1, uint64_t info2,
1680 enum exc_class exc1, exc2;
1683 KASSERT(info1 & VM_INTINFO_VALID, ("info1 %#lx is not valid", info1));
1684 KASSERT(info2 & VM_INTINFO_VALID, ("info2 %#lx is not valid", info2));
1687 * If an exception occurs while attempting to call the double-fault
1688 * handler the processor enters shutdown mode (aka triple fault).
1690 type1 = info1 & VM_INTINFO_TYPE;
1691 vector1 = info1 & 0xff;
1692 if (type1 == VM_INTINFO_HWEXCEPTION && vector1 == IDT_DF) {
1693 VCPU_CTR2(vm, vcpuid, "triple fault: info1(%#lx), info2(%#lx)",
1695 vm_suspend(vm, VM_SUSPEND_TRIPLEFAULT);
1701 * Table 6-5 "Conditions for Generating a Double Fault", Intel SDM, Vol3
1703 exc1 = exception_class(info1);
1704 exc2 = exception_class(info2);
1705 if ((exc1 == EXC_CONTRIBUTORY && exc2 == EXC_CONTRIBUTORY) ||
1706 (exc1 == EXC_PAGEFAULT && exc2 != EXC_BENIGN)) {
1707 /* Convert nested fault into a double fault. */
1709 *retinfo |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1710 *retinfo |= VM_INTINFO_DEL_ERRCODE;
1712 /* Handle exceptions serially */
1719 vcpu_exception_intinfo(struct vcpu *vcpu)
1723 if (vcpu->exception_pending) {
1724 info = vcpu->exc_vector & 0xff;
1725 info |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1726 if (vcpu->exc_errcode_valid) {
1727 info |= VM_INTINFO_DEL_ERRCODE;
1728 info |= (uint64_t)vcpu->exc_errcode << 32;
1735 vm_entry_intinfo(struct vm *vm, int vcpuid, uint64_t *retinfo)
1738 uint64_t info1, info2;
1741 KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU, ("invalid vcpu %d", vcpuid));
1743 vcpu = &vm->vcpu[vcpuid];
1745 info1 = vcpu->exitintinfo;
1746 vcpu->exitintinfo = 0;
1749 if (vcpu->exception_pending) {
1750 info2 = vcpu_exception_intinfo(vcpu);
1751 vcpu->exception_pending = 0;
1752 VCPU_CTR2(vm, vcpuid, "Exception %d delivered: %#lx",
1753 vcpu->exc_vector, info2);
1756 if ((info1 & VM_INTINFO_VALID) && (info2 & VM_INTINFO_VALID)) {
1757 valid = nested_fault(vm, vcpuid, info1, info2, retinfo);
1758 } else if (info1 & VM_INTINFO_VALID) {
1761 } else if (info2 & VM_INTINFO_VALID) {
1769 VCPU_CTR4(vm, vcpuid, "%s: info1(%#lx), info2(%#lx), "
1770 "retinfo(%#lx)", __func__, info1, info2, *retinfo);
1777 vm_get_intinfo(struct vm *vm, int vcpuid, uint64_t *info1, uint64_t *info2)
1781 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1784 vcpu = &vm->vcpu[vcpuid];
1785 *info1 = vcpu->exitintinfo;
1786 *info2 = vcpu_exception_intinfo(vcpu);
1791 vm_inject_exception(struct vm *vm, int vcpuid, int vector, int errcode_valid,
1792 uint32_t errcode, int restart_instruction)
1797 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1800 if (vector < 0 || vector >= 32)
1804 * A double fault exception should never be injected directly into
1805 * the guest. It is a derived exception that results from specific
1806 * combinations of nested faults.
1808 if (vector == IDT_DF)
1811 vcpu = &vm->vcpu[vcpuid];
1813 if (vcpu->exception_pending) {
1814 VCPU_CTR2(vm, vcpuid, "Unable to inject exception %d due to "
1815 "pending exception %d", vector, vcpu->exc_vector);
1820 * From section 26.6.1 "Interruptibility State" in Intel SDM:
1822 * Event blocking by "STI" or "MOV SS" is cleared after guest executes
1823 * one instruction or incurs an exception.
1825 error = vm_set_register(vm, vcpuid, VM_REG_GUEST_INTR_SHADOW, 0);
1826 KASSERT(error == 0, ("%s: error %d clearing interrupt shadow",
1829 if (restart_instruction)
1830 vm_restart_instruction(vm, vcpuid);
1832 vcpu->exception_pending = 1;
1833 vcpu->exc_vector = vector;
1834 vcpu->exc_errcode = errcode;
1835 vcpu->exc_errcode_valid = errcode_valid;
1836 VCPU_CTR1(vm, vcpuid, "Exception %d pending", vector);
1841 vm_inject_fault(void *vmarg, int vcpuid, int vector, int errcode_valid,
1845 int error, restart_instruction;
1848 restart_instruction = 1;
1850 error = vm_inject_exception(vm, vcpuid, vector, errcode_valid,
1851 errcode, restart_instruction);
1852 KASSERT(error == 0, ("vm_inject_exception error %d", error));
1856 vm_inject_pf(void *vmarg, int vcpuid, int error_code, uint64_t cr2)
1862 VCPU_CTR2(vm, vcpuid, "Injecting page fault: error_code %#x, cr2 %#lx",
1865 error = vm_set_register(vm, vcpuid, VM_REG_GUEST_CR2, cr2);
1866 KASSERT(error == 0, ("vm_set_register(cr2) error %d", error));
1868 vm_inject_fault(vm, vcpuid, IDT_PF, 1, error_code);
1871 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
1874 vm_inject_nmi(struct vm *vm, int vcpuid)
1878 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1881 vcpu = &vm->vcpu[vcpuid];
1883 vcpu->nmi_pending = 1;
1884 vcpu_notify_event(vm, vcpuid, false);
1889 vm_nmi_pending(struct vm *vm, int vcpuid)
1893 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1894 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1896 vcpu = &vm->vcpu[vcpuid];
1898 return (vcpu->nmi_pending);
1902 vm_nmi_clear(struct vm *vm, int vcpuid)
1906 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1907 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1909 vcpu = &vm->vcpu[vcpuid];
1911 if (vcpu->nmi_pending == 0)
1912 panic("vm_nmi_clear: inconsistent nmi_pending state");
1914 vcpu->nmi_pending = 0;
1915 vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
1918 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
1921 vm_inject_extint(struct vm *vm, int vcpuid)
1925 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1928 vcpu = &vm->vcpu[vcpuid];
1930 vcpu->extint_pending = 1;
1931 vcpu_notify_event(vm, vcpuid, false);
1936 vm_extint_pending(struct vm *vm, int vcpuid)
1940 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1941 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1943 vcpu = &vm->vcpu[vcpuid];
1945 return (vcpu->extint_pending);
1949 vm_extint_clear(struct vm *vm, int vcpuid)
1953 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1954 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
1956 vcpu = &vm->vcpu[vcpuid];
1958 if (vcpu->extint_pending == 0)
1959 panic("vm_extint_clear: inconsistent extint_pending state");
1961 vcpu->extint_pending = 0;
1962 vmm_stat_incr(vm, vcpuid, VCPU_EXTINT_COUNT, 1);
1966 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
1968 if (vcpu < 0 || vcpu >= VM_MAXCPU)
1971 if (type < 0 || type >= VM_CAP_MAX)
1974 return (VMGETCAP(vm->cookie, vcpu, type, retval));
1978 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
1980 if (vcpu < 0 || vcpu >= VM_MAXCPU)
1983 if (type < 0 || type >= VM_CAP_MAX)
1986 return (VMSETCAP(vm->cookie, vcpu, type, val));
1990 vm_lapic(struct vm *vm, int cpu)
1992 return (vm->vcpu[cpu].vlapic);
1996 vm_ioapic(struct vm *vm)
1999 return (vm->vioapic);
2003 vm_hpet(struct vm *vm)
2010 vmm_is_pptdev(int bus, int slot, int func)
2014 char *val, *cp, *cp2;
2018 * The length of an environment variable is limited to 128 bytes which
2019 * puts an upper limit on the number of passthru devices that may be
2020 * specified using a single environment variable.
2022 * Work around this by scanning multiple environment variable
2023 * names instead of a single one - yuck!
2025 const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
2027 /* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
2029 for (i = 0; names[i] != NULL && !found; i++) {
2030 cp = val = kern_getenv(names[i]);
2031 while (cp != NULL && *cp != '\0') {
2032 if ((cp2 = strchr(cp, ' ')) != NULL)
2035 n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
2036 if (n == 3 && bus == b && slot == s && func == f) {
2052 vm_iommu_domain(struct vm *vm)
2059 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate,
2065 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2066 panic("vm_set_run_state: invalid vcpuid %d", vcpuid);
2068 vcpu = &vm->vcpu[vcpuid];
2071 error = vcpu_set_state_locked(vcpu, newstate, from_idle);
2078 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
2081 enum vcpu_state state;
2083 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2084 panic("vm_get_run_state: invalid vcpuid %d", vcpuid);
2086 vcpu = &vm->vcpu[vcpuid];
2089 state = vcpu->state;
2090 if (hostcpu != NULL)
2091 *hostcpu = vcpu->hostcpu;
2098 vm_activate_cpu(struct vm *vm, int vcpuid)
2101 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2104 if (CPU_ISSET(vcpuid, &vm->active_cpus))
2107 VCPU_CTR0(vm, vcpuid, "activated");
2108 CPU_SET_ATOMIC(vcpuid, &vm->active_cpus);
2113 vm_active_cpus(struct vm *vm)
2116 return (vm->active_cpus);
2120 vm_suspended_cpus(struct vm *vm)
2123 return (vm->suspended_cpus);
2127 vcpu_stats(struct vm *vm, int vcpuid)
2130 return (vm->vcpu[vcpuid].stats);
2134 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
2136 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2139 *state = vm->vcpu[vcpuid].x2apic_state;
2145 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
2147 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2150 if (state >= X2APIC_STATE_LAST)
2153 vm->vcpu[vcpuid].x2apic_state = state;
2155 vlapic_set_x2apic_state(vm, vcpuid, state);
2161 * This function is called to ensure that a vcpu "sees" a pending event
2162 * as soon as possible:
2163 * - If the vcpu thread is sleeping then it is woken up.
2164 * - If the vcpu is running on a different host_cpu then an IPI will be directed
2165 * to the host_cpu to cause the vcpu to trap into the hypervisor.
2168 vcpu_notify_event(struct vm *vm, int vcpuid, bool lapic_intr)
2173 vcpu = &vm->vcpu[vcpuid];
2176 hostcpu = vcpu->hostcpu;
2177 if (vcpu->state == VCPU_RUNNING) {
2178 KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
2179 if (hostcpu != curcpu) {
2181 vlapic_post_intr(vcpu->vlapic, hostcpu,
2184 ipi_cpu(hostcpu, vmm_ipinum);
2188 * If the 'vcpu' is running on 'curcpu' then it must
2189 * be sending a notification to itself (e.g. SELF_IPI).
2190 * The pending event will be picked up when the vcpu
2191 * transitions back to guest context.
2195 KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
2196 "with hostcpu %d", vcpu->state, hostcpu));
2197 if (vcpu->state == VCPU_SLEEPING)
2204 vm_get_vmspace(struct vm *vm)
2207 return (vm->vmspace);
2211 vm_apicid2vcpuid(struct vm *vm, int apicid)
2214 * XXX apic id is assumed to be numerically identical to vcpu id
2220 vm_smp_rendezvous(struct vm *vm, int vcpuid, cpuset_t dest,
2221 vm_rendezvous_func_t func, void *arg)
2226 * Enforce that this function is called without any locks
2228 WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
2229 KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
2230 ("vm_smp_rendezvous: invalid vcpuid %d", vcpuid));
2233 mtx_lock(&vm->rendezvous_mtx);
2234 if (vm->rendezvous_func != NULL) {
2236 * If a rendezvous is already in progress then we need to
2237 * call the rendezvous handler in case this 'vcpuid' is one
2238 * of the targets of the rendezvous.
2240 RENDEZVOUS_CTR0(vm, vcpuid, "Rendezvous already in progress");
2241 mtx_unlock(&vm->rendezvous_mtx);
2242 vm_handle_rendezvous(vm, vcpuid);
2245 KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
2246 "rendezvous is still in progress"));
2248 RENDEZVOUS_CTR0(vm, vcpuid, "Initiating rendezvous");
2249 vm->rendezvous_req_cpus = dest;
2250 CPU_ZERO(&vm->rendezvous_done_cpus);
2251 vm->rendezvous_arg = arg;
2252 vm_set_rendezvous_func(vm, func);
2253 mtx_unlock(&vm->rendezvous_mtx);
2256 * Wake up any sleeping vcpus and trigger a VM-exit in any running
2257 * vcpus so they handle the rendezvous as soon as possible.
2259 for (i = 0; i < VM_MAXCPU; i++) {
2260 if (CPU_ISSET(i, &dest))
2261 vcpu_notify_event(vm, i, false);
2264 vm_handle_rendezvous(vm, vcpuid);
2268 vm_atpic(struct vm *vm)
2270 return (vm->vatpic);
2274 vm_atpit(struct vm *vm)
2276 return (vm->vatpit);
2280 vm_pmtmr(struct vm *vm)
2283 return (vm->vpmtmr);
2287 vm_rtc(struct vm *vm)
2294 vm_segment_name(int seg)
2296 static enum vm_reg_name seg_names[] = {
2305 KASSERT(seg >= 0 && seg < nitems(seg_names),
2306 ("%s: invalid segment encoding %d", __func__, seg));
2307 return (seg_names[seg]);
2311 vm_copy_teardown(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo,
2316 for (idx = 0; idx < num_copyinfo; idx++) {
2317 if (copyinfo[idx].cookie != NULL)
2318 vm_gpa_release(copyinfo[idx].cookie);
2320 bzero(copyinfo, num_copyinfo * sizeof(struct vm_copyinfo));
2324 vm_copy_setup(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
2325 uint64_t gla, size_t len, int prot, struct vm_copyinfo *copyinfo,
2328 int error, idx, nused;
2329 size_t n, off, remaining;
2333 bzero(copyinfo, sizeof(struct vm_copyinfo) * num_copyinfo);
2337 while (remaining > 0) {
2338 KASSERT(nused < num_copyinfo, ("insufficient vm_copyinfo"));
2339 error = vm_gla2gpa(vm, vcpuid, paging, gla, prot, &gpa);
2342 off = gpa & PAGE_MASK;
2343 n = min(remaining, PAGE_SIZE - off);
2344 copyinfo[nused].gpa = gpa;
2345 copyinfo[nused].len = n;
2351 for (idx = 0; idx < nused; idx++) {
2352 hva = vm_gpa_hold(vm, copyinfo[idx].gpa, copyinfo[idx].len,
2356 copyinfo[idx].hva = hva;
2357 copyinfo[idx].cookie = cookie;
2361 vm_copy_teardown(vm, vcpuid, copyinfo, num_copyinfo);
2369 vm_copyin(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo, void *kaddr,
2378 bcopy(copyinfo[idx].hva, dst, copyinfo[idx].len);
2379 len -= copyinfo[idx].len;
2380 dst += copyinfo[idx].len;
2386 vm_copyout(struct vm *vm, int vcpuid, const void *kaddr,
2387 struct vm_copyinfo *copyinfo, size_t len)
2395 bcopy(src, copyinfo[idx].hva, copyinfo[idx].len);
2396 len -= copyinfo[idx].len;
2397 src += copyinfo[idx].len;
2403 * Return the amount of in-use and wired memory for the VM. Since
2404 * these are global stats, only return the values with for vCPU 0
2406 VMM_STAT_DECLARE(VMM_MEM_RESIDENT);
2407 VMM_STAT_DECLARE(VMM_MEM_WIRED);
2410 vm_get_rescnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2414 vmm_stat_set(vm, vcpu, VMM_MEM_RESIDENT,
2415 PAGE_SIZE * vmspace_resident_count(vm->vmspace));
2420 vm_get_wiredcnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2424 vmm_stat_set(vm, vcpu, VMM_MEM_WIRED,
2425 PAGE_SIZE * pmap_wired_count(vmspace_pmap(vm->vmspace)));
2429 VMM_STAT_FUNC(VMM_MEM_RESIDENT, "Resident memory", vm_get_rescnt);
2430 VMM_STAT_FUNC(VMM_MEM_WIRED, "Wired memory", vm_get_wiredcnt);