xref: /freebsd/sys/amd64/vmm/intel/vmx.c (revision a831d7d1c538b93ffec095657d9a6e6e778db195)
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_DURING_ENTRY:
287 		return "mce-during-entry";
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 	uint32_t exc_bitmap;
825 
826 	vmx = malloc(sizeof(struct vmx), M_VMX, M_WAITOK | M_ZERO);
827 	if ((uintptr_t)vmx & PAGE_MASK) {
828 		panic("malloc of struct vmx not aligned on %d byte boundary",
829 		      PAGE_SIZE);
830 	}
831 	vmx->vm = vm;
832 
833 	vmx->eptp = eptp(vtophys((vm_offset_t)pmap->pm_pml4));
834 
835 	/*
836 	 * Clean up EPTP-tagged guest physical and combined mappings
837 	 *
838 	 * VMX transitions are not required to invalidate any guest physical
839 	 * mappings. So, it may be possible for stale guest physical mappings
840 	 * to be present in the processor TLBs.
841 	 *
842 	 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
843 	 */
844 	ept_invalidate_mappings(vmx->eptp);
845 
846 	msr_bitmap_initialize(vmx->msr_bitmap);
847 
848 	/*
849 	 * It is safe to allow direct access to MSR_GSBASE and MSR_FSBASE.
850 	 * The guest FSBASE and GSBASE are saved and restored during
851 	 * vm-exit and vm-entry respectively. The host FSBASE and GSBASE are
852 	 * always restored from the vmcs host state area on vm-exit.
853 	 *
854 	 * The SYSENTER_CS/ESP/EIP MSRs are identical to FS/GSBASE in
855 	 * how they are saved/restored so can be directly accessed by the
856 	 * guest.
857 	 *
858 	 * MSR_EFER is saved and restored in the guest VMCS area on a
859 	 * VM exit and entry respectively. It is also restored from the
860 	 * host VMCS area on a VM exit.
861 	 *
862 	 * MSR_PAT is saved and restored in the guest VMCS are on a VM exit
863 	 * and entry respectively. It is also restored from the host VMCS
864 	 * area on a VM exit.
865 	 *
866 	 * The TSC MSR is exposed read-only. Writes are disallowed as that
867 	 * will impact the host TSC.
868 	 * XXX Writes would be implemented with a wrmsr trap, and
869 	 * then modifying the TSC offset in the VMCS.
870 	 */
871 	if (guest_msr_rw(vmx, MSR_GSBASE) ||
872 	    guest_msr_rw(vmx, MSR_FSBASE) ||
873 	    guest_msr_rw(vmx, MSR_SYSENTER_CS_MSR) ||
874 	    guest_msr_rw(vmx, MSR_SYSENTER_ESP_MSR) ||
875 	    guest_msr_rw(vmx, MSR_SYSENTER_EIP_MSR) ||
876 	    guest_msr_rw(vmx, MSR_EFER) ||
877 	    guest_msr_rw(vmx, MSR_PAT) ||
878 	    guest_msr_ro(vmx, MSR_TSC))
879 		panic("vmx_vminit: error setting guest msr access");
880 
881 	vpid_alloc(vpid, VM_MAXCPU);
882 
883 	if (virtual_interrupt_delivery) {
884 		error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
885 		    APIC_ACCESS_ADDRESS);
886 		/* XXX this should really return an error to the caller */
887 		KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
888 	}
889 
890 	for (i = 0; i < VM_MAXCPU; i++) {
891 		vmcs = &vmx->vmcs[i];
892 		vmcs->identifier = vmx_revision();
893 		error = vmclear(vmcs);
894 		if (error != 0) {
895 			panic("vmx_vminit: vmclear error %d on vcpu %d\n",
896 			      error, i);
897 		}
898 
899 		vmx_msr_guest_init(vmx, i);
900 
901 		error = vmcs_init(vmcs);
902 		KASSERT(error == 0, ("vmcs_init error %d", error));
903 
904 		VMPTRLD(vmcs);
905 		error = 0;
906 		error += vmwrite(VMCS_HOST_RSP, (u_long)&vmx->ctx[i]);
907 		error += vmwrite(VMCS_EPTP, vmx->eptp);
908 		error += vmwrite(VMCS_PIN_BASED_CTLS, pinbased_ctls);
909 		error += vmwrite(VMCS_PRI_PROC_BASED_CTLS, procbased_ctls);
910 		error += vmwrite(VMCS_SEC_PROC_BASED_CTLS, procbased_ctls2);
911 		error += vmwrite(VMCS_EXIT_CTLS, exit_ctls);
912 		error += vmwrite(VMCS_ENTRY_CTLS, entry_ctls);
913 		error += vmwrite(VMCS_MSR_BITMAP, vtophys(vmx->msr_bitmap));
914 		error += vmwrite(VMCS_VPID, vpid[i]);
915 
916 		/* exception bitmap */
917 		if (vcpu_trace_exceptions(vm, i))
918 			exc_bitmap = 0xffffffff;
919 		else
920 			exc_bitmap = 1 << IDT_MC;
921 		error += vmwrite(VMCS_EXCEPTION_BITMAP, exc_bitmap);
922 
923 		if (virtual_interrupt_delivery) {
924 			error += vmwrite(VMCS_APIC_ACCESS, APIC_ACCESS_ADDRESS);
925 			error += vmwrite(VMCS_VIRTUAL_APIC,
926 			    vtophys(&vmx->apic_page[i]));
927 			error += vmwrite(VMCS_EOI_EXIT0, 0);
928 			error += vmwrite(VMCS_EOI_EXIT1, 0);
929 			error += vmwrite(VMCS_EOI_EXIT2, 0);
930 			error += vmwrite(VMCS_EOI_EXIT3, 0);
931 		}
932 		if (posted_interrupts) {
933 			error += vmwrite(VMCS_PIR_VECTOR, pirvec);
934 			error += vmwrite(VMCS_PIR_DESC,
935 			    vtophys(&vmx->pir_desc[i]));
936 		}
937 		VMCLEAR(vmcs);
938 		KASSERT(error == 0, ("vmx_vminit: error customizing the vmcs"));
939 
940 		vmx->cap[i].set = 0;
941 		vmx->cap[i].proc_ctls = procbased_ctls;
942 		vmx->cap[i].proc_ctls2 = procbased_ctls2;
943 
944 		vmx->state[i].nextrip = ~0;
945 		vmx->state[i].lastcpu = NOCPU;
946 		vmx->state[i].vpid = vpid[i];
947 
948 		/*
949 		 * Set up the CR0/4 shadows, and init the read shadow
950 		 * to the power-on register value from the Intel Sys Arch.
951 		 *  CR0 - 0x60000010
952 		 *  CR4 - 0
953 		 */
954 		error = vmx_setup_cr0_shadow(vmcs, 0x60000010);
955 		if (error != 0)
956 			panic("vmx_setup_cr0_shadow %d", error);
957 
958 		error = vmx_setup_cr4_shadow(vmcs, 0);
959 		if (error != 0)
960 			panic("vmx_setup_cr4_shadow %d", error);
961 
962 		vmx->ctx[i].pmap = pmap;
963 	}
964 
965 	return (vmx);
966 }
967 
968 static int
969 vmx_handle_cpuid(struct vm *vm, int vcpu, struct vmxctx *vmxctx)
970 {
971 	int handled, func;
972 
973 	func = vmxctx->guest_rax;
974 
975 	handled = x86_emulate_cpuid(vm, vcpu,
976 				    (uint32_t*)(&vmxctx->guest_rax),
977 				    (uint32_t*)(&vmxctx->guest_rbx),
978 				    (uint32_t*)(&vmxctx->guest_rcx),
979 				    (uint32_t*)(&vmxctx->guest_rdx));
980 	return (handled);
981 }
982 
983 static __inline void
984 vmx_run_trace(struct vmx *vmx, int vcpu)
985 {
986 #ifdef KTR
987 	VCPU_CTR1(vmx->vm, vcpu, "Resume execution at %#lx", vmcs_guest_rip());
988 #endif
989 }
990 
991 static __inline void
992 vmx_exit_trace(struct vmx *vmx, int vcpu, uint64_t rip, uint32_t exit_reason,
993 	       int handled)
994 {
995 #ifdef KTR
996 	VCPU_CTR3(vmx->vm, vcpu, "%s %s vmexit at 0x%0lx",
997 		 handled ? "handled" : "unhandled",
998 		 exit_reason_to_str(exit_reason), rip);
999 #endif
1000 }
1001 
1002 static __inline void
1003 vmx_astpending_trace(struct vmx *vmx, int vcpu, uint64_t rip)
1004 {
1005 #ifdef KTR
1006 	VCPU_CTR1(vmx->vm, vcpu, "astpending vmexit at 0x%0lx", rip);
1007 #endif
1008 }
1009 
1010 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
1011 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
1012 
1013 /*
1014  * Invalidate guest mappings identified by its vpid from the TLB.
1015  */
1016 static __inline void
1017 vmx_invvpid(struct vmx *vmx, int vcpu, pmap_t pmap, int running)
1018 {
1019 	struct vmxstate *vmxstate;
1020 	struct invvpid_desc invvpid_desc;
1021 
1022 	vmxstate = &vmx->state[vcpu];
1023 	if (vmxstate->vpid == 0)
1024 		return;
1025 
1026 	if (!running) {
1027 		/*
1028 		 * Set the 'lastcpu' to an invalid host cpu.
1029 		 *
1030 		 * This will invalidate TLB entries tagged with the vcpu's
1031 		 * vpid the next time it runs via vmx_set_pcpu_defaults().
1032 		 */
1033 		vmxstate->lastcpu = NOCPU;
1034 		return;
1035 	}
1036 
1037 	KASSERT(curthread->td_critnest > 0, ("%s: vcpu %d running outside "
1038 	    "critical section", __func__, vcpu));
1039 
1040 	/*
1041 	 * Invalidate all mappings tagged with 'vpid'
1042 	 *
1043 	 * We do this because this vcpu was executing on a different host
1044 	 * cpu when it last ran. We do not track whether it invalidated
1045 	 * mappings associated with its 'vpid' during that run. So we must
1046 	 * assume that the mappings associated with 'vpid' on 'curcpu' are
1047 	 * stale and invalidate them.
1048 	 *
1049 	 * Note that we incur this penalty only when the scheduler chooses to
1050 	 * move the thread associated with this vcpu between host cpus.
1051 	 *
1052 	 * Note also that this will invalidate mappings tagged with 'vpid'
1053 	 * for "all" EP4TAs.
1054 	 */
1055 	if (pmap->pm_eptgen == vmx->eptgen[curcpu]) {
1056 		invvpid_desc._res1 = 0;
1057 		invvpid_desc._res2 = 0;
1058 		invvpid_desc.vpid = vmxstate->vpid;
1059 		invvpid_desc.linear_addr = 0;
1060 		invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
1061 		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_DONE, 1);
1062 	} else {
1063 		/*
1064 		 * The invvpid can be skipped if an invept is going to
1065 		 * be performed before entering the guest. The invept
1066 		 * will invalidate combined mappings tagged with
1067 		 * 'vmx->eptp' for all vpids.
1068 		 */
1069 		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
1070 	}
1071 }
1072 
1073 static void
1074 vmx_set_pcpu_defaults(struct vmx *vmx, int vcpu, pmap_t pmap)
1075 {
1076 	struct vmxstate *vmxstate;
1077 
1078 	vmxstate = &vmx->state[vcpu];
1079 	if (vmxstate->lastcpu == curcpu)
1080 		return;
1081 
1082 	vmxstate->lastcpu = curcpu;
1083 
1084 	vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
1085 
1086 	vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1087 	vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1088 	vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1089 	vmx_invvpid(vmx, vcpu, pmap, 1);
1090 }
1091 
1092 /*
1093  * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1094  */
1095 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1096 
1097 static void __inline
1098 vmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
1099 {
1100 
1101 	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1102 		vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1103 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1104 		VCPU_CTR0(vmx->vm, vcpu, "Enabling interrupt window exiting");
1105 	}
1106 }
1107 
1108 static void __inline
1109 vmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
1110 {
1111 
1112 	KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1113 	    ("intr_window_exiting not set: %#x", vmx->cap[vcpu].proc_ctls));
1114 	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1115 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1116 	VCPU_CTR0(vmx->vm, vcpu, "Disabling interrupt window exiting");
1117 }
1118 
1119 static void __inline
1120 vmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
1121 {
1122 
1123 	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) == 0) {
1124 		vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1125 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1126 		VCPU_CTR0(vmx->vm, vcpu, "Enabling NMI window exiting");
1127 	}
1128 }
1129 
1130 static void __inline
1131 vmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
1132 {
1133 
1134 	KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0,
1135 	    ("nmi_window_exiting not set %#x", vmx->cap[vcpu].proc_ctls));
1136 	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1137 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1138 	VCPU_CTR0(vmx->vm, vcpu, "Disabling NMI window exiting");
1139 }
1140 
1141 #define	NMI_BLOCKING	(VMCS_INTERRUPTIBILITY_NMI_BLOCKING |		\
1142 			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1143 #define	HWINTR_BLOCKING	(VMCS_INTERRUPTIBILITY_STI_BLOCKING |		\
1144 			 VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1145 
1146 static void
1147 vmx_inject_nmi(struct vmx *vmx, int vcpu)
1148 {
1149 	uint32_t gi, info;
1150 
1151 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1152 	KASSERT((gi & NMI_BLOCKING) == 0, ("vmx_inject_nmi: invalid guest "
1153 	    "interruptibility-state %#x", gi));
1154 
1155 	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1156 	KASSERT((info & VMCS_INTR_VALID) == 0, ("vmx_inject_nmi: invalid "
1157 	    "VM-entry interruption information %#x", info));
1158 
1159 	/*
1160 	 * Inject the virtual NMI. The vector must be the NMI IDT entry
1161 	 * or the VMCS entry check will fail.
1162 	 */
1163 	info = IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID;
1164 	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1165 
1166 	VCPU_CTR0(vmx->vm, vcpu, "Injecting vNMI");
1167 
1168 	/* Clear the request */
1169 	vm_nmi_clear(vmx->vm, vcpu);
1170 }
1171 
1172 static void
1173 vmx_inject_interrupts(struct vmx *vmx, int vcpu, struct vlapic *vlapic,
1174     uint64_t guestrip)
1175 {
1176 	int vector, need_nmi_exiting, extint_pending;
1177 	uint64_t rflags, entryinfo;
1178 	uint32_t gi, info;
1179 
1180 	if (vmx->state[vcpu].nextrip != guestrip) {
1181 		gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1182 		if (gi & HWINTR_BLOCKING) {
1183 			VCPU_CTR2(vmx->vm, vcpu, "Guest interrupt blocking "
1184 			    "cleared due to rip change: %#lx/%#lx",
1185 			    vmx->state[vcpu].nextrip, guestrip);
1186 			gi &= ~HWINTR_BLOCKING;
1187 			vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1188 		}
1189 	}
1190 
1191 	if (vm_entry_intinfo(vmx->vm, vcpu, &entryinfo)) {
1192 		KASSERT((entryinfo & VMCS_INTR_VALID) != 0, ("%s: entry "
1193 		    "intinfo is not valid: %#lx", __func__, entryinfo));
1194 
1195 		info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1196 		KASSERT((info & VMCS_INTR_VALID) == 0, ("%s: cannot inject "
1197 		     "pending exception: %#lx/%#x", __func__, entryinfo, info));
1198 
1199 		info = entryinfo;
1200 		vector = info & 0xff;
1201 		if (vector == IDT_BP || vector == IDT_OF) {
1202 			/*
1203 			 * VT-x requires #BP and #OF to be injected as software
1204 			 * exceptions.
1205 			 */
1206 			info &= ~VMCS_INTR_T_MASK;
1207 			info |= VMCS_INTR_T_SWEXCEPTION;
1208 		}
1209 
1210 		if (info & VMCS_INTR_DEL_ERRCODE)
1211 			vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR, entryinfo >> 32);
1212 
1213 		vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1214 	}
1215 
1216 	if (vm_nmi_pending(vmx->vm, vcpu)) {
1217 		/*
1218 		 * If there are no conditions blocking NMI injection then
1219 		 * inject it directly here otherwise enable "NMI window
1220 		 * exiting" to inject it as soon as we can.
1221 		 *
1222 		 * We also check for STI_BLOCKING because some implementations
1223 		 * don't allow NMI injection in this case. If we are running
1224 		 * on a processor that doesn't have this restriction it will
1225 		 * immediately exit and the NMI will be injected in the
1226 		 * "NMI window exiting" handler.
1227 		 */
1228 		need_nmi_exiting = 1;
1229 		gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1230 		if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1231 			info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1232 			if ((info & VMCS_INTR_VALID) == 0) {
1233 				vmx_inject_nmi(vmx, vcpu);
1234 				need_nmi_exiting = 0;
1235 			} else {
1236 				VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI "
1237 				    "due to VM-entry intr info %#x", info);
1238 			}
1239 		} else {
1240 			VCPU_CTR1(vmx->vm, vcpu, "Cannot inject NMI due to "
1241 			    "Guest Interruptibility-state %#x", gi);
1242 		}
1243 
1244 		if (need_nmi_exiting)
1245 			vmx_set_nmi_window_exiting(vmx, vcpu);
1246 	}
1247 
1248 	extint_pending = vm_extint_pending(vmx->vm, vcpu);
1249 
1250 	if (!extint_pending && virtual_interrupt_delivery) {
1251 		vmx_inject_pir(vlapic);
1252 		return;
1253 	}
1254 
1255 	/*
1256 	 * If interrupt-window exiting is already in effect then don't bother
1257 	 * checking for pending interrupts. This is just an optimization and
1258 	 * not needed for correctness.
1259 	 */
1260 	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0) {
1261 		VCPU_CTR0(vmx->vm, vcpu, "Skip interrupt injection due to "
1262 		    "pending int_window_exiting");
1263 		return;
1264 	}
1265 
1266 	if (!extint_pending) {
1267 		/* Ask the local apic for a vector to inject */
1268 		if (!vlapic_pending_intr(vlapic, &vector))
1269 			return;
1270 
1271 		/*
1272 		 * From the Intel SDM, Volume 3, Section "Maskable
1273 		 * Hardware Interrupts":
1274 		 * - maskable interrupt vectors [16,255] can be delivered
1275 		 *   through the local APIC.
1276 		*/
1277 		KASSERT(vector >= 16 && vector <= 255,
1278 		    ("invalid vector %d from local APIC", vector));
1279 	} else {
1280 		/* Ask the legacy pic for a vector to inject */
1281 		vatpic_pending_intr(vmx->vm, &vector);
1282 
1283 		/*
1284 		 * From the Intel SDM, Volume 3, Section "Maskable
1285 		 * Hardware Interrupts":
1286 		 * - maskable interrupt vectors [0,255] can be delivered
1287 		 *   through the INTR pin.
1288 		 */
1289 		KASSERT(vector >= 0 && vector <= 255,
1290 		    ("invalid vector %d from INTR", vector));
1291 	}
1292 
1293 	/* Check RFLAGS.IF and the interruptibility state of the guest */
1294 	rflags = vmcs_read(VMCS_GUEST_RFLAGS);
1295 	if ((rflags & PSL_I) == 0) {
1296 		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1297 		    "rflags %#lx", vector, rflags);
1298 		goto cantinject;
1299 	}
1300 
1301 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1302 	if (gi & HWINTR_BLOCKING) {
1303 		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1304 		    "Guest Interruptibility-state %#x", vector, gi);
1305 		goto cantinject;
1306 	}
1307 
1308 	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1309 	if (info & VMCS_INTR_VALID) {
1310 		/*
1311 		 * This is expected and could happen for multiple reasons:
1312 		 * - A vectoring VM-entry was aborted due to astpending
1313 		 * - A VM-exit happened during event injection.
1314 		 * - An exception was injected above.
1315 		 * - An NMI was injected above or after "NMI window exiting"
1316 		 */
1317 		VCPU_CTR2(vmx->vm, vcpu, "Cannot inject vector %d due to "
1318 		    "VM-entry intr info %#x", vector, info);
1319 		goto cantinject;
1320 	}
1321 
1322 	/* Inject the interrupt */
1323 	info = VMCS_INTR_T_HWINTR | VMCS_INTR_VALID;
1324 	info |= vector;
1325 	vmcs_write(VMCS_ENTRY_INTR_INFO, info);
1326 
1327 	if (!extint_pending) {
1328 		/* Update the Local APIC ISR */
1329 		vlapic_intr_accepted(vlapic, vector);
1330 	} else {
1331 		vm_extint_clear(vmx->vm, vcpu);
1332 		vatpic_intr_accepted(vmx->vm, vector);
1333 
1334 		/*
1335 		 * After we accepted the current ExtINT the PIC may
1336 		 * have posted another one.  If that is the case, set
1337 		 * the Interrupt Window Exiting execution control so
1338 		 * we can inject that one too.
1339 		 *
1340 		 * Also, interrupt window exiting allows us to inject any
1341 		 * pending APIC vector that was preempted by the ExtINT
1342 		 * as soon as possible. This applies both for the software
1343 		 * emulated vlapic and the hardware assisted virtual APIC.
1344 		 */
1345 		vmx_set_int_window_exiting(vmx, vcpu);
1346 	}
1347 
1348 	VCPU_CTR1(vmx->vm, vcpu, "Injecting hwintr at vector %d", vector);
1349 
1350 	return;
1351 
1352 cantinject:
1353 	/*
1354 	 * Set the Interrupt Window Exiting execution control so we can inject
1355 	 * the interrupt as soon as blocking condition goes away.
1356 	 */
1357 	vmx_set_int_window_exiting(vmx, vcpu);
1358 }
1359 
1360 /*
1361  * If the Virtual NMIs execution control is '1' then the logical processor
1362  * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1363  * the VMCS. An IRET instruction in VMX non-root operation will remove any
1364  * virtual-NMI blocking.
1365  *
1366  * This unblocking occurs even if the IRET causes a fault. In this case the
1367  * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1368  */
1369 static void
1370 vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1371 {
1372 	uint32_t gi;
1373 
1374 	VCPU_CTR0(vmx->vm, vcpuid, "Restore Virtual-NMI blocking");
1375 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1376 	gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1377 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1378 }
1379 
1380 static void
1381 vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1382 {
1383 	uint32_t gi;
1384 
1385 	VCPU_CTR0(vmx->vm, vcpuid, "Clear Virtual-NMI blocking");
1386 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1387 	gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1388 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1389 }
1390 
1391 static void
1392 vmx_assert_nmi_blocking(struct vmx *vmx, int vcpuid)
1393 {
1394 	uint32_t gi;
1395 
1396 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1397 	KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1398 	    ("NMI blocking is not in effect %#x", gi));
1399 }
1400 
1401 static int
1402 vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1403 {
1404 	struct vmxctx *vmxctx;
1405 	uint64_t xcrval;
1406 	const struct xsave_limits *limits;
1407 
1408 	vmxctx = &vmx->ctx[vcpu];
1409 	limits = vmm_get_xsave_limits();
1410 
1411 	/*
1412 	 * Note that the processor raises a GP# fault on its own if
1413 	 * xsetbv is executed for CPL != 0, so we do not have to
1414 	 * emulate that fault here.
1415 	 */
1416 
1417 	/* Only xcr0 is supported. */
1418 	if (vmxctx->guest_rcx != 0) {
1419 		vm_inject_gp(vmx->vm, vcpu);
1420 		return (HANDLED);
1421 	}
1422 
1423 	/* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1424 	if (!limits->xsave_enabled || !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1425 		vm_inject_ud(vmx->vm, vcpu);
1426 		return (HANDLED);
1427 	}
1428 
1429 	xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1430 	if ((xcrval & ~limits->xcr0_allowed) != 0) {
1431 		vm_inject_gp(vmx->vm, vcpu);
1432 		return (HANDLED);
1433 	}
1434 
1435 	if (!(xcrval & XFEATURE_ENABLED_X87)) {
1436 		vm_inject_gp(vmx->vm, vcpu);
1437 		return (HANDLED);
1438 	}
1439 
1440 	/* AVX (YMM_Hi128) requires SSE. */
1441 	if (xcrval & XFEATURE_ENABLED_AVX &&
1442 	    (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1443 		vm_inject_gp(vmx->vm, vcpu);
1444 		return (HANDLED);
1445 	}
1446 
1447 	/*
1448 	 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1449 	 * ZMM_Hi256, and Hi16_ZMM.
1450 	 */
1451 	if (xcrval & XFEATURE_AVX512 &&
1452 	    (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1453 	    (XFEATURE_AVX512 | XFEATURE_AVX)) {
1454 		vm_inject_gp(vmx->vm, vcpu);
1455 		return (HANDLED);
1456 	}
1457 
1458 	/*
1459 	 * Intel MPX requires both bound register state flags to be
1460 	 * set.
1461 	 */
1462 	if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1463 	    ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1464 		vm_inject_gp(vmx->vm, vcpu);
1465 		return (HANDLED);
1466 	}
1467 
1468 	/*
1469 	 * This runs "inside" vmrun() with the guest's FPU state, so
1470 	 * modifying xcr0 directly modifies the guest's xcr0, not the
1471 	 * host's.
1472 	 */
1473 	load_xcr(0, xcrval);
1474 	return (HANDLED);
1475 }
1476 
1477 static uint64_t
1478 vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1479 {
1480 	const struct vmxctx *vmxctx;
1481 
1482 	vmxctx = &vmx->ctx[vcpu];
1483 
1484 	switch (ident) {
1485 	case 0:
1486 		return (vmxctx->guest_rax);
1487 	case 1:
1488 		return (vmxctx->guest_rcx);
1489 	case 2:
1490 		return (vmxctx->guest_rdx);
1491 	case 3:
1492 		return (vmxctx->guest_rbx);
1493 	case 4:
1494 		return (vmcs_read(VMCS_GUEST_RSP));
1495 	case 5:
1496 		return (vmxctx->guest_rbp);
1497 	case 6:
1498 		return (vmxctx->guest_rsi);
1499 	case 7:
1500 		return (vmxctx->guest_rdi);
1501 	case 8:
1502 		return (vmxctx->guest_r8);
1503 	case 9:
1504 		return (vmxctx->guest_r9);
1505 	case 10:
1506 		return (vmxctx->guest_r10);
1507 	case 11:
1508 		return (vmxctx->guest_r11);
1509 	case 12:
1510 		return (vmxctx->guest_r12);
1511 	case 13:
1512 		return (vmxctx->guest_r13);
1513 	case 14:
1514 		return (vmxctx->guest_r14);
1515 	case 15:
1516 		return (vmxctx->guest_r15);
1517 	default:
1518 		panic("invalid vmx register %d", ident);
1519 	}
1520 }
1521 
1522 static void
1523 vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1524 {
1525 	struct vmxctx *vmxctx;
1526 
1527 	vmxctx = &vmx->ctx[vcpu];
1528 
1529 	switch (ident) {
1530 	case 0:
1531 		vmxctx->guest_rax = regval;
1532 		break;
1533 	case 1:
1534 		vmxctx->guest_rcx = regval;
1535 		break;
1536 	case 2:
1537 		vmxctx->guest_rdx = regval;
1538 		break;
1539 	case 3:
1540 		vmxctx->guest_rbx = regval;
1541 		break;
1542 	case 4:
1543 		vmcs_write(VMCS_GUEST_RSP, regval);
1544 		break;
1545 	case 5:
1546 		vmxctx->guest_rbp = regval;
1547 		break;
1548 	case 6:
1549 		vmxctx->guest_rsi = regval;
1550 		break;
1551 	case 7:
1552 		vmxctx->guest_rdi = regval;
1553 		break;
1554 	case 8:
1555 		vmxctx->guest_r8 = regval;
1556 		break;
1557 	case 9:
1558 		vmxctx->guest_r9 = regval;
1559 		break;
1560 	case 10:
1561 		vmxctx->guest_r10 = regval;
1562 		break;
1563 	case 11:
1564 		vmxctx->guest_r11 = regval;
1565 		break;
1566 	case 12:
1567 		vmxctx->guest_r12 = regval;
1568 		break;
1569 	case 13:
1570 		vmxctx->guest_r13 = regval;
1571 		break;
1572 	case 14:
1573 		vmxctx->guest_r14 = regval;
1574 		break;
1575 	case 15:
1576 		vmxctx->guest_r15 = regval;
1577 		break;
1578 	default:
1579 		panic("invalid vmx register %d", ident);
1580 	}
1581 }
1582 
1583 static int
1584 vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1585 {
1586 	uint64_t crval, regval;
1587 
1588 	/* We only handle mov to %cr0 at this time */
1589 	if ((exitqual & 0xf0) != 0x00)
1590 		return (UNHANDLED);
1591 
1592 	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1593 
1594 	vmcs_write(VMCS_CR0_SHADOW, regval);
1595 
1596 	crval = regval | cr0_ones_mask;
1597 	crval &= ~cr0_zeros_mask;
1598 	vmcs_write(VMCS_GUEST_CR0, crval);
1599 
1600 	if (regval & CR0_PG) {
1601 		uint64_t efer, entry_ctls;
1602 
1603 		/*
1604 		 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1605 		 * the "IA-32e mode guest" bit in VM-entry control must be
1606 		 * equal.
1607 		 */
1608 		efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1609 		if (efer & EFER_LME) {
1610 			efer |= EFER_LMA;
1611 			vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1612 			entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1613 			entry_ctls |= VM_ENTRY_GUEST_LMA;
1614 			vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1615 		}
1616 	}
1617 
1618 	return (HANDLED);
1619 }
1620 
1621 static int
1622 vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1623 {
1624 	uint64_t crval, regval;
1625 
1626 	/* We only handle mov to %cr4 at this time */
1627 	if ((exitqual & 0xf0) != 0x00)
1628 		return (UNHANDLED);
1629 
1630 	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1631 
1632 	vmcs_write(VMCS_CR4_SHADOW, regval);
1633 
1634 	crval = regval | cr4_ones_mask;
1635 	crval &= ~cr4_zeros_mask;
1636 	vmcs_write(VMCS_GUEST_CR4, crval);
1637 
1638 	return (HANDLED);
1639 }
1640 
1641 static int
1642 vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1643 {
1644 	struct vlapic *vlapic;
1645 	uint64_t cr8;
1646 	int regnum;
1647 
1648 	/* We only handle mov %cr8 to/from a register at this time. */
1649 	if ((exitqual & 0xe0) != 0x00) {
1650 		return (UNHANDLED);
1651 	}
1652 
1653 	vlapic = vm_lapic(vmx->vm, vcpu);
1654 	regnum = (exitqual >> 8) & 0xf;
1655 	if (exitqual & 0x10) {
1656 		cr8 = vlapic_get_cr8(vlapic);
1657 		vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1658 	} else {
1659 		cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1660 		vlapic_set_cr8(vlapic, cr8);
1661 	}
1662 
1663 	return (HANDLED);
1664 }
1665 
1666 /*
1667  * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1668  */
1669 static int
1670 vmx_cpl(void)
1671 {
1672 	uint32_t ssar;
1673 
1674 	ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1675 	return ((ssar >> 5) & 0x3);
1676 }
1677 
1678 static enum vm_cpu_mode
1679 vmx_cpu_mode(void)
1680 {
1681 	uint32_t csar;
1682 
1683 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1684 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1685 		if (csar & 0x2000)
1686 			return (CPU_MODE_64BIT);	/* CS.L = 1 */
1687 		else
1688 			return (CPU_MODE_COMPATIBILITY);
1689 	} else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1690 		return (CPU_MODE_PROTECTED);
1691 	} else {
1692 		return (CPU_MODE_REAL);
1693 	}
1694 }
1695 
1696 static enum vm_paging_mode
1697 vmx_paging_mode(void)
1698 {
1699 
1700 	if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1701 		return (PAGING_MODE_FLAT);
1702 	if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1703 		return (PAGING_MODE_32);
1704 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1705 		return (PAGING_MODE_64);
1706 	else
1707 		return (PAGING_MODE_PAE);
1708 }
1709 
1710 static uint64_t
1711 inout_str_index(struct vmx *vmx, int vcpuid, int in)
1712 {
1713 	uint64_t val;
1714 	int error;
1715 	enum vm_reg_name reg;
1716 
1717 	reg = in ? VM_REG_GUEST_RDI : VM_REG_GUEST_RSI;
1718 	error = vmx_getreg(vmx, vcpuid, reg, &val);
1719 	KASSERT(error == 0, ("%s: vmx_getreg error %d", __func__, error));
1720 	return (val);
1721 }
1722 
1723 static uint64_t
1724 inout_str_count(struct vmx *vmx, int vcpuid, int rep)
1725 {
1726 	uint64_t val;
1727 	int error;
1728 
1729 	if (rep) {
1730 		error = vmx_getreg(vmx, vcpuid, VM_REG_GUEST_RCX, &val);
1731 		KASSERT(!error, ("%s: vmx_getreg error %d", __func__, error));
1732 	} else {
1733 		val = 1;
1734 	}
1735 	return (val);
1736 }
1737 
1738 static int
1739 inout_str_addrsize(uint32_t inst_info)
1740 {
1741 	uint32_t size;
1742 
1743 	size = (inst_info >> 7) & 0x7;
1744 	switch (size) {
1745 	case 0:
1746 		return (2);	/* 16 bit */
1747 	case 1:
1748 		return (4);	/* 32 bit */
1749 	case 2:
1750 		return (8);	/* 64 bit */
1751 	default:
1752 		panic("%s: invalid size encoding %d", __func__, size);
1753 	}
1754 }
1755 
1756 static void
1757 inout_str_seginfo(struct vmx *vmx, int vcpuid, uint32_t inst_info, int in,
1758     struct vm_inout_str *vis)
1759 {
1760 	int error, s;
1761 
1762 	if (in) {
1763 		vis->seg_name = VM_REG_GUEST_ES;
1764 	} else {
1765 		s = (inst_info >> 15) & 0x7;
1766 		vis->seg_name = vm_segment_name(s);
1767 	}
1768 
1769 	error = vmx_getdesc(vmx, vcpuid, vis->seg_name, &vis->seg_desc);
1770 	KASSERT(error == 0, ("%s: vmx_getdesc error %d", __func__, error));
1771 }
1772 
1773 static void
1774 vmx_paging_info(struct vm_guest_paging *paging)
1775 {
1776 	paging->cr3 = vmcs_guest_cr3();
1777 	paging->cpl = vmx_cpl();
1778 	paging->cpu_mode = vmx_cpu_mode();
1779 	paging->paging_mode = vmx_paging_mode();
1780 }
1781 
1782 static void
1783 vmexit_inst_emul(struct vm_exit *vmexit, uint64_t gpa, uint64_t gla)
1784 {
1785 	struct vm_guest_paging *paging;
1786 	uint32_t csar;
1787 
1788 	paging = &vmexit->u.inst_emul.paging;
1789 
1790 	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
1791 	vmexit->u.inst_emul.gpa = gpa;
1792 	vmexit->u.inst_emul.gla = gla;
1793 	vmx_paging_info(paging);
1794 	switch (paging->cpu_mode) {
1795 	case CPU_MODE_PROTECTED:
1796 	case CPU_MODE_COMPATIBILITY:
1797 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1798 		vmexit->u.inst_emul.cs_d = SEG_DESC_DEF32(csar);
1799 		break;
1800 	default:
1801 		vmexit->u.inst_emul.cs_d = 0;
1802 		break;
1803 	}
1804 	vie_init(&vmexit->u.inst_emul.vie, NULL, 0);
1805 }
1806 
1807 static int
1808 ept_fault_type(uint64_t ept_qual)
1809 {
1810 	int fault_type;
1811 
1812 	if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1813 		fault_type = VM_PROT_WRITE;
1814 	else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1815 		fault_type = VM_PROT_EXECUTE;
1816 	else
1817 		fault_type= VM_PROT_READ;
1818 
1819 	return (fault_type);
1820 }
1821 
1822 static boolean_t
1823 ept_emulation_fault(uint64_t ept_qual)
1824 {
1825 	int read, write;
1826 
1827 	/* EPT fault on an instruction fetch doesn't make sense here */
1828 	if (ept_qual & EPT_VIOLATION_INST_FETCH)
1829 		return (FALSE);
1830 
1831 	/* EPT fault must be a read fault or a write fault */
1832 	read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1833 	write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1834 	if ((read | write) == 0)
1835 		return (FALSE);
1836 
1837 	/*
1838 	 * The EPT violation must have been caused by accessing a
1839 	 * guest-physical address that is a translation of a guest-linear
1840 	 * address.
1841 	 */
1842 	if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1843 	    (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1844 		return (FALSE);
1845 	}
1846 
1847 	return (TRUE);
1848 }
1849 
1850 static __inline int
1851 apic_access_virtualization(struct vmx *vmx, int vcpuid)
1852 {
1853 	uint32_t proc_ctls2;
1854 
1855 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1856 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1857 }
1858 
1859 static __inline int
1860 x2apic_virtualization(struct vmx *vmx, int vcpuid)
1861 {
1862 	uint32_t proc_ctls2;
1863 
1864 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1865 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1866 }
1867 
1868 static int
1869 vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1870     uint64_t qual)
1871 {
1872 	int error, handled, offset;
1873 	uint32_t *apic_regs, vector;
1874 	bool retu;
1875 
1876 	handled = HANDLED;
1877 	offset = APIC_WRITE_OFFSET(qual);
1878 
1879 	if (!apic_access_virtualization(vmx, vcpuid)) {
1880 		/*
1881 		 * In general there should not be any APIC write VM-exits
1882 		 * unless APIC-access virtualization is enabled.
1883 		 *
1884 		 * However self-IPI virtualization can legitimately trigger
1885 		 * an APIC-write VM-exit so treat it specially.
1886 		 */
1887 		if (x2apic_virtualization(vmx, vcpuid) &&
1888 		    offset == APIC_OFFSET_SELF_IPI) {
1889 			apic_regs = (uint32_t *)(vlapic->apic_page);
1890 			vector = apic_regs[APIC_OFFSET_SELF_IPI / 4];
1891 			vlapic_self_ipi_handler(vlapic, vector);
1892 			return (HANDLED);
1893 		} else
1894 			return (UNHANDLED);
1895 	}
1896 
1897 	switch (offset) {
1898 	case APIC_OFFSET_ID:
1899 		vlapic_id_write_handler(vlapic);
1900 		break;
1901 	case APIC_OFFSET_LDR:
1902 		vlapic_ldr_write_handler(vlapic);
1903 		break;
1904 	case APIC_OFFSET_DFR:
1905 		vlapic_dfr_write_handler(vlapic);
1906 		break;
1907 	case APIC_OFFSET_SVR:
1908 		vlapic_svr_write_handler(vlapic);
1909 		break;
1910 	case APIC_OFFSET_ESR:
1911 		vlapic_esr_write_handler(vlapic);
1912 		break;
1913 	case APIC_OFFSET_ICR_LOW:
1914 		retu = false;
1915 		error = vlapic_icrlo_write_handler(vlapic, &retu);
1916 		if (error != 0 || retu)
1917 			handled = UNHANDLED;
1918 		break;
1919 	case APIC_OFFSET_CMCI_LVT:
1920 	case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1921 		vlapic_lvt_write_handler(vlapic, offset);
1922 		break;
1923 	case APIC_OFFSET_TIMER_ICR:
1924 		vlapic_icrtmr_write_handler(vlapic);
1925 		break;
1926 	case APIC_OFFSET_TIMER_DCR:
1927 		vlapic_dcr_write_handler(vlapic);
1928 		break;
1929 	default:
1930 		handled = UNHANDLED;
1931 		break;
1932 	}
1933 	return (handled);
1934 }
1935 
1936 static bool
1937 apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
1938 {
1939 
1940 	if (apic_access_virtualization(vmx, vcpuid) &&
1941 	    (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
1942 		return (true);
1943 	else
1944 		return (false);
1945 }
1946 
1947 static int
1948 vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
1949 {
1950 	uint64_t qual;
1951 	int access_type, offset, allowed;
1952 
1953 	if (!apic_access_virtualization(vmx, vcpuid))
1954 		return (UNHANDLED);
1955 
1956 	qual = vmexit->u.vmx.exit_qualification;
1957 	access_type = APIC_ACCESS_TYPE(qual);
1958 	offset = APIC_ACCESS_OFFSET(qual);
1959 
1960 	allowed = 0;
1961 	if (access_type == 0) {
1962 		/*
1963 		 * Read data access to the following registers is expected.
1964 		 */
1965 		switch (offset) {
1966 		case APIC_OFFSET_APR:
1967 		case APIC_OFFSET_PPR:
1968 		case APIC_OFFSET_RRR:
1969 		case APIC_OFFSET_CMCI_LVT:
1970 		case APIC_OFFSET_TIMER_CCR:
1971 			allowed = 1;
1972 			break;
1973 		default:
1974 			break;
1975 		}
1976 	} else if (access_type == 1) {
1977 		/*
1978 		 * Write data access to the following registers is expected.
1979 		 */
1980 		switch (offset) {
1981 		case APIC_OFFSET_VER:
1982 		case APIC_OFFSET_APR:
1983 		case APIC_OFFSET_PPR:
1984 		case APIC_OFFSET_RRR:
1985 		case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
1986 		case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
1987 		case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
1988 		case APIC_OFFSET_CMCI_LVT:
1989 		case APIC_OFFSET_TIMER_CCR:
1990 			allowed = 1;
1991 			break;
1992 		default:
1993 			break;
1994 		}
1995 	}
1996 
1997 	if (allowed) {
1998 		vmexit_inst_emul(vmexit, DEFAULT_APIC_BASE + offset,
1999 		    VIE_INVALID_GLA);
2000 	}
2001 
2002 	/*
2003 	 * Regardless of whether the APIC-access is allowed this handler
2004 	 * always returns UNHANDLED:
2005 	 * - if the access is allowed then it is handled by emulating the
2006 	 *   instruction that caused the VM-exit (outside the critical section)
2007 	 * - if the access is not allowed then it will be converted to an
2008 	 *   exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
2009 	 */
2010 	return (UNHANDLED);
2011 }
2012 
2013 static enum task_switch_reason
2014 vmx_task_switch_reason(uint64_t qual)
2015 {
2016 	int reason;
2017 
2018 	reason = (qual >> 30) & 0x3;
2019 	switch (reason) {
2020 	case 0:
2021 		return (TSR_CALL);
2022 	case 1:
2023 		return (TSR_IRET);
2024 	case 2:
2025 		return (TSR_JMP);
2026 	case 3:
2027 		return (TSR_IDT_GATE);
2028 	default:
2029 		panic("%s: invalid reason %d", __func__, reason);
2030 	}
2031 }
2032 
2033 static int
2034 emulate_wrmsr(struct vmx *vmx, int vcpuid, u_int num, uint64_t val, bool *retu)
2035 {
2036 	int error;
2037 
2038 	if (lapic_msr(num))
2039 		error = lapic_wrmsr(vmx->vm, vcpuid, num, val, retu);
2040 	else
2041 		error = vmx_wrmsr(vmx, vcpuid, num, val, retu);
2042 
2043 	return (error);
2044 }
2045 
2046 static int
2047 emulate_rdmsr(struct vmx *vmx, int vcpuid, u_int num, bool *retu)
2048 {
2049 	struct vmxctx *vmxctx;
2050 	uint64_t result;
2051 	uint32_t eax, edx;
2052 	int error;
2053 
2054 	if (lapic_msr(num))
2055 		error = lapic_rdmsr(vmx->vm, vcpuid, num, &result, retu);
2056 	else
2057 		error = vmx_rdmsr(vmx, vcpuid, num, &result, retu);
2058 
2059 	if (error == 0) {
2060 		eax = result;
2061 		vmxctx = &vmx->ctx[vcpuid];
2062 		error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RAX, eax);
2063 		KASSERT(error == 0, ("vmxctx_setreg(rax) error %d", error));
2064 
2065 		edx = result >> 32;
2066 		error = vmxctx_setreg(vmxctx, VM_REG_GUEST_RDX, edx);
2067 		KASSERT(error == 0, ("vmxctx_setreg(rdx) error %d", error));
2068 	}
2069 
2070 	return (error);
2071 }
2072 
2073 static int
2074 vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2075 {
2076 	int error, errcode, errcode_valid, handled, in;
2077 	struct vmxctx *vmxctx;
2078 	struct vlapic *vlapic;
2079 	struct vm_inout_str *vis;
2080 	struct vm_task_switch *ts;
2081 	uint32_t eax, ecx, edx, idtvec_info, idtvec_err, intr_info, inst_info;
2082 	uint32_t intr_type, intr_vec, reason;
2083 	uint64_t exitintinfo, qual, gpa;
2084 	bool retu;
2085 
2086 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2087 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2088 
2089 	handled = UNHANDLED;
2090 	vmxctx = &vmx->ctx[vcpu];
2091 
2092 	qual = vmexit->u.vmx.exit_qualification;
2093 	reason = vmexit->u.vmx.exit_reason;
2094 	vmexit->exitcode = VM_EXITCODE_BOGUS;
2095 
2096 	vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
2097 
2098 	/*
2099 	 * VM-entry failures during or after loading guest state.
2100 	 *
2101 	 * These VM-exits are uncommon but must be handled specially
2102 	 * as most VM-exit fields are not populated as usual.
2103 	 */
2104 	if (__predict_false(reason == EXIT_REASON_MCE_DURING_ENTRY)) {
2105 		VCPU_CTR0(vmx->vm, vcpu, "Handling MCE during VM-entry");
2106 		__asm __volatile("int $18");
2107 		return (1);
2108 	}
2109 
2110 	/*
2111 	 * VM exits that can be triggered during event delivery need to
2112 	 * be handled specially by re-injecting the event if the IDT
2113 	 * vectoring information field's valid bit is set.
2114 	 *
2115 	 * See "Information for VM Exits During Event Delivery" in Intel SDM
2116 	 * for details.
2117 	 */
2118 	idtvec_info = vmcs_idt_vectoring_info();
2119 	if (idtvec_info & VMCS_IDT_VEC_VALID) {
2120 		idtvec_info &= ~(1 << 12); /* clear undefined bit */
2121 		exitintinfo = idtvec_info;
2122 		if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2123 			idtvec_err = vmcs_idt_vectoring_err();
2124 			exitintinfo |= (uint64_t)idtvec_err << 32;
2125 		}
2126 		error = vm_exit_intinfo(vmx->vm, vcpu, exitintinfo);
2127 		KASSERT(error == 0, ("%s: vm_set_intinfo error %d",
2128 		    __func__, error));
2129 
2130 		/*
2131 		 * If 'virtual NMIs' are being used and the VM-exit
2132 		 * happened while injecting an NMI during the previous
2133 		 * VM-entry, then clear "blocking by NMI" in the
2134 		 * Guest Interruptibility-State so the NMI can be
2135 		 * reinjected on the subsequent VM-entry.
2136 		 *
2137 		 * However, if the NMI was being delivered through a task
2138 		 * gate, then the new task must start execution with NMIs
2139 		 * blocked so don't clear NMI blocking in this case.
2140 		 */
2141 		intr_type = idtvec_info & VMCS_INTR_T_MASK;
2142 		if (intr_type == VMCS_INTR_T_NMI) {
2143 			if (reason != EXIT_REASON_TASK_SWITCH)
2144 				vmx_clear_nmi_blocking(vmx, vcpu);
2145 			else
2146 				vmx_assert_nmi_blocking(vmx, vcpu);
2147 		}
2148 
2149 		/*
2150 		 * Update VM-entry instruction length if the event being
2151 		 * delivered was a software interrupt or software exception.
2152 		 */
2153 		if (intr_type == VMCS_INTR_T_SWINTR ||
2154 		    intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2155 		    intr_type == VMCS_INTR_T_SWEXCEPTION) {
2156 			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2157 		}
2158 	}
2159 
2160 	switch (reason) {
2161 	case EXIT_REASON_TASK_SWITCH:
2162 		ts = &vmexit->u.task_switch;
2163 		ts->tsssel = qual & 0xffff;
2164 		ts->reason = vmx_task_switch_reason(qual);
2165 		ts->ext = 0;
2166 		ts->errcode_valid = 0;
2167 		vmx_paging_info(&ts->paging);
2168 		/*
2169 		 * If the task switch was due to a CALL, JMP, IRET, software
2170 		 * interrupt (INT n) or software exception (INT3, INTO),
2171 		 * then the saved %rip references the instruction that caused
2172 		 * the task switch. The instruction length field in the VMCS
2173 		 * is valid in this case.
2174 		 *
2175 		 * In all other cases (e.g., NMI, hardware exception) the
2176 		 * saved %rip is one that would have been saved in the old TSS
2177 		 * had the task switch completed normally so the instruction
2178 		 * length field is not needed in this case and is explicitly
2179 		 * set to 0.
2180 		 */
2181 		if (ts->reason == TSR_IDT_GATE) {
2182 			KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2183 			    ("invalid idtvec_info %#x for IDT task switch",
2184 			    idtvec_info));
2185 			intr_type = idtvec_info & VMCS_INTR_T_MASK;
2186 			if (intr_type != VMCS_INTR_T_SWINTR &&
2187 			    intr_type != VMCS_INTR_T_SWEXCEPTION &&
2188 			    intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2189 				/* Task switch triggered by external event */
2190 				ts->ext = 1;
2191 				vmexit->inst_length = 0;
2192 				if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2193 					ts->errcode_valid = 1;
2194 					ts->errcode = vmcs_idt_vectoring_err();
2195 				}
2196 			}
2197 		}
2198 		vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2199 		VCPU_CTR4(vmx->vm, vcpu, "task switch reason %d, tss 0x%04x, "
2200 		    "%s errcode 0x%016lx", ts->reason, ts->tsssel,
2201 		    ts->ext ? "external" : "internal",
2202 		    ((uint64_t)ts->errcode << 32) | ts->errcode_valid);
2203 		break;
2204 	case EXIT_REASON_CR_ACCESS:
2205 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2206 		switch (qual & 0xf) {
2207 		case 0:
2208 			handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2209 			break;
2210 		case 4:
2211 			handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2212 			break;
2213 		case 8:
2214 			handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2215 			break;
2216 		}
2217 		break;
2218 	case EXIT_REASON_RDMSR:
2219 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_RDMSR, 1);
2220 		retu = false;
2221 		ecx = vmxctx->guest_rcx;
2222 		VCPU_CTR1(vmx->vm, vcpu, "rdmsr 0x%08x", ecx);
2223 		error = emulate_rdmsr(vmx, vcpu, ecx, &retu);
2224 		if (error) {
2225 			vmexit->exitcode = VM_EXITCODE_RDMSR;
2226 			vmexit->u.msr.code = ecx;
2227 		} else if (!retu) {
2228 			handled = HANDLED;
2229 		} else {
2230 			/* Return to userspace with a valid exitcode */
2231 			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2232 			    ("emulate_rdmsr retu with bogus exitcode"));
2233 		}
2234 		break;
2235 	case EXIT_REASON_WRMSR:
2236 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_WRMSR, 1);
2237 		retu = false;
2238 		eax = vmxctx->guest_rax;
2239 		ecx = vmxctx->guest_rcx;
2240 		edx = vmxctx->guest_rdx;
2241 		VCPU_CTR2(vmx->vm, vcpu, "wrmsr 0x%08x value 0x%016lx",
2242 		    ecx, (uint64_t)edx << 32 | eax);
2243 		error = emulate_wrmsr(vmx, vcpu, ecx,
2244 		    (uint64_t)edx << 32 | eax, &retu);
2245 		if (error) {
2246 			vmexit->exitcode = VM_EXITCODE_WRMSR;
2247 			vmexit->u.msr.code = ecx;
2248 			vmexit->u.msr.wval = (uint64_t)edx << 32 | eax;
2249 		} else if (!retu) {
2250 			handled = HANDLED;
2251 		} else {
2252 			/* Return to userspace with a valid exitcode */
2253 			KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
2254 			    ("emulate_wrmsr retu with bogus exitcode"));
2255 		}
2256 		break;
2257 	case EXIT_REASON_HLT:
2258 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2259 		vmexit->exitcode = VM_EXITCODE_HLT;
2260 		vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2261 		break;
2262 	case EXIT_REASON_MTF:
2263 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2264 		vmexit->exitcode = VM_EXITCODE_MTRAP;
2265 		vmexit->inst_length = 0;
2266 		break;
2267 	case EXIT_REASON_PAUSE:
2268 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2269 		vmexit->exitcode = VM_EXITCODE_PAUSE;
2270 		break;
2271 	case EXIT_REASON_INTR_WINDOW:
2272 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2273 		vmx_clear_int_window_exiting(vmx, vcpu);
2274 		return (1);
2275 	case EXIT_REASON_EXT_INTR:
2276 		/*
2277 		 * External interrupts serve only to cause VM exits and allow
2278 		 * the host interrupt handler to run.
2279 		 *
2280 		 * If this external interrupt triggers a virtual interrupt
2281 		 * to a VM, then that state will be recorded by the
2282 		 * host interrupt handler in the VM's softc. We will inject
2283 		 * this virtual interrupt during the subsequent VM enter.
2284 		 */
2285 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2286 
2287 		/*
2288 		 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2289 		 * This appears to be a bug in VMware Fusion?
2290 		 */
2291 		if (!(intr_info & VMCS_INTR_VALID))
2292 			return (1);
2293 		KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2294 		    (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2295 		    ("VM exit interruption info invalid: %#x", intr_info));
2296 		vmx_trigger_hostintr(intr_info & 0xff);
2297 
2298 		/*
2299 		 * This is special. We want to treat this as an 'handled'
2300 		 * VM-exit but not increment the instruction pointer.
2301 		 */
2302 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2303 		return (1);
2304 	case EXIT_REASON_NMI_WINDOW:
2305 		/* Exit to allow the pending virtual NMI to be injected */
2306 		if (vm_nmi_pending(vmx->vm, vcpu))
2307 			vmx_inject_nmi(vmx, vcpu);
2308 		vmx_clear_nmi_window_exiting(vmx, vcpu);
2309 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2310 		return (1);
2311 	case EXIT_REASON_INOUT:
2312 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2313 		vmexit->exitcode = VM_EXITCODE_INOUT;
2314 		vmexit->u.inout.bytes = (qual & 0x7) + 1;
2315 		vmexit->u.inout.in = in = (qual & 0x8) ? 1 : 0;
2316 		vmexit->u.inout.string = (qual & 0x10) ? 1 : 0;
2317 		vmexit->u.inout.rep = (qual & 0x20) ? 1 : 0;
2318 		vmexit->u.inout.port = (uint16_t)(qual >> 16);
2319 		vmexit->u.inout.eax = (uint32_t)(vmxctx->guest_rax);
2320 		if (vmexit->u.inout.string) {
2321 			inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
2322 			vmexit->exitcode = VM_EXITCODE_INOUT_STR;
2323 			vis = &vmexit->u.inout_str;
2324 			vmx_paging_info(&vis->paging);
2325 			vis->rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2326 			vis->cr0 = vmcs_read(VMCS_GUEST_CR0);
2327 			vis->index = inout_str_index(vmx, vcpu, in);
2328 			vis->count = inout_str_count(vmx, vcpu, vis->inout.rep);
2329 			vis->addrsize = inout_str_addrsize(inst_info);
2330 			inout_str_seginfo(vmx, vcpu, inst_info, in, vis);
2331 		}
2332 		break;
2333 	case EXIT_REASON_CPUID:
2334 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2335 		handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
2336 		break;
2337 	case EXIT_REASON_EXCEPTION:
2338 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2339 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2340 		KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2341 		    ("VM exit interruption info invalid: %#x", intr_info));
2342 
2343 		intr_vec = intr_info & 0xff;
2344 		intr_type = intr_info & VMCS_INTR_T_MASK;
2345 
2346 		/*
2347 		 * If Virtual NMIs control is 1 and the VM-exit is due to a
2348 		 * fault encountered during the execution of IRET then we must
2349 		 * restore the state of "virtual-NMI blocking" before resuming
2350 		 * the guest.
2351 		 *
2352 		 * See "Resuming Guest Software after Handling an Exception".
2353 		 * See "Information for VM Exits Due to Vectored Events".
2354 		 */
2355 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2356 		    (intr_vec != IDT_DF) &&
2357 		    (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2358 			vmx_restore_nmi_blocking(vmx, vcpu);
2359 
2360 		/*
2361 		 * The NMI has already been handled in vmx_exit_handle_nmi().
2362 		 */
2363 		if (intr_type == VMCS_INTR_T_NMI)
2364 			return (1);
2365 
2366 		/*
2367 		 * Call the machine check handler by hand. Also don't reflect
2368 		 * the machine check back into the guest.
2369 		 */
2370 		if (intr_vec == IDT_MC) {
2371 			VCPU_CTR0(vmx->vm, vcpu, "Vectoring to MCE handler");
2372 			__asm __volatile("int $18");
2373 			return (1);
2374 		}
2375 
2376 		if (intr_vec == IDT_PF) {
2377 			error = vmxctx_setreg(vmxctx, VM_REG_GUEST_CR2, qual);
2378 			KASSERT(error == 0, ("%s: vmxctx_setreg(cr2) error %d",
2379 			    __func__, error));
2380 		}
2381 
2382 		/*
2383 		 * Software exceptions exhibit trap-like behavior. This in
2384 		 * turn requires populating the VM-entry instruction length
2385 		 * so that the %rip in the trap frame is past the INT3/INTO
2386 		 * instruction.
2387 		 */
2388 		if (intr_type == VMCS_INTR_T_SWEXCEPTION)
2389 			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2390 
2391 		/* Reflect all other exceptions back into the guest */
2392 		errcode_valid = errcode = 0;
2393 		if (intr_info & VMCS_INTR_DEL_ERRCODE) {
2394 			errcode_valid = 1;
2395 			errcode = vmcs_read(VMCS_EXIT_INTR_ERRCODE);
2396 		}
2397 		VCPU_CTR2(vmx->vm, vcpu, "Reflecting exception %d/%#x into "
2398 		    "the guest", intr_vec, errcode);
2399 		error = vm_inject_exception(vmx->vm, vcpu, intr_vec,
2400 		    errcode_valid, errcode, 0);
2401 		KASSERT(error == 0, ("%s: vm_inject_exception error %d",
2402 		    __func__, error));
2403 		return (1);
2404 
2405 	case EXIT_REASON_EPT_FAULT:
2406 		/*
2407 		 * If 'gpa' lies within the address space allocated to
2408 		 * memory then this must be a nested page fault otherwise
2409 		 * this must be an instruction that accesses MMIO space.
2410 		 */
2411 		gpa = vmcs_gpa();
2412 		if (vm_mem_allocated(vmx->vm, gpa) ||
2413 		    apic_access_fault(vmx, vcpu, gpa)) {
2414 			vmexit->exitcode = VM_EXITCODE_PAGING;
2415 			vmexit->inst_length = 0;
2416 			vmexit->u.paging.gpa = gpa;
2417 			vmexit->u.paging.fault_type = ept_fault_type(qual);
2418 			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2419 		} else if (ept_emulation_fault(qual)) {
2420 			vmexit_inst_emul(vmexit, gpa, vmcs_gla());
2421 			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INST_EMUL, 1);
2422 		}
2423 		/*
2424 		 * If Virtual NMIs control is 1 and the VM-exit is due to an
2425 		 * EPT fault during the execution of IRET then we must restore
2426 		 * the state of "virtual-NMI blocking" before resuming.
2427 		 *
2428 		 * See description of "NMI unblocking due to IRET" in
2429 		 * "Exit Qualification for EPT Violations".
2430 		 */
2431 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2432 		    (qual & EXIT_QUAL_NMIUDTI) != 0)
2433 			vmx_restore_nmi_blocking(vmx, vcpu);
2434 		break;
2435 	case EXIT_REASON_VIRTUALIZED_EOI:
2436 		vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2437 		vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2438 		vmexit->inst_length = 0;	/* trap-like */
2439 		break;
2440 	case EXIT_REASON_APIC_ACCESS:
2441 		handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2442 		break;
2443 	case EXIT_REASON_APIC_WRITE:
2444 		/*
2445 		 * APIC-write VM exit is trap-like so the %rip is already
2446 		 * pointing to the next instruction.
2447 		 */
2448 		vmexit->inst_length = 0;
2449 		vlapic = vm_lapic(vmx->vm, vcpu);
2450 		handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2451 		break;
2452 	case EXIT_REASON_XSETBV:
2453 		handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2454 		break;
2455 	case EXIT_REASON_MONITOR:
2456 		vmexit->exitcode = VM_EXITCODE_MONITOR;
2457 		break;
2458 	case EXIT_REASON_MWAIT:
2459 		vmexit->exitcode = VM_EXITCODE_MWAIT;
2460 		break;
2461 	default:
2462 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2463 		break;
2464 	}
2465 
2466 	if (handled) {
2467 		/*
2468 		 * It is possible that control is returned to userland
2469 		 * even though we were able to handle the VM exit in the
2470 		 * kernel.
2471 		 *
2472 		 * In such a case we want to make sure that the userland
2473 		 * restarts guest execution at the instruction *after*
2474 		 * the one we just processed. Therefore we update the
2475 		 * guest rip in the VMCS and in 'vmexit'.
2476 		 */
2477 		vmexit->rip += vmexit->inst_length;
2478 		vmexit->inst_length = 0;
2479 		vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2480 	} else {
2481 		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2482 			/*
2483 			 * If this VM exit was not claimed by anybody then
2484 			 * treat it as a generic VMX exit.
2485 			 */
2486 			vmexit->exitcode = VM_EXITCODE_VMX;
2487 			vmexit->u.vmx.status = VM_SUCCESS;
2488 			vmexit->u.vmx.inst_type = 0;
2489 			vmexit->u.vmx.inst_error = 0;
2490 		} else {
2491 			/*
2492 			 * The exitcode and collateral have been populated.
2493 			 * The VM exit will be processed further in userland.
2494 			 */
2495 		}
2496 	}
2497 	return (handled);
2498 }
2499 
2500 static __inline void
2501 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2502 {
2503 
2504 	KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2505 	    ("vmx_exit_inst_error: invalid inst_fail_status %d",
2506 	    vmxctx->inst_fail_status));
2507 
2508 	vmexit->inst_length = 0;
2509 	vmexit->exitcode = VM_EXITCODE_VMX;
2510 	vmexit->u.vmx.status = vmxctx->inst_fail_status;
2511 	vmexit->u.vmx.inst_error = vmcs_instruction_error();
2512 	vmexit->u.vmx.exit_reason = ~0;
2513 	vmexit->u.vmx.exit_qualification = ~0;
2514 
2515 	switch (rc) {
2516 	case VMX_VMRESUME_ERROR:
2517 	case VMX_VMLAUNCH_ERROR:
2518 	case VMX_INVEPT_ERROR:
2519 		vmexit->u.vmx.inst_type = rc;
2520 		break;
2521 	default:
2522 		panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2523 	}
2524 }
2525 
2526 /*
2527  * If the NMI-exiting VM execution control is set to '1' then an NMI in
2528  * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2529  * sufficient to simply vector to the NMI handler via a software interrupt.
2530  * However, this must be done before maskable interrupts are enabled
2531  * otherwise the "iret" issued by an interrupt handler will incorrectly
2532  * clear NMI blocking.
2533  */
2534 static __inline void
2535 vmx_exit_handle_nmi(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2536 {
2537 	uint32_t intr_info;
2538 
2539 	KASSERT((read_rflags() & PSL_I) == 0, ("interrupts enabled"));
2540 
2541 	if (vmexit->u.vmx.exit_reason != EXIT_REASON_EXCEPTION)
2542 		return;
2543 
2544 	intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2545 	KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2546 	    ("VM exit interruption info invalid: %#x", intr_info));
2547 
2548 	if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2549 		KASSERT((intr_info & 0xff) == IDT_NMI, ("VM exit due "
2550 		    "to NMI has invalid vector: %#x", intr_info));
2551 		VCPU_CTR0(vmx->vm, vcpuid, "Vectoring to NMI handler");
2552 		__asm __volatile("int $2");
2553 	}
2554 }
2555 
2556 static int
2557 vmx_run(void *arg, int vcpu, register_t rip, pmap_t pmap,
2558     void *rendezvous_cookie, void *suspend_cookie)
2559 {
2560 	int rc, handled, launched;
2561 	struct vmx *vmx;
2562 	struct vm *vm;
2563 	struct vmxctx *vmxctx;
2564 	struct vmcs *vmcs;
2565 	struct vm_exit *vmexit;
2566 	struct vlapic *vlapic;
2567 	uint32_t exit_reason;
2568 
2569 	vmx = arg;
2570 	vm = vmx->vm;
2571 	vmcs = &vmx->vmcs[vcpu];
2572 	vmxctx = &vmx->ctx[vcpu];
2573 	vlapic = vm_lapic(vm, vcpu);
2574 	vmexit = vm_exitinfo(vm, vcpu);
2575 	launched = 0;
2576 
2577 	KASSERT(vmxctx->pmap == pmap,
2578 	    ("pmap %p different than ctx pmap %p", pmap, vmxctx->pmap));
2579 
2580 	vmx_msr_guest_enter(vmx, vcpu);
2581 
2582 	VMPTRLD(vmcs);
2583 
2584 	/*
2585 	 * XXX
2586 	 * We do this every time because we may setup the virtual machine
2587 	 * from a different process than the one that actually runs it.
2588 	 *
2589 	 * If the life of a virtual machine was spent entirely in the context
2590 	 * of a single process we could do this once in vmx_vminit().
2591 	 */
2592 	vmcs_write(VMCS_HOST_CR3, rcr3());
2593 
2594 	vmcs_write(VMCS_GUEST_RIP, rip);
2595 	vmx_set_pcpu_defaults(vmx, vcpu, pmap);
2596 	do {
2597 		KASSERT(vmcs_guest_rip() == rip, ("%s: vmcs guest rip mismatch "
2598 		    "%#lx/%#lx", __func__, vmcs_guest_rip(), rip));
2599 
2600 		handled = UNHANDLED;
2601 		/*
2602 		 * Interrupts are disabled from this point on until the
2603 		 * guest starts executing. This is done for the following
2604 		 * reasons:
2605 		 *
2606 		 * If an AST is asserted on this thread after the check below,
2607 		 * then the IPI_AST notification will not be lost, because it
2608 		 * will cause a VM exit due to external interrupt as soon as
2609 		 * the guest state is loaded.
2610 		 *
2611 		 * A posted interrupt after 'vmx_inject_interrupts()' will
2612 		 * not be "lost" because it will be held pending in the host
2613 		 * APIC because interrupts are disabled. The pending interrupt
2614 		 * will be recognized as soon as the guest state is loaded.
2615 		 *
2616 		 * The same reasoning applies to the IPI generated by
2617 		 * pmap_invalidate_ept().
2618 		 */
2619 		disable_intr();
2620 		vmx_inject_interrupts(vmx, vcpu, vlapic, rip);
2621 
2622 		/*
2623 		 * Check for vcpu suspension after injecting events because
2624 		 * vmx_inject_interrupts() can suspend the vcpu due to a
2625 		 * triple fault.
2626 		 */
2627 		if (vcpu_suspended(suspend_cookie)) {
2628 			enable_intr();
2629 			vm_exit_suspended(vmx->vm, vcpu, rip);
2630 			break;
2631 		}
2632 
2633 		if (vcpu_rendezvous_pending(rendezvous_cookie)) {
2634 			enable_intr();
2635 			vm_exit_rendezvous(vmx->vm, vcpu, rip);
2636 			break;
2637 		}
2638 
2639 		if (vcpu_should_yield(vm, vcpu)) {
2640 			enable_intr();
2641 			vm_exit_astpending(vmx->vm, vcpu, rip);
2642 			vmx_astpending_trace(vmx, vcpu, rip);
2643 			handled = HANDLED;
2644 			break;
2645 		}
2646 
2647 		vmx_run_trace(vmx, vcpu);
2648 		rc = vmx_enter_guest(vmxctx, vmx, launched);
2649 
2650 		/* Collect some information for VM exit processing */
2651 		vmexit->rip = rip = vmcs_guest_rip();
2652 		vmexit->inst_length = vmexit_instruction_length();
2653 		vmexit->u.vmx.exit_reason = exit_reason = vmcs_exit_reason();
2654 		vmexit->u.vmx.exit_qualification = vmcs_exit_qualification();
2655 
2656 		/* Update 'nextrip' */
2657 		vmx->state[vcpu].nextrip = rip;
2658 
2659 		if (rc == VMX_GUEST_VMEXIT) {
2660 			vmx_exit_handle_nmi(vmx, vcpu, vmexit);
2661 			enable_intr();
2662 			handled = vmx_exit_process(vmx, vcpu, vmexit);
2663 		} else {
2664 			enable_intr();
2665 			vmx_exit_inst_error(vmxctx, rc, vmexit);
2666 		}
2667 		launched = 1;
2668 		vmx_exit_trace(vmx, vcpu, rip, exit_reason, handled);
2669 		rip = vmexit->rip;
2670 	} while (handled);
2671 
2672 	/*
2673 	 * If a VM exit has been handled then the exitcode must be BOGUS
2674 	 * If a VM exit is not handled then the exitcode must not be BOGUS
2675 	 */
2676 	if ((handled && vmexit->exitcode != VM_EXITCODE_BOGUS) ||
2677 	    (!handled && vmexit->exitcode == VM_EXITCODE_BOGUS)) {
2678 		panic("Mismatch between handled (%d) and exitcode (%d)",
2679 		      handled, vmexit->exitcode);
2680 	}
2681 
2682 	if (!handled)
2683 		vmm_stat_incr(vm, vcpu, VMEXIT_USERSPACE, 1);
2684 
2685 	VCPU_CTR1(vm, vcpu, "returning from vmx_run: exitcode %d",
2686 	    vmexit->exitcode);
2687 
2688 	VMCLEAR(vmcs);
2689 	vmx_msr_guest_exit(vmx, vcpu);
2690 
2691 	return (0);
2692 }
2693 
2694 static void
2695 vmx_vmcleanup(void *arg)
2696 {
2697 	int i;
2698 	struct vmx *vmx = arg;
2699 
2700 	if (apic_access_virtualization(vmx, 0))
2701 		vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2702 
2703 	for (i = 0; i < VM_MAXCPU; i++)
2704 		vpid_free(vmx->state[i].vpid);
2705 
2706 	free(vmx, M_VMX);
2707 
2708 	return;
2709 }
2710 
2711 static register_t *
2712 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
2713 {
2714 
2715 	switch (reg) {
2716 	case VM_REG_GUEST_RAX:
2717 		return (&vmxctx->guest_rax);
2718 	case VM_REG_GUEST_RBX:
2719 		return (&vmxctx->guest_rbx);
2720 	case VM_REG_GUEST_RCX:
2721 		return (&vmxctx->guest_rcx);
2722 	case VM_REG_GUEST_RDX:
2723 		return (&vmxctx->guest_rdx);
2724 	case VM_REG_GUEST_RSI:
2725 		return (&vmxctx->guest_rsi);
2726 	case VM_REG_GUEST_RDI:
2727 		return (&vmxctx->guest_rdi);
2728 	case VM_REG_GUEST_RBP:
2729 		return (&vmxctx->guest_rbp);
2730 	case VM_REG_GUEST_R8:
2731 		return (&vmxctx->guest_r8);
2732 	case VM_REG_GUEST_R9:
2733 		return (&vmxctx->guest_r9);
2734 	case VM_REG_GUEST_R10:
2735 		return (&vmxctx->guest_r10);
2736 	case VM_REG_GUEST_R11:
2737 		return (&vmxctx->guest_r11);
2738 	case VM_REG_GUEST_R12:
2739 		return (&vmxctx->guest_r12);
2740 	case VM_REG_GUEST_R13:
2741 		return (&vmxctx->guest_r13);
2742 	case VM_REG_GUEST_R14:
2743 		return (&vmxctx->guest_r14);
2744 	case VM_REG_GUEST_R15:
2745 		return (&vmxctx->guest_r15);
2746 	case VM_REG_GUEST_CR2:
2747 		return (&vmxctx->guest_cr2);
2748 	default:
2749 		break;
2750 	}
2751 	return (NULL);
2752 }
2753 
2754 static int
2755 vmxctx_getreg(struct vmxctx *vmxctx, int reg, uint64_t *retval)
2756 {
2757 	register_t *regp;
2758 
2759 	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2760 		*retval = *regp;
2761 		return (0);
2762 	} else
2763 		return (EINVAL);
2764 }
2765 
2766 static int
2767 vmxctx_setreg(struct vmxctx *vmxctx, int reg, uint64_t val)
2768 {
2769 	register_t *regp;
2770 
2771 	if ((regp = vmxctx_regptr(vmxctx, reg)) != NULL) {
2772 		*regp = val;
2773 		return (0);
2774 	} else
2775 		return (EINVAL);
2776 }
2777 
2778 static int
2779 vmx_get_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t *retval)
2780 {
2781 	uint64_t gi;
2782 	int error;
2783 
2784 	error = vmcs_getreg(&vmx->vmcs[vcpu], running,
2785 	    VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY), &gi);
2786 	*retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
2787 	return (error);
2788 }
2789 
2790 static int
2791 vmx_modify_intr_shadow(struct vmx *vmx, int vcpu, int running, uint64_t val)
2792 {
2793 	struct vmcs *vmcs;
2794 	uint64_t gi;
2795 	int error, ident;
2796 
2797 	/*
2798 	 * Forcing the vcpu into an interrupt shadow is not supported.
2799 	 */
2800 	if (val) {
2801 		error = EINVAL;
2802 		goto done;
2803 	}
2804 
2805 	vmcs = &vmx->vmcs[vcpu];
2806 	ident = VMCS_IDENT(VMCS_GUEST_INTERRUPTIBILITY);
2807 	error = vmcs_getreg(vmcs, running, ident, &gi);
2808 	if (error == 0) {
2809 		gi &= ~HWINTR_BLOCKING;
2810 		error = vmcs_setreg(vmcs, running, ident, gi);
2811 	}
2812 done:
2813 	VCPU_CTR2(vmx->vm, vcpu, "Setting intr_shadow to %#lx %s", val,
2814 	    error ? "failed" : "succeeded");
2815 	return (error);
2816 }
2817 
2818 static int
2819 vmx_shadow_reg(int reg)
2820 {
2821 	int shreg;
2822 
2823 	shreg = -1;
2824 
2825 	switch (reg) {
2826 	case VM_REG_GUEST_CR0:
2827 		shreg = VMCS_CR0_SHADOW;
2828                 break;
2829         case VM_REG_GUEST_CR4:
2830 		shreg = VMCS_CR4_SHADOW;
2831 		break;
2832 	default:
2833 		break;
2834 	}
2835 
2836 	return (shreg);
2837 }
2838 
2839 static int
2840 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
2841 {
2842 	int running, hostcpu;
2843 	struct vmx *vmx = arg;
2844 
2845 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2846 	if (running && hostcpu != curcpu)
2847 		panic("vmx_getreg: %s%d is running", vm_name(vmx->vm), vcpu);
2848 
2849 	if (reg == VM_REG_GUEST_INTR_SHADOW)
2850 		return (vmx_get_intr_shadow(vmx, vcpu, running, retval));
2851 
2852 	if (vmxctx_getreg(&vmx->ctx[vcpu], reg, retval) == 0)
2853 		return (0);
2854 
2855 	return (vmcs_getreg(&vmx->vmcs[vcpu], running, reg, retval));
2856 }
2857 
2858 static int
2859 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
2860 {
2861 	int error, hostcpu, running, shadow;
2862 	uint64_t ctls;
2863 	pmap_t pmap;
2864 	struct vmx *vmx = arg;
2865 
2866 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2867 	if (running && hostcpu != curcpu)
2868 		panic("vmx_setreg: %s%d is running", vm_name(vmx->vm), vcpu);
2869 
2870 	if (reg == VM_REG_GUEST_INTR_SHADOW)
2871 		return (vmx_modify_intr_shadow(vmx, vcpu, running, val));
2872 
2873 	if (vmxctx_setreg(&vmx->ctx[vcpu], reg, val) == 0)
2874 		return (0);
2875 
2876 	error = vmcs_setreg(&vmx->vmcs[vcpu], running, reg, val);
2877 
2878 	if (error == 0) {
2879 		/*
2880 		 * If the "load EFER" VM-entry control is 1 then the
2881 		 * value of EFER.LMA must be identical to "IA-32e mode guest"
2882 		 * bit in the VM-entry control.
2883 		 */
2884 		if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0 &&
2885 		    (reg == VM_REG_GUEST_EFER)) {
2886 			vmcs_getreg(&vmx->vmcs[vcpu], running,
2887 				    VMCS_IDENT(VMCS_ENTRY_CTLS), &ctls);
2888 			if (val & EFER_LMA)
2889 				ctls |= VM_ENTRY_GUEST_LMA;
2890 			else
2891 				ctls &= ~VM_ENTRY_GUEST_LMA;
2892 			vmcs_setreg(&vmx->vmcs[vcpu], running,
2893 				    VMCS_IDENT(VMCS_ENTRY_CTLS), ctls);
2894 		}
2895 
2896 		shadow = vmx_shadow_reg(reg);
2897 		if (shadow > 0) {
2898 			/*
2899 			 * Store the unmodified value in the shadow
2900 			 */
2901 			error = vmcs_setreg(&vmx->vmcs[vcpu], running,
2902 				    VMCS_IDENT(shadow), val);
2903 		}
2904 
2905 		if (reg == VM_REG_GUEST_CR3) {
2906 			/*
2907 			 * Invalidate the guest vcpu's TLB mappings to emulate
2908 			 * the behavior of updating %cr3.
2909 			 *
2910 			 * XXX the processor retains global mappings when %cr3
2911 			 * is updated but vmx_invvpid() does not.
2912 			 */
2913 			pmap = vmx->ctx[vcpu].pmap;
2914 			vmx_invvpid(vmx, vcpu, pmap, running);
2915 		}
2916 	}
2917 
2918 	return (error);
2919 }
2920 
2921 static int
2922 vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2923 {
2924 	int hostcpu, running;
2925 	struct vmx *vmx = arg;
2926 
2927 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2928 	if (running && hostcpu != curcpu)
2929 		panic("vmx_getdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2930 
2931 	return (vmcs_getdesc(&vmx->vmcs[vcpu], running, reg, desc));
2932 }
2933 
2934 static int
2935 vmx_setdesc(void *arg, int vcpu, int reg, struct seg_desc *desc)
2936 {
2937 	int hostcpu, running;
2938 	struct vmx *vmx = arg;
2939 
2940 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
2941 	if (running && hostcpu != curcpu)
2942 		panic("vmx_setdesc: %s%d is running", vm_name(vmx->vm), vcpu);
2943 
2944 	return (vmcs_setdesc(&vmx->vmcs[vcpu], running, reg, desc));
2945 }
2946 
2947 static int
2948 vmx_getcap(void *arg, int vcpu, int type, int *retval)
2949 {
2950 	struct vmx *vmx = arg;
2951 	int vcap;
2952 	int ret;
2953 
2954 	ret = ENOENT;
2955 
2956 	vcap = vmx->cap[vcpu].set;
2957 
2958 	switch (type) {
2959 	case VM_CAP_HALT_EXIT:
2960 		if (cap_halt_exit)
2961 			ret = 0;
2962 		break;
2963 	case VM_CAP_PAUSE_EXIT:
2964 		if (cap_pause_exit)
2965 			ret = 0;
2966 		break;
2967 	case VM_CAP_MTRAP_EXIT:
2968 		if (cap_monitor_trap)
2969 			ret = 0;
2970 		break;
2971 	case VM_CAP_UNRESTRICTED_GUEST:
2972 		if (cap_unrestricted_guest)
2973 			ret = 0;
2974 		break;
2975 	case VM_CAP_ENABLE_INVPCID:
2976 		if (cap_invpcid)
2977 			ret = 0;
2978 		break;
2979 	default:
2980 		break;
2981 	}
2982 
2983 	if (ret == 0)
2984 		*retval = (vcap & (1 << type)) ? 1 : 0;
2985 
2986 	return (ret);
2987 }
2988 
2989 static int
2990 vmx_setcap(void *arg, int vcpu, int type, int val)
2991 {
2992 	struct vmx *vmx = arg;
2993 	struct vmcs *vmcs = &vmx->vmcs[vcpu];
2994 	uint32_t baseval;
2995 	uint32_t *pptr;
2996 	int error;
2997 	int flag;
2998 	int reg;
2999 	int retval;
3000 
3001 	retval = ENOENT;
3002 	pptr = NULL;
3003 
3004 	switch (type) {
3005 	case VM_CAP_HALT_EXIT:
3006 		if (cap_halt_exit) {
3007 			retval = 0;
3008 			pptr = &vmx->cap[vcpu].proc_ctls;
3009 			baseval = *pptr;
3010 			flag = PROCBASED_HLT_EXITING;
3011 			reg = VMCS_PRI_PROC_BASED_CTLS;
3012 		}
3013 		break;
3014 	case VM_CAP_MTRAP_EXIT:
3015 		if (cap_monitor_trap) {
3016 			retval = 0;
3017 			pptr = &vmx->cap[vcpu].proc_ctls;
3018 			baseval = *pptr;
3019 			flag = PROCBASED_MTF;
3020 			reg = VMCS_PRI_PROC_BASED_CTLS;
3021 		}
3022 		break;
3023 	case VM_CAP_PAUSE_EXIT:
3024 		if (cap_pause_exit) {
3025 			retval = 0;
3026 			pptr = &vmx->cap[vcpu].proc_ctls;
3027 			baseval = *pptr;
3028 			flag = PROCBASED_PAUSE_EXITING;
3029 			reg = VMCS_PRI_PROC_BASED_CTLS;
3030 		}
3031 		break;
3032 	case VM_CAP_UNRESTRICTED_GUEST:
3033 		if (cap_unrestricted_guest) {
3034 			retval = 0;
3035 			pptr = &vmx->cap[vcpu].proc_ctls2;
3036 			baseval = *pptr;
3037 			flag = PROCBASED2_UNRESTRICTED_GUEST;
3038 			reg = VMCS_SEC_PROC_BASED_CTLS;
3039 		}
3040 		break;
3041 	case VM_CAP_ENABLE_INVPCID:
3042 		if (cap_invpcid) {
3043 			retval = 0;
3044 			pptr = &vmx->cap[vcpu].proc_ctls2;
3045 			baseval = *pptr;
3046 			flag = PROCBASED2_ENABLE_INVPCID;
3047 			reg = VMCS_SEC_PROC_BASED_CTLS;
3048 		}
3049 		break;
3050 	default:
3051 		break;
3052 	}
3053 
3054 	if (retval == 0) {
3055 		if (val) {
3056 			baseval |= flag;
3057 		} else {
3058 			baseval &= ~flag;
3059 		}
3060 		VMPTRLD(vmcs);
3061 		error = vmwrite(reg, baseval);
3062 		VMCLEAR(vmcs);
3063 
3064 		if (error) {
3065 			retval = error;
3066 		} else {
3067 			/*
3068 			 * Update optional stored flags, and record
3069 			 * setting
3070 			 */
3071 			if (pptr != NULL) {
3072 				*pptr = baseval;
3073 			}
3074 
3075 			if (val) {
3076 				vmx->cap[vcpu].set |= (1 << type);
3077 			} else {
3078 				vmx->cap[vcpu].set &= ~(1 << type);
3079 			}
3080 		}
3081 	}
3082 
3083         return (retval);
3084 }
3085 
3086 struct vlapic_vtx {
3087 	struct vlapic	vlapic;
3088 	struct pir_desc	*pir_desc;
3089 	struct vmx	*vmx;
3090 };
3091 
3092 #define	VMX_CTR_PIR(vm, vcpuid, pir_desc, notify, vector, level, msg)	\
3093 do {									\
3094 	VCPU_CTR2(vm, vcpuid, msg " assert %s-triggered vector %d",	\
3095 	    level ? "level" : "edge", vector);				\
3096 	VCPU_CTR1(vm, vcpuid, msg " pir0 0x%016lx", pir_desc->pir[0]);	\
3097 	VCPU_CTR1(vm, vcpuid, msg " pir1 0x%016lx", pir_desc->pir[1]);	\
3098 	VCPU_CTR1(vm, vcpuid, msg " pir2 0x%016lx", pir_desc->pir[2]);	\
3099 	VCPU_CTR1(vm, vcpuid, msg " pir3 0x%016lx", pir_desc->pir[3]);	\
3100 	VCPU_CTR1(vm, vcpuid, msg " notify: %s", notify ? "yes" : "no");\
3101 } while (0)
3102 
3103 /*
3104  * vlapic->ops handlers that utilize the APICv hardware assist described in
3105  * Chapter 29 of the Intel SDM.
3106  */
3107 static int
3108 vmx_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
3109 {
3110 	struct vlapic_vtx *vlapic_vtx;
3111 	struct pir_desc *pir_desc;
3112 	uint64_t mask;
3113 	int idx, notify;
3114 
3115 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3116 	pir_desc = vlapic_vtx->pir_desc;
3117 
3118 	/*
3119 	 * Keep track of interrupt requests in the PIR descriptor. This is
3120 	 * because the virtual APIC page pointed to by the VMCS cannot be
3121 	 * modified if the vcpu is running.
3122 	 */
3123 	idx = vector / 64;
3124 	mask = 1UL << (vector % 64);
3125 	atomic_set_long(&pir_desc->pir[idx], mask);
3126 	notify = atomic_cmpset_long(&pir_desc->pending, 0, 1);
3127 
3128 	VMX_CTR_PIR(vlapic->vm, vlapic->vcpuid, pir_desc, notify, vector,
3129 	    level, "vmx_set_intr_ready");
3130 	return (notify);
3131 }
3132 
3133 static int
3134 vmx_pending_intr(struct vlapic *vlapic, int *vecptr)
3135 {
3136 	struct vlapic_vtx *vlapic_vtx;
3137 	struct pir_desc *pir_desc;
3138 	struct LAPIC *lapic;
3139 	uint64_t pending, pirval;
3140 	uint32_t ppr, vpr;
3141 	int i;
3142 
3143 	/*
3144 	 * This function is only expected to be called from the 'HLT' exit
3145 	 * handler which does not care about the vector that is pending.
3146 	 */
3147 	KASSERT(vecptr == NULL, ("vmx_pending_intr: vecptr must be NULL"));
3148 
3149 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3150 	pir_desc = vlapic_vtx->pir_desc;
3151 
3152 	pending = atomic_load_acq_long(&pir_desc->pending);
3153 	if (!pending)
3154 		return (0);	/* common case */
3155 
3156 	/*
3157 	 * If there is an interrupt pending then it will be recognized only
3158 	 * if its priority is greater than the processor priority.
3159 	 *
3160 	 * Special case: if the processor priority is zero then any pending
3161 	 * interrupt will be recognized.
3162 	 */
3163 	lapic = vlapic->apic_page;
3164 	ppr = lapic->ppr & 0xf0;
3165 	if (ppr == 0)
3166 		return (1);
3167 
3168 	VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "HLT with non-zero PPR %d",
3169 	    lapic->ppr);
3170 
3171 	for (i = 3; i >= 0; i--) {
3172 		pirval = pir_desc->pir[i];
3173 		if (pirval != 0) {
3174 			vpr = (i * 64 + flsl(pirval) - 1) & 0xf0;
3175 			return (vpr > ppr);
3176 		}
3177 	}
3178 	return (0);
3179 }
3180 
3181 static void
3182 vmx_intr_accepted(struct vlapic *vlapic, int vector)
3183 {
3184 
3185 	panic("vmx_intr_accepted: not expected to be called");
3186 }
3187 
3188 static void
3189 vmx_set_tmr(struct vlapic *vlapic, int vector, bool level)
3190 {
3191 	struct vlapic_vtx *vlapic_vtx;
3192 	struct vmx *vmx;
3193 	struct vmcs *vmcs;
3194 	uint64_t mask, val;
3195 
3196 	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
3197 	KASSERT(!vcpu_is_running(vlapic->vm, vlapic->vcpuid, NULL),
3198 	    ("vmx_set_tmr: vcpu cannot be running"));
3199 
3200 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3201 	vmx = vlapic_vtx->vmx;
3202 	vmcs = &vmx->vmcs[vlapic->vcpuid];
3203 	mask = 1UL << (vector % 64);
3204 
3205 	VMPTRLD(vmcs);
3206 	val = vmcs_read(VMCS_EOI_EXIT(vector));
3207 	if (level)
3208 		val |= mask;
3209 	else
3210 		val &= ~mask;
3211 	vmcs_write(VMCS_EOI_EXIT(vector), val);
3212 	VMCLEAR(vmcs);
3213 }
3214 
3215 static void
3216 vmx_enable_x2apic_mode(struct vlapic *vlapic)
3217 {
3218 	struct vmx *vmx;
3219 	struct vmcs *vmcs;
3220 	uint32_t proc_ctls2;
3221 	int vcpuid, error;
3222 
3223 	vcpuid = vlapic->vcpuid;
3224 	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3225 	vmcs = &vmx->vmcs[vcpuid];
3226 
3227 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3228 	KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3229 	    ("%s: invalid proc_ctls2 %#x", __func__, proc_ctls2));
3230 
3231 	proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3232 	proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3233 	vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3234 
3235 	VMPTRLD(vmcs);
3236 	vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3237 	VMCLEAR(vmcs);
3238 
3239 	if (vlapic->vcpuid == 0) {
3240 		/*
3241 		 * The nested page table mappings are shared by all vcpus
3242 		 * so unmap the APIC access page just once.
3243 		 */
3244 		error = vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
3245 		KASSERT(error == 0, ("%s: vm_unmap_mmio error %d",
3246 		    __func__, error));
3247 
3248 		/*
3249 		 * The MSR bitmap is shared by all vcpus so modify it only
3250 		 * once in the context of vcpu 0.
3251 		 */
3252 		error = vmx_allow_x2apic_msrs(vmx);
3253 		KASSERT(error == 0, ("%s: vmx_allow_x2apic_msrs error %d",
3254 		    __func__, error));
3255 	}
3256 }
3257 
3258 static void
3259 vmx_post_intr(struct vlapic *vlapic, int hostcpu)
3260 {
3261 
3262 	ipi_cpu(hostcpu, pirvec);
3263 }
3264 
3265 /*
3266  * Transfer the pending interrupts in the PIR descriptor to the IRR
3267  * in the virtual APIC page.
3268  */
3269 static void
3270 vmx_inject_pir(struct vlapic *vlapic)
3271 {
3272 	struct vlapic_vtx *vlapic_vtx;
3273 	struct pir_desc *pir_desc;
3274 	struct LAPIC *lapic;
3275 	uint64_t val, pirval;
3276 	int rvi, pirbase = -1;
3277 	uint16_t intr_status_old, intr_status_new;
3278 
3279 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3280 	pir_desc = vlapic_vtx->pir_desc;
3281 	if (atomic_cmpset_long(&pir_desc->pending, 1, 0) == 0) {
3282 		VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3283 		    "no posted interrupt pending");
3284 		return;
3285 	}
3286 
3287 	pirval = 0;
3288 	pirbase = -1;
3289 	lapic = vlapic->apic_page;
3290 
3291 	val = atomic_readandclear_long(&pir_desc->pir[0]);
3292 	if (val != 0) {
3293 		lapic->irr0 |= val;
3294 		lapic->irr1 |= val >> 32;
3295 		pirbase = 0;
3296 		pirval = val;
3297 	}
3298 
3299 	val = atomic_readandclear_long(&pir_desc->pir[1]);
3300 	if (val != 0) {
3301 		lapic->irr2 |= val;
3302 		lapic->irr3 |= val >> 32;
3303 		pirbase = 64;
3304 		pirval = val;
3305 	}
3306 
3307 	val = atomic_readandclear_long(&pir_desc->pir[2]);
3308 	if (val != 0) {
3309 		lapic->irr4 |= val;
3310 		lapic->irr5 |= val >> 32;
3311 		pirbase = 128;
3312 		pirval = val;
3313 	}
3314 
3315 	val = atomic_readandclear_long(&pir_desc->pir[3]);
3316 	if (val != 0) {
3317 		lapic->irr6 |= val;
3318 		lapic->irr7 |= val >> 32;
3319 		pirbase = 192;
3320 		pirval = val;
3321 	}
3322 
3323 	VLAPIC_CTR_IRR(vlapic, "vmx_inject_pir");
3324 
3325 	/*
3326 	 * Update RVI so the processor can evaluate pending virtual
3327 	 * interrupts on VM-entry.
3328 	 *
3329 	 * It is possible for pirval to be 0 here, even though the
3330 	 * pending bit has been set. The scenario is:
3331 	 * CPU-Y is sending a posted interrupt to CPU-X, which
3332 	 * is running a guest and processing posted interrupts in h/w.
3333 	 * CPU-X will eventually exit and the state seen in s/w is
3334 	 * the pending bit set, but no PIR bits set.
3335 	 *
3336 	 *      CPU-X                      CPU-Y
3337 	 *   (vm running)                (host running)
3338 	 *   rx posted interrupt
3339 	 *   CLEAR pending bit
3340 	 *				 SET PIR bit
3341 	 *   READ/CLEAR PIR bits
3342 	 *				 SET pending bit
3343 	 *   (vm exit)
3344 	 *   pending bit set, PIR 0
3345 	 */
3346 	if (pirval != 0) {
3347 		rvi = pirbase + flsl(pirval) - 1;
3348 		intr_status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
3349 		intr_status_new = (intr_status_old & 0xFF00) | rvi;
3350 		if (intr_status_new > intr_status_old) {
3351 			vmcs_write(VMCS_GUEST_INTR_STATUS, intr_status_new);
3352 			VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vmx_inject_pir: "
3353 			    "guest_intr_status changed from 0x%04x to 0x%04x",
3354 			    intr_status_old, intr_status_new);
3355 		}
3356 	}
3357 }
3358 
3359 static struct vlapic *
3360 vmx_vlapic_init(void *arg, int vcpuid)
3361 {
3362 	struct vmx *vmx;
3363 	struct vlapic *vlapic;
3364 	struct vlapic_vtx *vlapic_vtx;
3365 
3366 	vmx = arg;
3367 
3368 	vlapic = malloc(sizeof(struct vlapic_vtx), M_VLAPIC, M_WAITOK | M_ZERO);
3369 	vlapic->vm = vmx->vm;
3370 	vlapic->vcpuid = vcpuid;
3371 	vlapic->apic_page = (struct LAPIC *)&vmx->apic_page[vcpuid];
3372 
3373 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3374 	vlapic_vtx->pir_desc = &vmx->pir_desc[vcpuid];
3375 	vlapic_vtx->vmx = vmx;
3376 
3377 	if (virtual_interrupt_delivery) {
3378 		vlapic->ops.set_intr_ready = vmx_set_intr_ready;
3379 		vlapic->ops.pending_intr = vmx_pending_intr;
3380 		vlapic->ops.intr_accepted = vmx_intr_accepted;
3381 		vlapic->ops.set_tmr = vmx_set_tmr;
3382 		vlapic->ops.enable_x2apic_mode = vmx_enable_x2apic_mode;
3383 	}
3384 
3385 	if (posted_interrupts)
3386 		vlapic->ops.post_intr = vmx_post_intr;
3387 
3388 	vlapic_init(vlapic);
3389 
3390 	return (vlapic);
3391 }
3392 
3393 static void
3394 vmx_vlapic_cleanup(void *arg, struct vlapic *vlapic)
3395 {
3396 
3397 	vlapic_cleanup(vlapic);
3398 	free(vlapic, M_VLAPIC);
3399 }
3400 
3401 struct vmm_ops vmm_ops_intel = {
3402 	vmx_init,
3403 	vmx_cleanup,
3404 	vmx_restore,
3405 	vmx_vminit,
3406 	vmx_run,
3407 	vmx_vmcleanup,
3408 	vmx_getreg,
3409 	vmx_setreg,
3410 	vmx_getdesc,
3411 	vmx_setdesc,
3412 	vmx_getcap,
3413 	vmx_setcap,
3414 	ept_vmspace_alloc,
3415 	ept_vmspace_free,
3416 	vmx_vlapic_init,
3417 	vmx_vlapic_cleanup,
3418 };
3419