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"
81 #include "vmm_lapic.h"
90 * (a) allocated when vcpu is created
91 * (i) initialized when vcpu is created and when it is reinitialized
92 * (o) initialized the first time the vcpu is created
93 * (x) initialized before use
96 struct mtx mtx; /* (o) protects 'state' and 'hostcpu' */
97 enum vcpu_state state; /* (o) vcpu state */
98 int hostcpu; /* (o) vcpu's host cpu */
99 int reqidle; /* (i) request vcpu to idle */
100 struct vlapic *vlapic; /* (i) APIC device model */
101 enum x2apic_state x2apic_state; /* (i) APIC mode */
102 uint64_t exitintinfo; /* (i) events pending at VM exit */
103 int nmi_pending; /* (i) NMI pending */
104 int extint_pending; /* (i) INTR pending */
105 int exception_pending; /* (i) exception pending */
106 int exc_vector; /* (x) exception collateral */
107 int exc_errcode_valid;
108 uint32_t exc_errcode;
109 struct savefpu *guestfpu; /* (a,i) guest fpu state */
110 uint64_t guest_xcr0; /* (i) guest %xcr0 register */
111 void *stats; /* (a,i) statistics */
112 struct vm_exit exitinfo; /* (x) exit reason and collateral */
113 uint64_t nextrip; /* (x) next instruction to execute */
116 #define vcpu_lock_initialized(v) mtx_initialized(&((v)->mtx))
117 #define vcpu_lock_init(v) mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
118 #define vcpu_lock(v) mtx_lock_spin(&((v)->mtx))
119 #define vcpu_unlock(v) mtx_unlock_spin(&((v)->mtx))
120 #define vcpu_assert_locked(v) mtx_assert(&((v)->mtx), MA_OWNED)
128 #define VM_MAX_MEMORY_SEGMENTS 2
132 * (o) initialized the first time the VM is created
133 * (i) initialized when VM is created and when it is reinitialized
134 * (x) initialized before use
137 void *cookie; /* (i) cpu-specific data */
138 void *iommu; /* (x) iommu-specific data */
139 struct vhpet *vhpet; /* (i) virtual HPET */
140 struct vioapic *vioapic; /* (i) virtual ioapic */
141 struct vatpic *vatpic; /* (i) virtual atpic */
142 struct vatpit *vatpit; /* (i) virtual atpit */
143 struct vpmtmr *vpmtmr; /* (i) virtual ACPI PM timer */
144 struct vrtc *vrtc; /* (o) virtual RTC */
145 volatile cpuset_t active_cpus; /* (i) active vcpus */
146 int suspend; /* (i) stop VM execution */
147 volatile cpuset_t suspended_cpus; /* (i) suspended vcpus */
148 volatile cpuset_t halted_cpus; /* (x) cpus in a hard halt */
149 cpuset_t rendezvous_req_cpus; /* (x) rendezvous requested */
150 cpuset_t rendezvous_done_cpus; /* (x) rendezvous finished */
151 void *rendezvous_arg; /* (x) rendezvous func/arg */
152 vm_rendezvous_func_t rendezvous_func;
153 struct mtx rendezvous_mtx; /* (o) rendezvous lock */
154 int num_mem_segs; /* (o) guest memory segments */
155 struct mem_seg mem_segs[VM_MAX_MEMORY_SEGMENTS];
156 struct vmspace *vmspace; /* (o) guest's address space */
157 char name[VM_MAX_NAMELEN]; /* (o) virtual machine name */
158 struct vcpu vcpu[VM_MAXCPU]; /* (i) guest vcpus */
161 static int vmm_initialized;
163 static struct vmm_ops *ops;
164 #define VMM_INIT(num) (ops != NULL ? (*ops->init)(num) : 0)
165 #define VMM_CLEANUP() (ops != NULL ? (*ops->cleanup)() : 0)
166 #define VMM_RESUME() (ops != NULL ? (*ops->resume)() : 0)
168 #define VMINIT(vm, pmap) (ops != NULL ? (*ops->vminit)(vm, pmap): NULL)
169 #define VMRUN(vmi, vcpu, rip, pmap, evinfo) \
170 (ops != NULL ? (*ops->vmrun)(vmi, vcpu, rip, pmap, evinfo) : ENXIO)
171 #define VMCLEANUP(vmi) (ops != NULL ? (*ops->vmcleanup)(vmi) : NULL)
172 #define VMSPACE_ALLOC(min, max) \
173 (ops != NULL ? (*ops->vmspace_alloc)(min, max) : NULL)
174 #define VMSPACE_FREE(vmspace) \
175 (ops != NULL ? (*ops->vmspace_free)(vmspace) : ENXIO)
176 #define VMGETREG(vmi, vcpu, num, retval) \
177 (ops != NULL ? (*ops->vmgetreg)(vmi, vcpu, num, retval) : ENXIO)
178 #define VMSETREG(vmi, vcpu, num, val) \
179 (ops != NULL ? (*ops->vmsetreg)(vmi, vcpu, num, val) : ENXIO)
180 #define VMGETDESC(vmi, vcpu, num, desc) \
181 (ops != NULL ? (*ops->vmgetdesc)(vmi, vcpu, num, desc) : ENXIO)
182 #define VMSETDESC(vmi, vcpu, num, desc) \
183 (ops != NULL ? (*ops->vmsetdesc)(vmi, vcpu, num, desc) : ENXIO)
184 #define VMGETCAP(vmi, vcpu, num, retval) \
185 (ops != NULL ? (*ops->vmgetcap)(vmi, vcpu, num, retval) : ENXIO)
186 #define VMSETCAP(vmi, vcpu, num, val) \
187 (ops != NULL ? (*ops->vmsetcap)(vmi, vcpu, num, val) : ENXIO)
188 #define VLAPIC_INIT(vmi, vcpu) \
189 (ops != NULL ? (*ops->vlapic_init)(vmi, vcpu) : NULL)
190 #define VLAPIC_CLEANUP(vmi, vlapic) \
191 (ops != NULL ? (*ops->vlapic_cleanup)(vmi, vlapic) : NULL)
193 #define fpu_start_emulating() load_cr0(rcr0() | CR0_TS)
194 #define fpu_stop_emulating() clts()
196 static MALLOC_DEFINE(M_VM, "vm", "vm");
199 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
201 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW, NULL, NULL);
204 * Halt the guest if all vcpus are executing a HLT instruction with
205 * interrupts disabled.
207 static int halt_detection_enabled = 1;
208 TUNABLE_INT("hw.vmm.halt_detection", &halt_detection_enabled);
209 SYSCTL_INT(_hw_vmm, OID_AUTO, halt_detection, CTLFLAG_RDTUN,
210 &halt_detection_enabled, 0,
211 "Halt VM if all vcpus execute HLT with interrupts disabled");
213 static int vmm_ipinum;
214 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
215 "IPI vector used for vcpu notifications");
217 static int trace_guest_exceptions;
218 SYSCTL_INT(_hw_vmm, OID_AUTO, trace_guest_exceptions, CTLFLAG_RDTUN,
219 &trace_guest_exceptions, 0,
220 "Trap into hypervisor on all guest exceptions and reflect them back");
222 static int vmm_force_iommu = 0;
223 TUNABLE_INT("hw.vmm.force_iommu", &vmm_force_iommu);
224 SYSCTL_INT(_hw_vmm, OID_AUTO, force_iommu, CTLFLAG_RDTUN, &vmm_force_iommu, 0,
225 "Force use of I/O MMU even if no passthrough devices were found.");
227 static void vcpu_notify_event_locked(struct vcpu *vcpu, bool lapic_intr);
231 vcpu_state2str(enum vcpu_state state)
250 vcpu_cleanup(struct vm *vm, int i, bool destroy)
252 struct vcpu *vcpu = &vm->vcpu[i];
254 VLAPIC_CLEANUP(vm->cookie, vcpu->vlapic);
256 vmm_stat_free(vcpu->stats);
257 fpu_save_area_free(vcpu->guestfpu);
262 vcpu_init(struct vm *vm, int vcpu_id, bool create)
266 KASSERT(vcpu_id >= 0 && vcpu_id < VM_MAXCPU,
267 ("vcpu_init: invalid vcpu %d", vcpu_id));
269 vcpu = &vm->vcpu[vcpu_id];
272 KASSERT(!vcpu_lock_initialized(vcpu), ("vcpu %d already "
273 "initialized", vcpu_id));
274 vcpu_lock_init(vcpu);
275 vcpu->state = VCPU_IDLE;
276 vcpu->hostcpu = NOCPU;
277 vcpu->guestfpu = fpu_save_area_alloc();
278 vcpu->stats = vmm_stat_alloc();
281 vcpu->vlapic = VLAPIC_INIT(vm->cookie, vcpu_id);
282 vm_set_x2apic_state(vm, vcpu_id, X2APIC_DISABLED);
284 vcpu->exitintinfo = 0;
285 vcpu->nmi_pending = 0;
286 vcpu->extint_pending = 0;
287 vcpu->exception_pending = 0;
288 vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
289 fpu_save_area_reset(vcpu->guestfpu);
290 vmm_stat_init(vcpu->stats);
294 vcpu_trace_exceptions(struct vm *vm, int vcpuid)
297 return (trace_guest_exceptions);
301 vm_exitinfo(struct vm *vm, int cpuid)
305 if (cpuid < 0 || cpuid >= VM_MAXCPU)
306 panic("vm_exitinfo: invalid cpuid %d", cpuid);
308 vcpu = &vm->vcpu[cpuid];
310 return (&vcpu->exitinfo);
324 vmm_host_state_init();
326 vmm_ipinum = vmm_ipi_alloc();
328 vmm_ipinum = IPI_AST;
330 error = vmm_mem_init();
335 ops = &vmm_ops_intel;
336 else if (vmm_is_amd())
341 vmm_resume_p = vmm_resume;
343 return (VMM_INIT(vmm_ipinum));
347 vmm_handler(module_t mod, int what, void *arg)
354 if (vmm_force_iommu || ppt_avail_devices() > 0)
361 error = vmmdev_cleanup();
365 if (vmm_ipinum != IPI_AST)
366 vmm_ipi_free(vmm_ipinum);
367 error = VMM_CLEANUP();
369 * Something bad happened - prevent new
370 * VMs from being created
383 static moduledata_t vmm_kmod = {
390 * vmm initialization has the following dependencies:
392 * - iommu initialization must happen after the pci passthru driver has had
393 * a chance to attach to any passthru devices (after SI_SUB_CONFIGURE).
395 * - VT-x initialization requires smp_rendezvous() and therefore must happen
396 * after SMP is fully functional (after SI_SUB_SMP).
398 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
399 MODULE_VERSION(vmm, 1);
402 vm_init(struct vm *vm, bool create)
406 vm->cookie = VMINIT(vm, vmspace_pmap(vm->vmspace));
408 vm->vioapic = vioapic_init(vm);
409 vm->vhpet = vhpet_init(vm);
410 vm->vatpic = vatpic_init(vm);
411 vm->vatpit = vatpit_init(vm);
412 vm->vpmtmr = vpmtmr_init(vm);
414 vm->vrtc = vrtc_init(vm);
416 CPU_ZERO(&vm->active_cpus);
419 CPU_ZERO(&vm->suspended_cpus);
421 for (i = 0; i < VM_MAXCPU; i++)
422 vcpu_init(vm, i, create);
426 vm_create(const char *name, struct vm **retvm)
429 struct vmspace *vmspace;
432 * If vmm.ko could not be successfully initialized then don't attempt
433 * to create the virtual machine.
435 if (!vmm_initialized)
438 if (name == NULL || strlen(name) >= VM_MAX_NAMELEN)
441 vmspace = VMSPACE_ALLOC(0, VM_MAXUSER_ADDRESS);
445 vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
446 strcpy(vm->name, name);
447 vm->num_mem_segs = 0;
448 vm->vmspace = vmspace;
449 mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
458 vm_free_mem_seg(struct vm *vm, struct mem_seg *seg)
461 if (seg->object != NULL)
462 vmm_mem_free(vm->vmspace, seg->gpa, seg->len);
464 bzero(seg, sizeof(*seg));
468 vm_cleanup(struct vm *vm, bool destroy)
472 ppt_unassign_all(vm);
474 if (vm->iommu != NULL)
475 iommu_destroy_domain(vm->iommu);
478 vrtc_cleanup(vm->vrtc);
480 vrtc_reset(vm->vrtc);
481 vpmtmr_cleanup(vm->vpmtmr);
482 vatpit_cleanup(vm->vatpit);
483 vhpet_cleanup(vm->vhpet);
484 vatpic_cleanup(vm->vatpic);
485 vioapic_cleanup(vm->vioapic);
487 for (i = 0; i < VM_MAXCPU; i++)
488 vcpu_cleanup(vm, i, destroy);
490 VMCLEANUP(vm->cookie);
493 for (i = 0; i < vm->num_mem_segs; i++)
494 vm_free_mem_seg(vm, &vm->mem_segs[i]);
496 vm->num_mem_segs = 0;
498 VMSPACE_FREE(vm->vmspace);
504 vm_destroy(struct vm *vm)
506 vm_cleanup(vm, true);
511 vm_reinit(struct vm *vm)
516 * A virtual machine can be reset only if all vcpus are suspended.
518 if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
519 vm_cleanup(vm, false);
530 vm_name(struct vm *vm)
536 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
540 if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
547 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
550 vmm_mmio_free(vm->vmspace, gpa, len);
555 vm_mem_allocated(struct vm *vm, vm_paddr_t gpa)
558 vm_paddr_t gpabase, gpalimit;
560 for (i = 0; i < vm->num_mem_segs; i++) {
561 gpabase = vm->mem_segs[i].gpa;
562 gpalimit = gpabase + vm->mem_segs[i].len;
563 if (gpa >= gpabase && gpa < gpalimit)
564 return (TRUE); /* 'gpa' is regular memory */
567 if (ppt_is_mmio(vm, gpa))
568 return (TRUE); /* 'gpa' is pci passthru mmio */
574 vm_malloc(struct vm *vm, vm_paddr_t gpa, size_t len)
576 int available, allocated;
581 if ((gpa & PAGE_MASK) || (len & PAGE_MASK) || len == 0)
584 available = allocated = 0;
586 while (g < gpa + len) {
587 if (vm_mem_allocated(vm, g))
596 * If there are some allocated and some available pages in the address
597 * range then it is an error.
599 if (allocated && available)
603 * If the entire address range being requested has already been
604 * allocated then there isn't anything more to do.
606 if (allocated && available == 0)
609 if (vm->num_mem_segs >= VM_MAX_MEMORY_SEGMENTS)
612 seg = &vm->mem_segs[vm->num_mem_segs];
614 if ((object = vmm_mem_alloc(vm->vmspace, gpa, len)) == NULL)
619 seg->object = object;
628 vm_maxmem(struct vm *vm)
631 vm_paddr_t gpa, maxmem;
634 for (i = 0; i < vm->num_mem_segs; i++) {
635 gpa = vm->mem_segs[i].gpa + vm->mem_segs[i].len;
643 vm_gpa_unwire(struct vm *vm)
648 for (i = 0; i < vm->num_mem_segs; i++) {
649 seg = &vm->mem_segs[i];
653 rv = vm_map_unwire(&vm->vmspace->vm_map,
654 seg->gpa, seg->gpa + seg->len,
655 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
656 KASSERT(rv == KERN_SUCCESS, ("vm(%s) memory segment "
657 "%#lx/%ld could not be unwired: %d",
658 vm_name(vm), seg->gpa, seg->len, rv));
665 vm_gpa_wire(struct vm *vm)
670 for (i = 0; i < vm->num_mem_segs; i++) {
671 seg = &vm->mem_segs[i];
676 rv = vm_map_wire(&vm->vmspace->vm_map,
677 seg->gpa, seg->gpa + seg->len,
678 VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
679 if (rv != KERN_SUCCESS)
685 if (i < vm->num_mem_segs) {
687 * Undo the wiring before returning an error.
697 vm_iommu_modify(struct vm *vm, boolean_t map)
702 void *vp, *cookie, *host_domain;
705 host_domain = iommu_host_domain();
707 for (i = 0; i < vm->num_mem_segs; i++) {
708 seg = &vm->mem_segs[i];
709 KASSERT(seg->wired, ("vm(%s) memory segment %#lx/%ld not wired",
710 vm_name(vm), seg->gpa, seg->len));
713 while (gpa < seg->gpa + seg->len) {
714 vp = vm_gpa_hold(vm, gpa, PAGE_SIZE, VM_PROT_WRITE,
716 KASSERT(vp != NULL, ("vm(%s) could not map gpa %#lx",
719 vm_gpa_release(cookie);
721 hpa = DMAP_TO_PHYS((uintptr_t)vp);
723 iommu_create_mapping(vm->iommu, gpa, hpa, sz);
724 iommu_remove_mapping(host_domain, hpa, sz);
726 iommu_remove_mapping(vm->iommu, gpa, sz);
727 iommu_create_mapping(host_domain, hpa, hpa, sz);
735 * Invalidate the cached translations associated with the domain
736 * from which pages were removed.
739 iommu_invalidate_tlb(host_domain);
741 iommu_invalidate_tlb(vm->iommu);
744 #define vm_iommu_unmap(vm) vm_iommu_modify((vm), FALSE)
745 #define vm_iommu_map(vm) vm_iommu_modify((vm), TRUE)
748 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
752 error = ppt_unassign_device(vm, bus, slot, func);
756 if (ppt_assigned_devices(vm) == 0) {
764 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
770 * Virtual machines with pci passthru devices get special treatment:
771 * - the guest physical memory is wired
772 * - the iommu is programmed to do the 'gpa' to 'hpa' translation
774 * We need to do this before the first pci passthru device is attached.
776 if (ppt_assigned_devices(vm) == 0) {
777 KASSERT(vm->iommu == NULL,
778 ("vm_assign_pptdev: iommu must be NULL"));
779 maxaddr = vm_maxmem(vm);
780 vm->iommu = iommu_create_domain(maxaddr);
782 error = vm_gpa_wire(vm);
789 error = ppt_assign_device(vm, bus, slot, func);
794 vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
800 pageoff = gpa & PAGE_MASK;
801 if (len > PAGE_SIZE - pageoff)
802 panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
804 count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
805 trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
809 return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
817 vm_gpa_release(void *cookie)
819 vm_page_t m = cookie;
827 vm_gpabase2memseg(struct vm *vm, vm_paddr_t gpabase,
828 struct vm_memory_segment *seg)
832 for (i = 0; i < vm->num_mem_segs; i++) {
833 if (gpabase == vm->mem_segs[i].gpa) {
834 seg->gpa = vm->mem_segs[i].gpa;
835 seg->len = vm->mem_segs[i].len;
836 seg->wired = vm->mem_segs[i].wired;
844 vm_get_memobj(struct vm *vm, vm_paddr_t gpa, size_t len,
845 vm_offset_t *offset, struct vm_object **object)
852 for (i = 0; i < vm->num_mem_segs; i++) {
853 if ((seg_obj = vm->mem_segs[i].object) == NULL)
856 seg_gpa = vm->mem_segs[i].gpa;
857 seg_len = vm->mem_segs[i].len;
859 if (gpa >= seg_gpa && gpa < seg_gpa + seg_len) {
860 *offset = gpa - seg_gpa;
862 vm_object_reference(seg_obj);
871 vm_get_register(struct vm *vm, int vcpu, int reg, uint64_t *retval)
874 if (vcpu < 0 || vcpu >= VM_MAXCPU)
877 if (reg >= VM_REG_LAST)
880 return (VMGETREG(vm->cookie, vcpu, reg, retval));
884 vm_set_register(struct vm *vm, int vcpuid, int reg, uint64_t val)
889 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
892 if (reg >= VM_REG_LAST)
895 error = VMSETREG(vm->cookie, vcpuid, reg, val);
896 if (error || reg != VM_REG_GUEST_RIP)
899 /* Set 'nextrip' to match the value of %rip */
900 VCPU_CTR1(vm, vcpuid, "Setting nextrip to %#lx", val);
901 vcpu = &vm->vcpu[vcpuid];
907 is_descriptor_table(int reg)
911 case VM_REG_GUEST_IDTR:
912 case VM_REG_GUEST_GDTR:
920 is_segment_register(int reg)
924 case VM_REG_GUEST_ES:
925 case VM_REG_GUEST_CS:
926 case VM_REG_GUEST_SS:
927 case VM_REG_GUEST_DS:
928 case VM_REG_GUEST_FS:
929 case VM_REG_GUEST_GS:
930 case VM_REG_GUEST_TR:
931 case VM_REG_GUEST_LDTR:
939 vm_get_seg_desc(struct vm *vm, int vcpu, int reg,
940 struct seg_desc *desc)
943 if (vcpu < 0 || vcpu >= VM_MAXCPU)
946 if (!is_segment_register(reg) && !is_descriptor_table(reg))
949 return (VMGETDESC(vm->cookie, vcpu, reg, desc));
953 vm_set_seg_desc(struct vm *vm, int vcpu, int reg,
954 struct seg_desc *desc)
956 if (vcpu < 0 || vcpu >= VM_MAXCPU)
959 if (!is_segment_register(reg) && !is_descriptor_table(reg))
962 return (VMSETDESC(vm->cookie, vcpu, reg, desc));
966 restore_guest_fpustate(struct vcpu *vcpu)
969 /* flush host state to the pcb */
972 /* restore guest FPU state */
973 fpu_stop_emulating();
974 fpurestore(vcpu->guestfpu);
976 /* restore guest XCR0 if XSAVE is enabled in the host */
977 if (rcr4() & CR4_XSAVE)
978 load_xcr(0, vcpu->guest_xcr0);
981 * The FPU is now "dirty" with the guest's state so turn on emulation
982 * to trap any access to the FPU by the host.
984 fpu_start_emulating();
988 save_guest_fpustate(struct vcpu *vcpu)
991 if ((rcr0() & CR0_TS) == 0)
992 panic("fpu emulation not enabled in host!");
994 /* save guest XCR0 and restore host XCR0 */
995 if (rcr4() & CR4_XSAVE) {
996 vcpu->guest_xcr0 = rxcr(0);
997 load_xcr(0, vmm_get_host_xcr0());
1000 /* save guest FPU state */
1001 fpu_stop_emulating();
1002 fpusave(vcpu->guestfpu);
1003 fpu_start_emulating();
1006 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
1009 vcpu_set_state_locked(struct vm *vm, int vcpuid, enum vcpu_state newstate,
1015 vcpu = &vm->vcpu[vcpuid];
1016 vcpu_assert_locked(vcpu);
1019 * State transitions from the vmmdev_ioctl() must always begin from
1020 * the VCPU_IDLE state. This guarantees that there is only a single
1021 * ioctl() operating on a vcpu at any point.
1024 while (vcpu->state != VCPU_IDLE) {
1026 vcpu_notify_event_locked(vcpu, false);
1027 VCPU_CTR1(vm, vcpuid, "vcpu state change from %s to "
1028 "idle requested", vcpu_state2str(vcpu->state));
1029 msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
1032 KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
1033 "vcpu idle state"));
1036 if (vcpu->state == VCPU_RUNNING) {
1037 KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
1038 "mismatch for running vcpu", curcpu, vcpu->hostcpu));
1040 KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
1041 "vcpu that is not running", vcpu->hostcpu));
1045 * The following state transitions are allowed:
1046 * IDLE -> FROZEN -> IDLE
1047 * FROZEN -> RUNNING -> FROZEN
1048 * FROZEN -> SLEEPING -> FROZEN
1050 switch (vcpu->state) {
1054 error = (newstate != VCPU_FROZEN);
1057 error = (newstate == VCPU_FROZEN);
1067 VCPU_CTR2(vm, vcpuid, "vcpu state changed from %s to %s",
1068 vcpu_state2str(vcpu->state), vcpu_state2str(newstate));
1070 vcpu->state = newstate;
1071 if (newstate == VCPU_RUNNING)
1072 vcpu->hostcpu = curcpu;
1074 vcpu->hostcpu = NOCPU;
1076 if (newstate == VCPU_IDLE)
1077 wakeup(&vcpu->state);
1083 vcpu_require_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
1087 if ((error = vcpu_set_state(vm, vcpuid, newstate, false)) != 0)
1088 panic("Error %d setting state to %d\n", error, newstate);
1092 vcpu_require_state_locked(struct vm *vm, int vcpuid, enum vcpu_state newstate)
1096 if ((error = vcpu_set_state_locked(vm, vcpuid, newstate, false)) != 0)
1097 panic("Error %d setting state to %d", error, newstate);
1101 vm_set_rendezvous_func(struct vm *vm, vm_rendezvous_func_t func)
1104 KASSERT(mtx_owned(&vm->rendezvous_mtx), ("rendezvous_mtx not locked"));
1107 * Update 'rendezvous_func' and execute a write memory barrier to
1108 * ensure that it is visible across all host cpus. This is not needed
1109 * for correctness but it does ensure that all the vcpus will notice
1110 * that the rendezvous is requested immediately.
1112 vm->rendezvous_func = func;
1116 #define RENDEZVOUS_CTR0(vm, vcpuid, fmt) \
1119 VCPU_CTR0(vm, vcpuid, fmt); \
1125 vm_handle_rendezvous(struct vm *vm, int vcpuid)
1128 KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
1129 ("vm_handle_rendezvous: invalid vcpuid %d", vcpuid));
1131 mtx_lock(&vm->rendezvous_mtx);
1132 while (vm->rendezvous_func != NULL) {
1133 /* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
1134 CPU_AND(&vm->rendezvous_req_cpus, &vm->active_cpus);
1137 CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
1138 !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
1139 VCPU_CTR0(vm, vcpuid, "Calling rendezvous func");
1140 (*vm->rendezvous_func)(vm, vcpuid, vm->rendezvous_arg);
1141 CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
1143 if (CPU_CMP(&vm->rendezvous_req_cpus,
1144 &vm->rendezvous_done_cpus) == 0) {
1145 VCPU_CTR0(vm, vcpuid, "Rendezvous completed");
1146 vm_set_rendezvous_func(vm, NULL);
1147 wakeup(&vm->rendezvous_func);
1150 RENDEZVOUS_CTR0(vm, vcpuid, "Wait for rendezvous completion");
1151 mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
1154 mtx_unlock(&vm->rendezvous_mtx);
1158 * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1161 vm_handle_hlt(struct vm *vm, int vcpuid, bool intr_disabled, bool *retu)
1165 int t, vcpu_halted, vm_halted;
1167 KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1169 vcpu = &vm->vcpu[vcpuid];
1176 * Do a final check for pending NMI or interrupts before
1177 * really putting this thread to sleep. Also check for
1178 * software events that would cause this vcpu to wakeup.
1180 * These interrupts/events could have happened after the
1181 * vcpu returned from VMRUN() and before it acquired the
1184 if (vm->rendezvous_func != NULL || vm->suspend || vcpu->reqidle)
1186 if (vm_nmi_pending(vm, vcpuid))
1188 if (!intr_disabled) {
1189 if (vm_extint_pending(vm, vcpuid) ||
1190 vlapic_pending_intr(vcpu->vlapic, NULL)) {
1195 /* Don't go to sleep if the vcpu thread needs to yield */
1196 if (vcpu_should_yield(vm, vcpuid))
1200 * Some Linux guests implement "halt" by having all vcpus
1201 * execute HLT with interrupts disabled. 'halted_cpus' keeps
1202 * track of the vcpus that have entered this state. When all
1203 * vcpus enter the halted state the virtual machine is halted.
1205 if (intr_disabled) {
1207 VCPU_CTR0(vm, vcpuid, "Halted");
1208 if (!vcpu_halted && halt_detection_enabled) {
1210 CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1212 if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1221 vcpu_require_state_locked(vm, vcpuid, VCPU_SLEEPING);
1223 * XXX msleep_spin() cannot be interrupted by signals so
1224 * wake up periodically to check pending signals.
1226 msleep_spin(vcpu, &vcpu->mtx, wmesg, hz);
1227 vcpu_require_state_locked(vm, vcpuid, VCPU_FROZEN);
1228 vmm_stat_incr(vm, vcpuid, VCPU_IDLE_TICKS, ticks - t);
1232 CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1237 vm_suspend(vm, VM_SUSPEND_HALT);
1243 vm_handle_paging(struct vm *vm, int vcpuid, bool *retu)
1248 struct vm_exit *vme;
1250 vcpu = &vm->vcpu[vcpuid];
1251 vme = &vcpu->exitinfo;
1253 KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1254 __func__, vme->inst_length));
1256 ftype = vme->u.paging.fault_type;
1257 KASSERT(ftype == VM_PROT_READ ||
1258 ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1259 ("vm_handle_paging: invalid fault_type %d", ftype));
1261 if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1262 rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1263 vme->u.paging.gpa, ftype);
1265 VCPU_CTR2(vm, vcpuid, "%s bit emulation for gpa %#lx",
1266 ftype == VM_PROT_READ ? "accessed" : "dirty",
1272 map = &vm->vmspace->vm_map;
1273 rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL);
1275 VCPU_CTR3(vm, vcpuid, "vm_handle_paging rv = %d, gpa = %#lx, "
1276 "ftype = %d", rv, vme->u.paging.gpa, ftype);
1278 if (rv != KERN_SUCCESS)
1285 vm_handle_inst_emul(struct vm *vm, int vcpuid, bool *retu)
1289 struct vm_exit *vme;
1290 uint64_t gla, gpa, cs_base;
1291 struct vm_guest_paging *paging;
1292 mem_region_read_t mread;
1293 mem_region_write_t mwrite;
1294 enum vm_cpu_mode cpu_mode;
1295 int cs_d, error, fault;
1297 vcpu = &vm->vcpu[vcpuid];
1298 vme = &vcpu->exitinfo;
1300 KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1301 __func__, vme->inst_length));
1303 gla = vme->u.inst_emul.gla;
1304 gpa = vme->u.inst_emul.gpa;
1305 cs_base = vme->u.inst_emul.cs_base;
1306 cs_d = vme->u.inst_emul.cs_d;
1307 vie = &vme->u.inst_emul.vie;
1308 paging = &vme->u.inst_emul.paging;
1309 cpu_mode = paging->cpu_mode;
1311 VCPU_CTR1(vm, vcpuid, "inst_emul fault accessing gpa %#lx", gpa);
1313 /* Fetch, decode and emulate the faulting instruction */
1314 if (vie->num_valid == 0) {
1315 error = vmm_fetch_instruction(vm, vcpuid, paging, vme->rip +
1316 cs_base, VIE_INST_SIZE, vie, &fault);
1319 * The instruction bytes have already been copied into 'vie'
1326 if (vmm_decode_instruction(vm, vcpuid, gla, cpu_mode, cs_d, vie) != 0) {
1327 VCPU_CTR1(vm, vcpuid, "Error decoding instruction at %#lx",
1328 vme->rip + cs_base);
1329 *retu = true; /* dump instruction bytes in userspace */
1334 * Update 'nextrip' based on the length of the emulated instruction.
1336 vme->inst_length = vie->num_processed;
1337 vcpu->nextrip += vie->num_processed;
1338 VCPU_CTR1(vm, vcpuid, "nextrip updated to %#lx after instruction "
1339 "decoding", vcpu->nextrip);
1341 /* return to userland unless this is an in-kernel emulated device */
1342 if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1343 mread = lapic_mmio_read;
1344 mwrite = lapic_mmio_write;
1345 } else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1346 mread = vioapic_mmio_read;
1347 mwrite = vioapic_mmio_write;
1348 } else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1349 mread = vhpet_mmio_read;
1350 mwrite = vhpet_mmio_write;
1356 error = vmm_emulate_instruction(vm, vcpuid, gpa, vie, paging,
1357 mread, mwrite, retu);
1363 vm_handle_suspend(struct vm *vm, int vcpuid, bool *retu)
1369 vcpu = &vm->vcpu[vcpuid];
1371 CPU_SET_ATOMIC(vcpuid, &vm->suspended_cpus);
1374 * Wait until all 'active_cpus' have suspended themselves.
1376 * Since a VM may be suspended at any time including when one or
1377 * more vcpus are doing a rendezvous we need to call the rendezvous
1378 * handler while we are waiting to prevent a deadlock.
1382 if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1383 VCPU_CTR0(vm, vcpuid, "All vcpus suspended");
1387 if (vm->rendezvous_func == NULL) {
1388 VCPU_CTR0(vm, vcpuid, "Sleeping during suspend");
1389 vcpu_require_state_locked(vm, vcpuid, VCPU_SLEEPING);
1390 msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1391 vcpu_require_state_locked(vm, vcpuid, VCPU_FROZEN);
1393 VCPU_CTR0(vm, vcpuid, "Rendezvous during suspend");
1395 vm_handle_rendezvous(vm, vcpuid);
1402 * Wakeup the other sleeping vcpus and return to userspace.
1404 for (i = 0; i < VM_MAXCPU; i++) {
1405 if (CPU_ISSET(i, &vm->suspended_cpus)) {
1406 vcpu_notify_event(vm, i, false);
1415 vm_handle_reqidle(struct vm *vm, int vcpuid, bool *retu)
1417 struct vcpu *vcpu = &vm->vcpu[vcpuid];
1420 KASSERT(vcpu->reqidle, ("invalid vcpu reqidle %d", vcpu->reqidle));
1428 vm_suspend(struct vm *vm, enum vm_suspend_how how)
1432 if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
1435 if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
1436 VM_CTR2(vm, "virtual machine already suspended %d/%d",
1441 VM_CTR1(vm, "virtual machine successfully suspended %d", how);
1444 * Notify all active vcpus that they are now suspended.
1446 for (i = 0; i < VM_MAXCPU; i++) {
1447 if (CPU_ISSET(i, &vm->active_cpus))
1448 vcpu_notify_event(vm, i, false);
1455 vm_exit_suspended(struct vm *vm, int vcpuid, uint64_t rip)
1457 struct vm_exit *vmexit;
1459 KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
1460 ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
1462 vmexit = vm_exitinfo(vm, vcpuid);
1464 vmexit->inst_length = 0;
1465 vmexit->exitcode = VM_EXITCODE_SUSPENDED;
1466 vmexit->u.suspended.how = vm->suspend;
1470 vm_exit_rendezvous(struct vm *vm, int vcpuid, uint64_t rip)
1472 struct vm_exit *vmexit;
1474 KASSERT(vm->rendezvous_func != NULL, ("rendezvous not in progress"));
1476 vmexit = vm_exitinfo(vm, vcpuid);
1478 vmexit->inst_length = 0;
1479 vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1480 vmm_stat_incr(vm, vcpuid, VMEXIT_RENDEZVOUS, 1);
1484 vm_exit_reqidle(struct vm *vm, int vcpuid, uint64_t rip)
1486 struct vm_exit *vmexit;
1488 vmexit = vm_exitinfo(vm, vcpuid);
1490 vmexit->inst_length = 0;
1491 vmexit->exitcode = VM_EXITCODE_REQIDLE;
1492 vmm_stat_incr(vm, vcpuid, VMEXIT_REQIDLE, 1);
1496 vm_exit_astpending(struct vm *vm, int vcpuid, uint64_t rip)
1498 struct vm_exit *vmexit;
1500 vmexit = vm_exitinfo(vm, vcpuid);
1502 vmexit->inst_length = 0;
1503 vmexit->exitcode = VM_EXITCODE_BOGUS;
1504 vmm_stat_incr(vm, vcpuid, VMEXIT_ASTPENDING, 1);
1508 vm_run(struct vm *vm, struct vm_run *vmrun)
1510 struct vm_eventinfo evinfo;
1515 struct vm_exit *vme;
1516 bool retu, intr_disabled;
1519 vcpuid = vmrun->cpuid;
1521 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1524 if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1527 if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1530 pmap = vmspace_pmap(vm->vmspace);
1531 vcpu = &vm->vcpu[vcpuid];
1532 vme = &vcpu->exitinfo;
1533 evinfo.rptr = &vm->rendezvous_func;
1534 evinfo.sptr = &vm->suspend;
1535 evinfo.iptr = &vcpu->reqidle;
1539 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1540 ("vm_run: absurd pm_active"));
1544 pcb = PCPU_GET(curpcb);
1545 set_pcb_flags(pcb, PCB_FULL_IRET);
1547 restore_guest_fpustate(vcpu);
1549 vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
1550 error = VMRUN(vm->cookie, vcpuid, vcpu->nextrip, pmap, &evinfo);
1551 vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
1553 save_guest_fpustate(vcpu);
1555 vmm_stat_incr(vm, vcpuid, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1561 vcpu->nextrip = vme->rip + vme->inst_length;
1562 switch (vme->exitcode) {
1563 case VM_EXITCODE_REQIDLE:
1564 error = vm_handle_reqidle(vm, vcpuid, &retu);
1566 case VM_EXITCODE_SUSPENDED:
1567 error = vm_handle_suspend(vm, vcpuid, &retu);
1569 case VM_EXITCODE_IOAPIC_EOI:
1570 vioapic_process_eoi(vm, vcpuid,
1571 vme->u.ioapic_eoi.vector);
1573 case VM_EXITCODE_RENDEZVOUS:
1574 vm_handle_rendezvous(vm, vcpuid);
1577 case VM_EXITCODE_HLT:
1578 intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1579 error = vm_handle_hlt(vm, vcpuid, intr_disabled, &retu);
1581 case VM_EXITCODE_PAGING:
1582 error = vm_handle_paging(vm, vcpuid, &retu);
1584 case VM_EXITCODE_INST_EMUL:
1585 error = vm_handle_inst_emul(vm, vcpuid, &retu);
1587 case VM_EXITCODE_INOUT:
1588 case VM_EXITCODE_INOUT_STR:
1589 error = vm_handle_inout(vm, vcpuid, vme, &retu);
1591 case VM_EXITCODE_MONITOR:
1592 case VM_EXITCODE_MWAIT:
1593 vm_inject_ud(vm, vcpuid);
1596 retu = true; /* handled in userland */
1601 if (error == 0 && retu == false)
1604 VCPU_CTR2(vm, vcpuid, "retu %d/%d", error, vme->exitcode);
1606 /* copy the exit information */
1607 bcopy(vme, &vmrun->vm_exit, sizeof(struct vm_exit));
1612 vm_restart_instruction(void *arg, int vcpuid)
1616 enum vcpu_state state;
1621 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1624 vcpu = &vm->vcpu[vcpuid];
1625 state = vcpu_get_state(vm, vcpuid, NULL);
1626 if (state == VCPU_RUNNING) {
1628 * When a vcpu is "running" the next instruction is determined
1629 * by adding 'rip' and 'inst_length' in the vcpu's 'exitinfo'.
1630 * Thus setting 'inst_length' to zero will cause the current
1631 * instruction to be restarted.
1633 vcpu->exitinfo.inst_length = 0;
1634 VCPU_CTR1(vm, vcpuid, "restarting instruction at %#lx by "
1635 "setting inst_length to zero", vcpu->exitinfo.rip);
1636 } else if (state == VCPU_FROZEN) {
1638 * When a vcpu is "frozen" it is outside the critical section
1639 * around VMRUN() and 'nextrip' points to the next instruction.
1640 * Thus instruction restart is achieved by setting 'nextrip'
1641 * to the vcpu's %rip.
1643 error = vm_get_register(vm, vcpuid, VM_REG_GUEST_RIP, &rip);
1644 KASSERT(!error, ("%s: error %d getting rip", __func__, error));
1645 VCPU_CTR2(vm, vcpuid, "restarting instruction by updating "
1646 "nextrip from %#lx to %#lx", vcpu->nextrip, rip);
1647 vcpu->nextrip = rip;
1649 panic("%s: invalid state %d", __func__, state);
1655 vm_exit_intinfo(struct vm *vm, int vcpuid, uint64_t info)
1660 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1663 vcpu = &vm->vcpu[vcpuid];
1665 if (info & VM_INTINFO_VALID) {
1666 type = info & VM_INTINFO_TYPE;
1667 vector = info & 0xff;
1668 if (type == VM_INTINFO_NMI && vector != IDT_NMI)
1670 if (type == VM_INTINFO_HWEXCEPTION && vector >= 32)
1672 if (info & VM_INTINFO_RSVD)
1677 VCPU_CTR2(vm, vcpuid, "%s: info1(%#lx)", __func__, info);
1678 vcpu->exitintinfo = info;
1688 #define IDT_VE 20 /* Virtualization Exception (Intel specific) */
1690 static enum exc_class
1691 exception_class(uint64_t info)
1695 KASSERT(info & VM_INTINFO_VALID, ("intinfo must be valid: %#lx", info));
1696 type = info & VM_INTINFO_TYPE;
1697 vector = info & 0xff;
1699 /* Table 6-4, "Interrupt and Exception Classes", Intel SDM, Vol 3 */
1701 case VM_INTINFO_HWINTR:
1702 case VM_INTINFO_SWINTR:
1703 case VM_INTINFO_NMI:
1704 return (EXC_BENIGN);
1707 * Hardware exception.
1709 * SVM and VT-x use identical type values to represent NMI,
1710 * hardware interrupt and software interrupt.
1712 * SVM uses type '3' for all exceptions. VT-x uses type '3'
1713 * for exceptions except #BP and #OF. #BP and #OF use a type
1714 * value of '5' or '6'. Therefore we don't check for explicit
1715 * values of 'type' to classify 'intinfo' into a hardware
1724 return (EXC_PAGEFAULT);
1730 return (EXC_CONTRIBUTORY);
1732 return (EXC_BENIGN);
1737 nested_fault(struct vm *vm, int vcpuid, uint64_t info1, uint64_t info2,
1740 enum exc_class exc1, exc2;
1743 KASSERT(info1 & VM_INTINFO_VALID, ("info1 %#lx is not valid", info1));
1744 KASSERT(info2 & VM_INTINFO_VALID, ("info2 %#lx is not valid", info2));
1747 * If an exception occurs while attempting to call the double-fault
1748 * handler the processor enters shutdown mode (aka triple fault).
1750 type1 = info1 & VM_INTINFO_TYPE;
1751 vector1 = info1 & 0xff;
1752 if (type1 == VM_INTINFO_HWEXCEPTION && vector1 == IDT_DF) {
1753 VCPU_CTR2(vm, vcpuid, "triple fault: info1(%#lx), info2(%#lx)",
1755 vm_suspend(vm, VM_SUSPEND_TRIPLEFAULT);
1761 * Table 6-5 "Conditions for Generating a Double Fault", Intel SDM, Vol3
1763 exc1 = exception_class(info1);
1764 exc2 = exception_class(info2);
1765 if ((exc1 == EXC_CONTRIBUTORY && exc2 == EXC_CONTRIBUTORY) ||
1766 (exc1 == EXC_PAGEFAULT && exc2 != EXC_BENIGN)) {
1767 /* Convert nested fault into a double fault. */
1769 *retinfo |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1770 *retinfo |= VM_INTINFO_DEL_ERRCODE;
1772 /* Handle exceptions serially */
1779 vcpu_exception_intinfo(struct vcpu *vcpu)
1783 if (vcpu->exception_pending) {
1784 info = vcpu->exc_vector & 0xff;
1785 info |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
1786 if (vcpu->exc_errcode_valid) {
1787 info |= VM_INTINFO_DEL_ERRCODE;
1788 info |= (uint64_t)vcpu->exc_errcode << 32;
1795 vm_entry_intinfo(struct vm *vm, int vcpuid, uint64_t *retinfo)
1798 uint64_t info1, info2;
1801 KASSERT(vcpuid >= 0 && vcpuid < VM_MAXCPU, ("invalid vcpu %d", vcpuid));
1803 vcpu = &vm->vcpu[vcpuid];
1805 info1 = vcpu->exitintinfo;
1806 vcpu->exitintinfo = 0;
1809 if (vcpu->exception_pending) {
1810 info2 = vcpu_exception_intinfo(vcpu);
1811 vcpu->exception_pending = 0;
1812 VCPU_CTR2(vm, vcpuid, "Exception %d delivered: %#lx",
1813 vcpu->exc_vector, info2);
1816 if ((info1 & VM_INTINFO_VALID) && (info2 & VM_INTINFO_VALID)) {
1817 valid = nested_fault(vm, vcpuid, info1, info2, retinfo);
1818 } else if (info1 & VM_INTINFO_VALID) {
1821 } else if (info2 & VM_INTINFO_VALID) {
1829 VCPU_CTR4(vm, vcpuid, "%s: info1(%#lx), info2(%#lx), "
1830 "retinfo(%#lx)", __func__, info1, info2, *retinfo);
1837 vm_get_intinfo(struct vm *vm, int vcpuid, uint64_t *info1, uint64_t *info2)
1841 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1844 vcpu = &vm->vcpu[vcpuid];
1845 *info1 = vcpu->exitintinfo;
1846 *info2 = vcpu_exception_intinfo(vcpu);
1851 vm_inject_exception(struct vm *vm, int vcpuid, int vector, int errcode_valid,
1852 uint32_t errcode, int restart_instruction)
1858 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1861 if (vector < 0 || vector >= 32)
1865 * A double fault exception should never be injected directly into
1866 * the guest. It is a derived exception that results from specific
1867 * combinations of nested faults.
1869 if (vector == IDT_DF)
1872 vcpu = &vm->vcpu[vcpuid];
1874 if (vcpu->exception_pending) {
1875 VCPU_CTR2(vm, vcpuid, "Unable to inject exception %d due to "
1876 "pending exception %d", vector, vcpu->exc_vector);
1880 if (errcode_valid) {
1882 * Exceptions don't deliver an error code in real mode.
1884 error = vm_get_register(vm, vcpuid, VM_REG_GUEST_CR0, ®val);
1885 KASSERT(!error, ("%s: error %d getting CR0", __func__, error));
1886 if (!(regval & CR0_PE))
1891 * From section 26.6.1 "Interruptibility State" in Intel SDM:
1893 * Event blocking by "STI" or "MOV SS" is cleared after guest executes
1894 * one instruction or incurs an exception.
1896 error = vm_set_register(vm, vcpuid, VM_REG_GUEST_INTR_SHADOW, 0);
1897 KASSERT(error == 0, ("%s: error %d clearing interrupt shadow",
1900 if (restart_instruction)
1901 vm_restart_instruction(vm, vcpuid);
1903 vcpu->exception_pending = 1;
1904 vcpu->exc_vector = vector;
1905 vcpu->exc_errcode = errcode;
1906 vcpu->exc_errcode_valid = errcode_valid;
1907 VCPU_CTR1(vm, vcpuid, "Exception %d pending", vector);
1912 vm_inject_fault(void *vmarg, int vcpuid, int vector, int errcode_valid,
1916 int error, restart_instruction;
1919 restart_instruction = 1;
1921 error = vm_inject_exception(vm, vcpuid, vector, errcode_valid,
1922 errcode, restart_instruction);
1923 KASSERT(error == 0, ("vm_inject_exception error %d", error));
1927 vm_inject_pf(void *vmarg, int vcpuid, int error_code, uint64_t cr2)
1933 VCPU_CTR2(vm, vcpuid, "Injecting page fault: error_code %#x, cr2 %#lx",
1936 error = vm_set_register(vm, vcpuid, VM_REG_GUEST_CR2, cr2);
1937 KASSERT(error == 0, ("vm_set_register(cr2) error %d", error));
1939 vm_inject_fault(vm, vcpuid, IDT_PF, 1, error_code);
1942 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
1945 vm_inject_nmi(struct vm *vm, int vcpuid)
1949 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1952 vcpu = &vm->vcpu[vcpuid];
1954 vcpu->nmi_pending = 1;
1955 vcpu_notify_event(vm, vcpuid, false);
1960 vm_nmi_pending(struct vm *vm, int vcpuid)
1964 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1965 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1967 vcpu = &vm->vcpu[vcpuid];
1969 return (vcpu->nmi_pending);
1973 vm_nmi_clear(struct vm *vm, int vcpuid)
1977 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1978 panic("vm_nmi_pending: invalid vcpuid %d", vcpuid);
1980 vcpu = &vm->vcpu[vcpuid];
1982 if (vcpu->nmi_pending == 0)
1983 panic("vm_nmi_clear: inconsistent nmi_pending state");
1985 vcpu->nmi_pending = 0;
1986 vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
1989 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
1992 vm_inject_extint(struct vm *vm, int vcpuid)
1996 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
1999 vcpu = &vm->vcpu[vcpuid];
2001 vcpu->extint_pending = 1;
2002 vcpu_notify_event(vm, vcpuid, false);
2007 vm_extint_pending(struct vm *vm, int vcpuid)
2011 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2012 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
2014 vcpu = &vm->vcpu[vcpuid];
2016 return (vcpu->extint_pending);
2020 vm_extint_clear(struct vm *vm, int vcpuid)
2024 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2025 panic("vm_extint_pending: invalid vcpuid %d", vcpuid);
2027 vcpu = &vm->vcpu[vcpuid];
2029 if (vcpu->extint_pending == 0)
2030 panic("vm_extint_clear: inconsistent extint_pending state");
2032 vcpu->extint_pending = 0;
2033 vmm_stat_incr(vm, vcpuid, VCPU_EXTINT_COUNT, 1);
2037 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
2039 if (vcpu < 0 || vcpu >= VM_MAXCPU)
2042 if (type < 0 || type >= VM_CAP_MAX)
2045 return (VMGETCAP(vm->cookie, vcpu, type, retval));
2049 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
2051 if (vcpu < 0 || vcpu >= VM_MAXCPU)
2054 if (type < 0 || type >= VM_CAP_MAX)
2057 return (VMSETCAP(vm->cookie, vcpu, type, val));
2061 vm_lapic(struct vm *vm, int cpu)
2063 return (vm->vcpu[cpu].vlapic);
2067 vm_ioapic(struct vm *vm)
2070 return (vm->vioapic);
2074 vm_hpet(struct vm *vm)
2081 vmm_is_pptdev(int bus, int slot, int func)
2085 char *val, *cp, *cp2;
2089 * The length of an environment variable is limited to 128 bytes which
2090 * puts an upper limit on the number of passthru devices that may be
2091 * specified using a single environment variable.
2093 * Work around this by scanning multiple environment variable
2094 * names instead of a single one - yuck!
2096 const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
2098 /* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
2100 for (i = 0; names[i] != NULL && !found; i++) {
2101 cp = val = getenv(names[i]);
2102 while (cp != NULL && *cp != '\0') {
2103 if ((cp2 = strchr(cp, ' ')) != NULL)
2106 n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
2107 if (n == 3 && bus == b && slot == s && func == f) {
2123 vm_iommu_domain(struct vm *vm)
2130 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate,
2136 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2137 panic("vm_set_run_state: invalid vcpuid %d", vcpuid);
2139 vcpu = &vm->vcpu[vcpuid];
2142 error = vcpu_set_state_locked(vm, vcpuid, newstate, from_idle);
2149 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
2152 enum vcpu_state state;
2154 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2155 panic("vm_get_run_state: invalid vcpuid %d", vcpuid);
2157 vcpu = &vm->vcpu[vcpuid];
2160 state = vcpu->state;
2161 if (hostcpu != NULL)
2162 *hostcpu = vcpu->hostcpu;
2169 vm_activate_cpu(struct vm *vm, int vcpuid)
2172 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2175 if (CPU_ISSET(vcpuid, &vm->active_cpus))
2178 VCPU_CTR0(vm, vcpuid, "activated");
2179 CPU_SET_ATOMIC(vcpuid, &vm->active_cpus);
2184 vm_active_cpus(struct vm *vm)
2187 return (vm->active_cpus);
2191 vm_suspended_cpus(struct vm *vm)
2194 return (vm->suspended_cpus);
2198 vcpu_stats(struct vm *vm, int vcpuid)
2201 return (vm->vcpu[vcpuid].stats);
2205 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
2207 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2210 *state = vm->vcpu[vcpuid].x2apic_state;
2216 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
2218 if (vcpuid < 0 || vcpuid >= VM_MAXCPU)
2221 if (state >= X2APIC_STATE_LAST)
2224 vm->vcpu[vcpuid].x2apic_state = state;
2226 vlapic_set_x2apic_state(vm, vcpuid, state);
2232 * This function is called to ensure that a vcpu "sees" a pending event
2233 * as soon as possible:
2234 * - If the vcpu thread is sleeping then it is woken up.
2235 * - If the vcpu is running on a different host_cpu then an IPI will be directed
2236 * to the host_cpu to cause the vcpu to trap into the hypervisor.
2239 vcpu_notify_event_locked(struct vcpu *vcpu, bool lapic_intr)
2243 hostcpu = vcpu->hostcpu;
2244 if (vcpu->state == VCPU_RUNNING) {
2245 KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
2246 if (hostcpu != curcpu) {
2248 vlapic_post_intr(vcpu->vlapic, hostcpu,
2251 ipi_cpu(hostcpu, vmm_ipinum);
2255 * If the 'vcpu' is running on 'curcpu' then it must
2256 * be sending a notification to itself (e.g. SELF_IPI).
2257 * The pending event will be picked up when the vcpu
2258 * transitions back to guest context.
2262 KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
2263 "with hostcpu %d", vcpu->state, hostcpu));
2264 if (vcpu->state == VCPU_SLEEPING)
2270 vcpu_notify_event(struct vm *vm, int vcpuid, bool lapic_intr)
2272 struct vcpu *vcpu = &vm->vcpu[vcpuid];
2275 vcpu_notify_event_locked(vcpu, lapic_intr);
2280 vm_get_vmspace(struct vm *vm)
2283 return (vm->vmspace);
2287 vm_apicid2vcpuid(struct vm *vm, int apicid)
2290 * XXX apic id is assumed to be numerically identical to vcpu id
2296 vm_smp_rendezvous(struct vm *vm, int vcpuid, cpuset_t dest,
2297 vm_rendezvous_func_t func, void *arg)
2302 * Enforce that this function is called without any locks
2304 WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
2305 KASSERT(vcpuid == -1 || (vcpuid >= 0 && vcpuid < VM_MAXCPU),
2306 ("vm_smp_rendezvous: invalid vcpuid %d", vcpuid));
2309 mtx_lock(&vm->rendezvous_mtx);
2310 if (vm->rendezvous_func != NULL) {
2312 * If a rendezvous is already in progress then we need to
2313 * call the rendezvous handler in case this 'vcpuid' is one
2314 * of the targets of the rendezvous.
2316 RENDEZVOUS_CTR0(vm, vcpuid, "Rendezvous already in progress");
2317 mtx_unlock(&vm->rendezvous_mtx);
2318 vm_handle_rendezvous(vm, vcpuid);
2321 KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
2322 "rendezvous is still in progress"));
2324 RENDEZVOUS_CTR0(vm, vcpuid, "Initiating rendezvous");
2325 vm->rendezvous_req_cpus = dest;
2326 CPU_ZERO(&vm->rendezvous_done_cpus);
2327 vm->rendezvous_arg = arg;
2328 vm_set_rendezvous_func(vm, func);
2329 mtx_unlock(&vm->rendezvous_mtx);
2332 * Wake up any sleeping vcpus and trigger a VM-exit in any running
2333 * vcpus so they handle the rendezvous as soon as possible.
2335 for (i = 0; i < VM_MAXCPU; i++) {
2336 if (CPU_ISSET(i, &dest))
2337 vcpu_notify_event(vm, i, false);
2340 vm_handle_rendezvous(vm, vcpuid);
2344 vm_atpic(struct vm *vm)
2346 return (vm->vatpic);
2350 vm_atpit(struct vm *vm)
2352 return (vm->vatpit);
2356 vm_pmtmr(struct vm *vm)
2359 return (vm->vpmtmr);
2363 vm_rtc(struct vm *vm)
2370 vm_segment_name(int seg)
2372 static enum vm_reg_name seg_names[] = {
2381 KASSERT(seg >= 0 && seg < nitems(seg_names),
2382 ("%s: invalid segment encoding %d", __func__, seg));
2383 return (seg_names[seg]);
2387 vm_copy_teardown(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo,
2392 for (idx = 0; idx < num_copyinfo; idx++) {
2393 if (copyinfo[idx].cookie != NULL)
2394 vm_gpa_release(copyinfo[idx].cookie);
2396 bzero(copyinfo, num_copyinfo * sizeof(struct vm_copyinfo));
2400 vm_copy_setup(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
2401 uint64_t gla, size_t len, int prot, struct vm_copyinfo *copyinfo,
2402 int num_copyinfo, int *fault)
2404 int error, idx, nused;
2405 size_t n, off, remaining;
2409 bzero(copyinfo, sizeof(struct vm_copyinfo) * num_copyinfo);
2413 while (remaining > 0) {
2414 KASSERT(nused < num_copyinfo, ("insufficient vm_copyinfo"));
2415 error = vm_gla2gpa(vm, vcpuid, paging, gla, prot, &gpa, fault);
2416 if (error || *fault)
2418 off = gpa & PAGE_MASK;
2419 n = min(remaining, PAGE_SIZE - off);
2420 copyinfo[nused].gpa = gpa;
2421 copyinfo[nused].len = n;
2427 for (idx = 0; idx < nused; idx++) {
2428 hva = vm_gpa_hold(vm, copyinfo[idx].gpa, copyinfo[idx].len,
2432 copyinfo[idx].hva = hva;
2433 copyinfo[idx].cookie = cookie;
2437 vm_copy_teardown(vm, vcpuid, copyinfo, num_copyinfo);
2446 vm_copyin(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo, void *kaddr,
2455 bcopy(copyinfo[idx].hva, dst, copyinfo[idx].len);
2456 len -= copyinfo[idx].len;
2457 dst += copyinfo[idx].len;
2463 vm_copyout(struct vm *vm, int vcpuid, const void *kaddr,
2464 struct vm_copyinfo *copyinfo, size_t len)
2472 bcopy(src, copyinfo[idx].hva, copyinfo[idx].len);
2473 len -= copyinfo[idx].len;
2474 src += copyinfo[idx].len;
2480 * Return the amount of in-use and wired memory for the VM. Since
2481 * these are global stats, only return the values with for vCPU 0
2483 VMM_STAT_DECLARE(VMM_MEM_RESIDENT);
2484 VMM_STAT_DECLARE(VMM_MEM_WIRED);
2487 vm_get_rescnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2491 vmm_stat_set(vm, vcpu, VMM_MEM_RESIDENT,
2492 PAGE_SIZE * vmspace_resident_count(vm->vmspace));
2497 vm_get_wiredcnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
2501 vmm_stat_set(vm, vcpu, VMM_MEM_WIRED,
2502 PAGE_SIZE * pmap_wired_count(vmspace_pmap(vm->vmspace)));
2506 VMM_STAT_FUNC(VMM_MEM_RESIDENT, "Resident memory", vm_get_rescnt);
2507 VMM_STAT_FUNC(VMM_MEM_WIRED, "Wired memory", vm_get_wiredcnt);