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