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