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