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