1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * Kernel-based Virtual Machine driver for Linux 4 * 5 * This module enables machines with Intel VT-x extensions to run virtual 6 * machines without emulation or binary translation. 7 * 8 * Copyright (C) 2006 Qumranet, Inc. 9 * Copyright 2010 Red Hat, Inc. and/or its affiliates. 10 * 11 * Authors: 12 * Avi Kivity <avi@qumranet.com> 13 * Yaniv Kamay <yaniv@qumranet.com> 14 */ 15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 16 17 #include <linux/highmem.h> 18 #include <linux/hrtimer.h> 19 #include <linux/kernel.h> 20 #include <linux/kvm_host.h> 21 #include <linux/module.h> 22 #include <linux/moduleparam.h> 23 #include <linux/mod_devicetable.h> 24 #include <linux/mm.h> 25 #include <linux/objtool.h> 26 #include <linux/sched.h> 27 #include <linux/sched/smt.h> 28 #include <linux/slab.h> 29 #include <linux/tboot.h> 30 #include <linux/trace_events.h> 31 32 #include <asm/apic.h> 33 #include <asm/asm.h> 34 #include <asm/cpu.h> 35 #include <asm/cpu_device_id.h> 36 #include <asm/cpuid/api.h> 37 #include <asm/debugreg.h> 38 #include <asm/desc.h> 39 #include <asm/fpu/api.h> 40 #include <asm/fpu/xstate.h> 41 #include <asm/fred.h> 42 #include <asm/idtentry.h> 43 #include <asm/io.h> 44 #include <asm/irq_remapping.h> 45 #include <asm/reboot.h> 46 #include <asm/perf_event.h> 47 #include <asm/mmu_context.h> 48 #include <asm/mshyperv.h> 49 #include <asm/msr.h> 50 #include <asm/mwait.h> 51 #include <asm/spec-ctrl.h> 52 #include <asm/virt.h> 53 #include <asm/vmx.h> 54 55 #include <trace/events/ipi.h> 56 57 #include "capabilities.h" 58 #include "common.h" 59 #include "cpuid.h" 60 #include "hyperv.h" 61 #include "kvm_onhyperv.h" 62 #include "irq.h" 63 #include "kvm_cache_regs.h" 64 #include "lapic.h" 65 #include "mmu.h" 66 #include "nested.h" 67 #include "pmu.h" 68 #include "sgx.h" 69 #include "trace.h" 70 #include "vmcs.h" 71 #include "vmcs12.h" 72 #include "vmx.h" 73 #include "x86.h" 74 #include "x86_ops.h" 75 #include "smm.h" 76 #include "vmx_onhyperv.h" 77 #include "posted_intr.h" 78 79 #include "mmu/spte.h" 80 81 MODULE_AUTHOR("Qumranet"); 82 MODULE_DESCRIPTION("KVM support for VMX (Intel VT-x) extensions"); 83 MODULE_LICENSE("GPL"); 84 85 #ifdef MODULE 86 static const struct x86_cpu_id vmx_cpu_id[] = { 87 X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL), 88 {} 89 }; 90 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id); 91 #endif 92 93 bool __read_mostly enable_vpid = 1; 94 module_param_named(vpid, enable_vpid, bool, 0444); 95 96 static bool __read_mostly enable_vnmi = 1; 97 module_param_named(vnmi, enable_vnmi, bool, 0444); 98 99 bool __read_mostly flexpriority_enabled = 1; 100 module_param_named(flexpriority, flexpriority_enabled, bool, 0444); 101 102 bool __read_mostly enable_ept = 1; 103 module_param_named(ept, enable_ept, bool, 0444); 104 105 bool __read_mostly enable_unrestricted_guest = 1; 106 module_param_named(unrestricted_guest, 107 enable_unrestricted_guest, bool, 0444); 108 109 bool __read_mostly enable_ept_ad_bits = 1; 110 module_param_named(eptad, enable_ept_ad_bits, bool, 0444); 111 112 bool __read_mostly enable_cet = 1; 113 module_param_named(cet, enable_cet, bool, 0444); 114 115 static bool __read_mostly emulate_invalid_guest_state = true; 116 module_param(emulate_invalid_guest_state, bool, 0444); 117 118 static bool __read_mostly fasteoi = 1; 119 module_param(fasteoi, bool, 0444); 120 121 module_param(enable_apicv, bool, 0444); 122 module_param(enable_ipiv, bool, 0444); 123 124 module_param(enable_device_posted_irqs, bool, 0444); 125 126 /* 127 * If nested=1, nested virtualization is supported, i.e., guests may use 128 * VMX and be a hypervisor for its own guests. If nested=0, guests may not 129 * use VMX instructions. 130 */ 131 static bool __read_mostly nested = 1; 132 module_param(nested, bool, 0444); 133 134 bool __read_mostly enable_pml = 1; 135 module_param_named(pml, enable_pml, bool, 0444); 136 137 static bool __read_mostly error_on_inconsistent_vmcs_config = true; 138 module_param(error_on_inconsistent_vmcs_config, bool, 0444); 139 140 static bool __read_mostly dump_invalid_vmcs = 0; 141 module_param(dump_invalid_vmcs, bool, 0644); 142 143 #define MSR_BITMAP_MODE_X2APIC 1 144 #define MSR_BITMAP_MODE_X2APIC_APICV 2 145 146 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL 147 148 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */ 149 static int __read_mostly cpu_preemption_timer_multi; 150 static bool __read_mostly enable_preemption_timer = 1; 151 #ifdef CONFIG_X86_64 152 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO); 153 #endif 154 155 extern bool __read_mostly allow_smaller_maxphyaddr; 156 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO); 157 158 module_param(enable_mediated_pmu, bool, 0444); 159 160 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD) 161 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE 162 #define KVM_VM_CR0_ALWAYS_ON \ 163 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE) 164 165 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE 166 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE) 167 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE) 168 169 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM)) 170 171 #define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \ 172 RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \ 173 RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \ 174 RTIT_STATUS_BYTECNT)) 175 176 /* 177 * These 2 parameters are used to config the controls for Pause-Loop Exiting: 178 * ple_gap: upper bound on the amount of time between two successive 179 * executions of PAUSE in a loop. Also indicate if ple enabled. 180 * According to test, this time is usually smaller than 128 cycles. 181 * ple_window: upper bound on the amount of time a guest is allowed to execute 182 * in a PAUSE loop. Tests indicate that most spinlocks are held for 183 * less than 2^12 cycles 184 * Time is measured based on a counter that runs at the same rate as the TSC, 185 * refer SDM volume 3b section 21.6.13 & 22.1.3. 186 */ 187 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP; 188 module_param(ple_gap, uint, 0444); 189 190 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW; 191 module_param(ple_window, uint, 0444); 192 193 /* Default doubles per-vcpu window every exit. */ 194 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW; 195 module_param(ple_window_grow, uint, 0444); 196 197 /* Default resets per-vcpu window every exit to ple_window. */ 198 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK; 199 module_param(ple_window_shrink, uint, 0444); 200 201 /* Default is to compute the maximum so we can never overflow. */ 202 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX; 203 module_param(ple_window_max, uint, 0444); 204 205 /* Default is SYSTEM mode, 1 for host-guest mode (which is BROKEN) */ 206 int __read_mostly pt_mode = PT_MODE_SYSTEM; 207 #ifdef CONFIG_BROKEN 208 module_param(pt_mode, int, S_IRUGO); 209 #endif 210 211 struct x86_pmu_lbr __ro_after_init vmx_lbr_caps; 212 213 #ifdef CONFIG_CPU_MITIGATIONS 214 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush); 215 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond); 216 static DEFINE_MUTEX(vmx_l1d_flush_mutex); 217 218 /* Storage for pre module init parameter parsing */ 219 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO; 220 221 static const struct { 222 const char *option; 223 bool for_parse; 224 } vmentry_l1d_param[] = { 225 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true}, 226 [VMENTER_L1D_FLUSH_NEVER] = {"never", true}, 227 [VMENTER_L1D_FLUSH_COND] = {"cond", true}, 228 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true}, 229 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false}, 230 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false}, 231 }; 232 233 #define L1D_CACHE_ORDER 4 234 static void *vmx_l1d_flush_pages; 235 236 static int __vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf) 237 { 238 struct page *page; 239 unsigned int i; 240 241 if (!boot_cpu_has_bug(X86_BUG_L1TF)) { 242 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED; 243 return 0; 244 } 245 246 if (!enable_ept) { 247 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED; 248 return 0; 249 } 250 251 if (kvm_host.arch_capabilities & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) { 252 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED; 253 return 0; 254 } 255 256 /* If set to auto use the default l1tf mitigation method */ 257 if (l1tf == VMENTER_L1D_FLUSH_AUTO) { 258 switch (l1tf_mitigation) { 259 case L1TF_MITIGATION_OFF: 260 l1tf = VMENTER_L1D_FLUSH_NEVER; 261 break; 262 case L1TF_MITIGATION_AUTO: 263 case L1TF_MITIGATION_FLUSH_NOWARN: 264 case L1TF_MITIGATION_FLUSH: 265 case L1TF_MITIGATION_FLUSH_NOSMT: 266 l1tf = VMENTER_L1D_FLUSH_COND; 267 break; 268 case L1TF_MITIGATION_FULL: 269 case L1TF_MITIGATION_FULL_FORCE: 270 l1tf = VMENTER_L1D_FLUSH_ALWAYS; 271 break; 272 } 273 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) { 274 l1tf = VMENTER_L1D_FLUSH_ALWAYS; 275 } 276 277 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages && 278 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) { 279 /* 280 * This allocation for vmx_l1d_flush_pages is not tied to a VM 281 * lifetime and so should not be charged to a memcg. 282 */ 283 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER); 284 if (!page) 285 return -ENOMEM; 286 vmx_l1d_flush_pages = page_address(page); 287 288 /* 289 * Initialize each page with a different pattern in 290 * order to protect against KSM in the nested 291 * virtualization case. 292 */ 293 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) { 294 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1, 295 PAGE_SIZE); 296 } 297 } 298 299 l1tf_vmx_mitigation = l1tf; 300 301 if (l1tf != VMENTER_L1D_FLUSH_NEVER) 302 static_branch_enable(&vmx_l1d_should_flush); 303 else 304 static_branch_disable(&vmx_l1d_should_flush); 305 306 if (l1tf == VMENTER_L1D_FLUSH_COND) 307 static_branch_enable(&vmx_l1d_flush_cond); 308 else 309 static_branch_disable(&vmx_l1d_flush_cond); 310 return 0; 311 } 312 313 static int vmx_setup_l1d_flush(void) 314 { 315 /* 316 * Hand the parameter mitigation value in which was stored in the pre 317 * module init parser. If no parameter was given, it will contain 318 * 'auto' which will be turned into the default 'cond' mitigation mode. 319 */ 320 return __vmx_setup_l1d_flush(vmentry_l1d_flush_param); 321 } 322 323 static void vmx_cleanup_l1d_flush(void) 324 { 325 if (vmx_l1d_flush_pages) { 326 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER); 327 vmx_l1d_flush_pages = NULL; 328 } 329 /* Restore state so sysfs ignores VMX */ 330 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO; 331 } 332 333 static int vmentry_l1d_flush_parse(const char *s) 334 { 335 unsigned int i; 336 337 if (s) { 338 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) { 339 if (vmentry_l1d_param[i].for_parse && 340 sysfs_streq(s, vmentry_l1d_param[i].option)) 341 return i; 342 } 343 } 344 return -EINVAL; 345 } 346 347 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp) 348 { 349 int l1tf, ret; 350 351 l1tf = vmentry_l1d_flush_parse(s); 352 if (l1tf < 0) 353 return l1tf; 354 355 if (!boot_cpu_has(X86_BUG_L1TF)) 356 return 0; 357 358 /* 359 * Has vmx_init() run already? If not then this is the pre init 360 * parameter parsing. In that case just store the value and let 361 * vmx_init() do the proper setup after enable_ept has been 362 * established. 363 */ 364 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) { 365 vmentry_l1d_flush_param = l1tf; 366 return 0; 367 } 368 369 mutex_lock(&vmx_l1d_flush_mutex); 370 ret = __vmx_setup_l1d_flush(l1tf); 371 mutex_unlock(&vmx_l1d_flush_mutex); 372 return ret; 373 } 374 375 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp) 376 { 377 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param))) 378 return sysfs_emit(s, "???\n"); 379 380 return sysfs_emit(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option); 381 } 382 383 /* 384 * Software based L1D cache flush which is used when microcode providing 385 * the cache control MSR is not loaded. 386 * 387 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to 388 * flush it is required to read in 64 KiB because the replacement algorithm 389 * is not exactly LRU. This could be sized at runtime via topology 390 * information but as all relevant affected CPUs have 32KiB L1D cache size 391 * there is no point in doing so. 392 */ 393 static noinstr void vmx_l1d_flush(struct kvm_vcpu *vcpu) 394 { 395 int size = PAGE_SIZE << L1D_CACHE_ORDER; 396 397 if (!static_branch_unlikely(&vmx_l1d_should_flush)) 398 return; 399 400 /* 401 * This code is only executed when the flush mode is 'cond' or 402 * 'always' 403 */ 404 if (static_branch_likely(&vmx_l1d_flush_cond)) { 405 /* 406 * Clear the per-cpu flush bit, it gets set again if the vCPU 407 * is reloaded, i.e. if the vCPU is scheduled out or if KVM 408 * exits to userspace, or if KVM reaches one of the unsafe 409 * VMEXIT handlers, e.g. if KVM calls into the emulator, 410 * or from the interrupt handlers. 411 */ 412 if (!kvm_get_cpu_l1tf_flush_l1d()) 413 return; 414 kvm_clear_cpu_l1tf_flush_l1d(); 415 } 416 417 vcpu->stat.l1d_flush++; 418 419 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) { 420 native_wrmsrq(MSR_IA32_FLUSH_CMD, L1D_FLUSH); 421 return; 422 } 423 424 asm volatile( 425 /* First ensure the pages are in the TLB */ 426 "xorl %%eax, %%eax\n" 427 ".Lpopulate_tlb:\n\t" 428 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t" 429 "addl $4096, %%eax\n\t" 430 "cmpl %%eax, %[size]\n\t" 431 "jne .Lpopulate_tlb\n\t" 432 "xorl %%eax, %%eax\n\t" 433 "cpuid\n\t" 434 /* Now fill the cache */ 435 "xorl %%eax, %%eax\n" 436 ".Lfill_cache:\n" 437 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t" 438 "addl $64, %%eax\n\t" 439 "cmpl %%eax, %[size]\n\t" 440 "jne .Lfill_cache\n\t" 441 "lfence\n" 442 :: [flush_pages] "r" (vmx_l1d_flush_pages), 443 [size] "r" (size) 444 : "eax", "ebx", "ecx", "edx"); 445 } 446 447 #else /* CONFIG_CPU_MITIGATIONS*/ 448 static int vmx_setup_l1d_flush(void) 449 { 450 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NEVER; 451 return 0; 452 } 453 static void vmx_cleanup_l1d_flush(void) 454 { 455 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO; 456 } 457 static __always_inline void vmx_l1d_flush(struct kvm_vcpu *vcpu) 458 { 459 460 } 461 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp) 462 { 463 pr_warn_once("Kernel compiled without mitigations, ignoring vmentry_l1d_flush\n"); 464 return 0; 465 } 466 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp) 467 { 468 return sysfs_emit(s, "never\n"); 469 } 470 #endif 471 472 static const struct kernel_param_ops vmentry_l1d_flush_ops = { 473 .set = vmentry_l1d_flush_set, 474 .get = vmentry_l1d_flush_get, 475 }; 476 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644); 477 478 static __always_inline void vmx_disable_fb_clear(struct vcpu_vmx *vmx) 479 { 480 u64 msr; 481 482 if (!vmx->disable_fb_clear) 483 return; 484 485 msr = native_rdmsrq(MSR_IA32_MCU_OPT_CTRL); 486 msr |= FB_CLEAR_DIS; 487 native_wrmsrq(MSR_IA32_MCU_OPT_CTRL, msr); 488 /* Cache the MSR value to avoid reading it later */ 489 vmx->msr_ia32_mcu_opt_ctrl = msr; 490 } 491 492 static __always_inline void vmx_enable_fb_clear(struct vcpu_vmx *vmx) 493 { 494 if (!vmx->disable_fb_clear) 495 return; 496 497 vmx->msr_ia32_mcu_opt_ctrl &= ~FB_CLEAR_DIS; 498 native_wrmsrq(MSR_IA32_MCU_OPT_CTRL, vmx->msr_ia32_mcu_opt_ctrl); 499 } 500 501 static void vmx_update_fb_clear_dis(struct kvm_vcpu *vcpu, struct vcpu_vmx *vmx) 502 { 503 /* 504 * Disable VERW's behavior of clearing CPU buffers for the guest if the 505 * CPU isn't affected by MDS/TAA, and the host hasn't forcefully enabled 506 * the mitigation. Disabling the clearing behavior provides a 507 * performance boost for guests that aren't aware that manually clearing 508 * CPU buffers is unnecessary, at the cost of MSR accesses on VM-Entry 509 * and VM-Exit. 510 */ 511 vmx->disable_fb_clear = !cpu_feature_enabled(X86_FEATURE_CLEAR_CPU_BUF) && 512 (kvm_host.arch_capabilities & ARCH_CAP_FB_CLEAR_CTRL) && 513 !boot_cpu_has_bug(X86_BUG_MDS) && 514 !boot_cpu_has_bug(X86_BUG_TAA); 515 516 /* 517 * If guest will not execute VERW, there is no need to set FB_CLEAR_DIS 518 * at VMEntry. Skip the MSR read/write when a guest has no use case to 519 * execute VERW. 520 */ 521 if ((vcpu->arch.arch_capabilities & ARCH_CAP_FB_CLEAR) || 522 ((vcpu->arch.arch_capabilities & ARCH_CAP_MDS_NO) && 523 (vcpu->arch.arch_capabilities & ARCH_CAP_TAA_NO) && 524 (vcpu->arch.arch_capabilities & ARCH_CAP_PSDP_NO) && 525 (vcpu->arch.arch_capabilities & ARCH_CAP_FBSDP_NO) && 526 (vcpu->arch.arch_capabilities & ARCH_CAP_SBDR_SSDP_NO))) 527 vmx->disable_fb_clear = false; 528 } 529 530 static u32 vmx_segment_access_rights(struct kvm_segment *var); 531 532 void vmx_vmexit(void); 533 534 #define vmx_insn_failed(fmt...) \ 535 do { \ 536 WARN_ONCE(1, fmt); \ 537 pr_warn_ratelimited(fmt); \ 538 } while (0) 539 540 noinline void vmread_error(unsigned long field) 541 { 542 vmx_insn_failed("vmread failed: field=%lx\n", field); 543 } 544 545 #ifndef CONFIG_CC_HAS_ASM_GOTO_OUTPUT 546 noinstr void vmread_error_trampoline2(unsigned long field, bool fault) 547 { 548 if (fault) { 549 kvm_spurious_fault(); 550 } else { 551 instrumentation_begin(); 552 vmread_error(field); 553 instrumentation_end(); 554 } 555 } 556 #endif 557 558 noinline void vmwrite_error(unsigned long field, unsigned long value) 559 { 560 vmx_insn_failed("vmwrite failed: field=%lx val=%lx err=%u\n", 561 field, value, vmcs_read32(VM_INSTRUCTION_ERROR)); 562 } 563 564 noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr) 565 { 566 vmx_insn_failed("vmclear failed: %p/%llx err=%u\n", 567 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR)); 568 } 569 570 noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr) 571 { 572 vmx_insn_failed("vmptrld failed: %p/%llx err=%u\n", 573 vmcs, phys_addr, vmcs_read32(VM_INSTRUCTION_ERROR)); 574 } 575 576 noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva) 577 { 578 vmx_insn_failed("invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n", 579 ext, vpid, gva); 580 } 581 582 noinline void invept_error(unsigned long ext, u64 eptp) 583 { 584 vmx_insn_failed("invept failed: ext=0x%lx eptp=%llx\n", ext, eptp); 585 } 586 587 DEFINE_PER_CPU(struct vmcs *, current_vmcs); 588 /* 589 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed 590 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it. 591 */ 592 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu); 593 594 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS); 595 static DEFINE_SPINLOCK(vmx_vpid_lock); 596 597 struct vmcs_config vmcs_config __ro_after_init; 598 struct vmx_capability vmx_capability __ro_after_init; 599 600 #define VMX_SEGMENT_FIELD(seg) \ 601 [VCPU_SREG_##seg] = { \ 602 .selector = GUEST_##seg##_SELECTOR, \ 603 .base = GUEST_##seg##_BASE, \ 604 .limit = GUEST_##seg##_LIMIT, \ 605 .ar_bytes = GUEST_##seg##_AR_BYTES, \ 606 } 607 608 static const struct kvm_vmx_segment_field { 609 unsigned selector; 610 unsigned base; 611 unsigned limit; 612 unsigned ar_bytes; 613 } kvm_vmx_segment_fields[] = { 614 VMX_SEGMENT_FIELD(CS), 615 VMX_SEGMENT_FIELD(DS), 616 VMX_SEGMENT_FIELD(ES), 617 VMX_SEGMENT_FIELD(FS), 618 VMX_SEGMENT_FIELD(GS), 619 VMX_SEGMENT_FIELD(SS), 620 VMX_SEGMENT_FIELD(TR), 621 VMX_SEGMENT_FIELD(LDTR), 622 }; 623 624 625 static unsigned long host_idt_base; 626 627 #if IS_ENABLED(CONFIG_HYPERV) 628 static bool __read_mostly enlightened_vmcs = true; 629 module_param(enlightened_vmcs, bool, 0444); 630 631 static int hv_enable_l2_tlb_flush(struct kvm_vcpu *vcpu) 632 { 633 struct hv_enlightened_vmcs *evmcs; 634 hpa_t partition_assist_page = hv_get_partition_assist_page(vcpu); 635 636 if (partition_assist_page == INVALID_PAGE) 637 return -ENOMEM; 638 639 evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs; 640 641 evmcs->partition_assist_page = partition_assist_page; 642 evmcs->hv_vm_id = (unsigned long)vcpu->kvm; 643 evmcs->hv_enlightenments_control.nested_flush_hypercall = 1; 644 645 return 0; 646 } 647 648 static __init void hv_init_evmcs(void) 649 { 650 int cpu; 651 652 if (!enlightened_vmcs) 653 return; 654 655 /* 656 * Enlightened VMCS usage should be recommended and the host needs 657 * to support eVMCS v1 or above. 658 */ 659 if (ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED && 660 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >= 661 KVM_EVMCS_VERSION) { 662 663 /* Check that we have assist pages on all online CPUs */ 664 for_each_online_cpu(cpu) { 665 if (!hv_get_vp_assist_page(cpu)) { 666 enlightened_vmcs = false; 667 break; 668 } 669 } 670 671 if (enlightened_vmcs) { 672 pr_info("Using Hyper-V Enlightened VMCS\n"); 673 static_branch_enable(&__kvm_is_using_evmcs); 674 } 675 676 if (ms_hyperv.nested_features & HV_X64_NESTED_DIRECT_FLUSH) 677 vt_x86_ops.enable_l2_tlb_flush 678 = hv_enable_l2_tlb_flush; 679 } else { 680 enlightened_vmcs = false; 681 } 682 } 683 684 static void hv_reset_evmcs(void) 685 { 686 struct hv_vp_assist_page *vp_ap; 687 688 if (!kvm_is_using_evmcs()) 689 return; 690 691 /* 692 * KVM should enable eVMCS if and only if all CPUs have a VP assist 693 * page, and should reject CPU onlining if eVMCS is enabled the CPU 694 * doesn't have a VP assist page allocated. 695 */ 696 vp_ap = hv_get_vp_assist_page(smp_processor_id()); 697 if (WARN_ON_ONCE(!vp_ap)) 698 return; 699 700 /* 701 * Reset everything to support using non-enlightened VMCS access later 702 * (e.g. when we reload the module with enlightened_vmcs=0) 703 */ 704 vp_ap->nested_control.features.directhypercall = 0; 705 vp_ap->current_nested_vmcs = 0; 706 vp_ap->enlighten_vmentry = 0; 707 } 708 709 #else /* IS_ENABLED(CONFIG_HYPERV) */ 710 static void hv_init_evmcs(void) {} 711 static void hv_reset_evmcs(void) {} 712 #endif /* IS_ENABLED(CONFIG_HYPERV) */ 713 714 /* 715 * Comment's format: document - errata name - stepping - processor name. 716 * Refer from 717 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp 718 */ 719 static u32 vmx_preemption_cpu_tfms[] = { 720 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */ 721 0x000206E6, 722 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */ 723 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */ 724 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */ 725 0x00020652, 726 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */ 727 0x00020655, 728 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */ 729 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */ 730 /* 731 * 320767.pdf - AAP86 - B1 - 732 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile 733 */ 734 0x000106E5, 735 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */ 736 0x000106A0, 737 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */ 738 0x000106A1, 739 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */ 740 0x000106A4, 741 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */ 742 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */ 743 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */ 744 0x000106A5, 745 /* Xeon E3-1220 V2 */ 746 0x000306A8, 747 }; 748 749 static inline bool cpu_has_broken_vmx_preemption_timer(void) 750 { 751 u32 eax = cpuid_eax(0x00000001), i; 752 753 /* Clear the reserved bits */ 754 eax &= ~(0x3U << 14 | 0xfU << 28); 755 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++) 756 if (eax == vmx_preemption_cpu_tfms[i]) 757 return true; 758 759 return false; 760 } 761 762 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu) 763 { 764 return flexpriority_enabled && lapic_in_kernel(vcpu); 765 } 766 767 struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr) 768 { 769 int i; 770 771 i = kvm_find_user_return_msr(msr); 772 if (i >= 0) 773 return &vmx->guest_uret_msrs[i]; 774 return NULL; 775 } 776 777 static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx, 778 struct vmx_uret_msr *msr, u64 data) 779 { 780 unsigned int slot = msr - vmx->guest_uret_msrs; 781 int ret = 0; 782 783 if (msr->load_into_hardware) { 784 preempt_disable(); 785 ret = kvm_set_user_return_msr(slot, data, msr->mask); 786 preempt_enable(); 787 } 788 if (!ret) 789 msr->data = data; 790 return ret; 791 } 792 793 void vmx_emergency_disable_virtualization_cpu(void) 794 { 795 int cpu = raw_smp_processor_id(); 796 struct loaded_vmcs *v; 797 798 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu), 799 loaded_vmcss_on_cpu_link) { 800 vmcs_clear(v->vmcs); 801 if (v->shadow_vmcs) 802 vmcs_clear(v->shadow_vmcs); 803 } 804 } 805 806 static void __loaded_vmcs_clear(void *arg) 807 { 808 struct loaded_vmcs *loaded_vmcs = arg; 809 int cpu = raw_smp_processor_id(); 810 811 if (loaded_vmcs->cpu != cpu) 812 return; /* vcpu migration can race with cpu offline */ 813 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs) 814 per_cpu(current_vmcs, cpu) = NULL; 815 816 vmcs_clear(loaded_vmcs->vmcs); 817 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched) 818 vmcs_clear(loaded_vmcs->shadow_vmcs); 819 820 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link); 821 822 /* 823 * Ensure all writes to loaded_vmcs, including deleting it from its 824 * current percpu list, complete before setting loaded_vmcs->cpu to 825 * -1, otherwise a different cpu can see loaded_vmcs->cpu == -1 first 826 * and add loaded_vmcs to its percpu list before it's deleted from this 827 * cpu's list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs(). 828 */ 829 smp_wmb(); 830 831 loaded_vmcs->cpu = -1; 832 loaded_vmcs->launched = 0; 833 } 834 835 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs) 836 { 837 int cpu = loaded_vmcs->cpu; 838 839 if (cpu != -1) 840 smp_call_function_single(cpu, 841 __loaded_vmcs_clear, loaded_vmcs, 1); 842 } 843 844 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg, 845 unsigned field) 846 { 847 bool ret; 848 u32 mask = 1 << (seg * SEG_FIELD_NR + field); 849 850 if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) { 851 kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS); 852 vmx->segment_cache.bitmask = 0; 853 } 854 ret = vmx->segment_cache.bitmask & mask; 855 vmx->segment_cache.bitmask |= mask; 856 return ret; 857 } 858 859 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg) 860 { 861 u16 *p = &vmx->segment_cache.seg[seg].selector; 862 863 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL)) 864 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector); 865 return *p; 866 } 867 868 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg) 869 { 870 ulong *p = &vmx->segment_cache.seg[seg].base; 871 872 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE)) 873 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base); 874 return *p; 875 } 876 877 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg) 878 { 879 u32 *p = &vmx->segment_cache.seg[seg].limit; 880 881 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT)) 882 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit); 883 return *p; 884 } 885 886 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg) 887 { 888 u32 *p = &vmx->segment_cache.seg[seg].ar; 889 890 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR)) 891 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes); 892 return *p; 893 } 894 895 void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu) 896 { 897 u32 eb; 898 899 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) | 900 (1u << DB_VECTOR) | (1u << AC_VECTOR); 901 /* 902 * #VE isn't used for VMX. To test against unexpected changes 903 * related to #VE for VMX, intercept unexpected #VE and warn on it. 904 */ 905 if (IS_ENABLED(CONFIG_KVM_INTEL_PROVE_VE)) 906 eb |= 1u << VE_VECTOR; 907 /* 908 * Guest access to VMware backdoor ports could legitimately 909 * trigger #GP because of TSS I/O permission bitmap. 910 * We intercept those #GP and allow access to them anyway 911 * as VMware does. 912 */ 913 if (enable_vmware_backdoor) 914 eb |= (1u << GP_VECTOR); 915 if ((vcpu->guest_debug & 916 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) == 917 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) 918 eb |= 1u << BP_VECTOR; 919 if (to_vmx(vcpu)->rmode.vm86_active) 920 eb = ~0; 921 if (!vmx_need_pf_intercept(vcpu)) 922 eb &= ~(1u << PF_VECTOR); 923 924 /* When we are running a nested L2 guest and L1 specified for it a 925 * certain exception bitmap, we must trap the same exceptions and pass 926 * them to L1. When running L2, we will only handle the exceptions 927 * specified above if L1 did not want them. 928 */ 929 if (is_guest_mode(vcpu)) 930 eb |= get_vmcs12(vcpu)->exception_bitmap; 931 else { 932 int mask = 0, match = 0; 933 934 if (enable_ept && (eb & (1u << PF_VECTOR))) { 935 /* 936 * If EPT is enabled, #PF is currently only intercepted 937 * if MAXPHYADDR is smaller on the guest than on the 938 * host. In that case we only care about present, 939 * non-reserved faults. For vmcs02, however, PFEC_MASK 940 * and PFEC_MATCH are set in prepare_vmcs02_rare. 941 */ 942 mask = PFERR_PRESENT_MASK | PFERR_RSVD_MASK; 943 match = PFERR_PRESENT_MASK; 944 } 945 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask); 946 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, match); 947 } 948 949 /* 950 * Disabling xfd interception indicates that dynamic xfeatures 951 * might be used in the guest. Always trap #NM in this case 952 * to save guest xfd_err timely. 953 */ 954 if (vcpu->arch.xfd_no_write_intercept) 955 eb |= (1u << NM_VECTOR); 956 957 vmcs_write32(EXCEPTION_BITMAP, eb); 958 } 959 960 /* 961 * Check if MSR is intercepted for currently loaded MSR bitmap. 962 */ 963 static bool msr_write_intercepted(struct vcpu_vmx *vmx, u32 msr) 964 { 965 if (!(exec_controls_get(vmx) & CPU_BASED_USE_MSR_BITMAPS)) 966 return true; 967 968 return vmx_test_msr_bitmap_write(vmx->loaded_vmcs->msr_bitmap, msr); 969 } 970 971 unsigned int __vmx_vcpu_run_flags(struct vcpu_vmx *vmx) 972 { 973 unsigned int flags = 0; 974 975 if (vmx->loaded_vmcs->launched) 976 flags |= VMX_RUN_VMRESUME; 977 978 /* 979 * If writes to the SPEC_CTRL MSR aren't intercepted, the guest is free 980 * to change it directly without causing a vmexit. In that case read 981 * it after vmexit and store it in vmx->spec_ctrl. 982 */ 983 if (!msr_write_intercepted(vmx, MSR_IA32_SPEC_CTRL)) 984 flags |= VMX_RUN_SAVE_SPEC_CTRL; 985 986 if (cpu_feature_enabled(X86_FEATURE_CLEAR_CPU_BUF_VM_MMIO) && 987 kvm_vcpu_can_access_host_mmio(&vmx->vcpu)) 988 flags |= VMX_RUN_CLEAR_CPU_BUFFERS_FOR_MMIO; 989 990 return flags; 991 } 992 993 static __always_inline void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx, 994 unsigned long entry, unsigned long exit) 995 { 996 vm_entry_controls_clearbit(vmx, entry); 997 vm_exit_controls_clearbit(vmx, exit); 998 } 999 1000 static int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr) 1001 { 1002 unsigned int i; 1003 1004 for (i = 0; i < m->nr; ++i) { 1005 if (m->val[i].index == msr) 1006 return i; 1007 } 1008 return -ENOENT; 1009 } 1010 1011 static void vmx_remove_auto_msr(struct vmx_msrs *m, u32 msr, 1012 unsigned long vmcs_count_field) 1013 { 1014 int i; 1015 1016 i = vmx_find_loadstore_msr_slot(m, msr); 1017 if (i < 0) 1018 return; 1019 1020 --m->nr; 1021 m->val[i] = m->val[m->nr]; 1022 vmcs_write32(vmcs_count_field, m->nr); 1023 } 1024 1025 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr) 1026 { 1027 struct msr_autoload *m = &vmx->msr_autoload; 1028 1029 switch (msr) { 1030 case MSR_EFER: 1031 if (cpu_has_load_ia32_efer()) { 1032 clear_atomic_switch_msr_special(vmx, 1033 VM_ENTRY_LOAD_IA32_EFER, 1034 VM_EXIT_LOAD_IA32_EFER); 1035 return; 1036 } 1037 break; 1038 case MSR_CORE_PERF_GLOBAL_CTRL: 1039 if (cpu_has_load_perf_global_ctrl()) { 1040 clear_atomic_switch_msr_special(vmx, 1041 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, 1042 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL); 1043 return; 1044 } 1045 break; 1046 } 1047 1048 vmx_remove_auto_msr(&m->guest, msr, VM_ENTRY_MSR_LOAD_COUNT); 1049 vmx_remove_auto_msr(&m->host, msr, VM_EXIT_MSR_LOAD_COUNT); 1050 } 1051 1052 static __always_inline void add_atomic_switch_msr_special(struct vcpu_vmx *vmx, 1053 unsigned long entry, unsigned long exit, 1054 unsigned long guest_val_vmcs, unsigned long host_val_vmcs, 1055 u64 guest_val, u64 host_val) 1056 { 1057 vmcs_write64(guest_val_vmcs, guest_val); 1058 if (host_val_vmcs != HOST_IA32_EFER) 1059 vmcs_write64(host_val_vmcs, host_val); 1060 vm_entry_controls_setbit(vmx, entry); 1061 vm_exit_controls_setbit(vmx, exit); 1062 } 1063 1064 static void vmx_add_auto_msr(struct vmx_msrs *m, u32 msr, u64 value, 1065 unsigned long vmcs_count_field, struct kvm *kvm) 1066 { 1067 int i; 1068 1069 i = vmx_find_loadstore_msr_slot(m, msr); 1070 if (i < 0) { 1071 if (KVM_BUG_ON(m->nr == MAX_NR_LOADSTORE_MSRS, kvm)) 1072 return; 1073 1074 i = m->nr++; 1075 m->val[i].index = msr; 1076 vmcs_write32(vmcs_count_field, m->nr); 1077 } 1078 m->val[i].value = value; 1079 } 1080 1081 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr, 1082 u64 guest_val, u64 host_val) 1083 { 1084 struct msr_autoload *m = &vmx->msr_autoload; 1085 struct kvm *kvm = vmx->vcpu.kvm; 1086 1087 switch (msr) { 1088 case MSR_EFER: 1089 if (cpu_has_load_ia32_efer()) { 1090 add_atomic_switch_msr_special(vmx, 1091 VM_ENTRY_LOAD_IA32_EFER, 1092 VM_EXIT_LOAD_IA32_EFER, 1093 GUEST_IA32_EFER, 1094 HOST_IA32_EFER, 1095 guest_val, host_val); 1096 return; 1097 } 1098 break; 1099 case MSR_CORE_PERF_GLOBAL_CTRL: 1100 if (cpu_has_load_perf_global_ctrl()) { 1101 add_atomic_switch_msr_special(vmx, 1102 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, 1103 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL, 1104 GUEST_IA32_PERF_GLOBAL_CTRL, 1105 HOST_IA32_PERF_GLOBAL_CTRL, 1106 guest_val, host_val); 1107 return; 1108 } 1109 break; 1110 case MSR_IA32_PEBS_ENABLE: 1111 /* PEBS needs a quiescent period after being disabled (to write 1112 * a record). Disabling PEBS through VMX MSR swapping doesn't 1113 * provide that period, so a CPU could write host's record into 1114 * guest's memory. 1115 */ 1116 wrmsrq(MSR_IA32_PEBS_ENABLE, 0); 1117 } 1118 1119 vmx_add_auto_msr(&m->guest, msr, guest_val, VM_ENTRY_MSR_LOAD_COUNT, kvm); 1120 vmx_add_auto_msr(&m->host, msr, host_val, VM_EXIT_MSR_LOAD_COUNT, kvm); 1121 } 1122 1123 static bool update_transition_efer(struct vcpu_vmx *vmx) 1124 { 1125 u64 guest_efer = vmx->vcpu.arch.efer; 1126 u64 ignore_bits = 0; 1127 int i; 1128 1129 /* Shadow paging assumes NX to be available. */ 1130 if (!enable_ept) 1131 guest_efer |= EFER_NX; 1132 1133 /* 1134 * LMA and LME handled by hardware; SCE meaningless outside long mode. 1135 */ 1136 ignore_bits |= EFER_SCE; 1137 #ifdef CONFIG_X86_64 1138 ignore_bits |= EFER_LMA | EFER_LME; 1139 /* SCE is meaningful only in long mode on Intel */ 1140 if (guest_efer & EFER_LMA) 1141 ignore_bits &= ~(u64)EFER_SCE; 1142 #endif 1143 1144 /* 1145 * On EPT, we can't emulate NX, so we must switch EFER atomically. 1146 * On CPUs that support "load IA32_EFER", always switch EFER 1147 * atomically, since it's faster than switching it manually. 1148 */ 1149 if (cpu_has_load_ia32_efer() || 1150 (enable_ept && ((vmx->vcpu.arch.efer ^ kvm_host.efer) & EFER_NX))) { 1151 if (!(guest_efer & EFER_LMA)) 1152 guest_efer &= ~EFER_LME; 1153 if (guest_efer != kvm_host.efer) 1154 add_atomic_switch_msr(vmx, MSR_EFER, guest_efer, kvm_host.efer); 1155 else 1156 clear_atomic_switch_msr(vmx, MSR_EFER); 1157 return false; 1158 } 1159 1160 i = kvm_find_user_return_msr(MSR_EFER); 1161 if (i < 0) 1162 return false; 1163 1164 clear_atomic_switch_msr(vmx, MSR_EFER); 1165 1166 guest_efer &= ~ignore_bits; 1167 guest_efer |= kvm_host.efer & ignore_bits; 1168 1169 vmx->guest_uret_msrs[i].data = guest_efer; 1170 vmx->guest_uret_msrs[i].mask = ~ignore_bits; 1171 1172 return true; 1173 } 1174 1175 static void vmx_add_autostore_msr(struct vcpu_vmx *vmx, u32 msr) 1176 { 1177 vmx_add_auto_msr(&vmx->msr_autostore, msr, 0, VM_EXIT_MSR_STORE_COUNT, 1178 vmx->vcpu.kvm); 1179 } 1180 1181 static void vmx_remove_autostore_msr(struct vcpu_vmx *vmx, u32 msr) 1182 { 1183 vmx_remove_auto_msr(&vmx->msr_autostore, msr, VM_EXIT_MSR_STORE_COUNT); 1184 } 1185 1186 #ifdef CONFIG_X86_32 1187 /* 1188 * On 32-bit kernels, VM exits still load the FS and GS bases from the 1189 * VMCS rather than the segment table. KVM uses this helper to figure 1190 * out the current bases to poke them into the VMCS before entry. 1191 */ 1192 static unsigned long segment_base(u16 selector) 1193 { 1194 struct desc_struct *table; 1195 unsigned long v; 1196 1197 if (!(selector & ~SEGMENT_RPL_MASK)) 1198 return 0; 1199 1200 table = get_current_gdt_ro(); 1201 1202 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) { 1203 u16 ldt_selector = kvm_read_ldt(); 1204 1205 if (!(ldt_selector & ~SEGMENT_RPL_MASK)) 1206 return 0; 1207 1208 table = (struct desc_struct *)segment_base(ldt_selector); 1209 } 1210 v = get_desc_base(&table[selector >> 3]); 1211 return v; 1212 } 1213 #endif 1214 1215 static inline bool pt_can_write_msr(struct vcpu_vmx *vmx) 1216 { 1217 return vmx_pt_mode_is_host_guest() && 1218 !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN); 1219 } 1220 1221 static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base) 1222 { 1223 /* The base must be 128-byte aligned and a legal physical address. */ 1224 return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128); 1225 } 1226 1227 static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range) 1228 { 1229 u32 i; 1230 1231 wrmsrq(MSR_IA32_RTIT_STATUS, ctx->status); 1232 wrmsrq(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base); 1233 wrmsrq(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask); 1234 wrmsrq(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match); 1235 for (i = 0; i < addr_range; i++) { 1236 wrmsrq(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]); 1237 wrmsrq(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]); 1238 } 1239 } 1240 1241 static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range) 1242 { 1243 u32 i; 1244 1245 rdmsrq(MSR_IA32_RTIT_STATUS, ctx->status); 1246 rdmsrq(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base); 1247 rdmsrq(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask); 1248 rdmsrq(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match); 1249 for (i = 0; i < addr_range; i++) { 1250 rdmsrq(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]); 1251 rdmsrq(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]); 1252 } 1253 } 1254 1255 static void pt_guest_enter(struct vcpu_vmx *vmx) 1256 { 1257 if (vmx_pt_mode_is_system()) 1258 return; 1259 1260 /* 1261 * GUEST_IA32_RTIT_CTL is already set in the VMCS. 1262 * Save host state before VM entry. 1263 */ 1264 rdmsrq(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl); 1265 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) { 1266 wrmsrq(MSR_IA32_RTIT_CTL, 0); 1267 pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges); 1268 pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges); 1269 } 1270 } 1271 1272 static void pt_guest_exit(struct vcpu_vmx *vmx) 1273 { 1274 if (vmx_pt_mode_is_system()) 1275 return; 1276 1277 if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) { 1278 pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.num_address_ranges); 1279 pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.num_address_ranges); 1280 } 1281 1282 /* 1283 * KVM requires VM_EXIT_CLEAR_IA32_RTIT_CTL to expose PT to the guest, 1284 * i.e. RTIT_CTL is always cleared on VM-Exit. Restore it if necessary. 1285 */ 1286 if (vmx->pt_desc.host.ctl) 1287 wrmsrq(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl); 1288 } 1289 1290 void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel, 1291 unsigned long fs_base, unsigned long gs_base) 1292 { 1293 if (unlikely(fs_sel != host->fs_sel)) { 1294 if (!(fs_sel & 7)) 1295 vmcs_write16(HOST_FS_SELECTOR, fs_sel); 1296 else 1297 vmcs_write16(HOST_FS_SELECTOR, 0); 1298 host->fs_sel = fs_sel; 1299 } 1300 if (unlikely(gs_sel != host->gs_sel)) { 1301 if (!(gs_sel & 7)) 1302 vmcs_write16(HOST_GS_SELECTOR, gs_sel); 1303 else 1304 vmcs_write16(HOST_GS_SELECTOR, 0); 1305 host->gs_sel = gs_sel; 1306 } 1307 if (unlikely(fs_base != host->fs_base)) { 1308 vmcs_writel(HOST_FS_BASE, fs_base); 1309 host->fs_base = fs_base; 1310 } 1311 if (unlikely(gs_base != host->gs_base)) { 1312 vmcs_writel(HOST_GS_BASE, gs_base); 1313 host->gs_base = gs_base; 1314 } 1315 } 1316 1317 void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu) 1318 { 1319 struct vcpu_vmx *vmx = to_vmx(vcpu); 1320 struct vcpu_vt *vt = to_vt(vcpu); 1321 struct vmcs_host_state *host_state; 1322 #ifdef CONFIG_X86_64 1323 int cpu = raw_smp_processor_id(); 1324 #endif 1325 unsigned long fs_base, gs_base; 1326 u16 fs_sel, gs_sel; 1327 int i; 1328 1329 /* 1330 * Note that guest MSRs to be saved/restored can also be changed 1331 * when guest state is loaded. This happens when guest transitions 1332 * to/from long-mode by setting MSR_EFER.LMA. 1333 */ 1334 if (!vmx->guest_uret_msrs_loaded) { 1335 vmx->guest_uret_msrs_loaded = true; 1336 for (i = 0; i < kvm_nr_uret_msrs; ++i) { 1337 if (!vmx->guest_uret_msrs[i].load_into_hardware) 1338 continue; 1339 1340 kvm_set_user_return_msr(i, 1341 vmx->guest_uret_msrs[i].data, 1342 vmx->guest_uret_msrs[i].mask); 1343 } 1344 } 1345 1346 if (vmx->nested.need_vmcs12_to_shadow_sync) 1347 nested_sync_vmcs12_to_shadow(vcpu); 1348 1349 if (vt->guest_state_loaded) 1350 return; 1351 1352 host_state = &vmx->loaded_vmcs->host_state; 1353 1354 /* 1355 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not 1356 * allow segment selectors with cpl > 0 or ti == 1. 1357 */ 1358 host_state->ldt_sel = kvm_read_ldt(); 1359 1360 #ifdef CONFIG_X86_64 1361 savesegment(ds, host_state->ds_sel); 1362 savesegment(es, host_state->es_sel); 1363 1364 gs_base = cpu_kernelmode_gs_base(cpu); 1365 if (likely(is_64bit_mm(current->mm))) { 1366 current_save_fsgs(); 1367 fs_sel = current->thread.fsindex; 1368 gs_sel = current->thread.gsindex; 1369 fs_base = current->thread.fsbase; 1370 vt->msr_host_kernel_gs_base = current->thread.gsbase; 1371 } else { 1372 savesegment(fs, fs_sel); 1373 savesegment(gs, gs_sel); 1374 fs_base = read_msr(MSR_FS_BASE); 1375 vt->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE); 1376 } 1377 1378 wrmsrq(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base); 1379 #else 1380 savesegment(fs, fs_sel); 1381 savesegment(gs, gs_sel); 1382 fs_base = segment_base(fs_sel); 1383 gs_base = segment_base(gs_sel); 1384 #endif 1385 1386 vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base); 1387 vt->guest_state_loaded = true; 1388 } 1389 1390 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx) 1391 { 1392 struct vmcs_host_state *host_state; 1393 1394 if (!vmx->vt.guest_state_loaded) 1395 return; 1396 1397 host_state = &vmx->loaded_vmcs->host_state; 1398 1399 ++vmx->vcpu.stat.host_state_reload; 1400 1401 #ifdef CONFIG_X86_64 1402 rdmsrq(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base); 1403 #endif 1404 if (host_state->ldt_sel || (host_state->gs_sel & 7)) { 1405 kvm_load_ldt(host_state->ldt_sel); 1406 #ifdef CONFIG_X86_64 1407 load_gs_index(host_state->gs_sel); 1408 #else 1409 loadsegment(gs, host_state->gs_sel); 1410 #endif 1411 } 1412 if (host_state->fs_sel & 7) 1413 loadsegment(fs, host_state->fs_sel); 1414 #ifdef CONFIG_X86_64 1415 if (unlikely(host_state->ds_sel | host_state->es_sel)) { 1416 loadsegment(ds, host_state->ds_sel); 1417 loadsegment(es, host_state->es_sel); 1418 } 1419 #endif 1420 invalidate_tss_limit(); 1421 #ifdef CONFIG_X86_64 1422 wrmsrq(MSR_KERNEL_GS_BASE, vmx->vt.msr_host_kernel_gs_base); 1423 #endif 1424 load_fixmap_gdt(raw_smp_processor_id()); 1425 vmx->vt.guest_state_loaded = false; 1426 vmx->guest_uret_msrs_loaded = false; 1427 } 1428 1429 #ifdef CONFIG_X86_64 1430 static u64 vmx_read_guest_host_msr(struct vcpu_vmx *vmx, u32 msr, u64 *cache) 1431 { 1432 preempt_disable(); 1433 if (vmx->vt.guest_state_loaded) 1434 *cache = read_msr(msr); 1435 preempt_enable(); 1436 return *cache; 1437 } 1438 1439 static void vmx_write_guest_host_msr(struct vcpu_vmx *vmx, u32 msr, u64 data, 1440 u64 *cache) 1441 { 1442 preempt_disable(); 1443 if (vmx->vt.guest_state_loaded) 1444 wrmsrns(msr, data); 1445 preempt_enable(); 1446 *cache = data; 1447 } 1448 1449 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx) 1450 { 1451 return vmx_read_guest_host_msr(vmx, MSR_KERNEL_GS_BASE, 1452 &vmx->msr_guest_kernel_gs_base); 1453 } 1454 1455 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data) 1456 { 1457 vmx_write_guest_host_msr(vmx, MSR_KERNEL_GS_BASE, data, 1458 &vmx->msr_guest_kernel_gs_base); 1459 } 1460 #endif 1461 1462 static void grow_ple_window(struct kvm_vcpu *vcpu) 1463 { 1464 struct vcpu_vmx *vmx = to_vmx(vcpu); 1465 unsigned int old = vmx->ple_window; 1466 1467 vmx->ple_window = __grow_ple_window(old, ple_window, 1468 ple_window_grow, 1469 ple_window_max); 1470 1471 if (vmx->ple_window != old) { 1472 vmx->ple_window_dirty = true; 1473 trace_kvm_ple_window_update(vcpu->vcpu_id, 1474 vmx->ple_window, old); 1475 } 1476 } 1477 1478 static void shrink_ple_window(struct kvm_vcpu *vcpu) 1479 { 1480 struct vcpu_vmx *vmx = to_vmx(vcpu); 1481 unsigned int old = vmx->ple_window; 1482 1483 vmx->ple_window = __shrink_ple_window(old, ple_window, 1484 ple_window_shrink, 1485 ple_window); 1486 1487 if (vmx->ple_window != old) { 1488 vmx->ple_window_dirty = true; 1489 trace_kvm_ple_window_update(vcpu->vcpu_id, 1490 vmx->ple_window, old); 1491 } 1492 } 1493 1494 void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu) 1495 { 1496 struct vcpu_vmx *vmx = to_vmx(vcpu); 1497 bool already_loaded = vmx->loaded_vmcs->cpu == cpu; 1498 struct vmcs *prev; 1499 1500 if (!already_loaded) { 1501 loaded_vmcs_clear(vmx->loaded_vmcs); 1502 local_irq_disable(); 1503 1504 /* 1505 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to 1506 * this cpu's percpu list, otherwise it may not yet be deleted 1507 * from its previous cpu's percpu list. Pairs with the 1508 * smb_wmb() in __loaded_vmcs_clear(). 1509 */ 1510 smp_rmb(); 1511 1512 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link, 1513 &per_cpu(loaded_vmcss_on_cpu, cpu)); 1514 local_irq_enable(); 1515 } 1516 1517 prev = per_cpu(current_vmcs, cpu); 1518 if (prev != vmx->loaded_vmcs->vmcs) { 1519 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs; 1520 vmcs_load(vmx->loaded_vmcs->vmcs); 1521 } 1522 1523 if (!already_loaded) { 1524 void *gdt = get_current_gdt_ro(); 1525 1526 /* 1527 * Flush all EPTP/VPID contexts, the new pCPU may have stale 1528 * TLB entries from its previous association with the vCPU. 1529 */ 1530 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu); 1531 1532 /* 1533 * Linux uses per-cpu TSS and GDT, so set these when switching 1534 * processors. See 22.2.4. 1535 */ 1536 vmcs_writel(HOST_TR_BASE, 1537 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss); 1538 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */ 1539 1540 if (IS_ENABLED(CONFIG_IA32_EMULATION) || IS_ENABLED(CONFIG_X86_32)) { 1541 /* 22.2.3 */ 1542 vmcs_writel(HOST_IA32_SYSENTER_ESP, 1543 (unsigned long)(cpu_entry_stack(cpu) + 1)); 1544 } 1545 1546 vmx->loaded_vmcs->cpu = cpu; 1547 } 1548 } 1549 1550 /* 1551 * Switches to specified vcpu, until a matching vcpu_put(), but assumes 1552 * vcpu mutex is already taken. 1553 */ 1554 void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu) 1555 { 1556 if (vcpu->scheduled_out && !kvm_pause_in_guest(vcpu->kvm)) 1557 shrink_ple_window(vcpu); 1558 1559 vmx_vcpu_load_vmcs(vcpu, cpu); 1560 1561 vmx_vcpu_pi_load(vcpu, cpu); 1562 } 1563 1564 void vmx_vcpu_put(struct kvm_vcpu *vcpu) 1565 { 1566 vmx_vcpu_pi_put(vcpu); 1567 1568 vmx_prepare_switch_to_host(to_vmx(vcpu)); 1569 } 1570 1571 static void vmx_switch_loaded_vmcs(struct kvm_vcpu *vcpu, 1572 struct loaded_vmcs *vmcs) 1573 { 1574 struct vcpu_vmx *vmx = to_vmx(vcpu); 1575 int cpu; 1576 1577 cpu = get_cpu(); 1578 vmx->loaded_vmcs = vmcs; 1579 vmx_vcpu_load_vmcs(vcpu, cpu); 1580 put_cpu(); 1581 } 1582 1583 static void vmx_load_vmcs01(struct kvm_vcpu *vcpu) 1584 { 1585 struct vcpu_vmx *vmx = to_vmx(vcpu); 1586 1587 if (!is_guest_mode(vcpu)) { 1588 WARN_ON_ONCE(vmx->loaded_vmcs != &vmx->vmcs01); 1589 return; 1590 } 1591 1592 WARN_ON_ONCE(vmx->loaded_vmcs != &vmx->nested.vmcs02); 1593 vmx_switch_loaded_vmcs(vcpu, &vmx->vmcs01); 1594 } 1595 1596 static void vmx_put_vmcs01(struct kvm_vcpu *vcpu) 1597 { 1598 if (!is_guest_mode(vcpu)) 1599 return; 1600 1601 vmx_switch_loaded_vmcs(vcpu, &to_vmx(vcpu)->nested.vmcs02); 1602 } 1603 DEFINE_GUARD(vmx_vmcs01, struct kvm_vcpu *, 1604 vmx_load_vmcs01(_T), vmx_put_vmcs01(_T)) 1605 1606 bool vmx_emulation_required(struct kvm_vcpu *vcpu) 1607 { 1608 return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu); 1609 } 1610 1611 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu) 1612 { 1613 struct vcpu_vmx *vmx = to_vmx(vcpu); 1614 unsigned long rflags, save_rflags; 1615 1616 if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) { 1617 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS); 1618 rflags = vmcs_readl(GUEST_RFLAGS); 1619 if (vmx->rmode.vm86_active) { 1620 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS; 1621 save_rflags = vmx->rmode.save_rflags; 1622 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS; 1623 } 1624 vmx->rflags = rflags; 1625 } 1626 return vmx->rflags; 1627 } 1628 1629 void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags) 1630 { 1631 struct vcpu_vmx *vmx = to_vmx(vcpu); 1632 unsigned long old_rflags; 1633 1634 /* 1635 * Unlike CR0 and CR4, RFLAGS handling requires checking if the vCPU 1636 * is an unrestricted guest in order to mark L2 as needing emulation 1637 * if L1 runs L2 as a restricted guest. 1638 */ 1639 if (is_unrestricted_guest(vcpu)) { 1640 kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS); 1641 vmx->rflags = rflags; 1642 vmcs_writel(GUEST_RFLAGS, rflags); 1643 return; 1644 } 1645 1646 old_rflags = vmx_get_rflags(vcpu); 1647 vmx->rflags = rflags; 1648 if (vmx->rmode.vm86_active) { 1649 vmx->rmode.save_rflags = rflags; 1650 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM; 1651 } 1652 vmcs_writel(GUEST_RFLAGS, rflags); 1653 1654 if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM) 1655 vmx->vt.emulation_required = vmx_emulation_required(vcpu); 1656 } 1657 1658 bool vmx_get_if_flag(struct kvm_vcpu *vcpu) 1659 { 1660 return vmx_get_rflags(vcpu) & X86_EFLAGS_IF; 1661 } 1662 1663 u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu) 1664 { 1665 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO); 1666 int ret = 0; 1667 1668 if (interruptibility & GUEST_INTR_STATE_STI) 1669 ret |= KVM_X86_SHADOW_INT_STI; 1670 if (interruptibility & GUEST_INTR_STATE_MOV_SS) 1671 ret |= KVM_X86_SHADOW_INT_MOV_SS; 1672 1673 return ret; 1674 } 1675 1676 void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask) 1677 { 1678 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO); 1679 u32 interruptibility = interruptibility_old; 1680 1681 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS); 1682 1683 if (mask & KVM_X86_SHADOW_INT_MOV_SS) 1684 interruptibility |= GUEST_INTR_STATE_MOV_SS; 1685 else if (mask & KVM_X86_SHADOW_INT_STI) 1686 interruptibility |= GUEST_INTR_STATE_STI; 1687 1688 if ((interruptibility != interruptibility_old)) 1689 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility); 1690 } 1691 1692 static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data) 1693 { 1694 struct vcpu_vmx *vmx = to_vmx(vcpu); 1695 unsigned long value; 1696 1697 /* 1698 * Any MSR write that attempts to change bits marked reserved will 1699 * case a #GP fault. 1700 */ 1701 if (data & vmx->pt_desc.ctl_bitmask) 1702 return 1; 1703 1704 /* 1705 * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will 1706 * result in a #GP unless the same write also clears TraceEn. 1707 */ 1708 if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) && 1709 (data & RTIT_CTL_TRACEEN) && 1710 data != vmx->pt_desc.guest.ctl) 1711 return 1; 1712 1713 /* 1714 * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit 1715 * and FabricEn would cause #GP, if 1716 * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0 1717 */ 1718 if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) && 1719 !(data & RTIT_CTL_FABRIC_EN) && 1720 !intel_pt_validate_cap(vmx->pt_desc.caps, 1721 PT_CAP_single_range_output)) 1722 return 1; 1723 1724 /* 1725 * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that 1726 * utilize encodings marked reserved will cause a #GP fault. 1727 */ 1728 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods); 1729 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) && 1730 !test_bit((data & RTIT_CTL_MTC_RANGE) >> 1731 RTIT_CTL_MTC_RANGE_OFFSET, &value)) 1732 return 1; 1733 value = intel_pt_validate_cap(vmx->pt_desc.caps, 1734 PT_CAP_cycle_thresholds); 1735 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) && 1736 !test_bit((data & RTIT_CTL_CYC_THRESH) >> 1737 RTIT_CTL_CYC_THRESH_OFFSET, &value)) 1738 return 1; 1739 value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods); 1740 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) && 1741 !test_bit((data & RTIT_CTL_PSB_FREQ) >> 1742 RTIT_CTL_PSB_FREQ_OFFSET, &value)) 1743 return 1; 1744 1745 /* 1746 * If ADDRx_CFG is reserved or the encodings is >2 will 1747 * cause a #GP fault. 1748 */ 1749 value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET; 1750 if ((value && (vmx->pt_desc.num_address_ranges < 1)) || (value > 2)) 1751 return 1; 1752 value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET; 1753 if ((value && (vmx->pt_desc.num_address_ranges < 2)) || (value > 2)) 1754 return 1; 1755 value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET; 1756 if ((value && (vmx->pt_desc.num_address_ranges < 3)) || (value > 2)) 1757 return 1; 1758 value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET; 1759 if ((value && (vmx->pt_desc.num_address_ranges < 4)) || (value > 2)) 1760 return 1; 1761 1762 return 0; 1763 } 1764 1765 int vmx_check_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type, 1766 void *insn, int insn_len) 1767 { 1768 /* 1769 * Emulation of instructions in SGX enclaves is impossible as RIP does 1770 * not point at the failing instruction, and even if it did, the code 1771 * stream is inaccessible. Inject #UD instead of exiting to userspace 1772 * so that guest userspace can't DoS the guest simply by triggering 1773 * emulation (enclaves are CPL3 only). 1774 */ 1775 if (vmx_get_exit_reason(vcpu).enclave_mode) { 1776 kvm_queue_exception(vcpu, UD_VECTOR); 1777 return X86EMUL_PROPAGATE_FAULT; 1778 } 1779 1780 /* Check that emulation is possible during event vectoring */ 1781 if ((to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) && 1782 !kvm_can_emulate_event_vectoring(emul_type)) 1783 return X86EMUL_UNHANDLEABLE_VECTORING; 1784 1785 return X86EMUL_CONTINUE; 1786 } 1787 1788 static int skip_emulated_instruction(struct kvm_vcpu *vcpu) 1789 { 1790 union vmx_exit_reason exit_reason = vmx_get_exit_reason(vcpu); 1791 unsigned long rip, orig_rip; 1792 u32 instr_len; 1793 1794 /* 1795 * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on 1796 * undefined behavior: Intel's SDM doesn't mandate the VMCS field be 1797 * set when EPT misconfig occurs. In practice, real hardware updates 1798 * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors 1799 * (namely Hyper-V) don't set it due to it being undefined behavior, 1800 * i.e. we end up advancing IP with some random value. 1801 */ 1802 if (!static_cpu_has(X86_FEATURE_HYPERVISOR) || 1803 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) { 1804 instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN); 1805 1806 /* 1807 * Emulating an enclave's instructions isn't supported as KVM 1808 * cannot access the enclave's memory or its true RIP, e.g. the 1809 * vmcs.GUEST_RIP points at the exit point of the enclave, not 1810 * the RIP that actually triggered the VM-Exit. But, because 1811 * most instructions that cause VM-Exit will #UD in an enclave, 1812 * most instruction-based VM-Exits simply do not occur. 1813 * 1814 * There are a few exceptions, notably the debug instructions 1815 * INT1ICEBRK and INT3, as they are allowed in debug enclaves 1816 * and generate #DB/#BP as expected, which KVM might intercept. 1817 * But again, the CPU does the dirty work and saves an instr 1818 * length of zero so VMMs don't shoot themselves in the foot. 1819 * WARN if KVM tries to skip a non-zero length instruction on 1820 * a VM-Exit from an enclave. 1821 */ 1822 if (!instr_len) 1823 goto rip_updated; 1824 1825 WARN_ONCE(exit_reason.enclave_mode, 1826 "skipping instruction after SGX enclave VM-Exit"); 1827 1828 orig_rip = kvm_rip_read(vcpu); 1829 rip = orig_rip + instr_len; 1830 #ifdef CONFIG_X86_64 1831 /* 1832 * We need to mask out the high 32 bits of RIP if not in 64-bit 1833 * mode, but just finding out that we are in 64-bit mode is 1834 * quite expensive. Only do it if there was a carry. 1835 */ 1836 if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu)) 1837 rip = (u32)rip; 1838 #endif 1839 kvm_rip_write(vcpu, rip); 1840 } else { 1841 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP)) 1842 return 0; 1843 } 1844 1845 rip_updated: 1846 /* skipping an emulated instruction also counts */ 1847 vmx_set_interrupt_shadow(vcpu, 0); 1848 1849 return 1; 1850 } 1851 1852 /* 1853 * Recognizes a pending MTF VM-exit and records the nested state for later 1854 * delivery. 1855 */ 1856 void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu) 1857 { 1858 struct vmcs12 *vmcs12 = get_vmcs12(vcpu); 1859 struct vcpu_vmx *vmx = to_vmx(vcpu); 1860 1861 if (!is_guest_mode(vcpu)) 1862 return; 1863 1864 /* 1865 * Per the SDM, MTF takes priority over debug-trap exceptions besides 1866 * TSS T-bit traps and ICEBP (INT1). KVM doesn't emulate T-bit traps 1867 * or ICEBP (in the emulator proper), and skipping of ICEBP after an 1868 * intercepted #DB deliberately avoids single-step #DB and MTF updates 1869 * as ICEBP is higher priority than both. As instruction emulation is 1870 * completed at this point (i.e. KVM is at the instruction boundary), 1871 * any #DB exception pending delivery must be a debug-trap of lower 1872 * priority than MTF. Record the pending MTF state to be delivered in 1873 * vmx_check_nested_events(). 1874 */ 1875 if (nested_cpu_has_mtf(vmcs12) && 1876 (!vcpu->arch.exception.pending || 1877 vcpu->arch.exception.vector == DB_VECTOR) && 1878 (!vcpu->arch.exception_vmexit.pending || 1879 vcpu->arch.exception_vmexit.vector == DB_VECTOR)) { 1880 vmx->nested.mtf_pending = true; 1881 kvm_make_request(KVM_REQ_EVENT, vcpu); 1882 } else { 1883 vmx->nested.mtf_pending = false; 1884 } 1885 } 1886 1887 int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu) 1888 { 1889 vmx_update_emulated_instruction(vcpu); 1890 return skip_emulated_instruction(vcpu); 1891 } 1892 1893 static void vmx_clear_hlt(struct kvm_vcpu *vcpu) 1894 { 1895 /* 1896 * Ensure that we clear the HLT state in the VMCS. We don't need to 1897 * explicitly skip the instruction because if the HLT state is set, 1898 * then the instruction is already executing and RIP has already been 1899 * advanced. 1900 */ 1901 if (kvm_hlt_in_guest(vcpu->kvm) && 1902 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT) 1903 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE); 1904 } 1905 1906 void vmx_inject_exception(struct kvm_vcpu *vcpu) 1907 { 1908 struct kvm_queued_exception *ex = &vcpu->arch.exception; 1909 u32 intr_info = ex->vector | INTR_INFO_VALID_MASK; 1910 struct vcpu_vmx *vmx = to_vmx(vcpu); 1911 1912 kvm_deliver_exception_payload(vcpu, ex); 1913 1914 if (ex->has_error_code) { 1915 /* 1916 * Despite the error code being architecturally defined as 32 1917 * bits, and the VMCS field being 32 bits, Intel CPUs and thus 1918 * VMX don't actually supporting setting bits 31:16. Hardware 1919 * will (should) never provide a bogus error code, but AMD CPUs 1920 * do generate error codes with bits 31:16 set, and so KVM's 1921 * ABI lets userspace shove in arbitrary 32-bit values. Drop 1922 * the upper bits to avoid VM-Fail, losing information that 1923 * doesn't really exist is preferable to killing the VM. 1924 */ 1925 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, (u16)ex->error_code); 1926 intr_info |= INTR_INFO_DELIVER_CODE_MASK; 1927 } 1928 1929 if (vmx->rmode.vm86_active) { 1930 int inc_eip = 0; 1931 if (kvm_exception_is_soft(ex->vector)) 1932 inc_eip = vcpu->arch.event_exit_inst_len; 1933 kvm_inject_realmode_interrupt(vcpu, ex->vector, inc_eip); 1934 return; 1935 } 1936 1937 WARN_ON_ONCE(vmx->vt.emulation_required); 1938 1939 if (kvm_exception_is_soft(ex->vector)) { 1940 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN, 1941 vmx->vcpu.arch.event_exit_inst_len); 1942 intr_info |= INTR_TYPE_SOFT_EXCEPTION; 1943 } else 1944 intr_info |= INTR_TYPE_HARD_EXCEPTION; 1945 1946 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info); 1947 1948 vmx_clear_hlt(vcpu); 1949 } 1950 1951 static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr, 1952 bool load_into_hardware) 1953 { 1954 struct vmx_uret_msr *uret_msr; 1955 1956 uret_msr = vmx_find_uret_msr(vmx, msr); 1957 if (!uret_msr) 1958 return; 1959 1960 uret_msr->load_into_hardware = load_into_hardware; 1961 } 1962 1963 /* 1964 * Configuring user return MSRs to automatically save, load, and restore MSRs 1965 * that need to be shoved into hardware when running the guest. Note, omitting 1966 * an MSR here does _NOT_ mean it's not emulated, only that it will not be 1967 * loaded into hardware when running the guest. 1968 */ 1969 static void vmx_setup_uret_msrs(struct vcpu_vmx *vmx) 1970 { 1971 #ifdef CONFIG_X86_64 1972 bool load_syscall_msrs; 1973 1974 /* 1975 * The SYSCALL MSRs are only needed on long mode guests, and only 1976 * when EFER.SCE is set. 1977 */ 1978 load_syscall_msrs = is_long_mode(&vmx->vcpu) && 1979 (vmx->vcpu.arch.efer & EFER_SCE); 1980 1981 vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs); 1982 vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs); 1983 vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs); 1984 #endif 1985 vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx)); 1986 1987 vmx_setup_uret_msr(vmx, MSR_TSC_AUX, 1988 guest_cpu_cap_has(&vmx->vcpu, X86_FEATURE_RDTSCP) || 1989 guest_cpu_cap_has(&vmx->vcpu, X86_FEATURE_RDPID)); 1990 1991 /* 1992 * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new 1993 * kernel and old userspace. If those guests run on a tsx=off host, do 1994 * allow guests to use TSX_CTRL, but don't change the value in hardware 1995 * so that TSX remains always disabled. 1996 */ 1997 vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM)); 1998 1999 /* 2000 * The set of MSRs to load may have changed, reload MSRs before the 2001 * next VM-Enter. 2002 */ 2003 vmx->guest_uret_msrs_loaded = false; 2004 } 2005 2006 u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu) 2007 { 2008 struct vmcs12 *vmcs12 = get_vmcs12(vcpu); 2009 2010 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING)) 2011 return vmcs12->tsc_offset; 2012 2013 return 0; 2014 } 2015 2016 u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu) 2017 { 2018 struct vmcs12 *vmcs12 = get_vmcs12(vcpu); 2019 2020 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING) && 2021 nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING)) 2022 return vmcs12->tsc_multiplier; 2023 2024 return kvm_caps.default_tsc_scaling_ratio; 2025 } 2026 2027 void vmx_write_tsc_offset(struct kvm_vcpu *vcpu) 2028 { 2029 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset); 2030 } 2031 2032 void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu) 2033 { 2034 vmcs_write64(TSC_MULTIPLIER, vcpu->arch.tsc_scaling_ratio); 2035 } 2036 2037 /* 2038 * Userspace is allowed to set any supported IA32_FEATURE_CONTROL regardless of 2039 * guest CPUID. Note, KVM allows userspace to set "VMX in SMX" to maintain 2040 * backwards compatibility even though KVM doesn't support emulating SMX. And 2041 * because userspace set "VMX in SMX", the guest must also be allowed to set it, 2042 * e.g. if the MSR is left unlocked and the guest does a RMW operation. 2043 */ 2044 #define KVM_SUPPORTED_FEATURE_CONTROL (FEAT_CTL_LOCKED | \ 2045 FEAT_CTL_VMX_ENABLED_INSIDE_SMX | \ 2046 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX | \ 2047 FEAT_CTL_SGX_LC_ENABLED | \ 2048 FEAT_CTL_SGX_ENABLED | \ 2049 FEAT_CTL_LMCE_ENABLED) 2050 2051 static inline bool is_vmx_feature_control_msr_valid(struct vcpu_vmx *vmx, 2052 struct msr_data *msr) 2053 { 2054 uint64_t valid_bits; 2055 2056 /* 2057 * Ensure KVM_SUPPORTED_FEATURE_CONTROL is updated when new bits are 2058 * exposed to the guest. 2059 */ 2060 WARN_ON_ONCE(vmx->msr_ia32_feature_control_valid_bits & 2061 ~KVM_SUPPORTED_FEATURE_CONTROL); 2062 2063 if (!msr->host_initiated && 2064 (vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED)) 2065 return false; 2066 2067 if (msr->host_initiated) 2068 valid_bits = KVM_SUPPORTED_FEATURE_CONTROL; 2069 else 2070 valid_bits = vmx->msr_ia32_feature_control_valid_bits; 2071 2072 return !(msr->data & ~valid_bits); 2073 } 2074 2075 int vmx_get_feature_msr(u32 msr, u64 *data) 2076 { 2077 switch (msr) { 2078 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR: 2079 if (!nested) 2080 return 1; 2081 return vmx_get_vmx_msr(&vmcs_config.nested, msr, data); 2082 default: 2083 return KVM_MSR_RET_UNSUPPORTED; 2084 } 2085 } 2086 2087 /* 2088 * Reads an msr value (of 'msr_info->index') into 'msr_info->data'. 2089 * Returns 0 on success, non-0 otherwise. 2090 * Assumes vcpu_load() was already called. 2091 */ 2092 int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info) 2093 { 2094 struct vcpu_vmx *vmx = to_vmx(vcpu); 2095 struct vmx_uret_msr *msr; 2096 u32 index; 2097 2098 switch (msr_info->index) { 2099 #ifdef CONFIG_X86_64 2100 case MSR_FS_BASE: 2101 msr_info->data = vmcs_readl(GUEST_FS_BASE); 2102 break; 2103 case MSR_GS_BASE: 2104 msr_info->data = vmcs_readl(GUEST_GS_BASE); 2105 break; 2106 case MSR_KERNEL_GS_BASE: 2107 msr_info->data = vmx_read_guest_kernel_gs_base(vmx); 2108 break; 2109 #endif 2110 case MSR_EFER: 2111 return kvm_get_msr_common(vcpu, msr_info); 2112 case MSR_IA32_TSX_CTRL: 2113 if (!msr_info->host_initiated && 2114 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR)) 2115 return 1; 2116 goto find_uret_msr; 2117 case MSR_IA32_UMWAIT_CONTROL: 2118 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx)) 2119 return 1; 2120 2121 msr_info->data = vmx->msr_ia32_umwait_control; 2122 break; 2123 case MSR_IA32_SPEC_CTRL: 2124 if (!msr_info->host_initiated && 2125 !guest_has_spec_ctrl_msr(vcpu)) 2126 return 1; 2127 2128 msr_info->data = to_vmx(vcpu)->spec_ctrl; 2129 break; 2130 case MSR_IA32_SYSENTER_CS: 2131 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS); 2132 break; 2133 case MSR_IA32_SYSENTER_EIP: 2134 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP); 2135 break; 2136 case MSR_IA32_SYSENTER_ESP: 2137 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP); 2138 break; 2139 case MSR_IA32_BNDCFGS: 2140 if (!kvm_mpx_supported() || 2141 (!msr_info->host_initiated && 2142 !guest_cpu_cap_has(vcpu, X86_FEATURE_MPX))) 2143 return 1; 2144 msr_info->data = vmcs_read64(GUEST_BNDCFGS); 2145 break; 2146 case MSR_IA32_MCG_EXT_CTL: 2147 if (!msr_info->host_initiated && 2148 !(vmx->msr_ia32_feature_control & 2149 FEAT_CTL_LMCE_ENABLED)) 2150 return 1; 2151 msr_info->data = vcpu->arch.mcg_ext_ctl; 2152 break; 2153 case MSR_IA32_FEAT_CTL: 2154 msr_info->data = vmx->msr_ia32_feature_control; 2155 break; 2156 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3: 2157 if (!msr_info->host_initiated && 2158 !guest_cpu_cap_has(vcpu, X86_FEATURE_SGX_LC)) 2159 return 1; 2160 msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash 2161 [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0]; 2162 break; 2163 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR: 2164 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_VMX)) 2165 return 1; 2166 if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index, 2167 &msr_info->data)) 2168 return 1; 2169 #ifdef CONFIG_KVM_HYPERV 2170 /* 2171 * Enlightened VMCS v1 doesn't have certain VMCS fields but 2172 * instead of just ignoring the features, different Hyper-V 2173 * versions are either trying to use them and fail or do some 2174 * sanity checking and refuse to boot. Filter all unsupported 2175 * features out. 2176 */ 2177 if (!msr_info->host_initiated && guest_cpu_cap_has_evmcs(vcpu)) 2178 nested_evmcs_filter_control_msr(vcpu, msr_info->index, 2179 &msr_info->data); 2180 #endif 2181 break; 2182 case MSR_IA32_RTIT_CTL: 2183 if (!vmx_pt_mode_is_host_guest()) 2184 return 1; 2185 msr_info->data = vmx->pt_desc.guest.ctl; 2186 break; 2187 case MSR_IA32_RTIT_STATUS: 2188 if (!vmx_pt_mode_is_host_guest()) 2189 return 1; 2190 msr_info->data = vmx->pt_desc.guest.status; 2191 break; 2192 case MSR_IA32_RTIT_CR3_MATCH: 2193 if (!vmx_pt_mode_is_host_guest() || 2194 !intel_pt_validate_cap(vmx->pt_desc.caps, 2195 PT_CAP_cr3_filtering)) 2196 return 1; 2197 msr_info->data = vmx->pt_desc.guest.cr3_match; 2198 break; 2199 case MSR_IA32_RTIT_OUTPUT_BASE: 2200 if (!vmx_pt_mode_is_host_guest() || 2201 (!intel_pt_validate_cap(vmx->pt_desc.caps, 2202 PT_CAP_topa_output) && 2203 !intel_pt_validate_cap(vmx->pt_desc.caps, 2204 PT_CAP_single_range_output))) 2205 return 1; 2206 msr_info->data = vmx->pt_desc.guest.output_base; 2207 break; 2208 case MSR_IA32_RTIT_OUTPUT_MASK: 2209 if (!vmx_pt_mode_is_host_guest() || 2210 (!intel_pt_validate_cap(vmx->pt_desc.caps, 2211 PT_CAP_topa_output) && 2212 !intel_pt_validate_cap(vmx->pt_desc.caps, 2213 PT_CAP_single_range_output))) 2214 return 1; 2215 msr_info->data = vmx->pt_desc.guest.output_mask; 2216 break; 2217 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B: 2218 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A; 2219 if (!vmx_pt_mode_is_host_guest() || 2220 (index >= 2 * vmx->pt_desc.num_address_ranges)) 2221 return 1; 2222 if (index % 2) 2223 msr_info->data = vmx->pt_desc.guest.addr_b[index / 2]; 2224 else 2225 msr_info->data = vmx->pt_desc.guest.addr_a[index / 2]; 2226 break; 2227 case MSR_IA32_S_CET: 2228 msr_info->data = vmcs_readl(GUEST_S_CET); 2229 break; 2230 case MSR_KVM_INTERNAL_GUEST_SSP: 2231 msr_info->data = vmcs_readl(GUEST_SSP); 2232 break; 2233 case MSR_IA32_INT_SSP_TAB: 2234 msr_info->data = vmcs_readl(GUEST_INTR_SSP_TABLE); 2235 break; 2236 case MSR_IA32_DEBUGCTLMSR: 2237 msr_info->data = vmx_guest_debugctl_read(); 2238 break; 2239 default: 2240 find_uret_msr: 2241 msr = vmx_find_uret_msr(vmx, msr_info->index); 2242 if (msr) { 2243 msr_info->data = msr->data; 2244 break; 2245 } 2246 return kvm_get_msr_common(vcpu, msr_info); 2247 } 2248 2249 return 0; 2250 } 2251 2252 static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu, 2253 u64 data) 2254 { 2255 #ifdef CONFIG_X86_64 2256 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_LM)) 2257 return (u32)data; 2258 #endif 2259 return (unsigned long)data; 2260 } 2261 2262 u64 vmx_get_supported_debugctl(struct kvm_vcpu *vcpu, bool host_initiated) 2263 { 2264 u64 debugctl = 0; 2265 2266 if (boot_cpu_has(X86_FEATURE_BUS_LOCK_DETECT) && 2267 (host_initiated || guest_cpu_cap_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))) 2268 debugctl |= DEBUGCTLMSR_BUS_LOCK_DETECT; 2269 2270 if ((kvm_caps.supported_perf_cap & PERF_CAP_LBR_FMT) && 2271 (host_initiated || intel_pmu_lbr_is_enabled(vcpu))) 2272 debugctl |= DEBUGCTLMSR_LBR | DEBUGCTLMSR_FREEZE_LBRS_ON_PMI; 2273 2274 if (boot_cpu_has(X86_FEATURE_RTM) && 2275 (host_initiated || guest_cpu_cap_has(vcpu, X86_FEATURE_RTM))) 2276 debugctl |= DEBUGCTLMSR_RTM_DEBUG; 2277 2278 return debugctl; 2279 } 2280 2281 bool vmx_is_valid_debugctl(struct kvm_vcpu *vcpu, u64 data, bool host_initiated) 2282 { 2283 u64 invalid; 2284 2285 invalid = data & ~vmx_get_supported_debugctl(vcpu, host_initiated); 2286 if (invalid & (DEBUGCTLMSR_BTF | DEBUGCTLMSR_LBR)) { 2287 kvm_pr_unimpl_wrmsr(vcpu, MSR_IA32_DEBUGCTLMSR, data); 2288 invalid &= ~(DEBUGCTLMSR_BTF | DEBUGCTLMSR_LBR); 2289 } 2290 return !invalid; 2291 } 2292 2293 /* 2294 * Writes msr value into the appropriate "register". 2295 * Returns 0 on success, non-0 otherwise. 2296 * Assumes vcpu_load() was already called. 2297 */ 2298 int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info) 2299 { 2300 struct vcpu_vmx *vmx = to_vmx(vcpu); 2301 struct vmx_uret_msr *msr; 2302 int ret = 0; 2303 u32 msr_index = msr_info->index; 2304 u64 data = msr_info->data; 2305 u32 index; 2306 2307 switch (msr_index) { 2308 case MSR_EFER: 2309 ret = kvm_set_msr_common(vcpu, msr_info); 2310 break; 2311 #ifdef CONFIG_X86_64 2312 case MSR_FS_BASE: 2313 vmx_segment_cache_clear(vmx); 2314 vmcs_writel(GUEST_FS_BASE, data); 2315 break; 2316 case MSR_GS_BASE: 2317 vmx_segment_cache_clear(vmx); 2318 vmcs_writel(GUEST_GS_BASE, data); 2319 break; 2320 case MSR_KERNEL_GS_BASE: 2321 vmx_write_guest_kernel_gs_base(vmx, data); 2322 break; 2323 case MSR_IA32_XFD: 2324 ret = kvm_set_msr_common(vcpu, msr_info); 2325 /* 2326 * Always intercepting WRMSR could incur non-negligible 2327 * overhead given xfd might be changed frequently in 2328 * guest context switch. Disable write interception 2329 * upon the first write with a non-zero value (indicating 2330 * potential usage on dynamic xfeatures). Also update 2331 * exception bitmap to trap #NM for proper virtualization 2332 * of guest xfd_err. 2333 */ 2334 if (!ret && data) { 2335 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_XFD, 2336 MSR_TYPE_RW); 2337 vcpu->arch.xfd_no_write_intercept = true; 2338 vmx_update_exception_bitmap(vcpu); 2339 } 2340 break; 2341 #endif 2342 case MSR_IA32_SYSENTER_CS: 2343 if (is_guest_mode(vcpu)) 2344 get_vmcs12(vcpu)->guest_sysenter_cs = data; 2345 vmcs_write32(GUEST_SYSENTER_CS, data); 2346 break; 2347 case MSR_IA32_SYSENTER_EIP: 2348 if (is_guest_mode(vcpu)) { 2349 data = nested_vmx_truncate_sysenter_addr(vcpu, data); 2350 get_vmcs12(vcpu)->guest_sysenter_eip = data; 2351 } 2352 vmcs_writel(GUEST_SYSENTER_EIP, data); 2353 break; 2354 case MSR_IA32_SYSENTER_ESP: 2355 if (is_guest_mode(vcpu)) { 2356 data = nested_vmx_truncate_sysenter_addr(vcpu, data); 2357 get_vmcs12(vcpu)->guest_sysenter_esp = data; 2358 } 2359 vmcs_writel(GUEST_SYSENTER_ESP, data); 2360 break; 2361 case MSR_IA32_DEBUGCTLMSR: 2362 if (!vmx_is_valid_debugctl(vcpu, data, msr_info->host_initiated)) 2363 return 1; 2364 2365 data &= vmx_get_supported_debugctl(vcpu, msr_info->host_initiated); 2366 2367 if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls & 2368 VM_EXIT_SAVE_DEBUG_CONTROLS) 2369 get_vmcs12(vcpu)->guest_ia32_debugctl = data; 2370 2371 vmx_guest_debugctl_write(vcpu, data); 2372 2373 if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event && 2374 (data & DEBUGCTLMSR_LBR)) 2375 intel_pmu_create_guest_lbr_event(vcpu); 2376 return 0; 2377 case MSR_IA32_BNDCFGS: 2378 if (!kvm_mpx_supported() || 2379 (!msr_info->host_initiated && 2380 !guest_cpu_cap_has(vcpu, X86_FEATURE_MPX))) 2381 return 1; 2382 if (is_noncanonical_msr_address(data & PAGE_MASK, vcpu) || 2383 (data & MSR_IA32_BNDCFGS_RSVD)) 2384 return 1; 2385 2386 if (is_guest_mode(vcpu) && 2387 ((vmx->nested.msrs.entry_ctls_high & VM_ENTRY_LOAD_BNDCFGS) || 2388 (vmx->nested.msrs.exit_ctls_high & VM_EXIT_CLEAR_BNDCFGS))) 2389 get_vmcs12(vcpu)->guest_bndcfgs = data; 2390 2391 vmcs_write64(GUEST_BNDCFGS, data); 2392 break; 2393 case MSR_IA32_UMWAIT_CONTROL: 2394 if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx)) 2395 return 1; 2396 2397 /* The reserved bit 1 and non-32 bit [63:32] should be zero */ 2398 if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32))) 2399 return 1; 2400 2401 vmx->msr_ia32_umwait_control = data; 2402 break; 2403 case MSR_IA32_SPEC_CTRL: 2404 if (!msr_info->host_initiated && 2405 !guest_has_spec_ctrl_msr(vcpu)) 2406 return 1; 2407 2408 if (kvm_spec_ctrl_test_value(data)) 2409 return 1; 2410 2411 vmx->spec_ctrl = data; 2412 if (!data) 2413 break; 2414 2415 /* 2416 * For non-nested: 2417 * When it's written (to non-zero) for the first time, pass 2418 * it through. 2419 * 2420 * For nested: 2421 * The handling of the MSR bitmap for L2 guests is done in 2422 * nested_vmx_prepare_msr_bitmap. We should not touch the 2423 * vmcs02.msr_bitmap here since it gets completely overwritten 2424 * in the merging. We update the vmcs01 here for L1 as well 2425 * since it will end up touching the MSR anyway now. 2426 */ 2427 vmx_disable_intercept_for_msr(vcpu, 2428 MSR_IA32_SPEC_CTRL, 2429 MSR_TYPE_RW); 2430 break; 2431 case MSR_IA32_TSX_CTRL: 2432 if (!msr_info->host_initiated && 2433 !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR)) 2434 return 1; 2435 if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR)) 2436 return 1; 2437 goto find_uret_msr; 2438 case MSR_IA32_CR_PAT: 2439 ret = kvm_set_msr_common(vcpu, msr_info); 2440 if (ret) 2441 break; 2442 2443 if (is_guest_mode(vcpu) && 2444 get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT) 2445 get_vmcs12(vcpu)->guest_ia32_pat = data; 2446 2447 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) 2448 vmcs_write64(GUEST_IA32_PAT, data); 2449 break; 2450 case MSR_IA32_MCG_EXT_CTL: 2451 if ((!msr_info->host_initiated && 2452 !(to_vmx(vcpu)->msr_ia32_feature_control & 2453 FEAT_CTL_LMCE_ENABLED)) || 2454 (data & ~MCG_EXT_CTL_LMCE_EN)) 2455 return 1; 2456 vcpu->arch.mcg_ext_ctl = data; 2457 break; 2458 case MSR_IA32_FEAT_CTL: 2459 if (!is_vmx_feature_control_msr_valid(vmx, msr_info)) 2460 return 1; 2461 2462 vmx->msr_ia32_feature_control = data; 2463 if (msr_info->host_initiated && data == 0) 2464 vmx_leave_nested(vcpu); 2465 2466 /* SGX may be enabled/disabled by guest's firmware */ 2467 vmx_write_encls_bitmap(vcpu, NULL); 2468 break; 2469 case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3: 2470 /* 2471 * On real hardware, the LE hash MSRs are writable before 2472 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX), 2473 * at which point SGX related bits in IA32_FEATURE_CONTROL 2474 * become writable. 2475 * 2476 * KVM does not emulate SGX activation for simplicity, so 2477 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL 2478 * is unlocked. This is technically not architectural 2479 * behavior, but it's close enough. 2480 */ 2481 if (!msr_info->host_initiated && 2482 (!guest_cpu_cap_has(vcpu, X86_FEATURE_SGX_LC) || 2483 ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) && 2484 !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED)))) 2485 return 1; 2486 vmx->msr_ia32_sgxlepubkeyhash 2487 [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data; 2488 break; 2489 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR: 2490 if (!msr_info->host_initiated) 2491 return 1; /* they are read-only */ 2492 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_VMX)) 2493 return 1; 2494 return vmx_set_vmx_msr(vcpu, msr_index, data); 2495 case MSR_IA32_RTIT_CTL: 2496 if (!vmx_pt_mode_is_host_guest() || 2497 vmx_rtit_ctl_check(vcpu, data) || 2498 vmx->nested.vmxon) 2499 return 1; 2500 vmcs_write64(GUEST_IA32_RTIT_CTL, data); 2501 vmx->pt_desc.guest.ctl = data; 2502 pt_update_intercept_for_msr(vcpu); 2503 break; 2504 case MSR_IA32_RTIT_STATUS: 2505 if (!pt_can_write_msr(vmx)) 2506 return 1; 2507 if (data & MSR_IA32_RTIT_STATUS_MASK) 2508 return 1; 2509 vmx->pt_desc.guest.status = data; 2510 break; 2511 case MSR_IA32_RTIT_CR3_MATCH: 2512 if (!pt_can_write_msr(vmx)) 2513 return 1; 2514 if (!intel_pt_validate_cap(vmx->pt_desc.caps, 2515 PT_CAP_cr3_filtering)) 2516 return 1; 2517 vmx->pt_desc.guest.cr3_match = data; 2518 break; 2519 case MSR_IA32_RTIT_OUTPUT_BASE: 2520 if (!pt_can_write_msr(vmx)) 2521 return 1; 2522 if (!intel_pt_validate_cap(vmx->pt_desc.caps, 2523 PT_CAP_topa_output) && 2524 !intel_pt_validate_cap(vmx->pt_desc.caps, 2525 PT_CAP_single_range_output)) 2526 return 1; 2527 if (!pt_output_base_valid(vcpu, data)) 2528 return 1; 2529 vmx->pt_desc.guest.output_base = data; 2530 break; 2531 case MSR_IA32_RTIT_OUTPUT_MASK: 2532 if (!pt_can_write_msr(vmx)) 2533 return 1; 2534 if (!intel_pt_validate_cap(vmx->pt_desc.caps, 2535 PT_CAP_topa_output) && 2536 !intel_pt_validate_cap(vmx->pt_desc.caps, 2537 PT_CAP_single_range_output)) 2538 return 1; 2539 vmx->pt_desc.guest.output_mask = data; 2540 break; 2541 case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B: 2542 if (!pt_can_write_msr(vmx)) 2543 return 1; 2544 index = msr_info->index - MSR_IA32_RTIT_ADDR0_A; 2545 if (index >= 2 * vmx->pt_desc.num_address_ranges) 2546 return 1; 2547 if (is_noncanonical_msr_address(data, vcpu)) 2548 return 1; 2549 if (index % 2) 2550 vmx->pt_desc.guest.addr_b[index / 2] = data; 2551 else 2552 vmx->pt_desc.guest.addr_a[index / 2] = data; 2553 break; 2554 case MSR_IA32_S_CET: 2555 vmcs_writel(GUEST_S_CET, data); 2556 break; 2557 case MSR_KVM_INTERNAL_GUEST_SSP: 2558 vmcs_writel(GUEST_SSP, data); 2559 break; 2560 case MSR_IA32_INT_SSP_TAB: 2561 vmcs_writel(GUEST_INTR_SSP_TABLE, data); 2562 break; 2563 case MSR_IA32_PERF_CAPABILITIES: 2564 if (data & PERF_CAP_LBR_FMT) { 2565 if ((data & PERF_CAP_LBR_FMT) != 2566 (kvm_caps.supported_perf_cap & PERF_CAP_LBR_FMT)) 2567 return 1; 2568 if (!cpuid_model_is_consistent(vcpu)) 2569 return 1; 2570 } 2571 if (data & PERF_CAP_PEBS_FORMAT) { 2572 if ((data & PERF_CAP_PEBS_MASK) != 2573 (kvm_caps.supported_perf_cap & PERF_CAP_PEBS_MASK)) 2574 return 1; 2575 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_DS)) 2576 return 1; 2577 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_DTES64)) 2578 return 1; 2579 if (!cpuid_model_is_consistent(vcpu)) 2580 return 1; 2581 } 2582 ret = kvm_set_msr_common(vcpu, msr_info); 2583 break; 2584 2585 default: 2586 find_uret_msr: 2587 msr = vmx_find_uret_msr(vmx, msr_index); 2588 if (msr) 2589 ret = vmx_set_guest_uret_msr(vmx, msr, data); 2590 else 2591 ret = kvm_set_msr_common(vcpu, msr_info); 2592 } 2593 2594 /* FB_CLEAR may have changed, also update the FB_CLEAR_DIS behavior */ 2595 if (msr_index == MSR_IA32_ARCH_CAPABILITIES) 2596 vmx_update_fb_clear_dis(vcpu, vmx); 2597 2598 return ret; 2599 } 2600 2601 void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg) 2602 { 2603 unsigned long guest_owned_bits; 2604 2605 kvm_register_mark_available(vcpu, reg); 2606 2607 switch (reg) { 2608 case VCPU_REGS_RSP: 2609 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP); 2610 break; 2611 case VCPU_REGS_RIP: 2612 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP); 2613 break; 2614 case VCPU_EXREG_PDPTR: 2615 if (enable_ept) 2616 ept_save_pdptrs(vcpu); 2617 break; 2618 case VCPU_EXREG_CR0: 2619 guest_owned_bits = vcpu->arch.cr0_guest_owned_bits; 2620 2621 vcpu->arch.cr0 &= ~guest_owned_bits; 2622 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits; 2623 break; 2624 case VCPU_EXREG_CR3: 2625 /* 2626 * When intercepting CR3 loads, e.g. for shadowing paging, KVM's 2627 * CR3 is loaded into hardware, not the guest's CR3. 2628 */ 2629 if (!(exec_controls_get(to_vmx(vcpu)) & CPU_BASED_CR3_LOAD_EXITING)) 2630 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3); 2631 break; 2632 case VCPU_EXREG_CR4: 2633 guest_owned_bits = vcpu->arch.cr4_guest_owned_bits; 2634 2635 vcpu->arch.cr4 &= ~guest_owned_bits; 2636 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits; 2637 break; 2638 default: 2639 KVM_BUG_ON(1, vcpu->kvm); 2640 break; 2641 } 2642 } 2643 2644 /* 2645 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID 2646 * directly instead of going through cpu_has(), to ensure KVM is trapping 2647 * ENCLS whenever it's supported in hardware. It does not matter whether 2648 * the host OS supports or has enabled SGX. 2649 */ 2650 static bool cpu_has_sgx(void) 2651 { 2652 return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0)); 2653 } 2654 2655 static int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt, u32 msr, u32 *result) 2656 { 2657 u32 vmx_msr_low, vmx_msr_high; 2658 u32 ctl = ctl_min | ctl_opt; 2659 2660 rdmsr(msr, vmx_msr_low, vmx_msr_high); 2661 2662 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */ 2663 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */ 2664 2665 /* Ensure minimum (required) set of control bits are supported. */ 2666 if (ctl_min & ~ctl) 2667 return -EIO; 2668 2669 *result = ctl; 2670 return 0; 2671 } 2672 2673 static u64 adjust_vmx_controls64(u64 ctl_opt, u32 msr) 2674 { 2675 u64 allowed; 2676 2677 rdmsrq(msr, allowed); 2678 2679 return ctl_opt & allowed; 2680 } 2681 2682 #define vmx_check_entry_exit_pairs(pairs, entry_controls, exit_controls) \ 2683 ({ \ 2684 int i, r = 0; \ 2685 \ 2686 BUILD_BUG_ON(sizeof(pairs[0].entry_control) != sizeof(entry_controls)); \ 2687 BUILD_BUG_ON(sizeof(pairs[0].exit_control) != sizeof(exit_controls)); \ 2688 \ 2689 for (i = 0; i < ARRAY_SIZE(pairs); i++) { \ 2690 typeof(entry_controls) n_ctrl = pairs[i].entry_control; \ 2691 typeof(exit_controls) x_ctrl = pairs[i].exit_control; \ 2692 \ 2693 if (!(entry_controls & n_ctrl) == !(exit_controls & x_ctrl)) \ 2694 continue; \ 2695 \ 2696 pr_warn_once("Inconsistent VM-Entry/VM-Exit pair, " \ 2697 "entry = %llx (%llx), exit = %llx (%llx)\n", \ 2698 (u64)(entry_controls & n_ctrl), (u64)n_ctrl, \ 2699 (u64)(exit_controls & x_ctrl), (u64)x_ctrl); \ 2700 \ 2701 if (error_on_inconsistent_vmcs_config) \ 2702 r = -EIO; \ 2703 \ 2704 entry_controls &= ~n_ctrl; \ 2705 exit_controls &= ~x_ctrl; \ 2706 } \ 2707 r; \ 2708 }) 2709 2710 static int setup_vmcs_config(struct vmcs_config *vmcs_conf, 2711 struct vmx_capability *vmx_cap) 2712 { 2713 u32 _pin_based_exec_control = 0; 2714 u32 _cpu_based_exec_control = 0; 2715 u32 _cpu_based_2nd_exec_control = 0; 2716 u64 _cpu_based_3rd_exec_control = 0; 2717 u32 _vmexit_control = 0; 2718 u32 _vmentry_control = 0; 2719 u64 basic_msr; 2720 u64 misc_msr; 2721 2722 /* 2723 * LOAD/SAVE_DEBUG_CONTROLS are absent because both are mandatory. 2724 * SAVE_IA32_PAT and SAVE_IA32_EFER are absent because KVM always 2725 * intercepts writes to PAT and EFER, i.e. never enables those controls. 2726 */ 2727 struct { 2728 u32 entry_control; 2729 u32 exit_control; 2730 } const vmcs_entry_exit_pairs[] = { 2731 { VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL }, 2732 { VM_ENTRY_LOAD_IA32_PAT, VM_EXIT_LOAD_IA32_PAT }, 2733 { VM_ENTRY_LOAD_IA32_EFER, VM_EXIT_LOAD_IA32_EFER }, 2734 { VM_ENTRY_LOAD_BNDCFGS, VM_EXIT_CLEAR_BNDCFGS }, 2735 { VM_ENTRY_LOAD_IA32_RTIT_CTL, VM_EXIT_CLEAR_IA32_RTIT_CTL }, 2736 { VM_ENTRY_LOAD_CET_STATE, VM_EXIT_LOAD_CET_STATE }, 2737 }; 2738 2739 memset(vmcs_conf, 0, sizeof(*vmcs_conf)); 2740 2741 if (adjust_vmx_controls(KVM_REQUIRED_VMX_CPU_BASED_VM_EXEC_CONTROL, 2742 KVM_OPTIONAL_VMX_CPU_BASED_VM_EXEC_CONTROL, 2743 MSR_IA32_VMX_PROCBASED_CTLS, 2744 &_cpu_based_exec_control)) 2745 return -EIO; 2746 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) { 2747 if (adjust_vmx_controls(KVM_REQUIRED_VMX_SECONDARY_VM_EXEC_CONTROL, 2748 KVM_OPTIONAL_VMX_SECONDARY_VM_EXEC_CONTROL, 2749 MSR_IA32_VMX_PROCBASED_CTLS2, 2750 &_cpu_based_2nd_exec_control)) 2751 return -EIO; 2752 } 2753 if (!IS_ENABLED(CONFIG_KVM_INTEL_PROVE_VE)) 2754 _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_EPT_VIOLATION_VE; 2755 2756 #ifndef CONFIG_X86_64 2757 if (!(_cpu_based_2nd_exec_control & 2758 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) 2759 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW; 2760 #endif 2761 2762 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW)) 2763 _cpu_based_2nd_exec_control &= ~( 2764 SECONDARY_EXEC_APIC_REGISTER_VIRT | 2765 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE | 2766 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY); 2767 2768 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP, 2769 &vmx_cap->ept, &vmx_cap->vpid); 2770 2771 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) && 2772 vmx_cap->ept) { 2773 pr_warn_once("EPT CAP should not exist if not support " 2774 "1-setting enable EPT VM-execution control\n"); 2775 2776 if (error_on_inconsistent_vmcs_config) 2777 return -EIO; 2778 2779 vmx_cap->ept = 0; 2780 _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_EPT_VIOLATION_VE; 2781 } 2782 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) && 2783 vmx_cap->vpid) { 2784 pr_warn_once("VPID CAP should not exist if not support " 2785 "1-setting enable VPID VM-execution control\n"); 2786 2787 if (error_on_inconsistent_vmcs_config) 2788 return -EIO; 2789 2790 vmx_cap->vpid = 0; 2791 } 2792 2793 if (!cpu_has_sgx()) 2794 _cpu_based_2nd_exec_control &= ~SECONDARY_EXEC_ENCLS_EXITING; 2795 2796 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_TERTIARY_CONTROLS) 2797 _cpu_based_3rd_exec_control = 2798 adjust_vmx_controls64(KVM_OPTIONAL_VMX_TERTIARY_VM_EXEC_CONTROL, 2799 MSR_IA32_VMX_PROCBASED_CTLS3); 2800 2801 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_EXIT_CONTROLS, 2802 KVM_OPTIONAL_VMX_VM_EXIT_CONTROLS, 2803 MSR_IA32_VMX_EXIT_CTLS, 2804 &_vmexit_control)) 2805 return -EIO; 2806 2807 if (adjust_vmx_controls(KVM_REQUIRED_VMX_PIN_BASED_VM_EXEC_CONTROL, 2808 KVM_OPTIONAL_VMX_PIN_BASED_VM_EXEC_CONTROL, 2809 MSR_IA32_VMX_PINBASED_CTLS, 2810 &_pin_based_exec_control)) 2811 return -EIO; 2812 2813 if (cpu_has_broken_vmx_preemption_timer()) 2814 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER; 2815 if (!(_cpu_based_2nd_exec_control & 2816 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)) 2817 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR; 2818 2819 if (adjust_vmx_controls(KVM_REQUIRED_VMX_VM_ENTRY_CONTROLS, 2820 KVM_OPTIONAL_VMX_VM_ENTRY_CONTROLS, 2821 MSR_IA32_VMX_ENTRY_CTLS, 2822 &_vmentry_control)) 2823 return -EIO; 2824 2825 if (vmx_check_entry_exit_pairs(vmcs_entry_exit_pairs, 2826 _vmentry_control, _vmexit_control)) 2827 return -EIO; 2828 2829 /* 2830 * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they 2831 * can't be used due to an errata where VM Exit may incorrectly clear 2832 * IA32_PERF_GLOBAL_CTRL[34:32]. Workaround the errata by using the 2833 * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL. 2834 */ 2835 switch (boot_cpu_data.x86_vfm) { 2836 case INTEL_NEHALEM_EP: /* AAK155 */ 2837 case INTEL_NEHALEM: /* AAP115 */ 2838 case INTEL_WESTMERE: /* AAT100 */ 2839 case INTEL_WESTMERE_EP: /* BC86,AAY89,BD102 */ 2840 case INTEL_NEHALEM_EX: /* BA97 */ 2841 _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL; 2842 _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL; 2843 pr_warn_once("VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL " 2844 "does not work properly. Using workaround\n"); 2845 break; 2846 default: 2847 break; 2848 } 2849 2850 rdmsrq(MSR_IA32_VMX_BASIC, basic_msr); 2851 2852 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */ 2853 if (vmx_basic_vmcs_size(basic_msr) > PAGE_SIZE) 2854 return -EIO; 2855 2856 #ifdef CONFIG_X86_64 2857 /* 2858 * KVM expects to be able to shove all legal physical addresses into 2859 * VMCS fields for 64-bit kernels, and per the SDM, "This bit is always 2860 * 0 for processors that support Intel 64 architecture". 2861 */ 2862 if (basic_msr & VMX_BASIC_32BIT_PHYS_ADDR_ONLY) 2863 return -EIO; 2864 #endif 2865 2866 /* Require Write-Back (WB) memory type for VMCS accesses. */ 2867 if (vmx_basic_vmcs_mem_type(basic_msr) != X86_MEMTYPE_WB) 2868 return -EIO; 2869 2870 rdmsrq(MSR_IA32_VMX_MISC, misc_msr); 2871 2872 vmcs_conf->basic = basic_msr; 2873 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control; 2874 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control; 2875 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control; 2876 vmcs_conf->cpu_based_3rd_exec_ctrl = _cpu_based_3rd_exec_control; 2877 vmcs_conf->vmexit_ctrl = _vmexit_control; 2878 vmcs_conf->vmentry_ctrl = _vmentry_control; 2879 vmcs_conf->misc = misc_msr; 2880 2881 #if IS_ENABLED(CONFIG_HYPERV) 2882 if (enlightened_vmcs) 2883 evmcs_sanitize_exec_ctrls(vmcs_conf); 2884 #endif 2885 2886 return 0; 2887 } 2888 2889 static bool __kvm_is_vmx_supported(void) 2890 { 2891 int cpu = smp_processor_id(); 2892 2893 if (!(cpuid_ecx(1) & feature_bit(VMX))) { 2894 pr_err("VMX not supported by CPU %d\n", cpu); 2895 return false; 2896 } 2897 2898 if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL)) { 2899 pr_err("VMX not enabled (by BIOS) in MSR_IA32_FEAT_CTL on CPU %d\n", cpu); 2900 return false; 2901 } 2902 2903 if (!this_cpu_has(X86_FEATURE_VMX)) { 2904 pr_err("VMX not fully enabled on CPU %d. Check kernel logs and/or BIOS\n", cpu); 2905 return false; 2906 } 2907 2908 return true; 2909 } 2910 2911 static bool kvm_is_vmx_supported(void) 2912 { 2913 bool supported; 2914 2915 migrate_disable(); 2916 supported = __kvm_is_vmx_supported(); 2917 migrate_enable(); 2918 2919 return supported; 2920 } 2921 2922 int vmx_check_processor_compat(void) 2923 { 2924 int cpu = raw_smp_processor_id(); 2925 struct vmcs_config vmcs_conf; 2926 struct vmx_capability vmx_cap; 2927 2928 if (!__kvm_is_vmx_supported()) 2929 return -EIO; 2930 2931 if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0) { 2932 pr_err("Failed to setup VMCS config on CPU %d\n", cpu); 2933 return -EIO; 2934 } 2935 if (nested) 2936 nested_vmx_setup_ctls_msrs(&vmcs_conf, vmx_cap.ept); 2937 2938 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config))) { 2939 u32 *gold = (void *)&vmcs_config; 2940 u32 *mine = (void *)&vmcs_conf; 2941 int i; 2942 2943 BUILD_BUG_ON(sizeof(struct vmcs_config) % sizeof(u32)); 2944 2945 pr_err("VMCS config on CPU %d doesn't match reference config:", cpu); 2946 for (i = 0; i < sizeof(struct vmcs_config) / sizeof(u32); i++) { 2947 if (gold[i] == mine[i]) 2948 continue; 2949 2950 pr_cont("\n Offset %u REF = 0x%08x, CPU%u = 0x%08x, mismatch = 0x%08x", 2951 i * (int)sizeof(u32), gold[i], cpu, mine[i], gold[i] ^ mine[i]); 2952 } 2953 pr_cont("\n"); 2954 return -EIO; 2955 } 2956 return 0; 2957 } 2958 2959 int vmx_enable_virtualization_cpu(void) 2960 { 2961 int cpu = raw_smp_processor_id(); 2962 2963 /* 2964 * This can happen if we hot-added a CPU but failed to allocate 2965 * VP assist page for it. 2966 */ 2967 if (kvm_is_using_evmcs() && !hv_get_vp_assist_page(cpu)) 2968 return -EFAULT; 2969 2970 return x86_virt_get_ref(X86_FEATURE_VMX); 2971 } 2972 2973 static void vmclear_local_loaded_vmcss(void) 2974 { 2975 int cpu = raw_smp_processor_id(); 2976 struct loaded_vmcs *v, *n; 2977 2978 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu), 2979 loaded_vmcss_on_cpu_link) 2980 __loaded_vmcs_clear(v); 2981 } 2982 2983 void vmx_disable_virtualization_cpu(void) 2984 { 2985 vmclear_local_loaded_vmcss(); 2986 2987 x86_virt_put_ref(X86_FEATURE_VMX); 2988 2989 hv_reset_evmcs(); 2990 } 2991 2992 struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags) 2993 { 2994 int node = cpu_to_node(cpu); 2995 struct page *pages; 2996 struct vmcs *vmcs; 2997 2998 pages = __alloc_pages_node(node, flags, 0); 2999 if (!pages) 3000 return NULL; 3001 vmcs = page_address(pages); 3002 memset(vmcs, 0, vmx_basic_vmcs_size(vmcs_config.basic)); 3003 3004 /* KVM supports Enlightened VMCS v1 only */ 3005 if (kvm_is_using_evmcs()) 3006 vmcs->hdr.revision_id = KVM_EVMCS_VERSION; 3007 else 3008 vmcs->hdr.revision_id = vmx_basic_vmcs_revision_id(vmcs_config.basic); 3009 3010 if (shadow) 3011 vmcs->hdr.shadow_vmcs = 1; 3012 return vmcs; 3013 } 3014 3015 void free_vmcs(struct vmcs *vmcs) 3016 { 3017 free_page((unsigned long)vmcs); 3018 } 3019 3020 /* 3021 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded 3022 */ 3023 void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs) 3024 { 3025 if (!loaded_vmcs->vmcs) 3026 return; 3027 loaded_vmcs_clear(loaded_vmcs); 3028 free_vmcs(loaded_vmcs->vmcs); 3029 loaded_vmcs->vmcs = NULL; 3030 if (loaded_vmcs->msr_bitmap) 3031 free_page((unsigned long)loaded_vmcs->msr_bitmap); 3032 WARN_ON(loaded_vmcs->shadow_vmcs != NULL); 3033 } 3034 3035 int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs) 3036 { 3037 loaded_vmcs->vmcs = alloc_vmcs(false); 3038 if (!loaded_vmcs->vmcs) 3039 return -ENOMEM; 3040 3041 vmcs_clear(loaded_vmcs->vmcs); 3042 3043 loaded_vmcs->shadow_vmcs = NULL; 3044 loaded_vmcs->hv_timer_soft_disabled = false; 3045 loaded_vmcs->cpu = -1; 3046 loaded_vmcs->launched = 0; 3047 3048 if (cpu_has_vmx_msr_bitmap()) { 3049 loaded_vmcs->msr_bitmap = (unsigned long *) 3050 __get_free_page(GFP_KERNEL_ACCOUNT); 3051 if (!loaded_vmcs->msr_bitmap) 3052 goto out_vmcs; 3053 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE); 3054 } 3055 3056 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state)); 3057 memset(&loaded_vmcs->controls_shadow, 0, 3058 sizeof(struct vmcs_controls_shadow)); 3059 3060 return 0; 3061 3062 out_vmcs: 3063 free_loaded_vmcs(loaded_vmcs); 3064 return -ENOMEM; 3065 } 3066 3067 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg, 3068 struct kvm_segment *save) 3069 { 3070 if (!emulate_invalid_guest_state) { 3071 /* 3072 * CS and SS RPL should be equal during guest entry according 3073 * to VMX spec, but in reality it is not always so. Since vcpu 3074 * is in the middle of the transition from real mode to 3075 * protected mode it is safe to assume that RPL 0 is a good 3076 * default value. 3077 */ 3078 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS) 3079 save->selector &= ~SEGMENT_RPL_MASK; 3080 save->dpl = save->selector & SEGMENT_RPL_MASK; 3081 save->s = 1; 3082 } 3083 __vmx_set_segment(vcpu, save, seg); 3084 } 3085 3086 static void enter_pmode(struct kvm_vcpu *vcpu) 3087 { 3088 unsigned long flags; 3089 struct vcpu_vmx *vmx = to_vmx(vcpu); 3090 3091 /* 3092 * Update real mode segment cache. It may be not up-to-date if segment 3093 * register was written while vcpu was in a guest mode. 3094 */ 3095 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES); 3096 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS); 3097 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS); 3098 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS); 3099 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS); 3100 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS); 3101 3102 vmx->rmode.vm86_active = 0; 3103 3104 __vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR); 3105 3106 flags = vmcs_readl(GUEST_RFLAGS); 3107 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS; 3108 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS; 3109 vmcs_writel(GUEST_RFLAGS, flags); 3110 3111 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) | 3112 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME)); 3113 3114 vmx_update_exception_bitmap(vcpu); 3115 3116 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]); 3117 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]); 3118 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]); 3119 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]); 3120 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]); 3121 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]); 3122 } 3123 3124 static void fix_rmode_seg(int seg, struct kvm_segment *save) 3125 { 3126 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg]; 3127 struct kvm_segment var = *save; 3128 3129 var.dpl = 0x3; 3130 if (seg == VCPU_SREG_CS) 3131 var.type = 0x3; 3132 3133 if (!emulate_invalid_guest_state) { 3134 var.selector = var.base >> 4; 3135 var.base = var.base & 0xffff0; 3136 var.limit = 0xffff; 3137 var.g = 0; 3138 var.db = 0; 3139 var.present = 1; 3140 var.s = 1; 3141 var.l = 0; 3142 var.unusable = 0; 3143 var.type = 0x3; 3144 var.avl = 0; 3145 if (save->base & 0xf) 3146 pr_warn_once("segment base is not paragraph aligned " 3147 "when entering protected mode (seg=%d)", seg); 3148 } 3149 3150 vmcs_write16(sf->selector, var.selector); 3151 vmcs_writel(sf->base, var.base); 3152 vmcs_write32(sf->limit, var.limit); 3153 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var)); 3154 } 3155 3156 static void enter_rmode(struct kvm_vcpu *vcpu) 3157 { 3158 unsigned long flags; 3159 struct vcpu_vmx *vmx = to_vmx(vcpu); 3160 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm); 3161 3162 /* 3163 * KVM should never use VM86 to virtualize Real Mode when L2 is active, 3164 * as using VM86 is unnecessary if unrestricted guest is enabled, and 3165 * if unrestricted guest is disabled, VM-Enter (from L1) with CR0.PG=0 3166 * should VM-Fail and KVM should reject userspace attempts to stuff 3167 * CR0.PG=0 when L2 is active. 3168 */ 3169 WARN_ON_ONCE(is_guest_mode(vcpu)); 3170 3171 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR); 3172 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES); 3173 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS); 3174 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS); 3175 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS); 3176 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS); 3177 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS); 3178 3179 vmx->rmode.vm86_active = 1; 3180 3181 vmx_segment_cache_clear(vmx); 3182 3183 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr); 3184 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1); 3185 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b); 3186 3187 flags = vmcs_readl(GUEST_RFLAGS); 3188 vmx->rmode.save_rflags = flags; 3189 3190 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM; 3191 3192 vmcs_writel(GUEST_RFLAGS, flags); 3193 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME); 3194 vmx_update_exception_bitmap(vcpu); 3195 3196 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]); 3197 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]); 3198 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]); 3199 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]); 3200 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]); 3201 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]); 3202 } 3203 3204 int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer) 3205 { 3206 struct vcpu_vmx *vmx = to_vmx(vcpu); 3207 3208 /* Nothing to do if hardware doesn't support EFER. */ 3209 if (!vmx_find_uret_msr(vmx, MSR_EFER)) 3210 return 0; 3211 3212 vcpu->arch.efer = efer; 3213 #ifdef CONFIG_X86_64 3214 if (efer & EFER_LMA) 3215 vm_entry_controls_setbit(vmx, VM_ENTRY_IA32E_MODE); 3216 else 3217 vm_entry_controls_clearbit(vmx, VM_ENTRY_IA32E_MODE); 3218 #else 3219 if (KVM_BUG_ON(efer & EFER_LMA, vcpu->kvm)) 3220 return 1; 3221 #endif 3222 3223 vmx_setup_uret_msrs(vmx); 3224 return 0; 3225 } 3226 3227 #ifdef CONFIG_X86_64 3228 3229 static void enter_lmode(struct kvm_vcpu *vcpu) 3230 { 3231 u32 guest_tr_ar; 3232 3233 vmx_segment_cache_clear(to_vmx(vcpu)); 3234 3235 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES); 3236 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) { 3237 pr_debug_ratelimited("%s: tss fixup for long mode. \n", 3238 __func__); 3239 vmcs_write32(GUEST_TR_AR_BYTES, 3240 (guest_tr_ar & ~VMX_AR_TYPE_MASK) 3241 | VMX_AR_TYPE_BUSY_64_TSS); 3242 } 3243 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA); 3244 } 3245 3246 static void exit_lmode(struct kvm_vcpu *vcpu) 3247 { 3248 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA); 3249 } 3250 3251 #endif 3252 3253 void vmx_flush_tlb_all(struct kvm_vcpu *vcpu) 3254 { 3255 struct vcpu_vmx *vmx = to_vmx(vcpu); 3256 3257 /* 3258 * INVEPT must be issued when EPT is enabled, irrespective of VPID, as 3259 * the CPU is not required to invalidate guest-physical mappings on 3260 * VM-Entry, even if VPID is disabled. Guest-physical mappings are 3261 * associated with the root EPT structure and not any particular VPID 3262 * (INVVPID also isn't required to invalidate guest-physical mappings). 3263 */ 3264 if (enable_ept) { 3265 ept_sync_global(); 3266 } else if (enable_vpid) { 3267 if (cpu_has_vmx_invvpid_global()) { 3268 vpid_sync_vcpu_global(); 3269 } else { 3270 vpid_sync_vcpu_single(vmx->vpid); 3271 vpid_sync_vcpu_single(vmx->nested.vpid02); 3272 } 3273 } 3274 } 3275 3276 static inline int vmx_get_current_vpid(struct kvm_vcpu *vcpu) 3277 { 3278 if (is_guest_mode(vcpu) && nested_cpu_has_vpid(get_vmcs12(vcpu))) 3279 return nested_get_vpid02(vcpu); 3280 return to_vmx(vcpu)->vpid; 3281 } 3282 3283 static u64 construct_eptp(hpa_t root_hpa) 3284 { 3285 u64 eptp = root_hpa | VMX_EPTP_MT_WB; 3286 struct kvm_mmu_page *root; 3287 3288 if (kvm_mmu_is_dummy_root(root_hpa)) 3289 return eptp | VMX_EPTP_PWL_4; 3290 3291 /* 3292 * EPT roots should always have an associated MMU page. Return a "bad" 3293 * EPTP to induce VM-Fail instead of continuing on in a unknown state. 3294 */ 3295 root = root_to_sp(root_hpa); 3296 if (WARN_ON_ONCE(!root)) 3297 return INVALID_PAGE; 3298 3299 eptp |= (root->role.level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4; 3300 3301 if (enable_ept_ad_bits && !root->role.ad_disabled) 3302 eptp |= VMX_EPTP_AD_ENABLE_BIT; 3303 3304 return eptp; 3305 } 3306 3307 static void vmx_flush_tlb_ept_root(hpa_t root_hpa) 3308 { 3309 u64 eptp = construct_eptp(root_hpa); 3310 3311 if (VALID_PAGE(eptp)) 3312 ept_sync_context(eptp); 3313 else 3314 ept_sync_global(); 3315 } 3316 3317 void vmx_flush_tlb_current(struct kvm_vcpu *vcpu) 3318 { 3319 struct kvm_mmu *mmu = vcpu->arch.mmu; 3320 u64 root_hpa = mmu->root.hpa; 3321 3322 /* No flush required if the current context is invalid. */ 3323 if (!VALID_PAGE(root_hpa)) 3324 return; 3325 3326 if (enable_ept) 3327 vmx_flush_tlb_ept_root(root_hpa); 3328 else 3329 vpid_sync_context(vmx_get_current_vpid(vcpu)); 3330 } 3331 3332 void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr) 3333 { 3334 /* 3335 * vpid_sync_vcpu_addr() is a nop if vpid==0, see the comment in 3336 * vmx_flush_tlb_guest() for an explanation of why this is ok. 3337 */ 3338 vpid_sync_vcpu_addr(vmx_get_current_vpid(vcpu), addr); 3339 } 3340 3341 void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu) 3342 { 3343 /* 3344 * vpid_sync_context() is a nop if vpid==0, e.g. if enable_vpid==0 or a 3345 * vpid couldn't be allocated for this vCPU. VM-Enter and VM-Exit are 3346 * required to flush GVA->{G,H}PA mappings from the TLB if vpid is 3347 * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed), 3348 * i.e. no explicit INVVPID is necessary. 3349 */ 3350 vpid_sync_context(vmx_get_current_vpid(vcpu)); 3351 } 3352 3353 void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu) 3354 { 3355 struct kvm_mmu *mmu = vcpu->arch.walk_mmu; 3356 3357 if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR)) 3358 return; 3359 3360 if (is_pae_paging(vcpu)) { 3361 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]); 3362 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]); 3363 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]); 3364 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]); 3365 } 3366 } 3367 3368 void ept_save_pdptrs(struct kvm_vcpu *vcpu) 3369 { 3370 struct kvm_mmu *mmu = vcpu->arch.walk_mmu; 3371 3372 if (WARN_ON_ONCE(!is_pae_paging(vcpu))) 3373 return; 3374 3375 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0); 3376 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1); 3377 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2); 3378 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3); 3379 3380 kvm_register_mark_available(vcpu, VCPU_EXREG_PDPTR); 3381 } 3382 3383 #define CR3_EXITING_BITS (CPU_BASED_CR3_LOAD_EXITING | \ 3384 CPU_BASED_CR3_STORE_EXITING) 3385 3386 bool vmx_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0) 3387 { 3388 if (is_guest_mode(vcpu)) 3389 return nested_guest_cr0_valid(vcpu, cr0); 3390 3391 if (to_vmx(vcpu)->nested.vmxon) 3392 return nested_host_cr0_valid(vcpu, cr0); 3393 3394 return true; 3395 } 3396 3397 void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0) 3398 { 3399 struct vcpu_vmx *vmx = to_vmx(vcpu); 3400 unsigned long hw_cr0, old_cr0_pg; 3401 u32 tmp; 3402 3403 old_cr0_pg = kvm_read_cr0_bits(vcpu, X86_CR0_PG); 3404 3405 hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF); 3406 if (enable_unrestricted_guest) 3407 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST; 3408 else { 3409 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON; 3410 if (!enable_ept) 3411 hw_cr0 |= X86_CR0_WP; 3412 3413 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE)) 3414 enter_pmode(vcpu); 3415 3416 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE)) 3417 enter_rmode(vcpu); 3418 } 3419 3420 vmcs_writel(CR0_READ_SHADOW, cr0); 3421 vmcs_writel(GUEST_CR0, hw_cr0); 3422 vcpu->arch.cr0 = cr0; 3423 kvm_register_mark_available(vcpu, VCPU_EXREG_CR0); 3424 3425 #ifdef CONFIG_X86_64 3426 if (vcpu->arch.efer & EFER_LME) { 3427 if (!old_cr0_pg && (cr0 & X86_CR0_PG)) 3428 enter_lmode(vcpu); 3429 else if (old_cr0_pg && !(cr0 & X86_CR0_PG)) 3430 exit_lmode(vcpu); 3431 } 3432 #endif 3433 3434 if (enable_ept && !enable_unrestricted_guest) { 3435 /* 3436 * Ensure KVM has an up-to-date snapshot of the guest's CR3. If 3437 * the below code _enables_ CR3 exiting, vmx_cache_reg() will 3438 * (correctly) stop reading vmcs.GUEST_CR3 because it thinks 3439 * KVM's CR3 is installed. 3440 */ 3441 if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3)) 3442 vmx_cache_reg(vcpu, VCPU_EXREG_CR3); 3443 3444 /* 3445 * When running with EPT but not unrestricted guest, KVM must 3446 * intercept CR3 accesses when paging is _disabled_. This is 3447 * necessary because restricted guests can't actually run with 3448 * paging disabled, and so KVM stuffs its own CR3 in order to 3449 * run the guest when identity mapped page tables. 3450 * 3451 * Do _NOT_ check the old CR0.PG, e.g. to optimize away the 3452 * update, it may be stale with respect to CR3 interception, 3453 * e.g. after nested VM-Enter. 3454 * 3455 * Lastly, honor L1's desires, i.e. intercept CR3 loads and/or 3456 * stores to forward them to L1, even if KVM does not need to 3457 * intercept them to preserve its identity mapped page tables. 3458 */ 3459 if (!(cr0 & X86_CR0_PG)) { 3460 exec_controls_setbit(vmx, CR3_EXITING_BITS); 3461 } else if (!is_guest_mode(vcpu)) { 3462 exec_controls_clearbit(vmx, CR3_EXITING_BITS); 3463 } else { 3464 tmp = exec_controls_get(vmx); 3465 tmp &= ~CR3_EXITING_BITS; 3466 tmp |= get_vmcs12(vcpu)->cpu_based_vm_exec_control & CR3_EXITING_BITS; 3467 exec_controls_set(vmx, tmp); 3468 } 3469 3470 /* Note, vmx_set_cr4() consumes the new vcpu->arch.cr0. */ 3471 if ((old_cr0_pg ^ cr0) & X86_CR0_PG) 3472 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu)); 3473 3474 /* 3475 * When !CR0_PG -> CR0_PG, vcpu->arch.cr3 becomes active, but 3476 * GUEST_CR3 is still vmx->ept_identity_map_addr if EPT + !URG. 3477 */ 3478 if (!(old_cr0_pg & X86_CR0_PG) && (cr0 & X86_CR0_PG)) 3479 kvm_register_mark_dirty(vcpu, VCPU_EXREG_CR3); 3480 } 3481 3482 /* depends on vcpu->arch.cr0 to be set to a new value */ 3483 vmx->vt.emulation_required = vmx_emulation_required(vcpu); 3484 } 3485 3486 static int vmx_get_max_ept_level(void) 3487 { 3488 if (cpu_has_vmx_ept_5levels()) 3489 return 5; 3490 return 4; 3491 } 3492 3493 void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level) 3494 { 3495 struct kvm *kvm = vcpu->kvm; 3496 bool update_guest_cr3 = true; 3497 unsigned long guest_cr3; 3498 3499 if (enable_ept) { 3500 KVM_MMU_WARN_ON(root_to_sp(root_hpa) && 3501 root_level != root_to_sp(root_hpa)->role.level); 3502 vmcs_write64(EPT_POINTER, construct_eptp(root_hpa)); 3503 3504 hv_track_root_tdp(vcpu, root_hpa); 3505 3506 if (!enable_unrestricted_guest && !is_paging(vcpu)) 3507 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr; 3508 else if (kvm_register_is_dirty(vcpu, VCPU_EXREG_CR3)) 3509 guest_cr3 = vcpu->arch.cr3; 3510 else /* vmcs.GUEST_CR3 is already up-to-date. */ 3511 update_guest_cr3 = false; 3512 vmx_ept_load_pdptrs(vcpu); 3513 } else { 3514 guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu) | 3515 kvm_get_active_cr3_lam_bits(vcpu); 3516 } 3517 3518 if (update_guest_cr3) 3519 vmcs_writel(GUEST_CR3, guest_cr3); 3520 } 3521 3522 bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4) 3523 { 3524 /* 3525 * We operate under the default treatment of SMM, so VMX cannot be 3526 * enabled under SMM. Note, whether or not VMXE is allowed at all, 3527 * i.e. is a reserved bit, is handled by common x86 code. 3528 */ 3529 if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu)) 3530 return false; 3531 3532 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4)) 3533 return false; 3534 3535 return true; 3536 } 3537 3538 void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4) 3539 { 3540 unsigned long old_cr4 = kvm_read_cr4(vcpu); 3541 struct vcpu_vmx *vmx = to_vmx(vcpu); 3542 unsigned long hw_cr4; 3543 3544 /* 3545 * Pass through host's Machine Check Enable value to hw_cr4, which 3546 * is in force while we are in guest mode. Do not let guests control 3547 * this bit, even if host CR4.MCE == 0. 3548 */ 3549 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE); 3550 if (enable_unrestricted_guest) 3551 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST; 3552 else if (vmx->rmode.vm86_active) 3553 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON; 3554 else 3555 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON; 3556 3557 if (vmx_umip_emulated()) { 3558 if (cr4 & X86_CR4_UMIP) { 3559 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC); 3560 hw_cr4 &= ~X86_CR4_UMIP; 3561 } else if (!is_guest_mode(vcpu) || 3562 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) { 3563 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC); 3564 } 3565 } 3566 3567 vcpu->arch.cr4 = cr4; 3568 kvm_register_mark_available(vcpu, VCPU_EXREG_CR4); 3569 3570 if (!enable_unrestricted_guest) { 3571 if (enable_ept) { 3572 if (!is_paging(vcpu)) { 3573 hw_cr4 &= ~X86_CR4_PAE; 3574 hw_cr4 |= X86_CR4_PSE; 3575 } else if (!(cr4 & X86_CR4_PAE)) { 3576 hw_cr4 &= ~X86_CR4_PAE; 3577 } 3578 } 3579 3580 /* 3581 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in 3582 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs 3583 * to be manually disabled when guest switches to non-paging 3584 * mode. 3585 * 3586 * If !enable_unrestricted_guest, the CPU is always running 3587 * with CR0.PG=1 and CR4 needs to be modified. 3588 * If enable_unrestricted_guest, the CPU automatically 3589 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0. 3590 */ 3591 if (!is_paging(vcpu)) 3592 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE); 3593 } 3594 3595 vmcs_writel(CR4_READ_SHADOW, cr4); 3596 vmcs_writel(GUEST_CR4, hw_cr4); 3597 3598 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE)) 3599 vcpu->arch.cpuid_dynamic_bits_dirty = true; 3600 } 3601 3602 void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg) 3603 { 3604 struct vcpu_vmx *vmx = to_vmx(vcpu); 3605 u32 ar; 3606 3607 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) { 3608 *var = vmx->rmode.segs[seg]; 3609 if (seg == VCPU_SREG_TR 3610 || var->selector == vmx_read_guest_seg_selector(vmx, seg)) 3611 return; 3612 var->base = vmx_read_guest_seg_base(vmx, seg); 3613 var->selector = vmx_read_guest_seg_selector(vmx, seg); 3614 return; 3615 } 3616 var->base = vmx_read_guest_seg_base(vmx, seg); 3617 var->limit = vmx_read_guest_seg_limit(vmx, seg); 3618 var->selector = vmx_read_guest_seg_selector(vmx, seg); 3619 ar = vmx_read_guest_seg_ar(vmx, seg); 3620 var->unusable = (ar >> 16) & 1; 3621 var->type = ar & 15; 3622 var->s = (ar >> 4) & 1; 3623 var->dpl = (ar >> 5) & 3; 3624 /* 3625 * Some userspaces do not preserve unusable property. Since usable 3626 * segment has to be present according to VMX spec we can use present 3627 * property to amend userspace bug by making unusable segment always 3628 * nonpresent. vmx_segment_access_rights() already marks nonpresent 3629 * segment as unusable. 3630 */ 3631 var->present = !var->unusable; 3632 var->avl = (ar >> 12) & 1; 3633 var->l = (ar >> 13) & 1; 3634 var->db = (ar >> 14) & 1; 3635 var->g = (ar >> 15) & 1; 3636 } 3637 3638 u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg) 3639 { 3640 struct kvm_segment s; 3641 3642 if (to_vmx(vcpu)->rmode.vm86_active) { 3643 vmx_get_segment(vcpu, &s, seg); 3644 return s.base; 3645 } 3646 return vmx_read_guest_seg_base(to_vmx(vcpu), seg); 3647 } 3648 3649 static int __vmx_get_cpl(struct kvm_vcpu *vcpu, bool no_cache) 3650 { 3651 struct vcpu_vmx *vmx = to_vmx(vcpu); 3652 int ar; 3653 3654 if (unlikely(vmx->rmode.vm86_active)) 3655 return 0; 3656 3657 if (no_cache) 3658 ar = vmcs_read32(GUEST_SS_AR_BYTES); 3659 else 3660 ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS); 3661 return VMX_AR_DPL(ar); 3662 } 3663 3664 int vmx_get_cpl(struct kvm_vcpu *vcpu) 3665 { 3666 return __vmx_get_cpl(vcpu, false); 3667 } 3668 3669 int vmx_get_cpl_no_cache(struct kvm_vcpu *vcpu) 3670 { 3671 return __vmx_get_cpl(vcpu, true); 3672 } 3673 3674 static u32 vmx_segment_access_rights(struct kvm_segment *var) 3675 { 3676 u32 ar; 3677 3678 ar = var->type & 15; 3679 ar |= (var->s & 1) << 4; 3680 ar |= (var->dpl & 3) << 5; 3681 ar |= (var->present & 1) << 7; 3682 ar |= (var->avl & 1) << 12; 3683 ar |= (var->l & 1) << 13; 3684 ar |= (var->db & 1) << 14; 3685 ar |= (var->g & 1) << 15; 3686 ar |= (var->unusable || !var->present) << 16; 3687 3688 return ar; 3689 } 3690 3691 void __vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg) 3692 { 3693 struct vcpu_vmx *vmx = to_vmx(vcpu); 3694 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg]; 3695 3696 vmx_segment_cache_clear(vmx); 3697 3698 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) { 3699 vmx->rmode.segs[seg] = *var; 3700 if (seg == VCPU_SREG_TR) 3701 vmcs_write16(sf->selector, var->selector); 3702 else if (var->s) 3703 fix_rmode_seg(seg, &vmx->rmode.segs[seg]); 3704 return; 3705 } 3706 3707 vmcs_writel(sf->base, var->base); 3708 vmcs_write32(sf->limit, var->limit); 3709 vmcs_write16(sf->selector, var->selector); 3710 3711 /* 3712 * Fix the "Accessed" bit in AR field of segment registers for older 3713 * qemu binaries. 3714 * IA32 arch specifies that at the time of processor reset the 3715 * "Accessed" bit in the AR field of segment registers is 1. And qemu 3716 * is setting it to 0 in the userland code. This causes invalid guest 3717 * state vmexit when "unrestricted guest" mode is turned on. 3718 * Fix for this setup issue in cpu_reset is being pushed in the qemu 3719 * tree. Newer qemu binaries with that qemu fix would not need this 3720 * kvm hack. 3721 */ 3722 if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR)) 3723 var->type |= 0x1; /* Accessed */ 3724 3725 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var)); 3726 } 3727 3728 void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg) 3729 { 3730 __vmx_set_segment(vcpu, var, seg); 3731 3732 to_vmx(vcpu)->vt.emulation_required = vmx_emulation_required(vcpu); 3733 } 3734 3735 void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l) 3736 { 3737 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS); 3738 3739 *db = (ar >> 14) & 1; 3740 *l = (ar >> 13) & 1; 3741 } 3742 3743 void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt) 3744 { 3745 dt->size = vmcs_read32(GUEST_IDTR_LIMIT); 3746 dt->address = vmcs_readl(GUEST_IDTR_BASE); 3747 } 3748 3749 void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt) 3750 { 3751 vmcs_write32(GUEST_IDTR_LIMIT, dt->size); 3752 vmcs_writel(GUEST_IDTR_BASE, dt->address); 3753 } 3754 3755 void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt) 3756 { 3757 dt->size = vmcs_read32(GUEST_GDTR_LIMIT); 3758 dt->address = vmcs_readl(GUEST_GDTR_BASE); 3759 } 3760 3761 void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt) 3762 { 3763 vmcs_write32(GUEST_GDTR_LIMIT, dt->size); 3764 vmcs_writel(GUEST_GDTR_BASE, dt->address); 3765 } 3766 3767 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg) 3768 { 3769 struct kvm_segment var; 3770 u32 ar; 3771 3772 vmx_get_segment(vcpu, &var, seg); 3773 var.dpl = 0x3; 3774 if (seg == VCPU_SREG_CS) 3775 var.type = 0x3; 3776 ar = vmx_segment_access_rights(&var); 3777 3778 if (var.base != (var.selector << 4)) 3779 return false; 3780 if (var.limit != 0xffff) 3781 return false; 3782 if (ar != 0xf3) 3783 return false; 3784 3785 return true; 3786 } 3787 3788 static bool code_segment_valid(struct kvm_vcpu *vcpu) 3789 { 3790 struct kvm_segment cs; 3791 unsigned int cs_rpl; 3792 3793 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS); 3794 cs_rpl = cs.selector & SEGMENT_RPL_MASK; 3795 3796 if (cs.unusable) 3797 return false; 3798 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK)) 3799 return false; 3800 if (!cs.s) 3801 return false; 3802 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) { 3803 if (cs.dpl > cs_rpl) 3804 return false; 3805 } else { 3806 if (cs.dpl != cs_rpl) 3807 return false; 3808 } 3809 if (!cs.present) 3810 return false; 3811 3812 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */ 3813 return true; 3814 } 3815 3816 static bool stack_segment_valid(struct kvm_vcpu *vcpu) 3817 { 3818 struct kvm_segment ss; 3819 unsigned int ss_rpl; 3820 3821 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS); 3822 ss_rpl = ss.selector & SEGMENT_RPL_MASK; 3823 3824 if (ss.unusable) 3825 return true; 3826 if (ss.type != 3 && ss.type != 7) 3827 return false; 3828 if (!ss.s) 3829 return false; 3830 if (ss.dpl != ss_rpl) /* DPL != RPL */ 3831 return false; 3832 if (!ss.present) 3833 return false; 3834 3835 return true; 3836 } 3837 3838 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg) 3839 { 3840 struct kvm_segment var; 3841 unsigned int rpl; 3842 3843 vmx_get_segment(vcpu, &var, seg); 3844 rpl = var.selector & SEGMENT_RPL_MASK; 3845 3846 if (var.unusable) 3847 return true; 3848 if (!var.s) 3849 return false; 3850 if (!var.present) 3851 return false; 3852 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) { 3853 if (var.dpl < rpl) /* DPL < RPL */ 3854 return false; 3855 } 3856 3857 /* TODO: Add other members to kvm_segment_field to allow checking for other access 3858 * rights flags 3859 */ 3860 return true; 3861 } 3862 3863 static bool tr_valid(struct kvm_vcpu *vcpu) 3864 { 3865 struct kvm_segment tr; 3866 3867 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR); 3868 3869 if (tr.unusable) 3870 return false; 3871 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */ 3872 return false; 3873 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */ 3874 return false; 3875 if (!tr.present) 3876 return false; 3877 3878 return true; 3879 } 3880 3881 static bool ldtr_valid(struct kvm_vcpu *vcpu) 3882 { 3883 struct kvm_segment ldtr; 3884 3885 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR); 3886 3887 if (ldtr.unusable) 3888 return true; 3889 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */ 3890 return false; 3891 if (ldtr.type != 2) 3892 return false; 3893 if (!ldtr.present) 3894 return false; 3895 3896 return true; 3897 } 3898 3899 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu) 3900 { 3901 struct kvm_segment cs, ss; 3902 3903 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS); 3904 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS); 3905 3906 return ((cs.selector & SEGMENT_RPL_MASK) == 3907 (ss.selector & SEGMENT_RPL_MASK)); 3908 } 3909 3910 /* 3911 * Check if guest state is valid. Returns true if valid, false if 3912 * not. 3913 * We assume that registers are always usable 3914 */ 3915 bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu) 3916 { 3917 /* real mode guest state checks */ 3918 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) { 3919 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS)) 3920 return false; 3921 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS)) 3922 return false; 3923 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS)) 3924 return false; 3925 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES)) 3926 return false; 3927 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS)) 3928 return false; 3929 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS)) 3930 return false; 3931 } else { 3932 /* protected mode guest state checks */ 3933 if (!cs_ss_rpl_check(vcpu)) 3934 return false; 3935 if (!code_segment_valid(vcpu)) 3936 return false; 3937 if (!stack_segment_valid(vcpu)) 3938 return false; 3939 if (!data_segment_valid(vcpu, VCPU_SREG_DS)) 3940 return false; 3941 if (!data_segment_valid(vcpu, VCPU_SREG_ES)) 3942 return false; 3943 if (!data_segment_valid(vcpu, VCPU_SREG_FS)) 3944 return false; 3945 if (!data_segment_valid(vcpu, VCPU_SREG_GS)) 3946 return false; 3947 if (!tr_valid(vcpu)) 3948 return false; 3949 if (!ldtr_valid(vcpu)) 3950 return false; 3951 } 3952 /* TODO: 3953 * - Add checks on RIP 3954 * - Add checks on RFLAGS 3955 */ 3956 3957 return true; 3958 } 3959 3960 static int init_rmode_tss(struct kvm *kvm, void __user *ua) 3961 { 3962 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0))); 3963 u16 data; 3964 int i; 3965 3966 for (i = 0; i < 3; i++) { 3967 if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE)) 3968 return -EFAULT; 3969 } 3970 3971 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE; 3972 if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16))) 3973 return -EFAULT; 3974 3975 data = ~0; 3976 if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8))) 3977 return -EFAULT; 3978 3979 return 0; 3980 } 3981 3982 static int init_rmode_identity_map(struct kvm *kvm) 3983 { 3984 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm); 3985 int i, r = 0; 3986 void __user *uaddr; 3987 u32 tmp; 3988 3989 /* Protect kvm_vmx->ept_identity_pagetable_done. */ 3990 mutex_lock(&kvm->slots_lock); 3991 3992 if (likely(kvm_vmx->ept_identity_pagetable_done)) 3993 goto out; 3994 3995 if (!kvm_vmx->ept_identity_map_addr) 3996 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR; 3997 3998 uaddr = __x86_set_memory_region(kvm, 3999 IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 4000 kvm_vmx->ept_identity_map_addr, 4001 PAGE_SIZE); 4002 if (IS_ERR(uaddr)) { 4003 r = PTR_ERR(uaddr); 4004 goto out; 4005 } 4006 4007 /* Set up identity-mapping pagetable for EPT in real mode */ 4008 for (i = 0; i < (PAGE_SIZE / sizeof(tmp)); i++) { 4009 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER | 4010 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE); 4011 if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) { 4012 r = -EFAULT; 4013 goto out; 4014 } 4015 } 4016 kvm_vmx->ept_identity_pagetable_done = true; 4017 4018 out: 4019 mutex_unlock(&kvm->slots_lock); 4020 return r; 4021 } 4022 4023 static void seg_setup(int seg) 4024 { 4025 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg]; 4026 unsigned int ar; 4027 4028 vmcs_write16(sf->selector, 0); 4029 vmcs_writel(sf->base, 0); 4030 vmcs_write32(sf->limit, 0xffff); 4031 ar = 0x93; 4032 if (seg == VCPU_SREG_CS) 4033 ar |= 0x08; /* code segment */ 4034 4035 vmcs_write32(sf->ar_bytes, ar); 4036 } 4037 4038 int allocate_vpid(void) 4039 { 4040 int vpid; 4041 4042 if (!enable_vpid) 4043 return 0; 4044 spin_lock(&vmx_vpid_lock); 4045 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS); 4046 if (vpid < VMX_NR_VPIDS) 4047 __set_bit(vpid, vmx_vpid_bitmap); 4048 else 4049 vpid = 0; 4050 spin_unlock(&vmx_vpid_lock); 4051 return vpid; 4052 } 4053 4054 void free_vpid(int vpid) 4055 { 4056 if (!enable_vpid || vpid == 0) 4057 return; 4058 spin_lock(&vmx_vpid_lock); 4059 __clear_bit(vpid, vmx_vpid_bitmap); 4060 spin_unlock(&vmx_vpid_lock); 4061 } 4062 4063 static void vmx_msr_bitmap_l01_changed(struct vcpu_vmx *vmx) 4064 { 4065 /* 4066 * When KVM is a nested hypervisor on top of Hyper-V and uses 4067 * 'Enlightened MSR Bitmap' feature L0 needs to know that MSR 4068 * bitmap has changed. 4069 */ 4070 if (kvm_is_using_evmcs()) { 4071 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs; 4072 4073 if (evmcs->hv_enlightenments_control.msr_bitmap) 4074 evmcs->hv_clean_fields &= 4075 ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP; 4076 } 4077 4078 vmx->nested.force_msr_bitmap_recalc = true; 4079 } 4080 4081 void vmx_set_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type, bool set) 4082 { 4083 struct vcpu_vmx *vmx = to_vmx(vcpu); 4084 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap; 4085 4086 if (!cpu_has_vmx_msr_bitmap()) 4087 return; 4088 4089 vmx_msr_bitmap_l01_changed(vmx); 4090 4091 if (type & MSR_TYPE_R) { 4092 if (!set && kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) 4093 vmx_clear_msr_bitmap_read(msr_bitmap, msr); 4094 else 4095 vmx_set_msr_bitmap_read(msr_bitmap, msr); 4096 } 4097 4098 if (type & MSR_TYPE_W) { 4099 if (!set && kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) 4100 vmx_clear_msr_bitmap_write(msr_bitmap, msr); 4101 else 4102 vmx_set_msr_bitmap_write(msr_bitmap, msr); 4103 } 4104 } 4105 4106 static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu) 4107 { 4108 /* 4109 * x2APIC indices for 64-bit accesses into the RDMSR and WRMSR halves 4110 * of the MSR bitmap. KVM emulates APIC registers up through 0x3f0, 4111 * i.e. MSR 0x83f, and so only needs to dynamically manipulate 64 bits. 4112 */ 4113 const int read_idx = APIC_BASE_MSR / BITS_PER_LONG_LONG; 4114 const int write_idx = read_idx + (0x800 / sizeof(u64)); 4115 struct vcpu_vmx *vmx = to_vmx(vcpu); 4116 u64 *msr_bitmap = (u64 *)vmx->vmcs01.msr_bitmap; 4117 u8 mode; 4118 4119 if (!cpu_has_vmx_msr_bitmap() || WARN_ON_ONCE(!lapic_in_kernel(vcpu))) 4120 return; 4121 4122 if (cpu_has_secondary_exec_ctrls() && 4123 (secondary_exec_controls_get(vmx) & 4124 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) { 4125 mode = MSR_BITMAP_MODE_X2APIC; 4126 if (enable_apicv && kvm_vcpu_apicv_active(vcpu)) 4127 mode |= MSR_BITMAP_MODE_X2APIC_APICV; 4128 } else { 4129 mode = 0; 4130 } 4131 4132 if (mode == vmx->x2apic_msr_bitmap_mode) 4133 return; 4134 4135 vmx->x2apic_msr_bitmap_mode = mode; 4136 4137 /* 4138 * Reset the bitmap for MSRs 0x800 - 0x83f. Leave AMD's uber-extended 4139 * registers (0x840 and above) intercepted, KVM doesn't support them. 4140 * Intercept all writes by default and poke holes as needed. Pass 4141 * through reads for all valid registers by default in x2APIC+APICv 4142 * mode, only the current timer count needs on-demand emulation by KVM. 4143 */ 4144 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) 4145 msr_bitmap[read_idx] = ~kvm_lapic_readable_reg_mask(vcpu->arch.apic); 4146 else 4147 msr_bitmap[read_idx] = ~0ull; 4148 msr_bitmap[write_idx] = ~0ull; 4149 4150 /* 4151 * TPR reads and writes can be virtualized even if virtual interrupt 4152 * delivery is not in use. 4153 */ 4154 vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW, 4155 !(mode & MSR_BITMAP_MODE_X2APIC)); 4156 4157 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) { 4158 vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW); 4159 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W); 4160 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W); 4161 if (enable_ipiv) 4162 vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_ICR), MSR_TYPE_RW); 4163 } 4164 } 4165 4166 void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu) 4167 { 4168 struct vcpu_vmx *vmx = to_vmx(vcpu); 4169 bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN); 4170 u32 i; 4171 4172 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag); 4173 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag); 4174 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag); 4175 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag); 4176 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++) { 4177 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag); 4178 vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag); 4179 } 4180 } 4181 4182 static void vmx_recalc_pmu_msr_intercepts(struct kvm_vcpu *vcpu) 4183 { 4184 u64 vm_exit_controls_bits = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | 4185 VM_EXIT_SAVE_IA32_PERF_GLOBAL_CTRL; 4186 bool has_mediated_pmu = kvm_vcpu_has_mediated_pmu(vcpu); 4187 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu); 4188 struct vcpu_vmx *vmx = to_vmx(vcpu); 4189 bool intercept = !has_mediated_pmu; 4190 int i; 4191 4192 if (!enable_mediated_pmu) 4193 return; 4194 4195 if (!cpu_has_save_perf_global_ctrl()) { 4196 vm_exit_controls_bits &= ~VM_EXIT_SAVE_IA32_PERF_GLOBAL_CTRL; 4197 4198 if (has_mediated_pmu) 4199 vmx_add_autostore_msr(vmx, MSR_CORE_PERF_GLOBAL_CTRL); 4200 else 4201 vmx_remove_autostore_msr(vmx, MSR_CORE_PERF_GLOBAL_CTRL); 4202 } 4203 4204 vm_entry_controls_changebit(vmx, VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL, 4205 has_mediated_pmu); 4206 4207 vm_exit_controls_changebit(vmx, vm_exit_controls_bits, has_mediated_pmu); 4208 4209 for (i = 0; i < pmu->nr_arch_gp_counters; i++) { 4210 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PERFCTR0 + i, 4211 MSR_TYPE_RW, intercept); 4212 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PMC0 + i, MSR_TYPE_RW, 4213 intercept || !fw_writes_is_enabled(vcpu)); 4214 } 4215 for ( ; i < kvm_pmu_cap.num_counters_gp; i++) { 4216 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PERFCTR0 + i, 4217 MSR_TYPE_RW, true); 4218 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PMC0 + i, 4219 MSR_TYPE_RW, true); 4220 } 4221 4222 for (i = 0; i < pmu->nr_arch_fixed_counters; i++) 4223 vmx_set_intercept_for_msr(vcpu, MSR_CORE_PERF_FIXED_CTR0 + i, 4224 MSR_TYPE_RW, intercept); 4225 for ( ; i < kvm_pmu_cap.num_counters_fixed; i++) 4226 vmx_set_intercept_for_msr(vcpu, MSR_CORE_PERF_FIXED_CTR0 + i, 4227 MSR_TYPE_RW, true); 4228 4229 intercept = kvm_need_perf_global_ctrl_intercept(vcpu); 4230 vmx_set_intercept_for_msr(vcpu, MSR_CORE_PERF_GLOBAL_STATUS, 4231 MSR_TYPE_RW, intercept); 4232 vmx_set_intercept_for_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL, 4233 MSR_TYPE_RW, intercept); 4234 vmx_set_intercept_for_msr(vcpu, MSR_CORE_PERF_GLOBAL_OVF_CTRL, 4235 MSR_TYPE_RW, intercept); 4236 } 4237 4238 static void vmx_recalc_msr_intercepts(struct kvm_vcpu *vcpu) 4239 { 4240 bool intercept; 4241 4242 if (!cpu_has_vmx_msr_bitmap()) 4243 return; 4244 4245 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R); 4246 #ifdef CONFIG_X86_64 4247 vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW); 4248 vmx_disable_intercept_for_msr(vcpu, MSR_GS_BASE, MSR_TYPE_RW); 4249 vmx_disable_intercept_for_msr(vcpu, MSR_KERNEL_GS_BASE, MSR_TYPE_RW); 4250 #endif 4251 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW); 4252 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW); 4253 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW); 4254 if (kvm_cstate_in_guest(vcpu->kvm)) { 4255 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C1_RES, MSR_TYPE_R); 4256 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R); 4257 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R); 4258 vmx_disable_intercept_for_msr(vcpu, MSR_CORE_C7_RESIDENCY, MSR_TYPE_R); 4259 } 4260 if (kvm_aperfmperf_in_guest(vcpu->kvm)) { 4261 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_APERF, MSR_TYPE_R); 4262 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_MPERF, MSR_TYPE_R); 4263 } 4264 4265 /* PT MSRs can be passed through iff PT is exposed to the guest. */ 4266 if (vmx_pt_mode_is_host_guest()) 4267 pt_update_intercept_for_msr(vcpu); 4268 4269 if (vcpu->arch.xfd_no_write_intercept) 4270 vmx_disable_intercept_for_msr(vcpu, MSR_IA32_XFD, MSR_TYPE_RW); 4271 4272 vmx_set_intercept_for_msr(vcpu, MSR_IA32_SPEC_CTRL, MSR_TYPE_RW, 4273 !to_vmx(vcpu)->spec_ctrl); 4274 4275 if (kvm_cpu_cap_has(X86_FEATURE_XFD)) 4276 vmx_set_intercept_for_msr(vcpu, MSR_IA32_XFD_ERR, MSR_TYPE_R, 4277 !guest_cpu_cap_has(vcpu, X86_FEATURE_XFD)); 4278 4279 if (cpu_feature_enabled(X86_FEATURE_IBPB)) 4280 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W, 4281 !guest_has_pred_cmd_msr(vcpu)); 4282 4283 if (cpu_feature_enabled(X86_FEATURE_FLUSH_L1D)) 4284 vmx_set_intercept_for_msr(vcpu, MSR_IA32_FLUSH_CMD, MSR_TYPE_W, 4285 !guest_cpu_cap_has(vcpu, X86_FEATURE_FLUSH_L1D)); 4286 4287 if (kvm_cpu_cap_has(X86_FEATURE_SHSTK)) { 4288 intercept = !guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK); 4289 4290 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PL0_SSP, MSR_TYPE_RW, intercept); 4291 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PL1_SSP, MSR_TYPE_RW, intercept); 4292 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PL2_SSP, MSR_TYPE_RW, intercept); 4293 vmx_set_intercept_for_msr(vcpu, MSR_IA32_PL3_SSP, MSR_TYPE_RW, intercept); 4294 } 4295 4296 if (kvm_cpu_cap_has(X86_FEATURE_SHSTK) || kvm_cpu_cap_has(X86_FEATURE_IBT)) { 4297 intercept = !guest_cpu_cap_has(vcpu, X86_FEATURE_IBT) && 4298 !guest_cpu_cap_has(vcpu, X86_FEATURE_SHSTK); 4299 4300 vmx_set_intercept_for_msr(vcpu, MSR_IA32_U_CET, MSR_TYPE_RW, intercept); 4301 vmx_set_intercept_for_msr(vcpu, MSR_IA32_S_CET, MSR_TYPE_RW, intercept); 4302 } 4303 4304 vmx_recalc_pmu_msr_intercepts(vcpu); 4305 4306 /* 4307 * x2APIC and LBR MSR intercepts are modified on-demand and cannot be 4308 * filtered by userspace. 4309 */ 4310 } 4311 4312 static void vmx_recalc_instruction_intercepts(struct kvm_vcpu *vcpu) 4313 { 4314 exec_controls_changebit(to_vmx(vcpu), CPU_BASED_RDPMC_EXITING, 4315 kvm_need_rdpmc_intercept(vcpu)); 4316 } 4317 4318 void vmx_recalc_intercepts(struct kvm_vcpu *vcpu) 4319 { 4320 vmx_recalc_instruction_intercepts(vcpu); 4321 vmx_recalc_msr_intercepts(vcpu); 4322 } 4323 4324 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu, 4325 int vector) 4326 { 4327 struct vcpu_vmx *vmx = to_vmx(vcpu); 4328 4329 /* 4330 * DO NOT query the vCPU's vmcs12, as vmcs12 is dynamically allocated 4331 * and freed, and must not be accessed outside of vcpu->mutex. The 4332 * vCPU's cached PI NV is valid if and only if posted interrupts 4333 * enabled in its vmcs12, i.e. checking the vector also checks that 4334 * L1 has enabled posted interrupts for L2. 4335 */ 4336 if (is_guest_mode(vcpu) && 4337 vector == vmx->nested.posted_intr_nv) { 4338 /* 4339 * If a posted intr is not recognized by hardware, 4340 * we will accomplish it in the next vmentry. 4341 */ 4342 vmx->nested.pi_pending = true; 4343 kvm_make_request(KVM_REQ_EVENT, vcpu); 4344 4345 /* 4346 * This pairs with the smp_mb_*() after setting vcpu->mode in 4347 * vcpu_enter_guest() to guarantee the vCPU sees the event 4348 * request if triggering a posted interrupt "fails" because 4349 * vcpu->mode != IN_GUEST_MODE. The extra barrier is needed as 4350 * the smb_wmb() in kvm_make_request() only ensures everything 4351 * done before making the request is visible when the request 4352 * is visible, it doesn't ensure ordering between the store to 4353 * vcpu->requests and the load from vcpu->mode. 4354 */ 4355 smp_mb__after_atomic(); 4356 4357 /* the PIR and ON have been set by L1. */ 4358 kvm_vcpu_trigger_posted_interrupt(vcpu, POSTED_INTR_NESTED_VECTOR); 4359 return 0; 4360 } 4361 return -1; 4362 } 4363 /* 4364 * Send interrupt to vcpu via posted interrupt way. 4365 * 1. If target vcpu is running(non-root mode), send posted interrupt 4366 * notification to vcpu and hardware will sync PIR to vIRR atomically. 4367 * 2. If target vcpu isn't running(root mode), kick it to pick up the 4368 * interrupt from PIR in next vmentry. 4369 */ 4370 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector) 4371 { 4372 struct vcpu_vt *vt = to_vt(vcpu); 4373 int r; 4374 4375 r = vmx_deliver_nested_posted_interrupt(vcpu, vector); 4376 if (!r) 4377 return 0; 4378 4379 /* Note, this is called iff the local APIC is in-kernel. */ 4380 if (!vcpu->arch.apic->apicv_active) 4381 return -1; 4382 4383 __vmx_deliver_posted_interrupt(vcpu, &vt->pi_desc, vector); 4384 return 0; 4385 } 4386 4387 void vmx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode, 4388 int trig_mode, int vector) 4389 { 4390 struct kvm_vcpu *vcpu = apic->vcpu; 4391 4392 if (vmx_deliver_posted_interrupt(vcpu, vector)) { 4393 kvm_lapic_set_irr(vector, apic); 4394 kvm_make_request(KVM_REQ_EVENT, vcpu); 4395 kvm_vcpu_kick(vcpu); 4396 } else { 4397 trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode, 4398 trig_mode, vector); 4399 } 4400 } 4401 4402 /* 4403 * Set up the vmcs's constant host-state fields, i.e., host-state fields that 4404 * will not change in the lifetime of the guest. 4405 * Note that host-state that does change is set elsewhere. E.g., host-state 4406 * that is set differently for each CPU is set in vmx_vcpu_load(), not here. 4407 */ 4408 void vmx_set_constant_host_state(struct vcpu_vmx *vmx) 4409 { 4410 u32 low32, high32; 4411 unsigned long tmpl; 4412 unsigned long cr0, cr3, cr4; 4413 4414 cr0 = read_cr0(); 4415 WARN_ON(cr0 & X86_CR0_TS); 4416 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */ 4417 4418 /* 4419 * Save the most likely value for this task's CR3 in the VMCS. 4420 * We can't use __get_current_cr3_fast() because we're not atomic. 4421 */ 4422 cr3 = __read_cr3(); 4423 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */ 4424 vmx->loaded_vmcs->host_state.cr3 = cr3; 4425 4426 /* Save the most likely value for this task's CR4 in the VMCS. */ 4427 cr4 = cr4_read_shadow(); 4428 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */ 4429 vmx->loaded_vmcs->host_state.cr4 = cr4; 4430 4431 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */ 4432 #ifdef CONFIG_X86_64 4433 /* 4434 * Load null selectors, so we can avoid reloading them in 4435 * vmx_prepare_switch_to_host(), in case userspace uses 4436 * the null selectors too (the expected case). 4437 */ 4438 vmcs_write16(HOST_DS_SELECTOR, 0); 4439 vmcs_write16(HOST_ES_SELECTOR, 0); 4440 #else 4441 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ 4442 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */ 4443 #endif 4444 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */ 4445 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */ 4446 4447 vmcs_writel(HOST_IDTR_BASE, host_idt_base); /* 22.2.4 */ 4448 4449 vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */ 4450 4451 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32); 4452 vmcs_write32(HOST_IA32_SYSENTER_CS, low32); 4453 4454 /* 4455 * SYSENTER is used for 32-bit system calls on either 32-bit or 4456 * 64-bit kernels. It is always zero If neither is allowed, otherwise 4457 * vmx_vcpu_load_vmcs loads it with the per-CPU entry stack (and may 4458 * have already done so!). 4459 */ 4460 if (!IS_ENABLED(CONFIG_IA32_EMULATION) && !IS_ENABLED(CONFIG_X86_32)) 4461 vmcs_writel(HOST_IA32_SYSENTER_ESP, 0); 4462 4463 rdmsrq(MSR_IA32_SYSENTER_EIP, tmpl); 4464 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */ 4465 4466 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) { 4467 rdmsr(MSR_IA32_CR_PAT, low32, high32); 4468 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32)); 4469 } 4470 4471 if (cpu_has_load_ia32_efer()) 4472 vmcs_write64(HOST_IA32_EFER, kvm_host.efer); 4473 4474 /* 4475 * Supervisor shadow stack is not enabled on host side, i.e., 4476 * host IA32_S_CET.SHSTK_EN bit is guaranteed to 0 now, per SDM 4477 * description(RDSSP instruction), SSP is not readable in CPL0, 4478 * so resetting the two registers to 0s at VM-Exit does no harm 4479 * to kernel execution. When execution flow exits to userspace, 4480 * SSP is reloaded from IA32_PL3_SSP. Check SDM Vol.2A/B Chapter 4481 * 3 and 4 for details. 4482 */ 4483 if (enable_cet) { 4484 vmcs_writel(HOST_S_CET, kvm_host.s_cet); 4485 vmcs_writel(HOST_SSP, 0); 4486 vmcs_writel(HOST_INTR_SSP_TABLE, 0); 4487 } 4488 4489 /* 4490 * When running a guest with a mediated PMU, guest state is resident in 4491 * hardware after VM-Exit. Zero PERF_GLOBAL_CTRL on exit so that host 4492 * activity doesn't bleed into the guest counters. When running with 4493 * an emulated PMU, PERF_GLOBAL_CTRL is dynamically computed on every 4494 * entry/exit to merge guest and host PMU usage. 4495 */ 4496 if (enable_mediated_pmu) 4497 vmcs_write64(HOST_IA32_PERF_GLOBAL_CTRL, 0); 4498 } 4499 4500 void set_cr4_guest_host_mask(struct vcpu_vmx *vmx) 4501 { 4502 struct kvm_vcpu *vcpu = &vmx->vcpu; 4503 4504 vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS & 4505 ~vcpu->arch.cr4_guest_rsvd_bits; 4506 if (!enable_ept) { 4507 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_TLBFLUSH_BITS; 4508 vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PDPTR_BITS; 4509 } 4510 if (is_guest_mode(&vmx->vcpu)) 4511 vcpu->arch.cr4_guest_owned_bits &= 4512 ~get_vmcs12(vcpu)->cr4_guest_host_mask; 4513 vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits); 4514 } 4515 4516 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx) 4517 { 4518 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl; 4519 4520 if (!kvm_vcpu_apicv_active(&vmx->vcpu)) 4521 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR; 4522 4523 if (!enable_vnmi) 4524 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS; 4525 4526 if (!enable_preemption_timer) 4527 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER; 4528 4529 return pin_based_exec_ctrl; 4530 } 4531 4532 static u32 vmx_get_initial_vmentry_ctrl(void) 4533 { 4534 u32 vmentry_ctrl = vmcs_config.vmentry_ctrl; 4535 4536 if (vmx_pt_mode_is_system()) 4537 vmentry_ctrl &= ~(VM_ENTRY_PT_CONCEAL_PIP | 4538 VM_ENTRY_LOAD_IA32_RTIT_CTL); 4539 4540 if (!enable_cet) 4541 vmentry_ctrl &= ~VM_ENTRY_LOAD_CET_STATE; 4542 4543 /* 4544 * IA32e mode, and loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically. 4545 */ 4546 vmentry_ctrl &= ~(VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL | 4547 VM_ENTRY_LOAD_IA32_EFER | 4548 VM_ENTRY_IA32E_MODE); 4549 4550 return vmentry_ctrl; 4551 } 4552 4553 static u32 vmx_get_initial_vmexit_ctrl(void) 4554 { 4555 u32 vmexit_ctrl = vmcs_config.vmexit_ctrl; 4556 4557 if (!enable_cet) 4558 vmexit_ctrl &= ~VM_EXIT_LOAD_CET_STATE; 4559 4560 /* 4561 * Not used by KVM and never set in vmcs01 or vmcs02, but emulated for 4562 * nested virtualization and thus allowed to be set in vmcs12. 4563 */ 4564 vmexit_ctrl &= ~(VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER | 4565 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER); 4566 4567 if (vmx_pt_mode_is_system()) 4568 vmexit_ctrl &= ~(VM_EXIT_PT_CONCEAL_PIP | 4569 VM_EXIT_CLEAR_IA32_RTIT_CTL); 4570 /* Loading of EFER and PERF_GLOBAL_CTRL are toggled dynamically */ 4571 return vmexit_ctrl & 4572 ~(VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL | VM_EXIT_LOAD_IA32_EFER | 4573 VM_EXIT_SAVE_IA32_PERF_GLOBAL_CTRL); 4574 } 4575 4576 void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu) 4577 { 4578 struct vcpu_vmx *vmx = to_vmx(vcpu); 4579 4580 guard(vmx_vmcs01)(vcpu); 4581 4582 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx)); 4583 4584 secondary_exec_controls_changebit(vmx, 4585 SECONDARY_EXEC_APIC_REGISTER_VIRT | 4586 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY, 4587 kvm_vcpu_apicv_active(vcpu)); 4588 if (enable_ipiv) 4589 tertiary_exec_controls_changebit(vmx, TERTIARY_EXEC_IPI_VIRT, 4590 kvm_vcpu_apicv_active(vcpu)); 4591 4592 vmx_update_msr_bitmap_x2apic(vcpu); 4593 } 4594 4595 static u32 vmx_exec_control(struct vcpu_vmx *vmx) 4596 { 4597 u32 exec_control = vmcs_config.cpu_based_exec_ctrl; 4598 4599 /* 4600 * Not used by KVM, but fully supported for nesting, i.e. are allowed in 4601 * vmcs12 and propagated to vmcs02 when set in vmcs12. 4602 */ 4603 exec_control &= ~(CPU_BASED_RDTSC_EXITING | 4604 CPU_BASED_USE_IO_BITMAPS | 4605 CPU_BASED_MONITOR_TRAP_FLAG | 4606 CPU_BASED_PAUSE_EXITING); 4607 4608 /* INTR_WINDOW_EXITING and NMI_WINDOW_EXITING are toggled dynamically */ 4609 exec_control &= ~(CPU_BASED_INTR_WINDOW_EXITING | 4610 CPU_BASED_NMI_WINDOW_EXITING); 4611 4612 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT) 4613 exec_control &= ~CPU_BASED_MOV_DR_EXITING; 4614 4615 if (!cpu_need_tpr_shadow(&vmx->vcpu)) 4616 exec_control &= ~CPU_BASED_TPR_SHADOW; 4617 4618 #ifdef CONFIG_X86_64 4619 if (exec_control & CPU_BASED_TPR_SHADOW) 4620 exec_control &= ~(CPU_BASED_CR8_LOAD_EXITING | 4621 CPU_BASED_CR8_STORE_EXITING); 4622 else 4623 exec_control |= CPU_BASED_CR8_STORE_EXITING | 4624 CPU_BASED_CR8_LOAD_EXITING; 4625 #endif 4626 /* No need to intercept CR3 access or INVPLG when using EPT. */ 4627 if (enable_ept) 4628 exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING | 4629 CPU_BASED_CR3_STORE_EXITING | 4630 CPU_BASED_INVLPG_EXITING); 4631 if (kvm_mwait_in_guest(vmx->vcpu.kvm)) 4632 exec_control &= ~(CPU_BASED_MWAIT_EXITING | 4633 CPU_BASED_MONITOR_EXITING); 4634 if (kvm_hlt_in_guest(vmx->vcpu.kvm)) 4635 exec_control &= ~CPU_BASED_HLT_EXITING; 4636 return exec_control; 4637 } 4638 4639 static u64 vmx_tertiary_exec_control(struct vcpu_vmx *vmx) 4640 { 4641 u64 exec_control = vmcs_config.cpu_based_3rd_exec_ctrl; 4642 4643 /* 4644 * IPI virtualization relies on APICv. Disable IPI virtualization if 4645 * APICv is inhibited. 4646 */ 4647 if (!enable_ipiv || !kvm_vcpu_apicv_active(&vmx->vcpu)) 4648 exec_control &= ~TERTIARY_EXEC_IPI_VIRT; 4649 4650 return exec_control; 4651 } 4652 4653 /* 4654 * Adjust a single secondary execution control bit to intercept/allow an 4655 * instruction in the guest. This is usually done based on whether or not a 4656 * feature has been exposed to the guest in order to correctly emulate faults. 4657 */ 4658 static inline void 4659 vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control, 4660 u32 control, bool enabled, bool exiting) 4661 { 4662 /* 4663 * If the control is for an opt-in feature, clear the control if the 4664 * feature is not exposed to the guest, i.e. not enabled. If the 4665 * control is opt-out, i.e. an exiting control, clear the control if 4666 * the feature _is_ exposed to the guest, i.e. exiting/interception is 4667 * disabled for the associated instruction. Note, the caller is 4668 * responsible presetting exec_control to set all supported bits. 4669 */ 4670 if (enabled == exiting) 4671 *exec_control &= ~control; 4672 4673 /* 4674 * Update the nested MSR settings so that a nested VMM can/can't set 4675 * controls for features that are/aren't exposed to the guest. 4676 */ 4677 if (nested && 4678 kvm_check_has_quirk(vmx->vcpu.kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) { 4679 /* 4680 * All features that can be added or removed to VMX MSRs must 4681 * be supported in the first place for nested virtualization. 4682 */ 4683 if (WARN_ON_ONCE(!(vmcs_config.nested.secondary_ctls_high & control))) 4684 enabled = false; 4685 4686 if (enabled) 4687 vmx->nested.msrs.secondary_ctls_high |= control; 4688 else 4689 vmx->nested.msrs.secondary_ctls_high &= ~control; 4690 } 4691 } 4692 4693 /* 4694 * Wrapper macro for the common case of adjusting a secondary execution control 4695 * based on a single guest CPUID bit, with a dedicated feature bit. This also 4696 * verifies that the control is actually supported by KVM and hardware. 4697 */ 4698 #define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \ 4699 ({ \ 4700 struct kvm_vcpu *__vcpu = &(vmx)->vcpu; \ 4701 bool __enabled; \ 4702 \ 4703 if (cpu_has_vmx_##name()) { \ 4704 __enabled = guest_cpu_cap_has(__vcpu, X86_FEATURE_##feat_name); \ 4705 vmx_adjust_secondary_exec_control(vmx, exec_control, SECONDARY_EXEC_##ctrl_name,\ 4706 __enabled, exiting); \ 4707 } \ 4708 }) 4709 4710 /* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */ 4711 #define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \ 4712 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false) 4713 4714 #define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \ 4715 vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true) 4716 4717 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx) 4718 { 4719 struct kvm_vcpu *vcpu = &vmx->vcpu; 4720 4721 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl; 4722 4723 if (vmx_pt_mode_is_system()) 4724 exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX); 4725 if (!cpu_need_virtualize_apic_accesses(vcpu)) 4726 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; 4727 if (vmx->vpid == 0) 4728 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID; 4729 if (!enable_ept) { 4730 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT; 4731 exec_control &= ~SECONDARY_EXEC_EPT_VIOLATION_VE; 4732 enable_unrestricted_guest = 0; 4733 } 4734 if (!enable_unrestricted_guest) 4735 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST; 4736 if (kvm_pause_in_guest(vmx->vcpu.kvm)) 4737 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING; 4738 if (!kvm_vcpu_apicv_active(vcpu)) 4739 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT | 4740 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY); 4741 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE; 4742 4743 /* 4744 * KVM doesn't support VMFUNC for L1, but the control is set in KVM's 4745 * base configuration as KVM emulates VMFUNC[EPTP_SWITCHING] for L2. 4746 */ 4747 exec_control &= ~SECONDARY_EXEC_ENABLE_VMFUNC; 4748 4749 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP, 4750 * in vmx_set_cr4. */ 4751 exec_control &= ~SECONDARY_EXEC_DESC; 4752 4753 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD 4754 (handle_vmptrld). 4755 We can NOT enable shadow_vmcs here because we don't have yet 4756 a current VMCS12 4757 */ 4758 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS; 4759 4760 /* 4761 * PML is enabled/disabled when dirty logging of memsmlots changes, but 4762 * it needs to be set here when dirty logging is already active, e.g. 4763 * if this vCPU was created after dirty logging was enabled. 4764 */ 4765 if (!enable_pml || !atomic_read(&vcpu->kvm->nr_memslots_dirty_logging)) 4766 exec_control &= ~SECONDARY_EXEC_ENABLE_PML; 4767 4768 vmx_adjust_sec_exec_feature(vmx, &exec_control, xsaves, XSAVES); 4769 4770 /* 4771 * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either 4772 * feature is exposed to the guest. This creates a virtualization hole 4773 * if both are supported in hardware but only one is exposed to the 4774 * guest, but letting the guest execute RDTSCP or RDPID when either one 4775 * is advertised is preferable to emulating the advertised instruction 4776 * in KVM on #UD, and obviously better than incorrectly injecting #UD. 4777 */ 4778 if (cpu_has_vmx_rdtscp()) { 4779 bool rdpid_or_rdtscp_enabled = 4780 guest_cpu_cap_has(vcpu, X86_FEATURE_RDTSCP) || 4781 guest_cpu_cap_has(vcpu, X86_FEATURE_RDPID); 4782 4783 vmx_adjust_secondary_exec_control(vmx, &exec_control, 4784 SECONDARY_EXEC_ENABLE_RDTSCP, 4785 rdpid_or_rdtscp_enabled, false); 4786 } 4787 4788 vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID); 4789 4790 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND); 4791 vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED); 4792 4793 vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG, 4794 ENABLE_USR_WAIT_PAUSE, false); 4795 4796 if (!vcpu->kvm->arch.bus_lock_detection_enabled) 4797 exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION; 4798 4799 if (!kvm_notify_vmexit_enabled(vcpu->kvm)) 4800 exec_control &= ~SECONDARY_EXEC_NOTIFY_VM_EXITING; 4801 4802 return exec_control; 4803 } 4804 4805 static inline int vmx_get_pid_table_order(struct kvm *kvm) 4806 { 4807 return get_order(kvm->arch.max_vcpu_ids * sizeof(*to_kvm_vmx(kvm)->pid_table)); 4808 } 4809 4810 static int vmx_alloc_ipiv_pid_table(struct kvm *kvm) 4811 { 4812 struct page *pages; 4813 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm); 4814 4815 if (!irqchip_in_kernel(kvm) || !enable_ipiv) 4816 return 0; 4817 4818 if (kvm_vmx->pid_table) 4819 return 0; 4820 4821 pages = alloc_pages(GFP_KERNEL_ACCOUNT | __GFP_ZERO, 4822 vmx_get_pid_table_order(kvm)); 4823 if (!pages) 4824 return -ENOMEM; 4825 4826 kvm_vmx->pid_table = (void *)page_address(pages); 4827 return 0; 4828 } 4829 4830 int vmx_vcpu_precreate(struct kvm *kvm) 4831 { 4832 return vmx_alloc_ipiv_pid_table(kvm); 4833 } 4834 4835 #define VMX_XSS_EXIT_BITMAP 0 4836 4837 static void init_vmcs(struct vcpu_vmx *vmx) 4838 { 4839 struct kvm *kvm = vmx->vcpu.kvm; 4840 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm); 4841 4842 if (nested) 4843 nested_vmx_set_vmcs_shadowing_bitmap(); 4844 4845 if (cpu_has_vmx_msr_bitmap()) 4846 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap)); 4847 4848 vmcs_write64(VMCS_LINK_POINTER, INVALID_GPA); /* 22.3.1.5 */ 4849 4850 /* Control */ 4851 pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx)); 4852 4853 exec_controls_set(vmx, vmx_exec_control(vmx)); 4854 4855 if (cpu_has_secondary_exec_ctrls()) { 4856 secondary_exec_controls_set(vmx, vmx_secondary_exec_control(vmx)); 4857 if (vmx->ve_info) 4858 vmcs_write64(VE_INFORMATION_ADDRESS, 4859 __pa(vmx->ve_info)); 4860 } 4861 4862 if (cpu_has_tertiary_exec_ctrls()) 4863 tertiary_exec_controls_set(vmx, vmx_tertiary_exec_control(vmx)); 4864 4865 if (enable_apicv && lapic_in_kernel(&vmx->vcpu)) { 4866 vmcs_write64(EOI_EXIT_BITMAP0, 0); 4867 vmcs_write64(EOI_EXIT_BITMAP1, 0); 4868 vmcs_write64(EOI_EXIT_BITMAP2, 0); 4869 vmcs_write64(EOI_EXIT_BITMAP3, 0); 4870 4871 vmcs_write16(GUEST_INTR_STATUS, 0); 4872 4873 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR); 4874 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->vt.pi_desc))); 4875 } 4876 4877 if (vmx_can_use_ipiv(&vmx->vcpu)) { 4878 vmcs_write64(PID_POINTER_TABLE, __pa(kvm_vmx->pid_table)); 4879 vmcs_write16(LAST_PID_POINTER_INDEX, kvm->arch.max_vcpu_ids - 1); 4880 } 4881 4882 if (!kvm_pause_in_guest(kvm)) { 4883 vmcs_write32(PLE_GAP, ple_gap); 4884 vmx->ple_window = ple_window; 4885 vmx->ple_window_dirty = true; 4886 } 4887 4888 if (kvm_notify_vmexit_enabled(kvm)) 4889 vmcs_write32(NOTIFY_WINDOW, kvm->arch.notify_window); 4890 4891 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0); 4892 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0); 4893 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */ 4894 4895 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */ 4896 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */ 4897 vmx_set_constant_host_state(vmx); 4898 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */ 4899 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */ 4900 4901 if (cpu_has_vmx_vmfunc()) 4902 vmcs_write64(VM_FUNCTION_CONTROL, 0); 4903 4904 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0); 4905 vmcs_write64(VM_EXIT_MSR_STORE_ADDR, __pa(vmx->msr_autostore.val)); 4906 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0); 4907 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val)); 4908 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0); 4909 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val)); 4910 4911 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) 4912 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat); 4913 4914 vm_exit_controls_set(vmx, vmx_get_initial_vmexit_ctrl()); 4915 4916 /* 22.2.1, 20.8.1 */ 4917 vm_entry_controls_set(vmx, vmx_get_initial_vmentry_ctrl()); 4918 4919 vmx->vcpu.arch.cr0_guest_owned_bits = vmx_l1_guest_owned_cr0_bits(); 4920 vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits); 4921 4922 set_cr4_guest_host_mask(vmx); 4923 4924 if (vmx->vpid != 0) 4925 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid); 4926 4927 if (cpu_has_vmx_xsaves()) 4928 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP); 4929 4930 if (enable_pml) { 4931 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg)); 4932 vmcs_write16(GUEST_PML_INDEX, PML_HEAD_INDEX); 4933 } 4934 4935 vmx_write_encls_bitmap(&vmx->vcpu, NULL); 4936 4937 if (vmx_pt_mode_is_host_guest()) { 4938 memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc)); 4939 /* Bit[6~0] are forced to 1, writes are ignored. */ 4940 vmx->pt_desc.guest.output_mask = 0x7F; 4941 vmcs_write64(GUEST_IA32_RTIT_CTL, 0); 4942 } 4943 4944 vmcs_write32(GUEST_SYSENTER_CS, 0); 4945 vmcs_writel(GUEST_SYSENTER_ESP, 0); 4946 vmcs_writel(GUEST_SYSENTER_EIP, 0); 4947 4948 vmx_guest_debugctl_write(&vmx->vcpu, 0); 4949 4950 if (cpu_has_vmx_tpr_shadow()) { 4951 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0); 4952 if (cpu_need_tpr_shadow(&vmx->vcpu)) 4953 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 4954 __pa(vmx->vcpu.arch.apic->regs)); 4955 vmcs_write32(TPR_THRESHOLD, 0); 4956 } 4957 4958 vmx_setup_uret_msrs(vmx); 4959 } 4960 4961 static void __vmx_vcpu_reset(struct kvm_vcpu *vcpu) 4962 { 4963 struct vcpu_vmx *vmx = to_vmx(vcpu); 4964 4965 init_vmcs(vmx); 4966 4967 if (nested && 4968 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) 4969 memcpy(&vmx->nested.msrs, &vmcs_config.nested, sizeof(vmx->nested.msrs)); 4970 4971 vcpu_setup_sgx_lepubkeyhash(vcpu); 4972 4973 vmx->nested.posted_intr_nv = -1; 4974 vmx->nested.vmxon_ptr = INVALID_GPA; 4975 vmx->nested.current_vmptr = INVALID_GPA; 4976 4977 #ifdef CONFIG_KVM_HYPERV 4978 vmx->nested.hv_evmcs_vmptr = EVMPTR_INVALID; 4979 #endif 4980 4981 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_STUFF_FEATURE_MSRS)) 4982 vcpu->arch.microcode_version = 0x100000000ULL; 4983 vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED; 4984 4985 /* 4986 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR 4987 * or POSTED_INTR_WAKEUP_VECTOR. 4988 */ 4989 vmx->vt.pi_desc.nv = POSTED_INTR_VECTOR; 4990 __pi_set_sn(&vmx->vt.pi_desc); 4991 } 4992 4993 void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) 4994 { 4995 struct vcpu_vmx *vmx = to_vmx(vcpu); 4996 4997 if (!init_event) 4998 __vmx_vcpu_reset(vcpu); 4999 5000 vmx->rmode.vm86_active = 0; 5001 vmx->spec_ctrl = 0; 5002 5003 vmx->msr_ia32_umwait_control = 0; 5004 5005 vmx->hv_deadline_tsc = -1; 5006 kvm_set_cr8(vcpu, 0); 5007 5008 seg_setup(VCPU_SREG_CS); 5009 vmcs_write16(GUEST_CS_SELECTOR, 0xf000); 5010 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul); 5011 5012 seg_setup(VCPU_SREG_DS); 5013 seg_setup(VCPU_SREG_ES); 5014 seg_setup(VCPU_SREG_FS); 5015 seg_setup(VCPU_SREG_GS); 5016 seg_setup(VCPU_SREG_SS); 5017 5018 vmcs_write16(GUEST_TR_SELECTOR, 0); 5019 vmcs_writel(GUEST_TR_BASE, 0); 5020 vmcs_write32(GUEST_TR_LIMIT, 0xffff); 5021 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b); 5022 5023 vmcs_write16(GUEST_LDTR_SELECTOR, 0); 5024 vmcs_writel(GUEST_LDTR_BASE, 0); 5025 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff); 5026 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082); 5027 5028 vmcs_writel(GUEST_GDTR_BASE, 0); 5029 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff); 5030 5031 vmcs_writel(GUEST_IDTR_BASE, 0); 5032 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff); 5033 5034 vmx_segment_cache_clear(vmx); 5035 kvm_register_mark_available(vcpu, VCPU_EXREG_SEGMENTS); 5036 5037 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE); 5038 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0); 5039 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0); 5040 if (kvm_mpx_supported()) 5041 vmcs_write64(GUEST_BNDCFGS, 0); 5042 5043 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */ 5044 5045 if (kvm_cpu_cap_has(X86_FEATURE_SHSTK)) { 5046 vmcs_writel(GUEST_SSP, 0); 5047 vmcs_writel(GUEST_INTR_SSP_TABLE, 0); 5048 } 5049 if (kvm_cpu_cap_has(X86_FEATURE_IBT) || 5050 kvm_cpu_cap_has(X86_FEATURE_SHSTK)) 5051 vmcs_writel(GUEST_S_CET, 0); 5052 5053 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu); 5054 5055 vpid_sync_context(vmx->vpid); 5056 5057 vmx_update_fb_clear_dis(vcpu, vmx); 5058 } 5059 5060 void vmx_enable_irq_window(struct kvm_vcpu *vcpu) 5061 { 5062 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING); 5063 } 5064 5065 void vmx_enable_nmi_window(struct kvm_vcpu *vcpu) 5066 { 5067 if (!enable_vnmi || 5068 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) { 5069 vmx_enable_irq_window(vcpu); 5070 return; 5071 } 5072 5073 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING); 5074 } 5075 5076 void vmx_inject_irq(struct kvm_vcpu *vcpu, bool reinjected) 5077 { 5078 struct vcpu_vmx *vmx = to_vmx(vcpu); 5079 uint32_t intr; 5080 int irq = vcpu->arch.interrupt.nr; 5081 5082 trace_kvm_inj_virq(irq, vcpu->arch.interrupt.soft, reinjected); 5083 5084 ++vcpu->stat.irq_injections; 5085 if (vmx->rmode.vm86_active) { 5086 int inc_eip = 0; 5087 if (vcpu->arch.interrupt.soft) 5088 inc_eip = vcpu->arch.event_exit_inst_len; 5089 kvm_inject_realmode_interrupt(vcpu, irq, inc_eip); 5090 return; 5091 } 5092 intr = irq | INTR_INFO_VALID_MASK; 5093 if (vcpu->arch.interrupt.soft) { 5094 intr |= INTR_TYPE_SOFT_INTR; 5095 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN, 5096 vmx->vcpu.arch.event_exit_inst_len); 5097 } else 5098 intr |= INTR_TYPE_EXT_INTR; 5099 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr); 5100 5101 vmx_clear_hlt(vcpu); 5102 } 5103 5104 void vmx_inject_nmi(struct kvm_vcpu *vcpu) 5105 { 5106 struct vcpu_vmx *vmx = to_vmx(vcpu); 5107 5108 if (!enable_vnmi) { 5109 /* 5110 * Tracking the NMI-blocked state in software is built upon 5111 * finding the next open IRQ window. This, in turn, depends on 5112 * well-behaving guests: They have to keep IRQs disabled at 5113 * least as long as the NMI handler runs. Otherwise we may 5114 * cause NMI nesting, maybe breaking the guest. But as this is 5115 * highly unlikely, we can live with the residual risk. 5116 */ 5117 vmx->loaded_vmcs->soft_vnmi_blocked = 1; 5118 vmx->loaded_vmcs->vnmi_blocked_time = 0; 5119 } 5120 5121 ++vcpu->stat.nmi_injections; 5122 vmx->loaded_vmcs->nmi_known_unmasked = false; 5123 5124 if (vmx->rmode.vm86_active) { 5125 kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0); 5126 return; 5127 } 5128 5129 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 5130 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR); 5131 5132 vmx_clear_hlt(vcpu); 5133 } 5134 5135 bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu) 5136 { 5137 struct vcpu_vmx *vmx = to_vmx(vcpu); 5138 bool masked; 5139 5140 if (!enable_vnmi) 5141 return vmx->loaded_vmcs->soft_vnmi_blocked; 5142 if (vmx->loaded_vmcs->nmi_known_unmasked) 5143 return false; 5144 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI; 5145 vmx->loaded_vmcs->nmi_known_unmasked = !masked; 5146 return masked; 5147 } 5148 5149 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked) 5150 { 5151 struct vcpu_vmx *vmx = to_vmx(vcpu); 5152 5153 if (!enable_vnmi) { 5154 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) { 5155 vmx->loaded_vmcs->soft_vnmi_blocked = masked; 5156 vmx->loaded_vmcs->vnmi_blocked_time = 0; 5157 } 5158 } else { 5159 vmx->loaded_vmcs->nmi_known_unmasked = !masked; 5160 if (masked) 5161 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, 5162 GUEST_INTR_STATE_NMI); 5163 else 5164 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO, 5165 GUEST_INTR_STATE_NMI); 5166 } 5167 } 5168 5169 bool vmx_nmi_blocked(struct kvm_vcpu *vcpu) 5170 { 5171 if (is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu)) 5172 return false; 5173 5174 if (!enable_vnmi && to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked) 5175 return true; 5176 5177 return (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & 5178 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI | 5179 GUEST_INTR_STATE_NMI)); 5180 } 5181 5182 int vmx_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection) 5183 { 5184 if (vcpu->arch.nested_run_pending) 5185 return -EBUSY; 5186 5187 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */ 5188 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(vcpu)) 5189 return -EBUSY; 5190 5191 return !vmx_nmi_blocked(vcpu); 5192 } 5193 5194 bool __vmx_interrupt_blocked(struct kvm_vcpu *vcpu) 5195 { 5196 return !(vmx_get_rflags(vcpu) & X86_EFLAGS_IF) || 5197 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & 5198 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS)); 5199 } 5200 5201 bool vmx_interrupt_blocked(struct kvm_vcpu *vcpu) 5202 { 5203 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu)) 5204 return false; 5205 5206 return __vmx_interrupt_blocked(vcpu); 5207 } 5208 5209 int vmx_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection) 5210 { 5211 if (vcpu->arch.nested_run_pending) 5212 return -EBUSY; 5213 5214 /* 5215 * An IRQ must not be injected into L2 if it's supposed to VM-Exit, 5216 * e.g. if the IRQ arrived asynchronously after checking nested events. 5217 */ 5218 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(vcpu)) 5219 return -EBUSY; 5220 5221 return !vmx_interrupt_blocked(vcpu); 5222 } 5223 5224 int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr) 5225 { 5226 void __user *ret; 5227 5228 if (enable_unrestricted_guest) 5229 return 0; 5230 5231 mutex_lock(&kvm->slots_lock); 5232 ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr, 5233 PAGE_SIZE * 3); 5234 mutex_unlock(&kvm->slots_lock); 5235 5236 if (IS_ERR(ret)) 5237 return PTR_ERR(ret); 5238 5239 to_kvm_vmx(kvm)->tss_addr = addr; 5240 5241 return init_rmode_tss(kvm, ret); 5242 } 5243 5244 int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr) 5245 { 5246 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr; 5247 return 0; 5248 } 5249 5250 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec) 5251 { 5252 switch (vec) { 5253 case BP_VECTOR: 5254 /* 5255 * Update instruction length as we may reinject the exception 5256 * from user space while in guest debugging mode. 5257 */ 5258 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len = 5259 vmcs_read32(VM_EXIT_INSTRUCTION_LEN); 5260 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) 5261 return false; 5262 fallthrough; 5263 case DB_VECTOR: 5264 return !(vcpu->guest_debug & 5265 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)); 5266 case DE_VECTOR: 5267 case OF_VECTOR: 5268 case BR_VECTOR: 5269 case UD_VECTOR: 5270 case DF_VECTOR: 5271 case SS_VECTOR: 5272 case GP_VECTOR: 5273 case MF_VECTOR: 5274 return true; 5275 } 5276 return false; 5277 } 5278 5279 static int handle_rmode_exception(struct kvm_vcpu *vcpu, 5280 int vec, u32 err_code) 5281 { 5282 /* 5283 * Instruction with address size override prefix opcode 0x67 5284 * Cause the #SS fault with 0 error code in VM86 mode. 5285 */ 5286 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) { 5287 if (kvm_emulate_instruction(vcpu, 0)) { 5288 if (vcpu->arch.halt_request) { 5289 vcpu->arch.halt_request = 0; 5290 return kvm_emulate_halt_noskip(vcpu); 5291 } 5292 return 1; 5293 } 5294 return 0; 5295 } 5296 5297 /* 5298 * Forward all other exceptions that are valid in real mode. 5299 * FIXME: Breaks guest debugging in real mode, needs to be fixed with 5300 * the required debugging infrastructure rework. 5301 */ 5302 kvm_queue_exception(vcpu, vec); 5303 return 1; 5304 } 5305 5306 static int handle_machine_check(struct kvm_vcpu *vcpu) 5307 { 5308 /* handled by vmx_vcpu_run() */ 5309 return 1; 5310 } 5311 5312 /* 5313 * If the host has split lock detection disabled, then #AC is 5314 * unconditionally injected into the guest, which is the pre split lock 5315 * detection behaviour. 5316 * 5317 * If the host has split lock detection enabled then #AC is 5318 * only injected into the guest when: 5319 * - Guest CPL == 3 (user mode) 5320 * - Guest has #AC detection enabled in CR0 5321 * - Guest EFLAGS has AC bit set 5322 */ 5323 bool vmx_guest_inject_ac(struct kvm_vcpu *vcpu) 5324 { 5325 if (!boot_cpu_has(X86_FEATURE_SPLIT_LOCK_DETECT)) 5326 return true; 5327 5328 return vmx_get_cpl(vcpu) == 3 && kvm_is_cr0_bit_set(vcpu, X86_CR0_AM) && 5329 (kvm_get_rflags(vcpu) & X86_EFLAGS_AC); 5330 } 5331 5332 static bool is_xfd_nm_fault(struct kvm_vcpu *vcpu) 5333 { 5334 return vcpu->arch.guest_fpu.fpstate->xfd && 5335 !kvm_is_cr0_bit_set(vcpu, X86_CR0_TS); 5336 } 5337 5338 static int vmx_handle_page_fault(struct kvm_vcpu *vcpu, u32 error_code) 5339 { 5340 unsigned long cr2 = vmx_get_exit_qual(vcpu); 5341 5342 if (vcpu->arch.apf.host_apf_flags) 5343 goto handle_pf; 5344 5345 /* When using EPT, KVM intercepts #PF only to detect illegal GPAs. */ 5346 WARN_ON_ONCE(enable_ept && !allow_smaller_maxphyaddr); 5347 5348 /* 5349 * On SGX2 hardware, EPCM violations are delivered as #PF with the SGX 5350 * flag set in the error code (SGX1 hardware generates #GP(0)). EPCM 5351 * violations have nothing to do with shadow paging and can never be 5352 * resolved by KVM; always reflect them into the guest. 5353 */ 5354 if (error_code & PFERR_SGX_MASK) { 5355 WARN_ON_ONCE(!IS_ENABLED(CONFIG_X86_SGX_KVM) || 5356 !cpu_feature_enabled(X86_FEATURE_SGX2)); 5357 5358 if (guest_cpu_cap_has(vcpu, X86_FEATURE_SGX2)) 5359 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code); 5360 else 5361 kvm_inject_gp(vcpu, 0); 5362 return 1; 5363 } 5364 5365 /* 5366 * If EPT is enabled, fixup and inject the #PF. KVM intercepts #PFs 5367 * only to set PFERR_RSVD as appropriate (hardware won't set RSVD due 5368 * to the GPA being legal with respect to host.MAXPHYADDR). 5369 */ 5370 if (enable_ept) { 5371 kvm_fixup_and_inject_pf_error(vcpu, cr2, error_code); 5372 return 1; 5373 } 5374 5375 handle_pf: 5376 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0); 5377 } 5378 5379 static int handle_exception_nmi(struct kvm_vcpu *vcpu) 5380 { 5381 struct vcpu_vmx *vmx = to_vmx(vcpu); 5382 struct kvm_run *kvm_run = vcpu->run; 5383 u32 intr_info, ex_no, error_code; 5384 unsigned long dr6; 5385 u32 vect_info; 5386 5387 vect_info = vmx->idt_vectoring_info; 5388 intr_info = vmx_get_intr_info(vcpu); 5389 5390 /* 5391 * Machine checks are handled by handle_exception_irqoff(), or by 5392 * vmx_vcpu_run() if a #MC occurs on VM-Entry. NMIs are handled by 5393 * vmx_vcpu_enter_exit(). 5394 */ 5395 if (is_machine_check(intr_info) || is_nmi(intr_info)) 5396 return 1; 5397 5398 /* 5399 * Queue the exception here instead of in handle_nm_fault_irqoff(). 5400 * This ensures the nested_vmx check is not skipped so vmexit can 5401 * be reflected to L1 (when it intercepts #NM) before reaching this 5402 * point. 5403 */ 5404 if (is_nm_fault(intr_info)) { 5405 kvm_queue_exception_p(vcpu, NM_VECTOR, 5406 is_xfd_nm_fault(vcpu) ? vcpu->arch.guest_fpu.xfd_err : 0); 5407 return 1; 5408 } 5409 5410 if (is_invalid_opcode(intr_info)) 5411 return handle_ud(vcpu); 5412 5413 if (WARN_ON_ONCE(is_ve_fault(intr_info))) { 5414 struct vmx_ve_information *ve_info = vmx->ve_info; 5415 5416 WARN_ONCE(ve_info->exit_reason != EXIT_REASON_EPT_VIOLATION, 5417 "Unexpected #VE on VM-Exit reason 0x%x", ve_info->exit_reason); 5418 dump_vmcs(vcpu); 5419 kvm_mmu_print_sptes(vcpu, ve_info->guest_physical_address, "#VE"); 5420 return 1; 5421 } 5422 5423 error_code = 0; 5424 if (intr_info & INTR_INFO_DELIVER_CODE_MASK) 5425 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE); 5426 5427 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) { 5428 WARN_ON_ONCE(!enable_vmware_backdoor); 5429 5430 /* 5431 * VMware backdoor emulation on #GP interception only handles 5432 * IN{S}, OUT{S}, and RDPMC, none of which generate a non-zero 5433 * error code on #GP. 5434 */ 5435 if (error_code) { 5436 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code); 5437 return 1; 5438 } 5439 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP); 5440 } 5441 5442 /* 5443 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing 5444 * MMIO, it is better to report an internal error. 5445 * See the comments in vmx_handle_exit. 5446 */ 5447 if ((vect_info & VECTORING_INFO_VALID_MASK) && 5448 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) { 5449 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; 5450 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX; 5451 vcpu->run->internal.ndata = 4; 5452 vcpu->run->internal.data[0] = vect_info; 5453 vcpu->run->internal.data[1] = intr_info; 5454 vcpu->run->internal.data[2] = error_code; 5455 vcpu->run->internal.data[3] = vcpu->arch.last_vmentry_cpu; 5456 return 0; 5457 } 5458 5459 if (is_page_fault(intr_info)) 5460 return vmx_handle_page_fault(vcpu, error_code); 5461 5462 ex_no = intr_info & INTR_INFO_VECTOR_MASK; 5463 5464 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no)) 5465 return handle_rmode_exception(vcpu, ex_no, error_code); 5466 5467 switch (ex_no) { 5468 case DB_VECTOR: 5469 dr6 = vmx_get_exit_qual(vcpu); 5470 if (!(vcpu->guest_debug & 5471 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) { 5472 /* 5473 * If the #DB was due to ICEBP, a.k.a. INT1, skip the 5474 * instruction. ICEBP generates a trap-like #DB, but 5475 * despite its interception control being tied to #DB, 5476 * is an instruction intercept, i.e. the VM-Exit occurs 5477 * on the ICEBP itself. Use the inner "skip" helper to 5478 * avoid single-step #DB and MTF updates, as ICEBP is 5479 * higher priority. Note, skipping ICEBP still clears 5480 * STI and MOVSS blocking. 5481 * 5482 * For all other #DBs, set vmcs.PENDING_DBG_EXCEPTIONS.BS 5483 * if single-step is enabled in RFLAGS and STI or MOVSS 5484 * blocking is active, as the CPU doesn't set the bit 5485 * on VM-Exit due to #DB interception. VM-Entry has a 5486 * consistency check that a single-step #DB is pending 5487 * in this scenario as the previous instruction cannot 5488 * have toggled RFLAGS.TF 0=>1 (because STI and POP/MOV 5489 * don't modify RFLAGS), therefore the one instruction 5490 * delay when activating single-step breakpoints must 5491 * have already expired. Note, the CPU sets/clears BS 5492 * as appropriate for all other VM-Exits types. 5493 */ 5494 if (is_icebp(intr_info)) 5495 WARN_ON(!skip_emulated_instruction(vcpu)); 5496 else if ((vmx_get_rflags(vcpu) & X86_EFLAGS_TF) && 5497 (vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & 5498 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS))) 5499 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 5500 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS) | DR6_BS); 5501 5502 kvm_queue_exception_p(vcpu, DB_VECTOR, dr6); 5503 return 1; 5504 } 5505 kvm_run->debug.arch.dr6 = dr6 | DR6_ACTIVE_LOW; 5506 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7); 5507 fallthrough; 5508 case BP_VECTOR: 5509 /* 5510 * Update instruction length as we may reinject #BP from 5511 * user space while in guest debugging mode. Reading it for 5512 * #DB as well causes no harm, it is not used in that case. 5513 */ 5514 vmx->vcpu.arch.event_exit_inst_len = 5515 vmcs_read32(VM_EXIT_INSTRUCTION_LEN); 5516 kvm_run->exit_reason = KVM_EXIT_DEBUG; 5517 kvm_run->debug.arch.pc = kvm_get_linear_rip(vcpu); 5518 kvm_run->debug.arch.exception = ex_no; 5519 break; 5520 case AC_VECTOR: 5521 if (vmx_guest_inject_ac(vcpu)) { 5522 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code); 5523 return 1; 5524 } 5525 5526 /* 5527 * Handle split lock. Depending on detection mode this will 5528 * either warn and disable split lock detection for this 5529 * task or force SIGBUS on it. 5530 */ 5531 if (handle_guest_split_lock(kvm_rip_read(vcpu))) 5532 return 1; 5533 fallthrough; 5534 default: 5535 kvm_run->exit_reason = KVM_EXIT_EXCEPTION; 5536 kvm_run->ex.exception = ex_no; 5537 kvm_run->ex.error_code = error_code; 5538 break; 5539 } 5540 return 0; 5541 } 5542 5543 static __always_inline int handle_external_interrupt(struct kvm_vcpu *vcpu) 5544 { 5545 ++vcpu->stat.irq_exits; 5546 return 1; 5547 } 5548 5549 static int handle_triple_fault(struct kvm_vcpu *vcpu) 5550 { 5551 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN; 5552 vcpu->mmio_needed = 0; 5553 return 0; 5554 } 5555 5556 static int handle_io(struct kvm_vcpu *vcpu) 5557 { 5558 unsigned long exit_qualification; 5559 int size, in, string; 5560 unsigned port; 5561 5562 exit_qualification = vmx_get_exit_qual(vcpu); 5563 string = (exit_qualification & 16) != 0; 5564 5565 ++vcpu->stat.io_exits; 5566 5567 if (string) 5568 return kvm_emulate_instruction(vcpu, 0); 5569 5570 port = exit_qualification >> 16; 5571 size = (exit_qualification & 7) + 1; 5572 in = (exit_qualification & 8) != 0; 5573 5574 return kvm_fast_pio(vcpu, size, port, in); 5575 } 5576 5577 void vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall) 5578 { 5579 /* 5580 * Patch in the VMCALL instruction: 5581 */ 5582 hypercall[0] = 0x0f; 5583 hypercall[1] = 0x01; 5584 hypercall[2] = 0xc1; 5585 } 5586 5587 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */ 5588 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val) 5589 { 5590 if (is_guest_mode(vcpu)) { 5591 struct vmcs12 *vmcs12 = get_vmcs12(vcpu); 5592 unsigned long orig_val = val; 5593 5594 /* 5595 * We get here when L2 changed cr0 in a way that did not change 5596 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr), 5597 * but did change L0 shadowed bits. So we first calculate the 5598 * effective cr0 value that L1 would like to write into the 5599 * hardware. It consists of the L2-owned bits from the new 5600 * value combined with the L1-owned bits from L1's guest_cr0. 5601 */ 5602 val = (val & ~vmcs12->cr0_guest_host_mask) | 5603 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask); 5604 5605 if (kvm_set_cr0(vcpu, val)) 5606 return 1; 5607 vmcs_writel(CR0_READ_SHADOW, orig_val); 5608 return 0; 5609 } else { 5610 return kvm_set_cr0(vcpu, val); 5611 } 5612 } 5613 5614 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val) 5615 { 5616 if (is_guest_mode(vcpu)) { 5617 struct vmcs12 *vmcs12 = get_vmcs12(vcpu); 5618 unsigned long orig_val = val; 5619 5620 /* analogously to handle_set_cr0 */ 5621 val = (val & ~vmcs12->cr4_guest_host_mask) | 5622 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask); 5623 if (kvm_set_cr4(vcpu, val)) 5624 return 1; 5625 vmcs_writel(CR4_READ_SHADOW, orig_val); 5626 return 0; 5627 } else 5628 return kvm_set_cr4(vcpu, val); 5629 } 5630 5631 static int handle_desc(struct kvm_vcpu *vcpu) 5632 { 5633 /* 5634 * UMIP emulation relies on intercepting writes to CR4.UMIP, i.e. this 5635 * and other code needs to be updated if UMIP can be guest owned. 5636 */ 5637 BUILD_BUG_ON(KVM_POSSIBLE_CR4_GUEST_BITS & X86_CR4_UMIP); 5638 5639 WARN_ON_ONCE(!kvm_is_cr4_bit_set(vcpu, X86_CR4_UMIP)); 5640 return kvm_emulate_instruction(vcpu, 0); 5641 } 5642 5643 static int handle_cr(struct kvm_vcpu *vcpu) 5644 { 5645 unsigned long exit_qualification, val; 5646 int cr; 5647 int reg; 5648 int err; 5649 int ret; 5650 5651 exit_qualification = vmx_get_exit_qual(vcpu); 5652 cr = exit_qualification & 15; 5653 reg = (exit_qualification >> 8) & 15; 5654 switch ((exit_qualification >> 4) & 3) { 5655 case 0: /* mov to cr */ 5656 val = kvm_register_read(vcpu, reg); 5657 trace_kvm_cr_write(cr, val); 5658 switch (cr) { 5659 case 0: 5660 err = handle_set_cr0(vcpu, val); 5661 return kvm_complete_insn_gp(vcpu, err); 5662 case 3: 5663 WARN_ON_ONCE(enable_unrestricted_guest); 5664 5665 err = kvm_set_cr3(vcpu, val); 5666 return kvm_complete_insn_gp(vcpu, err); 5667 case 4: 5668 err = handle_set_cr4(vcpu, val); 5669 return kvm_complete_insn_gp(vcpu, err); 5670 case 8: { 5671 u8 cr8_prev = kvm_get_cr8(vcpu); 5672 u8 cr8 = (u8)val; 5673 err = kvm_set_cr8(vcpu, cr8); 5674 ret = kvm_complete_insn_gp(vcpu, err); 5675 if (lapic_in_kernel(vcpu)) 5676 return ret; 5677 if (cr8_prev <= cr8) 5678 return ret; 5679 /* 5680 * TODO: we might be squashing a 5681 * KVM_GUESTDBG_SINGLESTEP-triggered 5682 * KVM_EXIT_DEBUG here. 5683 */ 5684 vcpu->run->exit_reason = KVM_EXIT_SET_TPR; 5685 return 0; 5686 } 5687 } 5688 break; 5689 case 2: /* clts */ 5690 KVM_BUG(1, vcpu->kvm, "Guest always owns CR0.TS"); 5691 return -EIO; 5692 case 1: /*mov from cr*/ 5693 switch (cr) { 5694 case 3: 5695 WARN_ON_ONCE(enable_unrestricted_guest); 5696 5697 val = kvm_read_cr3(vcpu); 5698 kvm_register_write(vcpu, reg, val); 5699 trace_kvm_cr_read(cr, val); 5700 return kvm_skip_emulated_instruction(vcpu); 5701 case 8: 5702 val = kvm_get_cr8(vcpu); 5703 kvm_register_write(vcpu, reg, val); 5704 trace_kvm_cr_read(cr, val); 5705 return kvm_skip_emulated_instruction(vcpu); 5706 } 5707 break; 5708 case 3: /* lmsw */ 5709 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f; 5710 trace_kvm_cr_write(0, (kvm_read_cr0_bits(vcpu, ~0xful) | val)); 5711 kvm_lmsw(vcpu, val); 5712 5713 return kvm_skip_emulated_instruction(vcpu); 5714 default: 5715 break; 5716 } 5717 vcpu->run->exit_reason = 0; 5718 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n", 5719 (int)(exit_qualification >> 4) & 3, cr); 5720 return 0; 5721 } 5722 5723 static int handle_dr(struct kvm_vcpu *vcpu) 5724 { 5725 unsigned long exit_qualification; 5726 int dr, dr7, reg; 5727 int err = 1; 5728 5729 exit_qualification = vmx_get_exit_qual(vcpu); 5730 dr = exit_qualification & DEBUG_REG_ACCESS_NUM; 5731 5732 /* First, if DR does not exist, trigger UD */ 5733 if (!kvm_require_dr(vcpu, dr)) 5734 return 1; 5735 5736 if (vmx_get_cpl(vcpu) > 0) 5737 goto out; 5738 5739 dr7 = vmcs_readl(GUEST_DR7); 5740 if (dr7 & DR7_GD) { 5741 /* 5742 * As the vm-exit takes precedence over the debug trap, we 5743 * need to emulate the latter, either for the host or the 5744 * guest debugging itself. 5745 */ 5746 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) { 5747 vcpu->run->debug.arch.dr6 = DR6_BD | DR6_ACTIVE_LOW; 5748 vcpu->run->debug.arch.dr7 = dr7; 5749 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu); 5750 vcpu->run->debug.arch.exception = DB_VECTOR; 5751 vcpu->run->exit_reason = KVM_EXIT_DEBUG; 5752 return 0; 5753 } else { 5754 kvm_queue_exception_p(vcpu, DB_VECTOR, DR6_BD); 5755 return 1; 5756 } 5757 } 5758 5759 if (vcpu->guest_debug == 0) { 5760 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING); 5761 5762 /* 5763 * No more DR vmexits; force a reload of the debug registers 5764 * and reenter on this instruction. The next vmexit will 5765 * retrieve the full state of the debug registers. 5766 */ 5767 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT; 5768 return 1; 5769 } 5770 5771 reg = DEBUG_REG_ACCESS_REG(exit_qualification); 5772 if (exit_qualification & TYPE_MOV_FROM_DR) { 5773 kvm_register_write(vcpu, reg, kvm_get_dr(vcpu, dr)); 5774 err = 0; 5775 } else { 5776 err = kvm_set_dr(vcpu, dr, kvm_register_read(vcpu, reg)); 5777 } 5778 5779 out: 5780 return kvm_complete_insn_gp(vcpu, err); 5781 } 5782 5783 void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu) 5784 { 5785 get_debugreg(vcpu->arch.db[0], 0); 5786 get_debugreg(vcpu->arch.db[1], 1); 5787 get_debugreg(vcpu->arch.db[2], 2); 5788 get_debugreg(vcpu->arch.db[3], 3); 5789 get_debugreg(vcpu->arch.dr6, 6); 5790 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7); 5791 5792 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT; 5793 exec_controls_setbit(to_vmx(vcpu), CPU_BASED_MOV_DR_EXITING); 5794 5795 /* 5796 * exc_debug expects dr6 to be cleared after it runs, avoid that it sees 5797 * a stale dr6 from the guest. 5798 */ 5799 set_debugreg(DR6_RESERVED, 6); 5800 } 5801 5802 void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val) 5803 { 5804 vmcs_writel(GUEST_DR7, val); 5805 } 5806 5807 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu) 5808 { 5809 kvm_apic_update_ppr(vcpu); 5810 return 1; 5811 } 5812 5813 static int handle_interrupt_window(struct kvm_vcpu *vcpu) 5814 { 5815 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING); 5816 5817 kvm_make_request(KVM_REQ_EVENT, vcpu); 5818 5819 ++vcpu->stat.irq_window_exits; 5820 return 1; 5821 } 5822 5823 static int handle_invlpg(struct kvm_vcpu *vcpu) 5824 { 5825 unsigned long exit_qualification = vmx_get_exit_qual(vcpu); 5826 5827 kvm_mmu_invlpg(vcpu, exit_qualification); 5828 return kvm_skip_emulated_instruction(vcpu); 5829 } 5830 5831 static int handle_apic_access(struct kvm_vcpu *vcpu) 5832 { 5833 if (likely(fasteoi)) { 5834 unsigned long exit_qualification = vmx_get_exit_qual(vcpu); 5835 int access_type, offset; 5836 5837 access_type = exit_qualification & APIC_ACCESS_TYPE; 5838 offset = exit_qualification & APIC_ACCESS_OFFSET; 5839 /* 5840 * Sane guest uses MOV to write EOI, with written value 5841 * not cared. So make a short-circuit here by avoiding 5842 * heavy instruction emulation. 5843 */ 5844 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) && 5845 (offset == APIC_EOI)) { 5846 kvm_lapic_set_eoi(vcpu); 5847 return kvm_skip_emulated_instruction(vcpu); 5848 } 5849 } 5850 return kvm_emulate_instruction(vcpu, 0); 5851 } 5852 5853 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu) 5854 { 5855 unsigned long exit_qualification = vmx_get_exit_qual(vcpu); 5856 int vector = exit_qualification & 0xff; 5857 5858 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */ 5859 kvm_apic_set_eoi_accelerated(vcpu, vector); 5860 return 1; 5861 } 5862 5863 static int handle_apic_write(struct kvm_vcpu *vcpu) 5864 { 5865 unsigned long exit_qualification = vmx_get_exit_qual(vcpu); 5866 5867 /* 5868 * APIC-write VM-Exit is trap-like, KVM doesn't need to advance RIP and 5869 * hardware has done any necessary aliasing, offset adjustments, etc... 5870 * for the access. I.e. the correct value has already been written to 5871 * the vAPIC page for the correct 16-byte chunk. KVM needs only to 5872 * retrieve the register value and emulate the access. 5873 */ 5874 u32 offset = exit_qualification & 0xff0; 5875 5876 kvm_apic_write_nodecode(vcpu, offset); 5877 return 1; 5878 } 5879 5880 static int handle_task_switch(struct kvm_vcpu *vcpu) 5881 { 5882 struct vcpu_vmx *vmx = to_vmx(vcpu); 5883 unsigned long exit_qualification; 5884 bool has_error_code = false; 5885 u32 error_code = 0; 5886 u16 tss_selector; 5887 int reason, type, idt_v, idt_index; 5888 5889 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK); 5890 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK); 5891 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK); 5892 5893 exit_qualification = vmx_get_exit_qual(vcpu); 5894 5895 reason = (u32)exit_qualification >> 30; 5896 if (reason == TASK_SWITCH_GATE && idt_v) { 5897 switch (type) { 5898 case INTR_TYPE_NMI_INTR: 5899 vcpu->arch.nmi_injected = false; 5900 vmx_set_nmi_mask(vcpu, true); 5901 break; 5902 case INTR_TYPE_EXT_INTR: 5903 case INTR_TYPE_SOFT_INTR: 5904 kvm_clear_interrupt_queue(vcpu); 5905 break; 5906 case INTR_TYPE_HARD_EXCEPTION: 5907 if (vmx->idt_vectoring_info & 5908 VECTORING_INFO_DELIVER_CODE_MASK) { 5909 has_error_code = true; 5910 error_code = 5911 vmcs_read32(IDT_VECTORING_ERROR_CODE); 5912 } 5913 fallthrough; 5914 case INTR_TYPE_SOFT_EXCEPTION: 5915 kvm_clear_exception_queue(vcpu); 5916 break; 5917 default: 5918 break; 5919 } 5920 } 5921 tss_selector = exit_qualification; 5922 5923 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION && 5924 type != INTR_TYPE_EXT_INTR && 5925 type != INTR_TYPE_NMI_INTR)) 5926 WARN_ON(!skip_emulated_instruction(vcpu)); 5927 5928 /* 5929 * TODO: What about debug traps on tss switch? 5930 * Are we supposed to inject them and update dr6? 5931 */ 5932 return kvm_task_switch(vcpu, tss_selector, 5933 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, 5934 reason, has_error_code, error_code); 5935 } 5936 5937 static int handle_ept_violation(struct kvm_vcpu *vcpu) 5938 { 5939 unsigned long exit_qualification = vmx_get_exit_qual(vcpu); 5940 gpa_t gpa; 5941 5942 /* 5943 * EPT violation happened while executing iret from NMI, 5944 * "blocked by NMI" bit has to be set before next VM entry. 5945 * There are errata that may cause this bit to not be set: 5946 * AAK134, BY25. 5947 */ 5948 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) && 5949 enable_vnmi && 5950 (exit_qualification & INTR_INFO_UNBLOCK_NMI)) 5951 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI); 5952 5953 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS); 5954 trace_kvm_page_fault(vcpu, gpa, exit_qualification); 5955 5956 /* 5957 * Check that the GPA doesn't exceed physical memory limits, as that is 5958 * a guest page fault. We have to emulate the instruction here, because 5959 * if the illegal address is that of a paging structure, then 5960 * EPT_VIOLATION_ACC_WRITE bit is set. Alternatively, if supported we 5961 * would also use advanced VM-exit information for EPT violations to 5962 * reconstruct the page fault error code. 5963 */ 5964 if (unlikely(allow_smaller_maxphyaddr && !kvm_vcpu_is_legal_gpa(vcpu, gpa))) 5965 return kvm_emulate_instruction(vcpu, 0); 5966 5967 return __vmx_handle_ept_violation(vcpu, gpa, exit_qualification); 5968 } 5969 5970 static int handle_ept_misconfig(struct kvm_vcpu *vcpu) 5971 { 5972 gpa_t gpa; 5973 5974 if (vmx_check_emulate_instruction(vcpu, EMULTYPE_PF, NULL, 0)) 5975 return 1; 5976 5977 /* 5978 * A nested guest cannot optimize MMIO vmexits, because we have an 5979 * nGPA here instead of the required GPA. 5980 */ 5981 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS); 5982 if (!is_guest_mode(vcpu) && 5983 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) { 5984 trace_kvm_fast_mmio(gpa); 5985 return kvm_skip_emulated_instruction(vcpu); 5986 } 5987 5988 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0); 5989 } 5990 5991 static int handle_nmi_window(struct kvm_vcpu *vcpu) 5992 { 5993 if (KVM_BUG_ON(!enable_vnmi, vcpu->kvm)) 5994 return -EIO; 5995 5996 exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING); 5997 ++vcpu->stat.nmi_window_exits; 5998 kvm_make_request(KVM_REQ_EVENT, vcpu); 5999 6000 return 1; 6001 } 6002 6003 /* 6004 * Returns true if emulation is required (due to the vCPU having invalid state 6005 * with unsrestricted guest mode disabled) and KVM can't faithfully emulate the 6006 * current vCPU state. 6007 */ 6008 static bool vmx_unhandleable_emulation_required(struct kvm_vcpu *vcpu) 6009 { 6010 struct vcpu_vmx *vmx = to_vmx(vcpu); 6011 6012 if (!vmx->vt.emulation_required) 6013 return false; 6014 6015 /* 6016 * It is architecturally impossible for emulation to be required when a 6017 * nested VM-Enter is pending completion, as VM-Enter will VM-Fail if 6018 * guest state is invalid and unrestricted guest is disabled, i.e. KVM 6019 * should synthesize VM-Fail instead emulation L2 code. This path is 6020 * only reachable if userspace modifies L2 guest state after KVM has 6021 * performed the nested VM-Enter consistency checks. 6022 */ 6023 if (vcpu->arch.nested_run_pending) 6024 return true; 6025 6026 /* 6027 * KVM only supports emulating exceptions if the vCPU is in Real Mode. 6028 * If emulation is required, KVM can't perform a successful VM-Enter to 6029 * inject the exception. 6030 */ 6031 return !vmx->rmode.vm86_active && 6032 (kvm_is_exception_pending(vcpu) || vcpu->arch.exception.injected); 6033 } 6034 6035 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu) 6036 { 6037 struct vcpu_vmx *vmx = to_vmx(vcpu); 6038 bool intr_window_requested; 6039 unsigned count = 130; 6040 6041 intr_window_requested = exec_controls_get(vmx) & 6042 CPU_BASED_INTR_WINDOW_EXITING; 6043 6044 while (vmx->vt.emulation_required && count-- != 0) { 6045 if (intr_window_requested && !vmx_interrupt_blocked(vcpu)) 6046 return handle_interrupt_window(&vmx->vcpu); 6047 6048 if (kvm_test_request(KVM_REQ_EVENT, vcpu)) 6049 return 1; 6050 6051 /* 6052 * Ensure that any updates to kvm->buses[] observed by the 6053 * previous instruction (emulated or otherwise) are also 6054 * visible to the instruction KVM is about to emulate. 6055 */ 6056 smp_rmb(); 6057 6058 if (!kvm_emulate_instruction(vcpu, 0)) 6059 return 0; 6060 6061 if (vmx_unhandleable_emulation_required(vcpu)) { 6062 kvm_prepare_emulation_failure_exit(vcpu); 6063 return 0; 6064 } 6065 6066 if (vcpu->arch.halt_request) { 6067 vcpu->arch.halt_request = 0; 6068 return kvm_emulate_halt_noskip(vcpu); 6069 } 6070 6071 /* 6072 * Note, return 1 and not 0, vcpu_run() will invoke 6073 * xfer_to_guest_mode() which will create a proper return 6074 * code. 6075 */ 6076 if (__xfer_to_guest_mode_work_pending()) 6077 return 1; 6078 } 6079 6080 return 1; 6081 } 6082 6083 int vmx_vcpu_pre_run(struct kvm_vcpu *vcpu) 6084 { 6085 if (vmx_unhandleable_emulation_required(vcpu)) { 6086 kvm_prepare_emulation_failure_exit(vcpu); 6087 return 0; 6088 } 6089 6090 return 1; 6091 } 6092 6093 /* 6094 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE 6095 * exiting, so only get here on cpu with PAUSE-Loop-Exiting. 6096 */ 6097 static int handle_pause(struct kvm_vcpu *vcpu) 6098 { 6099 if (!kvm_pause_in_guest(vcpu->kvm)) 6100 grow_ple_window(vcpu); 6101 6102 /* 6103 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting" 6104 * VM-execution control is ignored if CPL > 0. OTOH, KVM 6105 * never set PAUSE_EXITING and just set PLE if supported, 6106 * so the vcpu must be CPL=0 if it gets a PAUSE exit. 6107 */ 6108 kvm_vcpu_on_spin(vcpu, true); 6109 return kvm_skip_emulated_instruction(vcpu); 6110 } 6111 6112 static int handle_monitor_trap(struct kvm_vcpu *vcpu) 6113 { 6114 return 1; 6115 } 6116 6117 static int handle_invpcid(struct kvm_vcpu *vcpu) 6118 { 6119 u32 vmx_instruction_info; 6120 unsigned long type; 6121 gva_t gva; 6122 struct { 6123 u64 pcid; 6124 u64 gla; 6125 } operand; 6126 int gpr_index; 6127 6128 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_INVPCID)) { 6129 kvm_queue_exception(vcpu, UD_VECTOR); 6130 return 1; 6131 } 6132 6133 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); 6134 gpr_index = vmx_get_instr_info_reg2(vmx_instruction_info); 6135 type = kvm_register_read(vcpu, gpr_index); 6136 6137 /* According to the Intel instruction reference, the memory operand 6138 * is read even if it isn't needed (e.g., for type==all) 6139 */ 6140 if (get_vmx_mem_address(vcpu, vmx_get_exit_qual(vcpu), 6141 vmx_instruction_info, false, 6142 sizeof(operand), &gva)) 6143 return 1; 6144 6145 return kvm_handle_invpcid(vcpu, type, gva); 6146 } 6147 6148 static int handle_pml_full(struct kvm_vcpu *vcpu) 6149 { 6150 unsigned long exit_qualification; 6151 6152 trace_kvm_pml_full(vcpu->vcpu_id); 6153 6154 exit_qualification = vmx_get_exit_qual(vcpu); 6155 6156 /* 6157 * PML buffer FULL happened while executing iret from NMI, 6158 * "blocked by NMI" bit has to be set before next VM entry. 6159 */ 6160 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) && 6161 enable_vnmi && 6162 (exit_qualification & INTR_INFO_UNBLOCK_NMI)) 6163 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, 6164 GUEST_INTR_STATE_NMI); 6165 6166 /* 6167 * PML buffer already flushed at beginning of VMEXIT. Nothing to do 6168 * here.., and there's no userspace involvement needed for PML. 6169 */ 6170 return 1; 6171 } 6172 6173 static fastpath_t handle_fastpath_preemption_timer(struct kvm_vcpu *vcpu, 6174 bool force_immediate_exit) 6175 { 6176 struct vcpu_vmx *vmx = to_vmx(vcpu); 6177 6178 /* 6179 * In the *extremely* unlikely scenario that this is a spurious VM-Exit 6180 * due to the timer expiring while it was "soft" disabled, just eat the 6181 * exit and re-enter the guest. 6182 */ 6183 if (unlikely(vmx->loaded_vmcs->hv_timer_soft_disabled)) 6184 return EXIT_FASTPATH_REENTER_GUEST; 6185 6186 /* 6187 * If the timer expired because KVM used it to force an immediate exit, 6188 * then mission accomplished. 6189 */ 6190 if (force_immediate_exit) 6191 return EXIT_FASTPATH_EXIT_HANDLED; 6192 6193 /* 6194 * If L2 is active, go down the slow path as emulating the guest timer 6195 * expiration likely requires synthesizing a nested VM-Exit. 6196 */ 6197 if (is_guest_mode(vcpu)) 6198 return EXIT_FASTPATH_NONE; 6199 6200 kvm_lapic_expired_hv_timer(vcpu); 6201 return EXIT_FASTPATH_REENTER_GUEST; 6202 } 6203 6204 static int handle_preemption_timer(struct kvm_vcpu *vcpu) 6205 { 6206 /* 6207 * This non-fastpath handler is reached if and only if the preemption 6208 * timer was being used to emulate a guest timer while L2 is active. 6209 * All other scenarios are supposed to be handled in the fastpath. 6210 */ 6211 WARN_ON_ONCE(!is_guest_mode(vcpu)); 6212 kvm_lapic_expired_hv_timer(vcpu); 6213 return 1; 6214 } 6215 6216 /* 6217 * When nested=0, all VMX instruction VM Exits filter here. The handlers 6218 * are overwritten by nested_vmx_hardware_setup() when nested=1. 6219 */ 6220 static int handle_vmx_instruction(struct kvm_vcpu *vcpu) 6221 { 6222 kvm_queue_exception(vcpu, UD_VECTOR); 6223 return 1; 6224 } 6225 6226 static int handle_tdx_instruction(struct kvm_vcpu *vcpu) 6227 { 6228 kvm_queue_exception(vcpu, UD_VECTOR); 6229 return 1; 6230 } 6231 6232 #ifndef CONFIG_X86_SGX_KVM 6233 static int handle_encls(struct kvm_vcpu *vcpu) 6234 { 6235 /* 6236 * SGX virtualization is disabled. There is no software enable bit for 6237 * SGX, so KVM intercepts all ENCLS leafs and injects a #UD to prevent 6238 * the guest from executing ENCLS (when SGX is supported by hardware). 6239 */ 6240 kvm_queue_exception(vcpu, UD_VECTOR); 6241 return 1; 6242 } 6243 #endif /* CONFIG_X86_SGX_KVM */ 6244 6245 static int handle_bus_lock_vmexit(struct kvm_vcpu *vcpu) 6246 { 6247 /* 6248 * Hardware may or may not set the BUS_LOCK_DETECTED flag on BUS_LOCK 6249 * VM-Exits. Unconditionally set the flag here and leave the handling to 6250 * vmx_handle_exit(). 6251 */ 6252 to_vt(vcpu)->exit_reason.bus_lock_detected = true; 6253 return 1; 6254 } 6255 6256 static int handle_notify(struct kvm_vcpu *vcpu) 6257 { 6258 unsigned long exit_qual = vmx_get_exit_qual(vcpu); 6259 bool context_invalid = exit_qual & NOTIFY_VM_CONTEXT_INVALID; 6260 6261 ++vcpu->stat.notify_window_exits; 6262 6263 /* 6264 * Notify VM exit happened while executing iret from NMI, 6265 * "blocked by NMI" bit has to be set before next VM entry. 6266 */ 6267 if (enable_vnmi && (exit_qual & INTR_INFO_UNBLOCK_NMI)) 6268 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, 6269 GUEST_INTR_STATE_NMI); 6270 6271 if (vcpu->kvm->arch.notify_vmexit_flags & KVM_X86_NOTIFY_VMEXIT_USER || 6272 context_invalid) { 6273 vcpu->run->exit_reason = KVM_EXIT_NOTIFY; 6274 vcpu->run->notify.flags = context_invalid ? 6275 KVM_NOTIFY_CONTEXT_INVALID : 0; 6276 return 0; 6277 } 6278 6279 return 1; 6280 } 6281 6282 static int vmx_get_msr_imm_reg(struct kvm_vcpu *vcpu) 6283 { 6284 return vmx_get_instr_info_reg(vmcs_read32(VMX_INSTRUCTION_INFO)); 6285 } 6286 6287 static int handle_rdmsr_imm(struct kvm_vcpu *vcpu) 6288 { 6289 return kvm_emulate_rdmsr_imm(vcpu, vmx_get_exit_qual(vcpu), 6290 vmx_get_msr_imm_reg(vcpu)); 6291 } 6292 6293 static int handle_wrmsr_imm(struct kvm_vcpu *vcpu) 6294 { 6295 return kvm_emulate_wrmsr_imm(vcpu, vmx_get_exit_qual(vcpu), 6296 vmx_get_msr_imm_reg(vcpu)); 6297 } 6298 6299 /* 6300 * The exit handlers return 1 if the exit was handled fully and guest execution 6301 * may resume. Otherwise they set the kvm_run parameter to indicate what needs 6302 * to be done to userspace and return 0. 6303 */ 6304 static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = { 6305 [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi, 6306 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt, 6307 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault, 6308 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window, 6309 [EXIT_REASON_IO_INSTRUCTION] = handle_io, 6310 [EXIT_REASON_CR_ACCESS] = handle_cr, 6311 [EXIT_REASON_DR_ACCESS] = handle_dr, 6312 [EXIT_REASON_CPUID] = kvm_emulate_cpuid, 6313 [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr, 6314 [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr, 6315 [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window, 6316 [EXIT_REASON_HLT] = kvm_emulate_halt, 6317 [EXIT_REASON_INVD] = kvm_emulate_invd, 6318 [EXIT_REASON_INVLPG] = handle_invlpg, 6319 [EXIT_REASON_RDPMC] = kvm_emulate_rdpmc, 6320 [EXIT_REASON_VMCALL] = kvm_emulate_hypercall, 6321 [EXIT_REASON_VMCLEAR] = handle_vmx_instruction, 6322 [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction, 6323 [EXIT_REASON_VMPTRLD] = handle_vmx_instruction, 6324 [EXIT_REASON_VMPTRST] = handle_vmx_instruction, 6325 [EXIT_REASON_VMREAD] = handle_vmx_instruction, 6326 [EXIT_REASON_VMRESUME] = handle_vmx_instruction, 6327 [EXIT_REASON_VMWRITE] = handle_vmx_instruction, 6328 [EXIT_REASON_VMOFF] = handle_vmx_instruction, 6329 [EXIT_REASON_VMON] = handle_vmx_instruction, 6330 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold, 6331 [EXIT_REASON_APIC_ACCESS] = handle_apic_access, 6332 [EXIT_REASON_APIC_WRITE] = handle_apic_write, 6333 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced, 6334 [EXIT_REASON_WBINVD] = kvm_emulate_wbinvd, 6335 [EXIT_REASON_XSETBV] = kvm_emulate_xsetbv, 6336 [EXIT_REASON_TASK_SWITCH] = handle_task_switch, 6337 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check, 6338 [EXIT_REASON_GDTR_IDTR] = handle_desc, 6339 [EXIT_REASON_LDTR_TR] = handle_desc, 6340 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation, 6341 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig, 6342 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause, 6343 [EXIT_REASON_MWAIT_INSTRUCTION] = kvm_emulate_mwait, 6344 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap, 6345 [EXIT_REASON_MONITOR_INSTRUCTION] = kvm_emulate_monitor, 6346 [EXIT_REASON_INVEPT] = handle_vmx_instruction, 6347 [EXIT_REASON_INVVPID] = handle_vmx_instruction, 6348 [EXIT_REASON_RDRAND] = kvm_handle_invalid_op, 6349 [EXIT_REASON_RDSEED] = kvm_handle_invalid_op, 6350 [EXIT_REASON_PML_FULL] = handle_pml_full, 6351 [EXIT_REASON_INVPCID] = handle_invpcid, 6352 [EXIT_REASON_VMFUNC] = handle_vmx_instruction, 6353 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer, 6354 [EXIT_REASON_ENCLS] = handle_encls, 6355 [EXIT_REASON_BUS_LOCK] = handle_bus_lock_vmexit, 6356 [EXIT_REASON_NOTIFY] = handle_notify, 6357 [EXIT_REASON_SEAMCALL] = handle_tdx_instruction, 6358 [EXIT_REASON_TDCALL] = handle_tdx_instruction, 6359 [EXIT_REASON_MSR_READ_IMM] = handle_rdmsr_imm, 6360 [EXIT_REASON_MSR_WRITE_IMM] = handle_wrmsr_imm, 6361 }; 6362 6363 static const int kvm_vmx_max_exit_handlers = 6364 ARRAY_SIZE(kvm_vmx_exit_handlers); 6365 6366 void vmx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason, 6367 u64 *info1, u64 *info2, u32 *intr_info, u32 *error_code) 6368 { 6369 struct vcpu_vmx *vmx = to_vmx(vcpu); 6370 6371 *reason = vmx->vt.exit_reason.full; 6372 *info1 = vmx_get_exit_qual(vcpu); 6373 if (!(vmx->vt.exit_reason.failed_vmentry)) { 6374 *info2 = vmx->idt_vectoring_info; 6375 *intr_info = vmx_get_intr_info(vcpu); 6376 if (is_exception_with_error_code(*intr_info)) 6377 *error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE); 6378 else 6379 *error_code = 0; 6380 } else { 6381 *info2 = 0; 6382 *intr_info = 0; 6383 *error_code = 0; 6384 } 6385 } 6386 6387 void vmx_get_entry_info(struct kvm_vcpu *vcpu, u32 *intr_info, u32 *error_code) 6388 { 6389 *intr_info = vmcs_read32(VM_ENTRY_INTR_INFO_FIELD); 6390 if (is_exception_with_error_code(*intr_info)) 6391 *error_code = vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE); 6392 else 6393 *error_code = 0; 6394 } 6395 6396 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx) 6397 { 6398 if (vmx->pml_pg) { 6399 __free_page(vmx->pml_pg); 6400 vmx->pml_pg = NULL; 6401 } 6402 } 6403 6404 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu) 6405 { 6406 struct vcpu_vmx *vmx = to_vmx(vcpu); 6407 u16 pml_idx, pml_tail_index; 6408 u64 *pml_buf; 6409 int i; 6410 6411 pml_idx = vmcs_read16(GUEST_PML_INDEX); 6412 6413 /* Do nothing if PML buffer is empty */ 6414 if (pml_idx == PML_HEAD_INDEX) 6415 return; 6416 /* 6417 * PML index always points to the next available PML buffer entity 6418 * unless PML log has just overflowed. 6419 */ 6420 pml_tail_index = (pml_idx >= PML_LOG_NR_ENTRIES) ? 0 : pml_idx + 1; 6421 6422 /* 6423 * PML log is written backwards: the CPU first writes the entry 511 6424 * then the entry 510, and so on. 6425 * 6426 * Read the entries in the same order they were written, to ensure that 6427 * the dirty ring is filled in the same order the CPU wrote them. 6428 */ 6429 pml_buf = page_address(vmx->pml_pg); 6430 6431 for (i = PML_HEAD_INDEX; i >= pml_tail_index; i--) { 6432 u64 gpa; 6433 6434 gpa = pml_buf[i]; 6435 WARN_ON(gpa & (PAGE_SIZE - 1)); 6436 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT); 6437 } 6438 6439 /* reset PML index */ 6440 vmcs_write16(GUEST_PML_INDEX, PML_HEAD_INDEX); 6441 } 6442 6443 static void nested_vmx_mark_all_vmcs12_pages_dirty(struct kvm_vcpu *vcpu) 6444 { 6445 struct vcpu_vmx *vmx = to_vmx(vcpu); 6446 6447 kvm_vcpu_map_mark_dirty(vcpu, &vmx->nested.apic_access_page_map); 6448 kvm_vcpu_map_mark_dirty(vcpu, &vmx->nested.virtual_apic_map); 6449 kvm_vcpu_map_mark_dirty(vcpu, &vmx->nested.pi_desc_map); 6450 } 6451 6452 static void vmx_dump_sel(char *name, uint32_t sel) 6453 { 6454 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n", 6455 name, vmcs_read16(sel), 6456 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR), 6457 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR), 6458 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR)); 6459 } 6460 6461 static void vmx_dump_dtsel(char *name, uint32_t limit) 6462 { 6463 pr_err("%s limit=0x%08x, base=0x%016lx\n", 6464 name, vmcs_read32(limit), 6465 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT)); 6466 } 6467 6468 static void vmx_dump_msrs(char *name, struct vmx_msrs *m) 6469 { 6470 unsigned int i; 6471 struct vmx_msr_entry *e; 6472 6473 pr_err("MSR %s:\n", name); 6474 for (i = 0, e = m->val; i < m->nr; ++i, ++e) 6475 pr_err(" %2d: msr=0x%08x value=0x%016llx\n", i, e->index, e->value); 6476 } 6477 6478 void dump_vmcs(struct kvm_vcpu *vcpu) 6479 { 6480 struct vcpu_vmx *vmx = to_vmx(vcpu); 6481 u32 vmentry_ctl, vmexit_ctl; 6482 u32 cpu_based_exec_ctrl, pin_based_exec_ctrl, secondary_exec_control; 6483 u64 tertiary_exec_control; 6484 unsigned long cr4; 6485 int efer_slot; 6486 6487 if (!dump_invalid_vmcs) { 6488 pr_warn_ratelimited("set kvm_intel.dump_invalid_vmcs=1 to dump internal KVM state.\n"); 6489 return; 6490 } 6491 6492 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS); 6493 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS); 6494 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL); 6495 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL); 6496 cr4 = vmcs_readl(GUEST_CR4); 6497 6498 if (cpu_has_secondary_exec_ctrls()) 6499 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL); 6500 else 6501 secondary_exec_control = 0; 6502 6503 if (cpu_has_tertiary_exec_ctrls()) 6504 tertiary_exec_control = vmcs_read64(TERTIARY_VM_EXEC_CONTROL); 6505 else 6506 tertiary_exec_control = 0; 6507 6508 pr_err("VMCS %p, last attempted VM-entry on CPU %d\n", 6509 vmx->loaded_vmcs->vmcs, vcpu->arch.last_vmentry_cpu); 6510 pr_err("*** Guest State ***\n"); 6511 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n", 6512 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW), 6513 vmcs_readl(CR0_GUEST_HOST_MASK)); 6514 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n", 6515 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK)); 6516 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3)); 6517 if (cpu_has_vmx_ept()) { 6518 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n", 6519 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1)); 6520 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n", 6521 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3)); 6522 } 6523 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n", 6524 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP)); 6525 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n", 6526 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7)); 6527 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n", 6528 vmcs_readl(GUEST_SYSENTER_ESP), 6529 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP)); 6530 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR); 6531 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR); 6532 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR); 6533 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR); 6534 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR); 6535 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR); 6536 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT); 6537 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR); 6538 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT); 6539 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR); 6540 efer_slot = vmx_find_loadstore_msr_slot(&vmx->msr_autoload.guest, MSR_EFER); 6541 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_EFER) 6542 pr_err("EFER= 0x%016llx\n", vmcs_read64(GUEST_IA32_EFER)); 6543 else if (efer_slot >= 0) 6544 pr_err("EFER= 0x%016llx (autoload)\n", 6545 vmx->msr_autoload.guest.val[efer_slot].value); 6546 else if (vmentry_ctl & VM_ENTRY_IA32E_MODE) 6547 pr_err("EFER= 0x%016llx (effective)\n", 6548 vcpu->arch.efer | (EFER_LMA | EFER_LME)); 6549 else 6550 pr_err("EFER= 0x%016llx (effective)\n", 6551 vcpu->arch.efer & ~(EFER_LMA | EFER_LME)); 6552 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PAT) 6553 pr_err("PAT = 0x%016llx\n", vmcs_read64(GUEST_IA32_PAT)); 6554 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n", 6555 vmcs_read64(GUEST_IA32_DEBUGCTL), 6556 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS)); 6557 if (cpu_has_load_perf_global_ctrl() && 6558 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) 6559 pr_err("PerfGlobCtl = 0x%016llx\n", 6560 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL)); 6561 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS) 6562 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS)); 6563 pr_err("Interruptibility = %08x ActivityState = %08x\n", 6564 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO), 6565 vmcs_read32(GUEST_ACTIVITY_STATE)); 6566 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) 6567 pr_err("InterruptStatus = %04x\n", 6568 vmcs_read16(GUEST_INTR_STATUS)); 6569 if (vmcs_read32(VM_ENTRY_MSR_LOAD_COUNT) > 0) 6570 vmx_dump_msrs("guest autoload", &vmx->msr_autoload.guest); 6571 if (vmcs_read32(VM_EXIT_MSR_STORE_COUNT) > 0) 6572 vmx_dump_msrs("autostore", &vmx->msr_autostore); 6573 6574 if (vmentry_ctl & VM_ENTRY_LOAD_CET_STATE) 6575 pr_err("S_CET = 0x%016lx, SSP = 0x%016lx, SSP TABLE = 0x%016lx\n", 6576 vmcs_readl(GUEST_S_CET), vmcs_readl(GUEST_SSP), 6577 vmcs_readl(GUEST_INTR_SSP_TABLE)); 6578 pr_err("*** Host State ***\n"); 6579 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n", 6580 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP)); 6581 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n", 6582 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR), 6583 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR), 6584 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR), 6585 vmcs_read16(HOST_TR_SELECTOR)); 6586 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n", 6587 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE), 6588 vmcs_readl(HOST_TR_BASE)); 6589 pr_err("GDTBase=%016lx IDTBase=%016lx\n", 6590 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE)); 6591 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n", 6592 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3), 6593 vmcs_readl(HOST_CR4)); 6594 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n", 6595 vmcs_readl(HOST_IA32_SYSENTER_ESP), 6596 vmcs_read32(HOST_IA32_SYSENTER_CS), 6597 vmcs_readl(HOST_IA32_SYSENTER_EIP)); 6598 if (vmexit_ctl & VM_EXIT_LOAD_IA32_EFER) 6599 pr_err("EFER= 0x%016llx\n", vmcs_read64(HOST_IA32_EFER)); 6600 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PAT) 6601 pr_err("PAT = 0x%016llx\n", vmcs_read64(HOST_IA32_PAT)); 6602 if (cpu_has_load_perf_global_ctrl() && 6603 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) 6604 pr_err("PerfGlobCtl = 0x%016llx\n", 6605 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL)); 6606 if (vmcs_read32(VM_EXIT_MSR_LOAD_COUNT) > 0) 6607 vmx_dump_msrs("host autoload", &vmx->msr_autoload.host); 6608 if (vmexit_ctl & VM_EXIT_LOAD_CET_STATE) 6609 pr_err("S_CET = 0x%016lx, SSP = 0x%016lx, SSP TABLE = 0x%016lx\n", 6610 vmcs_readl(HOST_S_CET), vmcs_readl(HOST_SSP), 6611 vmcs_readl(HOST_INTR_SSP_TABLE)); 6612 6613 pr_err("*** Control State ***\n"); 6614 pr_err("CPUBased=0x%08x SecondaryExec=0x%08x TertiaryExec=0x%016llx\n", 6615 cpu_based_exec_ctrl, secondary_exec_control, tertiary_exec_control); 6616 pr_err("PinBased=0x%08x EntryControls=%08x ExitControls=%08x\n", 6617 pin_based_exec_ctrl, vmentry_ctl, vmexit_ctl); 6618 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n", 6619 vmcs_read32(EXCEPTION_BITMAP), 6620 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK), 6621 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH)); 6622 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n", 6623 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD), 6624 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE), 6625 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN)); 6626 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n", 6627 vmcs_read32(VM_EXIT_INTR_INFO), 6628 vmcs_read32(VM_EXIT_INTR_ERROR_CODE), 6629 vmcs_read32(VM_EXIT_INSTRUCTION_LEN)); 6630 pr_err(" reason=%08x qualification=%016lx\n", 6631 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION)); 6632 pr_err("IDTVectoring: info=%08x errcode=%08x\n", 6633 vmcs_read32(IDT_VECTORING_INFO_FIELD), 6634 vmcs_read32(IDT_VECTORING_ERROR_CODE)); 6635 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET)); 6636 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING) 6637 pr_err("TSC Multiplier = 0x%016llx\n", 6638 vmcs_read64(TSC_MULTIPLIER)); 6639 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) { 6640 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) { 6641 u16 status = vmcs_read16(GUEST_INTR_STATUS); 6642 pr_err("SVI|RVI = %02x|%02x ", status >> 8, status & 0xff); 6643 } 6644 pr_cont("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD)); 6645 if (secondary_exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) 6646 pr_err("APIC-access addr = 0x%016llx ", vmcs_read64(APIC_ACCESS_ADDR)); 6647 pr_cont("virt-APIC addr = 0x%016llx\n", vmcs_read64(VIRTUAL_APIC_PAGE_ADDR)); 6648 } 6649 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR) 6650 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV)); 6651 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT)) 6652 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER)); 6653 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING) 6654 pr_err("PLE Gap=%08x Window=%08x\n", 6655 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW)); 6656 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID) 6657 pr_err("Virtual processor ID = 0x%04x\n", 6658 vmcs_read16(VIRTUAL_PROCESSOR_ID)); 6659 if (secondary_exec_control & SECONDARY_EXEC_EPT_VIOLATION_VE) { 6660 struct vmx_ve_information *ve_info = vmx->ve_info; 6661 u64 ve_info_pa = vmcs_read64(VE_INFORMATION_ADDRESS); 6662 6663 /* 6664 * If KVM is dumping the VMCS, then something has gone wrong 6665 * already. Derefencing an address from the VMCS, which could 6666 * very well be corrupted, is a terrible idea. The virtual 6667 * address is known so use it. 6668 */ 6669 pr_err("VE info address = 0x%016llx%s\n", ve_info_pa, 6670 ve_info_pa == __pa(ve_info) ? "" : "(corrupted!)"); 6671 pr_err("ve_info: 0x%08x 0x%08x 0x%016llx 0x%016llx 0x%016llx 0x%04x\n", 6672 ve_info->exit_reason, ve_info->delivery, 6673 ve_info->exit_qualification, 6674 ve_info->guest_linear_address, 6675 ve_info->guest_physical_address, ve_info->eptp_index); 6676 } 6677 } 6678 6679 /* 6680 * The guest has exited. See if we can fix it or if we need userspace 6681 * assistance. 6682 */ 6683 static int __vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath) 6684 { 6685 struct vcpu_vmx *vmx = to_vmx(vcpu); 6686 union vmx_exit_reason exit_reason = vmx_get_exit_reason(vcpu); 6687 u32 vectoring_info = vmx->idt_vectoring_info; 6688 u16 exit_handler_index; 6689 6690 /* 6691 * Flush logged GPAs PML buffer, this will make dirty_bitmap more 6692 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before 6693 * querying dirty_bitmap, we only need to kick all vcpus out of guest 6694 * mode as if vcpus is in root mode, the PML buffer must has been 6695 * flushed already. Note, PML is never enabled in hardware while 6696 * running L2. 6697 */ 6698 if (enable_pml && !is_guest_mode(vcpu)) 6699 vmx_flush_pml_buffer(vcpu); 6700 6701 /* 6702 * KVM should never reach this point with a pending nested VM-Enter. 6703 * More specifically, short-circuiting VM-Entry to emulate L2 due to 6704 * invalid guest state should never happen as that means KVM knowingly 6705 * allowed a nested VM-Enter with an invalid vmcs12. More below. 6706 */ 6707 if (KVM_BUG_ON(vcpu->arch.nested_run_pending, vcpu->kvm)) 6708 return -EIO; 6709 6710 if (is_guest_mode(vcpu)) { 6711 /* 6712 * PML is never enabled when running L2, bail immediately if a 6713 * PML full exit occurs as something is horribly wrong. 6714 */ 6715 if (exit_reason.basic == EXIT_REASON_PML_FULL) 6716 goto unexpected_vmexit; 6717 6718 /* 6719 * The host physical addresses of some pages of guest memory 6720 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC 6721 * Page). The CPU may write to these pages via their host 6722 * physical address while L2 is running, bypassing any 6723 * address-translation-based dirty tracking (e.g. EPT write 6724 * protection). 6725 * 6726 * Mark them dirty on every exit from L2 to prevent them from 6727 * getting out of sync with dirty tracking. 6728 */ 6729 nested_vmx_mark_all_vmcs12_pages_dirty(vcpu); 6730 6731 /* 6732 * Synthesize a triple fault if L2 state is invalid. In normal 6733 * operation, nested VM-Enter rejects any attempt to enter L2 6734 * with invalid state. However, those checks are skipped if 6735 * state is being stuffed via RSM or KVM_SET_NESTED_STATE. If 6736 * L2 state is invalid, it means either L1 modified SMRAM state 6737 * or userspace provided bad state. Synthesize TRIPLE_FAULT as 6738 * doing so is architecturally allowed in the RSM case, and is 6739 * the least awful solution for the userspace case without 6740 * risking false positives. 6741 */ 6742 if (vmx->vt.emulation_required) { 6743 nested_vmx_vmexit(vcpu, EXIT_REASON_TRIPLE_FAULT, 0, 0); 6744 return 1; 6745 } 6746 6747 if (nested_vmx_reflect_vmexit(vcpu)) 6748 return 1; 6749 } 6750 6751 /* If guest state is invalid, start emulating. L2 is handled above. */ 6752 if (vmx->vt.emulation_required) 6753 return handle_invalid_guest_state(vcpu); 6754 6755 if (exit_reason.failed_vmentry) { 6756 dump_vmcs(vcpu); 6757 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY; 6758 vcpu->run->fail_entry.hardware_entry_failure_reason 6759 = exit_reason.full; 6760 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu; 6761 return 0; 6762 } 6763 6764 if (unlikely(vmx->fail)) { 6765 dump_vmcs(vcpu); 6766 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY; 6767 vcpu->run->fail_entry.hardware_entry_failure_reason 6768 = vmcs_read32(VM_INSTRUCTION_ERROR); 6769 vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu; 6770 return 0; 6771 } 6772 6773 if ((vectoring_info & VECTORING_INFO_VALID_MASK) && 6774 (exit_reason.basic != EXIT_REASON_EXCEPTION_NMI && 6775 exit_reason.basic != EXIT_REASON_EPT_VIOLATION && 6776 exit_reason.basic != EXIT_REASON_PML_FULL && 6777 exit_reason.basic != EXIT_REASON_APIC_ACCESS && 6778 exit_reason.basic != EXIT_REASON_TASK_SWITCH && 6779 exit_reason.basic != EXIT_REASON_NOTIFY && 6780 exit_reason.basic != EXIT_REASON_EPT_MISCONFIG)) { 6781 kvm_prepare_event_vectoring_exit(vcpu, INVALID_GPA); 6782 return 0; 6783 } 6784 6785 if (unlikely(!enable_vnmi && 6786 vmx->loaded_vmcs->soft_vnmi_blocked)) { 6787 if (!vmx_interrupt_blocked(vcpu)) { 6788 vmx->loaded_vmcs->soft_vnmi_blocked = 0; 6789 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL && 6790 vcpu->arch.nmi_pending) { 6791 /* 6792 * This CPU don't support us in finding the end of an 6793 * NMI-blocked window if the guest runs with IRQs 6794 * disabled. So we pull the trigger after 1 s of 6795 * futile waiting, but inform the user about this. 6796 */ 6797 printk(KERN_WARNING "%s: Breaking out of NMI-blocked " 6798 "state on VCPU %d after 1 s timeout\n", 6799 __func__, vcpu->vcpu_id); 6800 vmx->loaded_vmcs->soft_vnmi_blocked = 0; 6801 } 6802 } 6803 6804 if (exit_fastpath != EXIT_FASTPATH_NONE) 6805 return 1; 6806 6807 if (exit_reason.basic >= kvm_vmx_max_exit_handlers) 6808 goto unexpected_vmexit; 6809 #ifdef CONFIG_MITIGATION_RETPOLINE 6810 if (exit_reason.basic == EXIT_REASON_MSR_WRITE) 6811 return kvm_emulate_wrmsr(vcpu); 6812 else if (exit_reason.basic == EXIT_REASON_MSR_WRITE_IMM) 6813 return handle_wrmsr_imm(vcpu); 6814 else if (exit_reason.basic == EXIT_REASON_PREEMPTION_TIMER) 6815 return handle_preemption_timer(vcpu); 6816 else if (exit_reason.basic == EXIT_REASON_INTERRUPT_WINDOW) 6817 return handle_interrupt_window(vcpu); 6818 else if (exit_reason.basic == EXIT_REASON_EXTERNAL_INTERRUPT) 6819 return handle_external_interrupt(vcpu); 6820 else if (exit_reason.basic == EXIT_REASON_HLT) 6821 return kvm_emulate_halt(vcpu); 6822 else if (exit_reason.basic == EXIT_REASON_EPT_MISCONFIG) 6823 return handle_ept_misconfig(vcpu); 6824 #endif 6825 6826 exit_handler_index = array_index_nospec((u16)exit_reason.basic, 6827 kvm_vmx_max_exit_handlers); 6828 if (!kvm_vmx_exit_handlers[exit_handler_index]) 6829 goto unexpected_vmexit; 6830 6831 return kvm_vmx_exit_handlers[exit_handler_index](vcpu); 6832 6833 unexpected_vmexit: 6834 dump_vmcs(vcpu); 6835 kvm_prepare_unexpected_reason_exit(vcpu, exit_reason.full); 6836 return 0; 6837 } 6838 6839 int vmx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath) 6840 { 6841 int ret = __vmx_handle_exit(vcpu, exit_fastpath); 6842 6843 /* 6844 * Exit to user space when bus lock detected to inform that there is 6845 * a bus lock in guest. 6846 */ 6847 if (vmx_get_exit_reason(vcpu).bus_lock_detected) { 6848 if (ret > 0) 6849 vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK; 6850 6851 vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK; 6852 return 0; 6853 } 6854 return ret; 6855 } 6856 6857 void vmx_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr) 6858 { 6859 struct vmcs12 *vmcs12 = get_vmcs12(vcpu); 6860 int tpr_threshold; 6861 6862 if (is_guest_mode(vcpu) && 6863 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) 6864 return; 6865 6866 guard(vmx_vmcs01)(vcpu); 6867 6868 tpr_threshold = (irr == -1 || tpr < irr) ? 0 : irr; 6869 vmcs_write32(TPR_THRESHOLD, tpr_threshold); 6870 } 6871 6872 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu) 6873 { 6874 struct vcpu_vmx *vmx = to_vmx(vcpu); 6875 u32 sec_exec_control; 6876 6877 if (!lapic_in_kernel(vcpu)) 6878 return; 6879 6880 if (!flexpriority_enabled && 6881 !cpu_has_vmx_virtualize_x2apic_mode()) 6882 return; 6883 6884 guard(vmx_vmcs01)(vcpu); 6885 6886 sec_exec_control = secondary_exec_controls_get(vmx); 6887 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES | 6888 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE); 6889 6890 switch (kvm_get_apic_mode(vcpu)) { 6891 case LAPIC_MODE_INVALID: 6892 WARN_ONCE(true, "Invalid local APIC state"); 6893 break; 6894 case LAPIC_MODE_DISABLED: 6895 break; 6896 case LAPIC_MODE_XAPIC: 6897 if (flexpriority_enabled) { 6898 sec_exec_control |= 6899 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; 6900 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu); 6901 6902 /* 6903 * Flush the TLB, reloading the APIC access page will 6904 * only do so if its physical address has changed, but 6905 * the guest may have inserted a non-APIC mapping into 6906 * the TLB while the APIC access page was disabled. 6907 * 6908 * If L2 is active, immediately flush L1's TLB instead 6909 * of requesting a flush of the current TLB, because 6910 * the current TLB context is L2's. 6911 */ 6912 if (!is_guest_mode(vcpu)) 6913 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu); 6914 else if (!enable_ept) 6915 vpid_sync_context(vmx->vpid); 6916 else if (VALID_PAGE(vcpu->arch.root_mmu.root.hpa)) 6917 vmx_flush_tlb_ept_root(vcpu->arch.root_mmu.root.hpa); 6918 } 6919 break; 6920 case LAPIC_MODE_X2APIC: 6921 if (cpu_has_vmx_virtualize_x2apic_mode()) 6922 sec_exec_control |= 6923 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE; 6924 break; 6925 } 6926 secondary_exec_controls_set(vmx, sec_exec_control); 6927 6928 vmx_update_msr_bitmap_x2apic(vcpu); 6929 } 6930 6931 void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu) 6932 { 6933 const gfn_t gfn = APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT; 6934 struct kvm *kvm = vcpu->kvm; 6935 struct kvm_memslots *slots = kvm_memslots(kvm); 6936 struct kvm_memory_slot *slot; 6937 struct page *refcounted_page; 6938 unsigned long mmu_seq; 6939 kvm_pfn_t pfn; 6940 bool writable; 6941 6942 /* Note, the VIRTUALIZE_APIC_ACCESSES check needs to query vmcs01. */ 6943 guard(vmx_vmcs01)(vcpu); 6944 6945 if (!(secondary_exec_controls_get(to_vmx(vcpu)) & 6946 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) 6947 return; 6948 6949 /* 6950 * Explicitly grab the memslot using KVM's internal slot ID to ensure 6951 * KVM doesn't unintentionally grab a userspace memslot. It _should_ 6952 * be impossible for userspace to create a memslot for the APIC when 6953 * APICv is enabled, but paranoia won't hurt in this case. 6954 */ 6955 slot = id_to_memslot(slots, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT); 6956 if (!slot || slot->flags & KVM_MEMSLOT_INVALID) 6957 return; 6958 6959 /* 6960 * Ensure that the mmu_notifier sequence count is read before KVM 6961 * retrieves the pfn from the primary MMU. Note, the memslot is 6962 * protected by SRCU, not the mmu_notifier. Pairs with the smp_wmb() 6963 * in kvm_mmu_invalidate_end(). 6964 */ 6965 mmu_seq = kvm->mmu_invalidate_seq; 6966 smp_rmb(); 6967 6968 /* 6969 * No need to retry if the memslot does not exist or is invalid. KVM 6970 * controls the APIC-access page memslot, and only deletes the memslot 6971 * if APICv is permanently inhibited, i.e. the memslot won't reappear. 6972 */ 6973 pfn = __kvm_faultin_pfn(slot, gfn, FOLL_WRITE, &writable, &refcounted_page); 6974 if (is_error_noslot_pfn(pfn)) 6975 return; 6976 6977 read_lock(&vcpu->kvm->mmu_lock); 6978 if (mmu_invalidate_retry_gfn(kvm, mmu_seq, gfn)) 6979 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu); 6980 else 6981 vmcs_write64(APIC_ACCESS_ADDR, pfn_to_hpa(pfn)); 6982 6983 /* 6984 * Do not pin the APIC access page in memory so that it can be freely 6985 * migrated, the MMU notifier will call us again if it is migrated or 6986 * swapped out. KVM backs the memslot with anonymous memory, the pfn 6987 * should always point at a refcounted page (if the pfn is valid). 6988 */ 6989 if (!WARN_ON_ONCE(!refcounted_page)) 6990 kvm_release_page_clean(refcounted_page); 6991 6992 /* 6993 * No need for a manual TLB flush at this point, KVM has already done a 6994 * flush if there were SPTEs pointing at the previous page. 6995 */ 6996 read_unlock(&vcpu->kvm->mmu_lock); 6997 } 6998 6999 void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr) 7000 { 7001 u16 status; 7002 u8 old; 7003 7004 if (max_isr == -1) 7005 max_isr = 0; 7006 7007 /* 7008 * Always update SVI in vmcs01, as SVI is only relevant for L2 if and 7009 * only if Virtual Interrupt Delivery is enabled in vmcs12, and if VID 7010 * is enabled then L2 EOIs affect L2's vAPIC, not L1's vAPIC. 7011 */ 7012 guard(vmx_vmcs01)(vcpu); 7013 7014 status = vmcs_read16(GUEST_INTR_STATUS); 7015 old = status >> 8; 7016 if (max_isr != old) { 7017 status &= 0xff; 7018 status |= max_isr << 8; 7019 vmcs_write16(GUEST_INTR_STATUS, status); 7020 } 7021 } 7022 7023 static void vmx_set_rvi(int vector) 7024 { 7025 u16 status; 7026 u8 old; 7027 7028 if (vector == -1) 7029 vector = 0; 7030 7031 status = vmcs_read16(GUEST_INTR_STATUS); 7032 old = (u8)status & 0xff; 7033 if ((u8)vector != old) { 7034 status &= ~0xff; 7035 status |= (u8)vector; 7036 vmcs_write16(GUEST_INTR_STATUS, status); 7037 } 7038 } 7039 7040 int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu) 7041 { 7042 struct vcpu_vt *vt = to_vt(vcpu); 7043 bool max_irr_is_from_pir; 7044 int max_irr; 7045 7046 if (KVM_BUG_ON(!enable_apicv, vcpu->kvm)) 7047 return -EIO; 7048 7049 if (pi_test_on(&vt->pi_desc)) { 7050 pi_clear_on(&vt->pi_desc); 7051 /* 7052 * IOMMU can write to PID.ON, so the barrier matters even on UP. 7053 * But on x86 this is just a compiler barrier anyway. 7054 */ 7055 smp_mb__after_atomic(); 7056 max_irr_is_from_pir = kvm_apic_update_irr(vcpu, vt->pi_desc.pir, 7057 &max_irr); 7058 } else { 7059 max_irr = kvm_lapic_find_highest_irr(vcpu); 7060 max_irr_is_from_pir = false; 7061 } 7062 7063 /* 7064 * If APICv is enabled and L2 is not active, then update the Requesting 7065 * Virtual Interrupt (RVI) portion of vmcs01.GUEST_INTR_STATUS with the 7066 * highest priority IRR to deliver the IRQ via Virtual Interrupt 7067 * Delivery. Note, this is required even if the highest priority IRQ 7068 * was already pending in the IRR, as RVI isn't updated in lockstep with 7069 * the IRR (unlike apic->irr_pending). 7070 * 7071 * For the cases where Virtual Interrupt Delivery can't be used: 7072 * 7073 * 1) If L2 is running and the vCPU has a new pending interrupt. If L1 7074 * wants to exit on interrupts, KVM_REQ_EVENT is needed to synthesize a 7075 * VM-Exit to L1. If L1 doesn't want to exit, the interrupt is injected 7076 * into L2, but KVM doesn't use virtual interrupt delivery to inject 7077 * interrupts into L2, and so KVM_REQ_EVENT is again needed. 7078 * 7079 * 2) If APICv is disabled for this vCPU, assigned devices may still 7080 * attempt to post interrupts. The posted interrupt vector will cause 7081 * a VM-Exit and the subsequent entry will call sync_pir_to_irr. 7082 * 7083 * In both cases, set KVM_REQ_EVENT if and only if the highest priority 7084 * pending IRQ came from the PIR, as setting KVM_REQ_EVENT if any IRQ 7085 * is pending may put the vCPU into an infinite loop, e.g. if the IRQ 7086 * is blocked, then it will stay pending until an IRQ window is opened. 7087 * 7088 * Note! It's possible that one or more IRQs were moved from the PIR 7089 * to the IRR _without_ max_irr_is_from_pir being true! I.e. if there 7090 * was a higher priority IRQ already pending in the IRR. Not setting 7091 * KVM_REQ_EVENT in this case is intentional and safe. If APICv is 7092 * inactive, or L2 is running with exit-on-interrupt off (in vmcs12), 7093 * i.e. without nested virtual interrupt delivery, then there's no need 7094 * to request an IRQ window as the lower priority IRQ only needs to be 7095 * delivered when the higher priority IRQ is dismissed from the ISR, 7096 * i.e. on the next EOI, and EOIs are always intercepted if APICv is 7097 * disabled or if L2 is running without nested VID. If L2 is running 7098 * exit-on-interrupt on (in vmcs12), then the higher priority IRQ will 7099 * trigger a nested VM-Exit, at which point KVM will re-evaluate L1's 7100 * pending IRQs. 7101 */ 7102 if (!is_guest_mode(vcpu) && kvm_vcpu_apicv_active(vcpu)) 7103 vmx_set_rvi(max_irr); 7104 else if (max_irr_is_from_pir) 7105 kvm_make_request(KVM_REQ_EVENT, vcpu); 7106 7107 return max_irr; 7108 } 7109 7110 void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap) 7111 { 7112 if (!kvm_vcpu_apicv_active(vcpu)) 7113 return; 7114 7115 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]); 7116 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]); 7117 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]); 7118 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]); 7119 } 7120 7121 static void handle_nm_fault_irqoff(struct kvm_vcpu *vcpu) 7122 { 7123 /* 7124 * Save xfd_err to guest_fpu before interrupt is enabled, so the 7125 * MSR value is not clobbered by the host activity before the guest 7126 * has chance to consume it. 7127 * 7128 * Update the guest's XFD_ERR if and only if XFD is enabled, as the #NM 7129 * interception may have been caused by L1 interception. Per the SDM, 7130 * XFD_ERR is not modified for non-XFD #NM, i.e. if CR0.TS=1. 7131 * 7132 * Note, XFD_ERR is updated _before_ the #NM interception check, i.e. 7133 * unlike CR2 and DR6, the value is not a payload that is attached to 7134 * the #NM exception. 7135 */ 7136 if (is_xfd_nm_fault(vcpu)) 7137 rdmsrq(MSR_IA32_XFD_ERR, vcpu->arch.guest_fpu.xfd_err); 7138 } 7139 7140 static void handle_exception_irqoff(struct kvm_vcpu *vcpu, u32 intr_info) 7141 { 7142 /* if exit due to PF check for async PF */ 7143 if (is_page_fault(intr_info)) 7144 vcpu->arch.apf.host_apf_flags = kvm_read_and_reset_apf_flags(); 7145 /* if exit due to NM, handle before interrupts are enabled */ 7146 else if (is_nm_fault(intr_info)) 7147 handle_nm_fault_irqoff(vcpu); 7148 /* Handle machine checks before interrupts are enabled */ 7149 else if (is_machine_check(intr_info)) 7150 kvm_machine_check(); 7151 } 7152 7153 static void handle_external_interrupt_irqoff(struct kvm_vcpu *vcpu, 7154 u32 intr_info) 7155 { 7156 unsigned int vector = intr_info & INTR_INFO_VECTOR_MASK; 7157 7158 if (KVM_BUG(!is_external_intr(intr_info), vcpu->kvm, 7159 "unexpected VM-Exit interrupt info: 0x%x", intr_info)) 7160 return; 7161 7162 kvm_before_interrupt(vcpu, KVM_HANDLING_IRQ); 7163 x86_entry_from_kvm(EVENT_TYPE_EXTINT, vector); 7164 kvm_after_interrupt(vcpu); 7165 7166 vcpu->arch.at_instruction_boundary = true; 7167 } 7168 7169 void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu) 7170 { 7171 if (to_vt(vcpu)->emulation_required) 7172 return; 7173 7174 switch (vmx_get_exit_reason(vcpu).basic) { 7175 case EXIT_REASON_EXTERNAL_INTERRUPT: 7176 handle_external_interrupt_irqoff(vcpu, vmx_get_intr_info(vcpu)); 7177 break; 7178 case EXIT_REASON_EXCEPTION_NMI: 7179 handle_exception_irqoff(vcpu, vmx_get_intr_info(vcpu)); 7180 break; 7181 case EXIT_REASON_MCE_DURING_VMENTRY: 7182 kvm_machine_check(); 7183 break; 7184 default: 7185 break; 7186 } 7187 } 7188 7189 /* 7190 * The kvm parameter can be NULL (module initialization, or invocation before 7191 * VM creation). Be sure to check the kvm parameter before using it. 7192 */ 7193 bool vmx_has_emulated_msr(struct kvm *kvm, u32 index) 7194 { 7195 switch (index) { 7196 case MSR_IA32_SMBASE: 7197 if (!IS_ENABLED(CONFIG_KVM_SMM)) 7198 return false; 7199 /* 7200 * We cannot do SMM unless we can run the guest in big 7201 * real mode. 7202 */ 7203 return enable_unrestricted_guest || emulate_invalid_guest_state; 7204 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR: 7205 return nested; 7206 case MSR_AMD64_VIRT_SPEC_CTRL: 7207 case MSR_AMD64_TSC_RATIO: 7208 /* This is AMD only. */ 7209 return false; 7210 default: 7211 return true; 7212 } 7213 } 7214 7215 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx) 7216 { 7217 u32 exit_intr_info; 7218 bool unblock_nmi; 7219 u8 vector; 7220 bool idtv_info_valid; 7221 7222 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK; 7223 7224 if (enable_vnmi) { 7225 if (vmx->loaded_vmcs->nmi_known_unmasked) 7226 return; 7227 7228 exit_intr_info = vmx_get_intr_info(&vmx->vcpu); 7229 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0; 7230 vector = exit_intr_info & INTR_INFO_VECTOR_MASK; 7231 /* 7232 * SDM 3: 27.7.1.2 (September 2008) 7233 * Re-set bit "block by NMI" before VM entry if vmexit caused by 7234 * a guest IRET fault. 7235 * SDM 3: 23.2.2 (September 2008) 7236 * Bit 12 is undefined in any of the following cases: 7237 * If the VM exit sets the valid bit in the IDT-vectoring 7238 * information field. 7239 * If the VM exit is due to a double fault. 7240 */ 7241 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi && 7242 vector != DF_VECTOR && !idtv_info_valid) 7243 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, 7244 GUEST_INTR_STATE_NMI); 7245 else 7246 vmx->loaded_vmcs->nmi_known_unmasked = 7247 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) 7248 & GUEST_INTR_STATE_NMI); 7249 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked)) 7250 vmx->loaded_vmcs->vnmi_blocked_time += 7251 ktime_to_ns(ktime_sub(ktime_get(), 7252 vmx->loaded_vmcs->entry_time)); 7253 } 7254 7255 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu, 7256 u32 idt_vectoring_info, 7257 int instr_len_field, 7258 int error_code_field) 7259 { 7260 u8 vector; 7261 int type; 7262 bool idtv_info_valid; 7263 7264 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK; 7265 7266 vcpu->arch.nmi_injected = false; 7267 kvm_clear_exception_queue(vcpu); 7268 kvm_clear_interrupt_queue(vcpu); 7269 7270 if (!idtv_info_valid) 7271 return; 7272 7273 kvm_make_request(KVM_REQ_EVENT, vcpu); 7274 7275 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK; 7276 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK; 7277 7278 switch (type) { 7279 case INTR_TYPE_NMI_INTR: 7280 vcpu->arch.nmi_injected = true; 7281 /* 7282 * SDM 3: 27.7.1.2 (September 2008) 7283 * Clear bit "block by NMI" before VM entry if a NMI 7284 * delivery faulted. 7285 */ 7286 vmx_set_nmi_mask(vcpu, false); 7287 break; 7288 case INTR_TYPE_SOFT_EXCEPTION: 7289 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field); 7290 fallthrough; 7291 case INTR_TYPE_HARD_EXCEPTION: { 7292 u32 error_code = 0; 7293 7294 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) 7295 error_code = vmcs_read32(error_code_field); 7296 7297 kvm_requeue_exception(vcpu, vector, 7298 idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK, 7299 error_code); 7300 break; 7301 } 7302 case INTR_TYPE_SOFT_INTR: 7303 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field); 7304 fallthrough; 7305 case INTR_TYPE_EXT_INTR: 7306 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR); 7307 break; 7308 default: 7309 break; 7310 } 7311 } 7312 7313 static void vmx_complete_interrupts(struct vcpu_vmx *vmx) 7314 { 7315 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info, 7316 VM_EXIT_INSTRUCTION_LEN, 7317 IDT_VECTORING_ERROR_CODE); 7318 } 7319 7320 void vmx_cancel_injection(struct kvm_vcpu *vcpu) 7321 { 7322 __vmx_complete_interrupts(vcpu, 7323 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD), 7324 VM_ENTRY_INSTRUCTION_LEN, 7325 VM_ENTRY_EXCEPTION_ERROR_CODE); 7326 7327 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); 7328 } 7329 7330 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx) 7331 { 7332 int i, nr_msrs; 7333 struct perf_guest_switch_msr *msrs; 7334 struct kvm_pmu *pmu = vcpu_to_pmu(&vmx->vcpu); 7335 7336 if (kvm_vcpu_has_mediated_pmu(&vmx->vcpu)) 7337 return; 7338 7339 pmu->host_cross_mapped_mask = 0; 7340 if (pmu->pebs_enable & pmu->global_ctrl) 7341 intel_pmu_cross_mapped_check(pmu); 7342 7343 /* Note, nr_msrs may be garbage if perf_guest_get_msrs() returns NULL. */ 7344 msrs = perf_guest_get_msrs(&nr_msrs, (void *)pmu); 7345 if (!msrs) 7346 return; 7347 7348 for (i = 0; i < nr_msrs; i++) 7349 if (msrs[i].host == msrs[i].guest) 7350 clear_atomic_switch_msr(vmx, msrs[i].msr); 7351 else 7352 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest, 7353 msrs[i].host); 7354 } 7355 7356 static void vmx_refresh_guest_perf_global_control(struct kvm_vcpu *vcpu) 7357 { 7358 struct kvm_pmu *pmu = vcpu_to_pmu(vcpu); 7359 struct vcpu_vmx *vmx = to_vmx(vcpu); 7360 7361 if (msr_write_intercepted(vmx, MSR_CORE_PERF_GLOBAL_CTRL)) 7362 return; 7363 7364 if (!cpu_has_save_perf_global_ctrl()) { 7365 int slot = vmx_find_loadstore_msr_slot(&vmx->msr_autostore, 7366 MSR_CORE_PERF_GLOBAL_CTRL); 7367 7368 if (WARN_ON_ONCE(slot < 0)) 7369 return; 7370 7371 pmu->global_ctrl = vmx->msr_autostore.val[slot].value; 7372 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL, pmu->global_ctrl); 7373 return; 7374 } 7375 7376 pmu->global_ctrl = vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL); 7377 } 7378 7379 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu, bool force_immediate_exit) 7380 { 7381 struct vcpu_vmx *vmx = to_vmx(vcpu); 7382 u64 tscl; 7383 u32 delta_tsc; 7384 7385 if (force_immediate_exit) { 7386 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, 0); 7387 vmx->loaded_vmcs->hv_timer_soft_disabled = false; 7388 } else if (vmx->hv_deadline_tsc != -1) { 7389 tscl = rdtsc(); 7390 if (vmx->hv_deadline_tsc > tscl) 7391 /* set_hv_timer ensures the delta fits in 32-bits */ 7392 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >> 7393 cpu_preemption_timer_multi); 7394 else 7395 delta_tsc = 0; 7396 7397 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc); 7398 vmx->loaded_vmcs->hv_timer_soft_disabled = false; 7399 } else if (!vmx->loaded_vmcs->hv_timer_soft_disabled) { 7400 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, -1); 7401 vmx->loaded_vmcs->hv_timer_soft_disabled = true; 7402 } 7403 } 7404 7405 void noinstr vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp) 7406 { 7407 if (unlikely(host_rsp != vmx->loaded_vmcs->host_state.rsp)) { 7408 vmx->loaded_vmcs->host_state.rsp = host_rsp; 7409 vmcs_writel(HOST_RSP, host_rsp); 7410 } 7411 } 7412 7413 void noinstr vmx_spec_ctrl_restore_host(struct vcpu_vmx *vmx, 7414 unsigned int flags) 7415 { 7416 u64 hostval = this_cpu_read(x86_spec_ctrl_current); 7417 7418 if (!cpu_feature_enabled(X86_FEATURE_MSR_SPEC_CTRL)) 7419 return; 7420 7421 if (flags & VMX_RUN_SAVE_SPEC_CTRL) 7422 vmx->spec_ctrl = native_rdmsrq(MSR_IA32_SPEC_CTRL); 7423 7424 /* 7425 * If the guest/host SPEC_CTRL values differ, restore the host value. 7426 * 7427 * For legacy IBRS, the IBRS bit always needs to be written after 7428 * transitioning from a less privileged predictor mode, regardless of 7429 * whether the guest/host values differ. 7430 */ 7431 if (cpu_feature_enabled(X86_FEATURE_KERNEL_IBRS) || 7432 vmx->spec_ctrl != hostval) 7433 native_wrmsrq(MSR_IA32_SPEC_CTRL, hostval); 7434 7435 barrier_nospec(); 7436 } 7437 7438 static fastpath_t vmx_exit_handlers_fastpath(struct kvm_vcpu *vcpu, 7439 bool force_immediate_exit) 7440 { 7441 /* 7442 * If L2 is active, some VMX preemption timer exits can be handled in 7443 * the fastpath even, all other exits must use the slow path. 7444 */ 7445 if (is_guest_mode(vcpu) && 7446 vmx_get_exit_reason(vcpu).basic != EXIT_REASON_PREEMPTION_TIMER) 7447 return EXIT_FASTPATH_NONE; 7448 7449 switch (vmx_get_exit_reason(vcpu).basic) { 7450 case EXIT_REASON_MSR_WRITE: 7451 return handle_fastpath_wrmsr(vcpu); 7452 case EXIT_REASON_MSR_WRITE_IMM: 7453 return handle_fastpath_wrmsr_imm(vcpu, vmx_get_exit_qual(vcpu), 7454 vmx_get_msr_imm_reg(vcpu)); 7455 case EXIT_REASON_PREEMPTION_TIMER: 7456 return handle_fastpath_preemption_timer(vcpu, force_immediate_exit); 7457 case EXIT_REASON_HLT: 7458 return handle_fastpath_hlt(vcpu); 7459 case EXIT_REASON_INVD: 7460 return handle_fastpath_invd(vcpu); 7461 default: 7462 return EXIT_FASTPATH_NONE; 7463 } 7464 } 7465 7466 noinstr void vmx_handle_nmi(struct kvm_vcpu *vcpu) 7467 { 7468 if ((u16)vmx_get_exit_reason(vcpu).basic != EXIT_REASON_EXCEPTION_NMI || 7469 !is_nmi(vmx_get_intr_info(vcpu))) 7470 return; 7471 7472 kvm_before_interrupt(vcpu, KVM_HANDLING_NMI); 7473 x86_entry_from_kvm(EVENT_TYPE_NMI, NMI_VECTOR); 7474 kvm_after_interrupt(vcpu); 7475 } 7476 7477 static noinstr void vmx_vcpu_enter_exit(struct kvm_vcpu *vcpu, 7478 unsigned int flags) 7479 { 7480 struct vcpu_vmx *vmx = to_vmx(vcpu); 7481 7482 guest_state_enter_irqoff(); 7483 7484 vmx_l1d_flush(vcpu); 7485 7486 vmx_disable_fb_clear(vmx); 7487 7488 if (vcpu->arch.cr2 != native_read_cr2()) 7489 native_write_cr2(vcpu->arch.cr2); 7490 7491 vmx->fail = __vmx_vcpu_run(vmx, (unsigned long *)&vcpu->arch.regs, 7492 flags); 7493 7494 vcpu->arch.cr2 = native_read_cr2(); 7495 vcpu->arch.regs_avail &= ~VMX_REGS_LAZY_LOAD_SET; 7496 7497 vmx->idt_vectoring_info = 0; 7498 7499 vmx_enable_fb_clear(vmx); 7500 7501 if (unlikely(vmx->fail)) { 7502 vmx->vt.exit_reason.full = 0xdead; 7503 goto out; 7504 } 7505 7506 vmx->vt.exit_reason.full = vmcs_read32(VM_EXIT_REASON); 7507 if (likely(!vmx_get_exit_reason(vcpu).failed_vmentry)) 7508 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD); 7509 7510 vmx_handle_nmi(vcpu); 7511 7512 out: 7513 guest_state_exit_irqoff(); 7514 } 7515 7516 fastpath_t vmx_vcpu_run(struct kvm_vcpu *vcpu, u64 run_flags) 7517 { 7518 bool force_immediate_exit = run_flags & KVM_RUN_FORCE_IMMEDIATE_EXIT; 7519 struct vcpu_vmx *vmx = to_vmx(vcpu); 7520 unsigned long cr3, cr4; 7521 7522 /* Record the guest's net vcpu time for enforced NMI injections. */ 7523 if (unlikely(!enable_vnmi && 7524 vmx->loaded_vmcs->soft_vnmi_blocked)) 7525 vmx->loaded_vmcs->entry_time = ktime_get(); 7526 7527 /* 7528 * Don't enter VMX if guest state is invalid, let the exit handler 7529 * start emulation until we arrive back to a valid state. Synthesize a 7530 * consistency check VM-Exit due to invalid guest state and bail. 7531 */ 7532 if (unlikely(vmx->vt.emulation_required)) { 7533 vmx->fail = 0; 7534 7535 vmx->vt.exit_reason.full = EXIT_REASON_INVALID_STATE; 7536 vmx->vt.exit_reason.failed_vmentry = 1; 7537 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_1); 7538 vmx->vt.exit_qualification = ENTRY_FAIL_DEFAULT; 7539 kvm_register_mark_available(vcpu, VCPU_EXREG_EXIT_INFO_2); 7540 vmx->vt.exit_intr_info = 0; 7541 return EXIT_FASTPATH_NONE; 7542 } 7543 7544 trace_kvm_entry(vcpu, force_immediate_exit); 7545 7546 if (vmx->ple_window_dirty) { 7547 vmx->ple_window_dirty = false; 7548 vmcs_write32(PLE_WINDOW, vmx->ple_window); 7549 } 7550 7551 /* 7552 * We did this in prepare_switch_to_guest, because it needs to 7553 * be within srcu_read_lock. 7554 */ 7555 WARN_ON_ONCE(vmx->nested.need_vmcs12_to_shadow_sync); 7556 7557 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RSP)) 7558 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]); 7559 if (kvm_register_is_dirty(vcpu, VCPU_REGS_RIP)) 7560 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]); 7561 vcpu->arch.regs_dirty = 0; 7562 7563 if (run_flags & KVM_RUN_LOAD_GUEST_DR6) 7564 set_debugreg(vcpu->arch.dr6, 6); 7565 7566 if (run_flags & KVM_RUN_LOAD_DEBUGCTL) 7567 vmx_reload_guest_debugctl(vcpu); 7568 7569 /* 7570 * Refresh vmcs.HOST_CR3 if necessary. This must be done immediately 7571 * prior to VM-Enter, as the kernel may load a new ASID (PCID) any time 7572 * it switches back to the current->mm, which can occur in KVM context 7573 * when switching to a temporary mm to patch kernel code, e.g. if KVM 7574 * toggles a static key while handling a VM-Exit. 7575 */ 7576 cr3 = __get_current_cr3_fast(); 7577 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) { 7578 vmcs_writel(HOST_CR3, cr3); 7579 vmx->loaded_vmcs->host_state.cr3 = cr3; 7580 } 7581 7582 cr4 = cr4_read_shadow(); 7583 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) { 7584 vmcs_writel(HOST_CR4, cr4); 7585 vmx->loaded_vmcs->host_state.cr4 = cr4; 7586 } 7587 7588 /* When single-stepping over STI and MOV SS, we must clear the 7589 * corresponding interruptibility bits in the guest state. Otherwise 7590 * vmentry fails as it then expects bit 14 (BS) in pending debug 7591 * exceptions being set, but that's not correct for the guest debugging 7592 * case. */ 7593 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) 7594 vmx_set_interrupt_shadow(vcpu, 0); 7595 7596 pt_guest_enter(vmx); 7597 7598 atomic_switch_perf_msrs(vmx); 7599 if (intel_pmu_lbr_is_enabled(vcpu)) 7600 vmx_passthrough_lbr_msrs(vcpu); 7601 7602 if (enable_preemption_timer) 7603 vmx_update_hv_timer(vcpu, force_immediate_exit); 7604 else if (force_immediate_exit) 7605 smp_send_reschedule(vcpu->cpu); 7606 7607 kvm_wait_lapic_expire(vcpu); 7608 7609 /* The actual VMENTER/EXIT is in the .noinstr.text section. */ 7610 vmx_vcpu_enter_exit(vcpu, __vmx_vcpu_run_flags(vmx)); 7611 7612 /* All fields are clean at this point */ 7613 if (kvm_is_using_evmcs()) { 7614 current_evmcs->hv_clean_fields |= 7615 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL; 7616 7617 current_evmcs->hv_vp_id = kvm_hv_get_vpindex(vcpu); 7618 } 7619 7620 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */ 7621 if (vcpu->arch.host_debugctl) 7622 update_debugctlmsr(vcpu->arch.host_debugctl); 7623 7624 #ifndef CONFIG_X86_64 7625 /* 7626 * The sysexit path does not restore ds/es, so we must set them to 7627 * a reasonable value ourselves. 7628 * 7629 * We can't defer this to vmx_prepare_switch_to_host() since that 7630 * function may be executed in interrupt context, which saves and 7631 * restore segments around it, nullifying its effect. 7632 */ 7633 loadsegment(ds, __USER_DS); 7634 loadsegment(es, __USER_DS); 7635 #endif 7636 7637 pt_guest_exit(vmx); 7638 7639 if (is_guest_mode(vcpu)) { 7640 /* 7641 * Track VMLAUNCH/VMRESUME that have made past guest state 7642 * checking. 7643 */ 7644 if (vcpu->arch.nested_run_pending && 7645 !vmx_get_exit_reason(vcpu).failed_vmentry) 7646 ++vcpu->stat.nested_run; 7647 7648 vcpu->arch.nested_run_pending = 0; 7649 } 7650 7651 if (unlikely(vmx->fail)) 7652 return EXIT_FASTPATH_NONE; 7653 7654 trace_kvm_exit(vcpu, KVM_ISA_VMX); 7655 7656 if (unlikely(vmx_get_exit_reason(vcpu).failed_vmentry)) 7657 return EXIT_FASTPATH_NONE; 7658 7659 vmx->loaded_vmcs->launched = 1; 7660 7661 vmx_refresh_guest_perf_global_control(vcpu); 7662 7663 vmx_recover_nmi_blocking(vmx); 7664 vmx_complete_interrupts(vmx); 7665 7666 return vmx_exit_handlers_fastpath(vcpu, force_immediate_exit); 7667 } 7668 7669 void vmx_vcpu_free(struct kvm_vcpu *vcpu) 7670 { 7671 struct vcpu_vmx *vmx = to_vmx(vcpu); 7672 7673 if (enable_pml) 7674 vmx_destroy_pml_buffer(vmx); 7675 free_vpid(vmx->vpid); 7676 nested_vmx_free_vcpu(vcpu); 7677 free_loaded_vmcs(vmx->loaded_vmcs); 7678 free_page((unsigned long)vmx->ve_info); 7679 } 7680 7681 int vmx_vcpu_create(struct kvm_vcpu *vcpu) 7682 { 7683 struct vmx_uret_msr *tsx_ctrl; 7684 struct vcpu_vmx *vmx; 7685 int i, err; 7686 7687 BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0); 7688 vmx = to_vmx(vcpu); 7689 7690 INIT_LIST_HEAD(&vmx->vt.pi_wakeup_list); 7691 7692 err = -ENOMEM; 7693 7694 vmx->vpid = allocate_vpid(); 7695 7696 /* 7697 * If PML is turned on, failure on enabling PML just results in failure 7698 * of creating the vcpu, therefore we can simplify PML logic (by 7699 * avoiding dealing with cases, such as enabling PML partially on vcpus 7700 * for the guest), etc. 7701 */ 7702 if (enable_pml) { 7703 vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO); 7704 if (!vmx->pml_pg) 7705 goto free_vpid; 7706 } 7707 7708 for (i = 0; i < kvm_nr_uret_msrs; ++i) 7709 vmx->guest_uret_msrs[i].mask = -1ull; 7710 if (boot_cpu_has(X86_FEATURE_RTM)) { 7711 /* 7712 * TSX_CTRL_CPUID_CLEAR is handled in the CPUID interception. 7713 * Keep the host value unchanged to avoid changing CPUID bits 7714 * under the host kernel's feet. 7715 */ 7716 tsx_ctrl = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL); 7717 if (tsx_ctrl) 7718 tsx_ctrl->mask = ~(u64)TSX_CTRL_CPUID_CLEAR; 7719 } 7720 7721 err = alloc_loaded_vmcs(&vmx->vmcs01); 7722 if (err < 0) 7723 goto free_pml; 7724 7725 /* 7726 * Use Hyper-V 'Enlightened MSR Bitmap' feature when KVM runs as a 7727 * nested (L1) hypervisor and Hyper-V in L0 supports it. Enable the 7728 * feature only for vmcs01, KVM currently isn't equipped to realize any 7729 * performance benefits from enabling it for vmcs02. 7730 */ 7731 if (kvm_is_using_evmcs() && 7732 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) { 7733 struct hv_enlightened_vmcs *evmcs = (void *)vmx->vmcs01.vmcs; 7734 7735 evmcs->hv_enlightenments_control.msr_bitmap = 1; 7736 } 7737 7738 vmx->loaded_vmcs = &vmx->vmcs01; 7739 7740 if (cpu_need_virtualize_apic_accesses(vcpu)) { 7741 err = kvm_alloc_apic_access_page(vcpu->kvm); 7742 if (err) 7743 goto free_vmcs; 7744 } 7745 7746 if (enable_ept && !enable_unrestricted_guest) { 7747 err = init_rmode_identity_map(vcpu->kvm); 7748 if (err) 7749 goto free_vmcs; 7750 } 7751 7752 err = -ENOMEM; 7753 if (vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_EPT_VIOLATION_VE) { 7754 struct page *page; 7755 7756 BUILD_BUG_ON(sizeof(*vmx->ve_info) > PAGE_SIZE); 7757 7758 /* ve_info must be page aligned. */ 7759 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO); 7760 if (!page) 7761 goto free_vmcs; 7762 7763 vmx->ve_info = page_to_virt(page); 7764 } 7765 7766 if (vmx_can_use_ipiv(vcpu)) 7767 WRITE_ONCE(to_kvm_vmx(vcpu->kvm)->pid_table[vcpu->vcpu_id], 7768 __pa(&vmx->vt.pi_desc) | PID_TABLE_ENTRY_VALID); 7769 7770 return 0; 7771 7772 free_vmcs: 7773 free_loaded_vmcs(vmx->loaded_vmcs); 7774 free_pml: 7775 vmx_destroy_pml_buffer(vmx); 7776 free_vpid: 7777 free_vpid(vmx->vpid); 7778 return err; 7779 } 7780 7781 #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n" 7782 #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n" 7783 7784 int vmx_vm_init(struct kvm *kvm) 7785 { 7786 if (!ple_gap) 7787 kvm_disable_exits(kvm, KVM_X86_DISABLE_EXITS_PAUSE); 7788 7789 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) { 7790 switch (l1tf_mitigation) { 7791 case L1TF_MITIGATION_OFF: 7792 case L1TF_MITIGATION_FLUSH_NOWARN: 7793 /* 'I explicitly don't care' is set */ 7794 break; 7795 case L1TF_MITIGATION_AUTO: 7796 case L1TF_MITIGATION_FLUSH: 7797 case L1TF_MITIGATION_FLUSH_NOSMT: 7798 case L1TF_MITIGATION_FULL: 7799 /* 7800 * Warn upon starting the first VM in a potentially 7801 * insecure environment. 7802 */ 7803 if (sched_smt_active()) 7804 pr_warn_once(L1TF_MSG_SMT); 7805 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER) 7806 pr_warn_once(L1TF_MSG_L1D); 7807 break; 7808 case L1TF_MITIGATION_FULL_FORCE: 7809 /* Flush is enforced */ 7810 break; 7811 } 7812 } 7813 7814 if (enable_pml) 7815 kvm->arch.cpu_dirty_log_size = PML_LOG_NR_ENTRIES; 7816 return 0; 7817 } 7818 7819 static inline bool vmx_ignore_guest_pat(struct kvm *kvm) 7820 { 7821 /* 7822 * Non-coherent DMA devices need the guest to flush CPU properly. 7823 * In that case it is not possible to map all guest RAM as WB, so 7824 * always trust guest PAT. 7825 */ 7826 return !kvm_arch_has_noncoherent_dma(kvm) && 7827 kvm_check_has_quirk(kvm, KVM_X86_QUIRK_IGNORE_GUEST_PAT); 7828 } 7829 7830 u8 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio) 7831 { 7832 /* 7833 * Force UC for host MMIO regions, as allowing the guest to access MMIO 7834 * with cacheable accesses will result in Machine Checks. 7835 */ 7836 if (is_mmio) 7837 return MTRR_TYPE_UNCACHABLE << VMX_EPT_MT_EPTE_SHIFT; 7838 7839 /* Force WB if ignoring guest PAT */ 7840 if (vmx_ignore_guest_pat(vcpu->kvm)) 7841 return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT) | VMX_EPT_IPAT_BIT; 7842 7843 return (MTRR_TYPE_WRBACK << VMX_EPT_MT_EPTE_SHIFT); 7844 } 7845 7846 static void vmcs_set_secondary_exec_control(struct vcpu_vmx *vmx, u32 new_ctl) 7847 { 7848 /* 7849 * These bits in the secondary execution controls field 7850 * are dynamic, the others are mostly based on the hypervisor 7851 * architecture and the guest's CPUID. Do not touch the 7852 * dynamic bits. 7853 */ 7854 u32 mask = 7855 SECONDARY_EXEC_SHADOW_VMCS | 7856 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE | 7857 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES | 7858 SECONDARY_EXEC_DESC; 7859 7860 u32 cur_ctl = secondary_exec_controls_get(vmx); 7861 7862 secondary_exec_controls_set(vmx, (new_ctl & ~mask) | (cur_ctl & mask)); 7863 } 7864 7865 /* 7866 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits 7867 * (indicating "allowed-1") if they are supported in the guest's CPUID. 7868 */ 7869 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu) 7870 { 7871 struct vcpu_vmx *vmx = to_vmx(vcpu); 7872 struct kvm_cpuid_entry2 *entry; 7873 7874 vmx->nested.msrs.cr0_fixed1 = 0xffffffff; 7875 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE; 7876 7877 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \ 7878 if (entry && (entry->_reg & (_cpuid_mask))) \ 7879 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \ 7880 } while (0) 7881 7882 entry = kvm_find_cpuid_entry(vcpu, 0x1); 7883 cr4_fixed1_update(X86_CR4_VME, edx, feature_bit(VME)); 7884 cr4_fixed1_update(X86_CR4_PVI, edx, feature_bit(VME)); 7885 cr4_fixed1_update(X86_CR4_TSD, edx, feature_bit(TSC)); 7886 cr4_fixed1_update(X86_CR4_DE, edx, feature_bit(DE)); 7887 cr4_fixed1_update(X86_CR4_PSE, edx, feature_bit(PSE)); 7888 cr4_fixed1_update(X86_CR4_PAE, edx, feature_bit(PAE)); 7889 cr4_fixed1_update(X86_CR4_MCE, edx, feature_bit(MCE)); 7890 cr4_fixed1_update(X86_CR4_PGE, edx, feature_bit(PGE)); 7891 cr4_fixed1_update(X86_CR4_OSFXSR, edx, feature_bit(FXSR)); 7892 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM)); 7893 cr4_fixed1_update(X86_CR4_VMXE, ecx, feature_bit(VMX)); 7894 cr4_fixed1_update(X86_CR4_SMXE, ecx, feature_bit(SMX)); 7895 cr4_fixed1_update(X86_CR4_PCIDE, ecx, feature_bit(PCID)); 7896 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, feature_bit(XSAVE)); 7897 7898 entry = kvm_find_cpuid_entry_index(vcpu, 0x7, 0); 7899 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, feature_bit(FSGSBASE)); 7900 cr4_fixed1_update(X86_CR4_SMEP, ebx, feature_bit(SMEP)); 7901 cr4_fixed1_update(X86_CR4_SMAP, ebx, feature_bit(SMAP)); 7902 cr4_fixed1_update(X86_CR4_PKE, ecx, feature_bit(PKU)); 7903 cr4_fixed1_update(X86_CR4_UMIP, ecx, feature_bit(UMIP)); 7904 cr4_fixed1_update(X86_CR4_LA57, ecx, feature_bit(LA57)); 7905 cr4_fixed1_update(X86_CR4_CET, ecx, feature_bit(SHSTK)); 7906 cr4_fixed1_update(X86_CR4_CET, edx, feature_bit(IBT)); 7907 7908 entry = kvm_find_cpuid_entry_index(vcpu, 0x7, 1); 7909 cr4_fixed1_update(X86_CR4_LAM_SUP, eax, feature_bit(LAM)); 7910 7911 #undef cr4_fixed1_update 7912 } 7913 7914 static void update_intel_pt_cfg(struct kvm_vcpu *vcpu) 7915 { 7916 struct vcpu_vmx *vmx = to_vmx(vcpu); 7917 struct kvm_cpuid_entry2 *best = NULL; 7918 int i; 7919 7920 for (i = 0; i < PT_CPUID_LEAVES; i++) { 7921 best = kvm_find_cpuid_entry_index(vcpu, 0x14, i); 7922 if (!best) 7923 return; 7924 vmx->pt_desc.caps[CPUID_EAX + i*PT_CPUID_REGS_NUM] = best->eax; 7925 vmx->pt_desc.caps[CPUID_EBX + i*PT_CPUID_REGS_NUM] = best->ebx; 7926 vmx->pt_desc.caps[CPUID_ECX + i*PT_CPUID_REGS_NUM] = best->ecx; 7927 vmx->pt_desc.caps[CPUID_EDX + i*PT_CPUID_REGS_NUM] = best->edx; 7928 } 7929 7930 /* Get the number of configurable Address Ranges for filtering */ 7931 vmx->pt_desc.num_address_ranges = intel_pt_validate_cap(vmx->pt_desc.caps, 7932 PT_CAP_num_address_ranges); 7933 7934 /* Initialize and clear the no dependency bits */ 7935 vmx->pt_desc.ctl_bitmask = ~(RTIT_CTL_TRACEEN | RTIT_CTL_OS | 7936 RTIT_CTL_USR | RTIT_CTL_TSC_EN | RTIT_CTL_DISRETC | 7937 RTIT_CTL_BRANCH_EN); 7938 7939 /* 7940 * If CPUID.(EAX=14H,ECX=0):EBX[0]=1 CR3Filter can be set otherwise 7941 * will inject an #GP 7942 */ 7943 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_cr3_filtering)) 7944 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_CR3EN; 7945 7946 /* 7947 * If CPUID.(EAX=14H,ECX=0):EBX[1]=1 CYCEn, CycThresh and 7948 * PSBFreq can be set 7949 */ 7950 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc)) 7951 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_CYCLEACC | 7952 RTIT_CTL_CYC_THRESH | RTIT_CTL_PSB_FREQ); 7953 7954 /* 7955 * If CPUID.(EAX=14H,ECX=0):EBX[3]=1 MTCEn and MTCFreq can be set 7956 */ 7957 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc)) 7958 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_MTC_EN | 7959 RTIT_CTL_MTC_RANGE); 7960 7961 /* If CPUID.(EAX=14H,ECX=0):EBX[4]=1 FUPonPTW and PTWEn can be set */ 7962 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_ptwrite)) 7963 vmx->pt_desc.ctl_bitmask &= ~(RTIT_CTL_FUP_ON_PTW | 7964 RTIT_CTL_PTW_EN); 7965 7966 /* If CPUID.(EAX=14H,ECX=0):EBX[5]=1 PwrEvEn can be set */ 7967 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_power_event_trace)) 7968 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_PWR_EVT_EN; 7969 7970 /* If CPUID.(EAX=14H,ECX=0):ECX[0]=1 ToPA can be set */ 7971 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_topa_output)) 7972 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_TOPA; 7973 7974 /* If CPUID.(EAX=14H,ECX=0):ECX[3]=1 FabricEn can be set */ 7975 if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_output_subsys)) 7976 vmx->pt_desc.ctl_bitmask &= ~RTIT_CTL_FABRIC_EN; 7977 7978 /* unmask address range configure area */ 7979 for (i = 0; i < vmx->pt_desc.num_address_ranges; i++) 7980 vmx->pt_desc.ctl_bitmask &= ~(0xfULL << (32 + i * 4)); 7981 } 7982 7983 void vmx_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu) 7984 { 7985 struct vcpu_vmx *vmx = to_vmx(vcpu); 7986 7987 /* 7988 * XSAVES is effectively enabled if and only if XSAVE is also exposed 7989 * to the guest. XSAVES depends on CR4.OSXSAVE, and CR4.OSXSAVE can be 7990 * set if and only if XSAVE is supported. 7991 */ 7992 if (!guest_cpu_cap_has(vcpu, X86_FEATURE_XSAVE)) 7993 guest_cpu_cap_clear(vcpu, X86_FEATURE_XSAVES); 7994 7995 vmx_setup_uret_msrs(vmx); 7996 7997 if (cpu_has_secondary_exec_ctrls()) 7998 vmcs_set_secondary_exec_control(vmx, 7999 vmx_secondary_exec_control(vmx)); 8000 8001 if (guest_cpu_cap_has(vcpu, X86_FEATURE_VMX)) 8002 vmx->msr_ia32_feature_control_valid_bits |= 8003 FEAT_CTL_VMX_ENABLED_INSIDE_SMX | 8004 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX; 8005 else 8006 vmx->msr_ia32_feature_control_valid_bits &= 8007 ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX | 8008 FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX); 8009 8010 if (guest_cpu_cap_has(vcpu, X86_FEATURE_VMX)) 8011 nested_vmx_cr_fixed1_bits_update(vcpu); 8012 8013 if (boot_cpu_has(X86_FEATURE_INTEL_PT) && 8014 guest_cpu_cap_has(vcpu, X86_FEATURE_INTEL_PT)) 8015 update_intel_pt_cfg(vcpu); 8016 8017 if (boot_cpu_has(X86_FEATURE_RTM)) { 8018 struct vmx_uret_msr *msr; 8019 msr = vmx_find_uret_msr(vmx, MSR_IA32_TSX_CTRL); 8020 if (msr) { 8021 bool enabled = guest_cpu_cap_has(vcpu, X86_FEATURE_RTM); 8022 vmx_set_guest_uret_msr(vmx, msr, enabled ? 0 : TSX_CTRL_RTM_DISABLE); 8023 } 8024 } 8025 8026 set_cr4_guest_host_mask(vmx); 8027 8028 vmx_write_encls_bitmap(vcpu, NULL); 8029 if (guest_cpu_cap_has(vcpu, X86_FEATURE_SGX)) 8030 vmx->msr_ia32_feature_control_valid_bits |= FEAT_CTL_SGX_ENABLED; 8031 else 8032 vmx->msr_ia32_feature_control_valid_bits &= ~FEAT_CTL_SGX_ENABLED; 8033 8034 if (guest_cpu_cap_has(vcpu, X86_FEATURE_SGX_LC)) 8035 vmx->msr_ia32_feature_control_valid_bits |= 8036 FEAT_CTL_SGX_LC_ENABLED; 8037 else 8038 vmx->msr_ia32_feature_control_valid_bits &= 8039 ~FEAT_CTL_SGX_LC_ENABLED; 8040 8041 /* Refresh #PF interception to account for MAXPHYADDR changes. */ 8042 vmx_update_exception_bitmap(vcpu); 8043 } 8044 8045 static __init u64 vmx_get_perf_capabilities(void) 8046 { 8047 u64 perf_cap = PERF_CAP_FW_WRITES; 8048 u64 host_perf_cap = 0; 8049 8050 if (!enable_pmu) 8051 return 0; 8052 8053 if (boot_cpu_has(X86_FEATURE_PDCM)) 8054 rdmsrq(MSR_IA32_PERF_CAPABILITIES, host_perf_cap); 8055 8056 if (!cpu_feature_enabled(X86_FEATURE_ARCH_LBR) && 8057 !enable_mediated_pmu) { 8058 x86_perf_get_lbr(&vmx_lbr_caps); 8059 8060 /* 8061 * KVM requires LBR callstack support, as the overhead due to 8062 * context switching LBRs without said support is too high. 8063 * See intel_pmu_create_guest_lbr_event() for more info. 8064 */ 8065 if (!vmx_lbr_caps.has_callstack) 8066 memset(&vmx_lbr_caps, 0, sizeof(vmx_lbr_caps)); 8067 else if (vmx_lbr_caps.nr) 8068 perf_cap |= host_perf_cap & PERF_CAP_LBR_FMT; 8069 } 8070 8071 if (vmx_pebs_supported()) { 8072 perf_cap |= host_perf_cap & PERF_CAP_PEBS_MASK; 8073 8074 /* 8075 * Disallow adaptive PEBS as it is functionally broken, can be 8076 * used by the guest to read *host* LBRs, and can be used to 8077 * bypass userspace event filters. To correctly and safely 8078 * support adaptive PEBS, KVM needs to: 8079 * 8080 * 1. Account for the ADAPTIVE flag when (re)programming fixed 8081 * counters. 8082 * 8083 * 2. Gain support from perf (or take direct control of counter 8084 * programming) to support events without adaptive PEBS 8085 * enabled for the hardware counter. 8086 * 8087 * 3. Ensure LBR MSRs cannot hold host data on VM-Entry with 8088 * adaptive PEBS enabled and MSR_PEBS_DATA_CFG.LBRS=1. 8089 * 8090 * 4. Document which PMU events are effectively exposed to the 8091 * guest via adaptive PEBS, and make adaptive PEBS mutually 8092 * exclusive with KVM_SET_PMU_EVENT_FILTER if necessary. 8093 */ 8094 perf_cap &= ~PERF_CAP_PEBS_BASELINE; 8095 } 8096 8097 return perf_cap; 8098 } 8099 8100 static __init void vmx_set_cpu_caps(void) 8101 { 8102 kvm_initialize_cpu_caps(); 8103 8104 /* CPUID 0x1 */ 8105 if (nested) 8106 kvm_cpu_cap_set(X86_FEATURE_VMX); 8107 8108 /* CPUID 0x7 */ 8109 if (kvm_mpx_supported()) 8110 kvm_cpu_cap_check_and_set(X86_FEATURE_MPX); 8111 if (!cpu_has_vmx_invpcid()) 8112 kvm_cpu_cap_clear(X86_FEATURE_INVPCID); 8113 if (vmx_pt_mode_is_host_guest()) 8114 kvm_cpu_cap_check_and_set(X86_FEATURE_INTEL_PT); 8115 if (vmx_pebs_supported()) { 8116 kvm_cpu_cap_check_and_set(X86_FEATURE_DS); 8117 kvm_cpu_cap_check_and_set(X86_FEATURE_DTES64); 8118 } 8119 8120 if (!enable_pmu) 8121 kvm_cpu_cap_clear(X86_FEATURE_PDCM); 8122 kvm_caps.supported_perf_cap = vmx_get_perf_capabilities(); 8123 8124 if (!enable_sgx) { 8125 kvm_cpu_cap_clear(X86_FEATURE_SGX); 8126 kvm_cpu_cap_clear(X86_FEATURE_SGX_LC); 8127 kvm_cpu_cap_clear(X86_FEATURE_SGX1); 8128 kvm_cpu_cap_clear(X86_FEATURE_SGX2); 8129 kvm_cpu_cap_clear(X86_FEATURE_SGX_EDECCSSA); 8130 } 8131 8132 if (vmx_umip_emulated()) 8133 kvm_cpu_cap_set(X86_FEATURE_UMIP); 8134 8135 /* CPUID 0xD.1 */ 8136 if (!cpu_has_vmx_xsaves()) 8137 kvm_cpu_cap_clear(X86_FEATURE_XSAVES); 8138 8139 /* CPUID 0x80000001 and 0x7 (RDPID) */ 8140 if (!cpu_has_vmx_rdtscp()) { 8141 kvm_cpu_cap_clear(X86_FEATURE_RDTSCP); 8142 kvm_cpu_cap_clear(X86_FEATURE_RDPID); 8143 } 8144 8145 if (cpu_has_vmx_waitpkg()) 8146 kvm_cpu_cap_check_and_set(X86_FEATURE_WAITPKG); 8147 8148 /* 8149 * Disable CET if unrestricted_guest is unsupported as KVM doesn't 8150 * enforce CET HW behaviors in emulator. On platforms with 8151 * VMX_BASIC[bit56] == 0, inject #CP at VMX entry with error code 8152 * fails, so disable CET in this case too. 8153 */ 8154 if (!enable_cet || !enable_unrestricted_guest || 8155 !cpu_has_vmx_basic_no_hw_errcode_cc()) { 8156 kvm_cpu_cap_clear(X86_FEATURE_SHSTK); 8157 kvm_cpu_cap_clear(X86_FEATURE_IBT); 8158 } 8159 8160 kvm_setup_xss_caps(); 8161 kvm_finalize_cpu_caps(); 8162 } 8163 8164 static bool vmx_is_io_intercepted(struct kvm_vcpu *vcpu, 8165 struct x86_instruction_info *info, 8166 unsigned long *exit_qualification) 8167 { 8168 struct vmcs12 *vmcs12 = get_vmcs12(vcpu); 8169 unsigned short port; 8170 int size; 8171 bool imm; 8172 8173 /* 8174 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction 8175 * VM-exits depend on the 'unconditional IO exiting' VM-execution 8176 * control. 8177 * 8178 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps. 8179 */ 8180 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS)) 8181 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING); 8182 8183 if (info->intercept == x86_intercept_in || 8184 info->intercept == x86_intercept_ins) { 8185 port = info->src_val; 8186 size = info->dst_bytes; 8187 imm = info->src_type == OP_IMM; 8188 } else { 8189 port = info->dst_val; 8190 size = info->src_bytes; 8191 imm = info->dst_type == OP_IMM; 8192 } 8193 8194 8195 *exit_qualification = ((unsigned long)port << 16) | (size - 1); 8196 8197 if (info->intercept == x86_intercept_ins || 8198 info->intercept == x86_intercept_outs) 8199 *exit_qualification |= BIT(4); 8200 8201 if (info->rep_prefix) 8202 *exit_qualification |= BIT(5); 8203 8204 if (imm) 8205 *exit_qualification |= BIT(6); 8206 8207 return nested_vmx_check_io_bitmaps(vcpu, port, size); 8208 } 8209 8210 int vmx_check_intercept(struct kvm_vcpu *vcpu, 8211 struct x86_instruction_info *info, 8212 enum x86_intercept_stage stage, 8213 struct x86_exception *exception) 8214 { 8215 struct vmcs12 *vmcs12 = get_vmcs12(vcpu); 8216 unsigned long exit_qualification = 0; 8217 u32 vm_exit_reason; 8218 u64 exit_insn_len; 8219 8220 switch (info->intercept) { 8221 case x86_intercept_rdpid: 8222 /* 8223 * RDPID causes #UD if not enabled through secondary execution 8224 * controls (ENABLE_RDTSCP). Note, the implicit MSR access to 8225 * TSC_AUX is NOT subject to interception, i.e. checking only 8226 * the dedicated execution control is architecturally correct. 8227 */ 8228 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_RDTSCP)) { 8229 exception->vector = UD_VECTOR; 8230 exception->error_code_valid = false; 8231 return X86EMUL_PROPAGATE_FAULT; 8232 } 8233 return X86EMUL_CONTINUE; 8234 8235 case x86_intercept_in: 8236 case x86_intercept_ins: 8237 case x86_intercept_out: 8238 case x86_intercept_outs: 8239 if (!vmx_is_io_intercepted(vcpu, info, &exit_qualification)) 8240 return X86EMUL_CONTINUE; 8241 8242 vm_exit_reason = EXIT_REASON_IO_INSTRUCTION; 8243 break; 8244 8245 case x86_intercept_lgdt: 8246 case x86_intercept_lidt: 8247 case x86_intercept_lldt: 8248 case x86_intercept_ltr: 8249 case x86_intercept_sgdt: 8250 case x86_intercept_sidt: 8251 case x86_intercept_sldt: 8252 case x86_intercept_str: 8253 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC)) 8254 return X86EMUL_CONTINUE; 8255 8256 if (info->intercept == x86_intercept_lldt || 8257 info->intercept == x86_intercept_ltr || 8258 info->intercept == x86_intercept_sldt || 8259 info->intercept == x86_intercept_str) 8260 vm_exit_reason = EXIT_REASON_LDTR_TR; 8261 else 8262 vm_exit_reason = EXIT_REASON_GDTR_IDTR; 8263 /* 8264 * FIXME: Decode the ModR/M to generate the correct exit 8265 * qualification for memory operands. 8266 */ 8267 break; 8268 8269 case x86_intercept_hlt: 8270 if (!nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING)) 8271 return X86EMUL_CONTINUE; 8272 8273 vm_exit_reason = EXIT_REASON_HLT; 8274 break; 8275 8276 case x86_intercept_pause: 8277 /* 8278 * PAUSE is a single-byte NOP with a REPE prefix, i.e. collides 8279 * with vanilla NOPs in the emulator. Apply the interception 8280 * check only to actual PAUSE instructions. Don't check 8281 * PAUSE-loop-exiting, software can't expect a given PAUSE to 8282 * exit, i.e. KVM is within its rights to allow L2 to execute 8283 * the PAUSE. 8284 */ 8285 if ((info->rep_prefix != REPE_PREFIX) || 8286 !nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING)) 8287 return X86EMUL_CONTINUE; 8288 8289 vm_exit_reason = EXIT_REASON_PAUSE_INSTRUCTION; 8290 break; 8291 8292 /* TODO: check more intercepts... */ 8293 default: 8294 return X86EMUL_UNHANDLEABLE; 8295 } 8296 8297 exit_insn_len = abs_diff((s64)info->next_rip, (s64)info->rip); 8298 if (!exit_insn_len || exit_insn_len > X86_MAX_INSTRUCTION_LENGTH) 8299 return X86EMUL_UNHANDLEABLE; 8300 8301 __nested_vmx_vmexit(vcpu, vm_exit_reason, 0, exit_qualification, 8302 exit_insn_len); 8303 return X86EMUL_INTERCEPTED; 8304 } 8305 8306 #ifdef CONFIG_X86_64 8307 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */ 8308 static inline int u64_shl_div_u64(u64 a, unsigned int shift, 8309 u64 divisor, u64 *result) 8310 { 8311 u64 low = a << shift, high = a >> (64 - shift); 8312 8313 /* To avoid the overflow on divq */ 8314 if (high >= divisor) 8315 return 1; 8316 8317 /* Low hold the result, high hold rem which is discarded */ 8318 asm("divq %2\n\t" : "=a" (low), "=d" (high) : 8319 "rm" (divisor), "0" (low), "1" (high)); 8320 *result = low; 8321 8322 return 0; 8323 } 8324 8325 int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc, 8326 bool *expired) 8327 { 8328 struct vcpu_vmx *vmx; 8329 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles; 8330 struct kvm_timer *ktimer = &vcpu->arch.apic->lapic_timer; 8331 8332 vmx = to_vmx(vcpu); 8333 tscl = rdtsc(); 8334 guest_tscl = kvm_read_l1_tsc(vcpu, tscl); 8335 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl; 8336 lapic_timer_advance_cycles = nsec_to_cycles(vcpu, 8337 ktimer->timer_advance_ns); 8338 8339 if (delta_tsc > lapic_timer_advance_cycles) 8340 delta_tsc -= lapic_timer_advance_cycles; 8341 else 8342 delta_tsc = 0; 8343 8344 /* Convert to host delta tsc if tsc scaling is enabled */ 8345 if (vcpu->arch.l1_tsc_scaling_ratio != kvm_caps.default_tsc_scaling_ratio && 8346 delta_tsc && u64_shl_div_u64(delta_tsc, 8347 kvm_caps.tsc_scaling_ratio_frac_bits, 8348 vcpu->arch.l1_tsc_scaling_ratio, &delta_tsc)) 8349 return -ERANGE; 8350 8351 /* 8352 * If the delta tsc can't fit in the 32 bit after the multi shift, 8353 * we can't use the preemption timer. 8354 * It's possible that it fits on later vmentries, but checking 8355 * on every vmentry is costly so we just use an hrtimer. 8356 */ 8357 if (delta_tsc >> (cpu_preemption_timer_multi + 32)) 8358 return -ERANGE; 8359 8360 vmx->hv_deadline_tsc = tscl + delta_tsc; 8361 *expired = !delta_tsc; 8362 return 0; 8363 } 8364 8365 void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu) 8366 { 8367 to_vmx(vcpu)->hv_deadline_tsc = -1; 8368 } 8369 #endif 8370 8371 void vmx_update_cpu_dirty_logging(struct kvm_vcpu *vcpu) 8372 { 8373 struct vcpu_vmx *vmx = to_vmx(vcpu); 8374 8375 if (WARN_ON_ONCE(!enable_pml)) 8376 return; 8377 8378 guard(vmx_vmcs01)(vcpu); 8379 8380 /* 8381 * Note, nr_memslots_dirty_logging can be changed concurrent with this 8382 * code, but in that case another update request will be made and so 8383 * the guest will never run with a stale PML value. 8384 */ 8385 if (atomic_read(&vcpu->kvm->nr_memslots_dirty_logging)) 8386 secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_ENABLE_PML); 8387 else 8388 secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_ENABLE_PML); 8389 } 8390 8391 void vmx_setup_mce(struct kvm_vcpu *vcpu) 8392 { 8393 if (vcpu->arch.mcg_cap & MCG_LMCE_P) 8394 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |= 8395 FEAT_CTL_LMCE_ENABLED; 8396 else 8397 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &= 8398 ~FEAT_CTL_LMCE_ENABLED; 8399 } 8400 8401 #ifdef CONFIG_KVM_SMM 8402 int vmx_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection) 8403 { 8404 /* we need a nested vmexit to enter SMM, postpone if run is pending */ 8405 if (vcpu->arch.nested_run_pending) 8406 return -EBUSY; 8407 return !is_smm(vcpu); 8408 } 8409 8410 int vmx_enter_smm(struct kvm_vcpu *vcpu, union kvm_smram *smram) 8411 { 8412 struct vcpu_vmx *vmx = to_vmx(vcpu); 8413 8414 /* 8415 * TODO: Implement custom flows for forcing the vCPU out/in of L2 on 8416 * SMI and RSM. Using the common VM-Exit + VM-Enter routines is wrong 8417 * SMI and RSM only modify state that is saved and restored via SMRAM. 8418 * E.g. most MSRs are left untouched, but many are modified by VM-Exit 8419 * and VM-Enter, and thus L2's values may be corrupted on SMI+RSM. 8420 */ 8421 vmx->nested.smm.guest_mode = is_guest_mode(vcpu); 8422 if (vmx->nested.smm.guest_mode) 8423 nested_vmx_vmexit(vcpu, -1, 0, 0); 8424 8425 vmx->nested.smm.vmxon = vmx->nested.vmxon; 8426 vmx->nested.vmxon = false; 8427 vmx_clear_hlt(vcpu); 8428 return 0; 8429 } 8430 8431 int vmx_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram) 8432 { 8433 struct vcpu_vmx *vmx = to_vmx(vcpu); 8434 int ret; 8435 8436 if (vmx->nested.smm.vmxon) { 8437 vmx->nested.vmxon = true; 8438 vmx->nested.smm.vmxon = false; 8439 } 8440 8441 if (vmx->nested.smm.guest_mode) { 8442 /* Triple fault if the state is invalid. */ 8443 if (nested_vmx_check_restored_vmcs12(vcpu) < 0) 8444 return 1; 8445 8446 ret = nested_vmx_enter_non_root_mode(vcpu, false); 8447 if (ret != NVMX_VMENTRY_SUCCESS) 8448 return 1; 8449 8450 vcpu->arch.nested_run_pending = KVM_NESTED_RUN_PENDING; 8451 vmx->nested.smm.guest_mode = false; 8452 } 8453 return 0; 8454 } 8455 8456 void vmx_enable_smi_window(struct kvm_vcpu *vcpu) 8457 { 8458 /* RSM will cause a vmexit anyway. */ 8459 } 8460 #endif 8461 8462 bool vmx_apic_init_signal_blocked(struct kvm_vcpu *vcpu) 8463 { 8464 return to_vmx(vcpu)->nested.vmxon && !is_guest_mode(vcpu); 8465 } 8466 8467 void vmx_migrate_timers(struct kvm_vcpu *vcpu) 8468 { 8469 if (is_guest_mode(vcpu)) { 8470 struct hrtimer *timer = &to_vmx(vcpu)->nested.preemption_timer; 8471 8472 if (hrtimer_try_to_cancel(timer) == 1) 8473 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED); 8474 } 8475 } 8476 8477 void vmx_hardware_unsetup(void) 8478 { 8479 kvm_set_posted_intr_wakeup_handler(NULL); 8480 8481 if (nested) 8482 nested_vmx_hardware_unsetup(); 8483 } 8484 8485 void vmx_vm_destroy(struct kvm *kvm) 8486 { 8487 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm); 8488 8489 free_pages((unsigned long)kvm_vmx->pid_table, vmx_get_pid_table_order(kvm)); 8490 } 8491 8492 /* 8493 * Note, the SDM states that the linear address is masked *after* the modified 8494 * canonicality check, whereas KVM masks (untags) the address and then performs 8495 * a "normal" canonicality check. Functionally, the two methods are identical, 8496 * and when the masking occurs relative to the canonicality check isn't visible 8497 * to software, i.e. KVM's behavior doesn't violate the SDM. 8498 */ 8499 gva_t vmx_get_untagged_addr(struct kvm_vcpu *vcpu, gva_t gva, unsigned int flags) 8500 { 8501 int lam_bit; 8502 unsigned long cr3_bits; 8503 8504 if (flags & (X86EMUL_F_FETCH | X86EMUL_F_IMPLICIT | X86EMUL_F_INVLPG)) 8505 return gva; 8506 8507 if (!is_64_bit_mode(vcpu)) 8508 return gva; 8509 8510 /* 8511 * Bit 63 determines if the address should be treated as user address 8512 * or a supervisor address. 8513 */ 8514 if (!(gva & BIT_ULL(63))) { 8515 cr3_bits = kvm_get_active_cr3_lam_bits(vcpu); 8516 if (!(cr3_bits & (X86_CR3_LAM_U57 | X86_CR3_LAM_U48))) 8517 return gva; 8518 8519 /* LAM_U48 is ignored if LAM_U57 is set. */ 8520 lam_bit = cr3_bits & X86_CR3_LAM_U57 ? 56 : 47; 8521 } else { 8522 if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_LAM_SUP)) 8523 return gva; 8524 8525 lam_bit = kvm_is_cr4_bit_set(vcpu, X86_CR4_LA57) ? 56 : 47; 8526 } 8527 8528 /* 8529 * Untag the address by sign-extending the lam_bit, but NOT to bit 63. 8530 * Bit 63 is retained from the raw virtual address so that untagging 8531 * doesn't change a user access to a supervisor access, and vice versa. 8532 */ 8533 return (sign_extend64(gva, lam_bit) & ~BIT_ULL(63)) | (gva & BIT_ULL(63)); 8534 } 8535 8536 static unsigned int vmx_handle_intel_pt_intr(void) 8537 { 8538 struct kvm_vcpu *vcpu = kvm_get_running_vcpu(); 8539 8540 /* '0' on failure so that the !PT case can use a RET0 static call. */ 8541 if (!vcpu || !kvm_handling_nmi_from_guest(vcpu)) 8542 return 0; 8543 8544 kvm_make_request(KVM_REQ_PMI, vcpu); 8545 __set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT, 8546 (unsigned long *)&vcpu->arch.pmu.global_status); 8547 return 1; 8548 } 8549 8550 static __init void vmx_setup_user_return_msrs(void) 8551 { 8552 8553 /* 8554 * Though SYSCALL is only supported in 64-bit mode on Intel CPUs, kvm 8555 * will emulate SYSCALL in legacy mode if the vendor string in guest 8556 * CPUID.0:{EBX,ECX,EDX} is "AuthenticAMD" or "AMDisbetter!" To 8557 * support this emulation, MSR_STAR is included in the list for i386, 8558 * but is never loaded into hardware. MSR_CSTAR is also never loaded 8559 * into hardware and is here purely for emulation purposes. 8560 */ 8561 const u32 vmx_uret_msrs_list[] = { 8562 #ifdef CONFIG_X86_64 8563 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR, 8564 #endif 8565 MSR_EFER, MSR_TSC_AUX, MSR_STAR, 8566 MSR_IA32_TSX_CTRL, 8567 }; 8568 int i; 8569 8570 BUILD_BUG_ON(ARRAY_SIZE(vmx_uret_msrs_list) != MAX_NR_USER_RETURN_MSRS); 8571 8572 for (i = 0; i < ARRAY_SIZE(vmx_uret_msrs_list); ++i) 8573 kvm_add_user_return_msr(vmx_uret_msrs_list[i]); 8574 } 8575 8576 static void __init vmx_setup_me_spte_mask(void) 8577 { 8578 u64 me_mask = 0; 8579 8580 /* 8581 * On pre-MKTME system, boot_cpu_data.x86_phys_bits equals to 8582 * kvm_host.maxphyaddr. On MKTME and/or TDX capable systems, 8583 * boot_cpu_data.x86_phys_bits holds the actual physical address 8584 * w/o the KeyID bits, and kvm_host.maxphyaddr equals to 8585 * MAXPHYADDR reported by CPUID. Those bits between are KeyID bits. 8586 */ 8587 if (boot_cpu_data.x86_phys_bits != kvm_host.maxphyaddr) 8588 me_mask = rsvd_bits(boot_cpu_data.x86_phys_bits, 8589 kvm_host.maxphyaddr - 1); 8590 8591 /* 8592 * Unlike SME, host kernel doesn't support setting up any 8593 * MKTME KeyID on Intel platforms. No memory encryption 8594 * bits should be included into the SPTE. 8595 */ 8596 kvm_mmu_set_me_spte_mask(0, me_mask); 8597 } 8598 8599 __init int vmx_hardware_setup(void) 8600 { 8601 unsigned long host_bndcfgs; 8602 struct desc_ptr dt; 8603 int r; 8604 8605 store_idt(&dt); 8606 host_idt_base = dt.address; 8607 8608 vmx_setup_user_return_msrs(); 8609 8610 if (boot_cpu_has(X86_FEATURE_MPX)) { 8611 rdmsrq(MSR_IA32_BNDCFGS, host_bndcfgs); 8612 WARN_ONCE(host_bndcfgs, "BNDCFGS in host will be lost"); 8613 } 8614 8615 if (!cpu_has_vmx_mpx()) 8616 kvm_caps.supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS | 8617 XFEATURE_MASK_BNDCSR); 8618 8619 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() || 8620 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global())) 8621 enable_vpid = 0; 8622 8623 if (!cpu_has_vmx_ept() || 8624 !cpu_has_vmx_ept_4levels() || 8625 !cpu_has_vmx_ept_mt_wb() || 8626 !cpu_has_vmx_invept_global()) 8627 enable_ept = 0; 8628 8629 if (!cpu_has_load_cet_ctrl()) 8630 enable_cet = 0; 8631 8632 /* NX support is required for shadow paging. */ 8633 if (!enable_ept && !boot_cpu_has(X86_FEATURE_NX)) { 8634 pr_err_ratelimited("NX (Execute Disable) not supported\n"); 8635 return -EOPNOTSUPP; 8636 } 8637 8638 /* 8639 * Shadow paging doesn't have a (further) performance penalty 8640 * from GUEST_MAXPHYADDR < HOST_MAXPHYADDR so enable it 8641 * by default 8642 */ 8643 if (!enable_ept) 8644 allow_smaller_maxphyaddr = true; 8645 8646 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept) 8647 enable_ept_ad_bits = 0; 8648 8649 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept) 8650 enable_unrestricted_guest = 0; 8651 8652 if (!cpu_has_vmx_flexpriority()) 8653 flexpriority_enabled = 0; 8654 8655 if (!cpu_has_virtual_nmis()) 8656 enable_vnmi = 0; 8657 8658 #ifdef CONFIG_X86_SGX_KVM 8659 if (!cpu_has_vmx_encls_vmexit()) 8660 enable_sgx = false; 8661 #endif 8662 8663 /* 8664 * set_apic_access_page_addr() is used to reload apic access 8665 * page upon invalidation. No need to do anything if not 8666 * using the APIC_ACCESS_ADDR VMCS field. 8667 */ 8668 if (!flexpriority_enabled) 8669 vt_x86_ops.set_apic_access_page_addr = NULL; 8670 8671 if (!cpu_has_vmx_tpr_shadow()) 8672 vt_x86_ops.update_cr8_intercept = NULL; 8673 8674 #if IS_ENABLED(CONFIG_HYPERV) 8675 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH 8676 && enable_ept) { 8677 vt_x86_ops.flush_remote_tlbs = hv_flush_remote_tlbs; 8678 vt_x86_ops.flush_remote_tlbs_range = hv_flush_remote_tlbs_range; 8679 } 8680 #endif 8681 8682 if (!cpu_has_vmx_ple()) { 8683 ple_gap = 0; 8684 ple_window = 0; 8685 ple_window_grow = 0; 8686 ple_window_max = 0; 8687 ple_window_shrink = 0; 8688 } 8689 8690 if (!cpu_has_vmx_apicv()) 8691 enable_apicv = 0; 8692 if (!enable_apicv) 8693 vt_x86_ops.sync_pir_to_irr = NULL; 8694 8695 if (!enable_apicv || !cpu_has_vmx_ipiv()) 8696 enable_ipiv = false; 8697 8698 if (cpu_has_vmx_tsc_scaling()) 8699 kvm_caps.has_tsc_control = true; 8700 8701 kvm_caps.max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX; 8702 kvm_caps.tsc_scaling_ratio_frac_bits = 48; 8703 kvm_caps.has_bus_lock_exit = cpu_has_vmx_bus_lock_detection(); 8704 kvm_caps.has_notify_vmexit = cpu_has_notify_vmexit(); 8705 8706 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */ 8707 8708 if (enable_ept) 8709 kvm_mmu_set_ept_masks(enable_ept_ad_bits, 8710 cpu_has_vmx_ept_execute_only()); 8711 else 8712 vt_x86_ops.get_mt_mask = NULL; 8713 8714 /* 8715 * Setup shadow_me_value/shadow_me_mask to include MKTME KeyID 8716 * bits to shadow_zero_check. 8717 */ 8718 vmx_setup_me_spte_mask(); 8719 8720 kvm_configure_mmu(enable_ept, 0, vmx_get_max_ept_level(), 8721 ept_caps_to_lpage_level(vmx_capability.ept)); 8722 8723 /* 8724 * Only enable PML when hardware supports PML feature, and both EPT 8725 * and EPT A/D bit features are enabled -- PML depends on them to work. 8726 */ 8727 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml()) 8728 enable_pml = 0; 8729 8730 if (!cpu_has_vmx_preemption_timer()) 8731 enable_preemption_timer = false; 8732 8733 if (enable_preemption_timer) { 8734 u64 use_timer_freq = 5000ULL * 1000 * 1000; 8735 8736 cpu_preemption_timer_multi = 8737 vmx_misc_preemption_timer_rate(vmcs_config.misc); 8738 8739 if (tsc_khz) 8740 use_timer_freq = (u64)tsc_khz * 1000; 8741 use_timer_freq >>= cpu_preemption_timer_multi; 8742 8743 /* 8744 * KVM "disables" the preemption timer by setting it to its max 8745 * value. Don't use the timer if it might cause spurious exits 8746 * at a rate faster than 0.1 Hz (of uninterrupted guest time). 8747 */ 8748 if (use_timer_freq > 0xffffffffu / 10) 8749 enable_preemption_timer = false; 8750 } 8751 8752 if (!enable_preemption_timer) { 8753 vt_x86_ops.set_hv_timer = NULL; 8754 vt_x86_ops.cancel_hv_timer = NULL; 8755 } 8756 8757 kvm_caps.supported_mce_cap |= MCG_LMCE_P; 8758 kvm_caps.supported_mce_cap |= MCG_CMCI_P; 8759 8760 if (pt_mode != PT_MODE_SYSTEM && pt_mode != PT_MODE_HOST_GUEST) 8761 return -EINVAL; 8762 if (!enable_ept || !enable_pmu || !cpu_has_vmx_intel_pt()) 8763 pt_mode = PT_MODE_SYSTEM; 8764 if (pt_mode == PT_MODE_HOST_GUEST) 8765 vt_init_ops.handle_intel_pt_intr = vmx_handle_intel_pt_intr; 8766 else 8767 vt_init_ops.handle_intel_pt_intr = NULL; 8768 8769 setup_default_sgx_lepubkeyhash(); 8770 8771 vmx_set_cpu_caps(); 8772 8773 /* 8774 * Configure nested capabilities after core CPU capabilities so that 8775 * nested support can be conditional on base support, e.g. so that KVM 8776 * can hide/show features based on kvm_cpu_cap_has(). 8777 */ 8778 if (nested) { 8779 r = nested_vmx_hardware_setup(kvm_vmx_exit_handlers); 8780 if (r) 8781 return r; 8782 } 8783 8784 kvm_set_posted_intr_wakeup_handler(pi_wakeup_handler); 8785 8786 /* 8787 * On Intel CPUs that lack self-snoop feature, letting the guest control 8788 * memory types may result in unexpected behavior. So always ignore guest 8789 * PAT on those CPUs and map VM as writeback, not allowing userspace to 8790 * disable the quirk. 8791 * 8792 * On certain Intel CPUs (e.g. SPR, ICX), though self-snoop feature is 8793 * supported, UC is slow enough to cause issues with some older guests (e.g. 8794 * an old version of bochs driver uses ioremap() instead of ioremap_wc() to 8795 * map the video RAM, causing wayland desktop to fail to get started 8796 * correctly). To avoid breaking those older guests that rely on KVM to force 8797 * memory type to WB, provide KVM_X86_QUIRK_IGNORE_GUEST_PAT to preserve the 8798 * safer (for performance) default behavior. 8799 * 8800 * On top of this, non-coherent DMA devices need the guest to flush CPU 8801 * caches properly. This also requires honoring guest PAT, and is forced 8802 * independent of the quirk in vmx_ignore_guest_pat(). 8803 */ 8804 if (!static_cpu_has(X86_FEATURE_SELFSNOOP)) 8805 kvm_caps.supported_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT; 8806 8807 kvm_caps.inapplicable_quirks &= ~KVM_X86_QUIRK_IGNORE_GUEST_PAT; 8808 8809 return 0; 8810 } 8811 8812 void vmx_exit(void) 8813 { 8814 allow_smaller_maxphyaddr = false; 8815 8816 vmx_cleanup_l1d_flush(); 8817 8818 kvm_x86_vendor_exit(); 8819 } 8820 8821 int __init vmx_init(void) 8822 { 8823 int r, cpu; 8824 8825 KVM_SANITY_CHECK_VM_STRUCT_SIZE(kvm_vmx); 8826 8827 if (!kvm_is_vmx_supported()) 8828 return -EOPNOTSUPP; 8829 8830 /* 8831 * Note, VMCS and eVMCS configuration only touch VMX knobs/variables, 8832 * i.e. there's nothing to unwind if a later step fails. 8833 */ 8834 hv_init_evmcs(); 8835 8836 /* 8837 * Parse the VMCS config and VMX capabilities before anything else, so 8838 * that the information is available to all setup flows. 8839 */ 8840 if (setup_vmcs_config(&vmcs_config, &vmx_capability) < 0) 8841 return -EIO; 8842 8843 r = kvm_x86_vendor_init(&vt_init_ops); 8844 if (r) 8845 return r; 8846 8847 /* Must be called after common x86 init so enable_ept is setup. */ 8848 r = vmx_setup_l1d_flush(); 8849 if (r) 8850 goto err_l1d_flush; 8851 8852 for_each_possible_cpu(cpu) { 8853 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu)); 8854 8855 pi_init_cpu(cpu); 8856 } 8857 8858 vmx_check_vmcs12_offsets(); 8859 8860 return 0; 8861 8862 err_l1d_flush: 8863 kvm_x86_vendor_exit(); 8864 return r; 8865 } 8866