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