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