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