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