vmx.c revision 284894
11722Sjkh/*-
21722Sjkh * Copyright (c) 2011 NetApp, Inc.
31722Sjkh * All rights reserved.
41722Sjkh *
51722Sjkh * Redistribution and use in source and binary forms, with or without
61722Sjkh * modification, are permitted provided that the following conditions
71722Sjkh * are met:
81722Sjkh * 1. Redistributions of source code must retain the above copyright
91722Sjkh *    notice, this list of conditions and the following disclaimer.
101722Sjkh * 2. Redistributions in binary form must reproduce the above copyright
111722Sjkh *    notice, this list of conditions and the following disclaimer in the
121722Sjkh *    documentation and/or other materials provided with the distribution.
131722Sjkh *
141722Sjkh * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
151722Sjkh * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
161722Sjkh * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
171722Sjkh * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
181722Sjkh * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
191722Sjkh * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
201722Sjkh * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
211722Sjkh * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
221722Sjkh * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
231722Sjkh * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
241722Sjkh * SUCH DAMAGE.
251722Sjkh *
261722Sjkh * $FreeBSD: stable/10/sys/amd64/vmm/intel/vmx.c 284894 2015-06-27 22:48:22Z neel $
271722Sjkh */
281722Sjkh
291722Sjkh#include <sys/cdefs.h>
301722Sjkh__FBSDID("$FreeBSD: stable/10/sys/amd64/vmm/intel/vmx.c 284894 2015-06-27 22:48:22Z neel $");
318857Srgrimes
321722Sjkh#include <sys/param.h>
33237625Sobrien#include <sys/systm.h>
34237625Sobrien#include <sys/smp.h>
35237625Sobrien#include <sys/kernel.h>
36237625Sobrien#include <sys/malloc.h>
37237625Sobrien#include <sys/pcpu.h>
3870884Sjoe#include <sys/proc.h>
3970884Sjoe#include <sys/sysctl.h>
4029453Scharnier
4129453Scharnier#include <vm/vm.h>
4270124Sjoe#include <vm/pmap.h>
4329453Scharnier
441722Sjkh#include <machine/psl.h>
4529453Scharnier#include <machine/cpufunc.h>
461722Sjkh#include <machine/md_var.h>
471722Sjkh#include <machine/segments.h>
481722Sjkh#include <machine/smp.h>
491722Sjkh#include <machine/specialreg.h>
501722Sjkh#include <machine/vmparam.h>
511722Sjkh
521722Sjkh#include <machine/vmm.h>
531722Sjkh#include <machine/vmm_dev.h>
541722Sjkh#include <machine/vmm_instruction_emul.h>
551722Sjkh#include "vmm_lapic.h"
561722Sjkh#include "vmm_host.h"
571722Sjkh#include "vmm_ioport.h"
581722Sjkh#include "vmm_ipi.h"
5970884Sjoe#include "vmm_ktr.h"
6070884Sjoe#include "vmm_stat.h"
611722Sjkh#include "vatpic.h"
621722Sjkh#include "vlapic.h"
631722Sjkh#include "vlapic_priv.h"
641722Sjkh
651722Sjkh#include "ept.h"
6670884Sjoe#include "vmx_cpufunc.h"
6770884Sjoe#include "vmx.h"
6870884Sjoe#include "vmx_msr.h"
6970884Sjoe#include "x86.h"
7070884Sjoe#include "vmx_controls.h"
7170884Sjoe
7270884Sjoe#define	PINBASED_CTLS_ONE_SETTING					\
7370884Sjoe	(PINBASED_EXTINT_EXITING	|				\
7470884Sjoe	 PINBASED_NMI_EXITING		|				\
7570884Sjoe	 PINBASED_VIRTUAL_NMI)
7670884Sjoe#define	PINBASED_CTLS_ZERO_SETTING	0
7793435Sluigi
78153687Sceri#define PROCBASED_CTLS_WINDOW_SETTING					\
7970884Sjoe	(PROCBASED_INT_WINDOW_EXITING	|				\
801722Sjkh	 PROCBASED_NMI_WINDOW_EXITING)
811722Sjkh
821722Sjkh#define	PROCBASED_CTLS_ONE_SETTING 					\
831722Sjkh	(PROCBASED_SECONDARY_CONTROLS	|				\
841722Sjkh	 PROCBASED_MWAIT_EXITING	|				\
8568750Sjoe	 PROCBASED_MONITOR_EXITING	|				\
8670884Sjoe	 PROCBASED_IO_EXITING		|				\
8770884Sjoe	 PROCBASED_MSR_BITMAPS		|				\
88153687Sceri	 PROCBASED_CTLS_WINDOW_SETTING	|				\
8970884Sjoe	 PROCBASED_CR8_LOAD_EXITING	|				\
901722Sjkh	 PROCBASED_CR8_STORE_EXITING)
911722Sjkh#define	PROCBASED_CTLS_ZERO_SETTING	\
921722Sjkh	(PROCBASED_CR3_LOAD_EXITING |	\
931722Sjkh	PROCBASED_CR3_STORE_EXITING |	\
9470884Sjoe	PROCBASED_IO_BITMAPS)
9570884Sjoe
96237574Sobrien#define	PROCBASED_CTLS2_ONE_SETTING	PROCBASED2_ENABLE_EPT
971722Sjkh#define	PROCBASED_CTLS2_ZERO_SETTING	0
981722Sjkh
991722Sjkh#define	VM_EXIT_CTLS_ONE_SETTING					\
10070884Sjoe	(VM_EXIT_HOST_LMA			|			\
1011722Sjkh	VM_EXIT_SAVE_EFER			|			\
10270884Sjoe	VM_EXIT_LOAD_EFER			|			\
1031722Sjkh	VM_EXIT_ACKNOWLEDGE_INTERRUPT)
1046696Sphk
1056696Sphk#define	VM_EXIT_CTLS_ZERO_SETTING	VM_EXIT_SAVE_DEBUG_CONTROLS
1061722Sjkh
1071722Sjkh#define	VM_ENTRY_CTLS_ONE_SETTING	(VM_ENTRY_LOAD_EFER)
108246256Spfg
1091722Sjkh#define	VM_ENTRY_CTLS_ZERO_SETTING					\
1101722Sjkh	(VM_ENTRY_LOAD_DEBUG_CONTROLS		|			\
111246256Spfg	VM_ENTRY_INTO_SMM			|			\
112246256Spfg	VM_ENTRY_DEACTIVATE_DUAL_MONITOR)
113153687Sceri
114153687Sceri#define	HANDLED		1
1151722Sjkh#define	UNHANDLED	0
116246261Spfg
1171722Sjkhstatic MALLOC_DEFINE(M_VMX, "vmx", "vmx");
1188857Srgrimesstatic MALLOC_DEFINE(M_VLAPIC, "vlapic", "vlapic");
1191722Sjkh
1201722SjkhSYSCTL_DECL(_hw_vmm);
1211722SjkhSYSCTL_NODE(_hw_vmm, OID_AUTO, vmx, CTLFLAG_RW, NULL, NULL);
122246261Spfg
1231722Sjkhint vmxon_enabled[MAXCPU];
124246261Spfgstatic char vmxon_region[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
125237625Sobrien
126237625Sobrienstatic uint32_t pinbased_ctls, procbased_ctls, procbased_ctls2;
1271722Sjkhstatic uint32_t exit_ctls, entry_ctls;
12870884Sjoe
12970884Sjoestatic uint64_t cr0_ones_mask, cr0_zeros_mask;
1301722SjkhSYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_ones_mask, CTLFLAG_RD,
13170884Sjoe	     &cr0_ones_mask, 0, NULL);
13270884SjoeSYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_zeros_mask, CTLFLAG_RD,
13370884Sjoe	     &cr0_zeros_mask, 0, NULL);
1348857Srgrimes
135237574Sobrienstatic uint64_t cr4_ones_mask, cr4_zeros_mask;
136237574SobrienSYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_ones_mask, CTLFLAG_RD,
137237574Sobrien	     &cr4_ones_mask, 0, NULL);
138237574SobrienSYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_zeros_mask, CTLFLAG_RD,
13970884Sjoe	     &cr4_zeros_mask, 0, NULL);
14070884Sjoe
14170884Sjoestatic int vmx_initialized;
14270884SjoeSYSCTL_INT(_hw_vmm_vmx, OID_AUTO, initialized, CTLFLAG_RD,
14370884Sjoe	   &vmx_initialized, 0, "Intel VMX initialized");
14470884Sjoe
14569413Sluigi/*
14670884Sjoe * Optional capabilities
14770884Sjoe */
14870884Sjoestatic SYSCTL_NODE(_hw_vmm_vmx, OID_AUTO, cap, CTLFLAG_RW, NULL, NULL);
14970884Sjoe
15070884Sjoestatic int cap_halt_exit;
15170884SjoeSYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, halt_exit, CTLFLAG_RD, &cap_halt_exit, 0,
15270884Sjoe    "HLT triggers a VM-exit");
15370884Sjoe
15470884Sjoestatic int cap_pause_exit;
15570884SjoeSYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, pause_exit, CTLFLAG_RD, &cap_pause_exit,
15670884Sjoe    0, "PAUSE triggers a VM-exit");
1571722Sjkh
15870884Sjoestatic int cap_unrestricted_guest;
15970884SjoeSYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, unrestricted_guest, CTLFLAG_RD,
16070884Sjoe    &cap_unrestricted_guest, 0, "Unrestricted guests");
16170884Sjoe
16270884Sjoestatic int cap_monitor_trap;
16370113SjoeSYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, monitor_trap, CTLFLAG_RD,
16470113Sjoe    &cap_monitor_trap, 0, "Monitor trap flag");
1651722Sjkh
16670884Sjoestatic int cap_invpcid;
16770884SjoeSYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, invpcid, CTLFLAG_RD, &cap_invpcid,
16870884Sjoe    0, "Guests are allowed to use INVPCID");
16970884Sjoe
17070884Sjoestatic int virtual_interrupt_delivery;
17170884SjoeSYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, virtual_interrupt_delivery, CTLFLAG_RD,
17270884Sjoe    &virtual_interrupt_delivery, 0, "APICv virtual interrupt delivery support");
17370884Sjoe
17470884Sjoestatic int posted_interrupts;
17570884SjoeSYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, posted_interrupts, CTLFLAG_RD,
17670884Sjoe    &posted_interrupts, 0, "APICv posted interrupt support");
17770884Sjoe
17870884Sjoestatic int pirvec;
17970884SjoeSYSCTL_INT(_hw_vmm_vmx, OID_AUTO, posted_interrupt_vector, CTLFLAG_RD,
18070884Sjoe    &pirvec, 0, "APICv posted interrupt vector");
18170884Sjoe
18270884Sjoestatic struct unrhdr *vpid_unr;
18370884Sjoestatic u_int vpid_alloc_failed;
18470884SjoeSYSCTL_UINT(_hw_vmm_vmx, OID_AUTO, vpid_alloc_failed, CTLFLAG_RD,
1851722Sjkh	    &vpid_alloc_failed, 0, NULL);
1861722Sjkh
18770884Sjoe/*
18870884Sjoe * Use the last page below 4GB as the APIC access address. This address is
1891722Sjkh * occupied by the boot firmware so it is guaranteed that it will not conflict
19070884Sjoe * with a page in system memory.
19170884Sjoe */
1921722Sjkh#define	APIC_ACCESS_ADDRESS	0xFFFFF000
19370884Sjoe
19470884Sjoestatic int vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc);
19570884Sjoestatic int vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval);
1961722Sjkhstatic int vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val);
19770884Sjoestatic void vmx_inject_pir(struct vlapic *vlapic);
1981722Sjkh
19970884Sjoe#ifdef KTR
2001722Sjkhstatic const char *
20170884Sjoeexit_reason_to_str(int reason)
20270884Sjoe{
20370884Sjoe	static char reasonbuf[32];
20470884Sjoe
2051722Sjkh	switch (reason) {
20670884Sjoe	case EXIT_REASON_EXCEPTION:
20770884Sjoe		return "exception";
2081722Sjkh	case EXIT_REASON_EXT_INTR:
20970884Sjoe		return "extint";
21070884Sjoe	case EXIT_REASON_TRIPLE_FAULT:
21170884Sjoe		return "triplefault";
21270884Sjoe	case EXIT_REASON_INIT:
21370884Sjoe		return "init";
21470884Sjoe	case EXIT_REASON_SIPI:
21570884Sjoe		return "sipi";
21670884Sjoe	case EXIT_REASON_IO_SMI:
21770884Sjoe		return "iosmi";
21870124Sjoe	case EXIT_REASON_SMI:
2191722Sjkh		return "smi";
22070884Sjoe	case EXIT_REASON_INTR_WINDOW:
22170884Sjoe		return "intrwindow";
22270884Sjoe	case EXIT_REASON_NMI_WINDOW:
2236696Sphk		return "nmiwindow";
22470884Sjoe	case EXIT_REASON_TASK_SWITCH:
2251722Sjkh		return "taskswitch";
22670884Sjoe	case EXIT_REASON_CPUID:
2271722Sjkh		return "cpuid";
2281722Sjkh	case EXIT_REASON_GETSEC:
2291722Sjkh		return "getsec";
230237625Sobrien	case EXIT_REASON_HLT:
231237625Sobrien		return "hlt";
2321722Sjkh	case EXIT_REASON_INVD:
23370884Sjoe		return "invd";
23470884Sjoe	case EXIT_REASON_INVLPG:
23570884Sjoe		return "invlpg";
23670884Sjoe	case EXIT_REASON_RDPMC:
23770884Sjoe		return "rdpmc";
2381722Sjkh	case EXIT_REASON_RDTSC:
2391722Sjkh		return "rdtsc";
2401722Sjkh	case EXIT_REASON_RSM:
2411722Sjkh		return "rsm";
2421722Sjkh	case EXIT_REASON_VMCALL:
2431722Sjkh		return "vmcall";
2441722Sjkh	case EXIT_REASON_VMCLEAR:
2451722Sjkh		return "vmclear";
2461722Sjkh	case EXIT_REASON_VMLAUNCH:
2471722Sjkh		return "vmlaunch";
2481722Sjkh	case EXIT_REASON_VMPTRLD:
2491722Sjkh		return "vmptrld";
250246256Spfg	case EXIT_REASON_VMPTRST:
2511722Sjkh		return "vmptrst";
2521722Sjkh	case EXIT_REASON_VMREAD:
2531722Sjkh		return "vmread";
2541722Sjkh	case EXIT_REASON_VMRESUME:
255153687Sceri		return "vmresume";
25668750Sjoe	case EXIT_REASON_VMWRITE:
2571722Sjkh		return "vmwrite";
2581722Sjkh	case EXIT_REASON_VMXOFF:
2591722Sjkh		return "vmxoff";
2601722Sjkh	case EXIT_REASON_VMXON:
2611722Sjkh		return "vmxon";
2621722Sjkh	case EXIT_REASON_CR_ACCESS:
263237625Sobrien		return "craccess";
264237625Sobrien	case EXIT_REASON_DR_ACCESS:
2651722Sjkh		return "draccess";
26670884Sjoe	case EXIT_REASON_INOUT:
26729453Scharnier		return "inout";
26870884Sjoe	case EXIT_REASON_RDMSR:
26970884Sjoe		return "rdmsr";
27070884Sjoe	case EXIT_REASON_WRMSR:
27170884Sjoe		return "wrmsr";
27270884Sjoe	case EXIT_REASON_INVAL_VMCS:
27370884Sjoe		return "invalvmcs";
2741722Sjkh	case EXIT_REASON_INVAL_MSR:
2751722Sjkh		return "invalmsr";
2761722Sjkh	case EXIT_REASON_MWAIT:
277237625Sobrien		return "mwait";
278237625Sobrien	case EXIT_REASON_MTF:
2791722Sjkh		return "mtf";
28070884Sjoe	case EXIT_REASON_MONITOR:
28170884Sjoe		return "monitor";
28270884Sjoe	case EXIT_REASON_PAUSE:
28370884Sjoe		return "pause";
28470884Sjoe	case EXIT_REASON_MCE_DURING_ENTRY:
2851722Sjkh		return "mce-during-entry";
28670884Sjoe	case EXIT_REASON_TPR:
28770884Sjoe		return "tpr";
28870884Sjoe	case EXIT_REASON_APIC_ACCESS:
2891722Sjkh		return "apic-access";
29070884Sjoe	case EXIT_REASON_GDTR_IDTR:
29170884Sjoe		return "gdtridtr";
29270884Sjoe	case EXIT_REASON_LDTR_TR:
29370884Sjoe		return "ldtrtr";
29470884Sjoe	case EXIT_REASON_EPT_FAULT:
2951722Sjkh		return "eptfault";
29670884Sjoe	case EXIT_REASON_EPT_MISCONFIG:
29770884Sjoe		return "eptmisconfig";
29870884Sjoe	case EXIT_REASON_INVEPT:
29970884Sjoe		return "invept";
30070884Sjoe	case EXIT_REASON_RDTSCP:
30170884Sjoe		return "rdtscp";
30270884Sjoe	case EXIT_REASON_VMX_PREEMPT:
30370884Sjoe		return "vmxpreempt";
30470884Sjoe	case EXIT_REASON_INVVPID:
30570884Sjoe		return "invvpid";
30670884Sjoe	case EXIT_REASON_WBINVD:
30770884Sjoe		return "wbinvd";
30870884Sjoe	case EXIT_REASON_XSETBV:
30970884Sjoe		return "xsetbv";
31070884Sjoe	case EXIT_REASON_APIC_WRITE:
31170884Sjoe		return "apic-write";
312153687Sceri	default:
313153687Sceri		snprintf(reasonbuf, sizeof(reasonbuf), "%d", reason);
31470884Sjoe		return (reasonbuf);
31570884Sjoe	}
31670884Sjoe}
31770884Sjoe#endif	/* KTR */
31870884Sjoe
31970884Sjoestatic int
32070884Sjoevmx_allow_x2apic_msrs(struct vmx *vmx)
32170884Sjoe{
32270884Sjoe	int i, error;
32370884Sjoe
32470884Sjoe	error = 0;
32570884Sjoe
32670884Sjoe	/*
32770884Sjoe	 * Allow readonly access to the following x2APIC MSRs from the guest.
32870884Sjoe	 */
32970884Sjoe	error += guest_msr_ro(vmx, MSR_APIC_ID);
33070884Sjoe	error += guest_msr_ro(vmx, MSR_APIC_VERSION);
33170884Sjoe	error += guest_msr_ro(vmx, MSR_APIC_LDR);
33270884Sjoe	error += guest_msr_ro(vmx, MSR_APIC_SVR);
33370884Sjoe
3341722Sjkh	for (i = 0; i < 8; i++)
33570884Sjoe		error += guest_msr_ro(vmx, MSR_APIC_ISR0 + i);
33670884Sjoe
33770884Sjoe	for (i = 0; i < 8; i++)
33870884Sjoe		error += guest_msr_ro(vmx, MSR_APIC_TMR0 + i);
3391722Sjkh
34070884Sjoe	for (i = 0; i < 8; i++)
3411722Sjkh		error += guest_msr_ro(vmx, MSR_APIC_IRR0 + i);
3421722Sjkh
3431722Sjkh	error += guest_msr_ro(vmx, MSR_APIC_ESR);
344237625Sobrien	error += guest_msr_ro(vmx, MSR_APIC_LVT_TIMER);
345246256Spfg	error += guest_msr_ro(vmx, MSR_APIC_LVT_THERMAL);
3461722Sjkh	error += guest_msr_ro(vmx, MSR_APIC_LVT_PCINT);
34770884Sjoe	error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT0);
3481722Sjkh	error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT1);
349246256Spfg	error += guest_msr_ro(vmx, MSR_APIC_LVT_ERROR);
35070884Sjoe	error += guest_msr_ro(vmx, MSR_APIC_ICR_TIMER);
3511722Sjkh	error += guest_msr_ro(vmx, MSR_APIC_DCR_TIMER);
35270884Sjoe	error += guest_msr_ro(vmx, MSR_APIC_ICR);
353246256Spfg
35470884Sjoe	/*
35570884Sjoe	 * Allow TPR, EOI and SELF_IPI MSRs to be read and written by the guest.
35670884Sjoe	 *
35770884Sjoe	 * These registers get special treatment described in the section
35870884Sjoe	 * "Virtualizing MSR-Based APIC Accesses".
35970884Sjoe	 */
36070884Sjoe	error += guest_msr_rw(vmx, MSR_APIC_TPR);
36170884Sjoe	error += guest_msr_rw(vmx, MSR_APIC_EOI);
362246256Spfg	error += guest_msr_rw(vmx, MSR_APIC_SELF_IPI);
36370884Sjoe
36470884Sjoe	return (error);
36570884Sjoe}
36670884Sjoe
36770884Sjoeu_long
36870884Sjoevmx_fix_cr0(u_long cr0)
36970884Sjoe{
37070884Sjoe
37170884Sjoe	return ((cr0 | cr0_ones_mask) & ~cr0_zeros_mask);
37270884Sjoe}
3731722Sjkh
3741722Sjkhu_long
3751722Sjkhvmx_fix_cr4(u_long cr4)
376237625Sobrien{
377237625Sobrien
3781722Sjkh	return ((cr4 | cr4_ones_mask) & ~cr4_zeros_mask);
37970884Sjoe}
3801722Sjkh
38170884Sjoestatic void
38270884Sjoevpid_free(int vpid)
38370884Sjoe{
38470884Sjoe	if (vpid < 0 || vpid > 0xffff)
38570884Sjoe		panic("vpid_free: invalid vpid %d", vpid);
38670884Sjoe
38770884Sjoe	/*
38870884Sjoe	 * VPIDs [0,VM_MAXCPU] are special and are not allocated from
3891722Sjkh	 * the unit number allocator.
3901722Sjkh	 */
3911722Sjkh
3921722Sjkh	if (vpid > VM_MAXCPU)
393237625Sobrien		free_unr(vpid_unr, vpid);
394237625Sobrien}
3951722Sjkh
39670884Sjoestatic void
3971722Sjkhvpid_alloc(uint16_t *vpid, int num)
39870884Sjoe{
39970884Sjoe	int i, x;
4001722Sjkh
4011722Sjkh	if (num <= 0 || num > VM_MAXCPU)
4021722Sjkh		panic("invalid number of vpids requested: %d", num);
403237625Sobrien
404237625Sobrien	/*
4051722Sjkh	 * If the "enable vpid" execution control is not enabled then the
40670884Sjoe	 * VPID is required to be 0 for all vcpus.
4071722Sjkh	 */
40870884Sjoe	if ((procbased_ctls2 & PROCBASED2_ENABLE_VPID) == 0) {
4091722Sjkh		for (i = 0; i < num; i++)
41070884Sjoe			vpid[i] = 0;
41170884Sjoe		return;
41270884Sjoe	}
4131722Sjkh
41470884Sjoe	/*
41570884Sjoe	 * Allocate a unique VPID for each vcpu from the unit number allocator.
41670884Sjoe	 */
41770884Sjoe	for (i = 0; i < num; i++) {
41870884Sjoe		x = alloc_unr(vpid_unr);
41970884Sjoe		if (x == -1)
42070884Sjoe			break;
4211722Sjkh		else
42270884Sjoe			vpid[i] = x;
42370884Sjoe	}
42470884Sjoe
42570884Sjoe	if (i < num) {
42670884Sjoe		atomic_add_int(&vpid_alloc_failed, 1);
4271722Sjkh
42870884Sjoe		/*
42970884Sjoe		 * If the unit number allocator does not have enough unique
43070884Sjoe		 * VPIDs then we need to allocate from the [1,VM_MAXCPU] range.
43170884Sjoe		 *
43270884Sjoe		 * These VPIDs are not be unique across VMs but this does not
43393435Sluigi		 * affect correctness because the combined mappings are also
434153687Sceri		 * tagged with the EP4TA which is unique for each VM.
43570884Sjoe		 *
43670884Sjoe		 * It is still sub-optimal because the invvpid will invalidate
43770884Sjoe		 * combined mappings for a particular VPID across all EP4TAs.
43870884Sjoe		 */
43970884Sjoe		while (i-- > 0)
44070884Sjoe			vpid_free(vpid[i]);
44170884Sjoe
4421722Sjkh		for (i = 0; i < num; i++)
4431722Sjkh			vpid[i] = i + 1;
4441722Sjkh	}
445237625Sobrien}
446237625Sobrien
4471722Sjkhstatic void
44870884Sjoevpid_init(void)
44970884Sjoe{
4501722Sjkh	/*
45170884Sjoe	 * VPID 0 is required when the "enable VPID" execution control is
45270884Sjoe	 * disabled.
45370884Sjoe	 *
45470884Sjoe	 * VPIDs [1,VM_MAXCPU] are used as the "overflow namespace" when the
45570884Sjoe	 * unit number allocator does not have sufficient unique VPIDs to
45670884Sjoe	 * satisfy the allocation.
45770884Sjoe	 *
45870884Sjoe	 * The remaining VPIDs are managed by the unit number allocator.
45970884Sjoe	 */
46070884Sjoe	vpid_unr = new_unrhdr(VM_MAXCPU + 1, 0xffff, NULL);
46170884Sjoe}
46270884Sjoe
46370884Sjoestatic void
4641722Sjkhvmx_disable(void *arg __unused)
4651722Sjkh{
4661722Sjkh	struct invvpid_desc invvpid_desc = { 0 };
467237625Sobrien	struct invept_desc invept_desc = { 0 };
468237625Sobrien
4691722Sjkh	if (vmxon_enabled[curcpu]) {
47070884Sjoe		/*
4711722Sjkh		 * See sections 25.3.3.3 and 25.3.3.4 in Intel Vol 3b.
472153687Sceri		 *
47370884Sjoe		 * VMXON or VMXOFF are not required to invalidate any TLB
474153687Sceri		 * caching structures. This prevents potential retention of
475153687Sceri		 * cached information in the TLB between distinct VMX episodes.
476153687Sceri		 */
477153687Sceri		invvpid(INVVPID_TYPE_ALL_CONTEXTS, invvpid_desc);
478153687Sceri		invept(INVEPT_TYPE_ALL_CONTEXTS, invept_desc);
4791722Sjkh		vmxoff();
4801722Sjkh	}
4811722Sjkh	load_cr4(rcr4() & ~CR4_VMXE);
482237625Sobrien}
483237625Sobrien
484153687Sceristatic int
485153687Scerivmx_cleanup(void)
486153687Sceri{
487153687Sceri
488153687Sceri	if (pirvec != 0)
489153687Sceri		vmm_ipi_free(pirvec);
490153687Sceri
491153687Sceri	if (vpid_unr != NULL) {
492153687Sceri		delete_unrhdr(vpid_unr);
493153687Sceri		vpid_unr = NULL;
494153687Sceri	}
495153687Sceri
496153687Sceri	smp_rendezvous(NULL, vmx_disable, NULL, NULL);
497237625Sobrien
498237625Sobrien	return (0);
49968750Sjoe}
50070884Sjoe
50168750Sjoestatic void
50270884Sjoevmx_enable(void *arg __unused)
50370884Sjoe{
50468750Sjoe	int error;
50568750Sjoe	uint64_t feature_control;
50668750Sjoe
507237625Sobrien	feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
508237625Sobrien	if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 0 ||
5091722Sjkh	    (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
51070884Sjoe		wrmsr(MSR_IA32_FEATURE_CONTROL,
51170884Sjoe		    feature_control | IA32_FEATURE_CONTROL_VMX_EN |
5121722Sjkh		    IA32_FEATURE_CONTROL_LOCK);
51370884Sjoe	}
51470884Sjoe
51570884Sjoe	load_cr4(rcr4() | CR4_VMXE);
5161722Sjkh
51770884Sjoe	*(uint32_t *)vmxon_region[curcpu] = vmx_revision();
51870884Sjoe	error = vmxon(vmxon_region[curcpu]);
51970884Sjoe	if (error == 0)
52070884Sjoe		vmxon_enabled[curcpu] = 1;
52170884Sjoe}
5221722Sjkh
52370884Sjoestatic void
52470884Sjoevmx_restore(void)
52570884Sjoe{
52670884Sjoe
52770884Sjoe	if (vmxon_enabled[curcpu])
52870884Sjoe		vmxon(vmxon_region[curcpu]);
52970884Sjoe}
53070884Sjoe
53170884Sjoestatic int
53270884Sjoevmx_init(int ipinum)
53370884Sjoe{
53470884Sjoe	int error, use_tpr_shadow;
53570884Sjoe	uint64_t basic, fixed0, fixed1, feature_control;
53670884Sjoe	uint32_t tmp, procbased2_vid_bits;
53770884Sjoe
53870884Sjoe	/* CPUID.1:ECX[bit 5] must be 1 for processor to support VMX */
53970884Sjoe	if (!(cpu_feature2 & CPUID2_VMX)) {
54070884Sjoe		printf("vmx_init: processor does not support VMX operation\n");
54170884Sjoe		return (ENXIO);
54270884Sjoe	}
54370884Sjoe
54470884Sjoe	/*
54570884Sjoe	 * Verify that MSR_IA32_FEATURE_CONTROL lock and VMXON enable bits
54670884Sjoe	 * are set (bits 0 and 2 respectively).
54770884Sjoe	 */
54870884Sjoe	feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
54970884Sjoe	if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 1 &&
55070884Sjoe	    (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
55170884Sjoe		printf("vmx_init: VMX operation disabled by BIOS\n");
55270884Sjoe		return (ENXIO);
55370884Sjoe	}
55470884Sjoe
55570884Sjoe	/*
55670884Sjoe	 * Verify capabilities MSR_VMX_BASIC:
55770884Sjoe	 * - bit 54 indicates support for INS/OUTS decoding
55870884Sjoe	 */
55993435Sluigi	basic = rdmsr(MSR_VMX_BASIC);
56093435Sluigi	if ((basic & (1UL << 54)) == 0) {
56193435Sluigi		printf("vmx_init: processor does not support desired basic "
56270884Sjoe		    "capabilities\n");
56370884Sjoe		return (EINVAL);
56470884Sjoe	}
56570884Sjoe
56670884Sjoe	/* Check support for primary processor-based VM-execution controls */
56770884Sjoe	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
5681722Sjkh			       MSR_VMX_TRUE_PROCBASED_CTLS,
5691722Sjkh			       PROCBASED_CTLS_ONE_SETTING,
57070884Sjoe			       PROCBASED_CTLS_ZERO_SETTING, &procbased_ctls);
5711722Sjkh	if (error) {
57270884Sjoe		printf("vmx_init: processor does not support desired primary "
5731722Sjkh		       "processor-based controls\n");
5741722Sjkh		return (error);
5751722Sjkh	}
5761722Sjkh
5771722Sjkh	/* Clear the processor-based ctl bits that are set on demand */
57870884Sjoe	procbased_ctls &= ~PROCBASED_CTLS_WINDOW_SETTING;
5791722Sjkh
58070884Sjoe	/* Check support for secondary processor-based VM-execution controls */
58170884Sjoe	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
58270884Sjoe			       MSR_VMX_PROCBASED_CTLS2,
5831722Sjkh			       PROCBASED_CTLS2_ONE_SETTING,
58470884Sjoe			       PROCBASED_CTLS2_ZERO_SETTING, &procbased_ctls2);
5851722Sjkh	if (error) {
5861722Sjkh		printf("vmx_init: processor does not support desired secondary "
5871722Sjkh		       "processor-based controls\n");
5881722Sjkh		return (error);
5891722Sjkh	}
5901722Sjkh
5911722Sjkh	/* Check support for VPID */
5921722Sjkh	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
5931722Sjkh			       PROCBASED2_ENABLE_VPID, 0, &tmp);
5941722Sjkh	if (error == 0)
5951722Sjkh		procbased_ctls2 |= PROCBASED2_ENABLE_VPID;
5961722Sjkh
5971722Sjkh	/* Check support for pin-based VM-execution controls */
5981722Sjkh	error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
5991722Sjkh			       MSR_VMX_TRUE_PINBASED_CTLS,
6001722Sjkh			       PINBASED_CTLS_ONE_SETTING,
6011722Sjkh			       PINBASED_CTLS_ZERO_SETTING, &pinbased_ctls);
6021722Sjkh	if (error) {
6031722Sjkh		printf("vmx_init: processor does not support desired "
6041722Sjkh		       "pin-based controls\n");
6051722Sjkh		return (error);
6061722Sjkh	}
6071722Sjkh
6081722Sjkh	/* Check support for VM-exit controls */
6091722Sjkh	error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
610237625Sobrien			       VM_EXIT_CTLS_ONE_SETTING,
611237625Sobrien			       VM_EXIT_CTLS_ZERO_SETTING,
6121722Sjkh			       &exit_ctls);
61370884Sjoe	if (error) {
6141722Sjkh		printf("vmx_init: processor does not support desired "
61570884Sjoe		    "exit controls\n");
61670884Sjoe		return (error);
6171722Sjkh	}
61870884Sjoe
61970884Sjoe	/* Check support for VM-entry controls */
62070884Sjoe	error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS, MSR_VMX_TRUE_ENTRY_CTLS,
62170884Sjoe	    VM_ENTRY_CTLS_ONE_SETTING, VM_ENTRY_CTLS_ZERO_SETTING,
62270884Sjoe	    &entry_ctls);
62370884Sjoe	if (error) {
624237574Sobrien		printf("vmx_init: processor does not support desired "
625237574Sobrien		    "entry controls\n");
6261722Sjkh		return (error);
6271722Sjkh	}
62856995Sluigi
62956995Sluigi	/*
63056995Sluigi	 * Check support for optional features by testing them
631237625Sobrien	 * as individual bits
632237625Sobrien	 */
6331722Sjkh	cap_halt_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
63470884Sjoe					MSR_VMX_TRUE_PROCBASED_CTLS,
63570884Sjoe					PROCBASED_HLT_EXITING, 0,
63670884Sjoe					&tmp) == 0);
6371722Sjkh
63870884Sjoe	cap_monitor_trap = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
63970884Sjoe					MSR_VMX_PROCBASED_CTLS,
6401722Sjkh					PROCBASED_MTF, 0,
64170884Sjoe					&tmp) == 0);
64270884Sjoe
64370331Sjoe	cap_pause_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
64470884Sjoe					 MSR_VMX_TRUE_PROCBASED_CTLS,
64570884Sjoe					 PROCBASED_PAUSE_EXITING, 0,
64670884Sjoe					 &tmp) == 0);
64770884Sjoe
64870112Sjoe	cap_unrestricted_guest = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
64970884Sjoe					MSR_VMX_PROCBASED_CTLS2,
65070884Sjoe					PROCBASED2_UNRESTRICTED_GUEST, 0,
65170884Sjoe				        &tmp) == 0);
65270884Sjoe
65370884Sjoe	cap_invpcid = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
65470884Sjoe	    MSR_VMX_PROCBASED_CTLS2, PROCBASED2_ENABLE_INVPCID, 0,
65570884Sjoe	    &tmp) == 0);
65670331Sjoe
65770884Sjoe	/*
65870884Sjoe	 * Check support for virtual interrupt delivery.
65970884Sjoe	 */
66070884Sjoe	procbased2_vid_bits = (PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
66170331Sjoe	    PROCBASED2_VIRTUALIZE_X2APIC_MODE |
66270884Sjoe	    PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
66370884Sjoe	    PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY);
66470331Sjoe
66570884Sjoe	use_tpr_shadow = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
66670884Sjoe	    MSR_VMX_TRUE_PROCBASED_CTLS, PROCBASED_USE_TPR_SHADOW, 0,
66770112Sjoe	    &tmp) == 0);
66870884Sjoe
66970884Sjoe	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
67070884Sjoe	    procbased2_vid_bits, 0, &tmp);
67170884Sjoe	if (error == 0 && use_tpr_shadow) {
67270884Sjoe		virtual_interrupt_delivery = 1;
673300806Sbdrewery		TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_vid",
674300806Sbdrewery		    &virtual_interrupt_delivery);
675300806Sbdrewery	}
67670884Sjoe
677300806Sbdrewery	if (virtual_interrupt_delivery) {
678300806Sbdrewery		procbased_ctls |= PROCBASED_USE_TPR_SHADOW;
679300806Sbdrewery		procbased_ctls2 |= procbased2_vid_bits;
68070884Sjoe		procbased_ctls2 &= ~PROCBASED2_VIRTUALIZE_X2APIC_MODE;
68170884Sjoe
68270884Sjoe		/*
68370884Sjoe		 * No need to emulate accesses to %CR8 if virtual
68470884Sjoe		 * interrupt delivery is enabled.
68570884Sjoe		 */
68670884Sjoe		procbased_ctls &= ~PROCBASED_CR8_LOAD_EXITING;
68770884Sjoe		procbased_ctls &= ~PROCBASED_CR8_STORE_EXITING;
68870884Sjoe
68970884Sjoe		/*
69070884Sjoe		 * Check for Posted Interrupts only if Virtual Interrupt
69170884Sjoe		 * Delivery is enabled.
69270884Sjoe		 */
69370884Sjoe		error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
69470114Sjoe		    MSR_VMX_TRUE_PINBASED_CTLS, PINBASED_POSTED_INTERRUPT, 0,
69570884Sjoe		    &tmp);
69670884Sjoe		if (error == 0) {
69770884Sjoe			pirvec = vmm_ipi_alloc();
69870884Sjoe			if (pirvec == 0) {
6991722Sjkh				if (bootverbose) {
70081700Sjoe					printf("vmx_init: unable to allocate "
70170884Sjoe					    "posted interrupt vector\n");
70270884Sjoe				}
70370884Sjoe			} else {
70470884Sjoe				posted_interrupts = 1;
70570884Sjoe				TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_pir",
70670884Sjoe				    &posted_interrupts);
70770880Sjoe			}
70881823Sjoe		}
70970884Sjoe	}
7101722Sjkh
7111722Sjkh	if (posted_interrupts)
712237625Sobrien		    pinbased_ctls |= PINBASED_POSTED_INTERRUPT;
713237625Sobrien
7141722Sjkh	/* Initialize EPT */
71570884Sjoe	error = ept_init(ipinum);
71670884Sjoe	if (error) {
71770884Sjoe		printf("vmx_init: ept initialization failed (%d)\n", error);
71870884Sjoe		return (error);
71970884Sjoe	}
72070884Sjoe
7211722Sjkh	/*
72270884Sjoe	 * Stash the cr0 and cr4 bits that must be fixed to 0 or 1
7231722Sjkh	 */
72470884Sjoe	fixed0 = rdmsr(MSR_VMX_CR0_FIXED0);
72570884Sjoe	fixed1 = rdmsr(MSR_VMX_CR0_FIXED1);
72670884Sjoe	cr0_ones_mask = fixed0 & fixed1;
72770884Sjoe	cr0_zeros_mask = ~fixed0 & ~fixed1;
72870884Sjoe
72970884Sjoe	/*
73070884Sjoe	 * CR0_PE and CR0_PG can be set to zero in VMX non-root operation
73170884Sjoe	 * if unrestricted guest execution is allowed.
73270884Sjoe	 */
73370884Sjoe	if (cap_unrestricted_guest)
73470884Sjoe		cr0_ones_mask &= ~(CR0_PG | CR0_PE);
7358857Srgrimes
73670884Sjoe	/*
73770884Sjoe	 * Do not allow the guest to set CR0_NW or CR0_CD.
73870884Sjoe	 */
73970884Sjoe	cr0_zeros_mask |= (CR0_NW | CR0_CD);
74070884Sjoe
74170884Sjoe	fixed0 = rdmsr(MSR_VMX_CR4_FIXED0);
742187943Sobrien	fixed1 = rdmsr(MSR_VMX_CR4_FIXED1);
74370884Sjoe	cr4_ones_mask = fixed0 & fixed1;
74470884Sjoe	cr4_zeros_mask = ~fixed0 & ~fixed1;
74570884Sjoe
74670884Sjoe	vpid_init();
747187131Sobrien
748187131Sobrien	vmx_msr_init();
74970884Sjoe
75070884Sjoe	/* enable VMX operation */
75168569Sjoe	smp_rendezvous(NULL, vmx_enable, NULL, NULL);
752113886Sru
753237574Sobrien	vmx_initialized = 1;
754237574Sobrien
75570884Sjoe	return (0);
75670884Sjoe}
75770884Sjoe
75868569Sjoestatic void
75970884Sjoevmx_trigger_hostintr(int vector)
7601722Sjkh{
761237574Sobrien	uintptr_t func;
762237574Sobrien	struct gate_descriptor *gd;
76370884Sjoe
76470884Sjoe	gd = &idt[vector];
76570884Sjoe
76670884Sjoe	KASSERT(vector >= 32 && vector <= 255, ("vmx_trigger_hostintr: "
76770884Sjoe	    "invalid vector %d", vector));
7681722Sjkh	KASSERT(gd->gd_p == 1, ("gate descriptor for vector %d not present",
76970884Sjoe	    vector));
77070884Sjoe	KASSERT(gd->gd_type == SDT_SYSIGT, ("gate descriptor for vector %d "
77170884Sjoe	    "has invalid type %d", vector, gd->gd_type));
77270884Sjoe	KASSERT(gd->gd_dpl == SEL_KPL, ("gate descriptor for vector %d "
77370884Sjoe	    "has invalid dpl %d", vector, gd->gd_dpl));
77470884Sjoe	KASSERT(gd->gd_selector == GSEL(GCODE_SEL, SEL_KPL), ("gate descriptor "
77570884Sjoe	    "for vector %d has invalid selector %d", vector, gd->gd_selector));
77670884Sjoe	KASSERT(gd->gd_ist == 0, ("gate descriptor for vector %d has invalid "
777246256Spfg	    "IST %d", vector, gd->gd_ist));
77870884Sjoe
77970884Sjoe	func = ((long)gd->gd_hioffset << 16 | gd->gd_looffset);
78070884Sjoe	vmx_call_isr(func);
78170884Sjoe}
782246256Spfg
78370884Sjoestatic int
78470884Sjoevmx_setup_cr_shadow(int which, struct vmcs *vmcs, uint32_t initial)
78570884Sjoe{
78670884Sjoe	int error, mask_ident, shadow_ident;
787246256Spfg	uint64_t mask_value;
78870884Sjoe
78970884Sjoe	if (which != 0 && which != 4)
7901722Sjkh		panic("vmx_setup_cr_shadow: unknown cr%d", which);
79170884Sjoe
79270884Sjoe	if (which == 0) {
79370884Sjoe		mask_ident = VMCS_CR0_MASK;
79470884Sjoe		mask_value = cr0_ones_mask | cr0_zeros_mask;
7951722Sjkh		shadow_ident = VMCS_CR0_SHADOW;
79670884Sjoe	} else {
79770884Sjoe		mask_ident = VMCS_CR4_MASK;
7981722Sjkh		mask_value = cr4_ones_mask | cr4_zeros_mask;
7991722Sjkh		shadow_ident = VMCS_CR4_SHADOW;
800237625Sobrien	}
801237625Sobrien
8021722Sjkh	error = vmcs_setreg(vmcs, 0, VMCS_IDENT(mask_ident), mask_value);
80370884Sjoe	if (error)
8041722Sjkh		return (error);
80570884Sjoe
80670884Sjoe	error = vmcs_setreg(vmcs, 0, VMCS_IDENT(shadow_ident), initial);
80770884Sjoe	if (error)
80870884Sjoe		return (error);
80970884Sjoe
81070884Sjoe	return (0);
81170884Sjoe}
81270884Sjoe#define	vmx_setup_cr0_shadow(vmcs,init)	vmx_setup_cr_shadow(0, (vmcs), (init))
81370884Sjoe#define	vmx_setup_cr4_shadow(vmcs,init)	vmx_setup_cr_shadow(4, (vmcs), (init))
81470884Sjoe
81570884Sjoestatic void *
81670884Sjoevmx_vminit(struct vm *vm, pmap_t pmap)
81770884Sjoe{
81870884Sjoe	uint16_t vpid[VM_MAXCPU];
8191722Sjkh	int i, error;
8201722Sjkh	struct vmx *vmx;
8211722Sjkh	struct vmcs *vmcs;
822237625Sobrien	uint32_t exc_bitmap;
823237625Sobrien
8241722Sjkh	vmx = malloc(sizeof(struct vmx), M_VMX, M_WAITOK | M_ZERO);
82570884Sjoe	if ((uintptr_t)vmx & PAGE_MASK) {
82670884Sjoe		panic("malloc of struct vmx not aligned on %d byte boundary",
82770884Sjoe		      PAGE_SIZE);
8281722Sjkh	}
82970884Sjoe	vmx->vm = vm;
83070884Sjoe
8311722Sjkh	vmx->eptp = eptp(vtophys((vm_offset_t)pmap->pm_pml4));
83270884Sjoe
83370884Sjoe	/*
83470884Sjoe	 * Clean up EPTP-tagged guest physical and combined mappings
83570884Sjoe	 *
83670884Sjoe	 * VMX transitions are not required to invalidate any guest physical
8371722Sjkh	 * mappings. So, it may be possible for stale guest physical mappings
83870884Sjoe	 * to be present in the processor TLBs.
83970884Sjoe	 *
8401722Sjkh	 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
8411722Sjkh	 */
84270884Sjoe	ept_invalidate_mappings(vmx->eptp);
84370884Sjoe
84470884Sjoe	msr_bitmap_initialize(vmx->msr_bitmap);
84570884Sjoe
84670884Sjoe	/*
84770884Sjoe	 * It is safe to allow direct access to MSR_GSBASE and MSR_FSBASE.
84870884Sjoe	 * The guest FSBASE and GSBASE are saved and restored during
84970884Sjoe	 * vm-exit and vm-entry respectively. The host FSBASE and GSBASE are
85070884Sjoe	 * always restored from the vmcs host state area on vm-exit.
85170884Sjoe	 *
85270884Sjoe	 * The SYSENTER_CS/ESP/EIP MSRs are identical to FS/GSBASE in
85370884Sjoe	 * how they are saved/restored so can be directly accessed by the
85470884Sjoe	 * guest.
85570884Sjoe	 *
85670884Sjoe	 * MSR_EFER is saved and restored in the guest VMCS area on a
85770884Sjoe	 * VM exit and entry respectively. It is also restored from the
8581722Sjkh	 * host VMCS area on a VM exit.
85970884Sjoe	 *
8601722Sjkh	 * The TSC MSR is exposed read-only. Writes are disallowed as that
8611722Sjkh	 * will impact the host TSC.
8621722Sjkh	 * XXX Writes would be implemented with a wrmsr trap, and
863237625Sobrien	 * then modifying the TSC offset in the VMCS.
864237625Sobrien	 */
8651722Sjkh	if (guest_msr_rw(vmx, MSR_GSBASE) ||
86670884Sjoe	    guest_msr_rw(vmx, MSR_FSBASE) ||
86770884Sjoe	    guest_msr_rw(vmx, MSR_SYSENTER_CS_MSR) ||
86870884Sjoe	    guest_msr_rw(vmx, MSR_SYSENTER_ESP_MSR) ||
8691722Sjkh	    guest_msr_rw(vmx, MSR_SYSENTER_EIP_MSR) ||
87070884Sjoe	    guest_msr_rw(vmx, MSR_EFER) ||
87170884Sjoe	    guest_msr_ro(vmx, MSR_TSC))
8721722Sjkh		panic("vmx_vminit: error setting guest msr access");
87370884Sjoe
87470884Sjoe	vpid_alloc(vpid, VM_MAXCPU);
87570884Sjoe
87670884Sjoe	if (virtual_interrupt_delivery) {
87770884Sjoe		error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
8781722Sjkh		    APIC_ACCESS_ADDRESS);
87970884Sjoe		/* XXX this should really return an error to the caller */
8801722Sjkh		KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
8811722Sjkh	}
88270884Sjoe
88370884Sjoe	for (i = 0; i < VM_MAXCPU; i++) {
8841722Sjkh		vmcs = &vmx->vmcs[i];
88570884Sjoe		vmcs->identifier = vmx_revision();
88670884Sjoe		error = vmclear(vmcs);
88770884Sjoe		if (error != 0) {
88870884Sjoe			panic("vmx_vminit: vmclear error %d on vcpu %d\n",
88970884Sjoe			      error, i);
89070884Sjoe		}
8911722Sjkh
8921722Sjkh		vmx_msr_guest_init(vmx, i);
8931722Sjkh
894237625Sobrien		error = vmcs_init(vmcs);
895237625Sobrien		KASSERT(error == 0, ("vmcs_init error %d", error));
8961722Sjkh
89770884Sjoe		VMPTRLD(vmcs);
89870884Sjoe		error = 0;
89970884Sjoe		error += vmwrite(VMCS_HOST_RSP, (u_long)&vmx->ctx[i]);
90070884Sjoe		error += vmwrite(VMCS_EPTP, vmx->eptp);
90170884Sjoe		error += vmwrite(VMCS_PIN_BASED_CTLS, pinbased_ctls);
9021722Sjkh		error += vmwrite(VMCS_PRI_PROC_BASED_CTLS, procbased_ctls);
90370884Sjoe		error += vmwrite(VMCS_SEC_PROC_BASED_CTLS, procbased_ctls2);
90470884Sjoe		error += vmwrite(VMCS_EXIT_CTLS, exit_ctls);
9051722Sjkh		error += vmwrite(VMCS_ENTRY_CTLS, entry_ctls);
90670884Sjoe		error += vmwrite(VMCS_MSR_BITMAP, vtophys(vmx->msr_bitmap));
90770884Sjoe		error += vmwrite(VMCS_VPID, vpid[i]);
90870884Sjoe
90970884Sjoe		/* exception bitmap */
91070884Sjoe		if (vcpu_trace_exceptions(vm, i))
9111722Sjkh			exc_bitmap = 0xffffffff;
91270884Sjoe		else
91370884Sjoe			exc_bitmap = 1 << IDT_MC;
9141722Sjkh		error += vmwrite(VMCS_EXCEPTION_BITMAP, exc_bitmap);
9151722Sjkh
91670884Sjoe		if (virtual_interrupt_delivery) {
91770884Sjoe			error += vmwrite(VMCS_APIC_ACCESS, APIC_ACCESS_ADDRESS);
91870884Sjoe			error += vmwrite(VMCS_VIRTUAL_APIC,
9191722Sjkh			    vtophys(&vmx->apic_page[i]));
92070884Sjoe			error += vmwrite(VMCS_EOI_EXIT0, 0);
92170884Sjoe			error += vmwrite(VMCS_EOI_EXIT1, 0);
9221722Sjkh			error += vmwrite(VMCS_EOI_EXIT2, 0);
92370884Sjoe			error += vmwrite(VMCS_EOI_EXIT3, 0);
92470884Sjoe		}
92570884Sjoe		if (posted_interrupts) {
92670884Sjoe			error += vmwrite(VMCS_PIR_VECTOR, pirvec);
92770884Sjoe			error += vmwrite(VMCS_PIR_DESC,
92870884Sjoe			    vtophys(&vmx->pir_desc[i]));
92970884Sjoe		}
93070884Sjoe		VMCLEAR(vmcs);
9318857Srgrimes		KASSERT(error == 0, ("vmx_vminit: error customizing the vmcs"));
93270884Sjoe
93370884Sjoe		vmx->cap[i].set = 0;
93470884Sjoe		vmx->cap[i].proc_ctls = procbased_ctls;
9351722Sjkh		vmx->cap[i].proc_ctls2 = procbased_ctls2;
9361722Sjkh
9371722Sjkh		vmx->state[i].nextrip = ~0;
9381722Sjkh		vmx->state[i].lastcpu = NOCPU;
9391722Sjkh		vmx->state[i].vpid = vpid[i];
94070884Sjoe
9411722Sjkh		/*
94270884Sjoe		 * Set up the CR0/4 shadows, and init the read shadow
94370884Sjoe		 * to the power-on register value from the Intel Sys Arch.
94470884Sjoe		 *  CR0 - 0x60000010
94570884Sjoe		 *  CR4 - 0
94670884Sjoe		 */
94770884Sjoe		error = vmx_setup_cr0_shadow(vmcs, 0x60000010);
9481722Sjkh		if (error != 0)
94970884Sjoe			panic("vmx_setup_cr0_shadow %d", error);
95070884Sjoe
95170884Sjoe		error = vmx_setup_cr4_shadow(vmcs, 0);
95270884Sjoe		if (error != 0)
95370884Sjoe			panic("vmx_setup_cr4_shadow %d", error);
954246256Spfg
95570884Sjoe		vmx->ctx[i].pmap = pmap;
95670884Sjoe	}
95770884Sjoe
95870884Sjoe	return (vmx);
9591722Sjkh}
9601722Sjkh
9611722Sjkhstatic int
9621722Sjkhvmx_handle_cpuid(struct vm *vm, int vcpu, struct vmxctx *vmxctx)
9631722Sjkh{
96470884Sjoe	int handled, func;
96570884Sjoe
96670884Sjoe	func = vmxctx->guest_rax;
9671722Sjkh
96870884Sjoe	handled = x86_emulate_cpuid(vm, vcpu,
96970884Sjoe				    (uint32_t*)(&vmxctx->guest_rax),
97070884Sjoe				    (uint32_t*)(&vmxctx->guest_rbx),
97170884Sjoe				    (uint32_t*)(&vmxctx->guest_rcx),
97270884Sjoe				    (uint32_t*)(&vmxctx->guest_rdx));
97370884Sjoe	return (handled);
97470884Sjoe}
97570884Sjoe
97670884Sjoestatic __inline void
97770331Sjoevmx_run_trace(struct vmx *vmx, int vcpu)
97870884Sjoe{
9791722Sjkh#ifdef KTR
9801722Sjkh	VCPU_CTR1(vmx->vm, vcpu, "Resume execution at %#lx", vmcs_guest_rip());
9811722Sjkh#endif
982237625Sobrien}
983237625Sobrien
9841722Sjkhstatic __inline void
98570884Sjoevmx_exit_trace(struct vmx *vmx, int vcpu, uint64_t rip, uint32_t exit_reason,
9861722Sjkh	       int handled)
987246346Spfg{
988285986Sbdrewery#ifdef KTR
989153687Sceri	VCPU_CTR3(vmx->vm, vcpu, "%s %s vmexit at 0x%0lx",
990153687Sceri		 handled ? "handled" : "unhandled",
991153687Sceri		 exit_reason_to_str(exit_reason), rip);
99278520Sjoe#endif
99370884Sjoe}
9941722Sjkh
995153687Sceristatic __inline void
996153687Scerivmx_astpending_trace(struct vmx *vmx, int vcpu, uint64_t rip)
997153687Sceri{
99870884Sjoe#ifdef KTR
99970884Sjoe	VCPU_CTR1(vmx->vm, vcpu, "astpending vmexit at 0x%0lx", rip);
1000133399Sharti#endif
1001133399Sharti}
100270884Sjoe
1003133399Shartistatic VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
100470884Sjoestatic VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
100570112Sjoe
100670884Sjoe/*
100770884Sjoe * Invalidate guest mappings identified by its vpid from the TLB.
100870884Sjoe */
100970884Sjoestatic __inline void
101068750Sjoevmx_invvpid(struct vmx *vmx, int vcpu, pmap_t pmap, int running)
101170884Sjoe{
101270884Sjoe	struct vmxstate *vmxstate;
101370884Sjoe	struct invvpid_desc invvpid_desc;
101470884Sjoe
10151722Sjkh	vmxstate = &vmx->state[vcpu];
101670884Sjoe	if (vmxstate->vpid == 0)
101770884Sjoe		return;
101870884Sjoe
101970884Sjoe	if (!running) {
102070884Sjoe		/*
102170884Sjoe		 * Set the 'lastcpu' to an invalid host cpu.
102270884Sjoe		 *
10231722Sjkh		 * This will invalidate TLB entries tagged with the vcpu's
102470884Sjoe		 * vpid the next time it runs via vmx_set_pcpu_defaults().
102570884Sjoe		 */
1026164504Sjb		vmxstate->lastcpu = NOCPU;
1027153687Sceri		return;
1028153687Sceri	}
1029153687Sceri
1030153687Sceri	KASSERT(curthread->td_critnest > 0, ("%s: vcpu %d running outside "
1031153687Sceri	    "critical section", __func__, vcpu));
1032153687Sceri
103370884Sjoe	/*
10341722Sjkh	 * Invalidate all mappings tagged with 'vpid'
1035153687Sceri	 *
1036285986Sbdrewery	 * We do this because this vcpu was executing on a different host
103770884Sjoe	 * cpu when it last ran. We do not track whether it invalidated
103870884Sjoe	 * mappings associated with its 'vpid' during that run. So we must
103970884Sjoe	 * assume that the mappings associated with 'vpid' on 'curcpu' are
10401722Sjkh	 * stale and invalidate them.
10411722Sjkh	 *
10421722Sjkh	 * Note that we incur this penalty only when the scheduler chooses to
1043237625Sobrien	 * move the thread associated with this vcpu between host cpus.
1044237625Sobrien	 *
10451722Sjkh	 * Note also that this will invalidate mappings tagged with 'vpid'
104670884Sjoe	 * for "all" EP4TAs.
104730120Sjoerg	 */
104870884Sjoe	if (pmap->pm_eptgen == vmx->eptgen[curcpu]) {
10491722Sjkh		invvpid_desc._res1 = 0;
105081700Sjoe		invvpid_desc._res2 = 0;
105181700Sjoe		invvpid_desc.vpid = vmxstate->vpid;
105281700Sjoe		invvpid_desc.linear_addr = 0;
105381700Sjoe		invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
105481700Sjoe		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_DONE, 1);
105581700Sjoe	} else {
105681700Sjoe		/*
105781700Sjoe		 * The invvpid can be skipped if an invept is going to
1058164571Sjb		 * be performed before entering the guest. The invept
1059164571Sjb		 * will invalidate combined mappings tagged with
1060164571Sjb		 * 'vmx->eptp' for all vpids.
1061164571Sjb		 */
1062164571Sjb		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
1063164571Sjb	}
1064164571Sjb}
1065164571Sjb
1066164571Sjbstatic void
1067311185Sbdreweryvmx_set_pcpu_defaults(struct vmx *vmx, int vcpu, pmap_t pmap)
1068164571Sjb{
106970884Sjoe	struct vmxstate *vmxstate;
107070884Sjoe
107170884Sjoe	vmxstate = &vmx->state[vcpu];
107270112Sjoe	if (vmxstate->lastcpu == curcpu)
107370884Sjoe		return;
107470884Sjoe
107570884Sjoe	vmxstate->lastcpu = curcpu;
107670884Sjoe
107770884Sjoe	vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
107870884Sjoe
1079164654Sjb	vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1080164571Sjb	vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1081164654Sjb	vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
108270884Sjoe	vmx_invvpid(vmx, vcpu, pmap, 1);
108370884Sjoe}
108470884Sjoe
1085133399Sharti/*
108670884Sjoe * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1087133399Sharti */
108870112SjoeCTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
108970884Sjoe
1090133399Shartistatic void __inline
109170884Sjoevmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
109270884Sjoe{
109370884Sjoe
109470884Sjoe	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1095133399Sharti		vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
109670884Sjoe		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
109770884Sjoe		VCPU_CTR0(vmx->vm, vcpu, "Enabling interrupt window exiting");
109870884Sjoe	}
109970884Sjoe}
110075152Sru
110168569Sjoestatic void __inline
11021722Sjkhvmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
110393435Sluigi{
110493435Sluigi
110593435Sluigi	KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
110693435Sluigi	    ("intr_window_exiting not set: %#x", vmx->cap[vcpu].proc_ctls));
11071722Sjkh	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
110870884Sjoe	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
110970884Sjoe	VCPU_CTR0(vmx->vm, vcpu, "Disabling interrupt window exiting");
111070884Sjoe}
111170884Sjoe
11121722Sjkhstatic void __inline
111393435Sluigivmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
11141722Sjkh{
111593435Sluigi
111693435Sluigi	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1117153687Sceri		vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
111893435Sluigi		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1119284422Stijl		VCPU_CTR0(vmx->vm, vcpu, "Enabling NMI window exiting");
11201722Sjkh	}
112193435Sluigi}
112293435Sluigi
112393435Sluigistatic void __inline
112470884Sjoevmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
112570884Sjoe{
112670884Sjoe
112770884Sjoe	KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
11281722Sjkh	    ("nmi_window_exiting not set %#x", vmx->cap[vcpu].proc_ctls));
11291722Sjkh	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1130237625Sobrien	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1131237625Sobrien	VCPU_CTR0(vmx->vm, vcpu, "Disabling NMI window exiting");
11321722Sjkh}
113370884Sjoe
1134153687Sceri#define	NMI_BLOCKING	(VMCS_INTERRUPTIBILITY_NMI_BLOCKING |		\
1135153687Sceri			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
113670884Sjoe#define	HWINTR_BLOCKING	(VMCS_INTERRUPTIBILITY_STI_BLOCKING |		\
11371722Sjkh			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
11381722Sjkh
11391722Sjkhstatic void
11401722Sjkhvmx_inject_nmi(struct vmx *vmx, int vcpu)
11411722Sjkh{
11421722Sjkh	uint32_t gi, info;
11431722Sjkh
11441722Sjkh	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
11451722Sjkh	KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1146237625Sobrien	    "interruptibility-state %#x", gi));
1147246256Spfg
11481722Sjkh	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
114970884Sjoe	KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
115070884Sjoe	    "VM-entry interruption information %#x", info));
11511722Sjkh
115270884Sjoe	/*
115370884Sjoe	 * Inject the virtual NMI. The vector must be the NMI IDT entry
11541722Sjkh	 * or the VMCS entry check will fail.
115570884Sjoe	 */
115670884Sjoe	info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
115770884Sjoe	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
115870884Sjoe
11591722Sjkh	VCPU_CTR0(vmx->vm, vcpu, "Injecting vNMI");
116070884Sjoe
116170884Sjoe	/* Clear the request */
116270884Sjoe	vm_nmi_clear(vmx->vm, vcpu);
11631722Sjkh}
11641722Sjkh
11651722Sjkhstatic void
1166237625Sobrienvmx_inject_interrupts(struct vmx *vmx, int vcpu, struct vlapic *vlapic,
1167237625Sobrien    uint64_t guestrip)
11681722Sjkh{
116970884Sjoe	int vector, need_nmi_exiting, extint_pending;
11701722Sjkh	uint64_t rflags, entryinfo;
11711722Sjkh	uint32_t gi, info;
11721722Sjkh
1173237625Sobrien	if (vmx->state[vcpu].nextrip != guestrip) {
1174237625Sobrien		gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
11751722Sjkh		if (gi & HWINTR_BLOCKING) {
117670884Sjoe			VCPU_CTR2(vmx->vm, vcpu, "Guest interrupt blocking "
11771722Sjkh			    "cleared due to rip change: %#lx/%#lx",
117870884Sjoe			    vmx->state[vcpu].nextrip, guestrip);
11791722Sjkh			gi &= ~HWINTR_BLOCKING;
118070884Sjoe			vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
118170884Sjoe		}
118270884Sjoe	}
11831722Sjkh
118470884Sjoe	if (vm_entry_intinfo(vmx->vm, vcpu, &entryinfo)) {
118570884Sjoe		KASSERT((entryinfo & VMCS_INTR_VALID) != 0, ("%s: entry "
118670884Sjoe		    "intinfo is not valid: %#lx", __func__, entryinfo));
118770884Sjoe
118870884Sjoe		info = vmcs_read(VMCS_ENTRY_INTR_INFO);
118970884Sjoe		KASSERT((info & VMCS_INTR_VALID) == 0, ("%s: cannot inject "
119070884Sjoe		     "pending exception: %#lx/%#x", __func__, entryinfo, info));
11911722Sjkh
119270884Sjoe		info = entryinfo;
119370884Sjoe		vector = info & 0xff;
119470884Sjoe		if (vector == IDT_BP || vector == IDT_OF) {
119570884Sjoe			/*
11961722Sjkh			 * VT-x requires #BP and #OF to be injected as software
11971722Sjkh			 * exceptions.
1198237625Sobrien			 */
1199237625Sobrien			info &= ~VMCS_INTR_T_MASK;
1200153687Sceri			info |= VMCS_INTR_T_SWEXCEPTION;
1201153687Sceri		}
1202153687Sceri
1203153687Sceri		if (info & VMCS_INTR_DEL_ERRCODE)
1204153687Sceri			vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, entryinfo >> 32);
1205153687Sceri
1206153687Sceri		vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1207153687Sceri	}
1208153687Sceri
1209153687Sceri	if (vm_nmi_pending(vmx->vm, vcpu)) {
1210153687Sceri		/*
12111722Sjkh		 * If there are no conditions blocking NMI injection then
1212237625Sobrien		 * inject it directly here otherwise enable "NMI window
1213237625Sobrien		 * exiting" to inject it as soon as we can.
1214153687Sceri		 *
1215153687Sceri		 * We also check for STI_BLOCKING because some implementations
1216153687Sceri		 * don't allow NMI injection in this case. If we are running
1217153687Sceri		 * on a processor that doesn't have this restriction it will
1218153687Sceri		 * immediately exit and the NMI will be injected in the
1219153687Sceri		 * "NMI window exiting" handler.
1220153687Sceri		 */
1221153687Sceri		need_nmi_exiting = 1;
1222237625Sobrien		gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1223246256Spfg		if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
12241722Sjkh			info = vmcs_read(VMCS_ENTRY_INTR_INFO);
122570884Sjoe			if ((info & VMCS_INTR_VALID) == 0) {
12261722Sjkh				vmx_inject_nmi(vmx, vcpu);
122770884Sjoe				need_nmi_exiting = 0;
122870884Sjoe			} else {
122970884Sjoe				VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI "
123070884Sjoe				    "due to VM-entry intr info %#x", info);
12311722Sjkh			}
12321722Sjkh		} else {
1233237625Sobrien			VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI due to "
1234246256Spfg			    "Guest Interruptibility-state %#x", gi);
12351722Sjkh		}
123670884Sjoe
12371722Sjkh		if (need_nmi_exiting)
123870884Sjoe			vmx_set_nmi_window_exiting(vmx, vcpu);
123970884Sjoe	}
12401722Sjkh
124170884Sjoe	extint_pending = vm_extint_pending(vmx->vm, vcpu);
12421722Sjkh
1243	if (!extint_pending && virtual_interrupt_delivery) {
1244		vmx_inject_pir(vlapic);
1245		return;
1246	}
1247
1248	/*
1249	 * If interrupt-window exiting is already in effect then don't bother
1250	 * checking for pending interrupts. This is just an optimization and
1251	 * not needed for correctness.
1252	 */
1253	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0) {
1254		VCPU_CTR0(vmx->vm, vcpu, "Skip interrupt injection due to "
1255		    "pending int_window_exiting");
1256		return;
1257	}
1258
1259	if (!extint_pending) {
1260		/* Ask the local apic for a vector to inject */
1261		if (!vlapic_pending_intr(vlapic, &vector))
1262			return;
1263
1264		/*
1265		 * From the Intel SDM, Volume 3, Section "Maskable
1266		 * Hardware Interrupts":
1267		 * - maskable interrupt vectors [16,255] can be delivered
1268		 *   through the local APIC.
1269		*/
1270		KASSERT(vector >= 16 && vector <= 255,
1271		    ("invalid vector %d from local APIC", vector));
1272	} else {
1273		/* Ask the legacy pic for a vector to inject */
1274		vatpic_pending_intr(vmx->vm, &vector);
1275
1276		/*
1277		 * From the Intel SDM, Volume 3, Section "Maskable
1278		 * Hardware Interrupts":
1279		 * - maskable interrupt vectors [0,255] can be delivered
1280		 *   through the INTR pin.
1281		 */
1282		KASSERT(vector >= 0 && vector <= 255,
1283		    ("invalid vector %d from INTR", vector));
1284	}
1285
1286	/* Check RFLAGS.IF and the interruptibility state of the guest */
1287	rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1288	if ((rflags & PSL_I) == 0) {
1289		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1290		    "rflags %#lx", vector, rflags);
1291		goto cantinject;
1292	}
1293
1294	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1295	if (gi & HWINTR_BLOCKING) {
1296		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1297		    "Guest Interruptibility-state %#x", vector, gi);
1298		goto cantinject;
1299	}
1300
1301	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1302	if (info & VMCS_INTR_VALID) {
1303		/*
1304		 * This is expected and could happen for multiple reasons:
1305		 * - A vectoring VM-entry was aborted due to astpending
1306		 * - A VM-exit happened during event injection.
1307		 * - An exception was injected above.
1308		 * - An NMI was injected above or after "NMI window exiting"
1309		 */
1310		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1311		    "VM-entry intr info %#x", vector, info);
1312		goto cantinject;
1313	}
1314
1315	/* Inject the interrupt */
1316	info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1317	info |= vector;
1318	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1319
1320	if (!extint_pending) {
1321		/* Update the Local APIC ISR */
1322		vlapic_intr_accepted(vlapic, vector);
1323	} else {
1324		vm_extint_clear(vmx->vm, vcpu);
1325		vatpic_intr_accepted(vmx->vm, vector);
1326
1327		/*
1328		 * After we accepted the current ExtINT the PIC may
1329		 * have posted another one.  If that is the case, set
1330		 * the Interrupt Window Exiting execution control so
1331		 * we can inject that one too.
1332		 *
1333		 * Also, interrupt window exiting allows us to inject any
1334		 * pending APIC vector that was preempted by the ExtINT
1335		 * as soon as possible. This applies both for the software
1336		 * emulated vlapic and the hardware assisted virtual APIC.
1337		 */
1338		vmx_set_int_window_exiting(vmx, vcpu);
1339	}
1340
1341	VCPU_CTR1(vmx->vm, vcpu, "Injecting hwintr at vector %d", vector);
1342
1343	return;
1344
1345cantinject:
1346	/*
1347	 * Set the Interrupt Window Exiting execution control so we can inject
1348	 * the interrupt as soon as blocking condition goes away.
1349	 */
1350	vmx_set_int_window_exiting(vmx, vcpu);
1351}
1352
1353/*
1354 * If the Virtual NMIs execution control is '1' then the logical processor
1355 * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1356 * the VMCS. An IRET instruction in VMX non-root operation will remove any
1357 * virtual-NMI blocking.
1358 *
1359 * This unblocking occurs even if the IRET causes a fault. In this case the
1360 * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1361 */
1362static void
1363vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1364{
1365	uint32_t gi;
1366
1367	VCPU_CTR0(vmx->vm, vcpuid, "Restore Virtual-NMI blocking");
1368	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1369	gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1370	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1371}
1372
1373static void
1374vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1375{
1376	uint32_t gi;
1377
1378	VCPU_CTR0(vmx->vm, vcpuid, "Clear Virtual-NMI blocking");
1379	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1380	gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1381	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1382}
1383
1384static void
1385vmx_assert_nmi_blocking(struct vmx *vmx, int vcpuid)
1386{
1387	uint32_t gi;
1388
1389	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1390	KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1391	    ("NMI blocking is not in effect %#x", gi));
1392}
1393
1394static int
1395vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1396{
1397	struct vmxctx *vmxctx;
1398	uint64_t xcrval;
1399	const struct xsave_limits *limits;
1400
1401	vmxctx = &vmx->ctx[vcpu];
1402	limits = vmm_get_xsave_limits();
1403
1404	/*
1405	 * Note that the processor raises a GP# fault on its own if
1406	 * xsetbv is executed for CPL != 0, so we do not have to
1407	 * emulate that fault here.
1408	 */
1409
1410	/* Only xcr0 is supported. */
1411	if (vmxctx->guest_rcx != 0) {
1412		vm_inject_gp(vmx->vm, vcpu);
1413		return (HANDLED);
1414	}
1415
1416	/* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1417	if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1418		vm_inject_ud(vmx->vm, vcpu);
1419		return (HANDLED);
1420	}
1421
1422	xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1423	if ((xcrval & ~limits->xcr0_allowed) != 0) {
1424		vm_inject_gp(vmx->vm, vcpu);
1425		return (HANDLED);
1426	}
1427
1428	if (!(xcrval & XFEATURE_ENABLED_X87)) {
1429		vm_inject_gp(vmx->vm, vcpu);
1430		return (HANDLED);
1431	}
1432
1433	/* AVX (YMM_Hi128) requires SSE. */
1434	if (xcrval & XFEATURE_ENABLED_AVX &&
1435	    (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1436		vm_inject_gp(vmx->vm, vcpu);
1437		return (HANDLED);
1438	}
1439
1440	/*
1441	 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1442	 * ZMM_Hi256, and Hi16_ZMM.
1443	 */
1444	if (xcrval & XFEATURE_AVX512 &&
1445	    (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1446	    (XFEATURE_AVX512 | XFEATURE_AVX)) {
1447		vm_inject_gp(vmx->vm, vcpu);
1448		return (HANDLED);
1449	}
1450
1451	/*
1452	 * Intel MPX requires both bound register state flags to be
1453	 * set.
1454	 */
1455	if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1456	    ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1457		vm_inject_gp(vmx->vm, vcpu);
1458		return (HANDLED);
1459	}
1460
1461	/*
1462	 * This runs "inside" vmrun() with the guest's FPU state, so
1463	 * modifying xcr0 directly modifies the guest's xcr0, not the
1464	 * host's.
1465	 */
1466	load_xcr(0, xcrval);
1467	return (HANDLED);
1468}
1469
1470static uint64_t
1471vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1472{
1473	const struct vmxctx *vmxctx;
1474
1475	vmxctx = &vmx->ctx[vcpu];
1476
1477	switch (ident) {
1478	case 0:
1479		return (vmxctx->guest_rax);
1480	case 1:
1481		return (vmxctx->guest_rcx);
1482	case 2:
1483		return (vmxctx->guest_rdx);
1484	case 3:
1485		return (vmxctx->guest_rbx);
1486	case 4:
1487		return (vmcs_read(VMCS_GUEST_RSP));
1488	case 5:
1489		return (vmxctx->guest_rbp);
1490	case 6:
1491		return (vmxctx->guest_rsi);
1492	case 7:
1493		return (vmxctx->guest_rdi);
1494	case 8:
1495		return (vmxctx->guest_r8);
1496	case 9:
1497		return (vmxctx->guest_r9);
1498	case 10:
1499		return (vmxctx->guest_r10);
1500	case 11:
1501		return (vmxctx->guest_r11);
1502	case 12:
1503		return (vmxctx->guest_r12);
1504	case 13:
1505		return (vmxctx->guest_r13);
1506	case 14:
1507		return (vmxctx->guest_r14);
1508	case 15:
1509		return (vmxctx->guest_r15);
1510	default:
1511		panic("invalid vmx register %d", ident);
1512	}
1513}
1514
1515static void
1516vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1517{
1518	struct vmxctx *vmxctx;
1519
1520	vmxctx = &vmx->ctx[vcpu];
1521
1522	switch (ident) {
1523	case 0:
1524		vmxctx->guest_rax = regval;
1525		break;
1526	case 1:
1527		vmxctx->guest_rcx = regval;
1528		break;
1529	case 2:
1530		vmxctx->guest_rdx = regval;
1531		break;
1532	case 3:
1533		vmxctx->guest_rbx = regval;
1534		break;
1535	case 4:
1536		vmcs_write(VMCS_GUEST_RSP, regval);
1537		break;
1538	case 5:
1539		vmxctx->guest_rbp = regval;
1540		break;
1541	case 6:
1542		vmxctx->guest_rsi = regval;
1543		break;
1544	case 7:
1545		vmxctx->guest_rdi = regval;
1546		break;
1547	case 8:
1548		vmxctx->guest_r8 = regval;
1549		break;
1550	case 9:
1551		vmxctx->guest_r9 = regval;
1552		break;
1553	case 10:
1554		vmxctx->guest_r10 = regval;
1555		break;
1556	case 11:
1557		vmxctx->guest_r11 = regval;
1558		break;
1559	case 12:
1560		vmxctx->guest_r12 = regval;
1561		break;
1562	case 13:
1563		vmxctx->guest_r13 = regval;
1564		break;
1565	case 14:
1566		vmxctx->guest_r14 = regval;
1567		break;
1568	case 15:
1569		vmxctx->guest_r15 = regval;
1570		break;
1571	default:
1572		panic("invalid vmx register %d", ident);
1573	}
1574}
1575
1576static int
1577vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1578{
1579	uint64_t crval, regval;
1580
1581	/* We only handle mov to %cr0 at this time */
1582	if ((exitqual & 0xf0) != 0x00)
1583		return (UNHANDLED);
1584
1585	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1586
1587	vmcs_write(VMCS_CR0_SHADOW, regval);
1588
1589	crval = regval | cr0_ones_mask;
1590	crval &= ~cr0_zeros_mask;
1591	vmcs_write(VMCS_GUEST_CR0, crval);
1592
1593	if (regval & CR0_PG) {
1594		uint64_t efer, entry_ctls;
1595
1596		/*
1597		 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1598		 * the "IA-32e mode guest" bit in VM-entry control must be
1599		 * equal.
1600		 */
1601		efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1602		if (efer & EFER_LME) {
1603			efer |= EFER_LMA;
1604			vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1605			entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1606			entry_ctls |= VM_ENTRY_GUEST_LMA;
1607			vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1608		}
1609	}
1610
1611	return (HANDLED);
1612}
1613
1614static int
1615vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1616{
1617	uint64_t crval, regval;
1618
1619	/* We only handle mov to %cr4 at this time */
1620	if ((exitqual & 0xf0) != 0x00)
1621		return (UNHANDLED);
1622
1623	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1624
1625	vmcs_write(VMCS_CR4_SHADOW, regval);
1626
1627	crval = regval | cr4_ones_mask;
1628	crval &= ~cr4_zeros_mask;
1629	vmcs_write(VMCS_GUEST_CR4, crval);
1630
1631	return (HANDLED);
1632}
1633
1634static int
1635vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1636{
1637	struct vlapic *vlapic;
1638	uint64_t cr8;
1639	int regnum;
1640
1641	/* We only handle mov %cr8 to/from a register at this time. */
1642	if ((exitqual & 0xe0) != 0x00) {
1643		return (UNHANDLED);
1644	}
1645
1646	vlapic = vm_lapic(vmx->vm, vcpu);
1647	regnum = (exitqual >> 8) & 0xf;
1648	if (exitqual & 0x10) {
1649		cr8 = vlapic_get_cr8(vlapic);
1650		vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1651	} else {
1652		cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1653		vlapic_set_cr8(vlapic, cr8);
1654	}
1655
1656	return (HANDLED);
1657}
1658
1659/*
1660 * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1661 */
1662static int
1663vmx_cpl(void)
1664{
1665	uint32_t ssar;
1666
1667	ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1668	return ((ssar >> 5) & 0x3);
1669}
1670
1671static enum vm_cpu_mode
1672vmx_cpu_mode(void)
1673{
1674	uint32_t csar;
1675
1676	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1677		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1678		if (csar & 0x2000)
1679			return (CPU_MODE_64BIT);	/* CS.L = 1 */
1680		else
1681			return (CPU_MODE_COMPATIBILITY);
1682	} else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1683		return (CPU_MODE_PROTECTED);
1684	} else {
1685		return (CPU_MODE_REAL);
1686	}
1687}
1688
1689static enum vm_paging_mode
1690vmx_paging_mode(void)
1691{
1692
1693	if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1694		return (PAGING_MODE_FLAT);
1695	if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1696		return (PAGING_MODE_32);
1697	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1698		return (PAGING_MODE_64);
1699	else
1700		return (PAGING_MODE_PAE);
1701}
1702
1703static uint64_t
1704inout_str_index(struct vmx *vmx, int vcpuid, int in)
1705{
1706	uint64_t val;
1707	int error;
1708	enum vm_reg_name reg;
1709
1710	reg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
1711	error = vmx_getreg(vmx, vcpuid, reg, &val);
1712	KASSERT(error == 0, ("%s: vmx_getreg error %d", __func__, error));
1713	return (val);
1714}
1715
1716static uint64_t
1717inout_str_count(struct vmx *vmx, int vcpuid, int rep)
1718{
1719	uint64_t val;
1720	int error;
1721
1722	if (rep) {
1723		error = vmx_getreg(vmx, vcpuid, VM_REG_GUEST_RCX, &val);
1724		KASSERT(!error, ("%s: vmx_getreg error %d", __func__, error));
1725	} else {
1726		val = 1;
1727	}
1728	return (val);
1729}
1730
1731static int
1732inout_str_addrsize(uint32_t inst_info)
1733{
1734	uint32_t size;
1735
1736	size = (inst_info >> 7) & 0x7;
1737	switch (size) {
1738	case 0:
1739		return (2);	/* 16 bit */
1740	case 1:
1741		return (4);	/* 32 bit */
1742	case 2:
1743		return (8);	/* 64 bit */
1744	default:
1745		panic("%s: invalid size encoding %d", __func__, size);
1746	}
1747}
1748
1749static void
1750inout_str_seginfo(struct vmx *vmx, int vcpuid, uint32_t inst_info, int in,
1751    struct vm_inout_str *vis)
1752{
1753	int error, s;
1754
1755	if (in) {
1756		vis->seg_name = VM_REG_GUEST_ES;
1757	} else {
1758		s = (inst_info >> 15) & 0x7;
1759		vis->seg_name = vm_segment_name(s);
1760	}
1761
1762	error = vmx_getdesc(vmx, vcpuid, vis->seg_name, &vis->seg_desc);
1763	KASSERT(error == 0, ("%s: vmx_getdesc error %d", __func__, error));
1764}
1765
1766static void
1767vmx_paging_info(struct vm_guest_paging *paging)
1768{
1769	paging->cr3 = vmcs_guest_cr3();
1770	paging->cpl = vmx_cpl();
1771	paging->cpu_mode = vmx_cpu_mode();
1772	paging->paging_mode = vmx_paging_mode();
1773}
1774
1775static void
1776vmexit_inst_emul(struct vm_exit *vmexit, uint64_t gpa, uint64_t gla)
1777{
1778	struct vm_guest_paging *paging;
1779	uint32_t csar;
1780
1781	paging = &vmexit->u.inst_emul.paging;
1782
1783	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
1784	vmexit->u.inst_emul.gpa = gpa;
1785	vmexit->u.inst_emul.gla = gla;
1786	vmx_paging_info(paging);
1787	switch (paging->cpu_mode) {
1788	case CPU_MODE_PROTECTED:
1789	case CPU_MODE_COMPATIBILITY:
1790		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1791		vmexit->u.inst_emul.cs_d = SEG_DESC_DEF32(csar);
1792		break;
1793	default:
1794		vmexit->u.inst_emul.cs_d = 0;
1795		break;
1796	}
1797	vie_init(&vmexit->u.inst_emul.vie, NULL, 0);
1798}
1799
1800static int
1801ept_fault_type(uint64_t ept_qual)
1802{
1803	int fault_type;
1804
1805	if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1806		fault_type = VM_PROT_WRITE;
1807	else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1808		fault_type = VM_PROT_EXECUTE;
1809	else
1810		fault_type= VM_PROT_READ;
1811
1812	return (fault_type);
1813}
1814
1815static boolean_t
1816ept_emulation_fault(uint64_t ept_qual)
1817{
1818	int read, write;
1819
1820	/* EPT fault on an instruction fetch doesn't make sense here */
1821	if (ept_qual & EPT_VIOLATION_INST_FETCH)
1822		return (FALSE);
1823
1824	/* EPT fault must be a read fault or a write fault */
1825	read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1826	write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1827	if ((read | write) == 0)
1828		return (FALSE);
1829
1830	/*
1831	 * The EPT violation must have been caused by accessing a
1832	 * guest-physical address that is a translation of a guest-linear
1833	 * address.
1834	 */
1835	if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1836	    (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1837		return (FALSE);
1838	}
1839
1840	return (TRUE);
1841}
1842
1843static __inline int
1844apic_access_virtualization(struct vmx *vmx, int vcpuid)
1845{
1846	uint32_t proc_ctls2;
1847
1848	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1849	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1850}
1851
1852static __inline int
1853x2apic_virtualization(struct vmx *vmx, int vcpuid)
1854{
1855	uint32_t proc_ctls2;
1856
1857	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1858	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1859}
1860
1861static int
1862vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1863    uint64_t qual)
1864{
1865	int error, handled, offset;
1866	uint32_t *apic_regs, vector;
1867	bool retu;
1868
1869	handled = HANDLED;
1870	offset = APIC_WRITE_OFFSET(qual);
1871
1872	if (!apic_access_virtualization(vmx, vcpuid)) {
1873		/*
1874		 * In general there should not be any APIC write VM-exits
1875		 * unless APIC-access virtualization is enabled.
1876		 *
1877		 * However self-IPI virtualization can legitimately trigger
1878		 * an APIC-write VM-exit so treat it specially.
1879		 */
1880		if (x2apic_virtualization(vmx, vcpuid) &&
1881		    offset == APIC_OFFSET_SELF_IPI) {
1882			apic_regs = (uint32_t *)(vlapic->apic_page);
1883			vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
1884			vlapic_self_ipi_handler(vlapic, vector);
1885			return (HANDLED);
1886		} else
1887			return (UNHANDLED);
1888	}
1889
1890	switch (offset) {
1891	case APIC_OFFSET_ID:
1892		vlapic_id_write_handler(vlapic);
1893		break;
1894	case APIC_OFFSET_LDR:
1895		vlapic_ldr_write_handler(vlapic);
1896		break;
1897	case APIC_OFFSET_DFR:
1898		vlapic_dfr_write_handler(vlapic);
1899		break;
1900	case APIC_OFFSET_SVR:
1901		vlapic_svr_write_handler(vlapic);
1902		break;
1903	case APIC_OFFSET_ESR:
1904		vlapic_esr_write_handler(vlapic);
1905		break;
1906	case APIC_OFFSET_ICR_LOW:
1907		retu = false;
1908		error = vlapic_icrlo_write_handler(vlapic, &retu);
1909		if (error != 0 || retu)
1910			handled = UNHANDLED;
1911		break;
1912	case APIC_OFFSET_CMCI_LVT:
1913	case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1914		vlapic_lvt_write_handler(vlapic, offset);
1915		break;
1916	case APIC_OFFSET_TIMER_ICR:
1917		vlapic_icrtmr_write_handler(vlapic);
1918		break;
1919	case APIC_OFFSET_TIMER_DCR:
1920		vlapic_dcr_write_handler(vlapic);
1921		break;
1922	default:
1923		handled = UNHANDLED;
1924		break;
1925	}
1926	return (handled);
1927}
1928
1929static bool
1930apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
1931{
1932
1933	if (apic_access_virtualization(vmx, vcpuid) &&
1934	    (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
1935		return (true);
1936	else
1937		return (false);
1938}
1939
1940static int
1941vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
1942{
1943	uint64_t qual;
1944	int access_type, offset, allowed;
1945
1946	if (!apic_access_virtualization(vmx, vcpuid))
1947		return (UNHANDLED);
1948
1949	qual = vmexit->u.vmx.exit_qualification;
1950	access_type = APIC_ACCESS_TYPE(qual);
1951	offset = APIC_ACCESS_OFFSET(qual);
1952
1953	allowed = 0;
1954	if (access_type == 0) {
1955		/*
1956		 * Read data access to the following registers is expected.
1957		 */
1958		switch (offset) {
1959		case APIC_OFFSET_APR:
1960		case APIC_OFFSET_PPR:
1961		case APIC_OFFSET_RRR:
1962		case APIC_OFFSET_CMCI_LVT:
1963		case APIC_OFFSET_TIMER_CCR:
1964			allowed = 1;
1965			break;
1966		default:
1967			break;
1968		}
1969	} else if (access_type == 1) {
1970		/*
1971		 * Write data access to the following registers is expected.
1972		 */
1973		switch (offset) {
1974		case APIC_OFFSET_VER:
1975		case APIC_OFFSET_APR:
1976		case APIC_OFFSET_PPR:
1977		case APIC_OFFSET_RRR:
1978		case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
1979		case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
1980		case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
1981		case APIC_OFFSET_CMCI_LVT:
1982		case APIC_OFFSET_TIMER_CCR:
1983			allowed = 1;
1984			break;
1985		default:
1986			break;
1987		}
1988	}
1989
1990	if (allowed) {
1991		vmexit_inst_emul(vmexit, DEFAULT_APIC_BASE + offset,
1992		    VIE_INVALID_GLA);
1993	}
1994
1995	/*
1996	 * Regardless of whether the APIC-access is allowed this handler
1997	 * always returns UNHANDLED:
1998	 * - if the access is allowed then it is handled by emulating the
1999	 *   instruction that caused the VM-exit (outside the critical section)
2000	 * - if the access is not allowed then it will be converted to an
2001	 *   exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
2002	 */
2003	return (UNHANDLED);
2004}
2005
2006static enum task_switch_reason
2007vmx_task_switch_reason(uint64_t qual)
2008{
2009	int reason;
2010
2011	reason = (qual >> 30) & 0x3;
2012	switch (reason) {
2013	case 0:
2014		return (TSR_CALL);
2015	case 1:
2016		return (TSR_IRET);
2017	case 2:
2018		return (TSR_JMP);
2019	case 3:
2020		return (TSR_IDT_GATE);
2021	default:
2022		panic("%s: invalid reason %d", __func__, reason);
2023	}
2024}
2025
2026static int
2027emulate_wrmsr(struct vmx *vmx, int vcpuid, u_int num, uint64_t val, bool *retu)
2028{
2029	int error;
2030
2031	if (lapic_msr(num))
2032		error = lapic_wrmsr(vmx->vm, vcpuid, num, val, retu);
2033	else
2034		error = vmx_wrmsr(vmx, vcpuid, num, val, retu);
2035
2036	return (error);
2037}
2038
2039static int
2040emulate_rdmsr(struct vmx *vmx, int vcpuid, u_int num, bool *retu)
2041{
2042	struct vmxctx *vmxctx;
2043	uint64_t result;
2044	uint32_t eax, edx;
2045	int error;
2046
2047	if (lapic_msr(num))
2048		error = lapic_rdmsr(vmx->vm, vcpuid, num, &result, retu);
2049	else
2050		error = vmx_rdmsr(vmx, vcpuid, num, &result, retu);
2051
2052	if (error == 0) {
2053		eax = result;
2054		vmxctx = &vmx->ctx[vcpuid];
2055		error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RAX, eax);
2056		KASSERT(error == 0, ("vmxctx_setreg(rax) error %d", error));
2057
2058		edx = result >> 32;
2059		error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RDX, edx);
2060		KASSERT(error == 0, ("vmxctx_setreg(rdx) error %d", error));
2061	}
2062
2063	return (error);
2064}
2065
2066static int
2067vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2068{
2069	int error, errcode, errcode_valid, handled, in;
2070	struct vmxctx *vmxctx;
2071	struct vlapic *vlapic;
2072	struct vm_inout_str *vis;
2073	struct vm_task_switch *ts;
2074	uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, inst_info;
2075	uint32_t intr_type, intr_vec, reason;
2076	uint64_t exitintinfo, qual, gpa;
2077	bool retu;
2078
2079	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2080	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2081
2082	handled = UNHANDLED;
2083	vmxctx = &vmx->ctx[vcpu];
2084
2085	qual = vmexit->u.vmx.exit_qualification;
2086	reason = vmexit->u.vmx.exit_reason;
2087	vmexit->exitcode = VM_EXITCODE_BOGUS;
2088
2089	vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
2090
2091	/*
2092	 * VM-entry failures during or after loading guest state.
2093	 *
2094	 * These VM-exits are uncommon but must be handled specially
2095	 * as most VM-exit fields are not populated as usual.
2096	 */
2097	if (__predict_false(reason == EXIT_REASON_MCE_DURING_ENTRY)) {
2098		VCPU_CTR0(vmx->vm, vcpu, "Handling MCE during VM-entry");
2099		__asm __volatile("int $18");
2100		return (1);
2101	}
2102
2103	/*
2104	 * VM exits that can be triggered during event delivery need to
2105	 * be handled specially by re-injecting the event if the IDT
2106	 * vectoring information field's valid bit is set.
2107	 *
2108	 * See "Information for VM Exits During Event Delivery" in Intel SDM
2109	 * for details.
2110	 */
2111	idtvec_info = vmcs_idt_vectoring_info();
2112	if (idtvec_info & VMCS_IDT_VEC_VALID) {
2113		idtvec_info &= ~(1 << 12); /* clear undefined bit */
2114		exitintinfo = idtvec_info;
2115		if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2116			idtvec_err = vmcs_idt_vectoring_err();
2117			exitintinfo |= (uint64_t)idtvec_err << 32;
2118		}
2119		error = vm_exit_intinfo(vmx->vm, vcpu, exitintinfo);
2120		KASSERT(error == 0, ("%s: vm_set_intinfo error %d",
2121		    __func__, error));
2122
2123		/*
2124		 * If 'virtual NMIs' are being used and the VM-exit
2125		 * happened while injecting an NMI during the previous
2126		 * VM-entry, then clear "blocking by NMI" in the
2127		 * Guest Interruptibility-State so the NMI can be
2128		 * reinjected on the subsequent VM-entry.
2129		 *
2130		 * However, if the NMI was being delivered through a task
2131		 * gate, then the new task must start execution with NMIs
2132		 * blocked so don't clear NMI blocking in this case.
2133		 */
2134		intr_type = idtvec_info & VMCS_INTR_T_MASK;
2135		if (intr_type == VMCS_INTR_T_NMI) {
2136			if (reason != EXIT_REASON_TASK_SWITCH)
2137				vmx_clear_nmi_blocking(vmx, vcpu);
2138			else
2139				vmx_assert_nmi_blocking(vmx, vcpu);
2140		}
2141
2142		/*
2143		 * Update VM-entry instruction length if the event being
2144		 * delivered was a software interrupt or software exception.
2145		 */
2146		if (intr_type == VMCS_INTR_T_SWINTR ||
2147		    intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2148		    intr_type == VMCS_INTR_T_SWEXCEPTION) {
2149			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2150		}
2151	}
2152
2153	switch (reason) {
2154	case EXIT_REASON_TASK_SWITCH:
2155		ts = &vmexit->u.task_switch;
2156		ts->tsssel = qual & 0xffff;
2157		ts->reason = vmx_task_switch_reason(qual);
2158		ts->ext = 0;
2159		ts->errcode_valid = 0;
2160		vmx_paging_info(&ts->paging);
2161		/*
2162		 * If the task switch was due to a CALL, JMP, IRET, software
2163		 * interrupt (INT n) or software exception (INT3, INTO),
2164		 * then the saved %rip references the instruction that caused
2165		 * the task switch. The instruction length field in the VMCS
2166		 * is valid in this case.
2167		 *
2168		 * In all other cases (e.g., NMI, hardware exception) the
2169		 * saved %rip is one that would have been saved in the old TSS
2170		 * had the task switch completed normally so the instruction
2171		 * length field is not needed in this case and is explicitly
2172		 * set to 0.
2173		 */
2174		if (ts->reason == TSR_IDT_GATE) {
2175			KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2176			    ("invalid idtvec_info %#x for IDT task switch",
2177			    idtvec_info));
2178			intr_type = idtvec_info & VMCS_INTR_T_MASK;
2179			if (intr_type != VMCS_INTR_T_SWINTR &&
2180			    intr_type != VMCS_INTR_T_SWEXCEPTION &&
2181			    intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2182				/* Task switch triggered by external event */
2183				ts->ext = 1;
2184				vmexit->inst_length = 0;
2185				if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2186					ts->errcode_valid = 1;
2187					ts->errcode = vmcs_idt_vectoring_err();
2188				}
2189			}
2190		}
2191		vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2192		VCPU_CTR4(vmx->vm, vcpu, "task switch reason %d, tss 0x%04x, "
2193		    "%s errcode 0x%016lx", ts->reason, ts->tsssel,
2194		    ts->ext ? "external" : "internal",
2195		    ((uint64_t)ts->errcode << 32) | ts->errcode_valid);
2196		break;
2197	case EXIT_REASON_CR_ACCESS:
2198		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2199		switch (qual & 0xf) {
2200		case 0:
2201			handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2202			break;
2203		case 4:
2204			handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2205			break;
2206		case 8:
2207			handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2208			break;
2209		}
2210		break;
2211	case EXIT_REASON_RDMSR:
2212		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RDMSR, 1);
2213		retu = false;
2214		ecx = vmxctx->guest_rcx;
2215		VCPU_CTR1(vmx->vm, vcpu, "rdmsr 0x%08x", ecx);
2216		error = emulate_rdmsr(vmx, vcpu, ecx, &retu);
2217		if (error) {
2218			vmexit->exitcode = VM_EXITCODE_RDMSR;
2219			vmexit->u.msr.code = ecx;
2220		} else if (!retu) {
2221			handled = HANDLED;
2222		} else {
2223			/* Return to userspace with a valid exitcode */
2224			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2225			    ("emulate_rdmsr retu with bogus exitcode"));
2226		}
2227		break;
2228	case EXIT_REASON_WRMSR:
2229		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_WRMSR, 1);
2230		retu = false;
2231		eax = vmxctx->guest_rax;
2232		ecx = vmxctx->guest_rcx;
2233		edx = vmxctx->guest_rdx;
2234		VCPU_CTR2(vmx->vm, vcpu, "wrmsr 0x%08x value 0x%016lx",
2235		    ecx, (uint64_t)edx << 32 | eax);
2236		error = emulate_wrmsr(vmx, vcpu, ecx,
2237		    (uint64_t)edx << 32 | eax, &retu);
2238		if (error) {
2239			vmexit->exitcode = VM_EXITCODE_WRMSR;
2240			vmexit->u.msr.code = ecx;
2241			vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
2242		} else if (!retu) {
2243			handled = HANDLED;
2244		} else {
2245			/* Return to userspace with a valid exitcode */
2246			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2247			    ("emulate_wrmsr retu with bogus exitcode"));
2248		}
2249		break;
2250	case EXIT_REASON_HLT:
2251		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2252		vmexit->exitcode = VM_EXITCODE_HLT;
2253		vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2254		break;
2255	case EXIT_REASON_MTF:
2256		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2257		vmexit->exitcode = VM_EXITCODE_MTRAP;
2258		vmexit->inst_length = 0;
2259		break;
2260	case EXIT_REASON_PAUSE:
2261		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2262		vmexit->exitcode = VM_EXITCODE_PAUSE;
2263		break;
2264	case EXIT_REASON_INTR_WINDOW:
2265		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2266		vmx_clear_int_window_exiting(vmx, vcpu);
2267		return (1);
2268	case EXIT_REASON_EXT_INTR:
2269		/*
2270		 * External interrupts serve only to cause VM exits and allow
2271		 * the host interrupt handler to run.
2272		 *
2273		 * If this external interrupt triggers a virtual interrupt
2274		 * to a VM, then that state will be recorded by the
2275		 * host interrupt handler in the VM's softc. We will inject
2276		 * this virtual interrupt during the subsequent VM enter.
2277		 */
2278		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2279
2280		/*
2281		 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2282		 * This appears to be a bug in VMware Fusion?
2283		 */
2284		if (!(intr_info & VMCS_INTR_VALID))
2285			return (1);
2286		KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2287		    (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2288		    ("VM exit interruption info invalid: %#x", intr_info));
2289		vmx_trigger_hostintr(intr_info & 0xff);
2290
2291		/*
2292		 * This is special. We want to treat this as an 'handled'
2293		 * VM-exit but not increment the instruction pointer.
2294		 */
2295		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2296		return (1);
2297	case EXIT_REASON_NMI_WINDOW:
2298		/* Exit to allow the pending virtual NMI to be injected */
2299		if (vm_nmi_pending(vmx->vm, vcpu))
2300			vmx_inject_nmi(vmx, vcpu);
2301		vmx_clear_nmi_window_exiting(vmx, vcpu);
2302		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2303		return (1);
2304	case EXIT_REASON_INOUT:
2305		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2306		vmexit->exitcode = VM_EXITCODE_INOUT;
2307		vmexit->u.inout.bytes = (qual & 0x7) + 1;
2308		vmexit->u.inout.in = in = (qual & 0x8) ? 1 : 0;
2309		vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
2310		vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
2311		vmexit->u.inout.port = (uint16_t)(qual >> 16);
2312		vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
2313		if (vmexit->u.inout.string) {
2314			inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
2315			vmexit->exitcode = VM_EXITCODE_INOUT_STR;
2316			vis = &vmexit->u.inout_str;
2317			vmx_paging_info(&vis->paging);
2318			vis->rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2319			vis->cr0 = vmcs_read(VMCS_GUEST_CR0);
2320			vis->index = inout_str_index(vmx, vcpu, in);
2321			vis->count = inout_str_count(vmx, vcpu, vis->inout.rep);
2322			vis->addrsize = inout_str_addrsize(inst_info);
2323			inout_str_seginfo(vmx, vcpu, inst_info, in, vis);
2324		}
2325		break;
2326	case EXIT_REASON_CPUID:
2327		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2328		handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
2329		break;
2330	case EXIT_REASON_EXCEPTION:
2331		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2332		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2333		KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2334		    ("VM exit interruption info invalid: %#x", intr_info));
2335
2336		intr_vec = intr_info & 0xff;
2337		intr_type = intr_info & VMCS_INTR_T_MASK;
2338
2339		/*
2340		 * If Virtual NMIs control is 1 and the VM-exit is due to a
2341		 * fault encountered during the execution of IRET then we must
2342		 * restore the state of "virtual-NMI blocking" before resuming
2343		 * the guest.
2344		 *
2345		 * See "Resuming Guest Software after Handling an Exception".
2346		 * See "Information for VM Exits Due to Vectored Events".
2347		 */
2348		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2349		    (intr_vec != IDT_DF) &&
2350		    (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2351			vmx_restore_nmi_blocking(vmx, vcpu);
2352
2353		/*
2354		 * The NMI has already been handled in vmx_exit_handle_nmi().
2355		 */
2356		if (intr_type == VMCS_INTR_T_NMI)
2357			return (1);
2358
2359		/*
2360		 * Call the machine check handler by hand. Also don't reflect
2361		 * the machine check back into the guest.
2362		 */
2363		if (intr_vec == IDT_MC) {
2364			VCPU_CTR0(vmx->vm, vcpu, "Vectoring to MCE handler");
2365			__asm __volatile("int $18");
2366			return (1);
2367		}
2368
2369		if (intr_vec == IDT_PF) {
2370			error = vmxctx_setreg(vmxctx, VM_REG_GUEST_CR2, qual);
2371			KASSERT(error == 0, ("%s: vmxctx_setreg(cr2) error %d",
2372			    __func__, error));
2373		}
2374
2375		/*
2376		 * Software exceptions exhibit trap-like behavior. This in
2377		 * turn requires populating the VM-entry instruction length
2378		 * so that the %rip in the trap frame is past the INT3/INTO
2379		 * instruction.
2380		 */
2381		if (intr_type == VMCS_INTR_T_SWEXCEPTION)
2382			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2383
2384		/* Reflect all other exceptions back into the guest */
2385		errcode_valid = errcode = 0;
2386		if (intr_info & VMCS_INTR_DEL_ERRCODE) {
2387			errcode_valid = 1;
2388			errcode = vmcs_read(VMCS_EXIT_INTR_ERRCODE);
2389		}
2390		VCPU_CTR2(vmx->vm, vcpu, "Reflecting exception %d/%#x into "
2391		    "the guest", intr_vec, errcode);
2392		error = vm_inject_exception(vmx->vm, vcpu, intr_vec,
2393		    errcode_valid, errcode, 0);
2394		KASSERT(error == 0, ("%s: vm_inject_exception error %d",
2395		    __func__, error));
2396		return (1);
2397
2398	case EXIT_REASON_EPT_FAULT:
2399		/*
2400		 * If 'gpa' lies within the address space allocated to
2401		 * memory then this must be a nested page fault otherwise
2402		 * this must be an instruction that accesses MMIO space.
2403		 */
2404		gpa = vmcs_gpa();
2405		if (vm_mem_allocated(vmx->vm, gpa) ||
2406		    apic_access_fault(vmx, vcpu, gpa)) {
2407			vmexit->exitcode = VM_EXITCODE_PAGING;
2408			vmexit->inst_length = 0;
2409			vmexit->u.paging.gpa = gpa;
2410			vmexit->u.paging.fault_type = ept_fault_type(qual);
2411			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2412		} else if (ept_emulation_fault(qual)) {
2413			vmexit_inst_emul(vmexit, gpa, vmcs_gla());
2414			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1);
2415		}
2416		/*
2417		 * If Virtual NMIs control is 1 and the VM-exit is due to an
2418		 * EPT fault during the execution of IRET then we must restore
2419		 * the state of "virtual-NMI blocking" before resuming.
2420		 *
2421		 * See description of "NMI unblocking due to IRET" in
2422		 * "Exit Qualification for EPT Violations".
2423		 */
2424		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2425		    (qual & EXIT_QUAL_NMIUDTI) != 0)
2426			vmx_restore_nmi_blocking(vmx, vcpu);
2427		break;
2428	case EXIT_REASON_VIRTUALIZED_EOI:
2429		vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2430		vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2431		vmexit->inst_length = 0;	/* trap-like */
2432		break;
2433	case EXIT_REASON_APIC_ACCESS:
2434		handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2435		break;
2436	case EXIT_REASON_APIC_WRITE:
2437		/*
2438		 * APIC-write VM exit is trap-like so the %rip is already
2439		 * pointing to the next instruction.
2440		 */
2441		vmexit->inst_length = 0;
2442		vlapic = vm_lapic(vmx->vm, vcpu);
2443		handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2444		break;
2445	case EXIT_REASON_XSETBV:
2446		handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2447		break;
2448	case EXIT_REASON_MONITOR:
2449		vmexit->exitcode = VM_EXITCODE_MONITOR;
2450		break;
2451	case EXIT_REASON_MWAIT:
2452		vmexit->exitcode = VM_EXITCODE_MWAIT;
2453		break;
2454	default:
2455		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2456		break;
2457	}
2458
2459	if (handled) {
2460		/*
2461		 * It is possible that control is returned to userland
2462		 * even though we were able to handle the VM exit in the
2463		 * kernel.
2464		 *
2465		 * In such a case we want to make sure that the userland
2466		 * restarts guest execution at the instruction *after*
2467		 * the one we just processed. Therefore we update the
2468		 * guest rip in the VMCS and in 'vmexit'.
2469		 */
2470		vmexit->rip += vmexit->inst_length;
2471		vmexit->inst_length = 0;
2472		vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2473	} else {
2474		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2475			/*
2476			 * If this VM exit was not claimed by anybody then
2477			 * treat it as a generic VMX exit.
2478			 */
2479			vmexit->exitcode = VM_EXITCODE_VMX;
2480			vmexit->u.vmx.status = VM_SUCCESS;
2481			vmexit->u.vmx.inst_type = 0;
2482			vmexit->u.vmx.inst_error = 0;
2483		} else {
2484			/*
2485			 * The exitcode and collateral have been populated.
2486			 * The VM exit will be processed further in userland.
2487			 */
2488		}
2489	}
2490	return (handled);
2491}
2492
2493static __inline void
2494vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2495{
2496
2497	KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2498	    ("vmx_exit_inst_error: invalid inst_fail_status %d",
2499	    vmxctx->inst_fail_status));
2500
2501	vmexit->inst_length = 0;
2502	vmexit->exitcode = VM_EXITCODE_VMX;
2503	vmexit->u.vmx.status = vmxctx->inst_fail_status;
2504	vmexit->u.vmx.inst_error = vmcs_instruction_error();
2505	vmexit->u.vmx.exit_reason = ~0;
2506	vmexit->u.vmx.exit_qualification = ~0;
2507
2508	switch (rc) {
2509	case VMX_VMRESUME_ERROR:
2510	case VMX_VMLAUNCH_ERROR:
2511	case VMX_INVEPT_ERROR:
2512		vmexit->u.vmx.inst_type = rc;
2513		break;
2514	default:
2515		panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2516	}
2517}
2518
2519/*
2520 * If the NMI-exiting VM execution control is set to '1' then an NMI in
2521 * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2522 * sufficient to simply vector to the NMI handler via a software interrupt.
2523 * However, this must be done before maskable interrupts are enabled
2524 * otherwise the "iret" issued by an interrupt handler will incorrectly
2525 * clear NMI blocking.
2526 */
2527static __inline void
2528vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2529{
2530	uint32_t intr_info;
2531
2532	KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2533
2534	if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2535		return;
2536
2537	intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2538	KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2539	    ("VM exit interruption info invalid: %#x", intr_info));
2540
2541	if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2542		KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2543		    "to NMI has invalid vector: %#x", intr_info));
2544		VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2545		__asm __volatile("int $2");
2546	}
2547}
2548
2549static int
2550vmx_run(void *arg, int vcpu, register_t rip, pmap_t pmap,
2551    void *rendezvous_cookie, void *suspend_cookie)
2552{
2553	int rc, handled, launched;
2554	struct vmx *vmx;
2555	struct vm *vm;
2556	struct vmxctx *vmxctx;
2557	struct vmcs *vmcs;
2558	struct vm_exit *vmexit;
2559	struct vlapic *vlapic;
2560	uint32_t exit_reason;
2561
2562	vmx = arg;
2563	vm = vmx->vm;
2564	vmcs = &vmx->vmcs[vcpu];
2565	vmxctx = &vmx->ctx[vcpu];
2566	vlapic = vm_lapic(vm, vcpu);
2567	vmexit = vm_exitinfo(vm, vcpu);
2568	launched = 0;
2569
2570	KASSERT(vmxctx->pmap == pmap,
2571	    ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
2572
2573	vmx_msr_guest_enter(vmx, vcpu);
2574
2575	VMPTRLD(vmcs);
2576
2577	/*
2578	 * XXX
2579	 * We do this every time because we may setup the virtual machine
2580	 * from a different process than the one that actually runs it.
2581	 *
2582	 * If the life of a virtual machine was spent entirely in the context
2583	 * of a single process we could do this once in vmx_vminit().
2584	 */
2585	vmcs_write(VMCS_HOST_CR3, rcr3());
2586
2587	vmcs_write(VMCS_GUEST_RIP, rip);
2588	vmx_set_pcpu_defaults(vmx, vcpu, pmap);
2589	do {
2590		KASSERT(vmcs_guest_rip() == rip, ("%s: vmcs guest rip mismatch "
2591		    "%#lx/%#lx", __func__, vmcs_guest_rip(), rip));
2592
2593		handled = UNHANDLED;
2594		/*
2595		 * Interrupts are disabled from this point on until the
2596		 * guest starts executing. This is done for the following
2597		 * reasons:
2598		 *
2599		 * If an AST is asserted on this thread after the check below,
2600		 * then the IPI_AST notification will not be lost, because it
2601		 * will cause a VM exit due to external interrupt as soon as
2602		 * the guest state is loaded.
2603		 *
2604		 * A posted interrupt after 'vmx_inject_interrupts()' will
2605		 * not be "lost" because it will be held pending in the host
2606		 * APIC because interrupts are disabled. The pending interrupt
2607		 * will be recognized as soon as the guest state is loaded.
2608		 *
2609		 * The same reasoning applies to the IPI generated by
2610		 * pmap_invalidate_ept().
2611		 */
2612		disable_intr();
2613		vmx_inject_interrupts(vmx, vcpu, vlapic, rip);
2614
2615		/*
2616		 * Check for vcpu suspension after injecting events because
2617		 * vmx_inject_interrupts() can suspend the vcpu due to a
2618		 * triple fault.
2619		 */
2620		if (vcpu_suspended(suspend_cookie)) {
2621			enable_intr();
2622			vm_exit_suspended(vmx->vm, vcpu, rip);
2623			break;
2624		}
2625
2626		if (vcpu_rendezvous_pending(rendezvous_cookie)) {
2627			enable_intr();
2628			vm_exit_rendezvous(vmx->vm, vcpu, rip);
2629			break;
2630		}
2631
2632		if (vcpu_should_yield(vm, vcpu)) {
2633			enable_intr();
2634			vm_exit_astpending(vmx->vm, vcpu, rip);
2635			vmx_astpending_trace(vmx, vcpu, rip);
2636			handled = HANDLED;
2637			break;
2638		}
2639
2640		vmx_run_trace(vmx, vcpu);
2641		rc = vmx_enter_guest(vmxctx, vmx, launched);
2642
2643		/* Collect some information for VM exit processing */
2644		vmexit->rip = rip = vmcs_guest_rip();
2645		vmexit->inst_length = vmexit_instruction_length();
2646		vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
2647		vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
2648
2649		/* Update 'nextrip' */
2650		vmx->state[vcpu].nextrip = rip;
2651
2652		if (rc == VMX_GUEST_VMEXIT) {
2653			vmx_exit_handle_nmi(vmx, vcpu, vmexit);
2654			enable_intr();
2655			handled = vmx_exit_process(vmx, vcpu, vmexit);
2656		} else {
2657			enable_intr();
2658			vmx_exit_inst_error(vmxctx, rc, vmexit);
2659		}
2660		launched = 1;
2661		vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
2662		rip = vmexit->rip;
2663	} while (handled);
2664
2665	/*
2666	 * If a VM exit has been handled then the exitcode must be BOGUS
2667	 * If a VM exit is not handled then the exitcode must not be BOGUS
2668	 */
2669	if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
2670	    (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
2671		panic("Mismatch between handled (%d) and exitcode (%d)",
2672		      handled, vmexit->exitcode);
2673	}
2674
2675	if (!handled)
2676		vmm_stat_incr(vm, vcpu, VMEXIT_USERSPACE, 1);
2677
2678	VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
2679	    vmexit->exitcode);
2680
2681	VMCLEAR(vmcs);
2682	vmx_msr_guest_exit(vmx, vcpu);
2683
2684	return (0);
2685}
2686
2687static void
2688vmx_vmcleanup(void *arg)
2689{
2690	int i;
2691	struct vmx *vmx = arg;
2692
2693	if (apic_access_virtualization(vmx, 0))
2694		vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2695
2696	for (i = 0; i < VM_MAXCPU; i++)
2697		vpid_free(vmx->state[i].vpid);
2698
2699	free(vmx, M_VMX);
2700
2701	return;
2702}
2703
2704static register_t *
2705vmxctx_regptr(struct vmxctx *vmxctx, int reg)
2706{
2707
2708	switch (reg) {
2709	case VM_REG_GUEST_RAX:
2710		return (&vmxctx->guest_rax);
2711	case VM_REG_GUEST_RBX:
2712		return (&vmxctx->guest_rbx);
2713	case VM_REG_GUEST_RCX:
2714		return (&vmxctx->guest_rcx);
2715	case VM_REG_GUEST_RDX:
2716		return (&vmxctx->guest_rdx);
2717	case VM_REG_GUEST_RSI:
2718		return (&vmxctx->guest_rsi);
2719	case VM_REG_GUEST_RDI:
2720		return (&vmxctx->guest_rdi);
2721	case VM_REG_GUEST_RBP:
2722		return (&vmxctx->guest_rbp);
2723	case VM_REG_GUEST_R8:
2724		return (&vmxctx->guest_r8);
2725	case VM_REG_GUEST_R9:
2726		return (&vmxctx->guest_r9);
2727	case VM_REG_GUEST_R10:
2728		return (&vmxctx->guest_r10);
2729	case VM_REG_GUEST_R11:
2730		return (&vmxctx->guest_r11);
2731	case VM_REG_GUEST_R12:
2732		return (&vmxctx->guest_r12);
2733	case VM_REG_GUEST_R13:
2734		return (&vmxctx->guest_r13);
2735	case VM_REG_GUEST_R14:
2736		return (&vmxctx->guest_r14);
2737	case VM_REG_GUEST_R15:
2738		return (&vmxctx->guest_r15);
2739	case VM_REG_GUEST_CR2:
2740		return (&vmxctx->guest_cr2);
2741	default:
2742		break;
2743	}
2744	return (NULL);
2745}
2746
2747static int
2748vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
2749{
2750	register_t *regp;
2751
2752	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2753		*retval = *regp;
2754		return (0);
2755	} else
2756		return (EINVAL);
2757}
2758
2759static int
2760vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
2761{
2762	register_t *regp;
2763
2764	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2765		*regp = val;
2766		return (0);
2767	} else
2768		return (EINVAL);
2769}
2770
2771static int
2772vmx_get_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t *retval)
2773{
2774	uint64_t gi;
2775	int error;
2776
2777	error = vmcs_getreg(&vmx->vmcs[vcpu], running,
2778	    VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY), &gi);
2779	*retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
2780	return (error);
2781}
2782
2783static int
2784vmx_modify_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t val)
2785{
2786	struct vmcs *vmcs;
2787	uint64_t gi;
2788	int error, ident;
2789
2790	/*
2791	 * Forcing the vcpu into an interrupt shadow is not supported.
2792	 */
2793	if (val) {
2794		error = EINVAL;
2795		goto done;
2796	}
2797
2798	vmcs = &vmx->vmcs[vcpu];
2799	ident = VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY);
2800	error = vmcs_getreg(vmcs, running, ident, &gi);
2801	if (error == 0) {
2802		gi &= ~HWINTR_BLOCKING;
2803		error = vmcs_setreg(vmcs, running, ident, gi);
2804	}
2805done:
2806	VCPU_CTR2(vmx->vm, vcpu, "Setting intr_shadow to %#lx %s", val,
2807	    error ? "failed" : "succeeded");
2808	return (error);
2809}
2810
2811static int
2812vmx_shadow_reg(int reg)
2813{
2814	int shreg;
2815
2816	shreg = -1;
2817
2818	switch (reg) {
2819	case VM_REG_GUEST_CR0:
2820		shreg = VMCS_CR0_SHADOW;
2821                break;
2822        case VM_REG_GUEST_CR4:
2823		shreg = VMCS_CR4_SHADOW;
2824		break;
2825	default:
2826		break;
2827	}
2828
2829	return (shreg);
2830}
2831
2832static int
2833vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
2834{
2835	int running, hostcpu;
2836	struct vmx *vmx = arg;
2837
2838	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2839	if (running && hostcpu != curcpu)
2840		panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
2841
2842	if (reg == VM_REG_GUEST_INTR_SHADOW)
2843		return (vmx_get_intr_shadow(vmx, vcpu, running, retval));
2844
2845	if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
2846		return (0);
2847
2848	return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
2849}
2850
2851static int
2852vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
2853{
2854	int error, hostcpu, running, shadow;
2855	uint64_t ctls;
2856	pmap_t pmap;
2857	struct vmx *vmx = arg;
2858
2859	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2860	if (running && hostcpu != curcpu)
2861		panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
2862
2863	if (reg == VM_REG_GUEST_INTR_SHADOW)
2864		return (vmx_modify_intr_shadow(vmx, vcpu, running, val));
2865
2866	if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
2867		return (0);
2868
2869	error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
2870
2871	if (error == 0) {
2872		/*
2873		 * If the "load EFER" VM-entry control is 1 then the
2874		 * value of EFER.LMA must be identical to "IA-32e mode guest"
2875		 * bit in the VM-entry control.
2876		 */
2877		if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
2878		    (reg == VM_REG_GUEST_EFER)) {
2879			vmcs_getreg(&vmx->vmcs[vcpu], running,
2880				    VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
2881			if (val & EFER_LMA)
2882				ctls |= VM_ENTRY_GUEST_LMA;
2883			else
2884				ctls &= ~VM_ENTRY_GUEST_LMA;
2885			vmcs_setreg(&vmx->vmcs[vcpu], running,
2886				    VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
2887		}
2888
2889		shadow = vmx_shadow_reg(reg);
2890		if (shadow > 0) {
2891			/*
2892			 * Store the unmodified value in the shadow
2893			 */
2894			error = vmcs_setreg(&vmx->vmcs[vcpu], running,
2895				    VMCS_IDENT(shadow), val);
2896		}
2897
2898		if (reg == VM_REG_GUEST_CR3) {
2899			/*
2900			 * Invalidate the guest vcpu's TLB mappings to emulate
2901			 * the behavior of updating %cr3.
2902			 *
2903			 * XXX the processor retains global mappings when %cr3
2904			 * is updated but vmx_invvpid() does not.
2905			 */
2906			pmap = vmx->ctx[vcpu].pmap;
2907			vmx_invvpid(vmx, vcpu, pmap, running);
2908		}
2909	}
2910
2911	return (error);
2912}
2913
2914static int
2915vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2916{
2917	int hostcpu, running;
2918	struct vmx *vmx = arg;
2919
2920	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2921	if (running && hostcpu != curcpu)
2922		panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2923
2924	return (vmcs_getdesc(&vmx->vmcs[vcpu], running, reg, desc));
2925}
2926
2927static int
2928vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2929{
2930	int hostcpu, running;
2931	struct vmx *vmx = arg;
2932
2933	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2934	if (running && hostcpu != curcpu)
2935		panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2936
2937	return (vmcs_setdesc(&vmx->vmcs[vcpu], running, reg, desc));
2938}
2939
2940static int
2941vmx_getcap(void *arg, int vcpu, int type, int *retval)
2942{
2943	struct vmx *vmx = arg;
2944	int vcap;
2945	int ret;
2946
2947	ret = ENOENT;
2948
2949	vcap = vmx->cap[vcpu].set;
2950
2951	switch (type) {
2952	case VM_CAP_HALT_EXIT:
2953		if (cap_halt_exit)
2954			ret = 0;
2955		break;
2956	case VM_CAP_PAUSE_EXIT:
2957		if (cap_pause_exit)
2958			ret = 0;
2959		break;
2960	case VM_CAP_MTRAP_EXIT:
2961		if (cap_monitor_trap)
2962			ret = 0;
2963		break;
2964	case VM_CAP_UNRESTRICTED_GUEST:
2965		if (cap_unrestricted_guest)
2966			ret = 0;
2967		break;
2968	case VM_CAP_ENABLE_INVPCID:
2969		if (cap_invpcid)
2970			ret = 0;
2971		break;
2972	default:
2973		break;
2974	}
2975
2976	if (ret == 0)
2977		*retval = (vcap & (1 << type)) ? 1 : 0;
2978
2979	return (ret);
2980}
2981
2982static int
2983vmx_setcap(void *arg, int vcpu, int type, int val)
2984{
2985	struct vmx *vmx = arg;
2986	struct vmcs *vmcs = &vmx->vmcs[vcpu];
2987	uint32_t baseval;
2988	uint32_t *pptr;
2989	int error;
2990	int flag;
2991	int reg;
2992	int retval;
2993
2994	retval = ENOENT;
2995	pptr = NULL;
2996
2997	switch (type) {
2998	case VM_CAP_HALT_EXIT:
2999		if (cap_halt_exit) {
3000			retval = 0;
3001			pptr = &vmx->cap[vcpu].proc_ctls;
3002			baseval = *pptr;
3003			flag = PROCBASED_HLT_EXITING;
3004			reg = VMCS_PRI_PROC_BASED_CTLS;
3005		}
3006		break;
3007	case VM_CAP_MTRAP_EXIT:
3008		if (cap_monitor_trap) {
3009			retval = 0;
3010			pptr = &vmx->cap[vcpu].proc_ctls;
3011			baseval = *pptr;
3012			flag = PROCBASED_MTF;
3013			reg = VMCS_PRI_PROC_BASED_CTLS;
3014		}
3015		break;
3016	case VM_CAP_PAUSE_EXIT:
3017		if (cap_pause_exit) {
3018			retval = 0;
3019			pptr = &vmx->cap[vcpu].proc_ctls;
3020			baseval = *pptr;
3021			flag = PROCBASED_PAUSE_EXITING;
3022			reg = VMCS_PRI_PROC_BASED_CTLS;
3023		}
3024		break;
3025	case VM_CAP_UNRESTRICTED_GUEST:
3026		if (cap_unrestricted_guest) {
3027			retval = 0;
3028			pptr = &vmx->cap[vcpu].proc_ctls2;
3029			baseval = *pptr;
3030			flag = PROCBASED2_UNRESTRICTED_GUEST;
3031			reg = VMCS_SEC_PROC_BASED_CTLS;
3032		}
3033		break;
3034	case VM_CAP_ENABLE_INVPCID:
3035		if (cap_invpcid) {
3036			retval = 0;
3037			pptr = &vmx->cap[vcpu].proc_ctls2;
3038			baseval = *pptr;
3039			flag = PROCBASED2_ENABLE_INVPCID;
3040			reg = VMCS_SEC_PROC_BASED_CTLS;
3041		}
3042		break;
3043	default:
3044		break;
3045	}
3046
3047	if (retval == 0) {
3048		if (val) {
3049			baseval |= flag;
3050		} else {
3051			baseval &= ~flag;
3052		}
3053		VMPTRLD(vmcs);
3054		error = vmwrite(reg, baseval);
3055		VMCLEAR(vmcs);
3056
3057		if (error) {
3058			retval = error;
3059		} else {
3060			/*
3061			 * Update optional stored flags, and record
3062			 * setting
3063			 */
3064			if (pptr != NULL) {
3065				*pptr = baseval;
3066			}
3067
3068			if (val) {
3069				vmx->cap[vcpu].set |= (1 << type);
3070			} else {
3071				vmx->cap[vcpu].set &= ~(1 << type);
3072			}
3073		}
3074	}
3075
3076        return (retval);
3077}
3078
3079struct vlapic_vtx {
3080	struct vlapic	vlapic;
3081	struct pir_desc	*pir_desc;
3082	struct vmx	*vmx;
3083};
3084
3085#define	VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg)	\
3086do {									\
3087	VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d",	\
3088	    level ? "level" : "edge", vector);				\
3089	VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]);	\
3090	VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]);	\
3091	VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]);	\
3092	VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]);	\
3093	VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
3094} while (0)
3095
3096/*
3097 * vlapic->ops handlers that utilize the APICv hardware assist described in
3098 * Chapter 29 of the Intel SDM.
3099 */
3100static int
3101vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3102{
3103	struct vlapic_vtx *vlapic_vtx;
3104	struct pir_desc *pir_desc;
3105	uint64_t mask;
3106	int idx, notify;
3107
3108	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3109	pir_desc = vlapic_vtx->pir_desc;
3110
3111	/*
3112	 * Keep track of interrupt requests in the PIR descriptor. This is
3113	 * because the virtual APIC page pointed to by the VMCS cannot be
3114	 * modified if the vcpu is running.
3115	 */
3116	idx = vector / 64;
3117	mask = 1UL << (vector % 64);
3118	atomic_set_long(&pir_desc->pir[idx], mask);
3119	notify = atomic_cmpset_long(&pir_desc->pending, 0, 1);
3120
3121	VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
3122	    level, "vmx_set_intr_ready");
3123	return (notify);
3124}
3125
3126static int
3127vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3128{
3129	struct vlapic_vtx *vlapic_vtx;
3130	struct pir_desc *pir_desc;
3131	struct LAPIC *lapic;
3132	uint64_t pending, pirval;
3133	uint32_t ppr, vpr;
3134	int i;
3135
3136	/*
3137	 * This function is only expected to be called from the 'HLT' exit
3138	 * handler which does not care about the vector that is pending.
3139	 */
3140	KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3141
3142	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3143	pir_desc = vlapic_vtx->pir_desc;
3144
3145	pending = atomic_load_acq_long(&pir_desc->pending);
3146	if (!pending)
3147		return (0);	/* common case */
3148
3149	/*
3150	 * If there is an interrupt pending then it will be recognized only
3151	 * if its priority is greater than the processor priority.
3152	 *
3153	 * Special case: if the processor priority is zero then any pending
3154	 * interrupt will be recognized.
3155	 */
3156	lapic = vlapic->apic_page;
3157	ppr = lapic->ppr & 0xf0;
3158	if (ppr == 0)
3159		return (1);
3160
3161	VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
3162	    lapic->ppr);
3163
3164	for (i = 3; i >= 0; i--) {
3165		pirval = pir_desc->pir[i];
3166		if (pirval != 0) {
3167			vpr = (i * 64 + flsl(pirval) - 1) & 0xf0;
3168			return (vpr > ppr);
3169		}
3170	}
3171	return (0);
3172}
3173
3174static void
3175vmx_intr_accepted(struct vlapic *vlapic, int vector)
3176{
3177
3178	panic("vmx_intr_accepted: not expected to be called");
3179}
3180
3181static void
3182vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3183{
3184	struct vlapic_vtx *vlapic_vtx;
3185	struct vmx *vmx;
3186	struct vmcs *vmcs;
3187	uint64_t mask, val;
3188
3189	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3190	KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
3191	    ("vmx_set_tmr: vcpu cannot be running"));
3192
3193	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3194	vmx = vlapic_vtx->vmx;
3195	vmcs = &vmx->vmcs[vlapic->vcpuid];
3196	mask = 1UL << (vector % 64);
3197
3198	VMPTRLD(vmcs);
3199	val = vmcs_read(VMCS_EOI_EXIT(vector));
3200	if (level)
3201		val |= mask;
3202	else
3203		val &= ~mask;
3204	vmcs_write(VMCS_EOI_EXIT(vector), val);
3205	VMCLEAR(vmcs);
3206}
3207
3208static void
3209vmx_enable_x2apic_mode(struct vlapic *vlapic)
3210{
3211	struct vmx *vmx;
3212	struct vmcs *vmcs;
3213	uint32_t proc_ctls2;
3214	int vcpuid, error;
3215
3216	vcpuid = vlapic->vcpuid;
3217	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3218	vmcs = &vmx->vmcs[vcpuid];
3219
3220	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3221	KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3222	    ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3223
3224	proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3225	proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3226	vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3227
3228	VMPTRLD(vmcs);
3229	vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3230	VMCLEAR(vmcs);
3231
3232	if (vlapic->vcpuid == 0) {
3233		/*
3234		 * The nested page table mappings are shared by all vcpus
3235		 * so unmap the APIC access page just once.
3236		 */
3237		error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3238		KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3239		    __func__, error));
3240
3241		/*
3242		 * The MSR bitmap is shared by all vcpus so modify it only
3243		 * once in the context of vcpu 0.
3244		 */
3245		error = vmx_allow_x2apic_msrs(vmx);
3246		KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3247		    __func__, error));
3248	}
3249}
3250
3251static void
3252vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3253{
3254
3255	ipi_cpu(hostcpu, pirvec);
3256}
3257
3258/*
3259 * Transfer the pending interrupts in the PIR descriptor to the IRR
3260 * in the virtual APIC page.
3261 */
3262static void
3263vmx_inject_pir(struct vlapic *vlapic)
3264{
3265	struct vlapic_vtx *vlapic_vtx;
3266	struct pir_desc *pir_desc;
3267	struct LAPIC *lapic;
3268	uint64_t val, pirval;
3269	int rvi, pirbase = -1;
3270	uint16_t intr_status_old, intr_status_new;
3271
3272	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3273	pir_desc = vlapic_vtx->pir_desc;
3274	if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3275		VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3276		    "no posted interrupt pending");
3277		return;
3278	}
3279
3280	pirval = 0;
3281	pirbase = -1;
3282	lapic = vlapic->apic_page;
3283
3284	val = atomic_readandclear_long(&pir_desc->pir[0]);
3285	if (val != 0) {
3286		lapic->irr0 |= val;
3287		lapic->irr1 |= val >> 32;
3288		pirbase = 0;
3289		pirval = val;
3290	}
3291
3292	val = atomic_readandclear_long(&pir_desc->pir[1]);
3293	if (val != 0) {
3294		lapic->irr2 |= val;
3295		lapic->irr3 |= val >> 32;
3296		pirbase = 64;
3297		pirval = val;
3298	}
3299
3300	val = atomic_readandclear_long(&pir_desc->pir[2]);
3301	if (val != 0) {
3302		lapic->irr4 |= val;
3303		lapic->irr5 |= val >> 32;
3304		pirbase = 128;
3305		pirval = val;
3306	}
3307
3308	val = atomic_readandclear_long(&pir_desc->pir[3]);
3309	if (val != 0) {
3310		lapic->irr6 |= val;
3311		lapic->irr7 |= val >> 32;
3312		pirbase = 192;
3313		pirval = val;
3314	}
3315
3316	VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
3317
3318	/*
3319	 * Update RVI so the processor can evaluate pending virtual
3320	 * interrupts on VM-entry.
3321	 *
3322	 * It is possible for pirval to be 0 here, even though the
3323	 * pending bit has been set. The scenario is:
3324	 * CPU-Y is sending a posted interrupt to CPU-X, which
3325	 * is running a guest and processing posted interrupts in h/w.
3326	 * CPU-X will eventually exit and the state seen in s/w is
3327	 * the pending bit set, but no PIR bits set.
3328	 *
3329	 *      CPU-X                      CPU-Y
3330	 *   (vm running)                (host running)
3331	 *   rx posted interrupt
3332	 *   CLEAR pending bit
3333	 *				 SET PIR bit
3334	 *   READ/CLEAR PIR bits
3335	 *				 SET pending bit
3336	 *   (vm exit)
3337	 *   pending bit set, PIR 0
3338	 */
3339	if (pirval != 0) {
3340		rvi = pirbase + flsl(pirval) - 1;
3341		intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
3342		intr_status_new = (intr_status_old & 0xFF00) | rvi;
3343		if (intr_status_new > intr_status_old) {
3344			vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
3345			VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3346			    "guest_intr_status changed from 0x%04x to 0x%04x",
3347			    intr_status_old, intr_status_new);
3348		}
3349	}
3350}
3351
3352static struct vlapic *
3353vmx_vlapic_init(void *arg, int vcpuid)
3354{
3355	struct vmx *vmx;
3356	struct vlapic *vlapic;
3357	struct vlapic_vtx *vlapic_vtx;
3358
3359	vmx = arg;
3360
3361	vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
3362	vlapic->vm = vmx->vm;
3363	vlapic->vcpuid = vcpuid;
3364	vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
3365
3366	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3367	vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
3368	vlapic_vtx->vmx = vmx;
3369
3370	if (virtual_interrupt_delivery) {
3371		vlapic->ops.set_intr_ready = vmx_set_intr_ready;
3372		vlapic->ops.pending_intr = vmx_pending_intr;
3373		vlapic->ops.intr_accepted = vmx_intr_accepted;
3374		vlapic->ops.set_tmr = vmx_set_tmr;
3375		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode;
3376	}
3377
3378	if (posted_interrupts)
3379		vlapic->ops.post_intr = vmx_post_intr;
3380
3381	vlapic_init(vlapic);
3382
3383	return (vlapic);
3384}
3385
3386static void
3387vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
3388{
3389
3390	vlapic_cleanup(vlapic);
3391	free(vlapic, M_VLAPIC);
3392}
3393
3394struct vmm_ops vmm_ops_intel = {
3395	vmx_init,
3396	vmx_cleanup,
3397	vmx_restore,
3398	vmx_vminit,
3399	vmx_run,
3400	vmx_vmcleanup,
3401	vmx_getreg,
3402	vmx_setreg,
3403	vmx_getdesc,
3404	vmx_setdesc,
3405	vmx_getcap,
3406	vmx_setcap,
3407	ept_vmspace_alloc,
3408	ept_vmspace_free,
3409	vmx_vlapic_init,
3410	vmx_vlapic_cleanup,
3411};
3412