xref: /illumos-gate/usr/src/uts/intel/io/vmm/intel/vmx.c (revision d4f59ae5)
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  * This file and its contents are supplied under the terms of the
33  * Common Development and Distribution License ("CDDL"), version 1.0.
34  * You may only use this file in accordance with the terms of version
35  * 1.0 of the CDDL.
36  *
37  * A full copy of the text of the CDDL should have accompanied this
38  * source.  A copy of the CDDL is also available via the Internet at
39  * http://www.illumos.org/license/CDDL.
40  *
41  * Copyright 2015 Pluribus Networks Inc.
42  * Copyright 2018 Joyent, Inc.
43  * Copyright 2022 Oxide Computer Company
44  */
45 
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/kernel.h>
52 #include <sys/malloc.h>
53 #include <sys/pcpu.h>
54 #include <sys/proc.h>
55 #include <sys/sysctl.h>
56 
57 #include <sys/x86_archext.h>
58 #include <sys/smp_impldefs.h>
59 #include <sys/smt.h>
60 #include <sys/hma.h>
61 #include <sys/trap.h>
62 #include <sys/archsystm.h>
63 
64 #include <machine/psl.h>
65 #include <machine/cpufunc.h>
66 #include <machine/md_var.h>
67 #include <machine/reg.h>
68 #include <machine/segments.h>
69 #include <machine/specialreg.h>
70 #include <machine/vmparam.h>
71 #include <sys/vmm_vm.h>
72 #include <sys/vmm_kernel.h>
73 
74 #include <machine/vmm.h>
75 #include <machine/vmm_dev.h>
76 #include <sys/vmm_instruction_emul.h>
77 #include "vmm_lapic.h"
78 #include "vmm_host.h"
79 #include "vmm_ioport.h"
80 #include "vmm_stat.h"
81 #include "vatpic.h"
82 #include "vlapic.h"
83 #include "vlapic_priv.h"
84 
85 #include "vmcs.h"
86 #include "vmx.h"
87 #include "vmx_msr.h"
88 #include "x86.h"
89 #include "vmx_controls.h"
90 
91 #define	PINBASED_CTLS_ONE_SETTING					\
92 	(PINBASED_EXTINT_EXITING	|				\
93 	PINBASED_NMI_EXITING		|				\
94 	PINBASED_VIRTUAL_NMI)
95 #define	PINBASED_CTLS_ZERO_SETTING	0
96 
97 #define	PROCBASED_CTLS_WINDOW_SETTING					\
98 	(PROCBASED_INT_WINDOW_EXITING	|				\
99 	PROCBASED_NMI_WINDOW_EXITING)
100 
101 /* We consider TSC offset a necessity for unsynched TSC handling */
102 #define	PROCBASED_CTLS_ONE_SETTING					\
103 	(PROCBASED_SECONDARY_CONTROLS	|				\
104 	PROCBASED_TSC_OFFSET		|				\
105 	PROCBASED_MWAIT_EXITING		|				\
106 	PROCBASED_MONITOR_EXITING	|				\
107 	PROCBASED_IO_EXITING		|				\
108 	PROCBASED_MSR_BITMAPS		|				\
109 	PROCBASED_CTLS_WINDOW_SETTING	|				\
110 	PROCBASED_CR8_LOAD_EXITING	|				\
111 	PROCBASED_CR8_STORE_EXITING)
112 
113 #define	PROCBASED_CTLS_ZERO_SETTING	\
114 	(PROCBASED_CR3_LOAD_EXITING |	\
115 	PROCBASED_CR3_STORE_EXITING |	\
116 	PROCBASED_IO_BITMAPS)
117 
118 /*
119  * EPT and Unrestricted Guest are considered necessities.  The latter is not a
120  * requirement on FreeBSD, where grub2-bhyve is used to load guests directly
121  * without a bootrom starting in real mode.
122  */
123 #define	PROCBASED_CTLS2_ONE_SETTING		\
124 	(PROCBASED2_ENABLE_EPT |		\
125 	PROCBASED2_UNRESTRICTED_GUEST)
126 #define	PROCBASED_CTLS2_ZERO_SETTING	0
127 
128 #define	VM_EXIT_CTLS_ONE_SETTING					\
129 	(VM_EXIT_SAVE_DEBUG_CONTROLS		|			\
130 	VM_EXIT_HOST_LMA			|			\
131 	VM_EXIT_LOAD_PAT			|			\
132 	VM_EXIT_SAVE_EFER			|			\
133 	VM_EXIT_LOAD_EFER			|			\
134 	VM_EXIT_ACKNOWLEDGE_INTERRUPT)
135 
136 #define	VM_EXIT_CTLS_ZERO_SETTING	0
137 
138 #define	VM_ENTRY_CTLS_ONE_SETTING					\
139 	(VM_ENTRY_LOAD_DEBUG_CONTROLS		|			\
140 	VM_ENTRY_LOAD_EFER)
141 
142 #define	VM_ENTRY_CTLS_ZERO_SETTING					\
143 	(VM_ENTRY_INTO_SMM			|			\
144 	VM_ENTRY_DEACTIVATE_DUAL_MONITOR)
145 
146 /*
147  * Cover the EPT capabilities used by bhyve at present:
148  * - 4-level page walks
149  * - write-back memory type
150  * - INVEPT operations (all types)
151  * - INVVPID operations (single-context only)
152  */
153 #define	EPT_CAPS_REQUIRED			\
154 	(IA32_VMX_EPT_VPID_PWL4 |		\
155 	IA32_VMX_EPT_VPID_TYPE_WB |		\
156 	IA32_VMX_EPT_VPID_INVEPT |		\
157 	IA32_VMX_EPT_VPID_INVEPT_SINGLE |	\
158 	IA32_VMX_EPT_VPID_INVEPT_ALL |		\
159 	IA32_VMX_EPT_VPID_INVVPID |		\
160 	IA32_VMX_EPT_VPID_INVVPID_SINGLE)
161 
162 #define	HANDLED		1
163 #define	UNHANDLED	0
164 
165 static MALLOC_DEFINE(M_VMX, "vmx", "vmx");
166 static MALLOC_DEFINE(M_VLAPIC, "vlapic", "vlapic");
167 
168 SYSCTL_DECL(_hw_vmm);
169 SYSCTL_NODE(_hw_vmm, OID_AUTO, vmx, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
170     NULL);
171 
172 static uint32_t pinbased_ctls, procbased_ctls, procbased_ctls2;
173 static uint32_t exit_ctls, entry_ctls;
174 
175 static uint64_t cr0_ones_mask, cr0_zeros_mask;
176 
177 static uint64_t cr4_ones_mask, cr4_zeros_mask;
178 
179 static int vmx_initialized;
180 
181 /* Do not flush RSB upon vmexit */
182 static int no_flush_rsb;
183 
184 /*
185  * Optional capabilities
186  */
187 
188 /* HLT triggers a VM-exit */
189 static int cap_halt_exit;
190 
191 /* PAUSE triggers a VM-exit */
192 static int cap_pause_exit;
193 
194 /* Monitor trap flag */
195 static int cap_monitor_trap;
196 
197 /* Guests are allowed to use INVPCID */
198 static int cap_invpcid;
199 
200 /* Extra capabilities (VMX_CAP_*) beyond the minimum */
201 static enum vmx_caps vmx_capabilities;
202 
203 /* APICv posted interrupt vector */
204 static int pirvec = -1;
205 
206 static uint_t vpid_alloc_failed;
207 
208 int guest_l1d_flush;
209 int guest_l1d_flush_sw;
210 
211 /* MSR save region is composed of an array of 'struct msr_entry' */
212 struct msr_entry {
213 	uint32_t	index;
214 	uint32_t	reserved;
215 	uint64_t	val;
216 };
217 
218 static struct msr_entry msr_load_list[1] __aligned(16);
219 
220 /*
221  * The definitions of SDT probes for VMX.
222  */
223 
224 /* BEGIN CSTYLED */
225 SDT_PROBE_DEFINE3(vmm, vmx, exit, entry,
226     "struct vmx *", "int", "struct vm_exit *");
227 
228 SDT_PROBE_DEFINE4(vmm, vmx, exit, taskswitch,
229     "struct vmx *", "int", "struct vm_exit *", "struct vm_task_switch *");
230 
231 SDT_PROBE_DEFINE4(vmm, vmx, exit, craccess,
232     "struct vmx *", "int", "struct vm_exit *", "uint64_t");
233 
234 SDT_PROBE_DEFINE4(vmm, vmx, exit, rdmsr,
235     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
236 
237 SDT_PROBE_DEFINE5(vmm, vmx, exit, wrmsr,
238     "struct vmx *", "int", "struct vm_exit *", "uint32_t", "uint64_t");
239 
240 SDT_PROBE_DEFINE3(vmm, vmx, exit, halt,
241     "struct vmx *", "int", "struct vm_exit *");
242 
243 SDT_PROBE_DEFINE3(vmm, vmx, exit, mtrap,
244     "struct vmx *", "int", "struct vm_exit *");
245 
246 SDT_PROBE_DEFINE3(vmm, vmx, exit, pause,
247     "struct vmx *", "int", "struct vm_exit *");
248 
249 SDT_PROBE_DEFINE3(vmm, vmx, exit, intrwindow,
250     "struct vmx *", "int", "struct vm_exit *");
251 
252 SDT_PROBE_DEFINE4(vmm, vmx, exit, interrupt,
253     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
254 
255 SDT_PROBE_DEFINE3(vmm, vmx, exit, nmiwindow,
256     "struct vmx *", "int", "struct vm_exit *");
257 
258 SDT_PROBE_DEFINE3(vmm, vmx, exit, inout,
259     "struct vmx *", "int", "struct vm_exit *");
260 
261 SDT_PROBE_DEFINE3(vmm, vmx, exit, cpuid,
262     "struct vmx *", "int", "struct vm_exit *");
263 
264 SDT_PROBE_DEFINE5(vmm, vmx, exit, exception,
265     "struct vmx *", "int", "struct vm_exit *", "uint32_t", "int");
266 
267 SDT_PROBE_DEFINE5(vmm, vmx, exit, nestedfault,
268     "struct vmx *", "int", "struct vm_exit *", "uint64_t", "uint64_t");
269 
270 SDT_PROBE_DEFINE4(vmm, vmx, exit, mmiofault,
271     "struct vmx *", "int", "struct vm_exit *", "uint64_t");
272 
273 SDT_PROBE_DEFINE3(vmm, vmx, exit, eoi,
274     "struct vmx *", "int", "struct vm_exit *");
275 
276 SDT_PROBE_DEFINE3(vmm, vmx, exit, apicaccess,
277     "struct vmx *", "int", "struct vm_exit *");
278 
279 SDT_PROBE_DEFINE4(vmm, vmx, exit, apicwrite,
280     "struct vmx *", "int", "struct vm_exit *", "struct vlapic *");
281 
282 SDT_PROBE_DEFINE3(vmm, vmx, exit, xsetbv,
283     "struct vmx *", "int", "struct vm_exit *");
284 
285 SDT_PROBE_DEFINE3(vmm, vmx, exit, monitor,
286     "struct vmx *", "int", "struct vm_exit *");
287 
288 SDT_PROBE_DEFINE3(vmm, vmx, exit, mwait,
289     "struct vmx *", "int", "struct vm_exit *");
290 
291 SDT_PROBE_DEFINE3(vmm, vmx, exit, vminsn,
292     "struct vmx *", "int", "struct vm_exit *");
293 
294 SDT_PROBE_DEFINE4(vmm, vmx, exit, unknown,
295     "struct vmx *", "int", "struct vm_exit *", "uint32_t");
296 
297 SDT_PROBE_DEFINE4(vmm, vmx, exit, return,
298     "struct vmx *", "int", "struct vm_exit *", "int");
299 /* END CSTYLED */
300 
301 static int vmx_getdesc(void *arg, int vcpu, int reg, struct seg_desc *desc);
302 static int vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval);
303 static void vmx_apply_tsc_adjust(struct vmx *, int);
304 static void vmx_apicv_sync_tmr(struct vlapic *vlapic);
305 static void vmx_tpr_shadow_enter(struct vlapic *vlapic);
306 static void vmx_tpr_shadow_exit(struct vlapic *vlapic);
307 
308 static void
309 vmx_allow_x2apic_msrs(struct vmx *vmx, int vcpuid)
310 {
311 	/*
312 	 * Allow readonly access to the following x2APIC MSRs from the guest.
313 	 */
314 	guest_msr_ro(vmx, vcpuid, MSR_APIC_ID);
315 	guest_msr_ro(vmx, vcpuid, MSR_APIC_VERSION);
316 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LDR);
317 	guest_msr_ro(vmx, vcpuid, MSR_APIC_SVR);
318 
319 	for (uint_t i = 0; i < 8; i++) {
320 		guest_msr_ro(vmx, vcpuid, MSR_APIC_ISR0 + i);
321 		guest_msr_ro(vmx, vcpuid, MSR_APIC_TMR0 + i);
322 		guest_msr_ro(vmx, vcpuid, MSR_APIC_IRR0 + i);
323 	}
324 
325 	guest_msr_ro(vmx, vcpuid, MSR_APIC_ESR);
326 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_TIMER);
327 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_THERMAL);
328 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_PCINT);
329 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_LINT0);
330 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_LINT1);
331 	guest_msr_ro(vmx, vcpuid, MSR_APIC_LVT_ERROR);
332 	guest_msr_ro(vmx, vcpuid, MSR_APIC_ICR_TIMER);
333 	guest_msr_ro(vmx, vcpuid, MSR_APIC_DCR_TIMER);
334 	guest_msr_ro(vmx, vcpuid, MSR_APIC_ICR);
335 
336 	/*
337 	 * Allow TPR, EOI and SELF_IPI MSRs to be read and written by the guest.
338 	 *
339 	 * These registers get special treatment described in the section
340 	 * "Virtualizing MSR-Based APIC Accesses".
341 	 */
342 	guest_msr_rw(vmx, vcpuid, MSR_APIC_TPR);
343 	guest_msr_rw(vmx, vcpuid, MSR_APIC_EOI);
344 	guest_msr_rw(vmx, vcpuid, MSR_APIC_SELF_IPI);
345 }
346 
347 static ulong_t
348 vmx_fix_cr0(ulong_t cr0)
349 {
350 	return ((cr0 | cr0_ones_mask) & ~cr0_zeros_mask);
351 }
352 
353 /*
354  * Given a live (VMCS-active) cr0 value, and its shadow counterpart, calculate
355  * the value observable from the guest.
356  */
357 static ulong_t
358 vmx_unshadow_cr0(uint64_t cr0, uint64_t shadow)
359 {
360 	return ((cr0 & ~cr0_ones_mask) |
361 	    (shadow & (cr0_zeros_mask | cr0_ones_mask)));
362 }
363 
364 static ulong_t
365 vmx_fix_cr4(ulong_t cr4)
366 {
367 	return ((cr4 | cr4_ones_mask) & ~cr4_zeros_mask);
368 }
369 
370 /*
371  * Given a live (VMCS-active) cr4 value, and its shadow counterpart, calculate
372  * the value observable from the guest.
373  */
374 static ulong_t
375 vmx_unshadow_cr4(uint64_t cr4, uint64_t shadow)
376 {
377 	return ((cr4 & ~cr4_ones_mask) |
378 	    (shadow & (cr4_zeros_mask | cr4_ones_mask)));
379 }
380 
381 static void
382 vpid_free(int vpid)
383 {
384 	if (vpid < 0 || vpid > 0xffff)
385 		panic("vpid_free: invalid vpid %d", vpid);
386 
387 	/*
388 	 * VPIDs [0,VM_MAXCPU] are special and are not allocated from
389 	 * the unit number allocator.
390 	 */
391 
392 	if (vpid > VM_MAXCPU)
393 		hma_vmx_vpid_free((uint16_t)vpid);
394 }
395 
396 static void
397 vpid_alloc(uint16_t *vpid, int num)
398 {
399 	int i, x;
400 
401 	if (num <= 0 || num > VM_MAXCPU)
402 		panic("invalid number of vpids requested: %d", num);
403 
404 	/*
405 	 * If the "enable vpid" execution control is not enabled then the
406 	 * VPID is required to be 0 for all vcpus.
407 	 */
408 	if ((procbased_ctls2 & PROCBASED2_ENABLE_VPID) == 0) {
409 		for (i = 0; i < num; i++)
410 			vpid[i] = 0;
411 		return;
412 	}
413 
414 	/*
415 	 * Allocate a unique VPID for each vcpu from the unit number allocator.
416 	 */
417 	for (i = 0; i < num; i++) {
418 		uint16_t tmp;
419 
420 		tmp = hma_vmx_vpid_alloc();
421 		x = (tmp == 0) ? -1 : tmp;
422 
423 		if (x == -1)
424 			break;
425 		else
426 			vpid[i] = x;
427 	}
428 
429 	if (i < num) {
430 		atomic_add_int(&vpid_alloc_failed, 1);
431 
432 		/*
433 		 * If the unit number allocator does not have enough unique
434 		 * VPIDs then we need to allocate from the [1,VM_MAXCPU] range.
435 		 *
436 		 * These VPIDs are not be unique across VMs but this does not
437 		 * affect correctness because the combined mappings are also
438 		 * tagged with the EP4TA which is unique for each VM.
439 		 *
440 		 * It is still sub-optimal because the invvpid will invalidate
441 		 * combined mappings for a particular VPID across all EP4TAs.
442 		 */
443 		while (i-- > 0)
444 			vpid_free(vpid[i]);
445 
446 		for (i = 0; i < num; i++)
447 			vpid[i] = i + 1;
448 	}
449 }
450 
451 static int
452 vmx_cleanup(void)
453 {
454 	/* This is taken care of by the hma registration */
455 	return (0);
456 }
457 
458 static void
459 vmx_restore(void)
460 {
461 	/* No-op on illumos */
462 }
463 
464 static int
465 vmx_init(void)
466 {
467 	int error;
468 	uint64_t fixed0, fixed1;
469 	uint32_t tmp;
470 	enum vmx_caps avail_caps = VMX_CAP_NONE;
471 
472 	/* Check support for primary processor-based VM-execution controls */
473 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
474 	    MSR_VMX_TRUE_PROCBASED_CTLS,
475 	    PROCBASED_CTLS_ONE_SETTING,
476 	    PROCBASED_CTLS_ZERO_SETTING, &procbased_ctls);
477 	if (error) {
478 		printf("vmx_init: processor does not support desired primary "
479 		    "processor-based controls\n");
480 		return (error);
481 	}
482 
483 	/* Clear the processor-based ctl bits that are set on demand */
484 	procbased_ctls &= ~PROCBASED_CTLS_WINDOW_SETTING;
485 
486 	/* Check support for secondary processor-based VM-execution controls */
487 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
488 	    MSR_VMX_PROCBASED_CTLS2,
489 	    PROCBASED_CTLS2_ONE_SETTING,
490 	    PROCBASED_CTLS2_ZERO_SETTING, &procbased_ctls2);
491 	if (error) {
492 		printf("vmx_init: processor does not support desired secondary "
493 		    "processor-based controls\n");
494 		return (error);
495 	}
496 
497 	/* Check support for VPID */
498 	error = vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
499 	    MSR_VMX_PROCBASED_CTLS2,
500 	    PROCBASED2_ENABLE_VPID,
501 	    0, &tmp);
502 	if (error == 0)
503 		procbased_ctls2 |= PROCBASED2_ENABLE_VPID;
504 
505 	/* Check support for pin-based VM-execution controls */
506 	error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
507 	    MSR_VMX_TRUE_PINBASED_CTLS,
508 	    PINBASED_CTLS_ONE_SETTING,
509 	    PINBASED_CTLS_ZERO_SETTING, &pinbased_ctls);
510 	if (error) {
511 		printf("vmx_init: processor does not support desired "
512 		    "pin-based controls\n");
513 		return (error);
514 	}
515 
516 	/* Check support for VM-exit controls */
517 	error = vmx_set_ctlreg(MSR_VMX_EXIT_CTLS, MSR_VMX_TRUE_EXIT_CTLS,
518 	    VM_EXIT_CTLS_ONE_SETTING,
519 	    VM_EXIT_CTLS_ZERO_SETTING,
520 	    &exit_ctls);
521 	if (error) {
522 		printf("vmx_init: processor does not support desired "
523 		    "exit controls\n");
524 		return (error);
525 	}
526 
527 	/* Check support for VM-entry controls */
528 	error = vmx_set_ctlreg(MSR_VMX_ENTRY_CTLS, MSR_VMX_TRUE_ENTRY_CTLS,
529 	    VM_ENTRY_CTLS_ONE_SETTING, VM_ENTRY_CTLS_ZERO_SETTING,
530 	    &entry_ctls);
531 	if (error) {
532 		printf("vmx_init: processor does not support desired "
533 		    "entry controls\n");
534 		return (error);
535 	}
536 
537 	/*
538 	 * Check support for optional features by testing them
539 	 * as individual bits
540 	 */
541 	cap_halt_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
542 	    MSR_VMX_TRUE_PROCBASED_CTLS,
543 	    PROCBASED_HLT_EXITING, 0,
544 	    &tmp) == 0);
545 
546 	cap_monitor_trap = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
547 	    MSR_VMX_PROCBASED_CTLS,
548 	    PROCBASED_MTF, 0,
549 	    &tmp) == 0);
550 
551 	cap_pause_exit = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS,
552 	    MSR_VMX_TRUE_PROCBASED_CTLS,
553 	    PROCBASED_PAUSE_EXITING, 0,
554 	    &tmp) == 0);
555 
556 	cap_invpcid = (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
557 	    MSR_VMX_PROCBASED_CTLS2, PROCBASED2_ENABLE_INVPCID, 0,
558 	    &tmp) == 0);
559 
560 	/*
561 	 * Check for APIC virtualization capabilities:
562 	 * - TPR shadowing
563 	 * - Full APICv (with or without x2APIC support)
564 	 * - Posted interrupt handling
565 	 */
566 	if (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS, MSR_VMX_TRUE_PROCBASED_CTLS,
567 	    PROCBASED_USE_TPR_SHADOW, 0, &tmp) == 0) {
568 		avail_caps |= VMX_CAP_TPR_SHADOW;
569 
570 		const uint32_t apicv_bits =
571 		    PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
572 		    PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
573 		    PROCBASED2_VIRTUALIZE_X2APIC_MODE |
574 		    PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY;
575 		if (vmx_set_ctlreg(MSR_VMX_PROCBASED_CTLS2,
576 		    MSR_VMX_PROCBASED_CTLS2, apicv_bits, 0, &tmp) == 0) {
577 			avail_caps |= VMX_CAP_APICV;
578 
579 			/*
580 			 * It may make sense in the future to differentiate
581 			 * hardware (or software) configurations with APICv but
582 			 * no support for accelerating x2APIC mode.
583 			 */
584 			avail_caps |= VMX_CAP_APICV_X2APIC;
585 
586 			error = vmx_set_ctlreg(MSR_VMX_PINBASED_CTLS,
587 			    MSR_VMX_TRUE_PINBASED_CTLS,
588 			    PINBASED_POSTED_INTERRUPT, 0, &tmp);
589 			if (error == 0) {
590 				/*
591 				 * If the PSM-provided interfaces for requesting
592 				 * and using a PIR IPI vector are present, use
593 				 * them for posted interrupts.
594 				 */
595 				if (psm_get_pir_ipivect != NULL &&
596 				    psm_send_pir_ipi != NULL) {
597 					pirvec = psm_get_pir_ipivect();
598 					avail_caps |= VMX_CAP_APICV_PIR;
599 				}
600 			}
601 		}
602 	}
603 
604 	/*
605 	 * Check for necessary EPT capabilities
606 	 *
607 	 * TODO: Properly handle when IA32_VMX_EPT_VPID_HW_AD is missing and the
608 	 * hypervisor intends to utilize dirty page tracking.
609 	 */
610 	uint64_t ept_caps = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
611 	if ((ept_caps & EPT_CAPS_REQUIRED) != EPT_CAPS_REQUIRED) {
612 		cmn_err(CE_WARN, "!Inadequate EPT capabilities: %lx", ept_caps);
613 		return (EINVAL);
614 	}
615 
616 #ifdef __FreeBSD__
617 	guest_l1d_flush = (cpu_ia32_arch_caps &
618 	    IA32_ARCH_CAP_SKIP_L1DFL_VMENTRY) == 0;
619 	TUNABLE_INT_FETCH("hw.vmm.l1d_flush", &guest_l1d_flush);
620 
621 	/*
622 	 * L1D cache flush is enabled.  Use IA32_FLUSH_CMD MSR when
623 	 * available.  Otherwise fall back to the software flush
624 	 * method which loads enough data from the kernel text to
625 	 * flush existing L1D content, both on VMX entry and on NMI
626 	 * return.
627 	 */
628 	if (guest_l1d_flush) {
629 		if ((cpu_stdext_feature3 & CPUID_STDEXT3_L1D_FLUSH) == 0) {
630 			guest_l1d_flush_sw = 1;
631 			TUNABLE_INT_FETCH("hw.vmm.l1d_flush_sw",
632 			    &guest_l1d_flush_sw);
633 		}
634 		if (guest_l1d_flush_sw) {
635 			if (nmi_flush_l1d_sw <= 1)
636 				nmi_flush_l1d_sw = 1;
637 		} else {
638 			msr_load_list[0].index = MSR_IA32_FLUSH_CMD;
639 			msr_load_list[0].val = IA32_FLUSH_CMD_L1D;
640 		}
641 	}
642 #else
643 	/* L1D flushing is taken care of by smt_acquire() and friends */
644 	guest_l1d_flush = 0;
645 #endif /* __FreeBSD__ */
646 
647 	/*
648 	 * Stash the cr0 and cr4 bits that must be fixed to 0 or 1
649 	 */
650 	fixed0 = rdmsr(MSR_VMX_CR0_FIXED0);
651 	fixed1 = rdmsr(MSR_VMX_CR0_FIXED1);
652 	cr0_ones_mask = fixed0 & fixed1;
653 	cr0_zeros_mask = ~fixed0 & ~fixed1;
654 
655 	/*
656 	 * Since Unrestricted Guest was already verified present, CR0_PE and
657 	 * CR0_PG are allowed to be set to zero in VMX non-root operation
658 	 */
659 	cr0_ones_mask &= ~(CR0_PG | CR0_PE);
660 
661 	/*
662 	 * Do not allow the guest to set CR0_NW or CR0_CD.
663 	 */
664 	cr0_zeros_mask |= (CR0_NW | CR0_CD);
665 
666 	fixed0 = rdmsr(MSR_VMX_CR4_FIXED0);
667 	fixed1 = rdmsr(MSR_VMX_CR4_FIXED1);
668 	cr4_ones_mask = fixed0 & fixed1;
669 	cr4_zeros_mask = ~fixed0 & ~fixed1;
670 
671 	vmx_msr_init();
672 
673 	vmx_capabilities = avail_caps;
674 	vmx_initialized = 1;
675 
676 	return (0);
677 }
678 
679 static void
680 vmx_trigger_hostintr(int vector)
681 {
682 	VERIFY(vector >= 32 && vector <= 255);
683 	vmx_call_isr(vector - 32);
684 }
685 
686 static void *
687 vmx_vminit(struct vm *vm)
688 {
689 	uint16_t vpid[VM_MAXCPU];
690 	int i, error, datasel;
691 	struct vmx *vmx;
692 	uint32_t exc_bitmap;
693 	uint16_t maxcpus;
694 	uint32_t proc_ctls, proc2_ctls, pin_ctls;
695 	uint64_t apic_access_pa = UINT64_MAX;
696 
697 	vmx = malloc(sizeof (struct vmx), M_VMX, M_WAITOK | M_ZERO);
698 	if ((uintptr_t)vmx & PAGE_MASK) {
699 		panic("malloc of struct vmx not aligned on %d byte boundary",
700 		    PAGE_SIZE);
701 	}
702 	vmx->vm = vm;
703 
704 	vmx->eptp = vmspace_table_root(vm_get_vmspace(vm));
705 
706 	/*
707 	 * Clean up EP4TA-tagged guest-physical and combined mappings
708 	 *
709 	 * VMX transitions are not required to invalidate any guest physical
710 	 * mappings. So, it may be possible for stale guest physical mappings
711 	 * to be present in the processor TLBs.
712 	 *
713 	 * Combined mappings for this EP4TA are also invalidated for all VPIDs.
714 	 */
715 	hma_vmx_invept_allcpus((uintptr_t)vmx->eptp);
716 
717 	vmx_msr_bitmap_initialize(vmx);
718 
719 	vpid_alloc(vpid, VM_MAXCPU);
720 
721 	/* Grab the established defaults */
722 	proc_ctls = procbased_ctls;
723 	proc2_ctls = procbased_ctls2;
724 	pin_ctls = pinbased_ctls;
725 	/* For now, default to the available capabilities */
726 	vmx->vmx_caps = vmx_capabilities;
727 
728 	if (vmx_cap_en(vmx, VMX_CAP_TPR_SHADOW)) {
729 		proc_ctls |= PROCBASED_USE_TPR_SHADOW;
730 		proc_ctls &= ~PROCBASED_CR8_LOAD_EXITING;
731 		proc_ctls &= ~PROCBASED_CR8_STORE_EXITING;
732 	}
733 	if (vmx_cap_en(vmx, VMX_CAP_APICV)) {
734 		ASSERT(vmx_cap_en(vmx, VMX_CAP_TPR_SHADOW));
735 
736 		proc2_ctls |= (PROCBASED2_VIRTUALIZE_APIC_ACCESSES |
737 		    PROCBASED2_APIC_REGISTER_VIRTUALIZATION |
738 		    PROCBASED2_VIRTUAL_INTERRUPT_DELIVERY);
739 
740 		/*
741 		 * Allocate a page of memory to back the APIC access address for
742 		 * when APICv features are in use.  Guest MMIO accesses should
743 		 * never actually reach this page, but rather be intercepted.
744 		 */
745 		vmx->apic_access_page = kmem_zalloc(PAGESIZE, KM_SLEEP);
746 		VERIFY3U((uintptr_t)vmx->apic_access_page & PAGEOFFSET, ==, 0);
747 		apic_access_pa = vtophys(vmx->apic_access_page);
748 
749 		error = vm_map_mmio(vm, DEFAULT_APIC_BASE, PAGE_SIZE,
750 		    apic_access_pa);
751 		/* XXX this should really return an error to the caller */
752 		KASSERT(error == 0, ("vm_map_mmio(apicbase) error %d", error));
753 	}
754 	if (vmx_cap_en(vmx, VMX_CAP_APICV_PIR)) {
755 		ASSERT(vmx_cap_en(vmx, VMX_CAP_APICV));
756 
757 		pin_ctls |= PINBASED_POSTED_INTERRUPT;
758 	}
759 
760 	maxcpus = vm_get_maxcpus(vm);
761 	datasel = vmm_get_host_datasel();
762 	for (i = 0; i < maxcpus; i++) {
763 		/*
764 		 * Cache physical address lookups for various components which
765 		 * may be required inside the critical_enter() section implied
766 		 * by VMPTRLD() below.
767 		 */
768 		vm_paddr_t msr_bitmap_pa = vtophys(vmx->msr_bitmap[i]);
769 		vm_paddr_t apic_page_pa = vtophys(&vmx->apic_page[i]);
770 		vm_paddr_t pir_desc_pa = vtophys(&vmx->pir_desc[i]);
771 
772 		vmx->vmcs_pa[i] = (uintptr_t)vtophys(&vmx->vmcs[i]);
773 		vmcs_initialize(&vmx->vmcs[i], vmx->vmcs_pa[i]);
774 
775 		vmx_msr_guest_init(vmx, i);
776 
777 		vmcs_load(vmx->vmcs_pa[i]);
778 
779 		vmcs_write(VMCS_HOST_IA32_PAT, vmm_get_host_pat());
780 		vmcs_write(VMCS_HOST_IA32_EFER, vmm_get_host_efer());
781 
782 		/* Load the control registers */
783 		vmcs_write(VMCS_HOST_CR0, vmm_get_host_cr0());
784 		vmcs_write(VMCS_HOST_CR4, vmm_get_host_cr4() | CR4_VMXE);
785 
786 		/* Load the segment selectors */
787 		vmcs_write(VMCS_HOST_CS_SELECTOR, vmm_get_host_codesel());
788 
789 		vmcs_write(VMCS_HOST_ES_SELECTOR, datasel);
790 		vmcs_write(VMCS_HOST_SS_SELECTOR, datasel);
791 		vmcs_write(VMCS_HOST_DS_SELECTOR, datasel);
792 
793 		vmcs_write(VMCS_HOST_FS_SELECTOR, vmm_get_host_fssel());
794 		vmcs_write(VMCS_HOST_GS_SELECTOR, vmm_get_host_gssel());
795 		vmcs_write(VMCS_HOST_TR_SELECTOR, vmm_get_host_tsssel());
796 
797 		/*
798 		 * Configure host sysenter MSRs to be restored on VM exit.
799 		 * The thread-specific MSR_INTC_SEP_ESP value is loaded in
800 		 * vmx_run.
801 		 */
802 		vmcs_write(VMCS_HOST_IA32_SYSENTER_CS, KCS_SEL);
803 		vmcs_write(VMCS_HOST_IA32_SYSENTER_EIP,
804 		    rdmsr(MSR_SYSENTER_EIP_MSR));
805 
806 		/* instruction pointer */
807 		if (no_flush_rsb) {
808 			vmcs_write(VMCS_HOST_RIP, (uint64_t)vmx_exit_guest);
809 		} else {
810 			vmcs_write(VMCS_HOST_RIP,
811 			    (uint64_t)vmx_exit_guest_flush_rsb);
812 		}
813 
814 		/* link pointer */
815 		vmcs_write(VMCS_LINK_POINTER, ~0);
816 
817 		vmcs_write(VMCS_EPTP, vmx->eptp);
818 		vmcs_write(VMCS_PIN_BASED_CTLS, pin_ctls);
819 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, proc_ctls);
820 		vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc2_ctls);
821 		vmcs_write(VMCS_EXIT_CTLS, exit_ctls);
822 		vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
823 		vmcs_write(VMCS_MSR_BITMAP, msr_bitmap_pa);
824 		vmcs_write(VMCS_VPID, vpid[i]);
825 
826 		if (guest_l1d_flush && !guest_l1d_flush_sw) {
827 			vmcs_write(VMCS_ENTRY_MSR_LOAD,
828 			    vtophys(&msr_load_list[0]));
829 			vmcs_write(VMCS_ENTRY_MSR_LOAD_COUNT,
830 			    nitems(msr_load_list));
831 			vmcs_write(VMCS_EXIT_MSR_STORE, 0);
832 			vmcs_write(VMCS_EXIT_MSR_STORE_COUNT, 0);
833 		}
834 
835 		/* exception bitmap */
836 		if (vcpu_trace_exceptions(vm, i))
837 			exc_bitmap = 0xffffffff;
838 		else
839 			exc_bitmap = 1 << IDT_MC;
840 		vmcs_write(VMCS_EXCEPTION_BITMAP, exc_bitmap);
841 
842 		vmx->ctx[i].guest_dr6 = DBREG_DR6_RESERVED1;
843 		vmcs_write(VMCS_GUEST_DR7, DBREG_DR7_RESERVED1);
844 
845 		if (vmx_cap_en(vmx, VMX_CAP_TPR_SHADOW)) {
846 			vmcs_write(VMCS_VIRTUAL_APIC, apic_page_pa);
847 		}
848 
849 		if (vmx_cap_en(vmx, VMX_CAP_APICV)) {
850 			vmcs_write(VMCS_APIC_ACCESS, apic_access_pa);
851 			vmcs_write(VMCS_EOI_EXIT0, 0);
852 			vmcs_write(VMCS_EOI_EXIT1, 0);
853 			vmcs_write(VMCS_EOI_EXIT2, 0);
854 			vmcs_write(VMCS_EOI_EXIT3, 0);
855 		}
856 		if (vmx_cap_en(vmx, VMX_CAP_APICV_PIR)) {
857 			vmcs_write(VMCS_PIR_VECTOR, pirvec);
858 			vmcs_write(VMCS_PIR_DESC, pir_desc_pa);
859 		}
860 
861 		/*
862 		 * Set up the CR0/4 masks and configure the read shadow state
863 		 * to the power-on register value from the Intel Sys Arch.
864 		 *  CR0 - 0x60000010
865 		 *  CR4 - 0
866 		 */
867 		vmcs_write(VMCS_CR0_MASK, cr0_ones_mask | cr0_zeros_mask);
868 		vmcs_write(VMCS_CR0_SHADOW, 0x60000010);
869 		vmcs_write(VMCS_CR4_MASK, cr4_ones_mask | cr4_zeros_mask);
870 		vmcs_write(VMCS_CR4_SHADOW, 0);
871 
872 		vmcs_clear(vmx->vmcs_pa[i]);
873 
874 		vmx->cap[i].set = 0;
875 		vmx->cap[i].proc_ctls = proc_ctls;
876 		vmx->cap[i].proc_ctls2 = proc2_ctls;
877 		vmx->cap[i].exc_bitmap = exc_bitmap;
878 
879 		vmx->state[i].nextrip = ~0;
880 		vmx->state[i].lastcpu = NOCPU;
881 		vmx->state[i].vpid = vpid[i];
882 	}
883 
884 	return (vmx);
885 }
886 
887 static int
888 vmx_handle_cpuid(struct vm *vm, int vcpu, struct vmxctx *vmxctx)
889 {
890 	int handled;
891 
892 	handled = x86_emulate_cpuid(vm, vcpu, (uint64_t *)&vmxctx->guest_rax,
893 	    (uint64_t *)&vmxctx->guest_rbx, (uint64_t *)&vmxctx->guest_rcx,
894 	    (uint64_t *)&vmxctx->guest_rdx);
895 	return (handled);
896 }
897 
898 static VMM_STAT_INTEL(VCPU_INVVPID_SAVED, "Number of vpid invalidations saved");
899 static VMM_STAT_INTEL(VCPU_INVVPID_DONE, "Number of vpid invalidations done");
900 
901 #define	INVVPID_TYPE_ADDRESS		0UL
902 #define	INVVPID_TYPE_SINGLE_CONTEXT	1UL
903 #define	INVVPID_TYPE_ALL_CONTEXTS	2UL
904 
905 struct invvpid_desc {
906 	uint16_t	vpid;
907 	uint16_t	_res1;
908 	uint32_t	_res2;
909 	uint64_t	linear_addr;
910 };
911 CTASSERT(sizeof (struct invvpid_desc) == 16);
912 
913 static __inline void
914 invvpid(uint64_t type, struct invvpid_desc desc)
915 {
916 	int error;
917 
918 	DTRACE_PROBE3(vmx__invvpid, uint64_t, type, uint16_t, desc.vpid,
919 	    uint64_t, desc.linear_addr);
920 
921 	__asm __volatile("invvpid %[desc], %[type];"
922 	    VMX_SET_ERROR_CODE_ASM
923 	    : [error] "=r" (error)
924 	    : [desc] "m" (desc), [type] "r" (type)
925 	    : "memory");
926 
927 	if (error) {
928 		panic("invvpid error %d", error);
929 	}
930 }
931 
932 /*
933  * Invalidate guest mappings identified by its VPID from the TLB.
934  *
935  * This is effectively a flush of the guest TLB, removing only "combined
936  * mappings" (to use the VMX parlance).  Actions which modify the EPT structures
937  * for the instance (such as unmapping GPAs) would require an 'invept' flush.
938  */
939 static void
940 vmx_invvpid(struct vmx *vmx, int vcpu, int running)
941 {
942 	struct vmxstate *vmxstate;
943 	struct vmspace *vms;
944 
945 	vmxstate = &vmx->state[vcpu];
946 	if (vmxstate->vpid == 0) {
947 		return;
948 	}
949 
950 	if (!running) {
951 		/*
952 		 * Set the 'lastcpu' to an invalid host cpu.
953 		 *
954 		 * This will invalidate TLB entries tagged with the vcpu's
955 		 * vpid the next time it runs via vmx_set_pcpu_defaults().
956 		 */
957 		vmxstate->lastcpu = NOCPU;
958 		return;
959 	}
960 
961 	/*
962 	 * Invalidate all mappings tagged with 'vpid'
963 	 *
964 	 * This is done when a vCPU moves between host CPUs, where there may be
965 	 * stale TLB entries for this VPID on the target, or if emulated actions
966 	 * in the guest CPU have incurred an explicit TLB flush.
967 	 */
968 	vms = vm_get_vmspace(vmx->vm);
969 	if (vmspace_table_gen(vms) == vmx->eptgen[curcpu]) {
970 		struct invvpid_desc invvpid_desc = {
971 			.vpid = vmxstate->vpid,
972 			.linear_addr = 0,
973 			._res1 = 0,
974 			._res2 = 0,
975 		};
976 
977 		invvpid(INVVPID_TYPE_SINGLE_CONTEXT, invvpid_desc);
978 		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_DONE, 1);
979 	} else {
980 		/*
981 		 * The INVVPID can be skipped if an INVEPT is going to be
982 		 * performed before entering the guest.  The INVEPT will
983 		 * invalidate combined mappings for the EP4TA associated with
984 		 * this guest, in all VPIDs.
985 		 */
986 		vmm_stat_incr(vmx->vm, vcpu, VCPU_INVVPID_SAVED, 1);
987 	}
988 }
989 
990 static __inline void
991 invept(uint64_t type, uint64_t eptp)
992 {
993 	int error;
994 	struct invept_desc {
995 		uint64_t eptp;
996 		uint64_t _resv;
997 	} desc = { eptp, 0 };
998 
999 	DTRACE_PROBE2(vmx__invept, uint64_t, type, uint64_t, eptp);
1000 
1001 	__asm __volatile("invept %[desc], %[type];"
1002 	    VMX_SET_ERROR_CODE_ASM
1003 	    : [error] "=r" (error)
1004 	    : [desc] "m" (desc), [type] "r" (type)
1005 	    : "memory");
1006 
1007 	if (error != 0) {
1008 		panic("invvpid error %d", error);
1009 	}
1010 }
1011 
1012 static void
1013 vmx_set_pcpu_defaults(struct vmx *vmx, int vcpu)
1014 {
1015 	struct vmxstate *vmxstate;
1016 
1017 	/*
1018 	 * Regardless of whether the VM appears to have migrated between CPUs,
1019 	 * save the host sysenter stack pointer.  As it points to the kernel
1020 	 * stack of each thread, the correct value must be maintained for every
1021 	 * trip into the critical section.
1022 	 */
1023 	vmcs_write(VMCS_HOST_IA32_SYSENTER_ESP, rdmsr(MSR_SYSENTER_ESP_MSR));
1024 
1025 	/*
1026 	 * Perform any needed TSC_OFFSET adjustment based on TSC_MSR writes or
1027 	 * migration between host CPUs with differing TSC values.
1028 	 */
1029 	vmx_apply_tsc_adjust(vmx, vcpu);
1030 
1031 	vmxstate = &vmx->state[vcpu];
1032 	if (vmxstate->lastcpu == curcpu)
1033 		return;
1034 
1035 	vmxstate->lastcpu = curcpu;
1036 
1037 	vmm_stat_incr(vmx->vm, vcpu, VCPU_MIGRATIONS, 1);
1038 
1039 	/* Load the per-CPU IDT address */
1040 	vmcs_write(VMCS_HOST_IDTR_BASE, vmm_get_host_idtrbase());
1041 	vmcs_write(VMCS_HOST_TR_BASE, vmm_get_host_trbase());
1042 	vmcs_write(VMCS_HOST_GDTR_BASE, vmm_get_host_gdtrbase());
1043 	vmcs_write(VMCS_HOST_GS_BASE, vmm_get_host_gsbase());
1044 	vmx_invvpid(vmx, vcpu, 1);
1045 }
1046 
1047 /*
1048  * We depend on 'procbased_ctls' to have the Interrupt Window Exiting bit set.
1049  */
1050 CTASSERT((PROCBASED_CTLS_ONE_SETTING & PROCBASED_INT_WINDOW_EXITING) != 0);
1051 
1052 static __inline void
1053 vmx_set_int_window_exiting(struct vmx *vmx, int vcpu)
1054 {
1055 	if ((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) == 0) {
1056 		/* Enable interrupt window exiting */
1057 		vmx->cap[vcpu].proc_ctls |= PROCBASED_INT_WINDOW_EXITING;
1058 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1059 	}
1060 }
1061 
1062 static __inline void
1063 vmx_clear_int_window_exiting(struct vmx *vmx, int vcpu)
1064 {
1065 	KASSERT((vmx->cap[vcpu].proc_ctls & PROCBASED_INT_WINDOW_EXITING) != 0,
1066 	    ("intr_window_exiting not set: %x", vmx->cap[vcpu].proc_ctls));
1067 
1068 	/* Disable interrupt window exiting */
1069 	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_INT_WINDOW_EXITING;
1070 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1071 }
1072 
1073 static __inline bool
1074 vmx_nmi_window_exiting(struct vmx *vmx, int vcpu)
1075 {
1076 	return ((vmx->cap[vcpu].proc_ctls & PROCBASED_NMI_WINDOW_EXITING) != 0);
1077 }
1078 
1079 static __inline void
1080 vmx_set_nmi_window_exiting(struct vmx *vmx, int vcpu)
1081 {
1082 	if (!vmx_nmi_window_exiting(vmx, vcpu)) {
1083 		vmx->cap[vcpu].proc_ctls |= PROCBASED_NMI_WINDOW_EXITING;
1084 		vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1085 	}
1086 }
1087 
1088 static __inline void
1089 vmx_clear_nmi_window_exiting(struct vmx *vmx, int vcpu)
1090 {
1091 	ASSERT(vmx_nmi_window_exiting(vmx, vcpu));
1092 	vmx->cap[vcpu].proc_ctls &= ~PROCBASED_NMI_WINDOW_EXITING;
1093 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, vmx->cap[vcpu].proc_ctls);
1094 }
1095 
1096 /*
1097  * Set the TSC adjustment, taking into account the offsets measured between
1098  * host physical CPUs.  This is required even if the guest has not set a TSC
1099  * offset since vCPUs inherit the TSC offset of whatever physical CPU it has
1100  * migrated onto.  Without this mitigation, un-synched host TSCs will convey
1101  * the appearance of TSC time-travel to the guest as its vCPUs migrate.
1102  */
1103 static void
1104 vmx_apply_tsc_adjust(struct vmx *vmx, int vcpu)
1105 {
1106 	const uint64_t offset = vcpu_tsc_offset(vmx->vm, vcpu, true);
1107 
1108 	ASSERT(vmx->cap[vcpu].proc_ctls & PROCBASED_TSC_OFFSET);
1109 
1110 	if (vmx->tsc_offset_active[vcpu] != offset) {
1111 		vmcs_write(VMCS_TSC_OFFSET, offset);
1112 		vmx->tsc_offset_active[vcpu] = offset;
1113 	}
1114 }
1115 
1116 CTASSERT(VMCS_INTR_T_HWINTR		== VM_INTINFO_HWINTR);
1117 CTASSERT(VMCS_INTR_T_NMI		== VM_INTINFO_NMI);
1118 CTASSERT(VMCS_INTR_T_HWEXCEPTION	== VM_INTINFO_HWEXCP);
1119 CTASSERT(VMCS_INTR_T_SWINTR		== VM_INTINFO_SWINTR);
1120 CTASSERT(VMCS_INTR_T_PRIV_SWEXCEPTION	== VM_INTINFO_RESV5);
1121 CTASSERT(VMCS_INTR_T_SWEXCEPTION	== VM_INTINFO_RESV6);
1122 CTASSERT(VMCS_IDT_VEC_ERRCODE_VALID	== VM_INTINFO_DEL_ERRCODE);
1123 CTASSERT(VMCS_INTR_T_MASK		== VM_INTINFO_MASK_TYPE);
1124 
1125 static uint64_t
1126 vmx_idtvec_to_intinfo(uint32_t info)
1127 {
1128 	ASSERT(info & VMCS_IDT_VEC_VALID);
1129 
1130 	const uint32_t type = info & VMCS_INTR_T_MASK;
1131 	const uint8_t vec = info & 0xff;
1132 
1133 	switch (type) {
1134 	case VMCS_INTR_T_HWINTR:
1135 	case VMCS_INTR_T_NMI:
1136 	case VMCS_INTR_T_HWEXCEPTION:
1137 	case VMCS_INTR_T_SWINTR:
1138 	case VMCS_INTR_T_PRIV_SWEXCEPTION:
1139 	case VMCS_INTR_T_SWEXCEPTION:
1140 		break;
1141 	default:
1142 		panic("unexpected event type 0x%03x", type);
1143 	}
1144 
1145 	uint64_t intinfo = VM_INTINFO_VALID | type | vec;
1146 	if (info & VMCS_IDT_VEC_ERRCODE_VALID) {
1147 		const uint32_t errcode = vmcs_read(VMCS_IDT_VECTORING_ERROR);
1148 		intinfo |= (uint64_t)errcode << 32;
1149 	}
1150 
1151 	return (intinfo);
1152 }
1153 
1154 static void
1155 vmx_inject_intinfo(uint64_t info)
1156 {
1157 	ASSERT(VM_INTINFO_PENDING(info));
1158 	ASSERT0(info & VM_INTINFO_MASK_RSVD);
1159 
1160 	/*
1161 	 * The bhyve format matches that of the VMCS, which is ensured by the
1162 	 * CTASSERTs above.
1163 	 */
1164 	uint32_t inject = info;
1165 	switch (VM_INTINFO_VECTOR(info)) {
1166 	case IDT_BP:
1167 	case IDT_OF:
1168 		/*
1169 		 * VT-x requires #BP and #OF to be injected as software
1170 		 * exceptions.
1171 		 */
1172 		inject &= ~VMCS_INTR_T_MASK;
1173 		inject |= VMCS_INTR_T_SWEXCEPTION;
1174 		break;
1175 	default:
1176 		break;
1177 	}
1178 
1179 	if (VM_INTINFO_HAS_ERRCODE(info)) {
1180 		vmcs_write(VMCS_ENTRY_EXCEPTION_ERROR,
1181 		    VM_INTINFO_ERRCODE(info));
1182 	}
1183 	vmcs_write(VMCS_ENTRY_INTR_INFO, inject);
1184 }
1185 
1186 #define	NMI_BLOCKING	(VMCS_INTERRUPTIBILITY_NMI_BLOCKING |		\
1187 			VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1188 #define	HWINTR_BLOCKING	(VMCS_INTERRUPTIBILITY_STI_BLOCKING |		\
1189 			VMCS_INTERRUPTIBILITY_MOVSS_BLOCKING)
1190 
1191 static void
1192 vmx_inject_nmi(struct vmx *vmx, int vcpu)
1193 {
1194 	ASSERT0(vmcs_read(VMCS_GUEST_INTERRUPTIBILITY) & NMI_BLOCKING);
1195 	ASSERT0(vmcs_read(VMCS_ENTRY_INTR_INFO) & VMCS_INTR_VALID);
1196 
1197 	/*
1198 	 * Inject the virtual NMI. The vector must be the NMI IDT entry
1199 	 * or the VMCS entry check will fail.
1200 	 */
1201 	vmcs_write(VMCS_ENTRY_INTR_INFO,
1202 	    IDT_NMI | VMCS_INTR_T_NMI | VMCS_INTR_VALID);
1203 
1204 	/* Clear the request */
1205 	vm_nmi_clear(vmx->vm, vcpu);
1206 }
1207 
1208 /*
1209  * Inject exceptions, NMIs, and ExtINTs.
1210  *
1211  * The logic behind these are complicated and may involve mutex contention, so
1212  * the injection is performed without the protection of host CPU interrupts
1213  * being disabled.  This means a racing notification could be "lost",
1214  * necessitating a later call to vmx_inject_recheck() to close that window
1215  * of opportunity.
1216  */
1217 static enum event_inject_state
1218 vmx_inject_events(struct vmx *vmx, int vcpu, uint64_t rip)
1219 {
1220 	uint64_t entryinfo;
1221 	uint32_t gi, info;
1222 	int vector;
1223 	enum event_inject_state state;
1224 
1225 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1226 	info = vmcs_read(VMCS_ENTRY_INTR_INFO);
1227 	state = EIS_CAN_INJECT;
1228 
1229 	/* Clear any interrupt blocking if the guest %rip has changed */
1230 	if (vmx->state[vcpu].nextrip != rip && (gi & HWINTR_BLOCKING) != 0) {
1231 		gi &= ~HWINTR_BLOCKING;
1232 		vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1233 	}
1234 
1235 	/*
1236 	 * It could be that an interrupt is already pending for injection from
1237 	 * the VMCS.  This would be the case if the vCPU exited for conditions
1238 	 * such as an AST before a vm-entry delivered the injection.
1239 	 */
1240 	if ((info & VMCS_INTR_VALID) != 0) {
1241 		return (EIS_EV_EXISTING | EIS_REQ_EXIT);
1242 	}
1243 
1244 	if (vm_entry_intinfo(vmx->vm, vcpu, &entryinfo)) {
1245 		vmx_inject_intinfo(entryinfo);
1246 		state = EIS_EV_INJECTED;
1247 	}
1248 
1249 	if (vm_nmi_pending(vmx->vm, vcpu)) {
1250 		/*
1251 		 * If there are no conditions blocking NMI injection then inject
1252 		 * it directly here otherwise enable "NMI window exiting" to
1253 		 * inject it as soon as we can.
1254 		 *
1255 		 * According to the Intel manual, some CPUs do not allow NMI
1256 		 * injection when STI_BLOCKING is active.  That check is
1257 		 * enforced here, regardless of CPU capability.  If running on a
1258 		 * CPU without such a restriction it will immediately exit and
1259 		 * the NMI will be injected in the "NMI window exiting" handler.
1260 		 */
1261 		if ((gi & (HWINTR_BLOCKING | NMI_BLOCKING)) == 0) {
1262 			if (state == EIS_CAN_INJECT) {
1263 				vmx_inject_nmi(vmx, vcpu);
1264 				state = EIS_EV_INJECTED;
1265 			} else {
1266 				return (state | EIS_REQ_EXIT);
1267 			}
1268 		} else {
1269 			vmx_set_nmi_window_exiting(vmx, vcpu);
1270 		}
1271 	}
1272 
1273 	if (vm_extint_pending(vmx->vm, vcpu)) {
1274 		if (state != EIS_CAN_INJECT) {
1275 			return (state | EIS_REQ_EXIT);
1276 		}
1277 		if ((gi & HWINTR_BLOCKING) != 0 ||
1278 		    (vmcs_read(VMCS_GUEST_RFLAGS) & PSL_I) == 0) {
1279 			return (EIS_GI_BLOCK);
1280 		}
1281 
1282 		/* Ask the legacy pic for a vector to inject */
1283 		vatpic_pending_intr(vmx->vm, &vector);
1284 
1285 		/*
1286 		 * From the Intel SDM, Volume 3, Section "Maskable
1287 		 * Hardware Interrupts":
1288 		 * - maskable interrupt vectors [0,255] can be delivered
1289 		 *   through the INTR pin.
1290 		 */
1291 		KASSERT(vector >= 0 && vector <= 255,
1292 		    ("invalid vector %d from INTR", vector));
1293 
1294 		/* Inject the interrupt */
1295 		vmcs_write(VMCS_ENTRY_INTR_INFO,
1296 		    VMCS_INTR_T_HWINTR | VMCS_INTR_VALID | vector);
1297 
1298 		vm_extint_clear(vmx->vm, vcpu);
1299 		vatpic_intr_accepted(vmx->vm, vector);
1300 		state = EIS_EV_INJECTED;
1301 	}
1302 
1303 	return (state);
1304 }
1305 
1306 /*
1307  * Inject any interrupts pending on the vLAPIC.
1308  *
1309  * This is done with host CPU interrupts disabled so notification IPIs, either
1310  * from the standard vCPU notification or APICv posted interrupts, will be
1311  * queued on the host APIC and recognized when entering VMX context.
1312  */
1313 static enum event_inject_state
1314 vmx_inject_vlapic(struct vmx *vmx, int vcpu, struct vlapic *vlapic)
1315 {
1316 	int vector;
1317 
1318 	if (!vlapic_pending_intr(vlapic, &vector)) {
1319 		return (EIS_CAN_INJECT);
1320 	}
1321 
1322 	/*
1323 	 * From the Intel SDM, Volume 3, Section "Maskable
1324 	 * Hardware Interrupts":
1325 	 * - maskable interrupt vectors [16,255] can be delivered
1326 	 *   through the local APIC.
1327 	 */
1328 	KASSERT(vector >= 16 && vector <= 255,
1329 	    ("invalid vector %d from local APIC", vector));
1330 
1331 	if (vmx_cap_en(vmx, VMX_CAP_APICV)) {
1332 		uint16_t status_old = vmcs_read(VMCS_GUEST_INTR_STATUS);
1333 		uint16_t status_new = (status_old & 0xff00) | vector;
1334 
1335 		/*
1336 		 * The APICv state will have been synced into the vLAPIC
1337 		 * as part of vlapic_pending_intr().  Prepare the VMCS
1338 		 * for the to-be-injected pending interrupt.
1339 		 */
1340 		if (status_new > status_old) {
1341 			vmcs_write(VMCS_GUEST_INTR_STATUS, status_new);
1342 		}
1343 
1344 		/*
1345 		 * Ensure VMCS state regarding EOI traps is kept in sync
1346 		 * with the TMRs in the vlapic.
1347 		 */
1348 		vmx_apicv_sync_tmr(vlapic);
1349 
1350 		/*
1351 		 * The rest of the injection process for injecting the
1352 		 * interrupt(s) is handled by APICv. It does not preclude other
1353 		 * event injection from occurring.
1354 		 */
1355 		return (EIS_CAN_INJECT);
1356 	}
1357 
1358 	ASSERT0(vmcs_read(VMCS_ENTRY_INTR_INFO) & VMCS_INTR_VALID);
1359 
1360 	/* Does guest interruptability block injection? */
1361 	if ((vmcs_read(VMCS_GUEST_INTERRUPTIBILITY) & HWINTR_BLOCKING) != 0 ||
1362 	    (vmcs_read(VMCS_GUEST_RFLAGS) & PSL_I) == 0) {
1363 		return (EIS_GI_BLOCK);
1364 	}
1365 
1366 	/* Inject the interrupt */
1367 	vmcs_write(VMCS_ENTRY_INTR_INFO,
1368 	    VMCS_INTR_T_HWINTR | VMCS_INTR_VALID | vector);
1369 
1370 	/* Update the Local APIC ISR */
1371 	vlapic_intr_accepted(vlapic, vector);
1372 
1373 	return (EIS_EV_INJECTED);
1374 }
1375 
1376 /*
1377  * Re-check for events to be injected.
1378  *
1379  * Once host CPU interrupts are disabled, check for the presence of any events
1380  * which require injection processing.  If an exit is required upon injection,
1381  * or once the guest becomes interruptable, that will be configured too.
1382  */
1383 static bool
1384 vmx_inject_recheck(struct vmx *vmx, int vcpu, enum event_inject_state state)
1385 {
1386 	if (state == EIS_CAN_INJECT) {
1387 		if (vm_nmi_pending(vmx->vm, vcpu) &&
1388 		    !vmx_nmi_window_exiting(vmx, vcpu)) {
1389 			/* queued NMI not blocked by NMI-window-exiting */
1390 			return (true);
1391 		}
1392 		if (vm_extint_pending(vmx->vm, vcpu)) {
1393 			/* queued ExtINT not blocked by existing injection */
1394 			return (true);
1395 		}
1396 	} else {
1397 		if ((state & EIS_REQ_EXIT) != 0) {
1398 			/*
1399 			 * Use a self-IPI to force an immediate exit after
1400 			 * event injection has occurred.
1401 			 */
1402 			poke_cpu(CPU->cpu_id);
1403 		} else {
1404 			/*
1405 			 * If any event is being injected, an exit immediately
1406 			 * upon becoming interruptable again will allow pending
1407 			 * or newly queued events to be injected in a timely
1408 			 * manner.
1409 			 */
1410 			vmx_set_int_window_exiting(vmx, vcpu);
1411 		}
1412 	}
1413 	return (false);
1414 }
1415 
1416 /*
1417  * If the Virtual NMIs execution control is '1' then the logical processor
1418  * tracks virtual-NMI blocking in the Guest Interruptibility-state field of
1419  * the VMCS. An IRET instruction in VMX non-root operation will remove any
1420  * virtual-NMI blocking.
1421  *
1422  * This unblocking occurs even if the IRET causes a fault. In this case the
1423  * hypervisor needs to restore virtual-NMI blocking before resuming the guest.
1424  */
1425 static void
1426 vmx_restore_nmi_blocking(struct vmx *vmx, int vcpuid)
1427 {
1428 	uint32_t gi;
1429 
1430 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1431 	gi |= VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1432 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1433 }
1434 
1435 static void
1436 vmx_clear_nmi_blocking(struct vmx *vmx, int vcpuid)
1437 {
1438 	uint32_t gi;
1439 
1440 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1441 	gi &= ~VMCS_INTERRUPTIBILITY_NMI_BLOCKING;
1442 	vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
1443 }
1444 
1445 static void
1446 vmx_assert_nmi_blocking(struct vmx *vmx, int vcpuid)
1447 {
1448 	uint32_t gi;
1449 
1450 	gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
1451 	KASSERT(gi & VMCS_INTERRUPTIBILITY_NMI_BLOCKING,
1452 	    ("NMI blocking is not in effect %x", gi));
1453 }
1454 
1455 static int
1456 vmx_emulate_xsetbv(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
1457 {
1458 	struct vmxctx *vmxctx;
1459 	uint64_t xcrval;
1460 	const struct xsave_limits *limits;
1461 
1462 	vmxctx = &vmx->ctx[vcpu];
1463 	limits = vmm_get_xsave_limits();
1464 
1465 	/*
1466 	 * Note that the processor raises a GP# fault on its own if
1467 	 * xsetbv is executed for CPL != 0, so we do not have to
1468 	 * emulate that fault here.
1469 	 */
1470 
1471 	/* Only xcr0 is supported. */
1472 	if (vmxctx->guest_rcx != 0) {
1473 		vm_inject_gp(vmx->vm, vcpu);
1474 		return (HANDLED);
1475 	}
1476 
1477 	/* We only handle xcr0 if both the host and guest have XSAVE enabled. */
1478 	if (!limits->xsave_enabled ||
1479 	    !(vmcs_read(VMCS_GUEST_CR4) & CR4_XSAVE)) {
1480 		vm_inject_ud(vmx->vm, vcpu);
1481 		return (HANDLED);
1482 	}
1483 
1484 	xcrval = vmxctx->guest_rdx << 32 | (vmxctx->guest_rax & 0xffffffff);
1485 	if ((xcrval & ~limits->xcr0_allowed) != 0) {
1486 		vm_inject_gp(vmx->vm, vcpu);
1487 		return (HANDLED);
1488 	}
1489 
1490 	if (!(xcrval & XFEATURE_ENABLED_X87)) {
1491 		vm_inject_gp(vmx->vm, vcpu);
1492 		return (HANDLED);
1493 	}
1494 
1495 	/* AVX (YMM_Hi128) requires SSE. */
1496 	if (xcrval & XFEATURE_ENABLED_AVX &&
1497 	    (xcrval & XFEATURE_AVX) != XFEATURE_AVX) {
1498 		vm_inject_gp(vmx->vm, vcpu);
1499 		return (HANDLED);
1500 	}
1501 
1502 	/*
1503 	 * AVX512 requires base AVX (YMM_Hi128) as well as OpMask,
1504 	 * ZMM_Hi256, and Hi16_ZMM.
1505 	 */
1506 	if (xcrval & XFEATURE_AVX512 &&
1507 	    (xcrval & (XFEATURE_AVX512 | XFEATURE_AVX)) !=
1508 	    (XFEATURE_AVX512 | XFEATURE_AVX)) {
1509 		vm_inject_gp(vmx->vm, vcpu);
1510 		return (HANDLED);
1511 	}
1512 
1513 	/*
1514 	 * Intel MPX requires both bound register state flags to be
1515 	 * set.
1516 	 */
1517 	if (((xcrval & XFEATURE_ENABLED_BNDREGS) != 0) !=
1518 	    ((xcrval & XFEATURE_ENABLED_BNDCSR) != 0)) {
1519 		vm_inject_gp(vmx->vm, vcpu);
1520 		return (HANDLED);
1521 	}
1522 
1523 	/*
1524 	 * This runs "inside" vmrun() with the guest's FPU state, so
1525 	 * modifying xcr0 directly modifies the guest's xcr0, not the
1526 	 * host's.
1527 	 */
1528 	load_xcr(0, xcrval);
1529 	return (HANDLED);
1530 }
1531 
1532 static uint64_t
1533 vmx_get_guest_reg(struct vmx *vmx, int vcpu, int ident)
1534 {
1535 	const struct vmxctx *vmxctx;
1536 
1537 	vmxctx = &vmx->ctx[vcpu];
1538 
1539 	switch (ident) {
1540 	case 0:
1541 		return (vmxctx->guest_rax);
1542 	case 1:
1543 		return (vmxctx->guest_rcx);
1544 	case 2:
1545 		return (vmxctx->guest_rdx);
1546 	case 3:
1547 		return (vmxctx->guest_rbx);
1548 	case 4:
1549 		return (vmcs_read(VMCS_GUEST_RSP));
1550 	case 5:
1551 		return (vmxctx->guest_rbp);
1552 	case 6:
1553 		return (vmxctx->guest_rsi);
1554 	case 7:
1555 		return (vmxctx->guest_rdi);
1556 	case 8:
1557 		return (vmxctx->guest_r8);
1558 	case 9:
1559 		return (vmxctx->guest_r9);
1560 	case 10:
1561 		return (vmxctx->guest_r10);
1562 	case 11:
1563 		return (vmxctx->guest_r11);
1564 	case 12:
1565 		return (vmxctx->guest_r12);
1566 	case 13:
1567 		return (vmxctx->guest_r13);
1568 	case 14:
1569 		return (vmxctx->guest_r14);
1570 	case 15:
1571 		return (vmxctx->guest_r15);
1572 	default:
1573 		panic("invalid vmx register %d", ident);
1574 	}
1575 }
1576 
1577 static void
1578 vmx_set_guest_reg(struct vmx *vmx, int vcpu, int ident, uint64_t regval)
1579 {
1580 	struct vmxctx *vmxctx;
1581 
1582 	vmxctx = &vmx->ctx[vcpu];
1583 
1584 	switch (ident) {
1585 	case 0:
1586 		vmxctx->guest_rax = regval;
1587 		break;
1588 	case 1:
1589 		vmxctx->guest_rcx = regval;
1590 		break;
1591 	case 2:
1592 		vmxctx->guest_rdx = regval;
1593 		break;
1594 	case 3:
1595 		vmxctx->guest_rbx = regval;
1596 		break;
1597 	case 4:
1598 		vmcs_write(VMCS_GUEST_RSP, regval);
1599 		break;
1600 	case 5:
1601 		vmxctx->guest_rbp = regval;
1602 		break;
1603 	case 6:
1604 		vmxctx->guest_rsi = regval;
1605 		break;
1606 	case 7:
1607 		vmxctx->guest_rdi = regval;
1608 		break;
1609 	case 8:
1610 		vmxctx->guest_r8 = regval;
1611 		break;
1612 	case 9:
1613 		vmxctx->guest_r9 = regval;
1614 		break;
1615 	case 10:
1616 		vmxctx->guest_r10 = regval;
1617 		break;
1618 	case 11:
1619 		vmxctx->guest_r11 = regval;
1620 		break;
1621 	case 12:
1622 		vmxctx->guest_r12 = regval;
1623 		break;
1624 	case 13:
1625 		vmxctx->guest_r13 = regval;
1626 		break;
1627 	case 14:
1628 		vmxctx->guest_r14 = regval;
1629 		break;
1630 	case 15:
1631 		vmxctx->guest_r15 = regval;
1632 		break;
1633 	default:
1634 		panic("invalid vmx register %d", ident);
1635 	}
1636 }
1637 
1638 static int
1639 vmx_emulate_cr0_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1640 {
1641 	uint64_t crval, regval;
1642 
1643 	/* We only handle mov to %cr0 at this time */
1644 	if ((exitqual & 0xf0) != 0x00)
1645 		return (UNHANDLED);
1646 
1647 	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1648 
1649 	vmcs_write(VMCS_CR0_SHADOW, regval);
1650 
1651 	crval = regval | cr0_ones_mask;
1652 	crval &= ~cr0_zeros_mask;
1653 
1654 	const uint64_t old = vmcs_read(VMCS_GUEST_CR0);
1655 	const uint64_t diff = crval ^ old;
1656 	/* Flush the TLB if the paging or write-protect bits are changing */
1657 	if ((diff & CR0_PG) != 0 || (diff & CR0_WP) != 0) {
1658 		vmx_invvpid(vmx, vcpu, 1);
1659 	}
1660 
1661 	vmcs_write(VMCS_GUEST_CR0, crval);
1662 
1663 	if (regval & CR0_PG) {
1664 		uint64_t efer, entry_ctls;
1665 
1666 		/*
1667 		 * If CR0.PG is 1 and EFER.LME is 1 then EFER.LMA and
1668 		 * the "IA-32e mode guest" bit in VM-entry control must be
1669 		 * equal.
1670 		 */
1671 		efer = vmcs_read(VMCS_GUEST_IA32_EFER);
1672 		if (efer & EFER_LME) {
1673 			efer |= EFER_LMA;
1674 			vmcs_write(VMCS_GUEST_IA32_EFER, efer);
1675 			entry_ctls = vmcs_read(VMCS_ENTRY_CTLS);
1676 			entry_ctls |= VM_ENTRY_GUEST_LMA;
1677 			vmcs_write(VMCS_ENTRY_CTLS, entry_ctls);
1678 		}
1679 	}
1680 
1681 	return (HANDLED);
1682 }
1683 
1684 static int
1685 vmx_emulate_cr4_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1686 {
1687 	uint64_t crval, regval;
1688 
1689 	/* We only handle mov to %cr4 at this time */
1690 	if ((exitqual & 0xf0) != 0x00)
1691 		return (UNHANDLED);
1692 
1693 	regval = vmx_get_guest_reg(vmx, vcpu, (exitqual >> 8) & 0xf);
1694 
1695 	vmcs_write(VMCS_CR4_SHADOW, regval);
1696 
1697 	crval = regval | cr4_ones_mask;
1698 	crval &= ~cr4_zeros_mask;
1699 	vmcs_write(VMCS_GUEST_CR4, crval);
1700 
1701 	return (HANDLED);
1702 }
1703 
1704 static int
1705 vmx_emulate_cr8_access(struct vmx *vmx, int vcpu, uint64_t exitqual)
1706 {
1707 	struct vlapic *vlapic;
1708 	uint64_t cr8;
1709 	int regnum;
1710 
1711 	/* We only handle mov %cr8 to/from a register at this time. */
1712 	if ((exitqual & 0xe0) != 0x00) {
1713 		return (UNHANDLED);
1714 	}
1715 
1716 	vlapic = vm_lapic(vmx->vm, vcpu);
1717 	regnum = (exitqual >> 8) & 0xf;
1718 	if (exitqual & 0x10) {
1719 		cr8 = vlapic_get_cr8(vlapic);
1720 		vmx_set_guest_reg(vmx, vcpu, regnum, cr8);
1721 	} else {
1722 		cr8 = vmx_get_guest_reg(vmx, vcpu, regnum);
1723 		vlapic_set_cr8(vlapic, cr8);
1724 	}
1725 
1726 	return (HANDLED);
1727 }
1728 
1729 /*
1730  * From section "Guest Register State" in the Intel SDM: CPL = SS.DPL
1731  */
1732 static int
1733 vmx_cpl(void)
1734 {
1735 	uint32_t ssar;
1736 
1737 	ssar = vmcs_read(VMCS_GUEST_SS_ACCESS_RIGHTS);
1738 	return ((ssar >> 5) & 0x3);
1739 }
1740 
1741 static enum vm_cpu_mode
1742 vmx_cpu_mode(void)
1743 {
1744 	uint32_t csar;
1745 
1746 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LMA) {
1747 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1748 		if (csar & 0x2000)
1749 			return (CPU_MODE_64BIT);	/* CS.L = 1 */
1750 		else
1751 			return (CPU_MODE_COMPATIBILITY);
1752 	} else if (vmcs_read(VMCS_GUEST_CR0) & CR0_PE) {
1753 		return (CPU_MODE_PROTECTED);
1754 	} else {
1755 		return (CPU_MODE_REAL);
1756 	}
1757 }
1758 
1759 static enum vm_paging_mode
1760 vmx_paging_mode(void)
1761 {
1762 
1763 	if (!(vmcs_read(VMCS_GUEST_CR0) & CR0_PG))
1764 		return (PAGING_MODE_FLAT);
1765 	if (!(vmcs_read(VMCS_GUEST_CR4) & CR4_PAE))
1766 		return (PAGING_MODE_32);
1767 	if (vmcs_read(VMCS_GUEST_IA32_EFER) & EFER_LME)
1768 		return (PAGING_MODE_64);
1769 	else
1770 		return (PAGING_MODE_PAE);
1771 }
1772 
1773 static void
1774 vmx_paging_info(struct vm_guest_paging *paging)
1775 {
1776 	paging->cr3 = vmcs_read(VMCS_GUEST_CR3);
1777 	paging->cpl = vmx_cpl();
1778 	paging->cpu_mode = vmx_cpu_mode();
1779 	paging->paging_mode = vmx_paging_mode();
1780 }
1781 
1782 static void
1783 vmexit_mmio_emul(struct vm_exit *vmexit, struct vie *vie, uint64_t gpa,
1784     uint64_t gla)
1785 {
1786 	struct vm_guest_paging paging;
1787 	uint32_t csar;
1788 
1789 	vmexit->exitcode = VM_EXITCODE_MMIO_EMUL;
1790 	vmexit->inst_length = 0;
1791 	vmexit->u.mmio_emul.gpa = gpa;
1792 	vmexit->u.mmio_emul.gla = gla;
1793 	vmx_paging_info(&paging);
1794 
1795 	switch (paging.cpu_mode) {
1796 	case CPU_MODE_REAL:
1797 		vmexit->u.mmio_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1798 		vmexit->u.mmio_emul.cs_d = 0;
1799 		break;
1800 	case CPU_MODE_PROTECTED:
1801 	case CPU_MODE_COMPATIBILITY:
1802 		vmexit->u.mmio_emul.cs_base = vmcs_read(VMCS_GUEST_CS_BASE);
1803 		csar = vmcs_read(VMCS_GUEST_CS_ACCESS_RIGHTS);
1804 		vmexit->u.mmio_emul.cs_d = SEG_DESC_DEF32(csar);
1805 		break;
1806 	default:
1807 		vmexit->u.mmio_emul.cs_base = 0;
1808 		vmexit->u.mmio_emul.cs_d = 0;
1809 		break;
1810 	}
1811 
1812 	vie_init_mmio(vie, NULL, 0, &paging, gpa);
1813 }
1814 
1815 static void
1816 vmexit_inout(struct vm_exit *vmexit, struct vie *vie, uint64_t qual,
1817     uint32_t eax)
1818 {
1819 	struct vm_guest_paging paging;
1820 	struct vm_inout *inout;
1821 
1822 	inout = &vmexit->u.inout;
1823 
1824 	inout->bytes = (qual & 0x7) + 1;
1825 	inout->flags = 0;
1826 	inout->flags |= (qual & 0x8) ? INOUT_IN : 0;
1827 	inout->flags |= (qual & 0x10) ? INOUT_STR : 0;
1828 	inout->flags |= (qual & 0x20) ? INOUT_REP : 0;
1829 	inout->port = (uint16_t)(qual >> 16);
1830 	inout->eax = eax;
1831 	if (inout->flags & INOUT_STR) {
1832 		uint64_t inst_info;
1833 
1834 		inst_info = vmcs_read(VMCS_EXIT_INSTRUCTION_INFO);
1835 
1836 		/*
1837 		 * According to the SDM, bits 9:7 encode the address size of the
1838 		 * ins/outs operation, but only values 0/1/2 are expected,
1839 		 * corresponding to 16/32/64 bit sizes.
1840 		 */
1841 		inout->addrsize = 2 << BITX(inst_info, 9, 7);
1842 		VERIFY(inout->addrsize == 2 || inout->addrsize == 4 ||
1843 		    inout->addrsize == 8);
1844 
1845 		if (inout->flags & INOUT_IN) {
1846 			/*
1847 			 * The bits describing the segment in INSTRUCTION_INFO
1848 			 * are not defined for ins, leaving it to system
1849 			 * software to assume %es (encoded as 0)
1850 			 */
1851 			inout->segment = 0;
1852 		} else {
1853 			/*
1854 			 * Bits 15-17 encode the segment for OUTS.
1855 			 * This value follows the standard x86 segment order.
1856 			 */
1857 			inout->segment = (inst_info >> 15) & 0x7;
1858 		}
1859 	}
1860 
1861 	vmexit->exitcode = VM_EXITCODE_INOUT;
1862 	vmx_paging_info(&paging);
1863 	vie_init_inout(vie, inout, vmexit->inst_length, &paging);
1864 
1865 	/* The in/out emulation will handle advancing %rip */
1866 	vmexit->inst_length = 0;
1867 }
1868 
1869 static int
1870 ept_fault_type(uint64_t ept_qual)
1871 {
1872 	int fault_type;
1873 
1874 	if (ept_qual & EPT_VIOLATION_DATA_WRITE)
1875 		fault_type = PROT_WRITE;
1876 	else if (ept_qual & EPT_VIOLATION_INST_FETCH)
1877 		fault_type = PROT_EXEC;
1878 	else
1879 		fault_type = PROT_READ;
1880 
1881 	return (fault_type);
1882 }
1883 
1884 static bool
1885 ept_emulation_fault(uint64_t ept_qual)
1886 {
1887 	int read, write;
1888 
1889 	/* EPT fault on an instruction fetch doesn't make sense here */
1890 	if (ept_qual & EPT_VIOLATION_INST_FETCH)
1891 		return (false);
1892 
1893 	/* EPT fault must be a read fault or a write fault */
1894 	read = ept_qual & EPT_VIOLATION_DATA_READ ? 1 : 0;
1895 	write = ept_qual & EPT_VIOLATION_DATA_WRITE ? 1 : 0;
1896 	if ((read | write) == 0)
1897 		return (false);
1898 
1899 	/*
1900 	 * The EPT violation must have been caused by accessing a
1901 	 * guest-physical address that is a translation of a guest-linear
1902 	 * address.
1903 	 */
1904 	if ((ept_qual & EPT_VIOLATION_GLA_VALID) == 0 ||
1905 	    (ept_qual & EPT_VIOLATION_XLAT_VALID) == 0) {
1906 		return (false);
1907 	}
1908 
1909 	return (true);
1910 }
1911 
1912 static __inline int
1913 apic_access_virtualization(struct vmx *vmx, int vcpuid)
1914 {
1915 	uint32_t proc_ctls2;
1916 
1917 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1918 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) ? 1 : 0);
1919 }
1920 
1921 static __inline int
1922 x2apic_virtualization(struct vmx *vmx, int vcpuid)
1923 {
1924 	uint32_t proc_ctls2;
1925 
1926 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
1927 	return ((proc_ctls2 & PROCBASED2_VIRTUALIZE_X2APIC_MODE) ? 1 : 0);
1928 }
1929 
1930 static int
1931 vmx_handle_apic_write(struct vmx *vmx, int vcpuid, struct vlapic *vlapic,
1932     uint64_t qual)
1933 {
1934 	const uint_t offset = APIC_WRITE_OFFSET(qual);
1935 
1936 	if (!apic_access_virtualization(vmx, vcpuid)) {
1937 		/*
1938 		 * In general there should not be any APIC write VM-exits
1939 		 * unless APIC-access virtualization is enabled.
1940 		 *
1941 		 * However self-IPI virtualization can legitimately trigger
1942 		 * an APIC-write VM-exit so treat it specially.
1943 		 */
1944 		if (x2apic_virtualization(vmx, vcpuid) &&
1945 		    offset == APIC_OFFSET_SELF_IPI) {
1946 			const uint32_t *apic_regs =
1947 			    (uint32_t *)(vlapic->apic_page);
1948 			const uint32_t vector =
1949 			    apic_regs[APIC_OFFSET_SELF_IPI / 4];
1950 
1951 			vlapic_self_ipi_handler(vlapic, vector);
1952 			return (HANDLED);
1953 		} else
1954 			return (UNHANDLED);
1955 	}
1956 
1957 	switch (offset) {
1958 	case APIC_OFFSET_ID:
1959 		vlapic_id_write_handler(vlapic);
1960 		break;
1961 	case APIC_OFFSET_LDR:
1962 		vlapic_ldr_write_handler(vlapic);
1963 		break;
1964 	case APIC_OFFSET_DFR:
1965 		vlapic_dfr_write_handler(vlapic);
1966 		break;
1967 	case APIC_OFFSET_SVR:
1968 		vlapic_svr_write_handler(vlapic);
1969 		break;
1970 	case APIC_OFFSET_ESR:
1971 		vlapic_esr_write_handler(vlapic);
1972 		break;
1973 	case APIC_OFFSET_ICR_LOW:
1974 		vlapic_icrlo_write_handler(vlapic);
1975 		break;
1976 	case APIC_OFFSET_CMCI_LVT:
1977 	case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1978 		vlapic_lvt_write_handler(vlapic, offset);
1979 		break;
1980 	case APIC_OFFSET_TIMER_ICR:
1981 		vlapic_icrtmr_write_handler(vlapic);
1982 		break;
1983 	case APIC_OFFSET_TIMER_DCR:
1984 		vlapic_dcr_write_handler(vlapic);
1985 		break;
1986 	default:
1987 		return (UNHANDLED);
1988 	}
1989 	return (HANDLED);
1990 }
1991 
1992 static bool
1993 apic_access_fault(struct vmx *vmx, int vcpuid, uint64_t gpa)
1994 {
1995 
1996 	if (apic_access_virtualization(vmx, vcpuid) &&
1997 	    (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE))
1998 		return (true);
1999 	else
2000 		return (false);
2001 }
2002 
2003 static int
2004 vmx_handle_apic_access(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit)
2005 {
2006 	uint64_t qual;
2007 	int access_type, offset, allowed;
2008 	struct vie *vie;
2009 
2010 	if (!apic_access_virtualization(vmx, vcpuid))
2011 		return (UNHANDLED);
2012 
2013 	qual = vmexit->u.vmx.exit_qualification;
2014 	access_type = APIC_ACCESS_TYPE(qual);
2015 	offset = APIC_ACCESS_OFFSET(qual);
2016 
2017 	allowed = 0;
2018 	if (access_type == 0) {
2019 		/*
2020 		 * Read data access to the following registers is expected.
2021 		 */
2022 		switch (offset) {
2023 		case APIC_OFFSET_APR:
2024 		case APIC_OFFSET_PPR:
2025 		case APIC_OFFSET_RRR:
2026 		case APIC_OFFSET_CMCI_LVT:
2027 		case APIC_OFFSET_TIMER_CCR:
2028 			allowed = 1;
2029 			break;
2030 		default:
2031 			break;
2032 		}
2033 	} else if (access_type == 1) {
2034 		/*
2035 		 * Write data access to the following registers is expected.
2036 		 */
2037 		switch (offset) {
2038 		case APIC_OFFSET_VER:
2039 		case APIC_OFFSET_APR:
2040 		case APIC_OFFSET_PPR:
2041 		case APIC_OFFSET_RRR:
2042 		case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
2043 		case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
2044 		case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
2045 		case APIC_OFFSET_CMCI_LVT:
2046 		case APIC_OFFSET_TIMER_CCR:
2047 			allowed = 1;
2048 			break;
2049 		default:
2050 			break;
2051 		}
2052 	}
2053 
2054 	if (allowed) {
2055 		vie = vm_vie_ctx(vmx->vm, vcpuid);
2056 		vmexit_mmio_emul(vmexit, vie, DEFAULT_APIC_BASE + offset,
2057 		    VIE_INVALID_GLA);
2058 	}
2059 
2060 	/*
2061 	 * Regardless of whether the APIC-access is allowed this handler
2062 	 * always returns UNHANDLED:
2063 	 * - if the access is allowed then it is handled by emulating the
2064 	 *   instruction that caused the VM-exit (outside the critical section)
2065 	 * - if the access is not allowed then it will be converted to an
2066 	 *   exitcode of VM_EXITCODE_VMX and will be dealt with in userland.
2067 	 */
2068 	return (UNHANDLED);
2069 }
2070 
2071 static enum task_switch_reason
2072 vmx_task_switch_reason(uint64_t qual)
2073 {
2074 	int reason;
2075 
2076 	reason = (qual >> 30) & 0x3;
2077 	switch (reason) {
2078 	case 0:
2079 		return (TSR_CALL);
2080 	case 1:
2081 		return (TSR_IRET);
2082 	case 2:
2083 		return (TSR_JMP);
2084 	case 3:
2085 		return (TSR_IDT_GATE);
2086 	default:
2087 		panic("%s: invalid reason %d", __func__, reason);
2088 	}
2089 }
2090 
2091 static int
2092 vmx_handle_msr(struct vmx *vmx, int vcpuid, struct vm_exit *vmexit,
2093     bool is_wrmsr)
2094 {
2095 	struct vmxctx *vmxctx = &vmx->ctx[vcpuid];
2096 	const uint32_t ecx = vmxctx->guest_rcx;
2097 	vm_msr_result_t res;
2098 	uint64_t val = 0;
2099 
2100 	if (is_wrmsr) {
2101 		vmm_stat_incr(vmx->vm, vcpuid, VMEXIT_WRMSR, 1);
2102 		val = vmxctx->guest_rdx << 32 | (uint32_t)vmxctx->guest_rax;
2103 
2104 		if (vlapic_owned_msr(ecx)) {
2105 			struct vlapic *vlapic = vm_lapic(vmx->vm, vcpuid);
2106 
2107 			res = vlapic_wrmsr(vlapic, ecx, val);
2108 		} else {
2109 			res = vmx_wrmsr(vmx, vcpuid, ecx, val);
2110 		}
2111 	} else {
2112 		vmm_stat_incr(vmx->vm, vcpuid, VMEXIT_RDMSR, 1);
2113 
2114 		if (vlapic_owned_msr(ecx)) {
2115 			struct vlapic *vlapic = vm_lapic(vmx->vm, vcpuid);
2116 
2117 			res = vlapic_rdmsr(vlapic, ecx, &val);
2118 		} else {
2119 			res = vmx_rdmsr(vmx, vcpuid, ecx, &val);
2120 		}
2121 	}
2122 
2123 	switch (res) {
2124 	case VMR_OK:
2125 		/* Store rdmsr result in the appropriate registers */
2126 		if (!is_wrmsr) {
2127 			vmxctx->guest_rax = (uint32_t)val;
2128 			vmxctx->guest_rdx = val >> 32;
2129 		}
2130 		return (HANDLED);
2131 	case VMR_GP:
2132 		vm_inject_gp(vmx->vm, vcpuid);
2133 		return (HANDLED);
2134 	case VMR_UNHANLDED:
2135 		vmexit->exitcode = is_wrmsr ?
2136 		    VM_EXITCODE_WRMSR : VM_EXITCODE_RDMSR;
2137 		vmexit->u.msr.code = ecx;
2138 		vmexit->u.msr.wval = val;
2139 		return (UNHANDLED);
2140 	default:
2141 		panic("unexpected msr result %u\n", res);
2142 	}
2143 }
2144 
2145 static int
2146 vmx_exit_process(struct vmx *vmx, int vcpu, struct vm_exit *vmexit)
2147 {
2148 	int error, errcode, errcode_valid, handled;
2149 	struct vmxctx *vmxctx;
2150 	struct vie *vie;
2151 	struct vlapic *vlapic;
2152 	struct vm_task_switch *ts;
2153 	uint32_t idtvec_info, intr_info;
2154 	uint32_t intr_type, intr_vec, reason;
2155 	uint64_t qual, gpa;
2156 
2157 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_VIRTUAL_NMI) != 0);
2158 	CTASSERT((PINBASED_CTLS_ONE_SETTING & PINBASED_NMI_EXITING) != 0);
2159 
2160 	handled = UNHANDLED;
2161 	vmxctx = &vmx->ctx[vcpu];
2162 
2163 	qual = vmexit->u.vmx.exit_qualification;
2164 	reason = vmexit->u.vmx.exit_reason;
2165 	vmexit->exitcode = VM_EXITCODE_BOGUS;
2166 
2167 	vmm_stat_incr(vmx->vm, vcpu, VMEXIT_COUNT, 1);
2168 	SDT_PROBE3(vmm, vmx, exit, entry, vmx, vcpu, vmexit);
2169 
2170 	/*
2171 	 * VM-entry failures during or after loading guest state.
2172 	 *
2173 	 * These VM-exits are uncommon but must be handled specially
2174 	 * as most VM-exit fields are not populated as usual.
2175 	 */
2176 	if (reason == EXIT_REASON_MCE_DURING_ENTRY) {
2177 		vmm_call_trap(T_MCE);
2178 		return (1);
2179 	}
2180 
2181 	/*
2182 	 * VM exits that can be triggered during event delivery need to
2183 	 * be handled specially by re-injecting the event if the IDT
2184 	 * vectoring information field's valid bit is set.
2185 	 *
2186 	 * See "Information for VM Exits During Event Delivery" in Intel SDM
2187 	 * for details.
2188 	 */
2189 	idtvec_info = vmcs_read(VMCS_IDT_VECTORING_INFO);
2190 	if (idtvec_info & VMCS_IDT_VEC_VALID) {
2191 		/* Record exit intinfo */
2192 		VERIFY0(vm_exit_intinfo(vmx->vm, vcpu,
2193 		    vmx_idtvec_to_intinfo(idtvec_info)));
2194 
2195 		/*
2196 		 * If 'virtual NMIs' are being used and the VM-exit
2197 		 * happened while injecting an NMI during the previous
2198 		 * VM-entry, then clear "blocking by NMI" in the
2199 		 * Guest Interruptibility-State so the NMI can be
2200 		 * reinjected on the subsequent VM-entry.
2201 		 *
2202 		 * However, if the NMI was being delivered through a task
2203 		 * gate, then the new task must start execution with NMIs
2204 		 * blocked so don't clear NMI blocking in this case.
2205 		 */
2206 		intr_type = idtvec_info & VMCS_INTR_T_MASK;
2207 		if (intr_type == VMCS_INTR_T_NMI) {
2208 			if (reason != EXIT_REASON_TASK_SWITCH)
2209 				vmx_clear_nmi_blocking(vmx, vcpu);
2210 			else
2211 				vmx_assert_nmi_blocking(vmx, vcpu);
2212 		}
2213 
2214 		/*
2215 		 * Update VM-entry instruction length if the event being
2216 		 * delivered was a software interrupt or software exception.
2217 		 */
2218 		if (intr_type == VMCS_INTR_T_SWINTR ||
2219 		    intr_type == VMCS_INTR_T_PRIV_SWEXCEPTION ||
2220 		    intr_type == VMCS_INTR_T_SWEXCEPTION) {
2221 			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2222 		}
2223 	}
2224 
2225 	switch (reason) {
2226 	case EXIT_REASON_TRIPLE_FAULT:
2227 		(void) vm_suspend(vmx->vm, VM_SUSPEND_TRIPLEFAULT);
2228 		handled = HANDLED;
2229 		break;
2230 	case EXIT_REASON_TASK_SWITCH:
2231 		ts = &vmexit->u.task_switch;
2232 		ts->tsssel = qual & 0xffff;
2233 		ts->reason = vmx_task_switch_reason(qual);
2234 		ts->ext = 0;
2235 		ts->errcode_valid = 0;
2236 		vmx_paging_info(&ts->paging);
2237 		/*
2238 		 * If the task switch was due to a CALL, JMP, IRET, software
2239 		 * interrupt (INT n) or software exception (INT3, INTO),
2240 		 * then the saved %rip references the instruction that caused
2241 		 * the task switch. The instruction length field in the VMCS
2242 		 * is valid in this case.
2243 		 *
2244 		 * In all other cases (e.g., NMI, hardware exception) the
2245 		 * saved %rip is one that would have been saved in the old TSS
2246 		 * had the task switch completed normally so the instruction
2247 		 * length field is not needed in this case and is explicitly
2248 		 * set to 0.
2249 		 */
2250 		if (ts->reason == TSR_IDT_GATE) {
2251 			KASSERT(idtvec_info & VMCS_IDT_VEC_VALID,
2252 			    ("invalid idtvec_info %x for IDT task switch",
2253 			    idtvec_info));
2254 			intr_type = idtvec_info & VMCS_INTR_T_MASK;
2255 			if (intr_type != VMCS_INTR_T_SWINTR &&
2256 			    intr_type != VMCS_INTR_T_SWEXCEPTION &&
2257 			    intr_type != VMCS_INTR_T_PRIV_SWEXCEPTION) {
2258 				/* Task switch triggered by external event */
2259 				ts->ext = 1;
2260 				vmexit->inst_length = 0;
2261 				if (idtvec_info & VMCS_IDT_VEC_ERRCODE_VALID) {
2262 					ts->errcode_valid = 1;
2263 					ts->errcode =
2264 					    vmcs_read(VMCS_IDT_VECTORING_ERROR);
2265 				}
2266 			}
2267 		}
2268 		vmexit->exitcode = VM_EXITCODE_TASK_SWITCH;
2269 		SDT_PROBE4(vmm, vmx, exit, taskswitch, vmx, vcpu, vmexit, ts);
2270 		break;
2271 	case EXIT_REASON_CR_ACCESS:
2272 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CR_ACCESS, 1);
2273 		SDT_PROBE4(vmm, vmx, exit, craccess, vmx, vcpu, vmexit, qual);
2274 		switch (qual & 0xf) {
2275 		case 0:
2276 			handled = vmx_emulate_cr0_access(vmx, vcpu, qual);
2277 			break;
2278 		case 4:
2279 			handled = vmx_emulate_cr4_access(vmx, vcpu, qual);
2280 			break;
2281 		case 8:
2282 			handled = vmx_emulate_cr8_access(vmx, vcpu, qual);
2283 			break;
2284 		}
2285 		break;
2286 	case EXIT_REASON_RDMSR:
2287 	case EXIT_REASON_WRMSR:
2288 		handled = vmx_handle_msr(vmx, vcpu, vmexit,
2289 		    reason == EXIT_REASON_WRMSR);
2290 		break;
2291 	case EXIT_REASON_HLT:
2292 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_HLT, 1);
2293 		SDT_PROBE3(vmm, vmx, exit, halt, vmx, vcpu, vmexit);
2294 		vmexit->exitcode = VM_EXITCODE_HLT;
2295 		vmexit->u.hlt.rflags = vmcs_read(VMCS_GUEST_RFLAGS);
2296 		break;
2297 	case EXIT_REASON_MTF:
2298 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MTRAP, 1);
2299 		SDT_PROBE3(vmm, vmx, exit, mtrap, vmx, vcpu, vmexit);
2300 		vmexit->exitcode = VM_EXITCODE_MTRAP;
2301 		vmexit->inst_length = 0;
2302 		break;
2303 	case EXIT_REASON_PAUSE:
2304 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_PAUSE, 1);
2305 		SDT_PROBE3(vmm, vmx, exit, pause, vmx, vcpu, vmexit);
2306 		vmexit->exitcode = VM_EXITCODE_PAUSE;
2307 		break;
2308 	case EXIT_REASON_INTR_WINDOW:
2309 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INTR_WINDOW, 1);
2310 		SDT_PROBE3(vmm, vmx, exit, intrwindow, vmx, vcpu, vmexit);
2311 		vmx_clear_int_window_exiting(vmx, vcpu);
2312 		return (1);
2313 	case EXIT_REASON_EXT_INTR:
2314 		/*
2315 		 * External interrupts serve only to cause VM exits and allow
2316 		 * the host interrupt handler to run.
2317 		 *
2318 		 * If this external interrupt triggers a virtual interrupt
2319 		 * to a VM, then that state will be recorded by the
2320 		 * host interrupt handler in the VM's softc. We will inject
2321 		 * this virtual interrupt during the subsequent VM enter.
2322 		 */
2323 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2324 		SDT_PROBE4(vmm, vmx, exit, interrupt,
2325 		    vmx, vcpu, vmexit, intr_info);
2326 
2327 		/*
2328 		 * XXX: Ignore this exit if VMCS_INTR_VALID is not set.
2329 		 * This appears to be a bug in VMware Fusion?
2330 		 */
2331 		if (!(intr_info & VMCS_INTR_VALID))
2332 			return (1);
2333 		KASSERT((intr_info & VMCS_INTR_VALID) != 0 &&
2334 		    (intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_HWINTR,
2335 		    ("VM exit interruption info invalid: %x", intr_info));
2336 		vmx_trigger_hostintr(intr_info & 0xff);
2337 
2338 		/*
2339 		 * This is special. We want to treat this as an 'handled'
2340 		 * VM-exit but not increment the instruction pointer.
2341 		 */
2342 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXTINT, 1);
2343 		return (1);
2344 	case EXIT_REASON_NMI_WINDOW:
2345 		SDT_PROBE3(vmm, vmx, exit, nmiwindow, vmx, vcpu, vmexit);
2346 		/* Exit to allow the pending virtual NMI to be injected */
2347 		if (vm_nmi_pending(vmx->vm, vcpu))
2348 			vmx_inject_nmi(vmx, vcpu);
2349 		vmx_clear_nmi_window_exiting(vmx, vcpu);
2350 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NMI_WINDOW, 1);
2351 		return (1);
2352 	case EXIT_REASON_INOUT:
2353 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_INOUT, 1);
2354 		vie = vm_vie_ctx(vmx->vm, vcpu);
2355 		vmexit_inout(vmexit, vie, qual, (uint32_t)vmxctx->guest_rax);
2356 		SDT_PROBE3(vmm, vmx, exit, inout, vmx, vcpu, vmexit);
2357 		break;
2358 	case EXIT_REASON_CPUID:
2359 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_CPUID, 1);
2360 		SDT_PROBE3(vmm, vmx, exit, cpuid, vmx, vcpu, vmexit);
2361 		handled = vmx_handle_cpuid(vmx->vm, vcpu, vmxctx);
2362 		break;
2363 	case EXIT_REASON_EXCEPTION:
2364 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_EXCEPTION, 1);
2365 		intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2366 		KASSERT((intr_info & VMCS_INTR_VALID) != 0,
2367 		    ("VM exit interruption info invalid: %x", intr_info));
2368 
2369 		intr_vec = intr_info & 0xff;
2370 		intr_type = intr_info & VMCS_INTR_T_MASK;
2371 
2372 		/*
2373 		 * If Virtual NMIs control is 1 and the VM-exit is due to a
2374 		 * fault encountered during the execution of IRET then we must
2375 		 * restore the state of "virtual-NMI blocking" before resuming
2376 		 * the guest.
2377 		 *
2378 		 * See "Resuming Guest Software after Handling an Exception".
2379 		 * See "Information for VM Exits Due to Vectored Events".
2380 		 */
2381 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2382 		    (intr_vec != IDT_DF) &&
2383 		    (intr_info & EXIT_QUAL_NMIUDTI) != 0)
2384 			vmx_restore_nmi_blocking(vmx, vcpu);
2385 
2386 		/*
2387 		 * The NMI has already been handled in vmx_exit_handle_nmi().
2388 		 */
2389 		if (intr_type == VMCS_INTR_T_NMI)
2390 			return (1);
2391 
2392 		/*
2393 		 * Call the machine check handler by hand. Also don't reflect
2394 		 * the machine check back into the guest.
2395 		 */
2396 		if (intr_vec == IDT_MC) {
2397 			vmm_call_trap(T_MCE);
2398 			return (1);
2399 		}
2400 
2401 		/*
2402 		 * If the hypervisor has requested user exits for
2403 		 * debug exceptions, bounce them out to userland.
2404 		 */
2405 		if (intr_type == VMCS_INTR_T_SWEXCEPTION &&
2406 		    intr_vec == IDT_BP &&
2407 		    (vmx->cap[vcpu].set & (1 << VM_CAP_BPT_EXIT))) {
2408 			vmexit->exitcode = VM_EXITCODE_BPT;
2409 			vmexit->u.bpt.inst_length = vmexit->inst_length;
2410 			vmexit->inst_length = 0;
2411 			break;
2412 		}
2413 
2414 		if (intr_vec == IDT_PF) {
2415 			vmxctx->guest_cr2 = qual;
2416 		}
2417 
2418 		/*
2419 		 * Software exceptions exhibit trap-like behavior. This in
2420 		 * turn requires populating the VM-entry instruction length
2421 		 * so that the %rip in the trap frame is past the INT3/INTO
2422 		 * instruction.
2423 		 */
2424 		if (intr_type == VMCS_INTR_T_SWEXCEPTION)
2425 			vmcs_write(VMCS_ENTRY_INST_LENGTH, vmexit->inst_length);
2426 
2427 		/* Reflect all other exceptions back into the guest */
2428 		errcode_valid = errcode = 0;
2429 		if (intr_info & VMCS_INTR_DEL_ERRCODE) {
2430 			errcode_valid = 1;
2431 			errcode = vmcs_read(VMCS_EXIT_INTR_ERRCODE);
2432 		}
2433 		SDT_PROBE5(vmm, vmx, exit, exception,
2434 		    vmx, vcpu, vmexit, intr_vec, errcode);
2435 		error = vm_inject_exception(vmx->vm, vcpu, intr_vec,
2436 		    errcode_valid, errcode, 0);
2437 		KASSERT(error == 0, ("%s: vm_inject_exception error %d",
2438 		    __func__, error));
2439 		return (1);
2440 
2441 	case EXIT_REASON_EPT_FAULT:
2442 		/*
2443 		 * If 'gpa' lies within the address space allocated to
2444 		 * memory then this must be a nested page fault otherwise
2445 		 * this must be an instruction that accesses MMIO space.
2446 		 */
2447 		gpa = vmcs_read(VMCS_GUEST_PHYSICAL_ADDRESS);
2448 		if (vm_mem_allocated(vmx->vm, vcpu, gpa) ||
2449 		    apic_access_fault(vmx, vcpu, gpa)) {
2450 			vmexit->exitcode = VM_EXITCODE_PAGING;
2451 			vmexit->inst_length = 0;
2452 			vmexit->u.paging.gpa = gpa;
2453 			vmexit->u.paging.fault_type = ept_fault_type(qual);
2454 			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
2455 			SDT_PROBE5(vmm, vmx, exit, nestedfault,
2456 			    vmx, vcpu, vmexit, gpa, qual);
2457 		} else if (ept_emulation_fault(qual)) {
2458 			vie = vm_vie_ctx(vmx->vm, vcpu);
2459 			vmexit_mmio_emul(vmexit, vie, gpa,
2460 			    vmcs_read(VMCS_GUEST_LINEAR_ADDRESS));
2461 			vmm_stat_incr(vmx->vm, vcpu, VMEXIT_MMIO_EMUL, 1);
2462 			SDT_PROBE4(vmm, vmx, exit, mmiofault,
2463 			    vmx, vcpu, vmexit, gpa);
2464 		}
2465 		/*
2466 		 * If Virtual NMIs control is 1 and the VM-exit is due to an
2467 		 * EPT fault during the execution of IRET then we must restore
2468 		 * the state of "virtual-NMI blocking" before resuming.
2469 		 *
2470 		 * See description of "NMI unblocking due to IRET" in
2471 		 * "Exit Qualification for EPT Violations".
2472 		 */
2473 		if ((idtvec_info & VMCS_IDT_VEC_VALID) == 0 &&
2474 		    (qual & EXIT_QUAL_NMIUDTI) != 0)
2475 			vmx_restore_nmi_blocking(vmx, vcpu);
2476 		break;
2477 	case EXIT_REASON_VIRTUALIZED_EOI:
2478 		vmexit->exitcode = VM_EXITCODE_IOAPIC_EOI;
2479 		vmexit->u.ioapic_eoi.vector = qual & 0xFF;
2480 		SDT_PROBE3(vmm, vmx, exit, eoi, vmx, vcpu, vmexit);
2481 		vmexit->inst_length = 0;	/* trap-like */
2482 		break;
2483 	case EXIT_REASON_APIC_ACCESS:
2484 		SDT_PROBE3(vmm, vmx, exit, apicaccess, vmx, vcpu, vmexit);
2485 		handled = vmx_handle_apic_access(vmx, vcpu, vmexit);
2486 		break;
2487 	case EXIT_REASON_APIC_WRITE:
2488 		/*
2489 		 * APIC-write VM exit is trap-like so the %rip is already
2490 		 * pointing to the next instruction.
2491 		 */
2492 		vmexit->inst_length = 0;
2493 		vlapic = vm_lapic(vmx->vm, vcpu);
2494 		SDT_PROBE4(vmm, vmx, exit, apicwrite,
2495 		    vmx, vcpu, vmexit, vlapic);
2496 		handled = vmx_handle_apic_write(vmx, vcpu, vlapic, qual);
2497 		break;
2498 	case EXIT_REASON_XSETBV:
2499 		SDT_PROBE3(vmm, vmx, exit, xsetbv, vmx, vcpu, vmexit);
2500 		handled = vmx_emulate_xsetbv(vmx, vcpu, vmexit);
2501 		break;
2502 	case EXIT_REASON_MONITOR:
2503 		SDT_PROBE3(vmm, vmx, exit, monitor, vmx, vcpu, vmexit);
2504 		vmexit->exitcode = VM_EXITCODE_MONITOR;
2505 		break;
2506 	case EXIT_REASON_MWAIT:
2507 		SDT_PROBE3(vmm, vmx, exit, mwait, vmx, vcpu, vmexit);
2508 		vmexit->exitcode = VM_EXITCODE_MWAIT;
2509 		break;
2510 	case EXIT_REASON_TPR:
2511 		vlapic = vm_lapic(vmx->vm, vcpu);
2512 		vlapic_sync_tpr(vlapic);
2513 		vmexit->inst_length = 0;
2514 		handled = HANDLED;
2515 		break;
2516 	case EXIT_REASON_VMCALL:
2517 	case EXIT_REASON_VMCLEAR:
2518 	case EXIT_REASON_VMLAUNCH:
2519 	case EXIT_REASON_VMPTRLD:
2520 	case EXIT_REASON_VMPTRST:
2521 	case EXIT_REASON_VMREAD:
2522 	case EXIT_REASON_VMRESUME:
2523 	case EXIT_REASON_VMWRITE:
2524 	case EXIT_REASON_VMXOFF:
2525 	case EXIT_REASON_VMXON:
2526 		SDT_PROBE3(vmm, vmx, exit, vminsn, vmx, vcpu, vmexit);
2527 		vmexit->exitcode = VM_EXITCODE_VMINSN;
2528 		break;
2529 	default:
2530 		SDT_PROBE4(vmm, vmx, exit, unknown,
2531 		    vmx, vcpu, vmexit, reason);
2532 		vmm_stat_incr(vmx->vm, vcpu, VMEXIT_UNKNOWN, 1);
2533 		break;
2534 	}
2535 
2536 	if (handled) {
2537 		/*
2538 		 * It is possible that control is returned to userland
2539 		 * even though we were able to handle the VM exit in the
2540 		 * kernel.
2541 		 *
2542 		 * In such a case we want to make sure that the userland
2543 		 * restarts guest execution at the instruction *after*
2544 		 * the one we just processed. Therefore we update the
2545 		 * guest rip in the VMCS and in 'vmexit'.
2546 		 */
2547 		vmexit->rip += vmexit->inst_length;
2548 		vmexit->inst_length = 0;
2549 		vmcs_write(VMCS_GUEST_RIP, vmexit->rip);
2550 	} else {
2551 		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
2552 			/*
2553 			 * If this VM exit was not claimed by anybody then
2554 			 * treat it as a generic VMX exit.
2555 			 */
2556 			vmexit->exitcode = VM_EXITCODE_VMX;
2557 			vmexit->u.vmx.status = VM_SUCCESS;
2558 			vmexit->u.vmx.inst_type = 0;
2559 			vmexit->u.vmx.inst_error = 0;
2560 		} else {
2561 			/*
2562 			 * The exitcode and collateral have been populated.
2563 			 * The VM exit will be processed further in userland.
2564 			 */
2565 		}
2566 	}
2567 
2568 	SDT_PROBE4(vmm, vmx, exit, return,
2569 	    vmx, vcpu, vmexit, handled);
2570 	return (handled);
2571 }
2572 
2573 static void
2574 vmx_exit_inst_error(struct vmxctx *vmxctx, int rc, struct vm_exit *vmexit)
2575 {
2576 
2577 	KASSERT(vmxctx->inst_fail_status != VM_SUCCESS,
2578 	    ("vmx_exit_inst_error: invalid inst_fail_status %d",
2579 	    vmxctx->inst_fail_status));
2580 
2581 	vmexit->inst_length = 0;
2582 	vmexit->exitcode = VM_EXITCODE_VMX;
2583 	vmexit->u.vmx.status = vmxctx->inst_fail_status;
2584 	vmexit->u.vmx.inst_error = vmcs_read(VMCS_INSTRUCTION_ERROR);
2585 	vmexit->u.vmx.exit_reason = ~0;
2586 	vmexit->u.vmx.exit_qualification = ~0;
2587 
2588 	switch (rc) {
2589 	case VMX_VMRESUME_ERROR:
2590 	case VMX_VMLAUNCH_ERROR:
2591 	case VMX_INVEPT_ERROR:
2592 	case VMX_VMWRITE_ERROR:
2593 		vmexit->u.vmx.inst_type = rc;
2594 		break;
2595 	default:
2596 		panic("vm_exit_inst_error: vmx_enter_guest returned %d", rc);
2597 	}
2598 }
2599 
2600 /*
2601  * If the NMI-exiting VM execution control is set to '1' then an NMI in
2602  * non-root operation causes a VM-exit. NMI blocking is in effect so it is
2603  * sufficient to simply vector to the NMI handler via a software interrupt.
2604  * However, this must be done before maskable interrupts are enabled
2605  * otherwise the "iret" issued by an interrupt handler will incorrectly
2606  * clear NMI blocking.
2607  */
2608 static __inline void
2609 vmx_exit_handle_possible_nmi(struct vm_exit *vmexit)
2610 {
2611 	ASSERT(!interrupts_enabled());
2612 
2613 	if (vmexit->u.vmx.exit_reason == EXIT_REASON_EXCEPTION) {
2614 		uint32_t intr_info = vmcs_read(VMCS_EXIT_INTR_INFO);
2615 		ASSERT(intr_info & VMCS_INTR_VALID);
2616 
2617 		if ((intr_info & VMCS_INTR_T_MASK) == VMCS_INTR_T_NMI) {
2618 			ASSERT3U(intr_info & 0xff, ==, IDT_NMI);
2619 			vmm_call_trap(T_NMIFLT);
2620 		}
2621 	}
2622 }
2623 
2624 static __inline void
2625 vmx_dr_enter_guest(struct vmxctx *vmxctx)
2626 {
2627 	uint64_t rflags;
2628 
2629 	/* Save host control debug registers. */
2630 	vmxctx->host_dr7 = rdr7();
2631 	vmxctx->host_debugctl = rdmsr(MSR_DEBUGCTLMSR);
2632 
2633 	/*
2634 	 * Disable debugging in DR7 and DEBUGCTL to avoid triggering
2635 	 * exceptions in the host based on the guest DRx values.  The
2636 	 * guest DR7 and DEBUGCTL are saved/restored in the VMCS.
2637 	 */
2638 	load_dr7(0);
2639 	wrmsr(MSR_DEBUGCTLMSR, 0);
2640 
2641 	/*
2642 	 * Disable single stepping the kernel to avoid corrupting the
2643 	 * guest DR6.  A debugger might still be able to corrupt the
2644 	 * guest DR6 by setting a breakpoint after this point and then
2645 	 * single stepping.
2646 	 */
2647 	rflags = read_rflags();
2648 	vmxctx->host_tf = rflags & PSL_T;
2649 	write_rflags(rflags & ~PSL_T);
2650 
2651 	/* Save host debug registers. */
2652 	vmxctx->host_dr0 = rdr0();
2653 	vmxctx->host_dr1 = rdr1();
2654 	vmxctx->host_dr2 = rdr2();
2655 	vmxctx->host_dr3 = rdr3();
2656 	vmxctx->host_dr6 = rdr6();
2657 
2658 	/* Restore guest debug registers. */
2659 	load_dr0(vmxctx->guest_dr0);
2660 	load_dr1(vmxctx->guest_dr1);
2661 	load_dr2(vmxctx->guest_dr2);
2662 	load_dr3(vmxctx->guest_dr3);
2663 	load_dr6(vmxctx->guest_dr6);
2664 }
2665 
2666 static __inline void
2667 vmx_dr_leave_guest(struct vmxctx *vmxctx)
2668 {
2669 
2670 	/* Save guest debug registers. */
2671 	vmxctx->guest_dr0 = rdr0();
2672 	vmxctx->guest_dr1 = rdr1();
2673 	vmxctx->guest_dr2 = rdr2();
2674 	vmxctx->guest_dr3 = rdr3();
2675 	vmxctx->guest_dr6 = rdr6();
2676 
2677 	/*
2678 	 * Restore host debug registers.  Restore DR7, DEBUGCTL, and
2679 	 * PSL_T last.
2680 	 */
2681 	load_dr0(vmxctx->host_dr0);
2682 	load_dr1(vmxctx->host_dr1);
2683 	load_dr2(vmxctx->host_dr2);
2684 	load_dr3(vmxctx->host_dr3);
2685 	load_dr6(vmxctx->host_dr6);
2686 	wrmsr(MSR_DEBUGCTLMSR, vmxctx->host_debugctl);
2687 	load_dr7(vmxctx->host_dr7);
2688 	write_rflags(read_rflags() | vmxctx->host_tf);
2689 }
2690 
2691 static int
2692 vmx_run(void *arg, int vcpu, uint64_t rip)
2693 {
2694 	int rc, handled, launched;
2695 	struct vmx *vmx;
2696 	struct vm *vm;
2697 	struct vmxctx *vmxctx;
2698 	uintptr_t vmcs_pa;
2699 	struct vm_exit *vmexit;
2700 	struct vlapic *vlapic;
2701 	uint32_t exit_reason;
2702 	bool tpr_shadow_active;
2703 	vm_client_t *vmc;
2704 
2705 	vmx = arg;
2706 	vm = vmx->vm;
2707 	vmcs_pa = vmx->vmcs_pa[vcpu];
2708 	vmxctx = &vmx->ctx[vcpu];
2709 	vlapic = vm_lapic(vm, vcpu);
2710 	vmexit = vm_exitinfo(vm, vcpu);
2711 	vmc = vm_get_vmclient(vm, vcpu);
2712 	launched = 0;
2713 	tpr_shadow_active = vmx_cap_en(vmx, VMX_CAP_TPR_SHADOW) &&
2714 	    !vmx_cap_en(vmx, VMX_CAP_APICV) &&
2715 	    (vmx->cap[vcpu].proc_ctls & PROCBASED_USE_TPR_SHADOW) != 0;
2716 
2717 	vmx_msr_guest_enter(vmx, vcpu);
2718 
2719 	vmcs_load(vmcs_pa);
2720 
2721 	VERIFY(vmx->vmcs_state[vcpu] == VS_NONE && curthread->t_preempt != 0);
2722 	vmx->vmcs_state[vcpu] = VS_LOADED;
2723 
2724 	/*
2725 	 * XXX
2726 	 * We do this every time because we may setup the virtual machine
2727 	 * from a different process than the one that actually runs it.
2728 	 *
2729 	 * If the life of a virtual machine was spent entirely in the context
2730 	 * of a single process we could do this once in vmx_vminit().
2731 	 */
2732 	vmcs_write(VMCS_HOST_CR3, rcr3());
2733 
2734 	vmcs_write(VMCS_GUEST_RIP, rip);
2735 	vmx_set_pcpu_defaults(vmx, vcpu);
2736 	do {
2737 		enum event_inject_state inject_state;
2738 		uint64_t eptgen;
2739 
2740 		ASSERT3U(vmcs_read(VMCS_GUEST_RIP), ==, rip);
2741 
2742 		handled = UNHANDLED;
2743 
2744 		/*
2745 		 * Perform initial event/exception/interrupt injection before
2746 		 * host CPU interrupts are disabled.
2747 		 */
2748 		inject_state = vmx_inject_events(vmx, vcpu, rip);
2749 
2750 		/*
2751 		 * Interrupts are disabled from this point on until the
2752 		 * guest starts executing. This is done for the following
2753 		 * reasons:
2754 		 *
2755 		 * If an AST is asserted on this thread after the check below,
2756 		 * then the IPI_AST notification will not be lost, because it
2757 		 * will cause a VM exit due to external interrupt as soon as
2758 		 * the guest state is loaded.
2759 		 *
2760 		 * A posted interrupt after vmx_inject_vlapic() will not be
2761 		 * "lost" because it will be held pending in the host APIC
2762 		 * because interrupts are disabled. The pending interrupt will
2763 		 * be recognized as soon as the guest state is loaded.
2764 		 *
2765 		 * The same reasoning applies to the IPI generated by vmspace
2766 		 * invalidation.
2767 		 */
2768 		disable_intr();
2769 
2770 		/*
2771 		 * If not precluded by existing events, inject any interrupt
2772 		 * pending on the vLAPIC.  As a lock-less operation, it is safe
2773 		 * (and prudent) to perform with host CPU interrupts disabled.
2774 		 */
2775 		if (inject_state == EIS_CAN_INJECT) {
2776 			inject_state = vmx_inject_vlapic(vmx, vcpu, vlapic);
2777 		}
2778 
2779 		/*
2780 		 * Check for vCPU bail-out conditions.  This must be done after
2781 		 * vmx_inject_events() to detect a triple-fault condition.
2782 		 */
2783 		if (vcpu_entry_bailout_checks(vmx->vm, vcpu, rip)) {
2784 			enable_intr();
2785 			break;
2786 		}
2787 
2788 		if (vcpu_run_state_pending(vm, vcpu)) {
2789 			enable_intr();
2790 			vm_exit_run_state(vmx->vm, vcpu, rip);
2791 			break;
2792 		}
2793 
2794 		/*
2795 		 * If subsequent activity queued events which require injection
2796 		 * handling, take another lap to handle them.
2797 		 */
2798 		if (vmx_inject_recheck(vmx, vcpu, inject_state)) {
2799 			enable_intr();
2800 			handled = HANDLED;
2801 			continue;
2802 		}
2803 
2804 		if ((rc = smt_acquire()) != 1) {
2805 			enable_intr();
2806 			vmexit->rip = rip;
2807 			vmexit->inst_length = 0;
2808 			if (rc == -1) {
2809 				vmexit->exitcode = VM_EXITCODE_HT;
2810 			} else {
2811 				vmexit->exitcode = VM_EXITCODE_BOGUS;
2812 				handled = HANDLED;
2813 			}
2814 			break;
2815 		}
2816 
2817 		/*
2818 		 * If this thread has gone off-cpu due to mutex operations
2819 		 * during vmx_run, the VMCS will have been unloaded, forcing a
2820 		 * re-VMLAUNCH as opposed to VMRESUME.
2821 		 */
2822 		launched = (vmx->vmcs_state[vcpu] & VS_LAUNCHED) != 0;
2823 		/*
2824 		 * Restoration of the GDT limit is taken care of by
2825 		 * vmx_savectx().  Since the maximum practical index for the
2826 		 * IDT is 255, restoring its limits from the post-VMX-exit
2827 		 * default of 0xffff is not a concern.
2828 		 *
2829 		 * Only 64-bit hypervisor callers are allowed, which forgoes
2830 		 * the need to restore any LDT descriptor.  Toss an error to
2831 		 * anyone attempting to break that rule.
2832 		 */
2833 		if (curproc->p_model != DATAMODEL_LP64) {
2834 			smt_release();
2835 			enable_intr();
2836 			bzero(vmexit, sizeof (*vmexit));
2837 			vmexit->rip = rip;
2838 			vmexit->exitcode = VM_EXITCODE_VMX;
2839 			vmexit->u.vmx.status = VM_FAIL_INVALID;
2840 			handled = UNHANDLED;
2841 			break;
2842 		}
2843 
2844 		if (tpr_shadow_active) {
2845 			vmx_tpr_shadow_enter(vlapic);
2846 		}
2847 
2848 		/*
2849 		 * Indicate activation of vmspace (EPT) table just prior to VMX
2850 		 * entry, checking for the necessity of an invept invalidation.
2851 		 */
2852 		eptgen = vmc_table_enter(vmc);
2853 		if (vmx->eptgen[curcpu] != eptgen) {
2854 			/*
2855 			 * VMspace generation does not match what was previously
2856 			 * used on this host CPU, so all mappings associated
2857 			 * with this EP4TA must be invalidated.
2858 			 */
2859 			invept(1, vmx->eptp);
2860 			vmx->eptgen[curcpu] = eptgen;
2861 		}
2862 
2863 		vcpu_ustate_change(vm, vcpu, VU_RUN);
2864 		vmx_dr_enter_guest(vmxctx);
2865 
2866 		/* Perform VMX entry */
2867 		rc = vmx_enter_guest(vmxctx, vmx, launched);
2868 
2869 		vmx_dr_leave_guest(vmxctx);
2870 		vcpu_ustate_change(vm, vcpu, VU_EMU_KERN);
2871 
2872 		vmx->vmcs_state[vcpu] |= VS_LAUNCHED;
2873 		smt_release();
2874 
2875 		if (tpr_shadow_active) {
2876 			vmx_tpr_shadow_exit(vlapic);
2877 		}
2878 
2879 		/* Collect some information for VM exit processing */
2880 		vmexit->rip = rip = vmcs_read(VMCS_GUEST_RIP);
2881 		vmexit->inst_length = vmcs_read(VMCS_EXIT_INSTRUCTION_LENGTH);
2882 		vmexit->u.vmx.exit_reason = exit_reason =
2883 		    (vmcs_read(VMCS_EXIT_REASON) & BASIC_EXIT_REASON_MASK);
2884 		vmexit->u.vmx.exit_qualification =
2885 		    vmcs_read(VMCS_EXIT_QUALIFICATION);
2886 		/* Update 'nextrip' */
2887 		vmx->state[vcpu].nextrip = rip;
2888 
2889 		if (rc == VMX_GUEST_VMEXIT) {
2890 			vmx_exit_handle_possible_nmi(vmexit);
2891 		}
2892 		enable_intr();
2893 		vmc_table_exit(vmc);
2894 
2895 		if (rc == VMX_GUEST_VMEXIT) {
2896 			handled = vmx_exit_process(vmx, vcpu, vmexit);
2897 		} else {
2898 			vmx_exit_inst_error(vmxctx, rc, vmexit);
2899 		}
2900 		DTRACE_PROBE3(vmm__vexit, int, vcpu, uint64_t, rip,
2901 		    uint32_t, exit_reason);
2902 		rip = vmexit->rip;
2903 	} while (handled);
2904 
2905 	/* If a VM exit has been handled then the exitcode must be BOGUS */
2906 	if (handled && vmexit->exitcode != VM_EXITCODE_BOGUS) {
2907 		panic("Non-BOGUS exitcode (%d) unexpected for handled VM exit",
2908 		    vmexit->exitcode);
2909 	}
2910 
2911 	vmcs_clear(vmcs_pa);
2912 	vmx_msr_guest_exit(vmx, vcpu);
2913 
2914 	VERIFY(vmx->vmcs_state != VS_NONE && curthread->t_preempt != 0);
2915 	vmx->vmcs_state[vcpu] = VS_NONE;
2916 
2917 	return (0);
2918 }
2919 
2920 static void
2921 vmx_vmcleanup(void *arg)
2922 {
2923 	int i;
2924 	struct vmx *vmx = arg;
2925 	uint16_t maxcpus;
2926 
2927 	if (vmx_cap_en(vmx, VMX_CAP_APICV)) {
2928 		(void) vm_unmap_mmio(vmx->vm, DEFAULT_APIC_BASE, PAGE_SIZE);
2929 		kmem_free(vmx->apic_access_page, PAGESIZE);
2930 	} else {
2931 		VERIFY3P(vmx->apic_access_page, ==, NULL);
2932 	}
2933 
2934 	vmx_msr_bitmap_destroy(vmx);
2935 
2936 	maxcpus = vm_get_maxcpus(vmx->vm);
2937 	for (i = 0; i < maxcpus; i++)
2938 		vpid_free(vmx->state[i].vpid);
2939 
2940 	free(vmx, M_VMX);
2941 }
2942 
2943 static uint64_t *
2944 vmxctx_regptr(struct vmxctx *vmxctx, int reg)
2945 {
2946 	switch (reg) {
2947 	case VM_REG_GUEST_RAX:
2948 		return (&vmxctx->guest_rax);
2949 	case VM_REG_GUEST_RBX:
2950 		return (&vmxctx->guest_rbx);
2951 	case VM_REG_GUEST_RCX:
2952 		return (&vmxctx->guest_rcx);
2953 	case VM_REG_GUEST_RDX:
2954 		return (&vmxctx->guest_rdx);
2955 	case VM_REG_GUEST_RSI:
2956 		return (&vmxctx->guest_rsi);
2957 	case VM_REG_GUEST_RDI:
2958 		return (&vmxctx->guest_rdi);
2959 	case VM_REG_GUEST_RBP:
2960 		return (&vmxctx->guest_rbp);
2961 	case VM_REG_GUEST_R8:
2962 		return (&vmxctx->guest_r8);
2963 	case VM_REG_GUEST_R9:
2964 		return (&vmxctx->guest_r9);
2965 	case VM_REG_GUEST_R10:
2966 		return (&vmxctx->guest_r10);
2967 	case VM_REG_GUEST_R11:
2968 		return (&vmxctx->guest_r11);
2969 	case VM_REG_GUEST_R12:
2970 		return (&vmxctx->guest_r12);
2971 	case VM_REG_GUEST_R13:
2972 		return (&vmxctx->guest_r13);
2973 	case VM_REG_GUEST_R14:
2974 		return (&vmxctx->guest_r14);
2975 	case VM_REG_GUEST_R15:
2976 		return (&vmxctx->guest_r15);
2977 	case VM_REG_GUEST_CR2:
2978 		return (&vmxctx->guest_cr2);
2979 	case VM_REG_GUEST_DR0:
2980 		return (&vmxctx->guest_dr0);
2981 	case VM_REG_GUEST_DR1:
2982 		return (&vmxctx->guest_dr1);
2983 	case VM_REG_GUEST_DR2:
2984 		return (&vmxctx->guest_dr2);
2985 	case VM_REG_GUEST_DR3:
2986 		return (&vmxctx->guest_dr3);
2987 	case VM_REG_GUEST_DR6:
2988 		return (&vmxctx->guest_dr6);
2989 	default:
2990 		break;
2991 	}
2992 	return (NULL);
2993 }
2994 
2995 static int
2996 vmx_getreg(void *arg, int vcpu, int reg, uint64_t *retval)
2997 {
2998 	int running, hostcpu, err;
2999 	struct vmx *vmx = arg;
3000 	uint64_t *regp;
3001 
3002 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3003 	if (running && hostcpu != curcpu)
3004 		panic("vmx_getreg: %d is running", vcpu);
3005 
3006 	/* VMCS access not required for ctx reads */
3007 	if ((regp = vmxctx_regptr(&vmx->ctx[vcpu], reg)) != NULL) {
3008 		*retval = *regp;
3009 		return (0);
3010 	}
3011 
3012 	if (!running) {
3013 		vmcs_load(vmx->vmcs_pa[vcpu]);
3014 	}
3015 
3016 	err = 0;
3017 	if (reg == VM_REG_GUEST_INTR_SHADOW) {
3018 		uint64_t gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
3019 		*retval = (gi & HWINTR_BLOCKING) ? 1 : 0;
3020 	} else {
3021 		uint32_t encoding;
3022 
3023 		encoding = vmcs_field_encoding(reg);
3024 		switch (encoding) {
3025 		case VMCS_GUEST_CR0:
3026 			/* Take the shadow bits into account */
3027 			*retval = vmx_unshadow_cr0(vmcs_read(encoding),
3028 			    vmcs_read(VMCS_CR0_SHADOW));
3029 			break;
3030 		case VMCS_GUEST_CR4:
3031 			/* Take the shadow bits into account */
3032 			*retval = vmx_unshadow_cr4(vmcs_read(encoding),
3033 			    vmcs_read(VMCS_CR4_SHADOW));
3034 			break;
3035 		case VMCS_INVALID_ENCODING:
3036 			err = EINVAL;
3037 			break;
3038 		default:
3039 			*retval = vmcs_read(encoding);
3040 			break;
3041 		}
3042 	}
3043 
3044 	if (!running) {
3045 		vmcs_clear(vmx->vmcs_pa[vcpu]);
3046 	}
3047 
3048 	return (err);
3049 }
3050 
3051 static int
3052 vmx_setreg(void *arg, int vcpu, int reg, uint64_t val)
3053 {
3054 	int running, hostcpu, error;
3055 	struct vmx *vmx = arg;
3056 	uint64_t *regp;
3057 
3058 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3059 	if (running && hostcpu != curcpu)
3060 		panic("vmx_setreg: %d is running", vcpu);
3061 
3062 	/* VMCS access not required for ctx writes */
3063 	if ((regp = vmxctx_regptr(&vmx->ctx[vcpu], reg)) != NULL) {
3064 		*regp = val;
3065 		return (0);
3066 	}
3067 
3068 	if (!running) {
3069 		vmcs_load(vmx->vmcs_pa[vcpu]);
3070 	}
3071 
3072 	if (reg == VM_REG_GUEST_INTR_SHADOW) {
3073 		if (val != 0) {
3074 			/*
3075 			 * Forcing the vcpu into an interrupt shadow is not
3076 			 * presently supported.
3077 			 */
3078 			error = EINVAL;
3079 		} else {
3080 			uint64_t gi;
3081 
3082 			gi = vmcs_read(VMCS_GUEST_INTERRUPTIBILITY);
3083 			gi &= ~HWINTR_BLOCKING;
3084 			vmcs_write(VMCS_GUEST_INTERRUPTIBILITY, gi);
3085 			error = 0;
3086 		}
3087 	} else {
3088 		uint32_t encoding;
3089 
3090 		error = 0;
3091 		encoding = vmcs_field_encoding(reg);
3092 		switch (encoding) {
3093 		case VMCS_GUEST_IA32_EFER:
3094 			/*
3095 			 * If the "load EFER" VM-entry control is 1 then the
3096 			 * value of EFER.LMA must be identical to "IA-32e mode
3097 			 * guest" bit in the VM-entry control.
3098 			 */
3099 			if ((entry_ctls & VM_ENTRY_LOAD_EFER) != 0) {
3100 				uint64_t ctls;
3101 
3102 				ctls = vmcs_read(VMCS_ENTRY_CTLS);
3103 				if (val & EFER_LMA) {
3104 					ctls |= VM_ENTRY_GUEST_LMA;
3105 				} else {
3106 					ctls &= ~VM_ENTRY_GUEST_LMA;
3107 				}
3108 				vmcs_write(VMCS_ENTRY_CTLS, ctls);
3109 			}
3110 			vmcs_write(encoding, val);
3111 			break;
3112 		case VMCS_GUEST_CR0:
3113 			/*
3114 			 * The guest is not allowed to modify certain bits in
3115 			 * %cr0 and %cr4.  To maintain the illusion of full
3116 			 * control, they have shadow versions which contain the
3117 			 * guest-perceived (via reads from the register) values
3118 			 * as opposed to the guest-effective values.
3119 			 *
3120 			 * This is detailed in the SDM: Vol. 3 Ch. 24.6.6.
3121 			 */
3122 			vmcs_write(VMCS_CR0_SHADOW, val);
3123 			vmcs_write(encoding, vmx_fix_cr0(val));
3124 			break;
3125 		case VMCS_GUEST_CR4:
3126 			/* See above for detail on %cr4 shadowing */
3127 			vmcs_write(VMCS_CR4_SHADOW, val);
3128 			vmcs_write(encoding, vmx_fix_cr4(val));
3129 			break;
3130 		case VMCS_GUEST_CR3:
3131 			vmcs_write(encoding, val);
3132 			/*
3133 			 * Invalidate the guest vcpu's TLB mappings to emulate
3134 			 * the behavior of updating %cr3.
3135 			 *
3136 			 * XXX the processor retains global mappings when %cr3
3137 			 * is updated but vmx_invvpid() does not.
3138 			 */
3139 			vmx_invvpid(vmx, vcpu, running);
3140 			break;
3141 		case VMCS_INVALID_ENCODING:
3142 			error = EINVAL;
3143 			break;
3144 		default:
3145 			vmcs_write(encoding, val);
3146 			break;
3147 		}
3148 	}
3149 
3150 	if (!running) {
3151 		vmcs_clear(vmx->vmcs_pa[vcpu]);
3152 	}
3153 
3154 	return (error);
3155 }
3156 
3157 static int
3158 vmx_getdesc(void *arg, int vcpu, int seg, struct seg_desc *desc)
3159 {
3160 	int hostcpu, running;
3161 	struct vmx *vmx = arg;
3162 	uint32_t base, limit, access;
3163 
3164 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3165 	if (running && hostcpu != curcpu)
3166 		panic("vmx_getdesc: %d is running", vcpu);
3167 
3168 	if (!running) {
3169 		vmcs_load(vmx->vmcs_pa[vcpu]);
3170 	}
3171 
3172 	vmcs_seg_desc_encoding(seg, &base, &limit, &access);
3173 	desc->base = vmcs_read(base);
3174 	desc->limit = vmcs_read(limit);
3175 	if (access != VMCS_INVALID_ENCODING) {
3176 		desc->access = vmcs_read(access);
3177 	} else {
3178 		desc->access = 0;
3179 	}
3180 
3181 	if (!running) {
3182 		vmcs_clear(vmx->vmcs_pa[vcpu]);
3183 	}
3184 	return (0);
3185 }
3186 
3187 static int
3188 vmx_setdesc(void *arg, int vcpu, int seg, const struct seg_desc *desc)
3189 {
3190 	int hostcpu, running;
3191 	struct vmx *vmx = arg;
3192 	uint32_t base, limit, access;
3193 
3194 	running = vcpu_is_running(vmx->vm, vcpu, &hostcpu);
3195 	if (running && hostcpu != curcpu)
3196 		panic("vmx_setdesc: %d is running", vcpu);
3197 
3198 	if (!running) {
3199 		vmcs_load(vmx->vmcs_pa[vcpu]);
3200 	}
3201 
3202 	vmcs_seg_desc_encoding(seg, &base, &limit, &access);
3203 	vmcs_write(base, desc->base);
3204 	vmcs_write(limit, desc->limit);
3205 	if (access != VMCS_INVALID_ENCODING) {
3206 		vmcs_write(access, desc->access);
3207 	}
3208 
3209 	if (!running) {
3210 		vmcs_clear(vmx->vmcs_pa[vcpu]);
3211 	}
3212 	return (0);
3213 }
3214 
3215 static int
3216 vmx_getcap(void *arg, int vcpu, int type, int *retval)
3217 {
3218 	struct vmx *vmx = arg;
3219 	int vcap;
3220 	int ret;
3221 
3222 	ret = ENOENT;
3223 
3224 	vcap = vmx->cap[vcpu].set;
3225 
3226 	switch (type) {
3227 	case VM_CAP_HALT_EXIT:
3228 		if (cap_halt_exit)
3229 			ret = 0;
3230 		break;
3231 	case VM_CAP_PAUSE_EXIT:
3232 		if (cap_pause_exit)
3233 			ret = 0;
3234 		break;
3235 	case VM_CAP_MTRAP_EXIT:
3236 		if (cap_monitor_trap)
3237 			ret = 0;
3238 		break;
3239 	case VM_CAP_ENABLE_INVPCID:
3240 		if (cap_invpcid)
3241 			ret = 0;
3242 		break;
3243 	case VM_CAP_BPT_EXIT:
3244 		ret = 0;
3245 		break;
3246 	default:
3247 		break;
3248 	}
3249 
3250 	if (ret == 0)
3251 		*retval = (vcap & (1 << type)) ? 1 : 0;
3252 
3253 	return (ret);
3254 }
3255 
3256 static int
3257 vmx_setcap(void *arg, int vcpu, int type, int val)
3258 {
3259 	struct vmx *vmx = arg;
3260 	uint32_t baseval, reg, flag;
3261 	uint32_t *pptr;
3262 	int error;
3263 
3264 	error = ENOENT;
3265 	pptr = NULL;
3266 
3267 	switch (type) {
3268 	case VM_CAP_HALT_EXIT:
3269 		if (cap_halt_exit) {
3270 			error = 0;
3271 			pptr = &vmx->cap[vcpu].proc_ctls;
3272 			baseval = *pptr;
3273 			flag = PROCBASED_HLT_EXITING;
3274 			reg = VMCS_PRI_PROC_BASED_CTLS;
3275 		}
3276 		break;
3277 	case VM_CAP_MTRAP_EXIT:
3278 		if (cap_monitor_trap) {
3279 			error = 0;
3280 			pptr = &vmx->cap[vcpu].proc_ctls;
3281 			baseval = *pptr;
3282 			flag = PROCBASED_MTF;
3283 			reg = VMCS_PRI_PROC_BASED_CTLS;
3284 		}
3285 		break;
3286 	case VM_CAP_PAUSE_EXIT:
3287 		if (cap_pause_exit) {
3288 			error = 0;
3289 			pptr = &vmx->cap[vcpu].proc_ctls;
3290 			baseval = *pptr;
3291 			flag = PROCBASED_PAUSE_EXITING;
3292 			reg = VMCS_PRI_PROC_BASED_CTLS;
3293 		}
3294 		break;
3295 	case VM_CAP_ENABLE_INVPCID:
3296 		if (cap_invpcid) {
3297 			error = 0;
3298 			pptr = &vmx->cap[vcpu].proc_ctls2;
3299 			baseval = *pptr;
3300 			flag = PROCBASED2_ENABLE_INVPCID;
3301 			reg = VMCS_SEC_PROC_BASED_CTLS;
3302 		}
3303 		break;
3304 	case VM_CAP_BPT_EXIT:
3305 		error = 0;
3306 
3307 		/* Don't change the bitmap if we are tracing all exceptions. */
3308 		if (vmx->cap[vcpu].exc_bitmap != 0xffffffff) {
3309 			pptr = &vmx->cap[vcpu].exc_bitmap;
3310 			baseval = *pptr;
3311 			flag = (1 << IDT_BP);
3312 			reg = VMCS_EXCEPTION_BITMAP;
3313 		}
3314 		break;
3315 	default:
3316 		break;
3317 	}
3318 
3319 	if (error != 0) {
3320 		return (error);
3321 	}
3322 
3323 	if (pptr != NULL) {
3324 		if (val) {
3325 			baseval |= flag;
3326 		} else {
3327 			baseval &= ~flag;
3328 		}
3329 		vmcs_load(vmx->vmcs_pa[vcpu]);
3330 		vmcs_write(reg, baseval);
3331 		vmcs_clear(vmx->vmcs_pa[vcpu]);
3332 
3333 		/*
3334 		 * Update optional stored flags, and record
3335 		 * setting
3336 		 */
3337 		*pptr = baseval;
3338 	}
3339 
3340 	if (val) {
3341 		vmx->cap[vcpu].set |= (1 << type);
3342 	} else {
3343 		vmx->cap[vcpu].set &= ~(1 << type);
3344 	}
3345 
3346 	return (0);
3347 }
3348 
3349 struct vlapic_vtx {
3350 	struct vlapic	vlapic;
3351 
3352 	/* Align to the nearest cacheline */
3353 	uint8_t		_pad[64 - (sizeof (struct vlapic) % 64)];
3354 
3355 	/* TMR handling state for posted interrupts */
3356 	uint32_t	tmr_active[8];
3357 	uint32_t	pending_level[8];
3358 	uint32_t	pending_edge[8];
3359 
3360 	struct pir_desc	*pir_desc;
3361 	struct vmx	*vmx;
3362 	uint_t	pending_prio;
3363 	boolean_t	tmr_sync;
3364 };
3365 
3366 CTASSERT((offsetof(struct vlapic_vtx, tmr_active) & 63) == 0);
3367 
3368 #define	VPR_PRIO_BIT(vpr)	(1 << ((vpr) >> 4))
3369 
3370 static vcpu_notify_t
3371 vmx_apicv_set_ready(struct vlapic *vlapic, int vector, bool level)
3372 {
3373 	struct vlapic_vtx *vlapic_vtx;
3374 	struct pir_desc *pir_desc;
3375 	uint32_t mask, tmrval;
3376 	int idx;
3377 	vcpu_notify_t notify = VCPU_NOTIFY_NONE;
3378 
3379 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3380 	pir_desc = vlapic_vtx->pir_desc;
3381 	idx = vector / 32;
3382 	mask = 1UL << (vector % 32);
3383 
3384 	/*
3385 	 * If the currently asserted TMRs do not match the state requested by
3386 	 * the incoming interrupt, an exit will be required to reconcile those
3387 	 * bits in the APIC page.  This will keep the vLAPIC behavior in line
3388 	 * with the architecturally defined expectations.
3389 	 *
3390 	 * If actors of mixed types (edge and level) are racing against the same
3391 	 * vector (toggling its TMR bit back and forth), the results could
3392 	 * inconsistent.  Such circumstances are considered a rare edge case and
3393 	 * are never expected to be found in the wild.
3394 	 */
3395 	tmrval = atomic_load_acq_int(&vlapic_vtx->tmr_active[idx]);
3396 	if (!level) {
3397 		if ((tmrval & mask) != 0) {
3398 			/* Edge-triggered interrupt needs TMR de-asserted */
3399 			atomic_set_int(&vlapic_vtx->pending_edge[idx], mask);
3400 			atomic_store_rel_long(&pir_desc->pending, 1);
3401 			return (VCPU_NOTIFY_EXIT);
3402 		}
3403 	} else {
3404 		if ((tmrval & mask) == 0) {
3405 			/* Level-triggered interrupt needs TMR asserted */
3406 			atomic_set_int(&vlapic_vtx->pending_level[idx], mask);
3407 			atomic_store_rel_long(&pir_desc->pending, 1);
3408 			return (VCPU_NOTIFY_EXIT);
3409 		}
3410 	}
3411 
3412 	/*
3413 	 * If the interrupt request does not require manipulation of the TMRs
3414 	 * for delivery, set it in PIR descriptor.  It cannot be inserted into
3415 	 * the APIC page while the vCPU might be running.
3416 	 */
3417 	atomic_set_int(&pir_desc->pir[idx], mask);
3418 
3419 	/*
3420 	 * A notification is required whenever the 'pending' bit makes a
3421 	 * transition from 0->1.
3422 	 *
3423 	 * Even if the 'pending' bit is already asserted, notification about
3424 	 * the incoming interrupt may still be necessary.  For example, if a
3425 	 * vCPU is HLTed with a high PPR, a low priority interrupt would cause
3426 	 * the 0->1 'pending' transition with a notification, but the vCPU
3427 	 * would ignore the interrupt for the time being.  The same vCPU would
3428 	 * need to then be notified if a high-priority interrupt arrived which
3429 	 * satisfied the PPR.
3430 	 *
3431 	 * The priorities of interrupts injected while 'pending' is asserted
3432 	 * are tracked in a custom bitfield 'pending_prio'.  Should the
3433 	 * to-be-injected interrupt exceed the priorities already present, the
3434 	 * notification is sent.  The priorities recorded in 'pending_prio' are
3435 	 * cleared whenever the 'pending' bit makes another 0->1 transition.
3436 	 */
3437 	if (atomic_cmpset_long(&pir_desc->pending, 0, 1) != 0) {
3438 		notify = VCPU_NOTIFY_APIC;
3439 		vlapic_vtx->pending_prio = 0;
3440 	} else {
3441 		const uint_t old_prio = vlapic_vtx->pending_prio;
3442 		const uint_t prio_bit = VPR_PRIO_BIT(vector & APIC_TPR_INT);
3443 
3444 		if ((old_prio & prio_bit) == 0 && prio_bit > old_prio) {
3445 			atomic_set_int(&vlapic_vtx->pending_prio, prio_bit);
3446 			notify = VCPU_NOTIFY_APIC;
3447 		}
3448 	}
3449 
3450 	return (notify);
3451 }
3452 
3453 static void
3454 vmx_apicv_accepted(struct vlapic *vlapic, int vector)
3455 {
3456 	/*
3457 	 * When APICv is enabled for an instance, the traditional interrupt
3458 	 * injection method (populating ENTRY_INTR_INFO in the VMCS) is not
3459 	 * used and the CPU does the heavy lifting of virtual interrupt
3460 	 * delivery.  For that reason vmx_intr_accepted() should never be called
3461 	 * when APICv is enabled.
3462 	 */
3463 	panic("vmx_intr_accepted: not expected to be called");
3464 }
3465 
3466 static void
3467 vmx_apicv_sync_tmr(struct vlapic *vlapic)
3468 {
3469 	struct vlapic_vtx *vlapic_vtx;
3470 	const uint32_t *tmrs;
3471 
3472 	vlapic_vtx = (struct vlapic_vtx *)vlapic;
3473 	tmrs = &vlapic_vtx->tmr_active[0];
3474 
3475 	if (!vlapic_vtx->tmr_sync) {
3476 		return;
3477 	}
3478 
3479 	vmcs_write(VMCS_EOI_EXIT0, ((uint64_t)tmrs[1] << 32) | tmrs[0]);
3480 	vmcs_write(VMCS_EOI_EXIT1, ((uint64_t)tmrs[3] << 32) | tmrs[2]);
3481 	vmcs_write(VMCS_EOI_EXIT2, ((uint64_t)tmrs[5] << 32) | tmrs[4]);
3482 	vmcs_write(VMCS_EOI_EXIT3, ((uint64_t)tmrs[7] << 32) | tmrs[6]);
3483 	vlapic_vtx->tmr_sync = B_FALSE;
3484 }
3485 
3486 static void
3487 vmx_enable_x2apic_mode_ts(struct vlapic *vlapic)
3488 {
3489 	struct vmx *vmx;
3490 	uint32_t proc_ctls;
3491 	int vcpuid;
3492 
3493 	vcpuid = vlapic->vcpuid;
3494 	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3495 
3496 	proc_ctls = vmx->cap[vcpuid].proc_ctls;
3497 	proc_ctls &= ~PROCBASED_USE_TPR_SHADOW;
3498 	proc_ctls |= PROCBASED_CR8_LOAD_EXITING;
3499 	proc_ctls |= PROCBASED_CR8_STORE_EXITING;
3500 	vmx->cap[vcpuid].proc_ctls = proc_ctls;
3501 
3502 	vmcs_load(vmx->vmcs_pa[vcpuid]);
3503 	vmcs_write(VMCS_PRI_PROC_BASED_CTLS, proc_ctls);
3504 	vmcs_clear(vmx->vmcs_pa[vcpuid]);
3505 }
3506 
3507 static void
3508 vmx_enable_x2apic_mode_vid(struct vlapic *vlapic)
3509 {
3510 	struct vmx *vmx;
3511 	uint32_t proc_ctls2;
3512 	int vcpuid;
3513 
3514 	vcpuid = vlapic->vcpuid;
3515 	vmx = ((struct vlapic_vtx *)vlapic)->vmx;
3516 
3517 	proc_ctls2 = vmx->cap[vcpuid].proc_ctls2;
3518 	KASSERT((proc_ctls2 & PROCBASED2_VIRTUALIZE_APIC_ACCESSES) != 0,
3519 	    ("%s: invalid proc_ctls2 %x", __func__, proc_ctls2));
3520 
3521 	proc_ctls2 &= ~PROCBASED2_VIRTUALIZE_APIC_ACCESSES;
3522 	proc_ctls2 |= PROCBASED2_VIRTUALIZE_X2APIC_MODE;
3523 	vmx->cap[vcpuid].proc_ctls2 = proc_ctls2;
3524 
3525 	vmcs_load(vmx->vmcs_pa[vcpuid]);
3526 	vmcs_write(VMCS_SEC_PROC_BASED_CTLS, proc_ctls2);
3527 	vmcs_clear(vmx->vmcs_pa[vcpuid]);
3528 
3529 	vmx_allow_x2apic_msrs(vmx, vcpuid);
3530 }
3531 
3532 static void
3533 vmx_apicv_notify(struct vlapic *vlapic, int hostcpu)
3534 {