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