xref: /freebsd/sys/amd64/vmm/intel/vmx.c (revision 6b129086dcee14496517fae085b448e3edc69bc7)
1 /*-
2  * Copyright (c) 2011 NetApp, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/smp.h>
35 #include <sys/kernel.h>
36 #include <sys/malloc.h>
37 #include <sys/pcpu.h>
38 #include <sys/proc.h>
39 #include <sys/sysctl.h>
40 
41 #include <vm/vm.h>
42 #include <vm/pmap.h>
43 
44 #include <machine/psl.h>
45 #include <machine/cpufunc.h>
46 #include <machine/md_var.h>
47 #include <machine/segments.h>
48 #include <machine/smp.h>
49 #include <machine/specialreg.h>
50 #include <machine/vmparam.h>
51 
52 #include <machine/vmm.h>
53 #include <machine/vmm_dev.h>
54 #include <machine/vmm_instruction_emul.h>
55 #include "vmm_lapic.h"
56 #include "vmm_host.h"
57 #include "vmm_ioport.h"
58 #include "vmm_ipi.h"
59 #include "vmm_ktr.h"
60 #include "vmm_stat.h"
61 #include "vatpic.h"
62 #include "vlapic.h"
63 #include "vlapic_priv.h"
64 
65 #include "ept.h"
66 #include "vmx_cpufunc.h"
67 #include "vmx.h"
68 #include "vmx_msr.h"
69 #include "x86.h"
70 #include "vmx_controls.h"
71 
72 #define	PINBASED_CTLS_ONE_SETTING					\
73 	(PINBASED_EXTINT_EXITING	|				\
74 	 PINBASED_NMI_EXITING		|				\
75 	 PINBASED_VIRTUAL_NMI)
76 #define	PINBASED_CTLS_ZERO_SETTING	0
77 
78 #define PROCBASED_CTLS_WINDOW_SETTING					\
79 	(PROCBASED_INT_WINDOW_EXITING	|				\
80 	 PROCBASED_NMI_WINDOW_EXITING)
81 
82 #define	PROCBASED_CTLS_ONE_SETTING 					\
83 	(PROCBASED_SECONDARY_CONTROLS	|				\
84 	 PROCBASED_MWAIT_EXITING	|				\
85 	 PROCBASED_MONITOR_EXITING	|				\
86 	 PROCBASED_IO_EXITING		|				\
87 	 PROCBASED_MSR_BITMAPS		|				\
88 	 PROCBASED_CTLS_WINDOW_SETTING	|				\
89 	 PROCBASED_CR8_LOAD_EXITING	|				\
90 	 PROCBASED_CR8_STORE_EXITING)
91 #define	PROCBASED_CTLS_ZERO_SETTING	\
92 	(PROCBASED_CR3_LOAD_EXITING |	\
93 	PROCBASED_CR3_STORE_EXITING |	\
94 	PROCBASED_IO_BITMAPS)
95 
96 #define	PROCBASED_CTLS2_ONE_SETTING	PROCBASED2_ENABLE_EPT
97 #define	PROCBASED_CTLS2_ZERO_SETTING	0
98 
99 #define	VM_EXIT_CTLS_ONE_SETTING					\
100 	(VM_EXIT_HOST_LMA			|			\
101 	VM_EXIT_SAVE_EFER			|			\
102 	VM_EXIT_LOAD_EFER			|			\
103 	VM_EXIT_ACKNOWLEDGE_INTERRUPT		|			\
104 	VM_EXIT_SAVE_PAT			|			\
105 	VM_EXIT_LOAD_PAT)
106 
107 #define	VM_EXIT_CTLS_ZERO_SETTING	VM_EXIT_SAVE_DEBUG_CONTROLS
108 
109 #define	VM_ENTRY_CTLS_ONE_SETTING	(VM_ENTRY_LOAD_EFER | VM_ENTRY_LOAD_PAT)
110 
111 #define	VM_ENTRY_CTLS_ZERO_SETTING					\
112 	(VM_ENTRY_LOAD_DEBUG_CONTROLS		|			\
113 	VM_ENTRY_INTO_SMM			|			\
114 	VM_ENTRY_DEACTIVATE_DUAL_MONITOR)
115 
116 #define	HANDLED		1
117 #define	UNHANDLED	0
118 
119 static MALLOC_DEFINE(M_VMX, "vmx", "vmx");
120 static MALLOC_DEFINE(M_VLAPIC, "vlapic", "vlapic");
121 
122 SYSCTL_DECL(_hw_vmm);
123 SYSCTL_NODE(_hw_vmm, OID_AUTO, vmx, CTLFLAG_RW, NULL, NULL);
124 
125 int vmxon_enabled[MAXCPU];
126 static char vmxon_region[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
127 
128 static uint32_t pinbased_ctls, procbased_ctls, procbased_ctls2;
129 static uint32_t exit_ctls, entry_ctls;
130 
131 static uint64_t cr0_ones_mask, cr0_zeros_mask;
132 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_ones_mask, CTLFLAG_RD,
133 	     &cr0_ones_mask, 0, NULL);
134 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr0_zeros_mask, CTLFLAG_RD,
135 	     &cr0_zeros_mask, 0, NULL);
136 
137 static uint64_t cr4_ones_mask, cr4_zeros_mask;
138 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_ones_mask, CTLFLAG_RD,
139 	     &cr4_ones_mask, 0, NULL);
140 SYSCTL_ULONG(_hw_vmm_vmx, OID_AUTO, cr4_zeros_mask, CTLFLAG_RD,
141 	     &cr4_zeros_mask, 0, NULL);
142 
143 static int vmx_initialized;
144 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, initialized, CTLFLAG_RD,
145 	   &vmx_initialized, 0, "Intel VMX initialized");
146 
147 /*
148  * Optional capabilities
149  */
150 static SYSCTL_NODE(_hw_vmm_vmx, OID_AUTO, cap, CTLFLAG_RW, NULL, NULL);
151 
152 static int cap_halt_exit;
153 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, halt_exit, CTLFLAG_RD, &cap_halt_exit, 0,
154     "HLT triggers a VM-exit");
155 
156 static int cap_pause_exit;
157 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, pause_exit, CTLFLAG_RD, &cap_pause_exit,
158     0, "PAUSE triggers a VM-exit");
159 
160 static int cap_unrestricted_guest;
161 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, unrestricted_guest, CTLFLAG_RD,
162     &cap_unrestricted_guest, 0, "Unrestricted guests");
163 
164 static int cap_monitor_trap;
165 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, monitor_trap, CTLFLAG_RD,
166     &cap_monitor_trap, 0, "Monitor trap flag");
167 
168 static int cap_invpcid;
169 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, invpcid, CTLFLAG_RD, &cap_invpcid,
170     0, "Guests are allowed to use INVPCID");
171 
172 static int virtual_interrupt_delivery;
173 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, virtual_interrupt_delivery, CTLFLAG_RD,
174     &virtual_interrupt_delivery, 0, "APICv virtual interrupt delivery support");
175 
176 static int posted_interrupts;
177 SYSCTL_INT(_hw_vmm_vmx_cap, OID_AUTO, posted_interrupts, CTLFLAG_RD,
178     &posted_interrupts, 0, "APICv posted interrupt support");
179 
180 static int pirvec;
181 SYSCTL_INT(_hw_vmm_vmx, OID_AUTO, posted_interrupt_vector, CTLFLAG_RD,
182     &pirvec, 0, "APICv posted interrupt vector");
183 
184 static struct unrhdr *vpid_unr;
185 static u_int vpid_alloc_failed;
186 SYSCTL_UINT(_hw_vmm_vmx, OID_AUTO, vpid_alloc_failed, CTLFLAG_RD,
187 	    &vpid_alloc_failed, 0, NULL);
188 
189 /*
190  * Use the last page below 4GB as the APIC access address. This address is
191  * occupied by the boot firmware so it is guaranteed that it will not conflict
192  * with a page in system memory.
193  */
194 #define	APIC_ACCESS_ADDRESS	0xFFFFF000
195 
196 static int vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc);
197 static int vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval);
198 static int vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val);
199 static void vmx_inject_pir(struct vlapic *vlapic);
200 
201 #ifdef KTR
202 static const char *
203 exit_reason_to_str(int reason)
204 {
205 	static char reasonbuf[32];
206 
207 	switch (reason) {
208 	case EXIT_REASON_EXCEPTION:
209 		return "exception";
210 	case EXIT_REASON_EXT_INTR:
211 		return "extint";
212 	case EXIT_REASON_TRIPLE_FAULT:
213 		return "triplefault";
214 	case EXIT_REASON_INIT:
215 		return "init";
216 	case EXIT_REASON_SIPI:
217 		return "sipi";
218 	case EXIT_REASON_IO_SMI:
219 		return "iosmi";
220 	case EXIT_REASON_SMI:
221 		return "smi";
222 	case EXIT_REASON_INTR_WINDOW:
223 		return "intrwindow";
224 	case EXIT_REASON_NMI_WINDOW:
225 		return "nmiwindow";
226 	case EXIT_REASON_TASK_SWITCH:
227 		return "taskswitch";
228 	case EXIT_REASON_CPUID:
229 		return "cpuid";
230 	case EXIT_REASON_GETSEC:
231 		return "getsec";
232 	case EXIT_REASON_HLT:
233 		return "hlt";
234 	case EXIT_REASON_INVD:
235 		return "invd";
236 	case EXIT_REASON_INVLPG:
237 		return "invlpg";
238 	case EXIT_REASON_RDPMC:
239 		return "rdpmc";
240 	case EXIT_REASON_RDTSC:
241 		return "rdtsc";
242 	case EXIT_REASON_RSM:
243 		return "rsm";
244 	case EXIT_REASON_VMCALL:
245 		return "vmcall";
246 	case EXIT_REASON_VMCLEAR:
247 		return "vmclear";
248 	case EXIT_REASON_VMLAUNCH:
249 		return "vmlaunch";
250 	case EXIT_REASON_VMPTRLD:
251 		return "vmptrld";
252 	case EXIT_REASON_VMPTRST:
253 		return "vmptrst";
254 	case EXIT_REASON_VMREAD:
255 		return "vmread";
256 	case EXIT_REASON_VMRESUME:
257 		return "vmresume";
258 	case EXIT_REASON_VMWRITE:
259 		return "vmwrite";
260 	case EXIT_REASON_VMXOFF:
261 		return "vmxoff";
262 	case EXIT_REASON_VMXON:
263 		return "vmxon";
264 	case EXIT_REASON_CR_ACCESS:
265 		return "craccess";
266 	case EXIT_REASON_DR_ACCESS:
267 		return "draccess";
268 	case EXIT_REASON_INOUT:
269 		return "inout";
270 	case EXIT_REASON_RDMSR:
271 		return "rdmsr";
272 	case EXIT_REASON_WRMSR:
273 		return "wrmsr";
274 	case EXIT_REASON_INVAL_VMCS:
275 		return "invalvmcs";
276 	case EXIT_REASON_INVAL_MSR:
277 		return "invalmsr";
278 	case EXIT_REASON_MWAIT:
279 		return "mwait";
280 	case EXIT_REASON_MTF:
281 		return "mtf";
282 	case EXIT_REASON_MONITOR:
283 		return "monitor";
284 	case EXIT_REASON_PAUSE:
285 		return "pause";
286 	case EXIT_REASON_MCE:
287 		return "mce";
288 	case EXIT_REASON_TPR:
289 		return "tpr";
290 	case EXIT_REASON_APIC_ACCESS:
291 		return "apic-access";
292 	case EXIT_REASON_GDTR_IDTR:
293 		return "gdtridtr";
294 	case EXIT_REASON_LDTR_TR:
295 		return "ldtrtr";
296 	case EXIT_REASON_EPT_FAULT:
297 		return "eptfault";
298 	case EXIT_REASON_EPT_MISCONFIG:
299 		return "eptmisconfig";
300 	case EXIT_REASON_INVEPT:
301 		return "invept";
302 	case EXIT_REASON_RDTSCP:
303 		return "rdtscp";
304 	case EXIT_REASON_VMX_PREEMPT:
305 		return "vmxpreempt";
306 	case EXIT_REASON_INVVPID:
307 		return "invvpid";
308 	case EXIT_REASON_WBINVD:
309 		return "wbinvd";
310 	case EXIT_REASON_XSETBV:
311 		return "xsetbv";
312 	case EXIT_REASON_APIC_WRITE:
313 		return "apic-write";
314 	default:
315 		snprintf(reasonbuf, sizeof(reasonbuf), "%d", reason);
316 		return (reasonbuf);
317 	}
318 }
319 #endif	/* KTR */
320 
321 static int
322 vmx_allow_x2apic_msrs(struct vmx *vmx)
323 {
324 	int i, error;
325 
326 	error = 0;
327 
328 	/*
329 	 * Allow readonly access to the following x2APIC MSRs from the guest.
330 	 */
331 	error += guest_msr_ro(vmx, MSR_APIC_ID);
332 	error += guest_msr_ro(vmx, MSR_APIC_VERSION);
333 	error += guest_msr_ro(vmx, MSR_APIC_LDR);
334 	error += guest_msr_ro(vmx, MSR_APIC_SVR);
335 
336 	for (i = 0; i < 8; i++)
337 		error += guest_msr_ro(vmx, MSR_APIC_ISR0 + i);
338 
339 	for (i = 0; i < 8; i++)
340 		error += guest_msr_ro(vmx, MSR_APIC_TMR0 + i);
341 
342 	for (i = 0; i < 8; i++)
343 		error += guest_msr_ro(vmx, MSR_APIC_IRR0 + i);
344 
345 	error += guest_msr_ro(vmx, MSR_APIC_ESR);
346 	error += guest_msr_ro(vmx, MSR_APIC_LVT_TIMER);
347 	error += guest_msr_ro(vmx, MSR_APIC_LVT_THERMAL);
348 	error += guest_msr_ro(vmx, MSR_APIC_LVT_PCINT);
349 	error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT0);
350 	error += guest_msr_ro(vmx, MSR_APIC_LVT_LINT1);
351 	error += guest_msr_ro(vmx, MSR_APIC_LVT_ERROR);
352 	error += guest_msr_ro(vmx, MSR_APIC_ICR_TIMER);
353 	error += guest_msr_ro(vmx, MSR_APIC_DCR_TIMER);
354 	error += guest_msr_ro(vmx, MSR_APIC_ICR);
355 
356 	/*
357 	 * Allow TPR, EOI and SELF_IPI MSRs to be read and written by the guest.
358 	 *
359 	 * These registers get special treatment described in the section
360 	 * "Virtualizing MSR-Based APIC Accesses".
361 	 */
362 	error += guest_msr_rw(vmx, MSR_APIC_TPR);
363 	error += guest_msr_rw(vmx, MSR_APIC_EOI);
364 	error += guest_msr_rw(vmx, MSR_APIC_SELF_IPI);
365 
366 	return (error);
367 }
368 
369 u_long
370 vmx_fix_cr0(u_long cr0)
371 {
372 
373 	return ((cr0 | cr0_ones_mask) & ~cr0_zeros_mask);
374 }
375 
376 u_long
377 vmx_fix_cr4(u_long cr4)
378 {
379 
380 	return ((cr4 | cr4_ones_mask) & ~cr4_zeros_mask);
381 }
382 
383 static void
384 vpid_free(int vpid)
385 {
386 	if (vpid < 0 || vpid > 0xffff)
387 		panic("vpid_free: invalid vpid %d", vpid);
388 
389 	/*
390 	 * VPIDs [0,VM_MAXCPU] are special and are not allocated from
391 	 * the unit number allocator.
392 	 */
393 
394 	if (vpid > VM_MAXCPU)
395 		free_unr(vpid_unr, vpid);
396 }
397 
398 static void
399 vpid_alloc(uint16_t *vpid, int num)
400 {
401 	int i, x;
402 
403 	if (num <= 0 || num > VM_MAXCPU)
404 		panic("invalid number of vpids requested: %d", num);
405 
406 	/*
407 	 * If the "enable vpid" execution control is not enabled then the
408 	 * VPID is required to be 0 for all vcpus.
409 	 */
410 	if ((procbased_ctls2 & PROCBASED2_ENABLE_VPID) == 0) {
411 		for (i = 0; i < num; i++)
412 			vpid[i] = 0;
413 		return;
414 	}
415 
416 	/*
417 	 * Allocate a unique VPID for each vcpu from the unit number allocator.
418 	 */
419 	for (i = 0; i < num; i++) {
420 		x = alloc_unr(vpid_unr);
421 		if (x == -1)
422 			break;
423 		else
424 			vpid[i] = x;
425 	}
426 
427 	if (i < num) {
428 		atomic_add_int(&vpid_alloc_failed, 1);
429 
430 		/*
431 		 * If the unit number allocator does not have enough unique
432 		 * VPIDs then we need to allocate from the [1,VM_MAXCPU] range.
433 		 *
434 		 * These VPIDs are not be unique across VMs but this does not
435 		 * affect correctness because the combined mappings are also
436 		 * tagged with the EP4TA which is unique for each VM.
437 		 *
438 		 * It is still sub-optimal because the invvpid will invalidate
439 		 * combined mappings for a particular VPID across all EP4TAs.
440 		 */
441 		while (i-- > 0)
442 			vpid_free(vpid[i]);
443 
444 		for (i = 0; i < num; i++)
445 			vpid[i] = i + 1;
446 	}
447 }
448 
449 static void
450 vpid_init(void)
451 {
452 	/*
453 	 * VPID 0 is required when the "enable VPID" execution control is
454 	 * disabled.
455 	 *
456 	 * VPIDs [1,VM_MAXCPU] are used as the "overflow namespace" when the
457 	 * unit number allocator does not have sufficient unique VPIDs to
458 	 * satisfy the allocation.
459 	 *
460 	 * The remaining VPIDs are managed by the unit number allocator.
461 	 */
462 	vpid_unr = new_unrhdr(VM_MAXCPU + 1, 0xffff, NULL);
463 }
464 
465 static void
466 vmx_disable(void *arg __unused)
467 {
468 	struct invvpid_desc invvpid_desc = { 0 };
469 	struct invept_desc invept_desc = { 0 };
470 
471 	if (vmxon_enabled[curcpu]) {
472 		/*
473 		 * See sections 25.3.3.3 and 25.3.3.4 in Intel Vol 3b.
474 		 *
475 		 * VMXON or VMXOFF are not required to invalidate any TLB
476 		 * caching structures. This prevents potential retention of
477 		 * cached information in the TLB between distinct VMX episodes.
478 		 */
479 		invvpid(INVVPID_TYPE_ALL_CONTEXTS, invvpid_desc);
480 		invept(INVEPT_TYPE_ALL_CONTEXTS, invept_desc);
481 		vmxoff();
482 	}
483 	load_cr4(rcr4() & ~CR4_VMXE);
484 }
485 
486 static int
487 vmx_cleanup(void)
488 {
489 
490 	if (pirvec != 0)
491 		vmm_ipi_free(pirvec);
492 
493 	if (vpid_unr != NULL) {
494 		delete_unrhdr(vpid_unr);
495 		vpid_unr = NULL;
496 	}
497 
498 	smp_rendezvous(NULL, vmx_disable, NULL, NULL);
499 
500 	return (0);
501 }
502 
503 static void
504 vmx_enable(void *arg __unused)
505 {
506 	int error;
507 	uint64_t feature_control;
508 
509 	feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
510 	if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 0 ||
511 	    (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
512 		wrmsr(MSR_IA32_FEATURE_CONTROL,
513 		    feature_control | IA32_FEATURE_CONTROL_VMX_EN |
514 		    IA32_FEATURE_CONTROL_LOCK);
515 	}
516 
517 	load_cr4(rcr4() | CR4_VMXE);
518 
519 	*(uint32_t *)vmxon_region[curcpu] = vmx_revision();
520 	error = vmxon(vmxon_region[curcpu]);
521 	if (error == 0)
522 		vmxon_enabled[curcpu] = 1;
523 }
524 
525 static void
526 vmx_restore(void)
527 {
528 
529 	if (vmxon_enabled[curcpu])
530 		vmxon(vmxon_region[curcpu]);
531 }
532 
533 static int
534 vmx_init(int ipinum)
535 {
536 	int error, use_tpr_shadow;
537 	uint64_t basic, fixed0, fixed1, feature_control;
538 	uint32_t tmp, procbased2_vid_bits;
539 
540 	/* CPUID.1:ECX[bit 5] must be 1 for processor to support VMX */
541 	if (!(cpu_feature2 & CPUID2_VMX)) {
542 		printf("vmx_init: processor does not support VMX operation\n");
543 		return (ENXIO);
544 	}
545 
546 	/*
547 	 * Verify that MSR_IA32_FEATURE_CONTROL lock and VMXON enable bits
548 	 * are set (bits 0 and 2 respectively).
549 	 */
550 	feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
551 	if ((feature_control & IA32_FEATURE_CONTROL_LOCK) == 1 &&
552 	    (feature_control & IA32_FEATURE_CONTROL_VMX_EN) == 0) {
553 		printf("vmx_init: VMX operation disabled by BIOS\n");
554 		return (ENXIO);
555 	}
556 
557 	/*
558 	 * Verify capabilities MSR_VMX_BASIC:
559 	 * - bit 54 indicates support for INS/OUTS decoding
560 	 */
561 	basic = rdmsr(MSR_VMX_BASIC);
562 	if ((basic & (1UL << 54)) == 0) {
563 		printf("vmx_init: processor does not support desired basic "
564 		    "capabilities\n");
565 		return (EINVAL);
566 	}
567 
568 	/* Check support for primary processor-based VM-execution controls */
569 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
570 			       MSR_VMX_TRUE_PROCBASED_CTLS,
571 			       PROCBASED_CTLS_ONE_SETTING,
572 			       PROCBASED_CTLS_ZERO_SETTING, &procbased_ctls);
573 	if (error) {
574 		printf("vmx_init: processor does not support desired primary "
575 		       "processor-based controls\n");
576 		return (error);
577 	}
578 
579 	/* Clear the processor-based ctl bits that are set on demand */
580 	procbased_ctls &= ~PROCBASED_CTLS_WINDOW_SETTING;
581 
582 	/* Check support for secondary processor-based VM-execution controls */
583 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
584 			       MSR_VMX_PROCBASED_CTLS2,
585 			       PROCBASED_CTLS2_ONE_SETTING,
586 			       PROCBASED_CTLS2_ZERO_SETTING, &procbased_ctls2);
587 	if (error) {
588 		printf("vmx_init: processor does not support desired secondary "
589 		       "processor-based controls\n");
590 		return (error);
591 	}
592 
593 	/* Check support for VPID */
594 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
595 			       PROCBASED2_ENABLE_VPID, 0, &tmp);
596 	if (error == 0)
597 		procbased_ctls2 |= PROCBASED2_ENABLE_VPID;
598 
599 	/* Check support for pin-based VM-execution controls */
600 	error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
601 			       MSR_VMX_TRUE_PINBASED_CTLS,
602 			       PINBASED_CTLS_ONE_SETTING,
603 			       PINBASED_CTLS_ZERO_SETTING, &pinbased_ctls);
604 	if (error) {
605 		printf("vmx_init: processor does not support desired "
606 		       "pin-based controls\n");
607 		return (error);
608 	}
609 
610 	/* Check support for VM-exit controls */
611 	error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
612 			       VM_EXIT_CTLS_ONE_SETTING,
613 			       VM_EXIT_CTLS_ZERO_SETTING,
614 			       &exit_ctls);
615 	if (error) {
616 		printf("vmx_init: processor does not support desired "
617 		    "exit controls\n");
618 		return (error);
619 	}
620 
621 	/* Check support for VM-entry controls */
622 	error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS, MSR_VMX_TRUE_ENTRY_CTLS,
623 	    VM_ENTRY_CTLS_ONE_SETTING, VM_ENTRY_CTLS_ZERO_SETTING,
624 	    &entry_ctls);
625 	if (error) {
626 		printf("vmx_init: processor does not support desired "
627 		    "entry controls\n");
628 		return (error);
629 	}
630 
631 	/*
632 	 * Check support for optional features by testing them
633 	 * as individual bits
634 	 */
635 	cap_halt_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
636 					MSR_VMX_TRUE_PROCBASED_CTLS,
637 					PROCBASED_HLT_EXITING, 0,
638 					&tmp) == 0);
639 
640 	cap_monitor_trap = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
641 					MSR_VMX_PROCBASED_CTLS,
642 					PROCBASED_MTF, 0,
643 					&tmp) == 0);
644 
645 	cap_pause_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
646 					 MSR_VMX_TRUE_PROCBASED_CTLS,
647 					 PROCBASED_PAUSE_EXITING, 0,
648 					 &tmp) == 0);
649 
650 	cap_unrestricted_guest = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
651 					MSR_VMX_PROCBASED_CTLS2,
652 					PROCBASED2_UNRESTRICTED_GUEST, 0,
653 				        &tmp) == 0);
654 
655 	cap_invpcid = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
656 	    MSR_VMX_PROCBASED_CTLS2, PROCBASED2_ENABLE_INVPCID, 0,
657 	    &tmp) == 0);
658 
659 	/*
660 	 * Check support for virtual interrupt delivery.
661 	 */
662 	procbased2_vid_bits = (PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
663 	    PROCBASED2_VIRTUALIZE_X2APIC_MODE |
664 	    PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
665 	    PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY);
666 
667 	use_tpr_shadow = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
668 	    MSR_VMX_TRUE_PROCBASED_CTLS, PROCBASED_USE_TPR_SHADOW, 0,
669 	    &tmp) == 0);
670 
671 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2, MSR_VMX_PROCBASED_CTLS2,
672 	    procbased2_vid_bits, 0, &tmp);
673 	if (error == 0 && use_tpr_shadow) {
674 		virtual_interrupt_delivery = 1;
675 		TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_vid",
676 		    &virtual_interrupt_delivery);
677 	}
678 
679 	if (virtual_interrupt_delivery) {
680 		procbased_ctls |= PROCBASED_USE_TPR_SHADOW;
681 		procbased_ctls2 |= procbased2_vid_bits;
682 		procbased_ctls2 &= ~PROCBASED2_VIRTUALIZE_X2APIC_MODE;
683 
684 		/*
685 		 * No need to emulate accesses to %CR8 if virtual
686 		 * interrupt delivery is enabled.
687 		 */
688 		procbased_ctls &= ~PROCBASED_CR8_LOAD_EXITING;
689 		procbased_ctls &= ~PROCBASED_CR8_STORE_EXITING;
690 
691 		/*
692 		 * Check for Posted Interrupts only if Virtual Interrupt
693 		 * Delivery is enabled.
694 		 */
695 		error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
696 		    MSR_VMX_TRUE_PINBASED_CTLS, PINBASED_POSTED_INTERRUPT, 0,
697 		    &tmp);
698 		if (error == 0) {
699 			pirvec = vmm_ipi_alloc();
700 			if (pirvec == 0) {
701 				if (bootverbose) {
702 					printf("vmx_init: unable to allocate "
703 					    "posted interrupt vector\n");
704 				}
705 			} else {
706 				posted_interrupts = 1;
707 				TUNABLE_INT_FETCH("hw.vmm.vmx.use_apic_pir",
708 				    &posted_interrupts);
709 			}
710 		}
711 	}
712 
713 	if (posted_interrupts)
714 		    pinbased_ctls |= PINBASED_POSTED_INTERRUPT;
715 
716 	/* Initialize EPT */
717 	error = ept_init(ipinum);
718 	if (error) {
719 		printf("vmx_init: ept initialization failed (%d)\n", error);
720 		return (error);
721 	}
722 
723 	/*
724 	 * Stash the cr0 and cr4 bits that must be fixed to 0 or 1
725 	 */
726 	fixed0 = rdmsr(MSR_VMX_CR0_FIXED0);
727 	fixed1 = rdmsr(MSR_VMX_CR0_FIXED1);
728 	cr0_ones_mask = fixed0 & fixed1;
729 	cr0_zeros_mask = ~fixed0 & ~fixed1;
730 
731 	/*
732 	 * CR0_PE and CR0_PG can be set to zero in VMX non-root operation
733 	 * if unrestricted guest execution is allowed.
734 	 */
735 	if (cap_unrestricted_guest)
736 		cr0_ones_mask &= ~(CR0_PG | CR0_PE);
737 
738 	/*
739 	 * Do not allow the guest to set CR0_NW or CR0_CD.
740 	 */
741 	cr0_zeros_mask |= (CR0_NW | CR0_CD);
742 
743 	fixed0 = rdmsr(MSR_VMX_CR4_FIXED0);
744 	fixed1 = rdmsr(MSR_VMX_CR4_FIXED1);
745 	cr4_ones_mask = fixed0 & fixed1;
746 	cr4_zeros_mask = ~fixed0 & ~fixed1;
747 
748 	vpid_init();
749 
750 	vmx_msr_init();
751 
752 	/* enable VMX operation */
753 	smp_rendezvous(NULL, vmx_enable, NULL, NULL);
754 
755 	vmx_initialized = 1;
756 
757 	return (0);
758 }
759 
760 static void
761 vmx_trigger_hostintr(int vector)
762 {
763 	uintptr_t func;
764 	struct gate_descriptor *gd;
765 
766 	gd = &idt[vector];
767 
768 	KASSERT(vector >= 32 && vector <= 255, ("vmx_trigger_hostintr: "
769 	    "invalid vector %d", vector));
770 	KASSERT(gd->gd_p == 1, ("gate descriptor for vector %d not present",
771 	    vector));
772 	KASSERT(gd->gd_type == SDT_SYSIGT, ("gate descriptor for vector %d "
773 	    "has invalid type %d", vector, gd->gd_type));
774 	KASSERT(gd->gd_dpl == SEL_KPL, ("gate descriptor for vector %d "
775 	    "has invalid dpl %d", vector, gd->gd_dpl));
776 	KASSERT(gd->gd_selector == GSEL(GCODE_SEL, SEL_KPL), ("gate descriptor "
777 	    "for vector %d has invalid selector %d", vector, gd->gd_selector));
778 	KASSERT(gd->gd_ist == 0, ("gate descriptor for vector %d has invalid "
779 	    "IST %d", vector, gd->gd_ist));
780 
781 	func = ((long)gd->gd_hioffset << 16 | gd->gd_looffset);
782 	vmx_call_isr(func);
783 }
784 
785 static int
786 vmx_setup_cr_shadow(int which, struct vmcs *vmcs, uint32_t initial)
787 {
788 	int error, mask_ident, shadow_ident;
789 	uint64_t mask_value;
790 
791 	if (which != 0 && which != 4)
792 		panic("vmx_setup_cr_shadow: unknown cr%d", which);
793 
794 	if (which == 0) {
795 		mask_ident = VMCS_CR0_MASK;
796 		mask_value = cr0_ones_mask | cr0_zeros_mask;
797 		shadow_ident = VMCS_CR0_SHADOW;
798 	} else {
799 		mask_ident = VMCS_CR4_MASK;
800 		mask_value = cr4_ones_mask | cr4_zeros_mask;
801 		shadow_ident = VMCS_CR4_SHADOW;
802 	}
803 
804 	error = vmcs_setreg(vmcs, 0, VMCS_IDENT(mask_ident), mask_value);
805 	if (error)
806 		return (error);
807 
808 	error = vmcs_setreg(vmcs, 0, VMCS_IDENT(shadow_ident), initial);
809 	if (error)
810 		return (error);
811 
812 	return (0);
813 }
814 #define	vmx_setup_cr0_shadow(vmcs,init)	vmx_setup_cr_shadow(0, (vmcs), (init))
815 #define	vmx_setup_cr4_shadow(vmcs,init)	vmx_setup_cr_shadow(4, (vmcs), (init))
816 
817 static void *
818 vmx_vminit(struct vm *vm, pmap_t pmap)
819 {
820 	uint16_t vpid[VM_MAXCPU];
821 	int i, error;
822 	struct vmx *vmx;
823 	struct vmcs *vmcs;
824 
825 	vmx = malloc(sizeof(struct vmx), M_VMX, M_WAITOK | M_ZERO);
826 	if ((uintptr_t)vmx & PAGE_MASK) {
827 		panic("malloc of struct vmx not aligned on %d byte boundary",
828 		      PAGE_SIZE);
829 	}
830 	vmx->vm = vm;
831 
832 	vmx->eptp = eptp(vtophys((vm_offset_t)pmap->pm_pml4));
833 
834 	/*
835 	 * Clean up EPTP-tagged guest physical and combined mappings
836 	 *
837 	 * VMX transitions are not required to invalidate any guest physical
838 	 * mappings. So, it may be possible for stale guest physical mappings
839 	 * to be present in the processor TLBs.
840 	 *
841 	 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
842 	 */
843 	ept_invalidate_mappings(vmx->eptp);
844 
845 	msr_bitmap_initialize(vmx->msr_bitmap);
846 
847 	/*
848 	 * It is safe to allow direct access to MSR_GSBASE and MSR_FSBASE.
849 	 * The guest FSBASE and GSBASE are saved and restored during
850 	 * vm-exit and vm-entry respectively. The host FSBASE and GSBASE are
851 	 * always restored from the vmcs host state area on vm-exit.
852 	 *
853 	 * The SYSENTER_CS/ESP/EIP MSRs are identical to FS/GSBASE in
854 	 * how they are saved/restored so can be directly accessed by the
855 	 * guest.
856 	 *
857 	 * MSR_EFER is saved and restored in the guest VMCS area on a
858 	 * VM exit and entry respectively. It is also restored from the
859 	 * host VMCS area on a VM exit.
860 	 *
861 	 * MSR_PAT is saved and restored in the guest VMCS are on a VM exit
862 	 * and entry respectively. It is also restored from the host VMCS
863 	 * area on a VM exit.
864 	 *
865 	 * The TSC MSR is exposed read-only. Writes are disallowed as that
866 	 * will impact the host TSC.
867 	 * XXX Writes would be implemented with a wrmsr trap, and
868 	 * then modifying the TSC offset in the VMCS.
869 	 */
870 	if (guest_msr_rw(vmx, MSR_GSBASE) ||
871 	    guest_msr_rw(vmx, MSR_FSBASE) ||
872 	    guest_msr_rw(vmx, MSR_SYSENTER_CS_MSR) ||
873 	    guest_msr_rw(vmx, MSR_SYSENTER_ESP_MSR) ||
874 	    guest_msr_rw(vmx, MSR_SYSENTER_EIP_MSR) ||
875 	    guest_msr_rw(vmx, MSR_EFER) ||
876 	    guest_msr_rw(vmx, MSR_PAT) ||
877 	    guest_msr_ro(vmx, MSR_TSC))
878 		panic("vmx_vminit: error setting guest msr access");
879 
880 	vpid_alloc(vpid, VM_MAXCPU);
881 
882 	if (virtual_interrupt_delivery) {
883 		error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
884 		    APIC_ACCESS_ADDRESS);
885 		/* XXX this should really return an error to the caller */
886 		KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
887 	}
888 
889 	for (i = 0; i < VM_MAXCPU; i++) {
890 		vmcs = &vmx->vmcs[i];
891 		vmcs->identifier = vmx_revision();
892 		error = vmclear(vmcs);
893 		if (error != 0) {
894 			panic("vmx_vminit: vmclear error %d on vcpu %d\n",
895 			      error, i);
896 		}
897 
898 		vmx_msr_guest_init(vmx, i);
899 
900 		error = vmcs_init(vmcs);
901 		KASSERT(error == 0, ("vmcs_init error %d", error));
902 
903 		VMPTRLD(vmcs);
904 		error = 0;
905 		error += vmwrite(VMCS_HOST_RSP, (u_long)&vmx->ctx[i]);
906 		error += vmwrite(VMCS_EPTP, vmx->eptp);
907 		error += vmwrite(VMCS_PIN_BASED_CTLS, pinbased_ctls);
908 		error += vmwrite(VMCS_PRI_PROC_BASED_CTLS, procbased_ctls);
909 		error += vmwrite(VMCS_SEC_PROC_BASED_CTLS, procbased_ctls2);
910 		error += vmwrite(VMCS_EXIT_CTLS, exit_ctls);
911 		error += vmwrite(VMCS_ENTRY_CTLS, entry_ctls);
912 		error += vmwrite(VMCS_MSR_BITMAP, vtophys(vmx->msr_bitmap));
913 		error += vmwrite(VMCS_VPID, vpid[i]);
914 		if (virtual_interrupt_delivery) {
915 			error += vmwrite(VMCS_APIC_ACCESS, APIC_ACCESS_ADDRESS);
916 			error += vmwrite(VMCS_VIRTUAL_APIC,
917 			    vtophys(&vmx->apic_page[i]));
918 			error += vmwrite(VMCS_EOI_EXIT0, 0);
919 			error += vmwrite(VMCS_EOI_EXIT1, 0);
920 			error += vmwrite(VMCS_EOI_EXIT2, 0);
921 			error += vmwrite(VMCS_EOI_EXIT3, 0);
922 		}
923 		if (posted_interrupts) {
924 			error += vmwrite(VMCS_PIR_VECTOR, pirvec);
925 			error += vmwrite(VMCS_PIR_DESC,
926 			    vtophys(&vmx->pir_desc[i]));
927 		}
928 		VMCLEAR(vmcs);
929 		KASSERT(error == 0, ("vmx_vminit: error customizing the vmcs"));
930 
931 		vmx->cap[i].set = 0;
932 		vmx->cap[i].proc_ctls = procbased_ctls;
933 		vmx->cap[i].proc_ctls2 = procbased_ctls2;
934 
935 		vmx->state[i].lastcpu = NOCPU;
936 		vmx->state[i].vpid = vpid[i];
937 
938 		/*
939 		 * Set up the CR0/4 shadows, and init the read shadow
940 		 * to the power-on register value from the Intel Sys Arch.
941 		 *  CR0 - 0x60000010
942 		 *  CR4 - 0
943 		 */
944 		error = vmx_setup_cr0_shadow(vmcs, 0x60000010);
945 		if (error != 0)
946 			panic("vmx_setup_cr0_shadow %d", error);
947 
948 		error = vmx_setup_cr4_shadow(vmcs, 0);
949 		if (error != 0)
950 			panic("vmx_setup_cr4_shadow %d", error);
951 
952 		vmx->ctx[i].pmap = pmap;
953 	}
954 
955 	return (vmx);
956 }
957 
958 static int
959 vmx_handle_cpuid(struct vm *vm, int vcpu, struct vmxctx *vmxctx)
960 {
961 	int handled, func;
962 
963 	func = vmxctx->guest_rax;
964 
965 	handled = x86_emulate_cpuid(vm, vcpu,
966 				    (uint32_t*)(&vmxctx->guest_rax),
967 				    (uint32_t*)(&vmxctx->guest_rbx),
968 				    (uint32_t*)(&vmxctx->guest_rcx),
969 				    (uint32_t*)(&vmxctx->guest_rdx));
970 	return (handled);
971 }
972 
973 static __inline void
974 vmx_run_trace(struct vmx *vmx, int vcpu)
975 {
976 #ifdef KTR
977 	VCPU_CTR1(vmx->vm, vcpu, "Resume execution at %#lx", vmcs_guest_rip());
978 #endif
979 }
980 
981 static __inline void
982 vmx_exit_trace(struct vmx *vmx, int vcpu, uint64_t rip, uint32_t exit_reason,
983 	       int handled)
984 {
985 #ifdef KTR
986 	VCPU_CTR3(vmx->vm, vcpu, "%s %s vmexit at 0x%0lx",
987 		 handled ? "handled" : "unhandled",
988 		 exit_reason_to_str(exit_reason), rip);
989 #endif
990 }
991 
992 static __inline void
993 vmx_astpending_trace(struct vmx *vmx, int vcpu, uint64_t rip)
994 {
995 #ifdef KTR
996 	VCPU_CTR1(vmx->vm, vcpu, "astpending vmexit at 0x%0lx", rip);
997 #endif
998 }
999 
1000 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
1001 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
1002 
1003 /*
1004  * Invalidate guest mappings identified by its vpid from the TLB.
1005  */
1006 static __inline void
1007 vmx_invvpid(struct vmx *vmx, int vcpu, pmap_t pmap, int running)
1008 {
1009 	struct vmxstate *vmxstate;
1010 	struct invvpid_desc invvpid_desc;
1011 
1012 	vmxstate = &vmx->state[vcpu];
1013 	if (vmxstate->vpid == 0)
1014 		return;
1015 
1016 	if (!running) {
1017 		/*
1018 		 * Set the 'lastcpu' to an invalid host cpu.
1019 		 *
1020 		 * This will invalidate TLB entries tagged with the vcpu's
1021 		 * vpid the next time it runs via vmx_set_pcpu_defaults().
1022 		 */
1023 		vmxstate->lastcpu = NOCPU;
1024 		return;
1025 	}
1026 
1027 	KASSERT(curthread->td_critnest > 0, ("%s: vcpu %d running outside "
1028 	    "critical section", __func__, vcpu));
1029 
1030 	/*
1031 	 * Invalidate all mappings tagged with 'vpid'
1032 	 *
1033 	 * We do this because this vcpu was executing on a different host
1034 	 * cpu when it last ran. We do not track whether it invalidated
1035 	 * mappings associated with its 'vpid' during that run. So we must
1036 	 * assume that the mappings associated with 'vpid' on 'curcpu' are
1037 	 * stale and invalidate them.
1038 	 *
1039 	 * Note that we incur this penalty only when the scheduler chooses to
1040 	 * move the thread associated with this vcpu between host cpus.
1041 	 *
1042 	 * Note also that this will invalidate mappings tagged with 'vpid'
1043 	 * for "all" EP4TAs.
1044 	 */
1045 	if (pmap->pm_eptgen == vmx->eptgen[curcpu]) {
1046 		invvpid_desc._res1 = 0;
1047 		invvpid_desc._res2 = 0;
1048 		invvpid_desc.vpid = vmxstate->vpid;
1049 		invvpid_desc.linear_addr = 0;
1050 		invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
1051 		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_DONE, 1);
1052 	} else {
1053 		/*
1054 		 * The invvpid can be skipped if an invept is going to
1055 		 * be performed before entering the guest. The invept
1056 		 * will invalidate combined mappings tagged with
1057 		 * 'vmx->eptp' for all vpids.
1058 		 */
1059 		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
1060 	}
1061 }
1062 
1063 static void
1064 vmx_set_pcpu_defaults(struct vmx *vmx, int vcpu, pmap_t pmap)
1065 {
1066 	struct vmxstate *vmxstate;
1067 
1068 	vmxstate = &vmx->state[vcpu];
1069 	if (vmxstate->lastcpu == curcpu)
1070 		return;
1071 
1072 	vmxstate->lastcpu = curcpu;
1073 
1074 	vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
1075 
1076 	vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1077 	vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1078 	vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1079 	vmx_invvpid(vmx, vcpu, pmap, 1);
1080 }
1081 
1082 /*
1083  * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1084  */
1085 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1086 
1087 static void __inline
1088 vmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
1089 {
1090 
1091 	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1092 		vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1093 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1094 		VCPU_CTR0(vmx->vm, vcpu, "Enabling interrupt window exiting");
1095 	}
1096 }
1097 
1098 static void __inline
1099 vmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
1100 {
1101 
1102 	KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1103 	    ("intr_window_exiting not set: %#x", vmx->cap[vcpu].proc_ctls));
1104 	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1105 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1106 	VCPU_CTR0(vmx->vm, vcpu, "Disabling interrupt window exiting");
1107 }
1108 
1109 static void __inline
1110 vmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
1111 {
1112 
1113 	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1114 		vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1115 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1116 		VCPU_CTR0(vmx->vm, vcpu, "Enabling NMI window exiting");
1117 	}
1118 }
1119 
1120 static void __inline
1121 vmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
1122 {
1123 
1124 	KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
1125 	    ("nmi_window_exiting not set %#x", vmx->cap[vcpu].proc_ctls));
1126 	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1127 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1128 	VCPU_CTR0(vmx->vm, vcpu, "Disabling NMI window exiting");
1129 }
1130 
1131 #define	NMI_BLOCKING	(VMCS_INTERRUPTIBILITY_NMI_BLOCKING |		\
1132 			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1133 #define	HWINTR_BLOCKING	(VMCS_INTERRUPTIBILITY_STI_BLOCKING |		\
1134 			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1135 
1136 static void
1137 vmx_inject_nmi(struct vmx *vmx, int vcpu)
1138 {
1139 	uint32_t gi, info;
1140 
1141 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1142 	KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1143 	    "interruptibility-state %#x", gi));
1144 
1145 	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1146 	KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
1147 	    "VM-entry interruption information %#x", info));
1148 
1149 	/*
1150 	 * Inject the virtual NMI. The vector must be the NMI IDT entry
1151 	 * or the VMCS entry check will fail.
1152 	 */
1153 	info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
1154 	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1155 
1156 	VCPU_CTR0(vmx->vm, vcpu, "Injecting vNMI");
1157 
1158 	/* Clear the request */
1159 	vm_nmi_clear(vmx->vm, vcpu);
1160 }
1161 
1162 static void
1163 vmx_inject_interrupts(struct vmx *vmx, int vcpu, struct vlapic *vlapic)
1164 {
1165 	int vector, need_nmi_exiting, extint_pending;
1166 	uint64_t rflags, entryinfo;
1167 	uint32_t gi, info;
1168 
1169 	if (vm_entry_intinfo(vmx->vm, vcpu, &entryinfo)) {
1170 		KASSERT((entryinfo & VMCS_INTR_VALID) != 0, ("%s: entry "
1171 		    "intinfo is not valid: %#lx", __func__, entryinfo));
1172 
1173 		info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1174 		KASSERT((info & VMCS_INTR_VALID) == 0, ("%s: cannot inject "
1175 		     "pending exception: %#lx/%#x", __func__, entryinfo, info));
1176 
1177 		info = entryinfo;
1178 		vector = info & 0xff;
1179 		if (vector == IDT_BP || vector == IDT_OF) {
1180 			/*
1181 			 * VT-x requires #BP and #OF to be injected as software
1182 			 * exceptions.
1183 			 */
1184 			info &= ~VMCS_INTR_T_MASK;
1185 			info |= VMCS_INTR_T_SWEXCEPTION;
1186 		}
1187 
1188 		if (info & VMCS_INTR_DEL_ERRCODE)
1189 			vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, entryinfo >> 32);
1190 
1191 		vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1192 	}
1193 
1194 	if (vm_nmi_pending(vmx->vm, vcpu)) {
1195 		/*
1196 		 * If there are no conditions blocking NMI injection then
1197 		 * inject it directly here otherwise enable "NMI window
1198 		 * exiting" to inject it as soon as we can.
1199 		 *
1200 		 * We also check for STI_BLOCKING because some implementations
1201 		 * don't allow NMI injection in this case. If we are running
1202 		 * on a processor that doesn't have this restriction it will
1203 		 * immediately exit and the NMI will be injected in the
1204 		 * "NMI window exiting" handler.
1205 		 */
1206 		need_nmi_exiting = 1;
1207 		gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1208 		if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1209 			info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1210 			if ((info & VMCS_INTR_VALID) == 0) {
1211 				vmx_inject_nmi(vmx, vcpu);
1212 				need_nmi_exiting = 0;
1213 			} else {
1214 				VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI "
1215 				    "due to VM-entry intr info %#x", info);
1216 			}
1217 		} else {
1218 			VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI due to "
1219 			    "Guest Interruptibility-state %#x", gi);
1220 		}
1221 
1222 		if (need_nmi_exiting)
1223 			vmx_set_nmi_window_exiting(vmx, vcpu);
1224 	}
1225 
1226 	extint_pending = vm_extint_pending(vmx->vm, vcpu);
1227 
1228 	if (!extint_pending && virtual_interrupt_delivery) {
1229 		vmx_inject_pir(vlapic);
1230 		return;
1231 	}
1232 
1233 	/*
1234 	 * If interrupt-window exiting is already in effect then don't bother
1235 	 * checking for pending interrupts. This is just an optimization and
1236 	 * not needed for correctness.
1237 	 */
1238 	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0) {
1239 		VCPU_CTR0(vmx->vm, vcpu, "Skip interrupt injection due to "
1240 		    "pending int_window_exiting");
1241 		return;
1242 	}
1243 
1244 	if (!extint_pending) {
1245 		/* Ask the local apic for a vector to inject */
1246 		if (!vlapic_pending_intr(vlapic, &vector))
1247 			return;
1248 
1249 		/*
1250 		 * From the Intel SDM, Volume 3, Section "Maskable
1251 		 * Hardware Interrupts":
1252 		 * - maskable interrupt vectors [16,255] can be delivered
1253 		 *   through the local APIC.
1254 		*/
1255 		KASSERT(vector >= 16 && vector <= 255,
1256 		    ("invalid vector %d from local APIC", vector));
1257 	} else {
1258 		/* Ask the legacy pic for a vector to inject */
1259 		vatpic_pending_intr(vmx->vm, &vector);
1260 
1261 		/*
1262 		 * From the Intel SDM, Volume 3, Section "Maskable
1263 		 * Hardware Interrupts":
1264 		 * - maskable interrupt vectors [0,255] can be delivered
1265 		 *   through the INTR pin.
1266 		 */
1267 		KASSERT(vector >= 0 && vector <= 255,
1268 		    ("invalid vector %d from INTR", vector));
1269 	}
1270 
1271 	/* Check RFLAGS.IF and the interruptibility state of the guest */
1272 	rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1273 	if ((rflags & PSL_I) == 0) {
1274 		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1275 		    "rflags %#lx", vector, rflags);
1276 		goto cantinject;
1277 	}
1278 
1279 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1280 	if (gi & HWINTR_BLOCKING) {
1281 		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1282 		    "Guest Interruptibility-state %#x", vector, gi);
1283 		goto cantinject;
1284 	}
1285 
1286 	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1287 	if (info & VMCS_INTR_VALID) {
1288 		/*
1289 		 * This is expected and could happen for multiple reasons:
1290 		 * - A vectoring VM-entry was aborted due to astpending
1291 		 * - A VM-exit happened during event injection.
1292 		 * - An exception was injected above.
1293 		 * - An NMI was injected above or after "NMI window exiting"
1294 		 */
1295 		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1296 		    "VM-entry intr info %#x", vector, info);
1297 		goto cantinject;
1298 	}
1299 
1300 	/* Inject the interrupt */
1301 	info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1302 	info |= vector;
1303 	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1304 
1305 	if (!extint_pending) {
1306 		/* Update the Local APIC ISR */
1307 		vlapic_intr_accepted(vlapic, vector);
1308 	} else {
1309 		vm_extint_clear(vmx->vm, vcpu);
1310 		vatpic_intr_accepted(vmx->vm, vector);
1311 
1312 		/*
1313 		 * After we accepted the current ExtINT the PIC may
1314 		 * have posted another one.  If that is the case, set
1315 		 * the Interrupt Window Exiting execution control so
1316 		 * we can inject that one too.
1317 		 *
1318 		 * Also, interrupt window exiting allows us to inject any
1319 		 * pending APIC vector that was preempted by the ExtINT
1320 		 * as soon as possible. This applies both for the software
1321 		 * emulated vlapic and the hardware assisted virtual APIC.
1322 		 */
1323 		vmx_set_int_window_exiting(vmx, vcpu);
1324 	}
1325 
1326 	VCPU_CTR1(vmx->vm, vcpu, "Injecting hwintr at vector %d", vector);
1327 
1328 	return;
1329 
1330 cantinject:
1331 	/*
1332 	 * Set the Interrupt Window Exiting execution control so we can inject
1333 	 * the interrupt as soon as blocking condition goes away.
1334 	 */
1335 	vmx_set_int_window_exiting(vmx, vcpu);
1336 }
1337 
1338 /*
1339  * If the Virtual NMIs execution control is '1' then the logical processor
1340  * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1341  * the VMCS. An IRET instruction in VMX non-root operation will remove any
1342  * virtual-NMI blocking.
1343  *
1344  * This unblocking occurs even if the IRET causes a fault. In this case the
1345  * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1346  */
1347 static void
1348 vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1349 {
1350 	uint32_t gi;
1351 
1352 	VCPU_CTR0(vmx->vm, vcpuid, "Restore Virtual-NMI blocking");
1353 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1354 	gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1355 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1356 }
1357 
1358 static void
1359 vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1360 {
1361 	uint32_t gi;
1362 
1363 	VCPU_CTR0(vmx->vm, vcpuid, "Clear Virtual-NMI blocking");
1364 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1365 	gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1366 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1367 }
1368 
1369 static void
1370 vmx_assert_nmi_blocking(struct vmx *vmx, int vcpuid)
1371 {
1372 	uint32_t gi;
1373 
1374 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1375 	KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1376 	    ("NMI blocking is not in effect %#x", gi));
1377 }
1378 
1379 static int
1380 vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1381 {
1382 	struct vmxctx *vmxctx;
1383 	uint64_t xcrval;
1384 	const struct xsave_limits *limits;
1385 
1386 	vmxctx = &vmx->ctx[vcpu];
1387 	limits = vmm_get_xsave_limits();
1388 
1389 	/*
1390 	 * Note that the processor raises a GP# fault on its own if
1391 	 * xsetbv is executed for CPL != 0, so we do not have to
1392 	 * emulate that fault here.
1393 	 */
1394 
1395 	/* Only xcr0 is supported. */
1396 	if (vmxctx->guest_rcx != 0) {
1397 		vm_inject_gp(vmx->vm, vcpu);
1398 		return (HANDLED);
1399 	}
1400 
1401 	/* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1402 	if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1403 		vm_inject_ud(vmx->vm, vcpu);
1404 		return (HANDLED);
1405 	}
1406 
1407 	xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1408 	if ((xcrval & ~limits->xcr0_allowed) != 0) {
1409 		vm_inject_gp(vmx->vm, vcpu);
1410 		return (HANDLED);
1411 	}
1412 
1413 	if (!(xcrval & XFEATURE_ENABLED_X87)) {
1414 		vm_inject_gp(vmx->vm, vcpu);
1415 		return (HANDLED);
1416 	}
1417 
1418 	/* AVX (YMM_Hi128) requires SSE. */
1419 	if (xcrval & XFEATURE_ENABLED_AVX &&
1420 	    (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1421 		vm_inject_gp(vmx->vm, vcpu);
1422 		return (HANDLED);
1423 	}
1424 
1425 	/*
1426 	 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1427 	 * ZMM_Hi256, and Hi16_ZMM.
1428 	 */
1429 	if (xcrval & XFEATURE_AVX512 &&
1430 	    (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1431 	    (XFEATURE_AVX512 | XFEATURE_AVX)) {
1432 		vm_inject_gp(vmx->vm, vcpu);
1433 		return (HANDLED);
1434 	}
1435 
1436 	/*
1437 	 * Intel MPX requires both bound register state flags to be
1438 	 * set.
1439 	 */
1440 	if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1441 	    ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1442 		vm_inject_gp(vmx->vm, vcpu);
1443 		return (HANDLED);
1444 	}
1445 
1446 	/*
1447 	 * This runs "inside" vmrun() with the guest's FPU state, so
1448 	 * modifying xcr0 directly modifies the guest's xcr0, not the
1449 	 * host's.
1450 	 */
1451 	load_xcr(0, xcrval);
1452 	return (HANDLED);
1453 }
1454 
1455 static uint64_t
1456 vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1457 {
1458 	const struct vmxctx *vmxctx;
1459 
1460 	vmxctx = &vmx->ctx[vcpu];
1461 
1462 	switch (ident) {
1463 	case 0:
1464 		return (vmxctx->guest_rax);
1465 	case 1:
1466 		return (vmxctx->guest_rcx);
1467 	case 2:
1468 		return (vmxctx->guest_rdx);
1469 	case 3:
1470 		return (vmxctx->guest_rbx);
1471 	case 4:
1472 		return (vmcs_read(VMCS_GUEST_RSP));
1473 	case 5:
1474 		return (vmxctx->guest_rbp);
1475 	case 6:
1476 		return (vmxctx->guest_rsi);
1477 	case 7:
1478 		return (vmxctx->guest_rdi);
1479 	case 8:
1480 		return (vmxctx->guest_r8);
1481 	case 9:
1482 		return (vmxctx->guest_r9);
1483 	case 10:
1484 		return (vmxctx->guest_r10);
1485 	case 11:
1486 		return (vmxctx->guest_r11);
1487 	case 12:
1488 		return (vmxctx->guest_r12);
1489 	case 13:
1490 		return (vmxctx->guest_r13);
1491 	case 14:
1492 		return (vmxctx->guest_r14);
1493 	case 15:
1494 		return (vmxctx->guest_r15);
1495 	default:
1496 		panic("invalid vmx register %d", ident);
1497 	}
1498 }
1499 
1500 static void
1501 vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1502 {
1503 	struct vmxctx *vmxctx;
1504 
1505 	vmxctx = &vmx->ctx[vcpu];
1506 
1507 	switch (ident) {
1508 	case 0:
1509 		vmxctx->guest_rax = regval;
1510 		break;
1511 	case 1:
1512 		vmxctx->guest_rcx = regval;
1513 		break;
1514 	case 2:
1515 		vmxctx->guest_rdx = regval;
1516 		break;
1517 	case 3:
1518 		vmxctx->guest_rbx = regval;
1519 		break;
1520 	case 4:
1521 		vmcs_write(VMCS_GUEST_RSP, regval);
1522 		break;
1523 	case 5:
1524 		vmxctx->guest_rbp = regval;
1525 		break;
1526 	case 6:
1527 		vmxctx->guest_rsi = regval;
1528 		break;
1529 	case 7:
1530 		vmxctx->guest_rdi = regval;
1531 		break;
1532 	case 8:
1533 		vmxctx->guest_r8 = regval;
1534 		break;
1535 	case 9:
1536 		vmxctx->guest_r9 = regval;
1537 		break;
1538 	case 10:
1539 		vmxctx->guest_r10 = regval;
1540 		break;
1541 	case 11:
1542 		vmxctx->guest_r11 = regval;
1543 		break;
1544 	case 12:
1545 		vmxctx->guest_r12 = regval;
1546 		break;
1547 	case 13:
1548 		vmxctx->guest_r13 = regval;
1549 		break;
1550 	case 14:
1551 		vmxctx->guest_r14 = regval;
1552 		break;
1553 	case 15:
1554 		vmxctx->guest_r15 = regval;
1555 		break;
1556 	default:
1557 		panic("invalid vmx register %d", ident);
1558 	}
1559 }
1560 
1561 static int
1562 vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1563 {
1564 	uint64_t crval, regval;
1565 
1566 	/* We only handle mov to %cr0 at this time */
1567 	if ((exitqual & 0xf0) != 0x00)
1568 		return (UNHANDLED);
1569 
1570 	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1571 
1572 	vmcs_write(VMCS_CR0_SHADOW, regval);
1573 
1574 	crval = regval | cr0_ones_mask;
1575 	crval &= ~cr0_zeros_mask;
1576 	vmcs_write(VMCS_GUEST_CR0, crval);
1577 
1578 	if (regval & CR0_PG) {
1579 		uint64_t efer, entry_ctls;
1580 
1581 		/*
1582 		 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1583 		 * the "IA-32e mode guest" bit in VM-entry control must be
1584 		 * equal.
1585 		 */
1586 		efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1587 		if (efer & EFER_LME) {
1588 			efer |= EFER_LMA;
1589 			vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1590 			entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1591 			entry_ctls |= VM_ENTRY_GUEST_LMA;
1592 			vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1593 		}
1594 	}
1595 
1596 	return (HANDLED);
1597 }
1598 
1599 static int
1600 vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1601 {
1602 	uint64_t crval, regval;
1603 
1604 	/* We only handle mov to %cr4 at this time */
1605 	if ((exitqual & 0xf0) != 0x00)
1606 		return (UNHANDLED);
1607 
1608 	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1609 
1610 	vmcs_write(VMCS_CR4_SHADOW, regval);
1611 
1612 	crval = regval | cr4_ones_mask;
1613 	crval &= ~cr4_zeros_mask;
1614 	vmcs_write(VMCS_GUEST_CR4, crval);
1615 
1616 	return (HANDLED);
1617 }
1618 
1619 static int
1620 vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1621 {
1622 	struct vlapic *vlapic;
1623 	uint64_t cr8;
1624 	int regnum;
1625 
1626 	/* We only handle mov %cr8 to/from a register at this time. */
1627 	if ((exitqual & 0xe0) != 0x00) {
1628 		return (UNHANDLED);
1629 	}
1630 
1631 	vlapic = vm_lapic(vmx->vm, vcpu);
1632 	regnum = (exitqual >> 8) & 0xf;
1633 	if (exitqual & 0x10) {
1634 		cr8 = vlapic_get_cr8(vlapic);
1635 		vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1636 	} else {
1637 		cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1638 		vlapic_set_cr8(vlapic, cr8);
1639 	}
1640 
1641 	return (HANDLED);
1642 }
1643 
1644 /*
1645  * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1646  */
1647 static int
1648 vmx_cpl(void)
1649 {
1650 	uint32_t ssar;
1651 
1652 	ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1653 	return ((ssar >> 5) & 0x3);
1654 }
1655 
1656 static enum vm_cpu_mode
1657 vmx_cpu_mode(void)
1658 {
1659 	uint32_t csar;
1660 
1661 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1662 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1663 		if (csar & 0x2000)
1664 			return (CPU_MODE_64BIT);	/* CS.L = 1 */
1665 		else
1666 			return (CPU_MODE_COMPATIBILITY);
1667 	} else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1668 		return (CPU_MODE_PROTECTED);
1669 	} else {
1670 		return (CPU_MODE_REAL);
1671 	}
1672 }
1673 
1674 static enum vm_paging_mode
1675 vmx_paging_mode(void)
1676 {
1677 
1678 	if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1679 		return (PAGING_MODE_FLAT);
1680 	if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1681 		return (PAGING_MODE_32);
1682 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1683 		return (PAGING_MODE_64);
1684 	else
1685 		return (PAGING_MODE_PAE);
1686 }
1687 
1688 static uint64_t
1689 inout_str_index(struct vmx *vmx, int vcpuid, int in)
1690 {
1691 	uint64_t val;
1692 	int error;
1693 	enum vm_reg_name reg;
1694 
1695 	reg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
1696 	error = vmx_getreg(vmx, vcpuid, reg, &val);
1697 	KASSERT(error == 0, ("%s: vmx_getreg error %d", __func__, error));
1698 	return (val);
1699 }
1700 
1701 static uint64_t
1702 inout_str_count(struct vmx *vmx, int vcpuid, int rep)
1703 {
1704 	uint64_t val;
1705 	int error;
1706 
1707 	if (rep) {
1708 		error = vmx_getreg(vmx, vcpuid, VM_REG_GUEST_RCX, &val);
1709 		KASSERT(!error, ("%s: vmx_getreg error %d", __func__, error));
1710 	} else {
1711 		val = 1;
1712 	}
1713 	return (val);
1714 }
1715 
1716 static int
1717 inout_str_addrsize(uint32_t inst_info)
1718 {
1719 	uint32_t size;
1720 
1721 	size = (inst_info >> 7) & 0x7;
1722 	switch (size) {
1723 	case 0:
1724 		return (2);	/* 16 bit */
1725 	case 1:
1726 		return (4);	/* 32 bit */
1727 	case 2:
1728 		return (8);	/* 64 bit */
1729 	default:
1730 		panic("%s: invalid size encoding %d", __func__, size);
1731 	}
1732 }
1733 
1734 static void
1735 inout_str_seginfo(struct vmx *vmx, int vcpuid, uint32_t inst_info, int in,
1736     struct vm_inout_str *vis)
1737 {
1738 	int error, s;
1739 
1740 	if (in) {
1741 		vis->seg_name = VM_REG_GUEST_ES;
1742 	} else {
1743 		s = (inst_info >> 15) & 0x7;
1744 		vis->seg_name = vm_segment_name(s);
1745 	}
1746 
1747 	error = vmx_getdesc(vmx, vcpuid, vis->seg_name, &vis->seg_desc);
1748 	KASSERT(error == 0, ("%s: vmx_getdesc error %d", __func__, error));
1749 }
1750 
1751 static void
1752 vmx_paging_info(struct vm_guest_paging *paging)
1753 {
1754 	paging->cr3 = vmcs_guest_cr3();
1755 	paging->cpl = vmx_cpl();
1756 	paging->cpu_mode = vmx_cpu_mode();
1757 	paging->paging_mode = vmx_paging_mode();
1758 }
1759 
1760 static void
1761 vmexit_inst_emul(struct vm_exit *vmexit, uint64_t gpa, uint64_t gla)
1762 {
1763 	struct vm_guest_paging *paging;
1764 	uint32_t csar;
1765 
1766 	paging = &vmexit->u.inst_emul.paging;
1767 
1768 	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
1769 	vmexit->u.inst_emul.gpa = gpa;
1770 	vmexit->u.inst_emul.gla = gla;
1771 	vmx_paging_info(paging);
1772 	switch (paging->cpu_mode) {
1773 	case CPU_MODE_PROTECTED:
1774 	case CPU_MODE_COMPATIBILITY:
1775 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1776 		vmexit->u.inst_emul.cs_d = SEG_DESC_DEF32(csar);
1777 		break;
1778 	default:
1779 		vmexit->u.inst_emul.cs_d = 0;
1780 		break;
1781 	}
1782 	vie_init(&vmexit->u.inst_emul.vie, NULL, 0);
1783 }
1784 
1785 static int
1786 ept_fault_type(uint64_t ept_qual)
1787 {
1788 	int fault_type;
1789 
1790 	if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1791 		fault_type = VM_PROT_WRITE;
1792 	else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1793 		fault_type = VM_PROT_EXECUTE;
1794 	else
1795 		fault_type= VM_PROT_READ;
1796 
1797 	return (fault_type);
1798 }
1799 
1800 static boolean_t
1801 ept_emulation_fault(uint64_t ept_qual)
1802 {
1803 	int read, write;
1804 
1805 	/* EPT fault on an instruction fetch doesn't make sense here */
1806 	if (ept_qual & EPT_VIOLATION_INST_FETCH)
1807 		return (FALSE);
1808 
1809 	/* EPT fault must be a read fault or a write fault */
1810 	read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1811 	write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1812 	if ((read | write) == 0)
1813 		return (FALSE);
1814 
1815 	/*
1816 	 * The EPT violation must have been caused by accessing a
1817 	 * guest-physical address that is a translation of a guest-linear
1818 	 * address.
1819 	 */
1820 	if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1821 	    (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1822 		return (FALSE);
1823 	}
1824 
1825 	return (TRUE);
1826 }
1827 
1828 static __inline int
1829 apic_access_virtualization(struct vmx *vmx, int vcpuid)
1830 {
1831 	uint32_t proc_ctls2;
1832 
1833 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1834 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1835 }
1836 
1837 static __inline int
1838 x2apic_virtualization(struct vmx *vmx, int vcpuid)
1839 {
1840 	uint32_t proc_ctls2;
1841 
1842 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1843 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1844 }
1845 
1846 static int
1847 vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1848     uint64_t qual)
1849 {
1850 	int error, handled, offset;
1851 	uint32_t *apic_regs, vector;
1852 	bool retu;
1853 
1854 	handled = HANDLED;
1855 	offset = APIC_WRITE_OFFSET(qual);
1856 
1857 	if (!apic_access_virtualization(vmx, vcpuid)) {
1858 		/*
1859 		 * In general there should not be any APIC write VM-exits
1860 		 * unless APIC-access virtualization is enabled.
1861 		 *
1862 		 * However self-IPI virtualization can legitimately trigger
1863 		 * an APIC-write VM-exit so treat it specially.
1864 		 */
1865 		if (x2apic_virtualization(vmx, vcpuid) &&
1866 		    offset == APIC_OFFSET_SELF_IPI) {
1867 			apic_regs = (uint32_t *)(vlapic->apic_page);
1868 			vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
1869 			vlapic_self_ipi_handler(vlapic, vector);
1870 			return (HANDLED);
1871 		} else
1872 			return (UNHANDLED);
1873 	}
1874 
1875 	switch (offset) {
1876 	case APIC_OFFSET_ID:
1877 		vlapic_id_write_handler(vlapic);
1878 		break;
1879 	case APIC_OFFSET_LDR:
1880 		vlapic_ldr_write_handler(vlapic);
1881 		break;
1882 	case APIC_OFFSET_DFR:
1883 		vlapic_dfr_write_handler(vlapic);
1884 		break;
1885 	case APIC_OFFSET_SVR:
1886 		vlapic_svr_write_handler(vlapic);
1887 		break;
1888 	case APIC_OFFSET_ESR:
1889 		vlapic_esr_write_handler(vlapic);
1890 		break;
1891 	case APIC_OFFSET_ICR_LOW:
1892 		retu = false;
1893 		error = vlapic_icrlo_write_handler(vlapic, &retu);
1894 		if (error != 0 || retu)
1895 			handled = UNHANDLED;
1896 		break;
1897 	case APIC_OFFSET_CMCI_LVT:
1898 	case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1899 		vlapic_lvt_write_handler(vlapic, offset);
1900 		break;
1901 	case APIC_OFFSET_TIMER_ICR:
1902 		vlapic_icrtmr_write_handler(vlapic);
1903 		break;
1904 	case APIC_OFFSET_TIMER_DCR:
1905 		vlapic_dcr_write_handler(vlapic);
1906 		break;
1907 	default:
1908 		handled = UNHANDLED;
1909 		break;
1910 	}
1911 	return (handled);
1912 }
1913 
1914 static bool
1915 apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
1916 {
1917 
1918 	if (apic_access_virtualization(vmx, vcpuid) &&
1919 	    (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
1920 		return (true);
1921 	else
1922 		return (false);
1923 }
1924 
1925 static int
1926 vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
1927 {
1928 	uint64_t qual;
1929 	int access_type, offset, allowed;
1930 
1931 	if (!apic_access_virtualization(vmx, vcpuid))
1932 		return (UNHANDLED);
1933 
1934 	qual = vmexit->u.vmx.exit_qualification;
1935 	access_type = APIC_ACCESS_TYPE(qual);
1936 	offset = APIC_ACCESS_OFFSET(qual);
1937 
1938 	allowed = 0;
1939 	if (access_type == 0) {
1940 		/*
1941 		 * Read data access to the following registers is expected.
1942 		 */
1943 		switch (offset) {
1944 		case APIC_OFFSET_APR:
1945 		case APIC_OFFSET_PPR:
1946 		case APIC_OFFSET_RRR:
1947 		case APIC_OFFSET_CMCI_LVT:
1948 		case APIC_OFFSET_TIMER_CCR:
1949 			allowed = 1;
1950 			break;
1951 		default:
1952 			break;
1953 		}
1954 	} else if (access_type == 1) {
1955 		/*
1956 		 * Write data access to the following registers is expected.
1957 		 */
1958 		switch (offset) {
1959 		case APIC_OFFSET_VER:
1960 		case APIC_OFFSET_APR:
1961 		case APIC_OFFSET_PPR:
1962 		case APIC_OFFSET_RRR:
1963 		case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
1964 		case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
1965 		case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
1966 		case APIC_OFFSET_CMCI_LVT:
1967 		case APIC_OFFSET_TIMER_CCR:
1968 			allowed = 1;
1969 			break;
1970 		default:
1971 			break;
1972 		}
1973 	}
1974 
1975 	if (allowed) {
1976 		vmexit_inst_emul(vmexit, DEFAULT_APIC_BASE + offset,
1977 		    VIE_INVALID_GLA);
1978 	}
1979 
1980 	/*
1981 	 * Regardless of whether the APIC-access is allowed this handler
1982 	 * always returns UNHANDLED:
1983 	 * - if the access is allowed then it is handled by emulating the
1984 	 *   instruction that caused the VM-exit (outside the critical section)
1985 	 * - if the access is not allowed then it will be converted to an
1986 	 *   exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
1987 	 */
1988 	return (UNHANDLED);
1989 }
1990 
1991 static enum task_switch_reason
1992 vmx_task_switch_reason(uint64_t qual)
1993 {
1994 	int reason;
1995 
1996 	reason = (qual >> 30) & 0x3;
1997 	switch (reason) {
1998 	case 0:
1999 		return (TSR_CALL);
2000 	case 1:
2001 		return (TSR_IRET);
2002 	case 2:
2003 		return (TSR_JMP);
2004 	case 3:
2005 		return (TSR_IDT_GATE);
2006 	default:
2007 		panic("%s: invalid reason %d", __func__, reason);
2008 	}
2009 }
2010 
2011 static int
2012 emulate_wrmsr(struct vmx *vmx, int vcpuid, u_int num, uint64_t val, bool *retu)
2013 {
2014 	int error;
2015 
2016 	if (lapic_msr(num))
2017 		error = lapic_wrmsr(vmx->vm, vcpuid, num, val, retu);
2018 	else
2019 		error = vmx_wrmsr(vmx, vcpuid, num, val, retu);
2020 
2021 	return (error);
2022 }
2023 
2024 static int
2025 emulate_rdmsr(struct vmx *vmx, int vcpuid, u_int num, bool *retu)
2026 {
2027 	struct vmxctx *vmxctx;
2028 	uint64_t result;
2029 	uint32_t eax, edx;
2030 	int error;
2031 
2032 	if (lapic_msr(num))
2033 		error = lapic_rdmsr(vmx->vm, vcpuid, num, &result, retu);
2034 	else
2035 		error = vmx_rdmsr(vmx, vcpuid, num, &result, retu);
2036 
2037 	if (error == 0) {
2038 		eax = result;
2039 		vmxctx = &vmx->ctx[vcpuid];
2040 		error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RAX, eax);
2041 		KASSERT(error == 0, ("vmxctx_setreg(rax) error %d", error));
2042 
2043 		edx = result >> 32;
2044 		error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RDX, edx);
2045 		KASSERT(error == 0, ("vmxctx_setreg(rdx) error %d", error));
2046 	}
2047 
2048 	return (error);
2049 }
2050 
2051 static int
2052 vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2053 {
2054 	int error, handled, in;
2055 	struct vmxctx *vmxctx;
2056 	struct vlapic *vlapic;
2057 	struct vm_inout_str *vis;
2058 	struct vm_task_switch *ts;
2059 	uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, inst_info;
2060 	uint32_t intr_type, reason;
2061 	uint64_t exitintinfo, qual, gpa;
2062 	bool retu;
2063 
2064 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2065 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2066 
2067 	handled = UNHANDLED;
2068 	vmxctx = &vmx->ctx[vcpu];
2069 
2070 	qual = vmexit->u.vmx.exit_qualification;
2071 	reason = vmexit->u.vmx.exit_reason;
2072 	vmexit->exitcode = VM_EXITCODE_BOGUS;
2073 
2074 	vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
2075 
2076 	/*
2077 	 * VM exits that can be triggered during event delivery need to
2078 	 * be handled specially by re-injecting the event if the IDT
2079 	 * vectoring information field's valid bit is set.
2080 	 *
2081 	 * See "Information for VM Exits During Event Delivery" in Intel SDM
2082 	 * for details.
2083 	 */
2084 	idtvec_info = vmcs_idt_vectoring_info();
2085 	if (idtvec_info & VMCS_IDT_VEC_VALID) {
2086 		idtvec_info &= ~(1 << 12); /* clear undefined bit */
2087 		exitintinfo = idtvec_info;
2088 		if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2089 			idtvec_err = vmcs_idt_vectoring_err();
2090 			exitintinfo |= (uint64_t)idtvec_err << 32;
2091 		}
2092 		error = vm_exit_intinfo(vmx->vm, vcpu, exitintinfo);
2093 		KASSERT(error == 0, ("%s: vm_set_intinfo error %d",
2094 		    __func__, error));
2095 
2096 		/*
2097 		 * If 'virtual NMIs' are being used and the VM-exit
2098 		 * happened while injecting an NMI during the previous
2099 		 * VM-entry, then clear "blocking by NMI" in the
2100 		 * Guest Interruptibility-State so the NMI can be
2101 		 * reinjected on the subsequent VM-entry.
2102 		 *
2103 		 * However, if the NMI was being delivered through a task
2104 		 * gate, then the new task must start execution with NMIs
2105 		 * blocked so don't clear NMI blocking in this case.
2106 		 */
2107 		intr_type = idtvec_info & VMCS_INTR_T_MASK;
2108 		if (intr_type == VMCS_INTR_T_NMI) {
2109 			if (reason != EXIT_REASON_TASK_SWITCH)
2110 				vmx_clear_nmi_blocking(vmx, vcpu);
2111 			else
2112 				vmx_assert_nmi_blocking(vmx, vcpu);
2113 		}
2114 
2115 		/*
2116 		 * Update VM-entry instruction length if the event being
2117 		 * delivered was a software interrupt or software exception.
2118 		 */
2119 		if (intr_type == VMCS_INTR_T_SWINTR ||
2120 		    intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2121 		    intr_type == VMCS_INTR_T_SWEXCEPTION) {
2122 			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2123 		}
2124 	}
2125 
2126 	switch (reason) {
2127 	case EXIT_REASON_TASK_SWITCH:
2128 		ts = &vmexit->u.task_switch;
2129 		ts->tsssel = qual & 0xffff;
2130 		ts->reason = vmx_task_switch_reason(qual);
2131 		ts->ext = 0;
2132 		ts->errcode_valid = 0;
2133 		vmx_paging_info(&ts->paging);
2134 		/*
2135 		 * If the task switch was due to a CALL, JMP, IRET, software
2136 		 * interrupt (INT n) or software exception (INT3, INTO),
2137 		 * then the saved %rip references the instruction that caused
2138 		 * the task switch. The instruction length field in the VMCS
2139 		 * is valid in this case.
2140 		 *
2141 		 * In all other cases (e.g., NMI, hardware exception) the
2142 		 * saved %rip is one that would have been saved in the old TSS
2143 		 * had the task switch completed normally so the instruction
2144 		 * length field is not needed in this case and is explicitly
2145 		 * set to 0.
2146 		 */
2147 		if (ts->reason == TSR_IDT_GATE) {
2148 			KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2149 			    ("invalid idtvec_info %#x for IDT task switch",
2150 			    idtvec_info));
2151 			intr_type = idtvec_info & VMCS_INTR_T_MASK;
2152 			if (intr_type != VMCS_INTR_T_SWINTR &&
2153 			    intr_type != VMCS_INTR_T_SWEXCEPTION &&
2154 			    intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2155 				/* Task switch triggered by external event */
2156 				ts->ext = 1;
2157 				vmexit->inst_length = 0;
2158 				if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2159 					ts->errcode_valid = 1;
2160 					ts->errcode = vmcs_idt_vectoring_err();
2161 				}
2162 			}
2163 		}
2164 		vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2165 		VCPU_CTR4(vmx->vm, vcpu, "task switch reason %d, tss 0x%04x, "
2166 		    "%s errcode 0x%016lx", ts->reason, ts->tsssel,
2167 		    ts->ext ? "external" : "internal",
2168 		    ((uint64_t)ts->errcode << 32) | ts->errcode_valid);
2169 		break;
2170 	case EXIT_REASON_CR_ACCESS:
2171 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2172 		switch (qual & 0xf) {
2173 		case 0:
2174 			handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2175 			break;
2176 		case 4:
2177 			handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2178 			break;
2179 		case 8:
2180 			handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2181 			break;
2182 		}
2183 		break;
2184 	case EXIT_REASON_RDMSR:
2185 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RDMSR, 1);
2186 		retu = false;
2187 		ecx = vmxctx->guest_rcx;
2188 		VCPU_CTR1(vmx->vm, vcpu, "rdmsr 0x%08x", ecx);
2189 		error = emulate_rdmsr(vmx, vcpu, ecx, &retu);
2190 		if (error) {
2191 			vmexit->exitcode = VM_EXITCODE_RDMSR;
2192 			vmexit->u.msr.code = ecx;
2193 		} else if (!retu) {
2194 			handled = HANDLED;
2195 		} else {
2196 			/* Return to userspace with a valid exitcode */
2197 			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2198 			    ("emulate_rdmsr retu with bogus exitcode"));
2199 		}
2200 		break;
2201 	case EXIT_REASON_WRMSR:
2202 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_WRMSR, 1);
2203 		retu = false;
2204 		eax = vmxctx->guest_rax;
2205 		ecx = vmxctx->guest_rcx;
2206 		edx = vmxctx->guest_rdx;
2207 		VCPU_CTR2(vmx->vm, vcpu, "wrmsr 0x%08x value 0x%016lx",
2208 		    ecx, (uint64_t)edx << 32 | eax);
2209 		error = emulate_wrmsr(vmx, vcpu, ecx,
2210 		    (uint64_t)edx << 32 | eax, &retu);
2211 		if (error) {
2212 			vmexit->exitcode = VM_EXITCODE_WRMSR;
2213 			vmexit->u.msr.code = ecx;
2214 			vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
2215 		} else if (!retu) {
2216 			handled = HANDLED;
2217 		} else {
2218 			/* Return to userspace with a valid exitcode */
2219 			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2220 			    ("emulate_wrmsr retu with bogus exitcode"));
2221 		}
2222 		break;
2223 	case EXIT_REASON_HLT:
2224 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2225 		vmexit->exitcode = VM_EXITCODE_HLT;
2226 		vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2227 		break;
2228 	case EXIT_REASON_MTF:
2229 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2230 		vmexit->exitcode = VM_EXITCODE_MTRAP;
2231 		break;
2232 	case EXIT_REASON_PAUSE:
2233 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2234 		vmexit->exitcode = VM_EXITCODE_PAUSE;
2235 		break;
2236 	case EXIT_REASON_INTR_WINDOW:
2237 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2238 		vmx_clear_int_window_exiting(vmx, vcpu);
2239 		return (1);
2240 	case EXIT_REASON_EXT_INTR:
2241 		/*
2242 		 * External interrupts serve only to cause VM exits and allow
2243 		 * the host interrupt handler to run.
2244 		 *
2245 		 * If this external interrupt triggers a virtual interrupt
2246 		 * to a VM, then that state will be recorded by the
2247 		 * host interrupt handler in the VM's softc. We will inject
2248 		 * this virtual interrupt during the subsequent VM enter.
2249 		 */
2250 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2251 
2252 		/*
2253 		 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2254 		 * This appears to be a bug in VMware Fusion?
2255 		 */
2256 		if (!(intr_info & VMCS_INTR_VALID))
2257 			return (1);
2258 		KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2259 		    (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2260 		    ("VM exit interruption info invalid: %#x", intr_info));
2261 		vmx_trigger_hostintr(intr_info & 0xff);
2262 
2263 		/*
2264 		 * This is special. We want to treat this as an 'handled'
2265 		 * VM-exit but not increment the instruction pointer.
2266 		 */
2267 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2268 		return (1);
2269 	case EXIT_REASON_NMI_WINDOW:
2270 		/* Exit to allow the pending virtual NMI to be injected */
2271 		if (vm_nmi_pending(vmx->vm, vcpu))
2272 			vmx_inject_nmi(vmx, vcpu);
2273 		vmx_clear_nmi_window_exiting(vmx, vcpu);
2274 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2275 		return (1);
2276 	case EXIT_REASON_INOUT:
2277 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2278 		vmexit->exitcode = VM_EXITCODE_INOUT;
2279 		vmexit->u.inout.bytes = (qual & 0x7) + 1;
2280 		vmexit->u.inout.in = in = (qual & 0x8) ? 1 : 0;
2281 		vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
2282 		vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
2283 		vmexit->u.inout.port = (uint16_t)(qual >> 16);
2284 		vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
2285 		if (vmexit->u.inout.string) {
2286 			inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
2287 			vmexit->exitcode = VM_EXITCODE_INOUT_STR;
2288 			vis = &vmexit->u.inout_str;
2289 			vmx_paging_info(&vis->paging);
2290 			vis->rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2291 			vis->cr0 = vmcs_read(VMCS_GUEST_CR0);
2292 			vis->index = inout_str_index(vmx, vcpu, in);
2293 			vis->count = inout_str_count(vmx, vcpu, vis->inout.rep);
2294 			vis->addrsize = inout_str_addrsize(inst_info);
2295 			inout_str_seginfo(vmx, vcpu, inst_info, in, vis);
2296 		}
2297 		break;
2298 	case EXIT_REASON_CPUID:
2299 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2300 		handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
2301 		break;
2302 	case EXIT_REASON_EXCEPTION:
2303 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2304 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2305 		KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2306 		    ("VM exit interruption info invalid: %#x", intr_info));
2307 
2308 		/*
2309 		 * If Virtual NMIs control is 1 and the VM-exit is due to a
2310 		 * fault encountered during the execution of IRET then we must
2311 		 * restore the state of "virtual-NMI blocking" before resuming
2312 		 * the guest.
2313 		 *
2314 		 * See "Resuming Guest Software after Handling an Exception".
2315 		 * See "Information for VM Exits Due to Vectored Events".
2316 		 */
2317 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2318 		    (intr_info & 0xff) != IDT_DF &&
2319 		    (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2320 			vmx_restore_nmi_blocking(vmx, vcpu);
2321 
2322 		/*
2323 		 * The NMI has already been handled in vmx_exit_handle_nmi().
2324 		 */
2325 		if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI)
2326 			return (1);
2327 		break;
2328 	case EXIT_REASON_EPT_FAULT:
2329 		/*
2330 		 * If 'gpa' lies within the address space allocated to
2331 		 * memory then this must be a nested page fault otherwise
2332 		 * this must be an instruction that accesses MMIO space.
2333 		 */
2334 		gpa = vmcs_gpa();
2335 		if (vm_mem_allocated(vmx->vm, gpa) ||
2336 		    apic_access_fault(vmx, vcpu, gpa)) {
2337 			vmexit->exitcode = VM_EXITCODE_PAGING;
2338 			vmexit->u.paging.gpa = gpa;
2339 			vmexit->u.paging.fault_type = ept_fault_type(qual);
2340 			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2341 		} else if (ept_emulation_fault(qual)) {
2342 			vmexit_inst_emul(vmexit, gpa, vmcs_gla());
2343 			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1);
2344 		}
2345 		/*
2346 		 * If Virtual NMIs control is 1 and the VM-exit is due to an
2347 		 * EPT fault during the execution of IRET then we must restore
2348 		 * the state of "virtual-NMI blocking" before resuming.
2349 		 *
2350 		 * See description of "NMI unblocking due to IRET" in
2351 		 * "Exit Qualification for EPT Violations".
2352 		 */
2353 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2354 		    (qual & EXIT_QUAL_NMIUDTI) != 0)
2355 			vmx_restore_nmi_blocking(vmx, vcpu);
2356 		break;
2357 	case EXIT_REASON_VIRTUALIZED_EOI:
2358 		vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2359 		vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2360 		vmexit->inst_length = 0;	/* trap-like */
2361 		break;
2362 	case EXIT_REASON_APIC_ACCESS:
2363 		handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2364 		break;
2365 	case EXIT_REASON_APIC_WRITE:
2366 		/*
2367 		 * APIC-write VM exit is trap-like so the %rip is already
2368 		 * pointing to the next instruction.
2369 		 */
2370 		vmexit->inst_length = 0;
2371 		vlapic = vm_lapic(vmx->vm, vcpu);
2372 		handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2373 		break;
2374 	case EXIT_REASON_XSETBV:
2375 		handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2376 		break;
2377 	case EXIT_REASON_MONITOR:
2378 		vmexit->exitcode = VM_EXITCODE_MONITOR;
2379 		break;
2380 	case EXIT_REASON_MWAIT:
2381 		vmexit->exitcode = VM_EXITCODE_MWAIT;
2382 		break;
2383 	default:
2384 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2385 		break;
2386 	}
2387 
2388 	if (handled) {
2389 		/*
2390 		 * It is possible that control is returned to userland
2391 		 * even though we were able to handle the VM exit in the
2392 		 * kernel.
2393 		 *
2394 		 * In such a case we want to make sure that the userland
2395 		 * restarts guest execution at the instruction *after*
2396 		 * the one we just processed. Therefore we update the
2397 		 * guest rip in the VMCS and in 'vmexit'.
2398 		 */
2399 		vmexit->rip += vmexit->inst_length;
2400 		vmexit->inst_length = 0;
2401 		vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2402 	} else {
2403 		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2404 			/*
2405 			 * If this VM exit was not claimed by anybody then
2406 			 * treat it as a generic VMX exit.
2407 			 */
2408 			vmexit->exitcode = VM_EXITCODE_VMX;
2409 			vmexit->u.vmx.status = VM_SUCCESS;
2410 			vmexit->u.vmx.inst_type = 0;
2411 			vmexit->u.vmx.inst_error = 0;
2412 		} else {
2413 			/*
2414 			 * The exitcode and collateral have been populated.
2415 			 * The VM exit will be processed further in userland.
2416 			 */
2417 		}
2418 	}
2419 	return (handled);
2420 }
2421 
2422 static __inline void
2423 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2424 {
2425 
2426 	KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2427 	    ("vmx_exit_inst_error: invalid inst_fail_status %d",
2428 	    vmxctx->inst_fail_status));
2429 
2430 	vmexit->inst_length = 0;
2431 	vmexit->exitcode = VM_EXITCODE_VMX;
2432 	vmexit->u.vmx.status = vmxctx->inst_fail_status;
2433 	vmexit->u.vmx.inst_error = vmcs_instruction_error();
2434 	vmexit->u.vmx.exit_reason = ~0;
2435 	vmexit->u.vmx.exit_qualification = ~0;
2436 
2437 	switch (rc) {
2438 	case VMX_VMRESUME_ERROR:
2439 	case VMX_VMLAUNCH_ERROR:
2440 	case VMX_INVEPT_ERROR:
2441 		vmexit->u.vmx.inst_type = rc;
2442 		break;
2443 	default:
2444 		panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2445 	}
2446 }
2447 
2448 /*
2449  * If the NMI-exiting VM execution control is set to '1' then an NMI in
2450  * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2451  * sufficient to simply vector to the NMI handler via a software interrupt.
2452  * However, this must be done before maskable interrupts are enabled
2453  * otherwise the "iret" issued by an interrupt handler will incorrectly
2454  * clear NMI blocking.
2455  */
2456 static __inline void
2457 vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2458 {
2459 	uint32_t intr_info;
2460 
2461 	KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2462 
2463 	if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2464 		return;
2465 
2466 	intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2467 	KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2468 	    ("VM exit interruption info invalid: %#x", intr_info));
2469 
2470 	if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2471 		KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2472 		    "to NMI has invalid vector: %#x", intr_info));
2473 		VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2474 		__asm __volatile("int $2");
2475 	}
2476 }
2477 
2478 static int
2479 vmx_run(void *arg, int vcpu, register_t startrip, pmap_t pmap,
2480     void *rendezvous_cookie, void *suspend_cookie)
2481 {
2482 	int rc, handled, launched;
2483 	struct vmx *vmx;
2484 	struct vm *vm;
2485 	struct vmxctx *vmxctx;
2486 	struct vmcs *vmcs;
2487 	struct vm_exit *vmexit;
2488 	struct vlapic *vlapic;
2489 	uint64_t rip;
2490 	uint32_t exit_reason;
2491 
2492 	vmx = arg;
2493 	vm = vmx->vm;
2494 	vmcs = &vmx->vmcs[vcpu];
2495 	vmxctx = &vmx->ctx[vcpu];
2496 	vlapic = vm_lapic(vm, vcpu);
2497 	vmexit = vm_exitinfo(vm, vcpu);
2498 	launched = 0;
2499 
2500 	KASSERT(vmxctx->pmap == pmap,
2501 	    ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
2502 
2503 	vmx_msr_guest_enter(vmx, vcpu);
2504 
2505 	VMPTRLD(vmcs);
2506 
2507 	/*
2508 	 * XXX
2509 	 * We do this every time because we may setup the virtual machine
2510 	 * from a different process than the one that actually runs it.
2511 	 *
2512 	 * If the life of a virtual machine was spent entirely in the context
2513 	 * of a single process we could do this once in vmx_vminit().
2514 	 */
2515 	vmcs_write(VMCS_HOST_CR3, rcr3());
2516 
2517 	vmcs_write(VMCS_GUEST_RIP, startrip);
2518 	vmx_set_pcpu_defaults(vmx, vcpu, pmap);
2519 	do {
2520 		handled = UNHANDLED;
2521 
2522 		/*
2523 		 * Interrupts are disabled from this point on until the
2524 		 * guest starts executing. This is done for the following
2525 		 * reasons:
2526 		 *
2527 		 * If an AST is asserted on this thread after the check below,
2528 		 * then the IPI_AST notification will not be lost, because it
2529 		 * will cause a VM exit due to external interrupt as soon as
2530 		 * the guest state is loaded.
2531 		 *
2532 		 * A posted interrupt after 'vmx_inject_interrupts()' will
2533 		 * not be "lost" because it will be held pending in the host
2534 		 * APIC because interrupts are disabled. The pending interrupt
2535 		 * will be recognized as soon as the guest state is loaded.
2536 		 *
2537 		 * The same reasoning applies to the IPI generated by
2538 		 * pmap_invalidate_ept().
2539 		 */
2540 		disable_intr();
2541 		vmx_inject_interrupts(vmx, vcpu, vlapic);
2542 
2543 		/*
2544 		 * Check for vcpu suspension after injecting events because
2545 		 * vmx_inject_interrupts() can suspend the vcpu due to a
2546 		 * triple fault.
2547 		 */
2548 		if (vcpu_suspended(suspend_cookie)) {
2549 			enable_intr();
2550 			vm_exit_suspended(vmx->vm, vcpu, vmcs_guest_rip());
2551 			break;
2552 		}
2553 
2554 		if (vcpu_rendezvous_pending(rendezvous_cookie)) {
2555 			enable_intr();
2556 			vm_exit_rendezvous(vmx->vm, vcpu, vmcs_guest_rip());
2557 			break;
2558 		}
2559 
2560 		if (vcpu_should_yield(vm, vcpu)) {
2561 			enable_intr();
2562 			vm_exit_astpending(vmx->vm, vcpu, vmcs_guest_rip());
2563 			vmx_astpending_trace(vmx, vcpu, vmexit->rip);
2564 			handled = HANDLED;
2565 			break;
2566 		}
2567 
2568 		vmx_run_trace(vmx, vcpu);
2569 		rc = vmx_enter_guest(vmxctx, vmx, launched);
2570 
2571 		/* Collect some information for VM exit processing */
2572 		vmexit->rip = rip = vmcs_guest_rip();
2573 		vmexit->inst_length = vmexit_instruction_length();
2574 		vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
2575 		vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
2576 
2577 		if (rc == VMX_GUEST_VMEXIT) {
2578 			vmx_exit_handle_nmi(vmx, vcpu, vmexit);
2579 			enable_intr();
2580 			handled = vmx_exit_process(vmx, vcpu, vmexit);
2581 		} else {
2582 			enable_intr();
2583 			vmx_exit_inst_error(vmxctx, rc, vmexit);
2584 		}
2585 		launched = 1;
2586 		vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
2587 	} while (handled);
2588 
2589 	/*
2590 	 * If a VM exit has been handled then the exitcode must be BOGUS
2591 	 * If a VM exit is not handled then the exitcode must not be BOGUS
2592 	 */
2593 	if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
2594 	    (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
2595 		panic("Mismatch between handled (%d) and exitcode (%d)",
2596 		      handled, vmexit->exitcode);
2597 	}
2598 
2599 	if (!handled)
2600 		vmm_stat_incr(vm, vcpu, VMEXIT_USERSPACE, 1);
2601 
2602 	VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
2603 	    vmexit->exitcode);
2604 
2605 	VMCLEAR(vmcs);
2606 	vmx_msr_guest_exit(vmx, vcpu);
2607 
2608 	return (0);
2609 }
2610 
2611 static void
2612 vmx_vmcleanup(void *arg)
2613 {
2614 	int i;
2615 	struct vmx *vmx = arg;
2616 
2617 	if (apic_access_virtualization(vmx, 0))
2618 		vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2619 
2620 	for (i = 0; i < VM_MAXCPU; i++)
2621 		vpid_free(vmx->state[i].vpid);
2622 
2623 	free(vmx, M_VMX);
2624 
2625 	return;
2626 }
2627 
2628 static register_t *
2629 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
2630 {
2631 
2632 	switch (reg) {
2633 	case VM_REG_GUEST_RAX:
2634 		return (&vmxctx->guest_rax);
2635 	case VM_REG_GUEST_RBX:
2636 		return (&vmxctx->guest_rbx);
2637 	case VM_REG_GUEST_RCX:
2638 		return (&vmxctx->guest_rcx);
2639 	case VM_REG_GUEST_RDX:
2640 		return (&vmxctx->guest_rdx);
2641 	case VM_REG_GUEST_RSI:
2642 		return (&vmxctx->guest_rsi);
2643 	case VM_REG_GUEST_RDI:
2644 		return (&vmxctx->guest_rdi);
2645 	case VM_REG_GUEST_RBP:
2646 		return (&vmxctx->guest_rbp);
2647 	case VM_REG_GUEST_R8:
2648 		return (&vmxctx->guest_r8);
2649 	case VM_REG_GUEST_R9:
2650 		return (&vmxctx->guest_r9);
2651 	case VM_REG_GUEST_R10:
2652 		return (&vmxctx->guest_r10);
2653 	case VM_REG_GUEST_R11:
2654 		return (&vmxctx->guest_r11);
2655 	case VM_REG_GUEST_R12:
2656 		return (&vmxctx->guest_r12);
2657 	case VM_REG_GUEST_R13:
2658 		return (&vmxctx->guest_r13);
2659 	case VM_REG_GUEST_R14:
2660 		return (&vmxctx->guest_r14);
2661 	case VM_REG_GUEST_R15:
2662 		return (&vmxctx->guest_r15);
2663 	case VM_REG_GUEST_CR2:
2664 		return (&vmxctx->guest_cr2);
2665 	default:
2666 		break;
2667 	}
2668 	return (NULL);
2669 }
2670 
2671 static int
2672 vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
2673 {
2674 	register_t *regp;
2675 
2676 	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2677 		*retval = *regp;
2678 		return (0);
2679 	} else
2680 		return (EINVAL);
2681 }
2682 
2683 static int
2684 vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
2685 {
2686 	register_t *regp;
2687 
2688 	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2689 		*regp = val;
2690 		return (0);
2691 	} else
2692 		return (EINVAL);
2693 }
2694 
2695 static int
2696 vmx_get_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t *retval)
2697 {
2698 	uint64_t gi;
2699 	int error;
2700 
2701 	error = vmcs_getreg(&vmx->vmcs[vcpu], running,
2702 	    VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY), &gi);
2703 	*retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
2704 	return (error);
2705 }
2706 
2707 static int
2708 vmx_modify_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t val)
2709 {
2710 	struct vmcs *vmcs;
2711 	uint64_t gi;
2712 	int error, ident;
2713 
2714 	/*
2715 	 * Forcing the vcpu into an interrupt shadow is not supported.
2716 	 */
2717 	if (val) {
2718 		error = EINVAL;
2719 		goto done;
2720 	}
2721 
2722 	vmcs = &vmx->vmcs[vcpu];
2723 	ident = VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY);
2724 	error = vmcs_getreg(vmcs, running, ident, &gi);
2725 	if (error == 0) {
2726 		gi &= ~HWINTR_BLOCKING;
2727 		error = vmcs_setreg(vmcs, running, ident, gi);
2728 	}
2729 done:
2730 	VCPU_CTR2(vmx->vm, vcpu, "Setting intr_shadow to %#lx %s", val,
2731 	    error ? "failed" : "succeeded");
2732 	return (error);
2733 }
2734 
2735 static int
2736 vmx_shadow_reg(int reg)
2737 {
2738 	int shreg;
2739 
2740 	shreg = -1;
2741 
2742 	switch (reg) {
2743 	case VM_REG_GUEST_CR0:
2744 		shreg = VMCS_CR0_SHADOW;
2745                 break;
2746         case VM_REG_GUEST_CR4:
2747 		shreg = VMCS_CR4_SHADOW;
2748 		break;
2749 	default:
2750 		break;
2751 	}
2752 
2753 	return (shreg);
2754 }
2755 
2756 static int
2757 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
2758 {
2759 	int running, hostcpu;
2760 	struct vmx *vmx = arg;
2761 
2762 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2763 	if (running && hostcpu != curcpu)
2764 		panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
2765 
2766 	if (reg == VM_REG_GUEST_INTR_SHADOW)
2767 		return (vmx_get_intr_shadow(vmx, vcpu, running, retval));
2768 
2769 	if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
2770 		return (0);
2771 
2772 	return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
2773 }
2774 
2775 static int
2776 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
2777 {
2778 	int error, hostcpu, running, shadow;
2779 	uint64_t ctls;
2780 	pmap_t pmap;
2781 	struct vmx *vmx = arg;
2782 
2783 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2784 	if (running && hostcpu != curcpu)
2785 		panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
2786 
2787 	if (reg == VM_REG_GUEST_INTR_SHADOW)
2788 		return (vmx_modify_intr_shadow(vmx, vcpu, running, val));
2789 
2790 	if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
2791 		return (0);
2792 
2793 	error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
2794 
2795 	if (error == 0) {
2796 		/*
2797 		 * If the "load EFER" VM-entry control is 1 then the
2798 		 * value of EFER.LMA must be identical to "IA-32e mode guest"
2799 		 * bit in the VM-entry control.
2800 		 */
2801 		if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
2802 		    (reg == VM_REG_GUEST_EFER)) {
2803 			vmcs_getreg(&vmx->vmcs[vcpu], running,
2804 				    VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
2805 			if (val & EFER_LMA)
2806 				ctls |= VM_ENTRY_GUEST_LMA;
2807 			else
2808 				ctls &= ~VM_ENTRY_GUEST_LMA;
2809 			vmcs_setreg(&vmx->vmcs[vcpu], running,
2810 				    VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
2811 		}
2812 
2813 		shadow = vmx_shadow_reg(reg);
2814 		if (shadow > 0) {
2815 			/*
2816 			 * Store the unmodified value in the shadow
2817 			 */
2818 			error = vmcs_setreg(&vmx->vmcs[vcpu], running,
2819 				    VMCS_IDENT(shadow), val);
2820 		}
2821 
2822 		if (reg == VM_REG_GUEST_CR3) {
2823 			/*
2824 			 * Invalidate the guest vcpu's TLB mappings to emulate
2825 			 * the behavior of updating %cr3.
2826 			 *
2827 			 * XXX the processor retains global mappings when %cr3
2828 			 * is updated but vmx_invvpid() does not.
2829 			 */
2830 			pmap = vmx->ctx[vcpu].pmap;
2831 			vmx_invvpid(vmx, vcpu, pmap, running);
2832 		}
2833 	}
2834 
2835 	return (error);
2836 }
2837 
2838 static int
2839 vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2840 {
2841 	int hostcpu, running;
2842 	struct vmx *vmx = arg;
2843 
2844 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2845 	if (running && hostcpu != curcpu)
2846 		panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2847 
2848 	return (vmcs_getdesc(&vmx->vmcs[vcpu], running, reg, desc));
2849 }
2850 
2851 static int
2852 vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2853 {
2854 	int hostcpu, running;
2855 	struct vmx *vmx = arg;
2856 
2857 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2858 	if (running && hostcpu != curcpu)
2859 		panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2860 
2861 	return (vmcs_setdesc(&vmx->vmcs[vcpu], running, reg, desc));
2862 }
2863 
2864 static int
2865 vmx_getcap(void *arg, int vcpu, int type, int *retval)
2866 {
2867 	struct vmx *vmx = arg;
2868 	int vcap;
2869 	int ret;
2870 
2871 	ret = ENOENT;
2872 
2873 	vcap = vmx->cap[vcpu].set;
2874 
2875 	switch (type) {
2876 	case VM_CAP_HALT_EXIT:
2877 		if (cap_halt_exit)
2878 			ret = 0;
2879 		break;
2880 	case VM_CAP_PAUSE_EXIT:
2881 		if (cap_pause_exit)
2882 			ret = 0;
2883 		break;
2884 	case VM_CAP_MTRAP_EXIT:
2885 		if (cap_monitor_trap)
2886 			ret = 0;
2887 		break;
2888 	case VM_CAP_UNRESTRICTED_GUEST:
2889 		if (cap_unrestricted_guest)
2890 			ret = 0;
2891 		break;
2892 	case VM_CAP_ENABLE_INVPCID:
2893 		if (cap_invpcid)
2894 			ret = 0;
2895 		break;
2896 	default:
2897 		break;
2898 	}
2899 
2900 	if (ret == 0)
2901 		*retval = (vcap & (1 << type)) ? 1 : 0;
2902 
2903 	return (ret);
2904 }
2905 
2906 static int
2907 vmx_setcap(void *arg, int vcpu, int type, int val)
2908 {
2909 	struct vmx *vmx = arg;
2910 	struct vmcs *vmcs = &vmx->vmcs[vcpu];
2911 	uint32_t baseval;
2912 	uint32_t *pptr;
2913 	int error;
2914 	int flag;
2915 	int reg;
2916 	int retval;
2917 
2918 	retval = ENOENT;
2919 	pptr = NULL;
2920 
2921 	switch (type) {
2922 	case VM_CAP_HALT_EXIT:
2923 		if (cap_halt_exit) {
2924 			retval = 0;
2925 			pptr = &vmx->cap[vcpu].proc_ctls;
2926 			baseval = *pptr;
2927 			flag = PROCBASED_HLT_EXITING;
2928 			reg = VMCS_PRI_PROC_BASED_CTLS;
2929 		}
2930 		break;
2931 	case VM_CAP_MTRAP_EXIT:
2932 		if (cap_monitor_trap) {
2933 			retval = 0;
2934 			pptr = &vmx->cap[vcpu].proc_ctls;
2935 			baseval = *pptr;
2936 			flag = PROCBASED_MTF;
2937 			reg = VMCS_PRI_PROC_BASED_CTLS;
2938 		}
2939 		break;
2940 	case VM_CAP_PAUSE_EXIT:
2941 		if (cap_pause_exit) {
2942 			retval = 0;
2943 			pptr = &vmx->cap[vcpu].proc_ctls;
2944 			baseval = *pptr;
2945 			flag = PROCBASED_PAUSE_EXITING;
2946 			reg = VMCS_PRI_PROC_BASED_CTLS;
2947 		}
2948 		break;
2949 	case VM_CAP_UNRESTRICTED_GUEST:
2950 		if (cap_unrestricted_guest) {
2951 			retval = 0;
2952 			pptr = &vmx->cap[vcpu].proc_ctls2;
2953 			baseval = *pptr;
2954 			flag = PROCBASED2_UNRESTRICTED_GUEST;
2955 			reg = VMCS_SEC_PROC_BASED_CTLS;
2956 		}
2957 		break;
2958 	case VM_CAP_ENABLE_INVPCID:
2959 		if (cap_invpcid) {
2960 			retval = 0;
2961 			pptr = &vmx->cap[vcpu].proc_ctls2;
2962 			baseval = *pptr;
2963 			flag = PROCBASED2_ENABLE_INVPCID;
2964 			reg = VMCS_SEC_PROC_BASED_CTLS;
2965 		}
2966 		break;
2967 	default:
2968 		break;
2969 	}
2970 
2971 	if (retval == 0) {
2972 		if (val) {
2973 			baseval |= flag;
2974 		} else {
2975 			baseval &= ~flag;
2976 		}
2977 		VMPTRLD(vmcs);
2978 		error = vmwrite(reg, baseval);
2979 		VMCLEAR(vmcs);
2980 
2981 		if (error) {
2982 			retval = error;
2983 		} else {
2984 			/*
2985 			 * Update optional stored flags, and record
2986 			 * setting
2987 			 */
2988 			if (pptr != NULL) {
2989 				*pptr = baseval;
2990 			}
2991 
2992 			if (val) {
2993 				vmx->cap[vcpu].set |= (1 << type);
2994 			} else {
2995 				vmx->cap[vcpu].set &= ~(1 << type);
2996 			}
2997 		}
2998 	}
2999 
3000         return (retval);
3001 }
3002 
3003 struct vlapic_vtx {
3004 	struct vlapic	vlapic;
3005 	struct pir_desc	*pir_desc;
3006 	struct vmx	*vmx;
3007 };
3008 
3009 #define	VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg)	\
3010 do {									\
3011 	VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d",	\
3012 	    level ? "level" : "edge", vector);				\
3013 	VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]);	\
3014 	VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]);	\
3015 	VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]);	\
3016 	VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]);	\
3017 	VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
3018 } while (0)
3019 
3020 /*
3021  * vlapic->ops handlers that utilize the APICv hardware assist described in
3022  * Chapter 29 of the Intel SDM.
3023  */
3024 static int
3025 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3026 {
3027 	struct vlapic_vtx *vlapic_vtx;
3028 	struct pir_desc *pir_desc;
3029 	uint64_t mask;
3030 	int idx, notify;
3031 
3032 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3033 	pir_desc = vlapic_vtx->pir_desc;
3034 
3035 	/*
3036 	 * Keep track of interrupt requests in the PIR descriptor. This is
3037 	 * because the virtual APIC page pointed to by the VMCS cannot be
3038 	 * modified if the vcpu is running.
3039 	 */
3040 	idx = vector / 64;
3041 	mask = 1UL << (vector % 64);
3042 	atomic_set_long(&pir_desc->pir[idx], mask);
3043 	notify = atomic_cmpset_long(&pir_desc->pending, 0, 1);
3044 
3045 	VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
3046 	    level, "vmx_set_intr_ready");
3047 	return (notify);
3048 }
3049 
3050 static int
3051 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3052 {
3053 	struct vlapic_vtx *vlapic_vtx;
3054 	struct pir_desc *pir_desc;
3055 	struct LAPIC *lapic;
3056 	uint64_t pending, pirval;
3057 	uint32_t ppr, vpr;
3058 	int i;
3059 
3060 	/*
3061 	 * This function is only expected to be called from the 'HLT' exit
3062 	 * handler which does not care about the vector that is pending.
3063 	 */
3064 	KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3065 
3066 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3067 	pir_desc = vlapic_vtx->pir_desc;
3068 
3069 	pending = atomic_load_acq_long(&pir_desc->pending);
3070 	if (!pending)
3071 		return (0);	/* common case */
3072 
3073 	/*
3074 	 * If there is an interrupt pending then it will be recognized only
3075 	 * if its priority is greater than the processor priority.
3076 	 *
3077 	 * Special case: if the processor priority is zero then any pending
3078 	 * interrupt will be recognized.
3079 	 */
3080 	lapic = vlapic->apic_page;
3081 	ppr = lapic->ppr & 0xf0;
3082 	if (ppr == 0)
3083 		return (1);
3084 
3085 	VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
3086 	    lapic->ppr);
3087 
3088 	for (i = 3; i >= 0; i--) {
3089 		pirval = pir_desc->pir[i];
3090 		if (pirval != 0) {
3091 			vpr = (i * 64 + flsl(pirval) - 1) & 0xf0;
3092 			return (vpr > ppr);
3093 		}
3094 	}
3095 	return (0);
3096 }
3097 
3098 static void
3099 vmx_intr_accepted(struct vlapic *vlapic, int vector)
3100 {
3101 
3102 	panic("vmx_intr_accepted: not expected to be called");
3103 }
3104 
3105 static void
3106 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3107 {
3108 	struct vlapic_vtx *vlapic_vtx;
3109 	struct vmx *vmx;
3110 	struct vmcs *vmcs;
3111 	uint64_t mask, val;
3112 
3113 	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3114 	KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
3115 	    ("vmx_set_tmr: vcpu cannot be running"));
3116 
3117 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3118 	vmx = vlapic_vtx->vmx;
3119 	vmcs = &vmx->vmcs[vlapic->vcpuid];
3120 	mask = 1UL << (vector % 64);
3121 
3122 	VMPTRLD(vmcs);
3123 	val = vmcs_read(VMCS_EOI_EXIT(vector));
3124 	if (level)
3125 		val |= mask;
3126 	else
3127 		val &= ~mask;
3128 	vmcs_write(VMCS_EOI_EXIT(vector), val);
3129 	VMCLEAR(vmcs);
3130 }
3131 
3132 static void
3133 vmx_enable_x2apic_mode(struct vlapic *vlapic)
3134 {
3135 	struct vmx *vmx;
3136 	struct vmcs *vmcs;
3137 	uint32_t proc_ctls2;
3138 	int vcpuid, error;
3139 
3140 	vcpuid = vlapic->vcpuid;
3141 	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3142 	vmcs = &vmx->vmcs[vcpuid];
3143 
3144 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3145 	KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3146 	    ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3147 
3148 	proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3149 	proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3150 	vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3151 
3152 	VMPTRLD(vmcs);
3153 	vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3154 	VMCLEAR(vmcs);
3155 
3156 	if (vlapic->vcpuid == 0) {
3157 		/*
3158 		 * The nested page table mappings are shared by all vcpus
3159 		 * so unmap the APIC access page just once.
3160 		 */
3161 		error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3162 		KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3163 		    __func__, error));
3164 
3165 		/*
3166 		 * The MSR bitmap is shared by all vcpus so modify it only
3167 		 * once in the context of vcpu 0.
3168 		 */
3169 		error = vmx_allow_x2apic_msrs(vmx);
3170 		KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3171 		    __func__, error));
3172 	}
3173 }
3174 
3175 static void
3176 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3177 {
3178 
3179 	ipi_cpu(hostcpu, pirvec);
3180 }
3181 
3182 /*
3183  * Transfer the pending interrupts in the PIR descriptor to the IRR
3184  * in the virtual APIC page.
3185  */
3186 static void
3187 vmx_inject_pir(struct vlapic *vlapic)
3188 {
3189 	struct vlapic_vtx *vlapic_vtx;
3190 	struct pir_desc *pir_desc;
3191 	struct LAPIC *lapic;
3192 	uint64_t val, pirval;
3193 	int rvi, pirbase = -1;
3194 	uint16_t intr_status_old, intr_status_new;
3195 
3196 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3197 	pir_desc = vlapic_vtx->pir_desc;
3198 	if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3199 		VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3200 		    "no posted interrupt pending");
3201 		return;
3202 	}
3203 
3204 	pirval = 0;
3205 	pirbase = -1;
3206 	lapic = vlapic->apic_page;
3207 
3208 	val = atomic_readandclear_long(&pir_desc->pir[0]);
3209 	if (val != 0) {
3210 		lapic->irr0 |= val;
3211 		lapic->irr1 |= val >> 32;
3212 		pirbase = 0;
3213 		pirval = val;
3214 	}
3215 
3216 	val = atomic_readandclear_long(&pir_desc->pir[1]);
3217 	if (val != 0) {
3218 		lapic->irr2 |= val;
3219 		lapic->irr3 |= val >> 32;
3220 		pirbase = 64;
3221 		pirval = val;
3222 	}
3223 
3224 	val = atomic_readandclear_long(&pir_desc->pir[2]);
3225 	if (val != 0) {
3226 		lapic->irr4 |= val;
3227 		lapic->irr5 |= val >> 32;
3228 		pirbase = 128;
3229 		pirval = val;
3230 	}
3231 
3232 	val = atomic_readandclear_long(&pir_desc->pir[3]);
3233 	if (val != 0) {
3234 		lapic->irr6 |= val;
3235 		lapic->irr7 |= val >> 32;
3236 		pirbase = 192;
3237 		pirval = val;
3238 	}
3239 
3240 	VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
3241 
3242 	/*
3243 	 * Update RVI so the processor can evaluate pending virtual
3244 	 * interrupts on VM-entry.
3245 	 *
3246 	 * It is possible for pirval to be 0 here, even though the
3247 	 * pending bit has been set. The scenario is:
3248 	 * CPU-Y is sending a posted interrupt to CPU-X, which
3249 	 * is running a guest and processing posted interrupts in h/w.
3250 	 * CPU-X will eventually exit and the state seen in s/w is
3251 	 * the pending bit set, but no PIR bits set.
3252 	 *
3253 	 *      CPU-X                      CPU-Y
3254 	 *   (vm running)                (host running)
3255 	 *   rx posted interrupt
3256 	 *   CLEAR pending bit
3257 	 *				 SET PIR bit
3258 	 *   READ/CLEAR PIR bits
3259 	 *				 SET pending bit
3260 	 *   (vm exit)
3261 	 *   pending bit set, PIR 0
3262 	 */
3263 	if (pirval != 0) {
3264 		rvi = pirbase + flsl(pirval) - 1;
3265 		intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
3266 		intr_status_new = (intr_status_old & 0xFF00) | rvi;
3267 		if (intr_status_new > intr_status_old) {
3268 			vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
3269 			VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3270 			    "guest_intr_status changed from 0x%04x to 0x%04x",
3271 			    intr_status_old, intr_status_new);
3272 		}
3273 	}
3274 }
3275 
3276 static struct vlapic *
3277 vmx_vlapic_init(void *arg, int vcpuid)
3278 {
3279 	struct vmx *vmx;
3280 	struct vlapic *vlapic;
3281 	struct vlapic_vtx *vlapic_vtx;
3282 
3283 	vmx = arg;
3284 
3285 	vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
3286 	vlapic->vm = vmx->vm;
3287 	vlapic->vcpuid = vcpuid;
3288 	vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
3289 
3290 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3291 	vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
3292 	vlapic_vtx->vmx = vmx;
3293 
3294 	if (virtual_interrupt_delivery) {
3295 		vlapic->ops.set_intr_ready = vmx_set_intr_ready;
3296 		vlapic->ops.pending_intr = vmx_pending_intr;
3297 		vlapic->ops.intr_accepted = vmx_intr_accepted;
3298 		vlapic->ops.set_tmr = vmx_set_tmr;
3299 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode;
3300 	}
3301 
3302 	if (posted_interrupts)
3303 		vlapic->ops.post_intr = vmx_post_intr;
3304 
3305 	vlapic_init(vlapic);
3306 
3307 	return (vlapic);
3308 }
3309 
3310 static void
3311 vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
3312 {
3313 
3314 	vlapic_cleanup(vlapic);
3315 	free(vlapic, M_VLAPIC);
3316 }
3317 
3318 struct vmm_ops vmm_ops_intel = {
3319 	vmx_init,
3320 	vmx_cleanup,
3321 	vmx_restore,
3322 	vmx_vminit,
3323 	vmx_run,
3324 	vmx_vmcleanup,
3325 	vmx_getreg,
3326 	vmx_setreg,
3327 	vmx_getdesc,
3328 	vmx_setdesc,
3329 	vmx_getcap,
3330 	vmx_setcap,
3331 	ept_vmspace_alloc,
3332 	ept_vmspace_free,
3333 	vmx_vlapic_init,
3334 	vmx_vlapic_cleanup,
3335 };
3336