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