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