linux/arch/x86/kvm/vmx/vmx.c
<<
>>
Prefs
   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
  16#include <linux/highmem.h>
  17#include <linux/hrtimer.h>
  18#include <linux/kernel.h>
  19#include <linux/kvm_host.h>
  20#include <linux/module.h>
  21#include <linux/moduleparam.h>
  22#include <linux/mod_devicetable.h>
  23#include <linux/mm.h>
  24#include <linux/objtool.h>
  25#include <linux/sched.h>
  26#include <linux/sched/smt.h>
  27#include <linux/slab.h>
  28#include <linux/tboot.h>
  29#include <linux/trace_events.h>
  30#include <linux/entry-kvm.h>
  31
  32#include <asm/apic.h>
  33#include <asm/asm.h>
  34#include <asm/cpu.h>
  35#include <asm/cpu_device_id.h>
  36#include <asm/debugreg.h>
  37#include <asm/desc.h>
  38#include <asm/fpu/internal.h>
  39#include <asm/idtentry.h>
  40#include <asm/io.h>
  41#include <asm/irq_remapping.h>
  42#include <asm/kexec.h>
  43#include <asm/perf_event.h>
  44#include <asm/mmu_context.h>
  45#include <asm/mshyperv.h>
  46#include <asm/mwait.h>
  47#include <asm/spec-ctrl.h>
  48#include <asm/virtext.h>
  49#include <asm/vmx.h>
  50
  51#include "capabilities.h"
  52#include "cpuid.h"
  53#include "evmcs.h"
  54#include "hyperv.h"
  55#include "kvm_onhyperv.h"
  56#include "irq.h"
  57#include "kvm_cache_regs.h"
  58#include "lapic.h"
  59#include "mmu.h"
  60#include "nested.h"
  61#include "pmu.h"
  62#include "sgx.h"
  63#include "trace.h"
  64#include "vmcs.h"
  65#include "vmcs12.h"
  66#include "vmx.h"
  67#include "x86.h"
  68
  69MODULE_AUTHOR("Qumranet");
  70MODULE_LICENSE("GPL");
  71
  72#ifdef MODULE
  73static const struct x86_cpu_id vmx_cpu_id[] = {
  74        X86_MATCH_FEATURE(X86_FEATURE_VMX, NULL),
  75        {}
  76};
  77MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
  78#endif
  79
  80bool __read_mostly enable_vpid = 1;
  81module_param_named(vpid, enable_vpid, bool, 0444);
  82
  83static bool __read_mostly enable_vnmi = 1;
  84module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
  85
  86bool __read_mostly flexpriority_enabled = 1;
  87module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
  88
  89bool __read_mostly enable_ept = 1;
  90module_param_named(ept, enable_ept, bool, S_IRUGO);
  91
  92bool __read_mostly enable_unrestricted_guest = 1;
  93module_param_named(unrestricted_guest,
  94                        enable_unrestricted_guest, bool, S_IRUGO);
  95
  96bool __read_mostly enable_ept_ad_bits = 1;
  97module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
  98
  99static bool __read_mostly emulate_invalid_guest_state = true;
 100module_param(emulate_invalid_guest_state, bool, S_IRUGO);
 101
 102static bool __read_mostly fasteoi = 1;
 103module_param(fasteoi, bool, S_IRUGO);
 104
 105module_param(enable_apicv, bool, S_IRUGO);
 106
 107/*
 108 * If nested=1, nested virtualization is supported, i.e., guests may use
 109 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
 110 * use VMX instructions.
 111 */
 112static bool __read_mostly nested = 1;
 113module_param(nested, bool, S_IRUGO);
 114
 115bool __read_mostly enable_pml = 1;
 116module_param_named(pml, enable_pml, bool, S_IRUGO);
 117
 118static bool __read_mostly dump_invalid_vmcs = 0;
 119module_param(dump_invalid_vmcs, bool, 0644);
 120
 121#define MSR_BITMAP_MODE_X2APIC          1
 122#define MSR_BITMAP_MODE_X2APIC_APICV    2
 123
 124#define KVM_VMX_TSC_MULTIPLIER_MAX     0xffffffffffffffffULL
 125
 126/* Guest_tsc -> host_tsc conversion requires 64-bit division.  */
 127static int __read_mostly cpu_preemption_timer_multi;
 128static bool __read_mostly enable_preemption_timer = 1;
 129#ifdef CONFIG_X86_64
 130module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
 131#endif
 132
 133extern bool __read_mostly allow_smaller_maxphyaddr;
 134module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
 135
 136#define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
 137#define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
 138#define KVM_VM_CR0_ALWAYS_ON                            \
 139        (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST |      \
 140         X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
 141
 142#define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
 143#define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
 144#define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
 145
 146#define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
 147
 148#define MSR_IA32_RTIT_STATUS_MASK (~(RTIT_STATUS_FILTEREN | \
 149        RTIT_STATUS_CONTEXTEN | RTIT_STATUS_TRIGGEREN | \
 150        RTIT_STATUS_ERROR | RTIT_STATUS_STOPPED | \
 151        RTIT_STATUS_BYTECNT))
 152
 153/*
 154 * List of MSRs that can be directly passed to the guest.
 155 * In addition to these x2apic and PT MSRs are handled specially.
 156 */
 157static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSTHROUGH_MSRS] = {
 158        MSR_IA32_SPEC_CTRL,
 159        MSR_IA32_PRED_CMD,
 160        MSR_IA32_TSC,
 161#ifdef CONFIG_X86_64
 162        MSR_FS_BASE,
 163        MSR_GS_BASE,
 164        MSR_KERNEL_GS_BASE,
 165#endif
 166        MSR_IA32_SYSENTER_CS,
 167        MSR_IA32_SYSENTER_ESP,
 168        MSR_IA32_SYSENTER_EIP,
 169        MSR_CORE_C1_RES,
 170        MSR_CORE_C3_RESIDENCY,
 171        MSR_CORE_C6_RESIDENCY,
 172        MSR_CORE_C7_RESIDENCY,
 173};
 174
 175/*
 176 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
 177 * ple_gap:    upper bound on the amount of time between two successive
 178 *             executions of PAUSE in a loop. Also indicate if ple enabled.
 179 *             According to test, this time is usually smaller than 128 cycles.
 180 * ple_window: upper bound on the amount of time a guest is allowed to execute
 181 *             in a PAUSE loop. Tests indicate that most spinlocks are held for
 182 *             less than 2^12 cycles
 183 * Time is measured based on a counter that runs at the same rate as the TSC,
 184 * refer SDM volume 3b section 21.6.13 & 22.1.3.
 185 */
 186static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
 187module_param(ple_gap, uint, 0444);
 188
 189static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
 190module_param(ple_window, uint, 0444);
 191
 192/* Default doubles per-vcpu window every exit. */
 193static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
 194module_param(ple_window_grow, uint, 0444);
 195
 196/* Default resets per-vcpu window every exit to ple_window. */
 197static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
 198module_param(ple_window_shrink, uint, 0444);
 199
 200/* Default is to compute the maximum so we can never overflow. */
 201static unsigned int ple_window_max        = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
 202module_param(ple_window_max, uint, 0444);
 203
 204/* Default is SYSTEM mode, 1 for host-guest mode */
 205int __read_mostly pt_mode = PT_MODE_SYSTEM;
 206module_param(pt_mode, int, S_IRUGO);
 207
 208static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
 209static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
 210static DEFINE_MUTEX(vmx_l1d_flush_mutex);
 211
 212/* Storage for pre module init parameter parsing */
 213static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
 214
 215static const struct {
 216        const char *option;
 217        bool for_parse;
 218} vmentry_l1d_param[] = {
 219        [VMENTER_L1D_FLUSH_AUTO]         = {"auto", true},
 220        [VMENTER_L1D_FLUSH_NEVER]        = {"never", true},
 221        [VMENTER_L1D_FLUSH_COND]         = {"cond", true},
 222        [VMENTER_L1D_FLUSH_ALWAYS]       = {"always", true},
 223        [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
 224        [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
 225};
 226
 227#define L1D_CACHE_ORDER 4
 228static void *vmx_l1d_flush_pages;
 229
 230static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
 231{
 232        struct page *page;
 233        unsigned int i;
 234
 235        if (!boot_cpu_has_bug(X86_BUG_L1TF)) {
 236                l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
 237                return 0;
 238        }
 239
 240        if (!enable_ept) {
 241                l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
 242                return 0;
 243        }
 244
 245        if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
 246                u64 msr;
 247
 248                rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
 249                if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
 250                        l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
 251                        return 0;
 252                }
 253        }
 254
 255        /* If set to auto use the default l1tf mitigation method */
 256        if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
 257                switch (l1tf_mitigation) {
 258                case L1TF_MITIGATION_OFF:
 259                        l1tf = VMENTER_L1D_FLUSH_NEVER;
 260                        break;
 261                case L1TF_MITIGATION_FLUSH_NOWARN:
 262                case L1TF_MITIGATION_FLUSH:
 263                case L1TF_MITIGATION_FLUSH_NOSMT:
 264                        l1tf = VMENTER_L1D_FLUSH_COND;
 265                        break;
 266                case L1TF_MITIGATION_FULL:
 267                case L1TF_MITIGATION_FULL_FORCE:
 268                        l1tf = VMENTER_L1D_FLUSH_ALWAYS;
 269                        break;
 270                }
 271        } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
 272                l1tf = VMENTER_L1D_FLUSH_ALWAYS;
 273        }
 274
 275        if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
 276            !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
 277                /*
 278                 * This allocation for vmx_l1d_flush_pages is not tied to a VM
 279                 * lifetime and so should not be charged to a memcg.
 280                 */
 281                page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
 282                if (!page)
 283                        return -ENOMEM;
 284                vmx_l1d_flush_pages = page_address(page);
 285
 286                /*
 287                 * Initialize each page with a different pattern in
 288                 * order to protect against KSM in the nested
 289                 * virtualization case.
 290                 */
 291                for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
 292                        memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
 293                               PAGE_SIZE);
 294                }
 295        }
 296
 297        l1tf_vmx_mitigation = l1tf;
 298
 299        if (l1tf != VMENTER_L1D_FLUSH_NEVER)
 300                static_branch_enable(&vmx_l1d_should_flush);
 301        else
 302                static_branch_disable(&vmx_l1d_should_flush);
 303
 304        if (l1tf == VMENTER_L1D_FLUSH_COND)
 305                static_branch_enable(&vmx_l1d_flush_cond);
 306        else
 307                static_branch_disable(&vmx_l1d_flush_cond);
 308        return 0;
 309}
 310
 311static int vmentry_l1d_flush_parse(const char *s)
 312{
 313        unsigned int i;
 314
 315        if (s) {
 316                for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
 317                        if (vmentry_l1d_param[i].for_parse &&
 318                            sysfs_streq(s, vmentry_l1d_param[i].option))
 319                                return i;
 320                }
 321        }
 322        return -EINVAL;
 323}
 324
 325static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
 326{
 327        int l1tf, ret;
 328
 329        l1tf = vmentry_l1d_flush_parse(s);
 330        if (l1tf < 0)
 331                return l1tf;
 332
 333        if (!boot_cpu_has(X86_BUG_L1TF))
 334                return 0;
 335
 336        /*
 337         * Has vmx_init() run already? If not then this is the pre init
 338         * parameter parsing. In that case just store the value and let
 339         * vmx_init() do the proper setup after enable_ept has been
 340         * established.
 341         */
 342        if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
 343                vmentry_l1d_flush_param = l1tf;
 344                return 0;
 345        }
 346
 347        mutex_lock(&vmx_l1d_flush_mutex);
 348        ret = vmx_setup_l1d_flush(l1tf);
 349        mutex_unlock(&vmx_l1d_flush_mutex);
 350        return ret;
 351}
 352
 353static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
 354{
 355        if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
 356                return sprintf(s, "???\n");
 357
 358        return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
 359}
 360
 361static const struct kernel_param_ops vmentry_l1d_flush_ops = {
 362        .set = vmentry_l1d_flush_set,
 363        .get = vmentry_l1d_flush_get,
 364};
 365module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
 366
 367static u32 vmx_segment_access_rights(struct kvm_segment *var);
 368
 369void vmx_vmexit(void);
 370
 371#define vmx_insn_failed(fmt...)         \
 372do {                                    \
 373        WARN_ONCE(1, fmt);              \
 374        pr_warn_ratelimited(fmt);       \
 375} while (0)
 376
 377asmlinkage void vmread_error(unsigned long field, bool fault)
 378{
 379        if (fault)
 380                kvm_spurious_fault();
 381        else
 382                vmx_insn_failed("kvm: vmread failed: field=%lx\n", field);
 383}
 384
 385noinline void vmwrite_error(unsigned long field, unsigned long value)
 386{
 387        vmx_insn_failed("kvm: vmwrite failed: field=%lx val=%lx err=%d\n",
 388                        field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
 389}
 390
 391noinline void vmclear_error(struct vmcs *vmcs, u64 phys_addr)
 392{
 393        vmx_insn_failed("kvm: vmclear failed: %p/%llx\n", vmcs, phys_addr);
 394}
 395
 396noinline void vmptrld_error(struct vmcs *vmcs, u64 phys_addr)
 397{
 398        vmx_insn_failed("kvm: vmptrld failed: %p/%llx\n", vmcs, phys_addr);
 399}
 400
 401noinline void invvpid_error(unsigned long ext, u16 vpid, gva_t gva)
 402{
 403        vmx_insn_failed("kvm: invvpid failed: ext=0x%lx vpid=%u gva=0x%lx\n",
 404                        ext, vpid, gva);
 405}
 406
 407noinline void invept_error(unsigned long ext, u64 eptp, gpa_t gpa)
 408{
 409        vmx_insn_failed("kvm: invept failed: ext=0x%lx eptp=%llx gpa=0x%llx\n",
 410                        ext, eptp, gpa);
 411}
 412
 413static DEFINE_PER_CPU(struct vmcs *, vmxarea);
 414DEFINE_PER_CPU(struct vmcs *, current_vmcs);
 415/*
 416 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
 417 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
 418 */
 419static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
 420
 421static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
 422static DEFINE_SPINLOCK(vmx_vpid_lock);
 423
 424struct vmcs_config vmcs_config;
 425struct vmx_capability vmx_capability;
 426
 427#define VMX_SEGMENT_FIELD(seg)                                  \
 428        [VCPU_SREG_##seg] = {                                   \
 429                .selector = GUEST_##seg##_SELECTOR,             \
 430                .base = GUEST_##seg##_BASE,                     \
 431                .limit = GUEST_##seg##_LIMIT,                   \
 432                .ar_bytes = GUEST_##seg##_AR_BYTES,             \
 433        }
 434
 435static const struct kvm_vmx_segment_field {
 436        unsigned selector;
 437        unsigned base;
 438        unsigned limit;
 439        unsigned ar_bytes;
 440} kvm_vmx_segment_fields[] = {
 441        VMX_SEGMENT_FIELD(CS),
 442        VMX_SEGMENT_FIELD(DS),
 443        VMX_SEGMENT_FIELD(ES),
 444        VMX_SEGMENT_FIELD(FS),
 445        VMX_SEGMENT_FIELD(GS),
 446        VMX_SEGMENT_FIELD(SS),
 447        VMX_SEGMENT_FIELD(TR),
 448        VMX_SEGMENT_FIELD(LDTR),
 449};
 450
 451static inline void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
 452{
 453        vmx->segment_cache.bitmask = 0;
 454}
 455
 456static unsigned long host_idt_base;
 457
 458#if IS_ENABLED(CONFIG_HYPERV)
 459static bool __read_mostly enlightened_vmcs = true;
 460module_param(enlightened_vmcs, bool, 0444);
 461
 462static int hv_enable_direct_tlbflush(struct kvm_vcpu *vcpu)
 463{
 464        struct hv_enlightened_vmcs *evmcs;
 465        struct hv_partition_assist_pg **p_hv_pa_pg =
 466                        &to_kvm_hv(vcpu->kvm)->hv_pa_pg;
 467        /*
 468         * Synthetic VM-Exit is not enabled in current code and so All
 469         * evmcs in singe VM shares same assist page.
 470         */
 471        if (!*p_hv_pa_pg)
 472                *p_hv_pa_pg = kzalloc(PAGE_SIZE, GFP_KERNEL_ACCOUNT);
 473
 474        if (!*p_hv_pa_pg)
 475                return -ENOMEM;
 476
 477        evmcs = (struct hv_enlightened_vmcs *)to_vmx(vcpu)->loaded_vmcs->vmcs;
 478
 479        evmcs->partition_assist_page =
 480                __pa(*p_hv_pa_pg);
 481        evmcs->hv_vm_id = (unsigned long)vcpu->kvm;
 482        evmcs->hv_enlightenments_control.nested_flush_hypercall = 1;
 483
 484        return 0;
 485}
 486
 487#endif /* IS_ENABLED(CONFIG_HYPERV) */
 488
 489/*
 490 * Comment's format: document - errata name - stepping - processor name.
 491 * Refer from
 492 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
 493 */
 494static u32 vmx_preemption_cpu_tfms[] = {
 495/* 323344.pdf - BA86   - D0 - Xeon 7500 Series */
 4960x000206E6,
 497/* 323056.pdf - AAX65  - C2 - Xeon L3406 */
 498/* 322814.pdf - AAT59  - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
 499/* 322911.pdf - AAU65  - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
 5000x00020652,
 501/* 322911.pdf - AAU65  - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
 5020x00020655,
 503/* 322373.pdf - AAO95  - B1 - Xeon 3400 Series */
 504/* 322166.pdf - AAN92  - B1 - i7-800 and i5-700 Desktop */
 505/*
 506 * 320767.pdf - AAP86  - B1 -
 507 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
 508 */
 5090x000106E5,
 510/* 321333.pdf - AAM126 - C0 - Xeon 3500 */
 5110x000106A0,
 512/* 321333.pdf - AAM126 - C1 - Xeon 3500 */
 5130x000106A1,
 514/* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
 5150x000106A4,
 516 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
 517 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
 518 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
 5190x000106A5,
 520 /* Xeon E3-1220 V2 */
 5210x000306A8,
 522};
 523
 524static inline bool cpu_has_broken_vmx_preemption_timer(void)
 525{
 526        u32 eax = cpuid_eax(0x00000001), i;
 527
 528        /* Clear the reserved bits */
 529        eax &= ~(0x3U << 14 | 0xfU << 28);
 530        for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
 531                if (eax == vmx_preemption_cpu_tfms[i])
 532                        return true;
 533
 534        return false;
 535}
 536
 537static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
 538{
 539        return flexpriority_enabled && lapic_in_kernel(vcpu);
 540}
 541
 542static inline bool report_flexpriority(void)
 543{
 544        return flexpriority_enabled;
 545}
 546
 547static int possible_passthrough_msr_slot(u32 msr)
 548{
 549        u32 i;
 550
 551        for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
 552                if (vmx_possible_passthrough_msrs[i] == msr)
 553                        return i;
 554
 555        return -ENOENT;
 556}
 557
 558static bool is_valid_passthrough_msr(u32 msr)
 559{
 560        bool r;
 561
 562        switch (msr) {
 563        case 0x800 ... 0x8ff:
 564                /* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
 565                return true;
 566        case MSR_IA32_RTIT_STATUS:
 567        case MSR_IA32_RTIT_OUTPUT_BASE:
 568        case MSR_IA32_RTIT_OUTPUT_MASK:
 569        case MSR_IA32_RTIT_CR3_MATCH:
 570        case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
 571                /* PT MSRs. These are handled in pt_update_intercept_for_msr() */
 572        case MSR_LBR_SELECT:
 573        case MSR_LBR_TOS:
 574        case MSR_LBR_INFO_0 ... MSR_LBR_INFO_0 + 31:
 575        case MSR_LBR_NHM_FROM ... MSR_LBR_NHM_FROM + 31:
 576        case MSR_LBR_NHM_TO ... MSR_LBR_NHM_TO + 31:
 577        case MSR_LBR_CORE_FROM ... MSR_LBR_CORE_FROM + 8:
 578        case MSR_LBR_CORE_TO ... MSR_LBR_CORE_TO + 8:
 579                /* LBR MSRs. These are handled in vmx_update_intercept_for_lbr_msrs() */
 580                return true;
 581        }
 582
 583        r = possible_passthrough_msr_slot(msr) != -ENOENT;
 584
 585        WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
 586
 587        return r;
 588}
 589
 590struct vmx_uret_msr *vmx_find_uret_msr(struct vcpu_vmx *vmx, u32 msr)
 591{
 592        int i;
 593
 594        i = kvm_find_user_return_msr(msr);
 595        if (i >= 0)
 596                return &vmx->guest_uret_msrs[i];
 597        return NULL;
 598}
 599
 600static int vmx_set_guest_uret_msr(struct vcpu_vmx *vmx,
 601                                  struct vmx_uret_msr *msr, u64 data)
 602{
 603        unsigned int slot = msr - vmx->guest_uret_msrs;
 604        int ret = 0;
 605
 606        u64 old_msr_data = msr->data;
 607        msr->data = data;
 608        if (msr->load_into_hardware) {
 609                preempt_disable();
 610                ret = kvm_set_user_return_msr(slot, msr->data, msr->mask);
 611                preempt_enable();
 612                if (ret)
 613                        msr->data = old_msr_data;
 614        }
 615        return ret;
 616}
 617
 618#ifdef CONFIG_KEXEC_CORE
 619static void crash_vmclear_local_loaded_vmcss(void)
 620{
 621        int cpu = raw_smp_processor_id();
 622        struct loaded_vmcs *v;
 623
 624        list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
 625                            loaded_vmcss_on_cpu_link)
 626                vmcs_clear(v->vmcs);
 627}
 628#endif /* CONFIG_KEXEC_CORE */
 629
 630static void __loaded_vmcs_clear(void *arg)
 631{
 632        struct loaded_vmcs *loaded_vmcs = arg;
 633        int cpu = raw_smp_processor_id();
 634
 635        if (loaded_vmcs->cpu != cpu)
 636                return; /* vcpu migration can race with cpu offline */
 637        if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
 638                per_cpu(current_vmcs, cpu) = NULL;
 639
 640        vmcs_clear(loaded_vmcs->vmcs);
 641        if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
 642                vmcs_clear(loaded_vmcs->shadow_vmcs);
 643
 644        list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
 645
 646        /*
 647         * Ensure all writes to loaded_vmcs, including deleting it from its
 648         * current percpu list, complete before setting loaded_vmcs->vcpu to
 649         * -1, otherwise a different cpu can see vcpu == -1 first and add
 650         * loaded_vmcs to its percpu list before it's deleted from this cpu's
 651         * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
 652         */
 653        smp_wmb();
 654
 655        loaded_vmcs->cpu = -1;
 656        loaded_vmcs->launched = 0;
 657}
 658
 659void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
 660{
 661        int cpu = loaded_vmcs->cpu;
 662
 663        if (cpu != -1)
 664                smp_call_function_single(cpu,
 665                         __loaded_vmcs_clear, loaded_vmcs, 1);
 666}
 667
 668static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
 669                                       unsigned field)
 670{
 671        bool ret;
 672        u32 mask = 1 << (seg * SEG_FIELD_NR + field);
 673
 674        if (!kvm_register_is_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS)) {
 675                kvm_register_mark_available(&vmx->vcpu, VCPU_EXREG_SEGMENTS);
 676                vmx->segment_cache.bitmask = 0;
 677        }
 678        ret = vmx->segment_cache.bitmask & mask;
 679        vmx->segment_cache.bitmask |= mask;
 680        return ret;
 681}
 682
 683static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
 684{
 685        u16 *p = &vmx->segment_cache.seg[seg].selector;
 686
 687        if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
 688                *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
 689        return *p;
 690}
 691
 692static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
 693{
 694        ulong *p = &vmx->segment_cache.seg[seg].base;
 695
 696        if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
 697                *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
 698        return *p;
 699}
 700
 701static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
 702{
 703        u32 *p = &vmx->segment_cache.seg[seg].limit;
 704
 705        if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
 706                *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
 707        return *p;
 708}
 709
 710static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
 711{
 712        u32 *p = &vmx->segment_cache.seg[seg].ar;
 713
 714        if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
 715                *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
 716        return *p;
 717}
 718
 719void vmx_update_exception_bitmap(struct kvm_vcpu *vcpu)
 720{
 721        u32 eb;
 722
 723        eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
 724             (1u << DB_VECTOR) | (1u << AC_VECTOR);
 725        /*
 726         * Guest access to VMware backdoor ports could legitimately
 727         * trigger #GP because of TSS I/O permission bitmap.
 728         * We intercept those #GP and allow access to them anyway
 729         * as VMware does.
 730         */
 731        if (enable_vmware_backdoor)
 732                eb |= (1u << GP_VECTOR);
 733        if ((vcpu->guest_debug &
 734             (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
 735            (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
 736                eb |= 1u << BP_VECTOR;
 737        if (to_vmx(vcpu)->rmode.vm86_active)
 738                eb = ~0;
 739        if (!vmx_need_pf_intercept(vcpu))
 740                eb &= ~(1u << PF_VECTOR);
 741
 742        /* When we are running a nested L2 guest and L1 specified for it a
 743         * certain exception bitmap, we must trap the same exceptions and pass
 744         * them to L1. When running L2, we will only handle the exceptions
 745         * specified above if L1 did not want them.
 746         */
 747        if (is_guest_mode(vcpu))
 748                eb |= get_vmcs12(vcpu)->exception_bitmap;
 749        else {
 750                int mask = 0, match = 0;
 751
 752                if (enable_ept && (eb & (1u << PF_VECTOR))) {
 753                        /*
 754                         * If EPT is enabled, #PF is currently only intercepted
 755                         * if MAXPHYADDR is smaller on the guest than on the
 756                         * host.  In that case we only care about present,
 757                         * non-reserved faults.  For vmcs02, however, PFEC_MASK
 758                         * and PFEC_MATCH are set in prepare_vmcs02_rare.
 759                         */
 760                        mask = PFERR_PRESENT_MASK | PFERR_RSVD_MASK;
 761                        match = PFERR_PRESENT_MASK;
 762                }
 763                vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, mask);
 764                vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, match);
 765        }
 766
 767        vmcs_write32(EXCEPTION_BITMAP, eb);
 768}
 769
 770/*
 771 * Check if MSR is intercepted for currently loaded MSR bitmap.
 772 */
 773static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
 774{
 775        unsigned long *msr_bitmap;
 776        int f = sizeof(unsigned long);
 777
 778        if (!cpu_has_vmx_msr_bitmap())
 779                return true;
 780
 781        msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
 782
 783        if (msr <= 0x1fff) {
 784                return !!test_bit(msr, msr_bitmap + 0x800 / f);
 785        } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
 786                msr &= 0x1fff;
 787                return !!test_bit(msr, msr_bitmap + 0xc00 / f);
 788        }
 789
 790        return true;
 791}
 792
 793static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
 794                unsigned long entry, unsigned long exit)
 795{
 796        vm_entry_controls_clearbit(vmx, entry);
 797        vm_exit_controls_clearbit(vmx, exit);
 798}
 799
 800int vmx_find_loadstore_msr_slot(struct vmx_msrs *m, u32 msr)
 801{
 802        unsigned int i;
 803
 804        for (i = 0; i < m->nr; ++i) {
 805                if (m->val[i].index == msr)
 806                        return i;
 807        }
 808        return -ENOENT;
 809}
 810
 811static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
 812{
 813        int i;
 814        struct msr_autoload *m = &vmx->msr_autoload;
 815
 816        switch (msr) {
 817        case MSR_EFER:
 818                if (cpu_has_load_ia32_efer()) {
 819                        clear_atomic_switch_msr_special(vmx,
 820                                        VM_ENTRY_LOAD_IA32_EFER,
 821                                        VM_EXIT_LOAD_IA32_EFER);
 822                        return;
 823                }
 824                break;
 825        case MSR_CORE_PERF_GLOBAL_CTRL:
 826                if (cpu_has_load_perf_global_ctrl()) {
 827                        clear_atomic_switch_msr_special(vmx,
 828                                        VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
 829                                        VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
 830                        return;
 831                }
 832                break;
 833        }
 834        i = vmx_find_loadstore_msr_slot(&m->guest, msr);
 835        if (i < 0)
 836                goto skip_guest;
 837        --m->guest.nr;
 838        m->guest.val[i] = m->guest.val[m->guest.nr];
 839        vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
 840
 841skip_guest:
 842        i = vmx_find_loadstore_msr_slot(&m->host, msr);
 843        if (i < 0)
 844                return;
 845
 846        --m->host.nr;
 847        m->host.val[i] = m->host.val[m->host.nr];
 848        vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
 849}
 850
 851static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
 852                unsigned long entry, unsigned long exit,
 853                unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
 854                u64 guest_val, u64 host_val)
 855{
 856        vmcs_write64(guest_val_vmcs, guest_val);
 857        if (host_val_vmcs != HOST_IA32_EFER)
 858                vmcs_write64(host_val_vmcs, host_val);
 859        vm_entry_controls_setbit(vmx, entry);
 860        vm_exit_controls_setbit(vmx, exit);
 861}
 862
 863static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
 864                                  u64 guest_val, u64 host_val, bool entry_only)
 865{
 866        int i, j = 0;
 867        struct msr_autoload *m = &vmx->msr_autoload;
 868
 869        switch (msr) {
 870        case MSR_EFER:
 871                if (cpu_has_load_ia32_efer()) {
 872                        add_atomic_switch_msr_special(vmx,
 873                                        VM_ENTRY_LOAD_IA32_EFER,
 874                                        VM_EXIT_LOAD_IA32_EFER,
 875                                        GUEST_IA32_EFER,
 876                                        HOST_IA32_EFER,
 877                                        guest_val, host_val);
 878                        return;
 879                }
 880                break;
 881        case MSR_CORE_PERF_GLOBAL_CTRL:
 882                if (cpu_has_load_perf_global_ctrl()) {
 883                        add_atomic_switch_msr_special(vmx,
 884                                        VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
 885                                        VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
 886                                        GUEST_IA32_PERF_GLOBAL_CTRL,
 887                                        HOST_IA32_PERF_GLOBAL_CTRL,
 888                                        guest_val, host_val);
 889                        return;
 890                }
 891                break;
 892        case MSR_IA32_PEBS_ENABLE:
 893                /* PEBS needs a quiescent period after being disabled (to write
 894                 * a record).  Disabling PEBS through VMX MSR swapping doesn't
 895                 * provide that period, so a CPU could write host's record into
 896                 * guest's memory.
 897                 */
 898                wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
 899        }
 900
 901        i = vmx_find_loadstore_msr_slot(&m->guest, msr);
 902        if (!entry_only)
 903                j = vmx_find_loadstore_msr_slot(&m->host, msr);
 904
 905        if ((i < 0 && m->guest.nr == MAX_NR_LOADSTORE_MSRS) ||
 906            (j < 0 &&  m->host.nr == MAX_NR_LOADSTORE_MSRS)) {
 907                printk_once(KERN_WARNING "Not enough msr switch entries. "
 908                                "Can't add msr %x\n", msr);
 909                return;
 910        }
 911        if (i < 0) {
 912                i = m->guest.nr++;
 913                vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
 914        }
 915        m->guest.val[i].index = msr;
 916        m->guest.val[i].value = guest_val;
 917
 918        if (entry_only)
 919                return;
 920
 921        if (j < 0) {
 922                j = m->host.nr++;
 923                vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
 924        }
 925        m->host.val[j].index = msr;
 926        m->host.val[j].value = host_val;
 927}
 928
 929static bool update_transition_efer(struct vcpu_vmx *vmx)
 930{
 931        u64 guest_efer = vmx->vcpu.arch.efer;
 932        u64 ignore_bits = 0;
 933        int i;
 934
 935        /* Shadow paging assumes NX to be available.  */
 936        if (!enable_ept)
 937                guest_efer |= EFER_NX;
 938
 939        /*
 940         * LMA and LME handled by hardware; SCE meaningless outside long mode.
 941         */
 942        ignore_bits |= EFER_SCE;
 943#ifdef CONFIG_X86_64
 944        ignore_bits |= EFER_LMA | EFER_LME;
 945        /* SCE is meaningful only in long mode on Intel */
 946        if (guest_efer & EFER_LMA)
 947                ignore_bits &= ~(u64)EFER_SCE;
 948#endif
 949
 950        /*
 951         * On EPT, we can't emulate NX, so we must switch EFER atomically.
 952         * On CPUs that support "load IA32_EFER", always switch EFER
 953         * atomically, since it's faster than switching it manually.
 954         */
 955        if (cpu_has_load_ia32_efer() ||
 956            (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
 957                if (!(guest_efer & EFER_LMA))
 958                        guest_efer &= ~EFER_LME;
 959                if (guest_efer != host_efer)
 960                        add_atomic_switch_msr(vmx, MSR_EFER,
 961                                              guest_efer, host_efer, false);
 962                else
 963                        clear_atomic_switch_msr(vmx, MSR_EFER);
 964                return false;
 965        }
 966
 967        i = kvm_find_user_return_msr(MSR_EFER);
 968        if (i < 0)
 969                return false;
 970
 971        clear_atomic_switch_msr(vmx, MSR_EFER);
 972
 973        guest_efer &= ~ignore_bits;
 974        guest_efer |= host_efer & ignore_bits;
 975
 976        vmx->guest_uret_msrs[i].data = guest_efer;
 977        vmx->guest_uret_msrs[i].mask = ~ignore_bits;
 978
 979        return true;
 980}
 981
 982#ifdef CONFIG_X86_32
 983/*
 984 * On 32-bit kernels, VM exits still load the FS and GS bases from the
 985 * VMCS rather than the segment table.  KVM uses this helper to figure
 986 * out the current bases to poke them into the VMCS before entry.
 987 */
 988static unsigned long segment_base(u16 selector)
 989{
 990        struct desc_struct *table;
 991        unsigned long v;
 992
 993        if (!(selector & ~SEGMENT_RPL_MASK))
 994                return 0;
 995
 996        table = get_current_gdt_ro();
 997
 998        if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
 999                u16 ldt_selector = kvm_read_ldt();
1000
1001                if (!(ldt_selector & ~SEGMENT_RPL_MASK))
1002                        return 0;
1003
1004                table = (struct desc_struct *)segment_base(ldt_selector);
1005        }
1006        v = get_desc_base(&table[selector >> 3]);
1007        return v;
1008}
1009#endif
1010
1011static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
1012{
1013        return vmx_pt_mode_is_host_guest() &&
1014               !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
1015}
1016
1017static inline bool pt_output_base_valid(struct kvm_vcpu *vcpu, u64 base)
1018{
1019        /* The base must be 128-byte aligned and a legal physical address. */
1020        return kvm_vcpu_is_legal_aligned_gpa(vcpu, base, 128);
1021}
1022
1023static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
1024{
1025        u32 i;
1026
1027        wrmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1028        wrmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1029        wrmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1030        wrmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1031        for (i = 0; i < addr_range; i++) {
1032                wrmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1033                wrmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1034        }
1035}
1036
1037static inline void pt_save_msr(struct pt_ctx *ctx, u32 addr_range)
1038{
1039        u32 i;
1040
1041        rdmsrl(MSR_IA32_RTIT_STATUS, ctx->status);
1042        rdmsrl(MSR_IA32_RTIT_OUTPUT_BASE, ctx->output_base);
1043        rdmsrl(MSR_IA32_RTIT_OUTPUT_MASK, ctx->output_mask);
1044        rdmsrl(MSR_IA32_RTIT_CR3_MATCH, ctx->cr3_match);
1045        for (i = 0; i < addr_range; i++) {
1046                rdmsrl(MSR_IA32_RTIT_ADDR0_A + i * 2, ctx->addr_a[i]);
1047                rdmsrl(MSR_IA32_RTIT_ADDR0_B + i * 2, ctx->addr_b[i]);
1048        }
1049}
1050
1051static void pt_guest_enter(struct vcpu_vmx *vmx)
1052{
1053        if (vmx_pt_mode_is_system())
1054                return;
1055
1056        /*
1057         * GUEST_IA32_RTIT_CTL is already set in the VMCS.
1058         * Save host state before VM entry.
1059         */
1060        rdmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1061        if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1062                wrmsrl(MSR_IA32_RTIT_CTL, 0);
1063                pt_save_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1064                pt_load_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1065        }
1066}
1067
1068static void pt_guest_exit(struct vcpu_vmx *vmx)
1069{
1070        if (vmx_pt_mode_is_system())
1071                return;
1072
1073        if (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) {
1074                pt_save_msr(&vmx->pt_desc.guest, vmx->pt_desc.addr_range);
1075                pt_load_msr(&vmx->pt_desc.host, vmx->pt_desc.addr_range);
1076        }
1077
1078        /* Reload host state (IA32_RTIT_CTL will be cleared on VM exit). */
1079        wrmsrl(MSR_IA32_RTIT_CTL, vmx->pt_desc.host.ctl);
1080}
1081
1082void vmx_set_host_fs_gs(struct vmcs_host_state *host, u16 fs_sel, u16 gs_sel,
1083                        unsigned long fs_base, unsigned long gs_base)
1084{
1085        if (unlikely(fs_sel != host->fs_sel)) {
1086                if (!(fs_sel & 7))
1087                        vmcs_write16(HOST_FS_SELECTOR, fs_sel);
1088                else
1089                        vmcs_write16(HOST_FS_SELECTOR, 0);
1090                host->fs_sel = fs_sel;
1091        }
1092        if (unlikely(gs_sel != host->gs_sel)) {
1093                if (!(gs_sel & 7))
1094                        vmcs_write16(HOST_GS_SELECTOR, gs_sel);
1095                else
1096                        vmcs_write16(HOST_GS_SELECTOR, 0);
1097                host->gs_sel = gs_sel;
1098        }
1099        if (unlikely(fs_base != host->fs_base)) {
1100                vmcs_writel(HOST_FS_BASE, fs_base);
1101                host->fs_base = fs_base;
1102        }
1103        if (unlikely(gs_base != host->gs_base)) {
1104                vmcs_writel(HOST_GS_BASE, gs_base);
1105                host->gs_base = gs_base;
1106        }
1107}
1108
1109void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1110{
1111        struct vcpu_vmx *vmx = to_vmx(vcpu);
1112        struct vmcs_host_state *host_state;
1113#ifdef CONFIG_X86_64
1114        int cpu = raw_smp_processor_id();
1115#endif
1116        unsigned long fs_base, gs_base;
1117        u16 fs_sel, gs_sel;
1118        int i;
1119
1120        vmx->req_immediate_exit = false;
1121
1122        /*
1123         * Note that guest MSRs to be saved/restored can also be changed
1124         * when guest state is loaded. This happens when guest transitions
1125         * to/from long-mode by setting MSR_EFER.LMA.
1126         */
1127        if (!vmx->guest_uret_msrs_loaded) {
1128                vmx->guest_uret_msrs_loaded = true;
1129                for (i = 0; i < kvm_nr_uret_msrs; ++i) {
1130                        if (!vmx->guest_uret_msrs[i].load_into_hardware)
1131                                continue;
1132
1133                        kvm_set_user_return_msr(i,
1134                                                vmx->guest_uret_msrs[i].data,
1135                                                vmx->guest_uret_msrs[i].mask);
1136                }
1137        }
1138
1139        if (vmx->nested.need_vmcs12_to_shadow_sync)
1140                nested_sync_vmcs12_to_shadow(vcpu);
1141
1142        if (vmx->guest_state_loaded)
1143                return;
1144
1145        host_state = &vmx->loaded_vmcs->host_state;
1146
1147        /*
1148         * Set host fs and gs selectors.  Unfortunately, 22.2.3 does not
1149         * allow segment selectors with cpl > 0 or ti == 1.
1150         */
1151        host_state->ldt_sel = kvm_read_ldt();
1152
1153#ifdef CONFIG_X86_64
1154        savesegment(ds, host_state->ds_sel);
1155        savesegment(es, host_state->es_sel);
1156
1157        gs_base = cpu_kernelmode_gs_base(cpu);
1158        if (likely(is_64bit_mm(current->mm))) {
1159                current_save_fsgs();
1160                fs_sel = current->thread.fsindex;
1161                gs_sel = current->thread.gsindex;
1162                fs_base = current->thread.fsbase;
1163                vmx->msr_host_kernel_gs_base = current->thread.gsbase;
1164        } else {
1165                savesegment(fs, fs_sel);
1166                savesegment(gs, gs_sel);
1167                fs_base = read_msr(MSR_FS_BASE);
1168                vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
1169        }
1170
1171        wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1172#else
1173        savesegment(fs, fs_sel);
1174        savesegment(gs, gs_sel);
1175        fs_base = segment_base(fs_sel);
1176        gs_base = segment_base(gs_sel);
1177#endif
1178
1179        vmx_set_host_fs_gs(host_state, fs_sel, gs_sel, fs_base, gs_base);
1180        vmx->guest_state_loaded = true;
1181}
1182
1183static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
1184{
1185        struct vmcs_host_state *host_state;
1186
1187        if (!vmx->guest_state_loaded)
1188                return;
1189
1190        host_state = &vmx->loaded_vmcs->host_state;
1191
1192        ++vmx->vcpu.stat.host_state_reload;
1193
1194#ifdef CONFIG_X86_64
1195        rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1196#endif
1197        if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
1198                kvm_load_ldt(host_state->ldt_sel);
1199#ifdef CONFIG_X86_64
1200                load_gs_index(host_state->gs_sel);
1201#else
1202                loadsegment(gs, host_state->gs_sel);
1203#endif
1204        }
1205        if (host_state->fs_sel & 7)
1206                loadsegment(fs, host_state->fs_sel);
1207#ifdef CONFIG_X86_64
1208        if (unlikely(host_state->ds_sel | host_state->es_sel)) {
1209                loadsegment(ds, host_state->ds_sel);
1210                loadsegment(es, host_state->es_sel);
1211        }
1212#endif
1213        invalidate_tss_limit();
1214#ifdef CONFIG_X86_64
1215        wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
1216#endif
1217        load_fixmap_gdt(raw_smp_processor_id());
1218        vmx->guest_state_loaded = false;
1219        vmx->guest_uret_msrs_loaded = false;
1220}
1221
1222#ifdef CONFIG_X86_64
1223static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
1224{
1225        preempt_disable();
1226        if (vmx->guest_state_loaded)
1227                rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
1228        preempt_enable();
1229        return vmx->msr_guest_kernel_gs_base;
1230}
1231
1232static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
1233{
1234        preempt_disable();
1235        if (vmx->guest_state_loaded)
1236                wrmsrl(MSR_KERNEL_GS_BASE, data);
1237        preempt_enable();
1238        vmx->msr_guest_kernel_gs_base = data;
1239}
1240#endif
1241
1242void vmx_vcpu_load_vmcs(struct kvm_vcpu *vcpu, int cpu,
1243                        struct loaded_vmcs *buddy)
1244{
1245        struct vcpu_vmx *vmx = to_vmx(vcpu);
1246        bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
1247        struct vmcs *prev;
1248
1249        if (!already_loaded) {
1250                loaded_vmcs_clear(vmx->loaded_vmcs);
1251                local_irq_disable();
1252
1253                /*
1254                 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
1255                 * this cpu's percpu list, otherwise it may not yet be deleted
1256                 * from its previous cpu's percpu list.  Pairs with the
1257                 * smb_wmb() in __loaded_vmcs_clear().
1258                 */
1259                smp_rmb();
1260
1261                list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
1262                         &per_cpu(loaded_vmcss_on_cpu, cpu));
1263                local_irq_enable();
1264        }
1265
1266        prev = per_cpu(current_vmcs, cpu);
1267        if (prev != vmx->loaded_vmcs->vmcs) {
1268                per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
1269                vmcs_load(vmx->loaded_vmcs->vmcs);
1270
1271                /*
1272                 * No indirect branch prediction barrier needed when switching
1273                 * the active VMCS within a guest, e.g. on nested VM-Enter.
1274                 * The L1 VMM can protect itself with retpolines, IBPB or IBRS.
1275                 */
1276                if (!buddy || WARN_ON_ONCE(buddy->vmcs != prev))
1277                        indirect_branch_prediction_barrier();
1278        }
1279
1280        if (!already_loaded) {
1281                void *gdt = get_current_gdt_ro();
1282                unsigned long sysenter_esp;
1283
1284                /*
1285                 * Flush all EPTP/VPID contexts, the new pCPU may have stale
1286                 * TLB entries from its previous association with the vCPU.
1287                 */
1288                kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
1289
1290                /*
1291                 * Linux uses per-cpu TSS and GDT, so set these when switching
1292                 * processors.  See 22.2.4.
1293                 */
1294                vmcs_writel(HOST_TR_BASE,
1295                            (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
1296                vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt);   /* 22.2.4 */
1297
1298                rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
1299                vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
1300
1301                vmx->loaded_vmcs->cpu = cpu;
1302        }
1303}
1304
1305/*
1306 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
1307 * vcpu mutex is already taken.
1308 */
1309static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1310{
1311        struct vcpu_vmx *vmx = to_vmx(vcpu);
1312
1313        vmx_vcpu_load_vmcs(vcpu, cpu, NULL);
1314
1315        vmx_vcpu_pi_load(vcpu, cpu);
1316
1317        vmx->host_debugctlmsr = get_debugctlmsr();
1318}
1319
1320static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
1321{
1322        vmx_vcpu_pi_put(vcpu);
1323
1324        vmx_prepare_switch_to_host(to_vmx(vcpu));
1325}
1326
1327static bool emulation_required(struct kvm_vcpu *vcpu)
1328{
1329        return emulate_invalid_guest_state && !vmx_guest_state_valid(vcpu);
1330}
1331
1332unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
1333{
1334        struct vcpu_vmx *vmx = to_vmx(vcpu);
1335        unsigned long rflags, save_rflags;
1336
1337        if (!kvm_register_is_available(vcpu, VCPU_EXREG_RFLAGS)) {
1338                kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1339                rflags = vmcs_readl(GUEST_RFLAGS);
1340                if (vmx->rmode.vm86_active) {
1341                        rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
1342                        save_rflags = vmx->rmode.save_rflags;
1343                        rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
1344                }
1345                vmx->rflags = rflags;
1346        }
1347        return vmx->rflags;
1348}
1349
1350void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1351{
1352        struct vcpu_vmx *vmx = to_vmx(vcpu);
1353        unsigned long old_rflags;
1354
1355        if (is_unrestricted_guest(vcpu)) {
1356                kvm_register_mark_available(vcpu, VCPU_EXREG_RFLAGS);
1357                vmx->rflags = rflags;
1358                vmcs_writel(GUEST_RFLAGS, rflags);
1359                return;
1360        }
1361
1362        old_rflags = vmx_get_rflags(vcpu);
1363        vmx->rflags = rflags;
1364        if (vmx->rmode.vm86_active) {
1365                vmx->rmode.save_rflags = rflags;
1366                rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
1367        }
1368        vmcs_writel(GUEST_RFLAGS, rflags);
1369
1370        if ((old_rflags ^ vmx->rflags) & X86_EFLAGS_VM)
1371                vmx->emulation_required = emulation_required(vcpu);
1372}
1373
1374u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
1375{
1376        u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1377        int ret = 0;
1378
1379        if (interruptibility & GUEST_INTR_STATE_STI)
1380                ret |= KVM_X86_SHADOW_INT_STI;
1381        if (interruptibility & GUEST_INTR_STATE_MOV_SS)
1382                ret |= KVM_X86_SHADOW_INT_MOV_SS;
1383
1384        return ret;
1385}
1386
1387void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
1388{
1389        u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
1390        u32 interruptibility = interruptibility_old;
1391
1392        interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
1393
1394        if (mask & KVM_X86_SHADOW_INT_MOV_SS)
1395                interruptibility |= GUEST_INTR_STATE_MOV_SS;
1396        else if (mask & KVM_X86_SHADOW_INT_STI)
1397                interruptibility |= GUEST_INTR_STATE_STI;
1398
1399        if ((interruptibility != interruptibility_old))
1400                vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
1401}
1402
1403static int vmx_rtit_ctl_check(struct kvm_vcpu *vcpu, u64 data)
1404{
1405        struct vcpu_vmx *vmx = to_vmx(vcpu);
1406        unsigned long value;
1407
1408        /*
1409         * Any MSR write that attempts to change bits marked reserved will
1410         * case a #GP fault.
1411         */
1412        if (data & vmx->pt_desc.ctl_bitmask)
1413                return 1;
1414
1415        /*
1416         * Any attempt to modify IA32_RTIT_CTL while TraceEn is set will
1417         * result in a #GP unless the same write also clears TraceEn.
1418         */
1419        if ((vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) &&
1420                ((vmx->pt_desc.guest.ctl ^ data) & ~RTIT_CTL_TRACEEN))
1421                return 1;
1422
1423        /*
1424         * WRMSR to IA32_RTIT_CTL that sets TraceEn but clears this bit
1425         * and FabricEn would cause #GP, if
1426         * CPUID.(EAX=14H, ECX=0):ECX.SNGLRGNOUT[bit 2] = 0
1427         */
1428        if ((data & RTIT_CTL_TRACEEN) && !(data & RTIT_CTL_TOPA) &&
1429                !(data & RTIT_CTL_FABRIC_EN) &&
1430                !intel_pt_validate_cap(vmx->pt_desc.caps,
1431                                        PT_CAP_single_range_output))
1432                return 1;
1433
1434        /*
1435         * MTCFreq, CycThresh and PSBFreq encodings check, any MSR write that
1436         * utilize encodings marked reserved will cause a #GP fault.
1437         */
1438        value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc_periods);
1439        if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_mtc) &&
1440                        !test_bit((data & RTIT_CTL_MTC_RANGE) >>
1441                        RTIT_CTL_MTC_RANGE_OFFSET, &value))
1442                return 1;
1443        value = intel_pt_validate_cap(vmx->pt_desc.caps,
1444                                                PT_CAP_cycle_thresholds);
1445        if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1446                        !test_bit((data & RTIT_CTL_CYC_THRESH) >>
1447                        RTIT_CTL_CYC_THRESH_OFFSET, &value))
1448                return 1;
1449        value = intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_periods);
1450        if (intel_pt_validate_cap(vmx->pt_desc.caps, PT_CAP_psb_cyc) &&
1451                        !test_bit((data & RTIT_CTL_PSB_FREQ) >>
1452                        RTIT_CTL_PSB_FREQ_OFFSET, &value))
1453                return 1;
1454
1455        /*
1456         * If ADDRx_CFG is reserved or the encodings is >2 will
1457         * cause a #GP fault.
1458         */
1459        value = (data & RTIT_CTL_ADDR0) >> RTIT_CTL_ADDR0_OFFSET;
1460        if ((value && (vmx->pt_desc.addr_range < 1)) || (value > 2))
1461                return 1;
1462        value = (data & RTIT_CTL_ADDR1) >> RTIT_CTL_ADDR1_OFFSET;
1463        if ((value && (vmx->pt_desc.addr_range < 2)) || (value > 2))
1464                return 1;
1465        value = (data & RTIT_CTL_ADDR2) >> RTIT_CTL_ADDR2_OFFSET;
1466        if ((value && (vmx->pt_desc.addr_range < 3)) || (value > 2))
1467                return 1;
1468        value = (data & RTIT_CTL_ADDR3) >> RTIT_CTL_ADDR3_OFFSET;
1469        if ((value && (vmx->pt_desc.addr_range < 4)) || (value > 2))
1470                return 1;
1471
1472        return 0;
1473}
1474
1475static bool vmx_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
1476{
1477        /*
1478         * Emulation of instructions in SGX enclaves is impossible as RIP does
1479         * not point  tthe failing instruction, and even if it did, the code
1480         * stream is inaccessible.  Inject #UD instead of exiting to userspace
1481         * so that guest userspace can't DoS the guest simply by triggering
1482         * emulation (enclaves are CPL3 only).
1483         */
1484        if (to_vmx(vcpu)->exit_reason.enclave_mode) {
1485                kvm_queue_exception(vcpu, UD_VECTOR);
1486                return false;
1487        }
1488        return true;
1489}
1490
1491static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
1492{
1493        union vmx_exit_reason exit_reason = to_vmx(vcpu)->exit_reason;
1494        unsigned long rip, orig_rip;
1495        u32 instr_len;
1496
1497        /*
1498         * Using VMCS.VM_EXIT_INSTRUCTION_LEN on EPT misconfig depends on
1499         * undefined behavior: Intel's SDM doesn't mandate the VMCS field be
1500         * set when EPT misconfig occurs.  In practice, real hardware updates
1501         * VM_EXIT_INSTRUCTION_LEN on EPT misconfig, but other hypervisors
1502         * (namely Hyper-V) don't set it due to it being undefined behavior,
1503         * i.e. we end up advancing IP with some random value.
1504         */
1505        if (!static_cpu_has(X86_FEATURE_HYPERVISOR) ||
1506            exit_reason.basic != EXIT_REASON_EPT_MISCONFIG) {
1507                instr_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
1508
1509                /*
1510                 * Emulating an enclave's instructions isn't supported as KVM
1511                 * cannot access the enclave's memory or its true RIP, e.g. the
1512                 * vmcs.GUEST_RIP points at the exit point of the enclave, not
1513                 * the RIP that actually triggered the VM-Exit.  But, because
1514                 * most instructions that cause VM-Exit will #UD in an enclave,
1515                 * most instruction-based VM-Exits simply do not occur.
1516                 *
1517                 * There are a few exceptions, notably the debug instructions
1518                 * INT1ICEBRK and INT3, as they are allowed in debug enclaves
1519                 * and generate #DB/#BP as expected, which KVM might intercept.
1520                 * But again, the CPU does the dirty work and saves an instr
1521                 * length of zero so VMMs don't shoot themselves in the foot.
1522                 * WARN if KVM tries to skip a non-zero length instruction on
1523                 * a VM-Exit from an enclave.
1524                 */
1525                if (!instr_len)
1526                        goto rip_updated;
1527
1528                WARN(exit_reason.enclave_mode,
1529                     "KVM: skipping instruction after SGX enclave VM-Exit");
1530
1531                orig_rip = kvm_rip_read(vcpu);
1532                rip = orig_rip + instr_len;
1533#ifdef CONFIG_X86_64
1534                /*
1535                 * We need to mask out the high 32 bits of RIP if not in 64-bit
1536                 * mode, but just finding out that we are in 64-bit mode is
1537                 * quite expensive.  Only do it if there was a carry.
1538                 */
1539                if (unlikely(((rip ^ orig_rip) >> 31) == 3) && !is_64_bit_mode(vcpu))
1540                        rip = (u32)rip;
1541#endif
1542                kvm_rip_write(vcpu, rip);
1543        } else {
1544                if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
1545                        return 0;
1546        }
1547
1548rip_updated:
1549        /* skipping an emulated instruction also counts */
1550        vmx_set_interrupt_shadow(vcpu, 0);
1551
1552        return 1;
1553}
1554
1555/*
1556 * Recognizes a pending MTF VM-exit and records the nested state for later
1557 * delivery.
1558 */
1559static void vmx_update_emulated_instruction(struct kvm_vcpu *vcpu)
1560{
1561        struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1562        struct vcpu_vmx *vmx = to_vmx(vcpu);
1563
1564        if (!is_guest_mode(vcpu))
1565                return;
1566
1567        /*
1568         * Per the SDM, MTF takes priority over debug-trap exceptions besides
1569         * T-bit traps. As instruction emulation is completed (i.e. at the
1570         * instruction boundary), any #DB exception pending delivery must be a
1571         * debug-trap. Record the pending MTF state to be delivered in
1572         * vmx_check_nested_events().
1573         */
1574        if (nested_cpu_has_mtf(vmcs12) &&
1575            (!vcpu->arch.exception.pending ||
1576             vcpu->arch.exception.nr == DB_VECTOR))
1577                vmx->nested.mtf_pending = true;
1578        else
1579                vmx->nested.mtf_pending = false;
1580}
1581
1582static int vmx_skip_emulated_instruction(struct kvm_vcpu *vcpu)
1583{
1584        vmx_update_emulated_instruction(vcpu);
1585        return skip_emulated_instruction(vcpu);
1586}
1587
1588static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
1589{
1590        /*
1591         * Ensure that we clear the HLT state in the VMCS.  We don't need to
1592         * explicitly skip the instruction because if the HLT state is set,
1593         * then the instruction is already executing and RIP has already been
1594         * advanced.
1595         */
1596        if (kvm_hlt_in_guest(vcpu->kvm) &&
1597                        vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
1598                vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
1599}
1600
1601static void vmx_queue_exception(struct kvm_vcpu *vcpu)
1602{
1603        struct vcpu_vmx *vmx = to_vmx(vcpu);
1604        unsigned nr = vcpu->arch.exception.nr;
1605        bool has_error_code = vcpu->arch.exception.has_error_code;
1606        u32 error_code = vcpu->arch.exception.error_code;
1607        u32 intr_info = nr | INTR_INFO_VALID_MASK;
1608
1609        kvm_deliver_exception_payload(vcpu);
1610
1611        if (has_error_code) {
1612                vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
1613                intr_info |= INTR_INFO_DELIVER_CODE_MASK;
1614        }
1615
1616        if (vmx->rmode.vm86_active) {
1617                int inc_eip = 0;
1618                if (kvm_exception_is_soft(nr))
1619                        inc_eip = vcpu->arch.event_exit_inst_len;
1620                kvm_inject_realmode_interrupt(vcpu, nr, inc_eip);
1621                return;
1622        }
1623
1624        WARN_ON_ONCE(vmx->emulation_required);
1625
1626        if (kvm_exception_is_soft(nr)) {
1627                vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
1628                             vmx->vcpu.arch.event_exit_inst_len);
1629                intr_info |= INTR_TYPE_SOFT_EXCEPTION;
1630        } else
1631                intr_info |= INTR_TYPE_HARD_EXCEPTION;
1632
1633        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
1634
1635        vmx_clear_hlt(vcpu);
1636}
1637
1638static void vmx_setup_uret_msr(struct vcpu_vmx *vmx, unsigned int msr,
1639                               bool load_into_hardware)
1640{
1641        struct vmx_uret_msr *uret_msr;
1642
1643        uret_msr = vmx_find_uret_msr(vmx, msr);
1644        if (!uret_msr)
1645                return;
1646
1647        uret_msr->load_into_hardware = load_into_hardware;
1648}
1649
1650/*
1651 * Set up the vmcs to automatically save and restore system
1652 * msrs.  Don't touch the 64-bit msrs if the guest is in legacy
1653 * mode, as fiddling with msrs is very expensive.
1654 */
1655static void setup_msrs(struct vcpu_vmx *vmx)
1656{
1657#ifdef CONFIG_X86_64
1658        bool load_syscall_msrs;
1659
1660        /*
1661         * The SYSCALL MSRs are only needed on long mode guests, and only
1662         * when EFER.SCE is set.
1663         */
1664        load_syscall_msrs = is_long_mode(&vmx->vcpu) &&
1665                            (vmx->vcpu.arch.efer & EFER_SCE);
1666
1667        vmx_setup_uret_msr(vmx, MSR_STAR, load_syscall_msrs);
1668        vmx_setup_uret_msr(vmx, MSR_LSTAR, load_syscall_msrs);
1669        vmx_setup_uret_msr(vmx, MSR_SYSCALL_MASK, load_syscall_msrs);
1670#endif
1671        vmx_setup_uret_msr(vmx, MSR_EFER, update_transition_efer(vmx));
1672
1673        vmx_setup_uret_msr(vmx, MSR_TSC_AUX,
1674                           guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP) ||
1675                           guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDPID));
1676
1677        /*
1678         * hle=0, rtm=0, tsx_ctrl=1 can be found with some combinations of new
1679         * kernel and old userspace.  If those guests run on a tsx=off host, do
1680         * allow guests to use TSX_CTRL, but don't change the value in hardware
1681         * so that TSX remains always disabled.
1682         */
1683        vmx_setup_uret_msr(vmx, MSR_IA32_TSX_CTRL, boot_cpu_has(X86_FEATURE_RTM));
1684
1685        if (cpu_has_vmx_msr_bitmap())
1686                vmx_update_msr_bitmap(&vmx->vcpu);
1687
1688        /*
1689         * The set of MSRs to load may have changed, reload MSRs before the
1690         * next VM-Enter.
1691         */
1692        vmx->guest_uret_msrs_loaded = false;
1693}
1694
1695u64 vmx_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1696{
1697        struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1698
1699        if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING))
1700                return vmcs12->tsc_offset;
1701
1702        return 0;
1703}
1704
1705u64 vmx_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1706{
1707        struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
1708
1709        if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETTING) &&
1710            nested_cpu_has2(vmcs12, SECONDARY_EXEC_TSC_SCALING))
1711                return vmcs12->tsc_multiplier;
1712
1713        return kvm_default_tsc_scaling_ratio;
1714}
1715
1716static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1717{
1718        vmcs_write64(TSC_OFFSET, offset);
1719}
1720
1721static void vmx_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1722{
1723        vmcs_write64(TSC_MULTIPLIER, multiplier);
1724}
1725
1726/*
1727 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
1728 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
1729 * all guests if the "nested" module option is off, and can also be disabled
1730 * for a single guest by disabling its VMX cpuid bit.
1731 */
1732bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
1733{
1734        return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
1735}
1736
1737static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
1738                                                 uint64_t val)
1739{
1740        uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
1741
1742        return !(val & ~valid_bits);
1743}
1744
1745static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
1746{
1747        switch (msr->index) {
1748        case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1749                if (!nested)
1750                        return 1;
1751                return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
1752        case MSR_IA32_PERF_CAPABILITIES:
1753                msr->data = vmx_get_perf_capabilities();
1754                return 0;
1755        default:
1756                return KVM_MSR_RET_INVALID;
1757        }
1758}
1759
1760/*
1761 * Reads an msr value (of 'msr_index') into 'pdata'.
1762 * Returns 0 on success, non-0 otherwise.
1763 * Assumes vcpu_load() was already called.
1764 */
1765static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1766{
1767        struct vcpu_vmx *vmx = to_vmx(vcpu);
1768        struct vmx_uret_msr *msr;
1769        u32 index;
1770
1771        switch (msr_info->index) {
1772#ifdef CONFIG_X86_64
1773        case MSR_FS_BASE:
1774                msr_info->data = vmcs_readl(GUEST_FS_BASE);
1775                break;
1776        case MSR_GS_BASE:
1777                msr_info->data = vmcs_readl(GUEST_GS_BASE);
1778                break;
1779        case MSR_KERNEL_GS_BASE:
1780                msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
1781                break;
1782#endif
1783        case MSR_EFER:
1784                return kvm_get_msr_common(vcpu, msr_info);
1785        case MSR_IA32_TSX_CTRL:
1786                if (!msr_info->host_initiated &&
1787                    !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
1788                        return 1;
1789                goto find_uret_msr;
1790        case MSR_IA32_UMWAIT_CONTROL:
1791                if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
1792                        return 1;
1793
1794                msr_info->data = vmx->msr_ia32_umwait_control;
1795                break;
1796        case MSR_IA32_SPEC_CTRL:
1797                if (!msr_info->host_initiated &&
1798                    !guest_has_spec_ctrl_msr(vcpu))
1799                        return 1;
1800
1801                msr_info->data = to_vmx(vcpu)->spec_ctrl;
1802                break;
1803        case MSR_IA32_SYSENTER_CS:
1804                msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
1805                break;
1806        case MSR_IA32_SYSENTER_EIP:
1807                msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
1808                break;
1809        case MSR_IA32_SYSENTER_ESP:
1810                msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
1811                break;
1812        case MSR_IA32_BNDCFGS:
1813                if (!kvm_mpx_supported() ||
1814                    (!msr_info->host_initiated &&
1815                     !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
1816                        return 1;
1817                msr_info->data = vmcs_read64(GUEST_BNDCFGS);
1818                break;
1819        case MSR_IA32_MCG_EXT_CTL:
1820                if (!msr_info->host_initiated &&
1821                    !(vmx->msr_ia32_feature_control &
1822                      FEAT_CTL_LMCE_ENABLED))
1823                        return 1;
1824                msr_info->data = vcpu->arch.mcg_ext_ctl;
1825                break;
1826        case MSR_IA32_FEAT_CTL:
1827                msr_info->data = vmx->msr_ia32_feature_control;
1828                break;
1829        case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
1830                if (!msr_info->host_initiated &&
1831                    !guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC))
1832                        return 1;
1833                msr_info->data = to_vmx(vcpu)->msr_ia32_sgxlepubkeyhash
1834                        [msr_info->index - MSR_IA32_SGXLEPUBKEYHASH0];
1835                break;
1836        case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
1837                if (!nested_vmx_allowed(vcpu))
1838                        return 1;
1839                if (vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
1840                                    &msr_info->data))
1841                        return 1;
1842                /*
1843                 * Enlightened VMCS v1 doesn't have certain fields, but buggy
1844                 * Hyper-V versions are still trying to use corresponding
1845                 * features when they are exposed. Filter out the essential
1846                 * minimum.
1847                 */
1848                if (!msr_info->host_initiated &&
1849                    vmx->nested.enlightened_vmcs_enabled)
1850                        nested_evmcs_filter_control_msr(msr_info->index,
1851                                                        &msr_info->data);
1852                break;
1853        case MSR_IA32_RTIT_CTL:
1854                if (!vmx_pt_mode_is_host_guest())
1855                        return 1;
1856                msr_info->data = vmx->pt_desc.guest.ctl;
1857                break;
1858        case MSR_IA32_RTIT_STATUS:
1859                if (!vmx_pt_mode_is_host_guest())
1860                        return 1;
1861                msr_info->data = vmx->pt_desc.guest.status;
1862                break;
1863        case MSR_IA32_RTIT_CR3_MATCH:
1864                if (!vmx_pt_mode_is_host_guest() ||
1865                        !intel_pt_validate_cap(vmx->pt_desc.caps,
1866                                                PT_CAP_cr3_filtering))
1867                        return 1;
1868                msr_info->data = vmx->pt_desc.guest.cr3_match;
1869                break;
1870        case MSR_IA32_RTIT_OUTPUT_BASE:
1871                if (!vmx_pt_mode_is_host_guest() ||
1872                        (!intel_pt_validate_cap(vmx->pt_desc.caps,
1873                                        PT_CAP_topa_output) &&
1874                         !intel_pt_validate_cap(vmx->pt_desc.caps,
1875                                        PT_CAP_single_range_output)))
1876                        return 1;
1877                msr_info->data = vmx->pt_desc.guest.output_base;
1878                break;
1879        case MSR_IA32_RTIT_OUTPUT_MASK:
1880                if (!vmx_pt_mode_is_host_guest() ||
1881                        (!intel_pt_validate_cap(vmx->pt_desc.caps,
1882                                        PT_CAP_topa_output) &&
1883                         !intel_pt_validate_cap(vmx->pt_desc.caps,
1884                                        PT_CAP_single_range_output)))
1885                        return 1;
1886                msr_info->data = vmx->pt_desc.guest.output_mask;
1887                break;
1888        case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
1889                index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
1890                if (!vmx_pt_mode_is_host_guest() ||
1891                        (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
1892                                        PT_CAP_num_address_ranges)))
1893                        return 1;
1894                if (index % 2)
1895                        msr_info->data = vmx->pt_desc.guest.addr_b[index / 2];
1896                else
1897                        msr_info->data = vmx->pt_desc.guest.addr_a[index / 2];
1898                break;
1899        case MSR_IA32_DEBUGCTLMSR:
1900                msr_info->data = vmcs_read64(GUEST_IA32_DEBUGCTL);
1901                break;
1902        default:
1903        find_uret_msr:
1904                msr = vmx_find_uret_msr(vmx, msr_info->index);
1905                if (msr) {
1906                        msr_info->data = msr->data;
1907                        break;
1908                }
1909                return kvm_get_msr_common(vcpu, msr_info);
1910        }
1911
1912        return 0;
1913}
1914
1915static u64 nested_vmx_truncate_sysenter_addr(struct kvm_vcpu *vcpu,
1916                                                    u64 data)
1917{
1918#ifdef CONFIG_X86_64
1919        if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
1920                return (u32)data;
1921#endif
1922        return (unsigned long)data;
1923}
1924
1925static u64 vcpu_supported_debugctl(struct kvm_vcpu *vcpu)
1926{
1927        u64 debugctl = vmx_supported_debugctl();
1928
1929        if (!intel_pmu_lbr_is_enabled(vcpu))
1930                debugctl &= ~DEBUGCTLMSR_LBR_MASK;
1931
1932        if (!guest_cpuid_has(vcpu, X86_FEATURE_BUS_LOCK_DETECT))
1933                debugctl &= ~DEBUGCTLMSR_BUS_LOCK_DETECT;
1934
1935        return debugctl;
1936}
1937
1938/*
1939 * Writes msr value into the appropriate "register".
1940 * Returns 0 on success, non-0 otherwise.
1941 * Assumes vcpu_load() was already called.
1942 */
1943static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
1944{
1945        struct vcpu_vmx *vmx = to_vmx(vcpu);
1946        struct vmx_uret_msr *msr;
1947        int ret = 0;
1948        u32 msr_index = msr_info->index;
1949        u64 data = msr_info->data;
1950        u32 index;
1951
1952        switch (msr_index) {
1953        case MSR_EFER:
1954                ret = kvm_set_msr_common(vcpu, msr_info);
1955                break;
1956#ifdef CONFIG_X86_64
1957        case MSR_FS_BASE:
1958                vmx_segment_cache_clear(vmx);
1959                vmcs_writel(GUEST_FS_BASE, data);
1960                break;
1961        case MSR_GS_BASE:
1962                vmx_segment_cache_clear(vmx);
1963                vmcs_writel(GUEST_GS_BASE, data);
1964                break;
1965        case MSR_KERNEL_GS_BASE:
1966                vmx_write_guest_kernel_gs_base(vmx, data);
1967                break;
1968#endif
1969        case MSR_IA32_SYSENTER_CS:
1970                if (is_guest_mode(vcpu))
1971                        get_vmcs12(vcpu)->guest_sysenter_cs = data;
1972                vmcs_write32(GUEST_SYSENTER_CS, data);
1973                break;
1974        case MSR_IA32_SYSENTER_EIP:
1975                if (is_guest_mode(vcpu)) {
1976                        data = nested_vmx_truncate_sysenter_addr(vcpu, data);
1977                        get_vmcs12(vcpu)->guest_sysenter_eip = data;
1978                }
1979                vmcs_writel(GUEST_SYSENTER_EIP, data);
1980                break;
1981        case MSR_IA32_SYSENTER_ESP:
1982                if (is_guest_mode(vcpu)) {
1983                        data = nested_vmx_truncate_sysenter_addr(vcpu, data);
1984                        get_vmcs12(vcpu)->guest_sysenter_esp = data;
1985                }
1986                vmcs_writel(GUEST_SYSENTER_ESP, data);
1987                break;
1988        case MSR_IA32_DEBUGCTLMSR: {
1989                u64 invalid = data & ~vcpu_supported_debugctl(vcpu);
1990                if (invalid & (DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR)) {
1991                        if (report_ignored_msrs)
1992                                vcpu_unimpl(vcpu, "%s: BTF|LBR in IA32_DEBUGCTLMSR 0x%llx, nop\n",
1993                                            __func__, data);
1994                        data &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
1995                        invalid &= ~(DEBUGCTLMSR_BTF|DEBUGCTLMSR_LBR);
1996                }
1997
1998                if (invalid)
1999                        return 1;
2000
2001                if (is_guest_mode(vcpu) && get_vmcs12(vcpu)->vm_exit_controls &
2002                                                VM_EXIT_SAVE_DEBUG_CONTROLS)
2003                        get_vmcs12(vcpu)->guest_ia32_debugctl = data;
2004
2005                vmcs_write64(GUEST_IA32_DEBUGCTL, data);
2006                if (intel_pmu_lbr_is_enabled(vcpu) && !to_vmx(vcpu)->lbr_desc.event &&
2007                    (data & DEBUGCTLMSR_LBR))
2008                        intel_pmu_create_guest_lbr_event(vcpu);
2009                return 0;
2010        }
2011        case MSR_IA32_BNDCFGS:
2012                if (!kvm_mpx_supported() ||
2013                    (!msr_info->host_initiated &&
2014                     !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
2015                        return 1;
2016                if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
2017                    (data & MSR_IA32_BNDCFGS_RSVD))
2018                        return 1;
2019                vmcs_write64(GUEST_BNDCFGS, data);
2020                break;
2021        case MSR_IA32_UMWAIT_CONTROL:
2022                if (!msr_info->host_initiated && !vmx_has_waitpkg(vmx))
2023                        return 1;
2024
2025                /* The reserved bit 1 and non-32 bit [63:32] should be zero */
2026                if (data & (BIT_ULL(1) | GENMASK_ULL(63, 32)))
2027                        return 1;
2028
2029                vmx->msr_ia32_umwait_control = data;
2030                break;
2031        case MSR_IA32_SPEC_CTRL:
2032                if (!msr_info->host_initiated &&
2033                    !guest_has_spec_ctrl_msr(vcpu))
2034                        return 1;
2035
2036                if (kvm_spec_ctrl_test_value(data))
2037                        return 1;
2038
2039                vmx->spec_ctrl = data;
2040                if (!data)
2041                        break;
2042
2043                /*
2044                 * For non-nested:
2045                 * When it's written (to non-zero) for the first time, pass
2046                 * it through.
2047                 *
2048                 * For nested:
2049                 * The handling of the MSR bitmap for L2 guests is done in
2050                 * nested_vmx_prepare_msr_bitmap. We should not touch the
2051                 * vmcs02.msr_bitmap here since it gets completely overwritten
2052                 * in the merging. We update the vmcs01 here for L1 as well
2053                 * since it will end up touching the MSR anyway now.
2054                 */
2055                vmx_disable_intercept_for_msr(vcpu,
2056                                              MSR_IA32_SPEC_CTRL,
2057                                              MSR_TYPE_RW);
2058                break;
2059        case MSR_IA32_TSX_CTRL:
2060                if (!msr_info->host_initiated &&
2061                    !(vcpu->arch.arch_capabilities & ARCH_CAP_TSX_CTRL_MSR))
2062                        return 1;
2063                if (data & ~(TSX_CTRL_RTM_DISABLE | TSX_CTRL_CPUID_CLEAR))
2064                        return 1;
2065                goto find_uret_msr;
2066        case MSR_IA32_PRED_CMD:
2067                if (!msr_info->host_initiated &&
2068                    !guest_has_pred_cmd_msr(vcpu))
2069                        return 1;
2070
2071                if (data & ~PRED_CMD_IBPB)
2072                        return 1;
2073                if (!boot_cpu_has(X86_FEATURE_IBPB))
2074                        return 1;
2075                if (!data)
2076                        break;
2077
2078                wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2079
2080                /*
2081                 * For non-nested:
2082                 * When it's written (to non-zero) for the first time, pass
2083                 * it through.
2084                 *
2085                 * For nested:
2086                 * The handling of the MSR bitmap for L2 guests is done in
2087                 * nested_vmx_prepare_msr_bitmap. We should not touch the
2088                 * vmcs02.msr_bitmap here since it gets completely overwritten
2089                 * in the merging.
2090                 */
2091                vmx_disable_intercept_for_msr(vcpu, MSR_IA32_PRED_CMD, MSR_TYPE_W);
2092                break;
2093        case MSR_IA32_CR_PAT:
2094                if (!kvm_pat_valid(data))
2095                        return 1;
2096
2097                if (is_guest_mode(vcpu) &&
2098                    get_vmcs12(vcpu)->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
2099                        get_vmcs12(vcpu)->guest_ia32_pat = data;
2100
2101                if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
2102                        vmcs_write64(GUEST_IA32_PAT, data);
2103                        vcpu->arch.pat = data;
2104                        break;
2105                }
2106                ret = kvm_set_msr_common(vcpu, msr_info);
2107                break;
2108        case MSR_IA32_TSC_ADJUST:
2109                ret = kvm_set_msr_common(vcpu, msr_info);
2110                break;
2111        case MSR_IA32_MCG_EXT_CTL:
2112                if ((!msr_info->host_initiated &&
2113                     !(to_vmx(vcpu)->msr_ia32_feature_control &
2114                       FEAT_CTL_LMCE_ENABLED)) ||
2115                    (data & ~MCG_EXT_CTL_LMCE_EN))
2116                        return 1;
2117                vcpu->arch.mcg_ext_ctl = data;
2118                break;
2119        case MSR_IA32_FEAT_CTL:
2120                if (!vmx_feature_control_msr_valid(vcpu, data) ||
2121                    (to_vmx(vcpu)->msr_ia32_feature_control &
2122                     FEAT_CTL_LOCKED && !msr_info->host_initiated))
2123                        return 1;
2124                vmx->msr_ia32_feature_control = data;
2125                if (msr_info->host_initiated && data == 0)
2126                        vmx_leave_nested(vcpu);
2127
2128                /* SGX may be enabled/disabled by guest's firmware */
2129                vmx_write_encls_bitmap(vcpu, NULL);
2130                break;
2131        case MSR_IA32_SGXLEPUBKEYHASH0 ... MSR_IA32_SGXLEPUBKEYHASH3:
2132                /*
2133                 * On real hardware, the LE hash MSRs are writable before
2134                 * the firmware sets bit 0 in MSR 0x7a ("activating" SGX),
2135                 * at which point SGX related bits in IA32_FEATURE_CONTROL
2136                 * become writable.
2137                 *
2138                 * KVM does not emulate SGX activation for simplicity, so
2139                 * allow writes to the LE hash MSRs if IA32_FEATURE_CONTROL
2140                 * is unlocked.  This is technically not architectural
2141                 * behavior, but it's close enough.
2142                 */
2143                if (!msr_info->host_initiated &&
2144                    (!guest_cpuid_has(vcpu, X86_FEATURE_SGX_LC) ||
2145                    ((vmx->msr_ia32_feature_control & FEAT_CTL_LOCKED) &&
2146                    !(vmx->msr_ia32_feature_control & FEAT_CTL_SGX_LC_ENABLED))))
2147                        return 1;
2148                vmx->msr_ia32_sgxlepubkeyhash
2149                        [msr_index - MSR_IA32_SGXLEPUBKEYHASH0] = data;
2150                break;
2151        case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
2152                if (!msr_info->host_initiated)
2153                        return 1; /* they are read-only */
2154                if (!nested_vmx_allowed(vcpu))
2155                        return 1;
2156                return vmx_set_vmx_msr(vcpu, msr_index, data);
2157        case MSR_IA32_RTIT_CTL:
2158                if (!vmx_pt_mode_is_host_guest() ||
2159                        vmx_rtit_ctl_check(vcpu, data) ||
2160                        vmx->nested.vmxon)
2161                        return 1;
2162                vmcs_write64(GUEST_IA32_RTIT_CTL, data);
2163                vmx->pt_desc.guest.ctl = data;
2164                pt_update_intercept_for_msr(vcpu);
2165                break;
2166        case MSR_IA32_RTIT_STATUS:
2167                if (!pt_can_write_msr(vmx))
2168                        return 1;
2169                if (data & MSR_IA32_RTIT_STATUS_MASK)
2170                        return 1;
2171                vmx->pt_desc.guest.status = data;
2172                break;
2173        case MSR_IA32_RTIT_CR3_MATCH:
2174                if (!pt_can_write_msr(vmx))
2175                        return 1;
2176                if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2177                                           PT_CAP_cr3_filtering))
2178                        return 1;
2179                vmx->pt_desc.guest.cr3_match = data;
2180                break;
2181        case MSR_IA32_RTIT_OUTPUT_BASE:
2182                if (!pt_can_write_msr(vmx))
2183                        return 1;
2184                if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2185                                           PT_CAP_topa_output) &&
2186                    !intel_pt_validate_cap(vmx->pt_desc.caps,
2187                                           PT_CAP_single_range_output))
2188                        return 1;
2189                if (!pt_output_base_valid(vcpu, data))
2190                        return 1;
2191                vmx->pt_desc.guest.output_base = data;
2192                break;
2193        case MSR_IA32_RTIT_OUTPUT_MASK:
2194                if (!pt_can_write_msr(vmx))
2195                        return 1;
2196                if (!intel_pt_validate_cap(vmx->pt_desc.caps,
2197                                           PT_CAP_topa_output) &&
2198                    !intel_pt_validate_cap(vmx->pt_desc.caps,
2199                                           PT_CAP_single_range_output))
2200                        return 1;
2201                vmx->pt_desc.guest.output_mask = data;
2202                break;
2203        case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
2204                if (!pt_can_write_msr(vmx))
2205                        return 1;
2206                index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
2207                if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
2208                                                       PT_CAP_num_address_ranges))
2209                        return 1;
2210                if (is_noncanonical_address(data, vcpu))
2211                        return 1;
2212                if (index % 2)
2213                        vmx->pt_desc.guest.addr_b[index / 2] = data;
2214                else
2215                        vmx->pt_desc.guest.addr_a[index / 2] = data;
2216                break;
2217        case MSR_IA32_PERF_CAPABILITIES:
2218                if (data && !vcpu_to_pmu(vcpu)->version)
2219                        return 1;
2220                if (data & PMU_CAP_LBR_FMT) {
2221                        if ((data & PMU_CAP_LBR_FMT) !=
2222                            (vmx_get_perf_capabilities() & PMU_CAP_LBR_FMT))
2223                                return 1;
2224                        if (!intel_pmu_lbr_is_compatible(vcpu))
2225                                return 1;
2226                }
2227                ret = kvm_set_msr_common(vcpu, msr_info);
2228                break;
2229
2230        default:
2231        find_uret_msr:
2232                msr = vmx_find_uret_msr(vmx, msr_index);
2233                if (msr)
2234                        ret = vmx_set_guest_uret_msr(vmx, msr, data);
2235                else
2236                        ret = kvm_set_msr_common(vcpu, msr_info);
2237        }
2238
2239        return ret;
2240}
2241
2242static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2243{
2244        unsigned long guest_owned_bits;
2245
2246        kvm_register_mark_available(vcpu, reg);
2247
2248        switch (reg) {
2249        case VCPU_REGS_RSP:
2250                vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
2251                break;
2252        case VCPU_REGS_RIP:
2253                vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
2254                break;
2255        case VCPU_EXREG_PDPTR:
2256                if (enable_ept)
2257                        ept_save_pdptrs(vcpu);
2258                break;
2259        case VCPU_EXREG_CR0:
2260                guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
2261
2262                vcpu->arch.cr0 &= ~guest_owned_bits;
2263                vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & guest_owned_bits;
2264                break;
2265        case VCPU_EXREG_CR3:
2266                if (is_unrestricted_guest(vcpu) ||
2267                    (enable_ept && is_paging(vcpu)))
2268                        vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
2269                break;
2270        case VCPU_EXREG_CR4:
2271                guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
2272
2273                vcpu->arch.cr4 &= ~guest_owned_bits;
2274                vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & guest_owned_bits;
2275                break;
2276        default:
2277                WARN_ON_ONCE(1);
2278                break;
2279        }
2280}
2281
2282static __init int cpu_has_kvm_support(void)
2283{
2284        return cpu_has_vmx();
2285}
2286
2287static __init int vmx_disabled_by_bios(void)
2288{
2289        return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
2290               !boot_cpu_has(X86_FEATURE_VMX);
2291}
2292
2293static int kvm_cpu_vmxon(u64 vmxon_pointer)
2294{
2295        u64 msr;
2296
2297        cr4_set_bits(X86_CR4_VMXE);
2298
2299        asm_volatile_goto("1: vmxon %[vmxon_pointer]\n\t"
2300                          _ASM_EXTABLE(1b, %l[fault])
2301                          : : [vmxon_pointer] "m"(vmxon_pointer)
2302                          : : fault);
2303        return 0;
2304
2305fault:
2306        WARN_ONCE(1, "VMXON faulted, MSR_IA32_FEAT_CTL (0x3a) = 0x%llx\n",
2307                  rdmsrl_safe(MSR_IA32_FEAT_CTL, &msr) ? 0xdeadbeef : msr);
2308        cr4_clear_bits(X86_CR4_VMXE);
2309
2310        return -EFAULT;
2311}
2312
2313static int hardware_enable(void)
2314{
2315        int cpu = raw_smp_processor_id();
2316        u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2317        int r;
2318
2319        if (cr4_read_shadow() & X86_CR4_VMXE)
2320                return -EBUSY;
2321
2322        /*
2323         * This can happen if we hot-added a CPU but failed to allocate
2324         * VP assist page for it.
2325         */
2326        if (static_branch_unlikely(&enable_evmcs) &&
2327            !hv_get_vp_assist_page(cpu))
2328                return -EFAULT;
2329
2330        intel_pt_handle_vmx(1);
2331
2332        r = kvm_cpu_vmxon(phys_addr);
2333        if (r) {
2334                intel_pt_handle_vmx(0);
2335                return r;
2336        }
2337
2338        if (enable_ept)
2339                ept_sync_global();
2340
2341        return 0;
2342}
2343
2344static void vmclear_local_loaded_vmcss(void)
2345{
2346        int cpu = raw_smp_processor_id();
2347        struct loaded_vmcs *v, *n;
2348
2349        list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
2350                                 loaded_vmcss_on_cpu_link)
2351                __loaded_vmcs_clear(v);
2352}
2353
2354static void hardware_disable(void)
2355{
2356        vmclear_local_loaded_vmcss();
2357
2358        if (cpu_vmxoff())
2359                kvm_spurious_fault();
2360
2361        intel_pt_handle_vmx(0);
2362}
2363
2364/*
2365 * There is no X86_FEATURE for SGX yet, but anyway we need to query CPUID
2366 * directly instead of going through cpu_has(), to ensure KVM is trapping
2367 * ENCLS whenever it's supported in hardware.  It does not matter whether
2368 * the host OS supports or has enabled SGX.
2369 */
2370static bool cpu_has_sgx(void)
2371{
2372        return cpuid_eax(0) >= 0x12 && (cpuid_eax(0x12) & BIT(0));
2373}
2374
2375static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
2376                                      u32 msr, u32 *result)
2377{
2378        u32 vmx_msr_low, vmx_msr_high;
2379        u32 ctl = ctl_min | ctl_opt;
2380
2381        rdmsr(msr, vmx_msr_low, vmx_msr_high);
2382
2383        ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
2384        ctl |= vmx_msr_low;  /* bit == 1 in low word  ==> must be one  */
2385
2386        /* Ensure minimum (required) set of control bits are supported. */
2387        if (ctl_min & ~ctl)
2388                return -EIO;
2389
2390        *result = ctl;
2391        return 0;
2392}
2393
2394static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf,
2395                                    struct vmx_capability *vmx_cap)
2396{
2397        u32 vmx_msr_low, vmx_msr_high;
2398        u32 min, opt, min2, opt2;
2399        u32 _pin_based_exec_control = 0;
2400        u32 _cpu_based_exec_control = 0;
2401        u32 _cpu_based_2nd_exec_control = 0;
2402        u32 _vmexit_control = 0;
2403        u32 _vmentry_control = 0;
2404
2405        memset(vmcs_conf, 0, sizeof(*vmcs_conf));
2406        min = CPU_BASED_HLT_EXITING |
2407#ifdef CONFIG_X86_64
2408              CPU_BASED_CR8_LOAD_EXITING |
2409              CPU_BASED_CR8_STORE_EXITING |
2410#endif
2411              CPU_BASED_CR3_LOAD_EXITING |
2412              CPU_BASED_CR3_STORE_EXITING |
2413              CPU_BASED_UNCOND_IO_EXITING |
2414              CPU_BASED_MOV_DR_EXITING |
2415              CPU_BASED_USE_TSC_OFFSETTING |
2416              CPU_BASED_MWAIT_EXITING |
2417              CPU_BASED_MONITOR_EXITING |
2418              CPU_BASED_INVLPG_EXITING |
2419              CPU_BASED_RDPMC_EXITING;
2420
2421        opt = CPU_BASED_TPR_SHADOW |
2422              CPU_BASED_USE_MSR_BITMAPS |
2423              CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2424        if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
2425                                &_cpu_based_exec_control) < 0)
2426                return -EIO;
2427#ifdef CONFIG_X86_64
2428        if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2429                _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
2430                                           ~CPU_BASED_CR8_STORE_EXITING;
2431#endif
2432        if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
2433                min2 = 0;
2434                opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2435                        SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2436                        SECONDARY_EXEC_WBINVD_EXITING |
2437                        SECONDARY_EXEC_ENABLE_VPID |
2438                        SECONDARY_EXEC_ENABLE_EPT |
2439                        SECONDARY_EXEC_UNRESTRICTED_GUEST |
2440                        SECONDARY_EXEC_PAUSE_LOOP_EXITING |
2441                        SECONDARY_EXEC_DESC |
2442                        SECONDARY_EXEC_ENABLE_RDTSCP |
2443                        SECONDARY_EXEC_ENABLE_INVPCID |
2444                        SECONDARY_EXEC_APIC_REGISTER_VIRT |
2445                        SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2446                        SECONDARY_EXEC_SHADOW_VMCS |
2447                        SECONDARY_EXEC_XSAVES |
2448                        SECONDARY_EXEC_RDSEED_EXITING |
2449                        SECONDARY_EXEC_RDRAND_EXITING |
2450                        SECONDARY_EXEC_ENABLE_PML |
2451                        SECONDARY_EXEC_TSC_SCALING |
2452                        SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE |
2453                        SECONDARY_EXEC_PT_USE_GPA |
2454                        SECONDARY_EXEC_PT_CONCEAL_VMX |
2455                        SECONDARY_EXEC_ENABLE_VMFUNC |
2456                        SECONDARY_EXEC_BUS_LOCK_DETECTION;
2457                if (cpu_has_sgx())
2458                        opt2 |= SECONDARY_EXEC_ENCLS_EXITING;
2459                if (adjust_vmx_controls(min2, opt2,
2460                                        MSR_IA32_VMX_PROCBASED_CTLS2,
2461                                        &_cpu_based_2nd_exec_control) < 0)
2462                        return -EIO;
2463        }
2464#ifndef CONFIG_X86_64
2465        if (!(_cpu_based_2nd_exec_control &
2466                                SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
2467                _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
2468#endif
2469
2470        if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
2471                _cpu_based_2nd_exec_control &= ~(
2472                                SECONDARY_EXEC_APIC_REGISTER_VIRT |
2473                                SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2474                                SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2475
2476        rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
2477                &vmx_cap->ept, &vmx_cap->vpid);
2478
2479        if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
2480                /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
2481                   enabled */
2482                _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
2483                                             CPU_BASED_CR3_STORE_EXITING |
2484                                             CPU_BASED_INVLPG_EXITING);
2485        } else if (vmx_cap->ept) {
2486                vmx_cap->ept = 0;
2487                pr_warn_once("EPT CAP should not exist if not support "
2488                                "1-setting enable EPT VM-execution control\n");
2489        }
2490        if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
2491                vmx_cap->vpid) {
2492                vmx_cap->vpid = 0;
2493                pr_warn_once("VPID CAP should not exist if not support "
2494                                "1-setting enable VPID VM-execution control\n");
2495        }
2496
2497        min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
2498#ifdef CONFIG_X86_64
2499        min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
2500#endif
2501        opt = VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL |
2502              VM_EXIT_LOAD_IA32_PAT |
2503              VM_EXIT_LOAD_IA32_EFER |
2504              VM_EXIT_CLEAR_BNDCFGS |
2505              VM_EXIT_PT_CONCEAL_PIP |
2506              VM_EXIT_CLEAR_IA32_RTIT_CTL;
2507        if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
2508                                &_vmexit_control) < 0)
2509                return -EIO;
2510
2511        min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
2512        opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
2513                 PIN_BASED_VMX_PREEMPTION_TIMER;
2514        if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
2515                                &_pin_based_exec_control) < 0)
2516                return -EIO;
2517
2518        if (cpu_has_broken_vmx_preemption_timer())
2519                _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
2520        if (!(_cpu_based_2nd_exec_control &
2521                SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
2522                _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
2523
2524        min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
2525        opt = VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL |
2526              VM_ENTRY_LOAD_IA32_PAT |
2527              VM_ENTRY_LOAD_IA32_EFER |
2528              VM_ENTRY_LOAD_BNDCFGS |
2529              VM_ENTRY_PT_CONCEAL_PIP |
2530              VM_ENTRY_LOAD_IA32_RTIT_CTL;
2531        if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
2532                                &_vmentry_control) < 0)
2533                return -EIO;
2534
2535        /*
2536         * Some cpus support VM_{ENTRY,EXIT}_IA32_PERF_GLOBAL_CTRL but they
2537         * can't be used due to an errata where VM Exit may incorrectly clear
2538         * IA32_PERF_GLOBAL_CTRL[34:32].  Workaround the errata by using the
2539         * MSR load mechanism to switch IA32_PERF_GLOBAL_CTRL.
2540         */
2541        if (boot_cpu_data.x86 == 0x6) {
2542                switch (boot_cpu_data.x86_model) {
2543                case 26: /* AAK155 */
2544                case 30: /* AAP115 */
2545                case 37: /* AAT100 */
2546                case 44: /* BC86,AAY89,BD102 */
2547                case 46: /* BA97 */
2548                        _vmentry_control &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
2549                        _vmexit_control &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
2550                        pr_warn_once("kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
2551                                        "does not work properly. Using workaround\n");
2552                        break;
2553                default:
2554                        break;
2555                }
2556        }
2557
2558
2559        rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
2560
2561        /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
2562        if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
2563                return -EIO;
2564
2565#ifdef CONFIG_X86_64
2566        /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
2567        if (vmx_msr_high & (1u<<16))
2568                return -EIO;
2569#endif
2570
2571        /* Require Write-Back (WB) memory type for VMCS accesses. */
2572        if (((vmx_msr_high >> 18) & 15) != 6)
2573                return -EIO;
2574
2575        vmcs_conf->size = vmx_msr_high & 0x1fff;
2576        vmcs_conf->order = get_order(vmcs_conf->size);
2577        vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
2578
2579        vmcs_conf->revision_id = vmx_msr_low;
2580
2581        vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
2582        vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
2583        vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
2584        vmcs_conf->vmexit_ctrl         = _vmexit_control;
2585        vmcs_conf->vmentry_ctrl        = _vmentry_control;
2586
2587#if IS_ENABLED(CONFIG_HYPERV)
2588        if (enlightened_vmcs)
2589                evmcs_sanitize_exec_ctrls(vmcs_conf);
2590#endif
2591
2592        return 0;
2593}
2594
2595struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu, gfp_t flags)
2596{
2597        int node = cpu_to_node(cpu);
2598        struct page *pages;
2599        struct vmcs *vmcs;
2600
2601        pages = __alloc_pages_node(node, flags, vmcs_config.order);
2602        if (!pages)
2603                return NULL;
2604        vmcs = page_address(pages);
2605        memset(vmcs, 0, vmcs_config.size);
2606
2607        /* KVM supports Enlightened VMCS v1 only */
2608        if (static_branch_unlikely(&enable_evmcs))
2609                vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
2610        else
2611                vmcs->hdr.revision_id = vmcs_config.revision_id;
2612
2613        if (shadow)
2614                vmcs->hdr.shadow_vmcs = 1;
2615        return vmcs;
2616}
2617
2618void free_vmcs(struct vmcs *vmcs)
2619{
2620        free_pages((unsigned long)vmcs, vmcs_config.order);
2621}
2622
2623/*
2624 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
2625 */
2626void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2627{
2628        if (!loaded_vmcs->vmcs)
2629                return;
2630        loaded_vmcs_clear(loaded_vmcs);
2631        free_vmcs(loaded_vmcs->vmcs);
2632        loaded_vmcs->vmcs = NULL;
2633        if (loaded_vmcs->msr_bitmap)
2634                free_page((unsigned long)loaded_vmcs->msr_bitmap);
2635        WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
2636}
2637
2638int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
2639{
2640        loaded_vmcs->vmcs = alloc_vmcs(false);
2641        if (!loaded_vmcs->vmcs)
2642                return -ENOMEM;
2643
2644        vmcs_clear(loaded_vmcs->vmcs);
2645
2646        loaded_vmcs->shadow_vmcs = NULL;
2647        loaded_vmcs->hv_timer_soft_disabled = false;
2648        loaded_vmcs->cpu = -1;
2649        loaded_vmcs->launched = 0;
2650
2651        if (cpu_has_vmx_msr_bitmap()) {
2652                loaded_vmcs->msr_bitmap = (unsigned long *)
2653                                __get_free_page(GFP_KERNEL_ACCOUNT);
2654                if (!loaded_vmcs->msr_bitmap)
2655                        goto out_vmcs;
2656                memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
2657
2658                if (IS_ENABLED(CONFIG_HYPERV) &&
2659                    static_branch_unlikely(&enable_evmcs) &&
2660                    (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
2661                        struct hv_enlightened_vmcs *evmcs =
2662                                (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
2663
2664                        evmcs->hv_enlightenments_control.msr_bitmap = 1;
2665                }
2666        }
2667
2668        memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
2669        memset(&loaded_vmcs->controls_shadow, 0,
2670                sizeof(struct vmcs_controls_shadow));
2671
2672        return 0;
2673
2674out_vmcs:
2675        free_loaded_vmcs(loaded_vmcs);
2676        return -ENOMEM;
2677}
2678
2679static void free_kvm_area(void)
2680{
2681        int cpu;
2682
2683        for_each_possible_cpu(cpu) {
2684                free_vmcs(per_cpu(vmxarea, cpu));
2685                per_cpu(vmxarea, cpu) = NULL;
2686        }
2687}
2688
2689static __init int alloc_kvm_area(void)
2690{
2691        int cpu;
2692
2693        for_each_possible_cpu(cpu) {
2694                struct vmcs *vmcs;
2695
2696                vmcs = alloc_vmcs_cpu(false, cpu, GFP_KERNEL);
2697                if (!vmcs) {
2698                        free_kvm_area();
2699                        return -ENOMEM;
2700                }
2701
2702                /*
2703                 * When eVMCS is enabled, alloc_vmcs_cpu() sets
2704                 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
2705                 * revision_id reported by MSR_IA32_VMX_BASIC.
2706                 *
2707                 * However, even though not explicitly documented by
2708                 * TLFS, VMXArea passed as VMXON argument should
2709                 * still be marked with revision_id reported by
2710                 * physical CPU.
2711                 */
2712                if (static_branch_unlikely(&enable_evmcs))
2713                        vmcs->hdr.revision_id = vmcs_config.revision_id;
2714
2715                per_cpu(vmxarea, cpu) = vmcs;
2716        }
2717        return 0;
2718}
2719
2720static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
2721                struct kvm_segment *save)
2722{
2723        if (!emulate_invalid_guest_state) {
2724                /*
2725                 * CS and SS RPL should be equal during guest entry according
2726                 * to VMX spec, but in reality it is not always so. Since vcpu
2727                 * is in the middle of the transition from real mode to
2728                 * protected mode it is safe to assume that RPL 0 is a good
2729                 * default value.
2730                 */
2731                if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
2732                        save->selector &= ~SEGMENT_RPL_MASK;
2733                save->dpl = save->selector & SEGMENT_RPL_MASK;
2734                save->s = 1;
2735        }
2736        vmx_set_segment(vcpu, save, seg);
2737}
2738
2739static void enter_pmode(struct kvm_vcpu *vcpu)
2740{
2741        unsigned long flags;
2742        struct vcpu_vmx *vmx = to_vmx(vcpu);
2743
2744        /*
2745         * Update real mode segment cache. It may be not up-to-date if segment
2746         * register was written while vcpu was in a guest mode.
2747         */
2748        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2749        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2750        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2751        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2752        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2753        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2754
2755        vmx->rmode.vm86_active = 0;
2756
2757        vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2758
2759        flags = vmcs_readl(GUEST_RFLAGS);
2760        flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2761        flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2762        vmcs_writel(GUEST_RFLAGS, flags);
2763
2764        vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
2765                        (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
2766
2767        vmx_update_exception_bitmap(vcpu);
2768
2769        fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2770        fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2771        fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2772        fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2773        fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2774        fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2775}
2776
2777static void fix_rmode_seg(int seg, struct kvm_segment *save)
2778{
2779        const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
2780        struct kvm_segment var = *save;
2781
2782        var.dpl = 0x3;
2783        if (seg == VCPU_SREG_CS)
2784                var.type = 0x3;
2785
2786        if (!emulate_invalid_guest_state) {
2787                var.selector = var.base >> 4;
2788                var.base = var.base & 0xffff0;
2789                var.limit = 0xffff;
2790                var.g = 0;
2791                var.db = 0;
2792                var.present = 1;
2793                var.s = 1;
2794                var.l = 0;
2795                var.unusable = 0;
2796                var.type = 0x3;
2797                var.avl = 0;
2798                if (save->base & 0xf)
2799                        printk_once(KERN_WARNING "kvm: segment base is not "
2800                                        "paragraph aligned when entering "
2801                                        "protected mode (seg=%d)", seg);
2802        }
2803
2804        vmcs_write16(sf->selector, var.selector);
2805        vmcs_writel(sf->base, var.base);
2806        vmcs_write32(sf->limit, var.limit);
2807        vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
2808}
2809
2810static void enter_rmode(struct kvm_vcpu *vcpu)
2811{
2812        unsigned long flags;
2813        struct vcpu_vmx *vmx = to_vmx(vcpu);
2814        struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
2815
2816        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
2817        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
2818        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
2819        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
2820        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
2821        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
2822        vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
2823
2824        vmx->rmode.vm86_active = 1;
2825
2826        /*
2827         * Very old userspace does not call KVM_SET_TSS_ADDR before entering
2828         * vcpu. Warn the user that an update is overdue.
2829         */
2830        if (!kvm_vmx->tss_addr)
2831                printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
2832                             "called before entering vcpu\n");
2833
2834        vmx_segment_cache_clear(vmx);
2835
2836        vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
2837        vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
2838        vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
2839
2840        flags = vmcs_readl(GUEST_RFLAGS);
2841        vmx->rmode.save_rflags = flags;
2842
2843        flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2844
2845        vmcs_writel(GUEST_RFLAGS, flags);
2846        vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
2847        vmx_update_exception_bitmap(vcpu);
2848
2849        fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
2850        fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
2851        fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
2852        fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
2853        fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
2854        fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
2855
2856        kvm_mmu_reset_context(vcpu);
2857}
2858
2859int vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
2860{
2861        struct vcpu_vmx *vmx = to_vmx(vcpu);
2862        struct vmx_uret_msr *msr = vmx_find_uret_msr(vmx, MSR_EFER);
2863
2864        /* Nothing to do if hardware doesn't support EFER. */
2865        if (!msr)
2866                return 0;
2867
2868        vcpu->arch.efer = efer;
2869        if (efer & EFER_LMA) {
2870                vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2871                msr->data = efer;
2872        } else {
2873                vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2874
2875                msr->data = efer & ~EFER_LME;
2876        }
2877        setup_msrs(vmx);
2878        return 0;
2879}
2880
2881#ifdef CONFIG_X86_64
2882
2883static void enter_lmode(struct kvm_vcpu *vcpu)
2884{
2885        u32 guest_tr_ar;
2886
2887        vmx_segment_cache_clear(to_vmx(vcpu));
2888
2889        guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
2890        if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
2891                pr_debug_ratelimited("%s: tss fixup for long mode. \n",
2892                                     __func__);
2893                vmcs_write32(GUEST_TR_AR_BYTES,
2894                             (guest_tr_ar & ~VMX_AR_TYPE_MASK)
2895                             | VMX_AR_TYPE_BUSY_64_TSS);
2896        }
2897        vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
2898}
2899
2900static void exit_lmode(struct kvm_vcpu *vcpu)
2901{
2902        vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
2903        vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
2904}
2905
2906#endif
2907
2908static void vmx_flush_tlb_all(struct kvm_vcpu *vcpu)
2909{
2910        struct vcpu_vmx *vmx = to_vmx(vcpu);
2911
2912        /*
2913         * INVEPT must be issued when EPT is enabled, irrespective of VPID, as
2914         * the CPU is not required to invalidate guest-physical mappings on
2915         * VM-Entry, even if VPID is disabled.  Guest-physical mappings are
2916         * associated with the root EPT structure and not any particular VPID
2917         * (INVVPID also isn't required to invalidate guest-physical mappings).
2918         */
2919        if (enable_ept) {
2920                ept_sync_global();
2921        } else if (enable_vpid) {
2922                if (cpu_has_vmx_invvpid_global()) {
2923                        vpid_sync_vcpu_global();
2924                } else {
2925                        vpid_sync_vcpu_single(vmx->vpid);
2926                        vpid_sync_vcpu_single(vmx->nested.vpid02);
2927                }
2928        }
2929}
2930
2931static void vmx_flush_tlb_current(struct kvm_vcpu *vcpu)
2932{
2933        struct kvm_mmu *mmu = vcpu->arch.mmu;
2934        u64 root_hpa = mmu->root_hpa;
2935
2936        /* No flush required if the current context is invalid. */
2937        if (!VALID_PAGE(root_hpa))
2938                return;
2939
2940        if (enable_ept)
2941                ept_sync_context(construct_eptp(vcpu, root_hpa,
2942                                                mmu->shadow_root_level));
2943        else if (!is_guest_mode(vcpu))
2944                vpid_sync_context(to_vmx(vcpu)->vpid);
2945        else
2946                vpid_sync_context(nested_get_vpid02(vcpu));
2947}
2948
2949static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
2950{
2951        /*
2952         * vpid_sync_vcpu_addr() is a nop if vmx->vpid==0, see the comment in
2953         * vmx_flush_tlb_guest() for an explanation of why this is ok.
2954         */
2955        vpid_sync_vcpu_addr(to_vmx(vcpu)->vpid, addr);
2956}
2957
2958static void vmx_flush_tlb_guest(struct kvm_vcpu *vcpu)
2959{
2960        /*
2961         * vpid_sync_context() is a nop if vmx->vpid==0, e.g. if enable_vpid==0
2962         * or a vpid couldn't be allocated for this vCPU.  VM-Enter and VM-Exit
2963         * are required to flush GVA->{G,H}PA mappings from the TLB if vpid is
2964         * disabled (VM-Enter with vpid enabled and vpid==0 is disallowed),
2965         * i.e. no explicit INVVPID is necessary.
2966         */
2967        vpid_sync_context(to_vmx(vcpu)->vpid);
2968}
2969
2970void vmx_ept_load_pdptrs(struct kvm_vcpu *vcpu)
2971{
2972        struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2973
2974        if (!kvm_register_is_dirty(vcpu, VCPU_EXREG_PDPTR))
2975                return;
2976
2977        if (is_pae_paging(vcpu)) {
2978                vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
2979                vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
2980                vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
2981                vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
2982        }
2983}
2984
2985void ept_save_pdptrs(struct kvm_vcpu *vcpu)
2986{
2987        struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
2988
2989        if (WARN_ON_ONCE(!is_pae_paging(vcpu)))
2990                return;
2991
2992        mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
2993        mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
2994        mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
2995        mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
2996
2997        kvm_register_mark_dirty(vcpu, VCPU_EXREG_PDPTR);
2998}
2999
3000static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
3001                                        unsigned long cr0,
3002                                        struct kvm_vcpu *vcpu)
3003{
3004        struct vcpu_vmx *vmx = to_vmx(vcpu);
3005
3006        if (!kvm_register_is_available(vcpu, VCPU_EXREG_CR3))
3007                vmx_cache_reg(vcpu, VCPU_EXREG_CR3);
3008        if (!(cr0 & X86_CR0_PG)) {
3009                /* From paging/starting to nonpaging */
3010                exec_controls_setbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3011                                          CPU_BASED_CR3_STORE_EXITING);
3012                vcpu->arch.cr0 = cr0;
3013                vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3014        } else if (!is_paging(vcpu)) {
3015                /* From nonpaging to paging */
3016                exec_controls_clearbit(vmx, CPU_BASED_CR3_LOAD_EXITING |
3017                                            CPU_BASED_CR3_STORE_EXITING);
3018                vcpu->arch.cr0 = cr0;
3019                vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
3020        }
3021
3022        if (!(cr0 & X86_CR0_WP))
3023                *hw_cr0 &= ~X86_CR0_WP;
3024}
3025
3026void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
3027{
3028        struct vcpu_vmx *vmx = to_vmx(vcpu);
3029        unsigned long hw_cr0;
3030
3031        hw_cr0 = (cr0 & ~KVM_VM_CR0_ALWAYS_OFF);
3032        if (is_unrestricted_guest(vcpu))
3033                hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
3034        else {
3035                hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
3036
3037                if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
3038                        enter_pmode(vcpu);
3039
3040                if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
3041                        enter_rmode(vcpu);
3042        }
3043
3044#ifdef CONFIG_X86_64
3045        if (vcpu->arch.efer & EFER_LME) {
3046                if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
3047                        enter_lmode(vcpu);
3048                if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
3049                        exit_lmode(vcpu);
3050        }
3051#endif
3052
3053        if (enable_ept && !is_unrestricted_guest(vcpu))
3054                ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
3055
3056        vmcs_writel(CR0_READ_SHADOW, cr0);
3057        vmcs_writel(GUEST_CR0, hw_cr0);
3058        vcpu->arch.cr0 = cr0;
3059        kvm_register_mark_available(vcpu, VCPU_EXREG_CR0);
3060
3061        /* depends on vcpu->arch.cr0 to be set to a new value */
3062        vmx->emulation_required = emulation_required(vcpu);
3063}
3064
3065static int vmx_get_max_tdp_level(void)
3066{
3067        if (cpu_has_vmx_ept_5levels())
3068                return 5;
3069        return 4;
3070}
3071
3072u64 construct_eptp(struct kvm_vcpu *vcpu, hpa_t root_hpa, int root_level)
3073{
3074        u64 eptp = VMX_EPTP_MT_WB;
3075
3076        eptp |= (root_level == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
3077
3078        if (enable_ept_ad_bits &&
3079            (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
3080                eptp |= VMX_EPTP_AD_ENABLE_BIT;
3081        eptp |= root_hpa;
3082
3083        return eptp;
3084}
3085
3086static void vmx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3087                             int root_level)
3088{
3089        struct kvm *kvm = vcpu->kvm;
3090        bool update_guest_cr3 = true;
3091        unsigned long guest_cr3;
3092        u64 eptp;
3093
3094        if (enable_ept) {
3095                eptp = construct_eptp(vcpu, root_hpa, root_level);
3096                vmcs_write64(EPT_POINTER, eptp);
3097
3098                hv_track_root_tdp(vcpu, root_hpa);
3099
3100                if (!enable_unrestricted_guest && !is_paging(vcpu))
3101                        guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
3102                else if (test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3103                        guest_cr3 = vcpu->arch.cr3;
3104                else /* vmcs01.GUEST_CR3 is already up-to-date. */
3105                        update_guest_cr3 = false;
3106                vmx_ept_load_pdptrs(vcpu);
3107        } else {
3108                guest_cr3 = root_hpa | kvm_get_active_pcid(vcpu);
3109        }
3110
3111        if (update_guest_cr3)
3112                vmcs_writel(GUEST_CR3, guest_cr3);
3113}
3114
3115static bool vmx_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3116{
3117        /*
3118         * We operate under the default treatment of SMM, so VMX cannot be
3119         * enabled under SMM.  Note, whether or not VMXE is allowed at all is
3120         * handled by kvm_is_valid_cr4().
3121         */
3122        if ((cr4 & X86_CR4_VMXE) && is_smm(vcpu))
3123                return false;
3124
3125        if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
3126                return false;
3127
3128        return true;
3129}
3130
3131void vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
3132{
3133        unsigned long old_cr4 = vcpu->arch.cr4;
3134        struct vcpu_vmx *vmx = to_vmx(vcpu);
3135        /*
3136         * Pass through host's Machine Check Enable value to hw_cr4, which
3137         * is in force while we are in guest mode.  Do not let guests control
3138         * this bit, even if host CR4.MCE == 0.
3139         */
3140        unsigned long hw_cr4;
3141
3142        hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
3143        if (is_unrestricted_guest(vcpu))
3144                hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
3145        else if (vmx->rmode.vm86_active)
3146                hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
3147        else
3148                hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
3149
3150        if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
3151                if (cr4 & X86_CR4_UMIP) {
3152                        secondary_exec_controls_setbit(vmx, SECONDARY_EXEC_DESC);
3153                        hw_cr4 &= ~X86_CR4_UMIP;
3154                } else if (!is_guest_mode(vcpu) ||
3155                        !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC)) {
3156                        secondary_exec_controls_clearbit(vmx, SECONDARY_EXEC_DESC);
3157                }
3158        }
3159
3160        vcpu->arch.cr4 = cr4;
3161        kvm_register_mark_available(vcpu, VCPU_EXREG_CR4);
3162
3163        if (!is_unrestricted_guest(vcpu)) {
3164                if (enable_ept) {
3165                        if (!is_paging(vcpu)) {
3166                                hw_cr4 &= ~X86_CR4_PAE;
3167                                hw_cr4 |= X86_CR4_PSE;
3168                        } else if (!(cr4 & X86_CR4_PAE)) {
3169                                hw_cr4 &= ~X86_CR4_PAE;
3170                        }
3171                }
3172
3173                /*
3174                 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
3175                 * hardware.  To emulate this behavior, SMEP/SMAP/PKU needs
3176                 * to be manually disabled when guest switches to non-paging
3177                 * mode.
3178                 *
3179                 * If !enable_unrestricted_guest, the CPU is always running
3180                 * with CR0.PG=1 and CR4 needs to be modified.
3181                 * If enable_unrestricted_guest, the CPU automatically
3182                 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
3183                 */
3184                if (!is_paging(vcpu))
3185                        hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
3186        }
3187
3188        vmcs_writel(CR4_READ_SHADOW, cr4);
3189        vmcs_writel(GUEST_CR4, hw_cr4);
3190
3191        if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
3192                kvm_update_cpuid_runtime(vcpu);
3193}
3194
3195void vmx_get_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3196{
3197        struct vcpu_vmx *vmx = to_vmx(vcpu);
3198        u32 ar;
3199
3200        if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3201                *var = vmx->rmode.segs[seg];
3202                if (seg == VCPU_SREG_TR
3203                    || var->selector == vmx_read_guest_seg_selector(vmx, seg))
3204                        return;
3205                var->base = vmx_read_guest_seg_base(vmx, seg);
3206                var->selector = vmx_read_guest_seg_selector(vmx, seg);
3207                return;
3208        }
3209        var->base = vmx_read_guest_seg_base(vmx, seg);
3210        var->limit = vmx_read_guest_seg_limit(vmx, seg);
3211        var->selector = vmx_read_guest_seg_selector(vmx, seg);
3212        ar = vmx_read_guest_seg_ar(vmx, seg);
3213        var->unusable = (ar >> 16) & 1;
3214        var->type = ar & 15;
3215        var->s = (ar >> 4) & 1;
3216        var->dpl = (ar >> 5) & 3;
3217        /*
3218         * Some userspaces do not preserve unusable property. Since usable
3219         * segment has to be present according to VMX spec we can use present
3220         * property to amend userspace bug by making unusable segment always
3221         * nonpresent. vmx_segment_access_rights() already marks nonpresent
3222         * segment as unusable.
3223         */
3224        var->present = !var->unusable;
3225        var->avl = (ar >> 12) & 1;
3226        var->l = (ar >> 13) & 1;
3227        var->db = (ar >> 14) & 1;
3228        var->g = (ar >> 15) & 1;
3229}
3230
3231static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
3232{
3233        struct kvm_segment s;
3234
3235        if (to_vmx(vcpu)->rmode.vm86_active) {
3236                vmx_get_segment(vcpu, &s, seg);
3237                return s.base;
3238        }
3239        return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
3240}
3241
3242int vmx_get_cpl(struct kvm_vcpu *vcpu)
3243{
3244        struct vcpu_vmx *vmx = to_vmx(vcpu);
3245
3246        if (unlikely(vmx->rmode.vm86_active))
3247                return 0;
3248        else {
3249                int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
3250                return VMX_AR_DPL(ar);
3251        }
3252}
3253
3254static u32 vmx_segment_access_rights(struct kvm_segment *var)
3255{
3256        u32 ar;
3257
3258        if (var->unusable || !var->present)
3259                ar = 1 << 16;
3260        else {
3261                ar = var->type & 15;
3262                ar |= (var->s & 1) << 4;
3263                ar |= (var->dpl & 3) << 5;
3264                ar |= (var->present & 1) << 7;
3265                ar |= (var->avl & 1) << 12;
3266                ar |= (var->l & 1) << 13;
3267                ar |= (var->db & 1) << 14;
3268                ar |= (var->g & 1) << 15;
3269        }
3270
3271        return ar;
3272}
3273
3274void vmx_set_segment(struct kvm_vcpu *vcpu, struct kvm_segment *var, int seg)
3275{
3276        struct vcpu_vmx *vmx = to_vmx(vcpu);
3277        const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3278
3279        vmx_segment_cache_clear(vmx);
3280
3281        if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
3282                vmx->rmode.segs[seg] = *var;
3283                if (seg == VCPU_SREG_TR)
3284                        vmcs_write16(sf->selector, var->selector);
3285                else if (var->s)
3286                        fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
3287                goto out;
3288        }
3289
3290        vmcs_writel(sf->base, var->base);
3291        vmcs_write32(sf->limit, var->limit);
3292        vmcs_write16(sf->selector, var->selector);
3293
3294        /*
3295         *   Fix the "Accessed" bit in AR field of segment registers for older
3296         * qemu binaries.
3297         *   IA32 arch specifies that at the time of processor reset the
3298         * "Accessed" bit in the AR field of segment registers is 1. And qemu
3299         * is setting it to 0 in the userland code. This causes invalid guest
3300         * state vmexit when "unrestricted guest" mode is turned on.
3301         *    Fix for this setup issue in cpu_reset is being pushed in the qemu
3302         * tree. Newer qemu binaries with that qemu fix would not need this
3303         * kvm hack.
3304         */
3305        if (is_unrestricted_guest(vcpu) && (seg != VCPU_SREG_LDTR))
3306                var->type |= 0x1; /* Accessed */
3307
3308        vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
3309
3310out:
3311        vmx->emulation_required = emulation_required(vcpu);
3312}
3313
3314static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
3315{
3316        u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
3317
3318        *db = (ar >> 14) & 1;
3319        *l = (ar >> 13) & 1;
3320}
3321
3322static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3323{
3324        dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
3325        dt->address = vmcs_readl(GUEST_IDTR_BASE);
3326}
3327
3328static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3329{
3330        vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
3331        vmcs_writel(GUEST_IDTR_BASE, dt->address);
3332}
3333
3334static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3335{
3336        dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
3337        dt->address = vmcs_readl(GUEST_GDTR_BASE);
3338}
3339
3340static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
3341{
3342        vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
3343        vmcs_writel(GUEST_GDTR_BASE, dt->address);
3344}
3345
3346static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
3347{
3348        struct kvm_segment var;
3349        u32 ar;
3350
3351        vmx_get_segment(vcpu, &var, seg);
3352        var.dpl = 0x3;
3353        if (seg == VCPU_SREG_CS)
3354                var.type = 0x3;
3355        ar = vmx_segment_access_rights(&var);
3356
3357        if (var.base != (var.selector << 4))
3358                return false;
3359        if (var.limit != 0xffff)
3360                return false;
3361        if (ar != 0xf3)
3362                return false;
3363
3364        return true;
3365}
3366
3367static bool code_segment_valid(struct kvm_vcpu *vcpu)
3368{
3369        struct kvm_segment cs;
3370        unsigned int cs_rpl;
3371
3372        vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3373        cs_rpl = cs.selector & SEGMENT_RPL_MASK;
3374
3375        if (cs.unusable)
3376                return false;
3377        if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
3378                return false;
3379        if (!cs.s)
3380                return false;
3381        if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
3382                if (cs.dpl > cs_rpl)
3383                        return false;
3384        } else {
3385                if (cs.dpl != cs_rpl)
3386                        return false;
3387        }
3388        if (!cs.present)
3389                return false;
3390
3391        /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
3392        return true;
3393}
3394
3395static bool stack_segment_valid(struct kvm_vcpu *vcpu)
3396{
3397        struct kvm_segment ss;
3398        unsigned int ss_rpl;
3399
3400        vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3401        ss_rpl = ss.selector & SEGMENT_RPL_MASK;
3402
3403        if (ss.unusable)
3404                return true;
3405        if (ss.type != 3 && ss.type != 7)
3406                return false;
3407        if (!ss.s)
3408                return false;
3409        if (ss.dpl != ss_rpl) /* DPL != RPL */
3410                return false;
3411        if (!ss.present)
3412                return false;
3413
3414        return true;
3415}
3416
3417static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
3418{
3419        struct kvm_segment var;
3420        unsigned int rpl;
3421
3422        vmx_get_segment(vcpu, &var, seg);
3423        rpl = var.selector & SEGMENT_RPL_MASK;
3424
3425        if (var.unusable)
3426                return true;
3427        if (!var.s)
3428                return false;
3429        if (!var.present)
3430                return false;
3431        if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
3432                if (var.dpl < rpl) /* DPL < RPL */
3433                        return false;
3434        }
3435
3436        /* TODO: Add other members to kvm_segment_field to allow checking for other access
3437         * rights flags
3438         */
3439        return true;
3440}
3441
3442static bool tr_valid(struct kvm_vcpu *vcpu)
3443{
3444        struct kvm_segment tr;
3445
3446        vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
3447
3448        if (tr.unusable)
3449                return false;
3450        if (tr.selector & SEGMENT_TI_MASK)      /* TI = 1 */
3451                return false;
3452        if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
3453                return false;
3454        if (!tr.present)
3455                return false;
3456
3457        return true;
3458}
3459
3460static bool ldtr_valid(struct kvm_vcpu *vcpu)
3461{
3462        struct kvm_segment ldtr;
3463
3464        vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
3465
3466        if (ldtr.unusable)
3467                return true;
3468        if (ldtr.selector & SEGMENT_TI_MASK)    /* TI = 1 */
3469                return false;
3470        if (ldtr.type != 2)
3471                return false;
3472        if (!ldtr.present)
3473                return false;
3474
3475        return true;
3476}
3477
3478static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
3479{
3480        struct kvm_segment cs, ss;
3481
3482        vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
3483        vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
3484
3485        return ((cs.selector & SEGMENT_RPL_MASK) ==
3486                 (ss.selector & SEGMENT_RPL_MASK));
3487}
3488
3489/*
3490 * Check if guest state is valid. Returns true if valid, false if
3491 * not.
3492 * We assume that registers are always usable
3493 */
3494bool __vmx_guest_state_valid(struct kvm_vcpu *vcpu)
3495{
3496        /* real mode guest state checks */
3497        if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
3498                if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
3499                        return false;
3500                if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
3501                        return false;
3502                if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
3503                        return false;
3504                if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
3505                        return false;
3506                if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
3507                        return false;
3508                if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
3509                        return false;
3510        } else {
3511        /* protected mode guest state checks */
3512                if (!cs_ss_rpl_check(vcpu))
3513                        return false;
3514                if (!code_segment_valid(vcpu))
3515                        return false;
3516                if (!stack_segment_valid(vcpu))
3517                        return false;
3518                if (!data_segment_valid(vcpu, VCPU_SREG_DS))
3519                        return false;
3520                if (!data_segment_valid(vcpu, VCPU_SREG_ES))
3521                        return false;
3522                if (!data_segment_valid(vcpu, VCPU_SREG_FS))
3523                        return false;
3524                if (!data_segment_valid(vcpu, VCPU_SREG_GS))
3525                        return false;
3526                if (!tr_valid(vcpu))
3527                        return false;
3528                if (!ldtr_valid(vcpu))
3529                        return false;
3530        }
3531        /* TODO:
3532         * - Add checks on RIP
3533         * - Add checks on RFLAGS
3534         */
3535
3536        return true;
3537}
3538
3539static int init_rmode_tss(struct kvm *kvm, void __user *ua)
3540{
3541        const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
3542        u16 data;
3543        int i;
3544
3545        for (i = 0; i < 3; i++) {
3546                if (__copy_to_user(ua + PAGE_SIZE * i, zero_page, PAGE_SIZE))
3547                        return -EFAULT;
3548        }
3549
3550        data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
3551        if (__copy_to_user(ua + TSS_IOPB_BASE_OFFSET, &data, sizeof(u16)))
3552                return -EFAULT;
3553
3554        data = ~0;
3555        if (__copy_to_user(ua + RMODE_TSS_SIZE - 1, &data, sizeof(u8)))
3556                return -EFAULT;
3557
3558        return 0;
3559}
3560
3561static int init_rmode_identity_map(struct kvm *kvm)
3562{
3563        struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
3564        int i, r = 0;
3565        void __user *uaddr;
3566        u32 tmp;
3567
3568        /* Protect kvm_vmx->ept_identity_pagetable_done. */
3569        mutex_lock(&kvm->slots_lock);
3570
3571        if (likely(kvm_vmx->ept_identity_pagetable_done))
3572                goto out;
3573
3574        if (!kvm_vmx->ept_identity_map_addr)
3575                kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
3576
3577        uaddr = __x86_set_memory_region(kvm,
3578                                        IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
3579                                        kvm_vmx->ept_identity_map_addr,
3580                                        PAGE_SIZE);
3581        if (IS_ERR(uaddr)) {
3582                r = PTR_ERR(uaddr);
3583                goto out;
3584        }
3585
3586        /* Set up identity-mapping pagetable for EPT in real mode */
3587        for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
3588                tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
3589                        _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
3590                if (__copy_to_user(uaddr + i * sizeof(tmp), &tmp, sizeof(tmp))) {
3591                        r = -EFAULT;
3592                        goto out;
3593                }
3594        }
3595        kvm_vmx->ept_identity_pagetable_done = true;
3596
3597out:
3598        mutex_unlock(&kvm->slots_lock);
3599        return r;
3600}
3601
3602static void seg_setup(int seg)
3603{
3604        const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3605        unsigned int ar;
3606
3607        vmcs_write16(sf->selector, 0);
3608        vmcs_writel(sf->base, 0);
3609        vmcs_write32(sf->limit, 0xffff);
3610        ar = 0x93;
3611        if (seg == VCPU_SREG_CS)
3612                ar |= 0x08; /* code segment */
3613
3614        vmcs_write32(sf->ar_bytes, ar);
3615}
3616
3617static int alloc_apic_access_page(struct kvm *kvm)
3618{
3619        struct page *page;
3620        void __user *hva;
3621        int ret = 0;
3622
3623        mutex_lock(&kvm->slots_lock);
3624        if (kvm->arch.apic_access_memslot_enabled)
3625                goto out;
3626        hva = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
3627                                      APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
3628        if (IS_ERR(hva)) {
3629                ret = PTR_ERR(hva);
3630                goto out;
3631        }
3632
3633        page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
3634        if (is_error_page(page)) {
3635                ret = -EFAULT;
3636                goto out;
3637        }
3638
3639        /*
3640         * Do not pin the page in memory, so that memory hot-unplug
3641         * is able to migrate it.
3642         */
3643        put_page(page);
3644        kvm->arch.apic_access_memslot_enabled = true;
3645out:
3646        mutex_unlock(&kvm->slots_lock);
3647        return ret;
3648}
3649
3650int allocate_vpid(void)
3651{
3652        int vpid;
3653
3654        if (!enable_vpid)
3655                return 0;
3656        spin_lock(&vmx_vpid_lock);
3657        vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
3658        if (vpid < VMX_NR_VPIDS)
3659                __set_bit(vpid, vmx_vpid_bitmap);
3660        else
3661                vpid = 0;
3662        spin_unlock(&vmx_vpid_lock);
3663        return vpid;
3664}
3665
3666void free_vpid(int vpid)
3667{
3668        if (!enable_vpid || vpid == 0)
3669                return;
3670        spin_lock(&vmx_vpid_lock);
3671        __clear_bit(vpid, vmx_vpid_bitmap);
3672        spin_unlock(&vmx_vpid_lock);
3673}
3674
3675static void vmx_clear_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
3676{
3677        int f = sizeof(unsigned long);
3678
3679        if (msr <= 0x1fff)
3680                __clear_bit(msr, msr_bitmap + 0x000 / f);
3681        else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3682                __clear_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3683}
3684
3685static void vmx_clear_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3686{
3687        int f = sizeof(unsigned long);
3688
3689        if (msr <= 0x1fff)
3690                __clear_bit(msr, msr_bitmap + 0x800 / f);
3691        else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3692                __clear_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3693}
3694
3695static void vmx_set_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
3696{
3697        int f = sizeof(unsigned long);
3698
3699        if (msr <= 0x1fff)
3700                __set_bit(msr, msr_bitmap + 0x000 / f);
3701        else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3702                __set_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
3703}
3704
3705static void vmx_set_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
3706{
3707        int f = sizeof(unsigned long);
3708
3709        if (msr <= 0x1fff)
3710                __set_bit(msr, msr_bitmap + 0x800 / f);
3711        else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
3712                __set_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
3713}
3714
3715void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3716{
3717        struct vcpu_vmx *vmx = to_vmx(vcpu);
3718        unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3719
3720        if (!cpu_has_vmx_msr_bitmap())
3721                return;
3722
3723        if (static_branch_unlikely(&enable_evmcs))
3724                evmcs_touch_msr_bitmap();
3725
3726        /*
3727         * Mark the desired intercept state in shadow bitmap, this is needed
3728         * for resync when the MSR filters change.
3729        */
3730        if (is_valid_passthrough_msr(msr)) {
3731                int idx = possible_passthrough_msr_slot(msr);
3732
3733                if (idx != -ENOENT) {
3734                        if (type & MSR_TYPE_R)
3735                                clear_bit(idx, vmx->shadow_msr_intercept.read);
3736                        if (type & MSR_TYPE_W)
3737                                clear_bit(idx, vmx->shadow_msr_intercept.write);
3738                }
3739        }
3740
3741        if ((type & MSR_TYPE_R) &&
3742            !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
3743                vmx_set_msr_bitmap_read(msr_bitmap, msr);
3744                type &= ~MSR_TYPE_R;
3745        }
3746
3747        if ((type & MSR_TYPE_W) &&
3748            !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
3749                vmx_set_msr_bitmap_write(msr_bitmap, msr);
3750                type &= ~MSR_TYPE_W;
3751        }
3752
3753        if (type & MSR_TYPE_R)
3754                vmx_clear_msr_bitmap_read(msr_bitmap, msr);
3755
3756        if (type & MSR_TYPE_W)
3757                vmx_clear_msr_bitmap_write(msr_bitmap, msr);
3758}
3759
3760void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu, u32 msr, int type)
3761{
3762        struct vcpu_vmx *vmx = to_vmx(vcpu);
3763        unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
3764
3765        if (!cpu_has_vmx_msr_bitmap())
3766                return;
3767
3768        if (static_branch_unlikely(&enable_evmcs))
3769                evmcs_touch_msr_bitmap();
3770
3771        /*
3772         * Mark the desired intercept state in shadow bitmap, this is needed
3773         * for resync when the MSR filter changes.
3774        */
3775        if (is_valid_passthrough_msr(msr)) {
3776                int idx = possible_passthrough_msr_slot(msr);
3777
3778                if (idx != -ENOENT) {
3779                        if (type & MSR_TYPE_R)
3780                                set_bit(idx, vmx->shadow_msr_intercept.read);
3781                        if (type & MSR_TYPE_W)
3782                                set_bit(idx, vmx->shadow_msr_intercept.write);
3783                }
3784        }
3785
3786        if (type & MSR_TYPE_R)
3787                vmx_set_msr_bitmap_read(msr_bitmap, msr);
3788
3789        if (type & MSR_TYPE_W)
3790                vmx_set_msr_bitmap_write(msr_bitmap, msr);
3791}
3792
3793static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
3794{
3795        u8 mode = 0;
3796
3797        if (cpu_has_secondary_exec_ctrls() &&
3798            (secondary_exec_controls_get(to_vmx(vcpu)) &
3799             SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
3800                mode |= MSR_BITMAP_MODE_X2APIC;
3801                if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
3802                        mode |= MSR_BITMAP_MODE_X2APIC_APICV;
3803        }
3804
3805        return mode;
3806}
3807
3808static void vmx_reset_x2apic_msrs(struct kvm_vcpu *vcpu, u8 mode)
3809{
3810        unsigned long *msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
3811        unsigned long read_intercept;
3812        int msr;
3813
3814        read_intercept = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
3815
3816        for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
3817                unsigned int read_idx = msr / BITS_PER_LONG;
3818                unsigned int write_idx = read_idx + (0x800 / sizeof(long));
3819
3820                msr_bitmap[read_idx] = read_intercept;
3821                msr_bitmap[write_idx] = ~0ul;
3822        }
3823}
3824
3825static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu, u8 mode)
3826{
3827        if (!cpu_has_vmx_msr_bitmap())
3828                return;
3829
3830        vmx_reset_x2apic_msrs(vcpu, mode);
3831
3832        /*
3833         * TPR reads and writes can be virtualized even if virtual interrupt
3834         * delivery is not in use.
3835         */
3836        vmx_set_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW,
3837                                  !(mode & MSR_BITMAP_MODE_X2APIC));
3838
3839        if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
3840                vmx_enable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_RW);
3841                vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
3842                vmx_disable_intercept_for_msr(vcpu, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
3843        }
3844}
3845
3846void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
3847{
3848        struct vcpu_vmx *vmx = to_vmx(vcpu);
3849        u8 mode = vmx_msr_bitmap_mode(vcpu);
3850        u8 changed = mode ^ vmx->msr_bitmap_mode;
3851
3852        if (!changed)
3853                return;
3854
3855        if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
3856                vmx_update_msr_bitmap_x2apic(vcpu, mode);
3857
3858        vmx->msr_bitmap_mode = mode;
3859}
3860
3861void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu)
3862{
3863        struct vcpu_vmx *vmx = to_vmx(vcpu);
3864        bool flag = !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
3865        u32 i;
3866
3867        vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_STATUS, MSR_TYPE_RW, flag);
3868        vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_BASE, MSR_TYPE_RW, flag);
3869        vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_OUTPUT_MASK, MSR_TYPE_RW, flag);
3870        vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_CR3_MATCH, MSR_TYPE_RW, flag);
3871        for (i = 0; i < vmx->pt_desc.addr_range; i++) {
3872                vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_A + i * 2, MSR_TYPE_RW, flag);
3873                vmx_set_intercept_for_msr(vcpu, MSR_IA32_RTIT_ADDR0_B + i * 2, MSR_TYPE_RW, flag);
3874        }
3875}
3876
3877static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
3878{
3879        struct vcpu_vmx *vmx = to_vmx(vcpu);
3880        void *vapic_page;
3881        u32 vppr;
3882        int rvi;
3883
3884        if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
3885                !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
3886                WARN_ON_ONCE(!vmx->nested.virtual_apic_map.gfn))
3887                return false;
3888
3889        rvi = vmx_get_rvi();
3890
3891        vapic_page = vmx->nested.virtual_apic_map.hva;
3892        vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
3893
3894        return ((rvi & 0xf0) > (vppr & 0xf0));
3895}
3896
3897static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
3898{
3899        struct vcpu_vmx *vmx = to_vmx(vcpu);
3900        u32 i;
3901
3902        /*
3903         * Set intercept permissions for all potentially passed through MSRs
3904         * again. They will automatically get filtered through the MSR filter,
3905         * so we are back in sync after this.
3906         */
3907        for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
3908                u32 msr = vmx_possible_passthrough_msrs[i];
3909                bool read = test_bit(i, vmx->shadow_msr_intercept.read);
3910                bool write = test_bit(i, vmx->shadow_msr_intercept.write);
3911
3912                vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_R, read);
3913                vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_W, write);
3914        }
3915
3916        pt_update_intercept_for_msr(vcpu);
3917        vmx_update_msr_bitmap_x2apic(vcpu, vmx_msr_bitmap_mode(vcpu));
3918}
3919
3920static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
3921                                                     bool nested)
3922{
3923#ifdef CONFIG_SMP
3924        int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
3925
3926        if (vcpu->mode == IN_GUEST_MODE) {
3927                /*
3928                 * The vector of interrupt to be delivered to vcpu had
3929                 * been set in PIR before this function.
3930                 *
3931                 * Following cases will be reached in this block, and
3932                 * we always send a notification event in all cases as
3933                 * explained below.
3934                 *
3935                 * Case 1: vcpu keeps in non-root mode. Sending a
3936                 * notification event posts the interrupt to vcpu.
3937                 *
3938                 * Case 2: vcpu exits to root mode and is still
3939                 * runnable. PIR will be synced to vIRR before the
3940                 * next vcpu entry. Sending a notification event in
3941                 * this case has no effect, as vcpu is not in root
3942                 * mode.
3943                 *
3944                 * Case 3: vcpu exits to root mode and is blocked.
3945                 * vcpu_block() has already synced PIR to vIRR and
3946                 * never blocks vcpu if vIRR is not cleared. Therefore,
3947                 * a blocked vcpu here does not wait for any requested
3948                 * interrupts in PIR, and sending a notification event
3949                 * which has no effect is safe here.
3950                 */
3951
3952                apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
3953                return true;
3954        }
3955#endif
3956        return false;
3957}
3958
3959static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
3960                                                int vector)
3961{
3962        struct vcpu_vmx *vmx = to_vmx(vcpu);
3963
3964        if (is_guest_mode(vcpu) &&
3965            vector == vmx->nested.posted_intr_nv) {
3966                /*
3967                 * If a posted intr is not recognized by hardware,
3968                 * we will accomplish it in the next vmentry.
3969                 */
3970                vmx->nested.pi_pending = true;
3971                kvm_make_request(KVM_REQ_EVENT, vcpu);
3972                /* the PIR and ON have been set by L1. */
3973                if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
3974                        kvm_vcpu_kick(vcpu);
3975                return 0;
3976        }
3977        return -1;
3978}
3979/*
3980 * Send interrupt to vcpu via posted interrupt way.
3981 * 1. If target vcpu is running(non-root mode), send posted interrupt
3982 * notification to vcpu and hardware will sync PIR to vIRR atomically.
3983 * 2. If target vcpu isn't running(root mode), kick it to pick up the
3984 * interrupt from PIR in next vmentry.
3985 */
3986static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
3987{
3988        struct vcpu_vmx *vmx = to_vmx(vcpu);
3989        int r;
3990
3991        r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
3992        if (!r)
3993                return 0;
3994
3995        if (!vcpu->arch.apicv_active)
3996                return -1;
3997
3998        if (pi_test_and_set_pir(vector, &vmx->pi_desc))
3999                return 0;
4000
4001        /* If a previous notification has sent the IPI, nothing to do.  */
4002        if (pi_test_and_set_on(&vmx->pi_desc))
4003                return 0;
4004
4005        if (vcpu != kvm_get_running_vcpu() &&
4006            !kvm_vcpu_trigger_posted_interrupt(vcpu, false))
4007                kvm_vcpu_kick(vcpu);
4008
4009        return 0;
4010}
4011
4012/*
4013 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
4014 * will not change in the lifetime of the guest.
4015 * Note that host-state that does change is set elsewhere. E.g., host-state
4016 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
4017 */
4018void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
4019{
4020        u32 low32, high32;
4021        unsigned long tmpl;
4022        unsigned long cr0, cr3, cr4;
4023
4024        cr0 = read_cr0();
4025        WARN_ON(cr0 & X86_CR0_TS);
4026        vmcs_writel(HOST_CR0, cr0);  /* 22.2.3 */
4027
4028        /*
4029         * Save the most likely value for this task's CR3 in the VMCS.
4030         * We can't use __get_current_cr3_fast() because we're not atomic.
4031         */
4032        cr3 = __read_cr3();
4033        vmcs_writel(HOST_CR3, cr3);             /* 22.2.3  FIXME: shadow tables */
4034        vmx->loaded_vmcs->host_state.cr3 = cr3;
4035
4036        /* Save the most likely value for this task's CR4 in the VMCS. */
4037        cr4 = cr4_read_shadow();
4038        vmcs_writel(HOST_CR4, cr4);                     /* 22.2.3, 22.2.5 */
4039        vmx->loaded_vmcs->host_state.cr4 = cr4;
4040
4041        vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS);  /* 22.2.4 */
4042#ifdef CONFIG_X86_64
4043        /*
4044         * Load null selectors, so we can avoid reloading them in
4045         * vmx_prepare_switch_to_host(), in case userspace uses
4046         * the null selectors too (the expected case).
4047         */
4048        vmcs_write16(HOST_DS_SELECTOR, 0);
4049        vmcs_write16(HOST_ES_SELECTOR, 0);
4050#else
4051        vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4052        vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4053#endif
4054        vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS);  /* 22.2.4 */
4055        vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8);  /* 22.2.4 */
4056
4057        vmcs_writel(HOST_IDTR_BASE, host_idt_base);   /* 22.2.4 */
4058
4059        vmcs_writel(HOST_RIP, (unsigned long)vmx_vmexit); /* 22.2.5 */
4060
4061        rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
4062        vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
4063        rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
4064        vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl);   /* 22.2.3 */
4065
4066        if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
4067                rdmsr(MSR_IA32_CR_PAT, low32, high32);
4068                vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
4069        }
4070
4071        if (cpu_has_load_ia32_efer())
4072                vmcs_write64(HOST_IA32_EFER, host_efer);
4073}
4074
4075void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
4076{
4077        struct kvm_vcpu *vcpu = &vmx->vcpu;
4078
4079        vcpu->arch.cr4_guest_owned_bits = KVM_POSSIBLE_CR4_GUEST_BITS &
4080                                          ~vcpu->arch.cr4_guest_rsvd_bits;
4081        if (!enable_ept)
4082                vcpu->arch.cr4_guest_owned_bits &= ~X86_CR4_PGE;
4083        if (is_guest_mode(&vmx->vcpu))
4084                vcpu->arch.cr4_guest_owned_bits &=
4085                        ~get_vmcs12(vcpu)->cr4_guest_host_mask;
4086        vmcs_writel(CR4_GUEST_HOST_MASK, ~vcpu->arch.cr4_guest_owned_bits);
4087}
4088
4089u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
4090{
4091        u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
4092
4093        if (!kvm_vcpu_apicv_active(&vmx->vcpu))
4094                pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
4095
4096        if (!enable_vnmi)
4097                pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
4098
4099        if (!enable_preemption_timer)
4100                pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4101
4102        return pin_based_exec_ctrl;
4103}
4104
4105static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4106{
4107        struct vcpu_vmx *vmx = to_vmx(vcpu);
4108
4109        pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4110        if (cpu_has_secondary_exec_ctrls()) {
4111                if (kvm_vcpu_apicv_active(vcpu))
4112                        secondary_exec_controls_setbit(vmx,
4113                                      SECONDARY_EXEC_APIC_REGISTER_VIRT |
4114                                      SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4115                else
4116                        secondary_exec_controls_clearbit(vmx,
4117                                        SECONDARY_EXEC_APIC_REGISTER_VIRT |
4118                                        SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4119        }
4120
4121        if (cpu_has_vmx_msr_bitmap())
4122                vmx_update_msr_bitmap(vcpu);
4123}
4124
4125u32 vmx_exec_control(struct vcpu_vmx *vmx)
4126{
4127        u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
4128
4129        if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
4130                exec_control &= ~CPU_BASED_MOV_DR_EXITING;
4131
4132        if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
4133                exec_control &= ~CPU_BASED_TPR_SHADOW;
4134#ifdef CONFIG_X86_64
4135                exec_control |= CPU_BASED_CR8_STORE_EXITING |
4136                                CPU_BASED_CR8_LOAD_EXITING;
4137#endif
4138        }
4139        if (!enable_ept)
4140                exec_control |= CPU_BASED_CR3_STORE_EXITING |
4141                                CPU_BASED_CR3_LOAD_EXITING  |
4142                                CPU_BASED_INVLPG_EXITING;
4143        if (kvm_mwait_in_guest(vmx->vcpu.kvm))
4144                exec_control &= ~(CPU_BASED_MWAIT_EXITING |
4145                                CPU_BASED_MONITOR_EXITING);
4146        if (kvm_hlt_in_guest(vmx->vcpu.kvm))
4147                exec_control &= ~CPU_BASED_HLT_EXITING;
4148        return exec_control;
4149}
4150
4151/*
4152 * Adjust a single secondary execution control bit to intercept/allow an
4153 * instruction in the guest.  This is usually done based on whether or not a
4154 * feature has been exposed to the guest in order to correctly emulate faults.
4155 */
4156static inline void
4157vmx_adjust_secondary_exec_control(struct vcpu_vmx *vmx, u32 *exec_control,
4158                                  u32 control, bool enabled, bool exiting)
4159{
4160        /*
4161         * If the control is for an opt-in feature, clear the control if the
4162         * feature is not exposed to the guest, i.e. not enabled.  If the
4163         * control is opt-out, i.e. an exiting control, clear the control if
4164         * the feature _is_ exposed to the guest, i.e. exiting/interception is
4165         * disabled for the associated instruction.  Note, the caller is
4166         * responsible presetting exec_control to set all supported bits.
4167         */
4168        if (enabled == exiting)
4169                *exec_control &= ~control;
4170
4171        /*
4172         * Update the nested MSR settings so that a nested VMM can/can't set
4173         * controls for features that are/aren't exposed to the guest.
4174         */
4175        if (nested) {
4176                if (enabled)
4177                        vmx->nested.msrs.secondary_ctls_high |= control;
4178                else
4179                        vmx->nested.msrs.secondary_ctls_high &= ~control;
4180        }
4181}
4182
4183/*
4184 * Wrapper macro for the common case of adjusting a secondary execution control
4185 * based on a single guest CPUID bit, with a dedicated feature bit.  This also
4186 * verifies that the control is actually supported by KVM and hardware.
4187 */
4188#define vmx_adjust_sec_exec_control(vmx, exec_control, name, feat_name, ctrl_name, exiting) \
4189({                                                                       \
4190        bool __enabled;                                                  \
4191                                                                         \
4192        if (cpu_has_vmx_##name()) {                                      \
4193                __enabled = guest_cpuid_has(&(vmx)->vcpu,                \
4194                                            X86_FEATURE_##feat_name);    \
4195                vmx_adjust_secondary_exec_control(vmx, exec_control,     \
4196                        SECONDARY_EXEC_##ctrl_name, __enabled, exiting); \
4197        }                                                                \
4198})
4199
4200/* More macro magic for ENABLE_/opt-in versus _EXITING/opt-out controls. */
4201#define vmx_adjust_sec_exec_feature(vmx, exec_control, lname, uname) \
4202        vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, ENABLE_##uname, false)
4203
4204#define vmx_adjust_sec_exec_exiting(vmx, exec_control, lname, uname) \
4205        vmx_adjust_sec_exec_control(vmx, exec_control, lname, uname, uname##_EXITING, true)
4206
4207static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
4208{
4209        struct kvm_vcpu *vcpu = &vmx->vcpu;
4210
4211        u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
4212
4213        if (vmx_pt_mode_is_system())
4214                exec_control &= ~(SECONDARY_EXEC_PT_USE_GPA | SECONDARY_EXEC_PT_CONCEAL_VMX);
4215        if (!cpu_need_virtualize_apic_accesses(vcpu))
4216                exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
4217        if (vmx->vpid == 0)
4218                exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
4219        if (!enable_ept) {
4220                exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
4221                enable_unrestricted_guest = 0;
4222        }
4223        if (!enable_unrestricted_guest)
4224                exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
4225        if (kvm_pause_in_guest(vmx->vcpu.kvm))
4226                exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
4227        if (!kvm_vcpu_apicv_active(vcpu))
4228                exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
4229                                  SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4230        exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
4231
4232        /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
4233         * in vmx_set_cr4.  */
4234        exec_control &= ~SECONDARY_EXEC_DESC;
4235
4236        /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
4237           (handle_vmptrld).
4238           We can NOT enable shadow_vmcs here because we don't have yet
4239           a current VMCS12
4240        */
4241        exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
4242
4243        /*
4244         * PML is enabled/disabled when dirty logging of memsmlots changes, but
4245         * it needs to be set here when dirty logging is already active, e.g.
4246         * if this vCPU was created after dirty logging was enabled.
4247         */
4248        if (!vcpu->kvm->arch.cpu_dirty_logging_count)
4249                exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
4250
4251        if (cpu_has_vmx_xsaves()) {
4252                /* Exposing XSAVES only when XSAVE is exposed */
4253                bool xsaves_enabled =
4254                        boot_cpu_has(X86_FEATURE_XSAVE) &&
4255                        guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4256                        guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
4257
4258                vcpu->arch.xsaves_enabled = xsaves_enabled;
4259
4260                vmx_adjust_secondary_exec_control(vmx, &exec_control,
4261                                                  SECONDARY_EXEC_XSAVES,
4262                                                  xsaves_enabled, false);
4263        }
4264
4265        /*
4266         * RDPID is also gated by ENABLE_RDTSCP, turn on the control if either
4267         * feature is exposed to the guest.  This creates a virtualization hole
4268         * if both are supported in hardware but only one is exposed to the
4269         * guest, but letting the guest execute RDTSCP or RDPID when either one
4270         * is advertised is preferable to emulating the advertised instruction
4271         * in KVM on #UD, and obviously better than incorrectly injecting #UD.
4272         */
4273        if (cpu_has_vmx_rdtscp()) {
4274                bool rdpid_or_rdtscp_enabled =
4275                        guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP) ||
4276                        guest_cpuid_has(vcpu, X86_FEATURE_RDPID);
4277
4278                vmx_adjust_secondary_exec_control(vmx, &exec_control,
4279                                                  SECONDARY_EXEC_ENABLE_RDTSCP,
4280                                                  rdpid_or_rdtscp_enabled, false);
4281        }
4282        vmx_adjust_sec_exec_feature(vmx, &exec_control, invpcid, INVPCID);
4283
4284        vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdrand, RDRAND);
4285        vmx_adjust_sec_exec_exiting(vmx, &exec_control, rdseed, RDSEED);
4286
4287        vmx_adjust_sec_exec_control(vmx, &exec_control, waitpkg, WAITPKG,
4288                                    ENABLE_USR_WAIT_PAUSE, false);
4289
4290        if (!vcpu->kvm->arch.bus_lock_detection_enabled)
4291                exec_control &= ~SECONDARY_EXEC_BUS_LOCK_DETECTION;
4292
4293        vmx->secondary_exec_control = exec_control;
4294}
4295
4296#define VMX_XSS_EXIT_BITMAP 0
4297
4298/*
4299 * Noting that the initialization of Guest-state Area of VMCS is in
4300 * vmx_vcpu_reset().
4301 */
4302static void init_vmcs(struct vcpu_vmx *vmx)
4303{
4304        if (nested)
4305                nested_vmx_set_vmcs_shadowing_bitmap();
4306
4307        if (cpu_has_vmx_msr_bitmap())
4308                vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
4309
4310        vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
4311
4312        /* Control */
4313        pin_controls_set(vmx, vmx_pin_based_exec_ctrl(vmx));
4314
4315        exec_controls_set(vmx, vmx_exec_control(vmx));
4316
4317        if (cpu_has_secondary_exec_ctrls()) {
4318                vmx_compute_secondary_exec_control(vmx);
4319                secondary_exec_controls_set(vmx, vmx->secondary_exec_control);
4320        }
4321
4322        if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
4323                vmcs_write64(EOI_EXIT_BITMAP0, 0);
4324                vmcs_write64(EOI_EXIT_BITMAP1, 0);
4325                vmcs_write64(EOI_EXIT_BITMAP2, 0);
4326                vmcs_write64(EOI_EXIT_BITMAP3, 0);
4327
4328                vmcs_write16(GUEST_INTR_STATUS, 0);
4329
4330                vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
4331                vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
4332        }
4333
4334        if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
4335                vmcs_write32(PLE_GAP, ple_gap);
4336                vmx->ple_window = ple_window;
4337                vmx->ple_window_dirty = true;
4338        }
4339
4340        vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
4341        vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
4342        vmcs_write32(CR3_TARGET_COUNT, 0);           /* 22.2.1 */
4343
4344        vmcs_write16(HOST_FS_SELECTOR, 0);            /* 22.2.4 */
4345        vmcs_write16(HOST_GS_SELECTOR, 0);            /* 22.2.4 */
4346        vmx_set_constant_host_state(vmx);
4347        vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
4348        vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
4349
4350        if (cpu_has_vmx_vmfunc())
4351                vmcs_write64(VM_FUNCTION_CONTROL, 0);
4352
4353        vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
4354        vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
4355        vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
4356        vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
4357        vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
4358
4359        if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
4360                vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
4361
4362        vm_exit_controls_set(vmx, vmx_vmexit_ctrl());
4363
4364        /* 22.2.1, 20.8.1 */
4365        vm_entry_controls_set(vmx, vmx_vmentry_ctrl());
4366
4367        vmx->vcpu.arch.cr0_guest_owned_bits = KVM_POSSIBLE_CR0_GUEST_BITS;
4368        vmcs_writel(CR0_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr0_guest_owned_bits);
4369
4370        set_cr4_guest_host_mask(vmx);
4371
4372        if (vmx->vpid != 0)
4373                vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
4374
4375        if (cpu_has_vmx_xsaves())
4376                vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
4377
4378        if (enable_pml) {
4379                vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
4380                vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
4381        }
4382
4383        vmx_write_encls_bitmap(&vmx->vcpu, NULL);
4384
4385        if (vmx_pt_mode_is_host_guest()) {
4386                memset(&vmx->pt_desc, 0, sizeof(vmx->pt_desc));
4387                /* Bit[6~0] are forced to 1, writes are ignored. */
4388                vmx->pt_desc.guest.output_mask = 0x7F;
4389                vmcs_write64(GUEST_IA32_RTIT_CTL, 0);
4390        }
4391}
4392
4393static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
4394{
4395        struct vcpu_vmx *vmx = to_vmx(vcpu);
4396        struct msr_data apic_base_msr;
4397        u64 cr0;
4398
4399        vmx->rmode.vm86_active = 0;
4400        vmx->spec_ctrl = 0;
4401
4402        vmx->msr_ia32_umwait_control = 0;
4403
4404        vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
4405        vmx->hv_deadline_tsc = -1;
4406        kvm_set_cr8(vcpu, 0);
4407
4408        if (!init_event) {
4409                apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
4410                                     MSR_IA32_APICBASE_ENABLE;
4411                if (kvm_vcpu_is_reset_bsp(vcpu))
4412                        apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
4413                apic_base_msr.host_initiated = true;
4414                kvm_set_apic_base(vcpu, &apic_base_msr);
4415        }
4416
4417        vmx_segment_cache_clear(vmx);
4418
4419        seg_setup(VCPU_SREG_CS);
4420        vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
4421        vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
4422
4423        seg_setup(VCPU_SREG_DS);
4424        seg_setup(VCPU_SREG_ES);
4425        seg_setup(VCPU_SREG_FS);
4426        seg_setup(VCPU_SREG_GS);
4427        seg_setup(VCPU_SREG_SS);
4428
4429        vmcs_write16(GUEST_TR_SELECTOR, 0);
4430        vmcs_writel(GUEST_TR_BASE, 0);
4431        vmcs_write32(GUEST_TR_LIMIT, 0xffff);
4432        vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4433
4434        vmcs_write16(GUEST_LDTR_SELECTOR, 0);
4435        vmcs_writel(GUEST_LDTR_BASE, 0);
4436        vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
4437        vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
4438
4439        if (!init_event) {
4440                vmcs_write32(GUEST_SYSENTER_CS, 0);
4441                vmcs_writel(GUEST_SYSENTER_ESP, 0);
4442                vmcs_writel(GUEST_SYSENTER_EIP, 0);
4443                vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
4444        }
4445
4446        kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
4447        kvm_rip_write(vcpu, 0xfff0);
4448
4449        vmcs_writel(GUEST_GDTR_BASE, 0);
4450        vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
4451
4452        vmcs_writel(GUEST_IDTR_BASE, 0);
4453        vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
4454
4455        vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
4456        vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
4457        vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
4458        if (kvm_mpx_supported())
4459                vmcs_write64(GUEST_BNDCFGS, 0);
4460
4461        setup_msrs(vmx);
4462
4463        vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);  /* 22.2.1 */
4464
4465        if (cpu_has_vmx_tpr_shadow() && !init_event) {
4466                vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
4467                if (cpu_need_tpr_shadow(vcpu))
4468                        vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
4469                                     __pa(vcpu->arch.apic->regs));
4470                vmcs_write32(TPR_THRESHOLD, 0);
4471        }
4472
4473        kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
4474
4475        cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
4476        vmx->vcpu.arch.cr0 = cr0;
4477        vmx_set_cr0(vcpu, cr0); /* enter rmode */
4478        vmx_set_cr4(vcpu, 0);
4479        vmx_set_efer(vcpu, 0);
4480
4481        vmx_update_exception_bitmap(vcpu);
4482
4483        vpid_sync_context(vmx->vpid);