Merge tag 'kvm-5.6-1' of git://git.kernel.org/pub/scm/virt/kvm/kvm
authorLinus Torvalds <torvalds@linux-foundation.org>
Fri, 31 Jan 2020 17:30:41 +0000 (09:30 -0800)
committerLinus Torvalds <torvalds@linux-foundation.org>
Fri, 31 Jan 2020 17:30:41 +0000 (09:30 -0800)
Pull KVM updates from Paolo Bonzini:
 "This is the first batch of KVM changes.

  ARM:
   - cleanups and corner case fixes.

  PPC:
   - Bugfixes

  x86:
   - Support for mapping DAX areas with large nested page table entries.

   - Cleanups and bugfixes here too. A particularly important one is a
     fix for FPU load when the thread has TIF_NEED_FPU_LOAD. There is
     also a race condition which could be used in guest userspace to
     exploit the guest kernel, for which the embargo expired today.

   - Fast path for IPI delivery vmexits, shaving about 200 clock cycles
     from IPI latency.

   - Protect against "Spectre-v1/L1TF" (bring data in the cache via
     speculative out of bound accesses, use L1TF on the sibling
     hyperthread to read it), which unfortunately is an even bigger
     whack-a-mole game than SpectreV1.

  Sean continues his mission to rewrite KVM. In addition to a sizable
  number of x86 patches, this time he contributed a pretty large
  refactoring of vCPU creation that affects all architectures but should
  not have any visible effect.

  s390 will come next week together with some more x86 patches"

* tag 'kvm-5.6-1' of git://git.kernel.org/pub/scm/virt/kvm/kvm: (204 commits)
  x86/KVM: Clean up host's steal time structure
  x86/KVM: Make sure KVM_VCPU_FLUSH_TLB flag is not missed
  x86/kvm: Cache gfn to pfn translation
  x86/kvm: Introduce kvm_(un)map_gfn()
  x86/kvm: Be careful not to clear KVM_VCPU_FLUSH_TLB bit
  KVM: PPC: Book3S PR: Fix -Werror=return-type build failure
  KVM: PPC: Book3S HV: Release lock on page-out failure path
  KVM: arm64: Treat emulated TVAL TimerValue as a signed 32-bit integer
  KVM: arm64: pmu: Only handle supported event counters
  KVM: arm64: pmu: Fix chained SW_INCR counters
  KVM: arm64: pmu: Don't mark a counter as chained if the odd one is disabled
  KVM: arm64: pmu: Don't increment SW_INCR if PMCR.E is unset
  KVM: x86: Use a typedef for fastop functions
  KVM: X86: Add 'else' to unify fastop and execute call path
  KVM: x86: inline memslot_valid_for_gpte
  KVM: x86/mmu: Use huge pages for DAX-backed files
  KVM: x86/mmu: Remove lpage_is_disallowed() check from set_spte()
  KVM: x86/mmu: Fold max_mapping_level() into kvm_mmu_hugepage_adjust()
  KVM: x86/mmu: Zap any compound page when collapsing sptes
  KVM: x86/mmu: Remove obsolete gfn restoration in FNAME(fetch)
  ...

1  2 
arch/arm64/include/asm/kvm_host.h
arch/arm64/kvm/hyp/entry.S
arch/x86/include/asm/pgtable_types.h
arch/x86/include/asm/vmx.h
arch/x86/kvm/mmu/mmu.c
arch/x86/kvm/vmx/nested.c
arch/x86/kvm/vmx/vmx.c
arch/x86/kvm/x86.c
arch/x86/mm/pat/set_memory.c
mm/huge_memory.c

@@@ -24,7 -24,6 +24,6 @@@
  #include <asm/fpsimd.h>
  #include <asm/kvm.h>
  #include <asm/kvm_asm.h>
- #include <asm/kvm_mmio.h>
  #include <asm/thread_info.h>
  
  #define __KVM_HAVE_ARCH_INTC_INITIALIZED
@@@ -53,7 -52,7 +52,7 @@@ int kvm_arm_init_sve(void)
  
  int __attribute_const__ kvm_target_cpu(void);
  int kvm_reset_vcpu(struct kvm_vcpu *vcpu);
- void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu);
+ void kvm_arm_vcpu_destroy(struct kvm_vcpu *vcpu);
  int kvm_arch_vm_ioctl_check_extension(struct kvm *kvm, long ext);
  void __extended_idmap_trampoline(phys_addr_t boot_pgd, phys_addr_t idmap_start);
  
@@@ -325,9 -324,6 +324,6 @@@ struct kvm_vcpu_arch 
        /* Don't run the guest (internal implementation need) */
        bool pause;
  
-       /* IO related fields */
-       struct kvm_decode mmio_decode;
        /* Cache some mmu pages needed inside spinlock regions */
        struct kvm_mmu_memory_cache mmu_page_cache;
  
@@@ -446,8 -442,6 +442,6 @@@ int kvm_set_spte_hva(struct kvm *kvm, u
  int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end);
  int kvm_test_age_hva(struct kvm *kvm, unsigned long hva);
  
- struct kvm_vcpu *kvm_arm_get_running_vcpu(void);
- struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void);
  void kvm_arm_halt_guest(struct kvm *kvm);
  void kvm_arm_resume_guest(struct kvm *kvm);
  
@@@ -491,6 -485,14 +485,14 @@@ int handle_exit(struct kvm_vcpu *vcpu, 
  void handle_exit_early(struct kvm_vcpu *vcpu, struct kvm_run *run,
                       int exception_index);
  
+ /* MMIO helpers */
+ void kvm_mmio_write_buf(void *buf, unsigned int len, unsigned long data);
+ unsigned long kvm_mmio_read_buf(const void *buf, unsigned int len);
+ int kvm_handle_mmio_return(struct kvm_vcpu *vcpu, struct kvm_run *run);
+ int io_mem_abort(struct kvm_vcpu *vcpu, struct kvm_run *run,
+                phys_addr_t fault_ipa);
  int kvm_perf_init(void);
  int kvm_perf_teardown(void);
  
@@@ -547,7 -549,7 +549,7 @@@ static inline void __cpu_init_hyp_mode(
         * wrong, and hyp will crash and burn when it uses any
         * cpus_have_const_cap() wrapper.
         */
 -      BUG_ON(!static_branch_likely(&arm64_const_caps_ready));
 +      BUG_ON(!system_capabilities_finalized());
        __kvm_call_hyp((void *)pgd_ptr, hyp_stack_ptr, vector_ptr, tpidr_el2);
  
        /*
@@@ -571,7 -573,7 +573,7 @@@ static inline bool kvm_arch_requires_vh
                return true;
  
        /* Some implementations have defects that confine them to VHE */
 -      if (cpus_have_cap(ARM64_WORKAROUND_1165522))
 +      if (cpus_have_cap(ARM64_WORKAROUND_SPECULATIVE_AT_VHE))
                return true;
  
        return false;
        .text
        .pushsection    .hyp.text, "ax"
  
 +/*
 + * We treat x18 as callee-saved as the host may use it as a platform
 + * register (e.g. for shadow call stack).
 + */
  .macro save_callee_saved_regs ctxt
 +      str     x18,      [\ctxt, #CPU_XREG_OFFSET(18)]
        stp     x19, x20, [\ctxt, #CPU_XREG_OFFSET(19)]
        stp     x21, x22, [\ctxt, #CPU_XREG_OFFSET(21)]
        stp     x23, x24, [\ctxt, #CPU_XREG_OFFSET(23)]
@@@ -37,8 -32,6 +37,8 @@@
  .endm
  
  .macro restore_callee_saved_regs ctxt
 +      // We require \ctxt is not x18-x28
 +      ldr     x18,      [\ctxt, #CPU_XREG_OFFSET(18)]
        ldp     x19, x20, [\ctxt, #CPU_XREG_OFFSET(19)]
        ldp     x21, x22, [\ctxt, #CPU_XREG_OFFSET(21)]
        ldp     x23, x24, [\ctxt, #CPU_XREG_OFFSET(23)]
   * u64 __guest_enter(struct kvm_vcpu *vcpu,
   *                 struct kvm_cpu_context *host_ctxt);
   */
ENTRY(__guest_enter)
SYM_FUNC_START(__guest_enter)
        // x0: vcpu
        // x1: host context
        // x2-x17: clobbered by macros
 -      // x18: guest context
 +      // x29: guest context
  
        // Store the host regs
        save_callee_saved_regs x1
@@@ -74,35 -67,37 +74,34 @@@ alternative_else_nop_endi
        ret
  
  1:
 -      add     x18, x0, #VCPU_CONTEXT
 +      add     x29, x0, #VCPU_CONTEXT
  
        // Macro ptrauth_switch_to_guest format:
        //      ptrauth_switch_to_guest(guest cxt, tmp1, tmp2, tmp3)
        // The below macro to restore guest keys is not implemented in C code
        // as it may cause Pointer Authentication key signing mismatch errors
        // when this feature is enabled for kernel code.
 -      ptrauth_switch_to_guest x18, x0, x1, x2
 +      ptrauth_switch_to_guest x29, x0, x1, x2
  
        // Restore guest regs x0-x17
 -      ldp     x0, x1,   [x18, #CPU_XREG_OFFSET(0)]
 -      ldp     x2, x3,   [x18, #CPU_XREG_OFFSET(2)]
 -      ldp     x4, x5,   [x18, #CPU_XREG_OFFSET(4)]
 -      ldp     x6, x7,   [x18, #CPU_XREG_OFFSET(6)]
 -      ldp     x8, x9,   [x18, #CPU_XREG_OFFSET(8)]
 -      ldp     x10, x11, [x18, #CPU_XREG_OFFSET(10)]
 -      ldp     x12, x13, [x18, #CPU_XREG_OFFSET(12)]
 -      ldp     x14, x15, [x18, #CPU_XREG_OFFSET(14)]
 -      ldp     x16, x17, [x18, #CPU_XREG_OFFSET(16)]
 -
 -      // Restore guest regs x19-x29, lr
 -      restore_callee_saved_regs x18
 -
 -      // Restore guest reg x18
 -      ldr     x18,      [x18, #CPU_XREG_OFFSET(18)]
 +      ldp     x0, x1,   [x29, #CPU_XREG_OFFSET(0)]
 +      ldp     x2, x3,   [x29, #CPU_XREG_OFFSET(2)]
 +      ldp     x4, x5,   [x29, #CPU_XREG_OFFSET(4)]
 +      ldp     x6, x7,   [x29, #CPU_XREG_OFFSET(6)]
 +      ldp     x8, x9,   [x29, #CPU_XREG_OFFSET(8)]
 +      ldp     x10, x11, [x29, #CPU_XREG_OFFSET(10)]
 +      ldp     x12, x13, [x29, #CPU_XREG_OFFSET(12)]
 +      ldp     x14, x15, [x29, #CPU_XREG_OFFSET(14)]
 +      ldp     x16, x17, [x29, #CPU_XREG_OFFSET(16)]
 +
 +      // Restore guest regs x18-x29, lr
 +      restore_callee_saved_regs x29
  
        // Do not touch any register after this!
        eret
        sb
- ENDPROC(__guest_enter)
  
ENTRY(__guest_exit)
SYM_INNER_LABEL(__guest_exit, SYM_L_GLOBAL)
        // x0: return code
        // x1: vcpu
        // x2-x29,lr: vcpu regs
        // Retrieve the guest regs x0-x1 from the stack
        ldp     x2, x3, [sp], #16       // x0, x1
  
 -      // Store the guest regs x0-x1 and x4-x18
 +      // Store the guest regs x0-x1 and x4-x17
        stp     x2, x3,   [x1, #CPU_XREG_OFFSET(0)]
        stp     x4, x5,   [x1, #CPU_XREG_OFFSET(4)]
        stp     x6, x7,   [x1, #CPU_XREG_OFFSET(6)]
        stp     x12, x13, [x1, #CPU_XREG_OFFSET(12)]
        stp     x14, x15, [x1, #CPU_XREG_OFFSET(14)]
        stp     x16, x17, [x1, #CPU_XREG_OFFSET(16)]
 -      str     x18,      [x1, #CPU_XREG_OFFSET(18)]
  
 -      // Store the guest regs x19-x29, lr
 +      // Store the guest regs x18-x29, lr
        save_callee_saved_regs x1
  
        get_host_ctxt   x2, x3
@@@ -195,4 -191,4 +194,4 @@@ abort_guest_exit_end
        msr     spsr_el2, x4
        orr     x0, x0, x5
  1:    ret
ENDPROC(__guest_exit)
SYM_FUNC_END(__guest_enter)
  
  #define _PAGE_PROTNONE        (_AT(pteval_t, 1) << _PAGE_BIT_PROTNONE)
  
 -#define _PAGE_TABLE_NOENC     (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |\
 -                               _PAGE_ACCESSED | _PAGE_DIRTY)
 -#define _KERNPG_TABLE_NOENC   (_PAGE_PRESENT | _PAGE_RW |             \
 -                               _PAGE_ACCESSED | _PAGE_DIRTY)
 -
  /*
   * Set of bits not changed in pte_modify.  The pte's
   * protection key is treated like _PAGE_RW, for
   */
  #ifndef __ASSEMBLY__
  enum page_cache_mode {
 -      _PAGE_CACHE_MODE_WB = 0,
 -      _PAGE_CACHE_MODE_WC = 1,
 +      _PAGE_CACHE_MODE_WB       = 0,
 +      _PAGE_CACHE_MODE_WC       = 1,
        _PAGE_CACHE_MODE_UC_MINUS = 2,
 -      _PAGE_CACHE_MODE_UC = 3,
 -      _PAGE_CACHE_MODE_WT = 4,
 -      _PAGE_CACHE_MODE_WP = 5,
 -      _PAGE_CACHE_MODE_NUM = 8
 +      _PAGE_CACHE_MODE_UC       = 3,
 +      _PAGE_CACHE_MODE_WT       = 4,
 +      _PAGE_CACHE_MODE_WP       = 5,
 +
 +      _PAGE_CACHE_MODE_NUM      = 8
  };
  #endif
  
 -#define _PAGE_CACHE_MASK      (_PAGE_PAT | _PAGE_PCD | _PAGE_PWT)
 -#define _PAGE_NOCACHE         (cachemode2protval(_PAGE_CACHE_MODE_UC))
 -#define _PAGE_CACHE_WP                (cachemode2protval(_PAGE_CACHE_MODE_WP))
 +#define _PAGE_ENC             (_AT(pteval_t, sme_me_mask))
  
 -#define PAGE_NONE     __pgprot(_PAGE_PROTNONE | _PAGE_ACCESSED)
 -#define PAGE_SHARED   __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_USER | \
 -                               _PAGE_ACCESSED | _PAGE_NX)
 -
 -#define PAGE_SHARED_EXEC      __pgprot(_PAGE_PRESENT | _PAGE_RW |     \
 -                                       _PAGE_USER | _PAGE_ACCESSED)
 -#define PAGE_COPY_NOEXEC      __pgprot(_PAGE_PRESENT | _PAGE_USER |   \
 -                                       _PAGE_ACCESSED | _PAGE_NX)
 -#define PAGE_COPY_EXEC                __pgprot(_PAGE_PRESENT | _PAGE_USER |   \
 -                                       _PAGE_ACCESSED)
 -#define PAGE_COPY             PAGE_COPY_NOEXEC
 -#define PAGE_READONLY         __pgprot(_PAGE_PRESENT | _PAGE_USER |   \
 -                                       _PAGE_ACCESSED | _PAGE_NX)
 -#define PAGE_READONLY_EXEC    __pgprot(_PAGE_PRESENT | _PAGE_USER |   \
 -                                       _PAGE_ACCESSED)
 -
 -#define __PAGE_KERNEL_EXEC                                            \
 -      (_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY | _PAGE_ACCESSED | _PAGE_GLOBAL)
 -#define __PAGE_KERNEL         (__PAGE_KERNEL_EXEC | _PAGE_NX)
 -
 -#define __PAGE_KERNEL_RO              (__PAGE_KERNEL & ~_PAGE_RW)
 -#define __PAGE_KERNEL_RX              (__PAGE_KERNEL_EXEC & ~_PAGE_RW)
 -#define __PAGE_KERNEL_NOCACHE         (__PAGE_KERNEL | _PAGE_NOCACHE)
 -#define __PAGE_KERNEL_VVAR            (__PAGE_KERNEL_RO | _PAGE_USER)
 -#define __PAGE_KERNEL_LARGE           (__PAGE_KERNEL | _PAGE_PSE)
 -#define __PAGE_KERNEL_LARGE_EXEC      (__PAGE_KERNEL_EXEC | _PAGE_PSE)
 -#define __PAGE_KERNEL_WP              (__PAGE_KERNEL | _PAGE_CACHE_WP)
 -
 -#define __PAGE_KERNEL_IO              (__PAGE_KERNEL)
 -#define __PAGE_KERNEL_IO_NOCACHE      (__PAGE_KERNEL_NOCACHE)
 +#define _PAGE_CACHE_MASK      (_PAGE_PWT | _PAGE_PCD | _PAGE_PAT)
  
 -#ifndef __ASSEMBLY__
 +#define _PAGE_NOCACHE         (cachemode2protval(_PAGE_CACHE_MODE_UC))
 +#define _PAGE_CACHE_WP                (cachemode2protval(_PAGE_CACHE_MODE_WP))
  
 -#define _PAGE_ENC     (_AT(pteval_t, sme_me_mask))
 +#define __PP _PAGE_PRESENT
 +#define __RW _PAGE_RW
 +#define _USR _PAGE_USER
 +#define ___A _PAGE_ACCESSED
 +#define ___D _PAGE_DIRTY
 +#define ___G _PAGE_GLOBAL
 +#define __NX _PAGE_NX
 +
 +#define _ENC _PAGE_ENC
 +#define __WP _PAGE_CACHE_WP
 +#define __NC _PAGE_NOCACHE
 +#define _PSE _PAGE_PSE
 +
 +#define pgprot_val(x)         ((x).pgprot)
 +#define __pgprot(x)           ((pgprot_t) { (x) } )
 +#define __pg(x)                       __pgprot(x)
 +
 +#define _PAGE_PAT_LARGE               (_AT(pteval_t, 1) << _PAGE_BIT_PAT_LARGE)
 +
 +#define PAGE_NONE          __pg(   0|   0|   0|___A|   0|   0|   0|___G)
 +#define PAGE_SHARED        __pg(__PP|__RW|_USR|___A|__NX|   0|   0|   0)
 +#define PAGE_SHARED_EXEC     __pg(__PP|__RW|_USR|___A|   0|   0|   0|   0)
 +#define PAGE_COPY_NOEXEC     __pg(__PP|   0|_USR|___A|__NX|   0|   0|   0)
 +#define PAGE_COPY_EXEC             __pg(__PP|   0|_USR|___A|   0|   0|   0|   0)
 +#define PAGE_COPY          __pg(__PP|   0|_USR|___A|__NX|   0|   0|   0)
 +#define PAGE_READONLY      __pg(__PP|   0|_USR|___A|__NX|   0|   0|   0)
 +#define PAGE_READONLY_EXEC   __pg(__PP|   0|_USR|___A|   0|   0|   0|   0)
 +
 +#define __PAGE_KERNEL          (__PP|__RW|   0|___A|__NX|___D|   0|___G)
 +#define __PAGE_KERNEL_EXEC     (__PP|__RW|   0|___A|   0|___D|   0|___G)
 +#define _KERNPG_TABLE_NOENC    (__PP|__RW|   0|___A|   0|___D|   0|   0)
 +#define _KERNPG_TABLE          (__PP|__RW|   0|___A|   0|___D|   0|   0| _ENC)
 +#define _PAGE_TABLE_NOENC      (__PP|__RW|_USR|___A|   0|___D|   0|   0)
 +#define _PAGE_TABLE            (__PP|__RW|_USR|___A|   0|___D|   0|   0| _ENC)
 +#define __PAGE_KERNEL_RO       (__PP|   0|   0|___A|__NX|___D|   0|___G)
 +#define __PAGE_KERNEL_RX       (__PP|   0|   0|___A|   0|___D|   0|___G)
 +#define __PAGE_KERNEL_NOCACHE  (__PP|__RW|   0|___A|__NX|___D|   0|___G| __NC)
 +#define __PAGE_KERNEL_VVAR     (__PP|   0|_USR|___A|__NX|___D|   0|___G)
 +#define __PAGE_KERNEL_LARGE    (__PP|__RW|   0|___A|__NX|___D|_PSE|___G)
 +#define __PAGE_KERNEL_LARGE_EXEC (__PP|__RW|   0|___A|   0|___D|_PSE|___G)
 +#define __PAGE_KERNEL_WP       (__PP|__RW|   0|___A|__NX|___D|   0|___G| __WP)
 +
 +
 +#define __PAGE_KERNEL_IO              __PAGE_KERNEL
 +#define __PAGE_KERNEL_IO_NOCACHE      __PAGE_KERNEL_NOCACHE
  
 -#define _KERNPG_TABLE (_PAGE_PRESENT | _PAGE_RW | _PAGE_ACCESSED |    \
 -                       _PAGE_DIRTY | _PAGE_ENC)
 -#define _PAGE_TABLE   (_KERNPG_TABLE | _PAGE_USER)
  
 -#define __PAGE_KERNEL_ENC     (__PAGE_KERNEL | _PAGE_ENC)
 -#define __PAGE_KERNEL_ENC_WP  (__PAGE_KERNEL_WP | _PAGE_ENC)
 +#ifndef __ASSEMBLY__
  
 -#define __PAGE_KERNEL_NOENC   (__PAGE_KERNEL)
 -#define __PAGE_KERNEL_NOENC_WP        (__PAGE_KERNEL_WP)
 +#define __PAGE_KERNEL_ENC     (__PAGE_KERNEL    | _ENC)
 +#define __PAGE_KERNEL_ENC_WP  (__PAGE_KERNEL_WP | _ENC)
 +#define __PAGE_KERNEL_NOENC   (__PAGE_KERNEL    |    0)
 +#define __PAGE_KERNEL_NOENC_WP        (__PAGE_KERNEL_WP |    0)
  
 -#define default_pgprot(x)     __pgprot((x) & __default_kernel_pte_mask)
 +#define __pgprot_mask(x)      __pgprot((x) & __default_kernel_pte_mask)
  
 -#define PAGE_KERNEL           default_pgprot(__PAGE_KERNEL | _PAGE_ENC)
 -#define PAGE_KERNEL_NOENC     default_pgprot(__PAGE_KERNEL)
 -#define PAGE_KERNEL_RO                default_pgprot(__PAGE_KERNEL_RO | _PAGE_ENC)
 -#define PAGE_KERNEL_EXEC      default_pgprot(__PAGE_KERNEL_EXEC | _PAGE_ENC)
 -#define PAGE_KERNEL_EXEC_NOENC        default_pgprot(__PAGE_KERNEL_EXEC)
 -#define PAGE_KERNEL_RX                default_pgprot(__PAGE_KERNEL_RX | _PAGE_ENC)
 -#define PAGE_KERNEL_NOCACHE   default_pgprot(__PAGE_KERNEL_NOCACHE | _PAGE_ENC)
 -#define PAGE_KERNEL_LARGE     default_pgprot(__PAGE_KERNEL_LARGE | _PAGE_ENC)
 -#define PAGE_KERNEL_LARGE_EXEC        default_pgprot(__PAGE_KERNEL_LARGE_EXEC | _PAGE_ENC)
 -#define PAGE_KERNEL_VVAR      default_pgprot(__PAGE_KERNEL_VVAR | _PAGE_ENC)
 +#define PAGE_KERNEL           __pgprot_mask(__PAGE_KERNEL            | _ENC)
 +#define PAGE_KERNEL_NOENC     __pgprot_mask(__PAGE_KERNEL            |    0)
 +#define PAGE_KERNEL_RO                __pgprot_mask(__PAGE_KERNEL_RO         | _ENC)
 +#define PAGE_KERNEL_EXEC      __pgprot_mask(__PAGE_KERNEL_EXEC       | _ENC)
 +#define PAGE_KERNEL_EXEC_NOENC        __pgprot_mask(__PAGE_KERNEL_EXEC       |    0)
 +#define PAGE_KERNEL_RX                __pgprot_mask(__PAGE_KERNEL_RX         | _ENC)
 +#define PAGE_KERNEL_NOCACHE   __pgprot_mask(__PAGE_KERNEL_NOCACHE    | _ENC)
 +#define PAGE_KERNEL_LARGE     __pgprot_mask(__PAGE_KERNEL_LARGE      | _ENC)
 +#define PAGE_KERNEL_LARGE_EXEC        __pgprot_mask(__PAGE_KERNEL_LARGE_EXEC | _ENC)
 +#define PAGE_KERNEL_VVAR      __pgprot_mask(__PAGE_KERNEL_VVAR       | _ENC)
  
 -#define PAGE_KERNEL_IO                default_pgprot(__PAGE_KERNEL_IO)
 -#define PAGE_KERNEL_IO_NOCACHE        default_pgprot(__PAGE_KERNEL_IO_NOCACHE)
 +#define PAGE_KERNEL_IO                __pgprot_mask(__PAGE_KERNEL_IO)
 +#define PAGE_KERNEL_IO_NOCACHE        __pgprot_mask(__PAGE_KERNEL_IO_NOCACHE)
  
  #endif        /* __ASSEMBLY__ */
  
@@@ -457,6 -449,9 +457,6 @@@ static inline pteval_t pte_flags(pte_t 
        return native_pte_val(pte) & PTE_FLAGS_MASK;
  }
  
 -#define pgprot_val(x) ((x).pgprot)
 -#define __pgprot(x)   ((pgprot_t) { (x) } )
 -
  extern uint16_t __cachemode2pte_tbl[_PAGE_CACHE_MODE_NUM];
  extern uint8_t __pte2cachemode_tbl[8];
  
@@@ -566,6 -561,10 +566,10 @@@ static inline void update_page_count(in
  extern pte_t *lookup_address(unsigned long address, unsigned int *level);
  extern pte_t *lookup_address_in_pgd(pgd_t *pgd, unsigned long address,
                                    unsigned int *level);
+ struct mm_struct;
+ extern pte_t *lookup_address_in_mm(struct mm_struct *mm, unsigned long address,
+                                  unsigned int *level);
  extern pmd_t *lookup_pmd_address(unsigned long address);
  extern phys_addr_t slow_virt_to_phys(void *__address);
  extern int __init kernel_map_pages_in_pgd(pgd_t *pgd, u64 pfn,
  #include <linux/bitops.h>
  #include <linux/types.h>
  #include <uapi/asm/vmx.h>
 +#include <asm/vmxfeatures.h>
 +
 +#define VMCS_CONTROL_BIT(x)   BIT(VMX_FEATURE_##x & 0x1f)
  
  /*
   * Definitions of Primary Processor-Based VM-Execution Controls.
   */
- #define CPU_BASED_VIRTUAL_INTR_PENDING          VMCS_CONTROL_BIT(VIRTUAL_INTR_PENDING)
- #define CPU_BASED_USE_TSC_OFFSETING             VMCS_CONTROL_BIT(TSC_OFFSETTING)
 -#define CPU_BASED_INTR_WINDOW_EXITING           0x00000004
 -#define CPU_BASED_USE_TSC_OFFSETTING            0x00000008
 -#define CPU_BASED_HLT_EXITING                   0x00000080
 -#define CPU_BASED_INVLPG_EXITING                0x00000200
 -#define CPU_BASED_MWAIT_EXITING                 0x00000400
 -#define CPU_BASED_RDPMC_EXITING                 0x00000800
 -#define CPU_BASED_RDTSC_EXITING                 0x00001000
 -#define CPU_BASED_CR3_LOAD_EXITING            0x00008000
 -#define CPU_BASED_CR3_STORE_EXITING           0x00010000
 -#define CPU_BASED_CR8_LOAD_EXITING              0x00080000
 -#define CPU_BASED_CR8_STORE_EXITING             0x00100000
 -#define CPU_BASED_TPR_SHADOW                    0x00200000
 -#define CPU_BASED_NMI_WINDOW_EXITING          0x00400000
 -#define CPU_BASED_MOV_DR_EXITING                0x00800000
 -#define CPU_BASED_UNCOND_IO_EXITING             0x01000000
 -#define CPU_BASED_USE_IO_BITMAPS                0x02000000
 -#define CPU_BASED_MONITOR_TRAP_FLAG             0x08000000
 -#define CPU_BASED_USE_MSR_BITMAPS               0x10000000
 -#define CPU_BASED_MONITOR_EXITING               0x20000000
 -#define CPU_BASED_PAUSE_EXITING                 0x40000000
 -#define CPU_BASED_ACTIVATE_SECONDARY_CONTROLS   0x80000000
++#define CPU_BASED_INTR_WINDOW_EXITING           VMCS_CONTROL_BIT(VIRTUAL_INTR_PENDING)
++#define CPU_BASED_USE_TSC_OFFSETTING            VMCS_CONTROL_BIT(TSC_OFFSETTING)
 +#define CPU_BASED_HLT_EXITING                   VMCS_CONTROL_BIT(HLT_EXITING)
 +#define CPU_BASED_INVLPG_EXITING                VMCS_CONTROL_BIT(INVLPG_EXITING)
 +#define CPU_BASED_MWAIT_EXITING                 VMCS_CONTROL_BIT(MWAIT_EXITING)
 +#define CPU_BASED_RDPMC_EXITING                 VMCS_CONTROL_BIT(RDPMC_EXITING)
 +#define CPU_BASED_RDTSC_EXITING                 VMCS_CONTROL_BIT(RDTSC_EXITING)
 +#define CPU_BASED_CR3_LOAD_EXITING            VMCS_CONTROL_BIT(CR3_LOAD_EXITING)
 +#define CPU_BASED_CR3_STORE_EXITING           VMCS_CONTROL_BIT(CR3_STORE_EXITING)
 +#define CPU_BASED_CR8_LOAD_EXITING              VMCS_CONTROL_BIT(CR8_LOAD_EXITING)
 +#define CPU_BASED_CR8_STORE_EXITING             VMCS_CONTROL_BIT(CR8_STORE_EXITING)
 +#define CPU_BASED_TPR_SHADOW                    VMCS_CONTROL_BIT(VIRTUAL_TPR)
- #define CPU_BASED_VIRTUAL_NMI_PENDING         VMCS_CONTROL_BIT(VIRTUAL_NMI_PENDING)
++#define CPU_BASED_NMI_WINDOW_EXITING          VMCS_CONTROL_BIT(VIRTUAL_NMI_PENDING)
 +#define CPU_BASED_MOV_DR_EXITING                VMCS_CONTROL_BIT(MOV_DR_EXITING)
 +#define CPU_BASED_UNCOND_IO_EXITING             VMCS_CONTROL_BIT(UNCOND_IO_EXITING)
 +#define CPU_BASED_USE_IO_BITMAPS                VMCS_CONTROL_BIT(USE_IO_BITMAPS)
 +#define CPU_BASED_MONITOR_TRAP_FLAG             VMCS_CONTROL_BIT(MONITOR_TRAP_FLAG)
 +#define CPU_BASED_USE_MSR_BITMAPS               VMCS_CONTROL_BIT(USE_MSR_BITMAPS)
 +#define CPU_BASED_MONITOR_EXITING               VMCS_CONTROL_BIT(MONITOR_EXITING)
 +#define CPU_BASED_PAUSE_EXITING                 VMCS_CONTROL_BIT(PAUSE_EXITING)
 +#define CPU_BASED_ACTIVATE_SECONDARY_CONTROLS   VMCS_CONTROL_BIT(SEC_CONTROLS)
  
  #define CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR   0x0401e172
  
  /*
   * Definitions of Secondary Processor-Based VM-Execution Controls.
   */
 -#define SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES 0x00000001
 -#define SECONDARY_EXEC_ENABLE_EPT               0x00000002
 -#define SECONDARY_EXEC_DESC                   0x00000004
 -#define SECONDARY_EXEC_RDTSCP                 0x00000008
 -#define SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE   0x00000010
 -#define SECONDARY_EXEC_ENABLE_VPID              0x00000020
 -#define SECONDARY_EXEC_WBINVD_EXITING         0x00000040
 -#define SECONDARY_EXEC_UNRESTRICTED_GUEST     0x00000080
 -#define SECONDARY_EXEC_APIC_REGISTER_VIRT       0x00000100
 -#define SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY    0x00000200
 -#define SECONDARY_EXEC_PAUSE_LOOP_EXITING     0x00000400
 -#define SECONDARY_EXEC_RDRAND_EXITING         0x00000800
 -#define SECONDARY_EXEC_ENABLE_INVPCID         0x00001000
 -#define SECONDARY_EXEC_ENABLE_VMFUNC            0x00002000
 -#define SECONDARY_EXEC_SHADOW_VMCS              0x00004000
 -#define SECONDARY_EXEC_ENCLS_EXITING          0x00008000
 -#define SECONDARY_EXEC_RDSEED_EXITING         0x00010000
 -#define SECONDARY_EXEC_ENABLE_PML               0x00020000
 -#define SECONDARY_EXEC_PT_CONCEAL_VMX         0x00080000
 -#define SECONDARY_EXEC_XSAVES                 0x00100000
 -#define SECONDARY_EXEC_PT_USE_GPA             0x01000000
 -#define SECONDARY_EXEC_MODE_BASED_EPT_EXEC    0x00400000
 -#define SECONDARY_EXEC_TSC_SCALING              0x02000000
 +#define SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES VMCS_CONTROL_BIT(VIRT_APIC_ACCESSES)
 +#define SECONDARY_EXEC_ENABLE_EPT               VMCS_CONTROL_BIT(EPT)
 +#define SECONDARY_EXEC_DESC                   VMCS_CONTROL_BIT(DESC_EXITING)
 +#define SECONDARY_EXEC_RDTSCP                 VMCS_CONTROL_BIT(RDTSCP)
 +#define SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE   VMCS_CONTROL_BIT(VIRTUAL_X2APIC)
 +#define SECONDARY_EXEC_ENABLE_VPID              VMCS_CONTROL_BIT(VPID)
 +#define SECONDARY_EXEC_WBINVD_EXITING         VMCS_CONTROL_BIT(WBINVD_EXITING)
 +#define SECONDARY_EXEC_UNRESTRICTED_GUEST     VMCS_CONTROL_BIT(UNRESTRICTED_GUEST)
 +#define SECONDARY_EXEC_APIC_REGISTER_VIRT       VMCS_CONTROL_BIT(APIC_REGISTER_VIRT)
 +#define SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY    VMCS_CONTROL_BIT(VIRT_INTR_DELIVERY)
 +#define SECONDARY_EXEC_PAUSE_LOOP_EXITING     VMCS_CONTROL_BIT(PAUSE_LOOP_EXITING)
 +#define SECONDARY_EXEC_RDRAND_EXITING         VMCS_CONTROL_BIT(RDRAND_EXITING)
 +#define SECONDARY_EXEC_ENABLE_INVPCID         VMCS_CONTROL_BIT(INVPCID)
 +#define SECONDARY_EXEC_ENABLE_VMFUNC            VMCS_CONTROL_BIT(VMFUNC)
 +#define SECONDARY_EXEC_SHADOW_VMCS              VMCS_CONTROL_BIT(SHADOW_VMCS)
 +#define SECONDARY_EXEC_ENCLS_EXITING          VMCS_CONTROL_BIT(ENCLS_EXITING)
 +#define SECONDARY_EXEC_RDSEED_EXITING         VMCS_CONTROL_BIT(RDSEED_EXITING)
 +#define SECONDARY_EXEC_ENABLE_PML               VMCS_CONTROL_BIT(PAGE_MOD_LOGGING)
 +#define SECONDARY_EXEC_PT_CONCEAL_VMX         VMCS_CONTROL_BIT(PT_CONCEAL_VMX)
 +#define SECONDARY_EXEC_XSAVES                 VMCS_CONTROL_BIT(XSAVES)
 +#define SECONDARY_EXEC_MODE_BASED_EPT_EXEC    VMCS_CONTROL_BIT(MODE_BASED_EPT_EXEC)
 +#define SECONDARY_EXEC_PT_USE_GPA             VMCS_CONTROL_BIT(PT_USE_GPA)
 +#define SECONDARY_EXEC_TSC_SCALING              VMCS_CONTROL_BIT(TSC_SCALING)
  #define SECONDARY_EXEC_ENABLE_USR_WAIT_PAUSE  0x04000000
  
 -#define PIN_BASED_EXT_INTR_MASK                 0x00000001
 -#define PIN_BASED_NMI_EXITING                   0x00000008
 -#define PIN_BASED_VIRTUAL_NMIS                  0x00000020
 -#define PIN_BASED_VMX_PREEMPTION_TIMER          0x00000040
 -#define PIN_BASED_POSTED_INTR                   0x00000080
 +#define PIN_BASED_EXT_INTR_MASK                 VMCS_CONTROL_BIT(INTR_EXITING)
 +#define PIN_BASED_NMI_EXITING                   VMCS_CONTROL_BIT(NMI_EXITING)
 +#define PIN_BASED_VIRTUAL_NMIS                  VMCS_CONTROL_BIT(VIRTUAL_NMIS)
 +#define PIN_BASED_VMX_PREEMPTION_TIMER          VMCS_CONTROL_BIT(PREEMPTION_TIMER)
 +#define PIN_BASED_POSTED_INTR                   VMCS_CONTROL_BIT(POSTED_INTR)
  
  #define PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR   0x00000016
  
  #define VMX_MISC_MSR_LIST_MULTIPLIER          512
  
  /* VMFUNC functions */
 -#define VMX_VMFUNC_EPTP_SWITCHING               0x00000001
 +#define VMFUNC_CONTROL_BIT(x) BIT((VMX_FEATURE_##x & 0x1f) - 28)
 +
 +#define VMX_VMFUNC_EPTP_SWITCHING               VMFUNC_CONTROL_BIT(EPTP_SWITCHING)
  #define VMFUNC_EPTP_ENTRIES  512
  
  static inline u32 vmx_basic_vmcs_revision_id(u64 vmx_basic)
diff --combined arch/x86/kvm/mmu/mmu.c
@@@ -40,7 -40,7 +40,7 @@@
  #include <linux/kthread.h>
  
  #include <asm/page.h>
 -#include <asm/pat.h>
 +#include <asm/memtype.h>
  #include <asm/cmpxchg.h>
  #include <asm/e820/api.h>
  #include <asm/io.h>
@@@ -418,22 -418,24 +418,24 @@@ static inline bool is_access_track_spte
   * requires a full MMU zap).  The flag is instead explicitly queried when
   * checking for MMIO spte cache hits.
   */
- #define MMIO_SPTE_GEN_MASK            GENMASK_ULL(18, 0)
+ #define MMIO_SPTE_GEN_MASK            GENMASK_ULL(17, 0)
  
  #define MMIO_SPTE_GEN_LOW_START               3
  #define MMIO_SPTE_GEN_LOW_END         11
  #define MMIO_SPTE_GEN_LOW_MASK                GENMASK_ULL(MMIO_SPTE_GEN_LOW_END, \
                                                    MMIO_SPTE_GEN_LOW_START)
  
- #define MMIO_SPTE_GEN_HIGH_START      52
- #define MMIO_SPTE_GEN_HIGH_END                61
+ #define MMIO_SPTE_GEN_HIGH_START      PT64_SECOND_AVAIL_BITS_SHIFT
+ #define MMIO_SPTE_GEN_HIGH_END                62
  #define MMIO_SPTE_GEN_HIGH_MASK               GENMASK_ULL(MMIO_SPTE_GEN_HIGH_END, \
                                                    MMIO_SPTE_GEN_HIGH_START)
  static u64 generation_mmio_spte_mask(u64 gen)
  {
        u64 mask;
  
        WARN_ON(gen & ~MMIO_SPTE_GEN_MASK);
+       BUILD_BUG_ON((MMIO_SPTE_GEN_HIGH_MASK | MMIO_SPTE_GEN_LOW_MASK) & SPTE_SPECIAL_MASK);
  
        mask = (gen << MMIO_SPTE_GEN_LOW_START) & MMIO_SPTE_GEN_LOW_MASK;
        mask |= (gen << MMIO_SPTE_GEN_HIGH_START) & MMIO_SPTE_GEN_HIGH_MASK;
@@@ -444,8 -446,6 +446,6 @@@ static u64 get_mmio_spte_generation(u6
  {
        u64 gen;
  
-       spte &= ~shadow_mmio_mask;
        gen = (spte & MMIO_SPTE_GEN_LOW_MASK) >> MMIO_SPTE_GEN_LOW_START;
        gen |= (spte & MMIO_SPTE_GEN_HIGH_MASK) >> MMIO_SPTE_GEN_HIGH_START;
        return gen;
@@@ -538,16 -538,20 +538,20 @@@ EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes
  static u8 kvm_get_shadow_phys_bits(void)
  {
        /*
-        * boot_cpu_data.x86_phys_bits is reduced when MKTME is detected
-        * in CPU detection code, but MKTME treats those reduced bits as
-        * 'keyID' thus they are not reserved bits. Therefore for MKTME
-        * we should still return physical address bits reported by CPUID.
+        * boot_cpu_data.x86_phys_bits is reduced when MKTME or SME are detected
+        * in CPU detection code, but the processor treats those reduced bits as
+        * 'keyID' thus they are not reserved bits. Therefore KVM needs to look at
+        * the physical address bits reported by CPUID.
         */
-       if (!boot_cpu_has(X86_FEATURE_TME) ||
-           WARN_ON_ONCE(boot_cpu_data.extended_cpuid_level < 0x80000008))
-               return boot_cpu_data.x86_phys_bits;
+       if (likely(boot_cpu_data.extended_cpuid_level >= 0x80000008))
+               return cpuid_eax(0x80000008) & 0xff;
  
-       return cpuid_eax(0x80000008) & 0xff;
+       /*
+        * Quite weird to have VMX or SVM but not MAXPHYADDR; probably a VM with
+        * custom CPUID.  Proceed with whatever the kernel found since these features
+        * aren't virtualizable (SME/SEV also require CPUIDs higher than 0x80000008).
+        */
+       return boot_cpu_data.x86_phys_bits;
  }
  
  static void kvm_mmu_reset_all_pte_masks(void)
@@@ -1260,56 -1264,6 +1264,6 @@@ static void unaccount_huge_nx_page(stru
        list_del(&sp->lpage_disallowed_link);
  }
  
- static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
-                                         struct kvm_memory_slot *slot)
- {
-       struct kvm_lpage_info *linfo;
-       if (slot) {
-               linfo = lpage_info_slot(gfn, slot, level);
-               return !!linfo->disallow_lpage;
-       }
-       return true;
- }
- static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
-                                       int level)
- {
-       struct kvm_memory_slot *slot;
-       slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
-       return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
- }
- static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
- {
-       unsigned long page_size;
-       int i, ret = 0;
-       page_size = kvm_host_page_size(kvm, gfn);
-       for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
-               if (page_size >= KVM_HPAGE_SIZE(i))
-                       ret = i;
-               else
-                       break;
-       }
-       return ret;
- }
- static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
-                                         bool no_dirty_log)
- {
-       if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
-               return false;
-       if (no_dirty_log && slot->dirty_bitmap)
-               return false;
-       return true;
- }
  static struct kvm_memory_slot *
  gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
                            bool no_dirty_log)
        struct kvm_memory_slot *slot;
  
        slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
-       if (!memslot_valid_for_gpte(slot, no_dirty_log))
-               slot = NULL;
+       if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
+               return NULL;
+       if (no_dirty_log && slot->dirty_bitmap)
+               return NULL;
  
        return slot;
  }
  
- static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
-                        bool *force_pt_level)
- {
-       int host_level, level, max_level;
-       struct kvm_memory_slot *slot;
-       if (unlikely(*force_pt_level))
-               return PT_PAGE_TABLE_LEVEL;
-       slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
-       *force_pt_level = !memslot_valid_for_gpte(slot, true);
-       if (unlikely(*force_pt_level))
-               return PT_PAGE_TABLE_LEVEL;
-       host_level = host_mapping_level(vcpu->kvm, large_gfn);
-       if (host_level == PT_PAGE_TABLE_LEVEL)
-               return host_level;
-       max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
-       for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
-               if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
-                       break;
-       return level - 1;
- }
  /*
   * About rmap_head encoding:
   *
@@@ -1410,7 -1338,7 +1338,7 @@@ pte_list_desc_remove_entry(struct kvm_r
        if (j != 0)
                return;
        if (!prev_desc && !desc->more)
-               rmap_head->val = (unsigned long)desc->sptes[0];
+               rmap_head->val = 0;
        else
                if (prev_desc)
                        prev_desc->more = desc->more;
@@@ -1525,7 -1453,7 +1453,7 @@@ struct rmap_iterator 
  /*
   * Iteration must be started by this function.  This should also be used after
   * removing/dropping sptes from the rmap link because in such cases the
-  * information in the itererator may not be valid.
+  * information in the iterator may not be valid.
   *
   * Returns sptep if found, NULL otherwise.
   */
@@@ -2899,6 -2827,26 +2827,26 @@@ static bool prepare_zap_oldest_mmu_page
        return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
  }
  
+ static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
+ {
+       LIST_HEAD(invalid_list);
+       if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
+               return 0;
+       while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
+               if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
+                       break;
+               ++vcpu->kvm->stat.mmu_recycled;
+       }
+       kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
+       if (!kvm_mmu_available_pages(vcpu->kvm))
+               return -ENOSPC;
+       return 0;
+ }
  /*
   * Changing the number of mmu pages allocated to the vm
   * Note: if goal_nr_mmu_pages is too small, you will get dead lock
@@@ -3099,17 -3047,6 +3047,6 @@@ static int set_spte(struct kvm_vcpu *vc
        spte |= (u64)pfn << PAGE_SHIFT;
  
        if (pte_access & ACC_WRITE_MASK) {
-               /*
-                * Other vcpu creates new sp in the window between
-                * mapping_level() and acquiring mmu-lock. We can
-                * allow guest to retry the access, the mapping can
-                * be fixed if guest refault.
-                */
-               if (level > PT_PAGE_TABLE_LEVEL &&
-                   mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
-                       goto done;
                spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
  
                /*
  set_pte:
        if (mmu_spte_update(sptep, spte))
                ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
- done:
        return ret;
  }
  
@@@ -3294,6 -3230,83 +3230,83 @@@ static void direct_pte_prefetch(struct 
        __direct_pte_prefetch(vcpu, sp, sptep);
  }
  
+ static int host_pfn_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn,
+                                 kvm_pfn_t pfn, struct kvm_memory_slot *slot)
+ {
+       unsigned long hva;
+       pte_t *pte;
+       int level;
+       BUILD_BUG_ON(PT_PAGE_TABLE_LEVEL != (int)PG_LEVEL_4K ||
+                    PT_DIRECTORY_LEVEL != (int)PG_LEVEL_2M ||
+                    PT_PDPE_LEVEL != (int)PG_LEVEL_1G);
+       if (!PageCompound(pfn_to_page(pfn)) && !kvm_is_zone_device_pfn(pfn))
+               return PT_PAGE_TABLE_LEVEL;
+       /*
+        * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
+        * is not solely for performance, it's also necessary to avoid the
+        * "writable" check in __gfn_to_hva_many(), which will always fail on
+        * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
+        * page fault steps have already verified the guest isn't writing a
+        * read-only memslot.
+        */
+       hva = __gfn_to_hva_memslot(slot, gfn);
+       pte = lookup_address_in_mm(vcpu->kvm->mm, hva, &level);
+       if (unlikely(!pte))
+               return PT_PAGE_TABLE_LEVEL;
+       return level;
+ }
+ static int kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, gfn_t gfn,
+                                  int max_level, kvm_pfn_t *pfnp)
+ {
+       struct kvm_memory_slot *slot;
+       struct kvm_lpage_info *linfo;
+       kvm_pfn_t pfn = *pfnp;
+       kvm_pfn_t mask;
+       int level;
+       if (unlikely(max_level == PT_PAGE_TABLE_LEVEL))
+               return PT_PAGE_TABLE_LEVEL;
+       if (is_error_noslot_pfn(pfn) || kvm_is_reserved_pfn(pfn))
+               return PT_PAGE_TABLE_LEVEL;
+       slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, true);
+       if (!slot)
+               return PT_PAGE_TABLE_LEVEL;
+       max_level = min(max_level, kvm_x86_ops->get_lpage_level());
+       for ( ; max_level > PT_PAGE_TABLE_LEVEL; max_level--) {
+               linfo = lpage_info_slot(gfn, slot, max_level);
+               if (!linfo->disallow_lpage)
+                       break;
+       }
+       if (max_level == PT_PAGE_TABLE_LEVEL)
+               return PT_PAGE_TABLE_LEVEL;
+       level = host_pfn_mapping_level(vcpu, gfn, pfn, slot);
+       if (level == PT_PAGE_TABLE_LEVEL)
+               return level;
+       level = min(level, max_level);
+       /*
+        * mmu_notifier_retry() was successful and mmu_lock is held, so
+        * the pmd can't be split from under us.
+        */
+       mask = KVM_PAGES_PER_HPAGE(level) - 1;
+       VM_BUG_ON((gfn & mask) != (pfn & mask));
+       *pfnp = pfn & ~mask;
+       return level;
+ }
  static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
                                       gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
  {
  }
  
  static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
-                       int map_writable, int level, kvm_pfn_t pfn,
-                       bool prefault, bool lpage_disallowed)
+                       int map_writable, int max_level, kvm_pfn_t pfn,
+                       bool prefault, bool account_disallowed_nx_lpage)
  {
        struct kvm_shadow_walk_iterator it;
        struct kvm_mmu_page *sp;
-       int ret;
+       int level, ret;
        gfn_t gfn = gpa >> PAGE_SHIFT;
        gfn_t base_gfn = gfn;
  
-       if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
+       if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
                return RET_PF_RETRY;
  
+       level = kvm_mmu_hugepage_adjust(vcpu, gfn, max_level, &pfn);
        trace_kvm_mmu_spte_requested(gpa, level, pfn);
        for_each_shadow_entry(vcpu, gpa, it) {
                /*
                                              it.level - 1, true, ACC_ALL);
  
                        link_shadow_page(vcpu, it.sptep, sp);
-                       if (lpage_disallowed)
+                       if (account_disallowed_nx_lpage)
                                account_huge_nx_page(vcpu->kvm, sp);
                }
        }
@@@ -3384,45 -3399,6 +3399,6 @@@ static int kvm_handle_bad_page(struct k
        return -EFAULT;
  }
  
- static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
-                                       gfn_t gfn, kvm_pfn_t *pfnp,
-                                       int *levelp)
- {
-       kvm_pfn_t pfn = *pfnp;
-       int level = *levelp;
-       /*
-        * Check if it's a transparent hugepage. If this would be an
-        * hugetlbfs page, level wouldn't be set to
-        * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
-        * here.
-        */
-       if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
-           !kvm_is_zone_device_pfn(pfn) && level == PT_PAGE_TABLE_LEVEL &&
-           PageTransCompoundMap(pfn_to_page(pfn)) &&
-           !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
-               unsigned long mask;
-               /*
-                * mmu_notifier_retry was successful and we hold the
-                * mmu_lock here, so the pmd can't become splitting
-                * from under us, and in turn
-                * __split_huge_page_refcount() can't run from under
-                * us and we can safely transfer the refcount from
-                * PG_tail to PG_head as we switch the pfn to tail to
-                * head.
-                */
-               *levelp = level = PT_DIRECTORY_LEVEL;
-               mask = KVM_PAGES_PER_HPAGE(level) - 1;
-               VM_BUG_ON((gfn & mask) != (pfn & mask));
-               if (pfn & mask) {
-                       kvm_release_pfn_clean(pfn);
-                       pfn &= ~mask;
-                       kvm_get_pfn(pfn);
-                       *pfnp = pfn;
-               }
-       }
- }
  static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
                                kvm_pfn_t pfn, unsigned access, int *ret_val)
  {
@@@ -3528,7 -3504,7 +3504,7 @@@ static bool is_access_allowed(u32 fault
   * - true: let the vcpu to access on the same address again.
   * - false: let the real page fault path to fix it.
   */
- static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
+ static bool fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
                            u32 error_code)
  {
        struct kvm_shadow_walk_iterator iterator;
        u64 spte = 0ull;
        uint retry_count = 0;
  
-       if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
-               return false;
        if (!page_fault_can_be_fast(error_code))
                return false;
  
        do {
                u64 new_spte;
  
-               for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
-                       if (!is_shadow_present_pte(spte) ||
-                           iterator.level < level)
+               for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
+                       if (!is_shadow_present_pte(spte))
                                break;
  
                sp = page_header(__pa(iterator.sptep));
  
        } while (true);
  
-       trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
+       trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
                              spte, fault_handled);
        walk_shadow_page_lockless_end(vcpu);
  
        return fault_handled;
  }
  
- static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
-                        gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
- static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
- static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
-                        gfn_t gfn, bool prefault)
- {
-       int r;
-       int level;
-       bool force_pt_level;
-       kvm_pfn_t pfn;
-       unsigned long mmu_seq;
-       bool map_writable, write = error_code & PFERR_WRITE_MASK;
-       bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
-                               is_nx_huge_page_enabled();
-       force_pt_level = lpage_disallowed;
-       level = mapping_level(vcpu, gfn, &force_pt_level);
-       if (likely(!force_pt_level)) {
-               /*
-                * This path builds a PAE pagetable - so we can map
-                * 2mb pages at maximum. Therefore check if the level
-                * is larger than that.
-                */
-               if (level > PT_DIRECTORY_LEVEL)
-                       level = PT_DIRECTORY_LEVEL;
-               gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
-       }
-       if (fast_page_fault(vcpu, v, level, error_code))
-               return RET_PF_RETRY;
-       mmu_seq = vcpu->kvm->mmu_notifier_seq;
-       smp_rmb();
-       if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
-               return RET_PF_RETRY;
-       if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
-               return r;
-       r = RET_PF_RETRY;
-       spin_lock(&vcpu->kvm->mmu_lock);
-       if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
-               goto out_unlock;
-       if (make_mmu_pages_available(vcpu) < 0)
-               goto out_unlock;
-       if (likely(!force_pt_level))
-               transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
-       r = __direct_map(vcpu, v, write, map_writable, level, pfn,
-                        prefault, false);
- out_unlock:
-       spin_unlock(&vcpu->kvm->mmu_lock);
-       kvm_release_pfn_clean(pfn);
-       return r;
- }
  static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
                               struct list_head *invalid_list)
  {
@@@ -3981,7 -3895,7 +3895,7 @@@ void kvm_mmu_sync_roots(struct kvm_vcp
  }
  EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
  
- static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
+ static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
                                  u32 access, struct x86_exception *exception)
  {
        if (exception)
        return vaddr;
  }
  
- static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
+ static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
                                         u32 access,
                                         struct x86_exception *exception)
  {
  static bool
  __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
  {
-       int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
+       int bit7 = (pte >> 7) & 1;
  
-       return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
-               ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
+       return pte & rsvd_check->rsvd_bits_mask[bit7][level-1];
  }
  
- static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
+ static bool __is_bad_mt_xwr(struct rsvd_bits_validate *rsvd_check, u64 pte)
  {
-       return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
- }
- static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
- {
-       return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
+       return rsvd_check->bad_mt_xwr & BIT_ULL(pte & 0x3f);
  }
  
  static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
@@@ -4038,11 -3946,11 +3946,11 @@@ walk_shadow_page_get_mmio_spte(struct k
  {
        struct kvm_shadow_walk_iterator iterator;
        u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
+       struct rsvd_bits_validate *rsvd_check;
        int root, leaf;
        bool reserved = false;
  
-       if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
-               goto exit;
+       rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
  
        walk_shadow_page_lockless_begin(vcpu);
  
                if (!is_shadow_present_pte(spte))
                        break;
  
-               reserved |= is_shadow_zero_bits_set(vcpu->arch.mmu, spte,
-                                                   iterator.level);
+               /*
+                * Use a bitwise-OR instead of a logical-OR to aggregate the
+                * reserved bit and EPT's invalid memtype/XWR checks to avoid
+                * adding a Jcc in the loop.
+                */
+               reserved |= __is_bad_mt_xwr(rsvd_check, spte) |
+                           __is_rsvd_bits_set(rsvd_check, spte, iterator.level);
        }
  
        walk_shadow_page_lockless_end(vcpu);
                        root--;
                }
        }
- exit:
        *sptep = spte;
        return reserved;
  }
@@@ -4137,9 -4050,6 +4050,6 @@@ static void shadow_page_table_clear_flo
        struct kvm_shadow_walk_iterator iterator;
        u64 spte;
  
-       if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
-               return;
        walk_shadow_page_lockless_begin(vcpu);
        for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
                clear_sp_write_flooding_count(iterator.sptep);
        walk_shadow_page_lockless_end(vcpu);
  }
  
- static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
-                               u32 error_code, bool prefault)
- {
-       gfn_t gfn = gva >> PAGE_SHIFT;
-       int r;
-       pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
-       if (page_fault_handle_page_track(vcpu, error_code, gfn))
-               return RET_PF_EMULATE;
-       r = mmu_topup_memory_caches(vcpu);
-       if (r)
-               return r;
-       MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
-       return nonpaging_map(vcpu, gva & PAGE_MASK,
-                            error_code, gfn, prefault);
- }
- static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
+ static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
+                                  gfn_t gfn)
  {
        struct kvm_arch_async_pf arch;
  
        arch.direct_map = vcpu->arch.mmu->direct_map;
        arch.cr3 = vcpu->arch.mmu->get_cr3(vcpu);
  
-       return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
+       return kvm_setup_async_pf(vcpu, cr2_or_gpa,
+                                 kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
  }
  
  static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
-                        gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
+                        gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
+                        bool *writable)
  {
        struct kvm_memory_slot *slot;
        bool async;
                return false; /* *pfn has correct page already */
  
        if (!prefault && kvm_can_do_async_pf(vcpu)) {
-               trace_kvm_try_async_get_page(gva, gfn);
+               trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
                if (kvm_find_async_pf_gfn(vcpu, gfn)) {
-                       trace_kvm_async_pf_doublefault(gva, gfn);
+                       trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
                        kvm_make_request(KVM_REQ_APF_HALT, vcpu);
                        return true;
-               } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
+               } else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
                        return true;
        }
  
        return false;
  }
  
+ static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
+                            bool prefault, int max_level, bool is_tdp)
+ {
+       bool write = error_code & PFERR_WRITE_MASK;
+       bool exec = error_code & PFERR_FETCH_MASK;
+       bool lpage_disallowed = exec && is_nx_huge_page_enabled();
+       bool map_writable;
+       gfn_t gfn = gpa >> PAGE_SHIFT;
+       unsigned long mmu_seq;
+       kvm_pfn_t pfn;
+       int r;
+       if (page_fault_handle_page_track(vcpu, error_code, gfn))
+               return RET_PF_EMULATE;
+       r = mmu_topup_memory_caches(vcpu);
+       if (r)
+               return r;
+       if (lpage_disallowed)
+               max_level = PT_PAGE_TABLE_LEVEL;
+       if (fast_page_fault(vcpu, gpa, error_code))
+               return RET_PF_RETRY;
+       mmu_seq = vcpu->kvm->mmu_notifier_seq;
+       smp_rmb();
+       if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
+               return RET_PF_RETRY;
+       if (handle_abnormal_pfn(vcpu, is_tdp ? 0 : gpa, gfn, pfn, ACC_ALL, &r))
+               return r;
+       r = RET_PF_RETRY;
+       spin_lock(&vcpu->kvm->mmu_lock);
+       if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
+               goto out_unlock;
+       if (make_mmu_pages_available(vcpu) < 0)
+               goto out_unlock;
+       r = __direct_map(vcpu, gpa, write, map_writable, max_level, pfn,
+                        prefault, is_tdp && lpage_disallowed);
+ out_unlock:
+       spin_unlock(&vcpu->kvm->mmu_lock);
+       kvm_release_pfn_clean(pfn);
+       return r;
+ }
+ static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
+                               u32 error_code, bool prefault)
+ {
+       pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
+       /* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
+       return direct_page_fault(vcpu, gpa & PAGE_MASK, error_code, prefault,
+                                PT_DIRECTORY_LEVEL, false);
+ }
  int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
                                u64 fault_address, char *insn, int insn_len)
  {
        int r = 1;
  
+ #ifndef CONFIG_X86_64
+       /* A 64-bit CR2 should be impossible on 32-bit KVM. */
+       if (WARN_ON_ONCE(fault_address >> 32))
+               return -EFAULT;
+ #endif
        vcpu->arch.l1tf_flush_l1d = true;
        switch (vcpu->arch.apf.host_apf_reason) {
        default:
  }
  EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
  
- static bool
- check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
- {
-       int page_num = KVM_PAGES_PER_HPAGE(level);
-       gfn &= ~(page_num - 1);
-       return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
- }
- static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
+ static int tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
                          bool prefault)
  {
-       kvm_pfn_t pfn;
-       int r;
-       int level;
-       bool force_pt_level;
-       gfn_t gfn = gpa >> PAGE_SHIFT;
-       unsigned long mmu_seq;
-       int write = error_code & PFERR_WRITE_MASK;
-       bool map_writable;
-       bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
-                               is_nx_huge_page_enabled();
-       MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa));
+       int max_level;
  
-       if (page_fault_handle_page_track(vcpu, error_code, gfn))
-               return RET_PF_EMULATE;
+       for (max_level = PT_MAX_HUGEPAGE_LEVEL;
+            max_level > PT_PAGE_TABLE_LEVEL;
+            max_level--) {
+               int page_num = KVM_PAGES_PER_HPAGE(max_level);
+               gfn_t base = (gpa >> PAGE_SHIFT) & ~(page_num - 1);
  
-       r = mmu_topup_memory_caches(vcpu);
-       if (r)
-               return r;
-       force_pt_level =
-               lpage_disallowed ||
-               !check_hugepage_cache_consistency(vcpu, gfn, PT_DIRECTORY_LEVEL);
-       level = mapping_level(vcpu, gfn, &force_pt_level);
-       if (likely(!force_pt_level)) {
-               if (level > PT_DIRECTORY_LEVEL &&
-                   !check_hugepage_cache_consistency(vcpu, gfn, level))
-                       level = PT_DIRECTORY_LEVEL;
-               gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
+               if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
+                       break;
        }
  
-       if (fast_page_fault(vcpu, gpa, level, error_code))
-               return RET_PF_RETRY;
-       mmu_seq = vcpu->kvm->mmu_notifier_seq;
-       smp_rmb();
-       if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
-               return RET_PF_RETRY;
-       if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
-               return r;
-       r = RET_PF_RETRY;
-       spin_lock(&vcpu->kvm->mmu_lock);
-       if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
-               goto out_unlock;
-       if (make_mmu_pages_available(vcpu) < 0)
-               goto out_unlock;
-       if (likely(!force_pt_level))
-               transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
-       r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
-                        prefault, lpage_disallowed);
- out_unlock:
-       spin_unlock(&vcpu->kvm->mmu_lock);
-       kvm_release_pfn_clean(pfn);
-       return r;
+       return direct_page_fault(vcpu, gpa, error_code, prefault,
+                                max_level, true);
  }
  
  static void nonpaging_init_context(struct kvm_vcpu *vcpu,
@@@ -5496,47 -5400,30 +5400,30 @@@ int kvm_mmu_unprotect_page_virt(struct 
  }
  EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
  
- static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
- {
-       LIST_HEAD(invalid_list);
-       if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
-               return 0;
-       while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
-               if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
-                       break;
-               ++vcpu->kvm->stat.mmu_recycled;
-       }
-       kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
-       if (!kvm_mmu_available_pages(vcpu->kvm))
-               return -ENOSPC;
-       return 0;
- }
- int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
+ int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
                       void *insn, int insn_len)
  {
        int r, emulation_type = 0;
        bool direct = vcpu->arch.mmu->direct_map;
  
+       if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
+               return RET_PF_RETRY;
        /* With shadow page tables, fault_address contains a GVA or nGPA.  */
        if (vcpu->arch.mmu->direct_map) {
                vcpu->arch.gpa_available = true;
-               vcpu->arch.gpa_val = cr2;
+               vcpu->arch.gpa_val = cr2_or_gpa;
        }
  
        r = RET_PF_INVALID;
        if (unlikely(error_code & PFERR_RSVD_MASK)) {
-               r = handle_mmio_page_fault(vcpu, cr2, direct);
+               r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
                if (r == RET_PF_EMULATE)
                        goto emulate;
        }
  
        if (r == RET_PF_INVALID) {
-               r = vcpu->arch.mmu->page_fault(vcpu, cr2,
+               r = vcpu->arch.mmu->page_fault(vcpu, cr2_or_gpa,
                                               lower_32_bits(error_code),
                                               false);
                WARN_ON(r == RET_PF_INVALID);
         */
        if (vcpu->arch.mmu->direct_map &&
            (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
-               kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
+               kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
                return 1;
        }
  
         * explicitly shadowing L1's page tables, i.e. unprotecting something
         * for L1 isn't going to magically fix whatever issue cause L2 to fail.
         */
-       if (!mmio_info_in_cache(vcpu, cr2, direct) && !is_guest_mode(vcpu))
+       if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
                emulation_type = EMULTYPE_ALLOW_RETRY;
  emulate:
        /*
                        return 1;
        }
  
-       return x86_emulate_instruction(vcpu, cr2, emulation_type, insn,
+       return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
                                       insn_len);
  }
  EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
@@@ -6015,8 -5902,8 +5902,8 @@@ restart
                 * mapping if the indirect sp has level = 1.
                 */
                if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
-                   !kvm_is_zone_device_pfn(pfn) &&
-                   PageTransCompoundMap(pfn_to_page(pfn))) {
+                   (kvm_is_zone_device_pfn(pfn) ||
+                    PageCompound(pfn_to_page(pfn)))) {
                        pte_list_remove(rmap_head, sptep);
  
                        if (kvm_available_flush_tlb_with_range())
@@@ -6249,7 -6136,7 +6136,7 @@@ static void kvm_set_mmio_spte_mask(void
         * If reserved bit is not supported, clear the present bit to disable
         * mmio page fault.
         */
-       if (IS_ENABLED(CONFIG_X86_64) && shadow_phys_bits == 52)
+       if (shadow_phys_bits == 52)
                mask &= ~1ull;
  
        kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
@@@ -28,16 -28,6 +28,6 @@@ module_param(nested_early_check, bool, 
        failed;                                                         \
  })
  
- #define SET_MSR_OR_WARN(vcpu, idx, data)                              \
- ({                                                                    \
-       bool failed = kvm_set_msr(vcpu, idx, data);                     \
-       if (failed)                                                     \
-               pr_warn_ratelimited(                                    \
-                               "%s cannot write MSR (0x%x, 0x%llx)\n", \
-                               __func__, idx, data);                   \
-       failed;                                                         \
- })
  /*
   * Hyper-V requires all of these, so mark them as supported even though
   * they are just treated the same as all-context.
@@@ -2172,8 -2162,8 +2162,8 @@@ static void prepare_vmcs02_early(struc
         * EXEC CONTROLS
         */
        exec_control = vmx_exec_control(vmx); /* L0's desires */
-       exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
-       exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
+       exec_control &= ~CPU_BASED_INTR_WINDOW_EXITING;
+       exec_control &= ~CPU_BASED_NMI_WINDOW_EXITING;
        exec_control &= ~CPU_BASED_TPR_SHADOW;
        exec_control |= vmcs12->cpu_based_vm_exec_control;
  
@@@ -2550,8 -2540,8 +2540,8 @@@ static int prepare_vmcs02(struct kvm_vc
                vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
  
        if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) &&
-           SET_MSR_OR_WARN(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
-                           vmcs12->guest_ia32_perf_global_ctrl))
+           WARN_ON_ONCE(kvm_set_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
+                                    vmcs12->guest_ia32_perf_global_ctrl)))
                return -EINVAL;
  
        kvm_rsp_write(vcpu, vmcs12->guest_rsp);
@@@ -2566,7 -2556,7 +2556,7 @@@ static int nested_vmx_check_nmi_control
                return -EINVAL;
  
        if (CC(!nested_cpu_has_virtual_nmis(vmcs12) &&
-              nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING)))
+              nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING)))
                return -EINVAL;
  
        return 0;
@@@ -2823,7 -2813,6 +2813,6 @@@ static int nested_vmx_check_host_state(
            CC(vmcs12->host_ss_selector == 0 && !ia32e))
                return -EINVAL;
  
- #ifdef CONFIG_X86_64
        if (CC(is_noncanonical_address(vmcs12->host_fs_base, vcpu)) ||
            CC(is_noncanonical_address(vmcs12->host_gs_base, vcpu)) ||
            CC(is_noncanonical_address(vmcs12->host_gdtr_base, vcpu)) ||
            CC(is_noncanonical_address(vmcs12->host_tr_base, vcpu)) ||
            CC(is_noncanonical_address(vmcs12->host_rip, vcpu)))
                return -EINVAL;
- #endif
  
        /*
         * If the load IA32_EFER VM-exit control is 1, bits reserved in the
@@@ -2899,6 -2887,10 +2887,10 @@@ static int nested_vmx_check_guest_state
            CC(!nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4)))
                return -EINVAL;
  
+       if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) &&
+           CC(!kvm_dr7_valid(vmcs12->guest_dr7)))
+               return -EINVAL;
        if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) &&
            CC(!kvm_pat_valid(vmcs12->guest_ia32_pat)))
                return -EINVAL;
@@@ -3048,9 -3040,6 +3040,6 @@@ static int nested_vmx_check_vmentry_hw(
        return 0;
  }
  
- static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
-                                                struct vmcs12 *vmcs12);
  static bool nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
  {
        struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
@@@ -3183,7 -3172,7 +3172,7 @@@ enum nvmx_vmentry_status nested_vmx_ent
        u32 exit_qual;
  
        evaluate_pending_interrupts = exec_controls_get(vmx) &
-               (CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_VIRTUAL_NMI_PENDING);
+               (CPU_BASED_INTR_WINDOW_EXITING | CPU_BASED_NMI_WINDOW_EXITING);
        if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
                evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
  
        }
  
        enter_guest_mode(vcpu);
-       if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
+       if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
                vcpu->arch.tsc_offset += vmcs12->tsc_offset;
  
        if (prepare_vmcs02(vcpu, vmcs12, &exit_qual))
         * 26.7 "VM-entry failures during or after loading guest state".
         */
  vmentry_fail_vmexit_guest_mode:
-       if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
+       if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
                vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
        leave_guest_mode(vcpu);
  
@@@ -3407,8 -3396,8 +3396,8 @@@ static int nested_vmx_run(struct kvm_vc
         */
        if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
            !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) &&
-           !(vmcs12->cpu_based_vm_exec_control & CPU_BASED_VIRTUAL_NMI_PENDING) &&
-           !((vmcs12->cpu_based_vm_exec_control & CPU_BASED_VIRTUAL_INTR_PENDING) &&
+           !(vmcs12->cpu_based_vm_exec_control & CPU_BASED_NMI_WINDOW_EXITING) &&
+           !((vmcs12->cpu_based_vm_exec_control & CPU_BASED_INTR_WINDOW_EXITING) &&
              (vmcs12->guest_rflags & X86_EFLAGS_IF))) {
                vmx->nested.nested_run_pending = 0;
                return kvm_vcpu_halt(vcpu);
@@@ -3427,7 -3416,7 +3416,7 @@@ vmentry_failed
  
  /*
   * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
-  * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
+  * because L2 may have changed some cr0 bits directly (CR0_GUEST_HOST_MASK).
   * This function returns the new value we should put in vmcs12.guest_cr0.
   * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
   *  1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
@@@ -3999,8 -3988,8 +3988,8 @@@ static void load_vmcs12_host_state(stru
                vcpu->arch.pat = vmcs12->host_ia32_pat;
        }
        if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
-               SET_MSR_OR_WARN(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
-                               vmcs12->host_ia32_perf_global_ctrl);
+               WARN_ON_ONCE(kvm_set_msr(vcpu, MSR_CORE_PERF_GLOBAL_CTRL,
+                                        vmcs12->host_ia32_perf_global_ctrl));
  
        /* Set L1 segment info according to Intel SDM
            27.5.2 Loading Host Segment and Descriptor-Table Registers */
@@@ -4209,7 -4198,7 +4198,7 @@@ void nested_vmx_vmexit(struct kvm_vcpu 
        if (nested_cpu_has_preemption_timer(vmcs12))
                hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
  
-       if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
+       if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING)
                vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
  
        if (likely(!vmx->fail)) {
@@@ -4588,8 -4577,8 +4577,8 @@@ static int handle_vmon(struct kvm_vcpu 
        gpa_t vmptr;
        uint32_t revision;
        struct vcpu_vmx *vmx = to_vmx(vcpu);
 -      const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
 -              | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
 +      const u64 VMXON_NEEDED_FEATURES = FEAT_CTL_LOCKED
 +              | FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
  
        /*
         * The Intel VMX Instruction Reference lists a bunch of bits that are
@@@ -4751,36 -4740,32 +4740,32 @@@ static int handle_vmresume(struct kvm_v
  
  static int handle_vmread(struct kvm_vcpu *vcpu)
  {
-       unsigned long field;
-       u64 field_value;
+       struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
+                                                   : get_vmcs12(vcpu);
        unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
-       u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
-       int len;
-       gva_t gva = 0;
-       struct vmcs12 *vmcs12;
+       u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
+       struct vcpu_vmx *vmx = to_vmx(vcpu);
        struct x86_exception e;
+       unsigned long field;
+       u64 value;
+       gva_t gva = 0;
        short offset;
+       int len;
  
        if (!nested_vmx_check_permission(vcpu))
                return 1;
  
-       if (to_vmx(vcpu)->nested.current_vmptr == -1ull)
+       /*
+        * In VMX non-root operation, when the VMCS-link pointer is -1ull,
+        * any VMREAD sets the ALU flags for VMfailInvalid.
+        */
+       if (vmx->nested.current_vmptr == -1ull ||
+           (is_guest_mode(vcpu) &&
+            get_vmcs12(vcpu)->vmcs_link_pointer == -1ull))
                return nested_vmx_failInvalid(vcpu);
  
-       if (!is_guest_mode(vcpu))
-               vmcs12 = get_vmcs12(vcpu);
-       else {
-               /*
-                * When vmcs->vmcs_link_pointer is -1ull, any VMREAD
-                * to shadowed-field sets the ALU flags for VMfailInvalid.
-                */
-               if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull)
-                       return nested_vmx_failInvalid(vcpu);
-               vmcs12 = get_shadow_vmcs12(vcpu);
-       }
        /* Decode instruction info and find the field to read */
-       field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
+       field = kvm_register_readl(vcpu, (((instr_info) >> 28) & 0xf));
  
        offset = vmcs_field_to_offset(field);
        if (offset < 0)
        if (!is_guest_mode(vcpu) && is_vmcs12_ext_field(field))
                copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
  
-       /* Read the field, zero-extended to a u64 field_value */
-       field_value = vmcs12_read_any(vmcs12, field, offset);
+       /* Read the field, zero-extended to a u64 value */
+       value = vmcs12_read_any(vmcs12, field, offset);
  
        /*
         * Now copy part of this value to register or memory, as requested.
         * Note that the number of bits actually copied is 32 or 64 depending
         * on the guest's mode (32 or 64 bit), not on the given field's length.
         */
-       if (vmx_instruction_info & (1u << 10)) {
-               kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
-                       field_value);
+       if (instr_info & BIT(10)) {
+               kvm_register_writel(vcpu, (((instr_info) >> 3) & 0xf), value);
        } else {
                len = is_64_bit_mode(vcpu) ? 8 : 4;
                if (get_vmx_mem_address(vcpu, exit_qualification,
-                               vmx_instruction_info, true, len, &gva))
+                                       instr_info, true, len, &gva))
                        return 1;
                /* _system ok, nested_vmx_check_permission has verified cpl=0 */
-               if (kvm_write_guest_virt_system(vcpu, gva, &field_value, len, &e))
+               if (kvm_write_guest_virt_system(vcpu, gva, &value, len, &e)) {
                        kvm_inject_page_fault(vcpu, &e);
+                       return 1;
+               }
        }
  
        return nested_vmx_succeed(vcpu);
@@@ -4840,46 -4826,58 +4826,58 @@@ static bool is_shadow_field_ro(unsigne
  
  static int handle_vmwrite(struct kvm_vcpu *vcpu)
  {
+       struct vmcs12 *vmcs12 = is_guest_mode(vcpu) ? get_shadow_vmcs12(vcpu)
+                                                   : get_vmcs12(vcpu);
+       unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
+       u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
+       struct vcpu_vmx *vmx = to_vmx(vcpu);
+       struct x86_exception e;
        unsigned long field;
-       int len;
+       short offset;
        gva_t gva;
-       struct vcpu_vmx *vmx = to_vmx(vcpu);
-       unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
-       u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
+       int len;
  
-       /* The value to write might be 32 or 64 bits, depending on L1's long
+       /*
+        * The value to write might be 32 or 64 bits, depending on L1's long
         * mode, and eventually we need to write that into a field of several
         * possible lengths. The code below first zero-extends the value to 64
-        * bit (field_value), and then copies only the appropriate number of
+        * bit (value), and then copies only the appropriate number of
         * bits into the vmcs12 field.
         */
-       u64 field_value = 0;
-       struct x86_exception e;
-       struct vmcs12 *vmcs12;
-       short offset;
+       u64 value = 0;
  
        if (!nested_vmx_check_permission(vcpu))
                return 1;
  
-       if (vmx->nested.current_vmptr == -1ull)
+       /*
+        * In VMX non-root operation, when the VMCS-link pointer is -1ull,
+        * any VMWRITE sets the ALU flags for VMfailInvalid.
+        */
+       if (vmx->nested.current_vmptr == -1ull ||
+           (is_guest_mode(vcpu) &&
+            get_vmcs12(vcpu)->vmcs_link_pointer == -1ull))
                return nested_vmx_failInvalid(vcpu);
  
-       if (vmx_instruction_info & (1u << 10))
-               field_value = kvm_register_readl(vcpu,
-                       (((vmx_instruction_info) >> 3) & 0xf));
+       if (instr_info & BIT(10))
+               value = kvm_register_readl(vcpu, (((instr_info) >> 3) & 0xf));
        else {
                len = is_64_bit_mode(vcpu) ? 8 : 4;
                if (get_vmx_mem_address(vcpu, exit_qualification,
-                               vmx_instruction_info, false, len, &gva))
+                                       instr_info, false, len, &gva))
                        return 1;
-               if (kvm_read_guest_virt(vcpu, gva, &field_value, len, &e)) {
+               if (kvm_read_guest_virt(vcpu, gva, &value, len, &e)) {
                        kvm_inject_page_fault(vcpu, &e);
                        return 1;
                }
        }
  
+       field = kvm_register_readl(vcpu, (((instr_info) >> 28) & 0xf));
+       offset = vmcs_field_to_offset(field);
+       if (offset < 0)
+               return nested_vmx_failValid(vcpu,
+                       VMXERR_UNSUPPORTED_VMCS_COMPONENT);
  
-       field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
        /*
         * If the vCPU supports "VMWRITE to any supported field in the
         * VMCS," then the "read-only" fields are actually read/write.
                return nested_vmx_failValid(vcpu,
                        VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
  
-       if (!is_guest_mode(vcpu)) {
-               vmcs12 = get_vmcs12(vcpu);
-               /*
-                * Ensure vmcs12 is up-to-date before any VMWRITE that dirties
-                * vmcs12, else we may crush a field or consume a stale value.
-                */
-               if (!is_shadow_field_rw(field))
-                       copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
-       } else {
-               /*
-                * When vmcs->vmcs_link_pointer is -1ull, any VMWRITE
-                * to shadowed-field sets the ALU flags for VMfailInvalid.
-                */
-               if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull)
-                       return nested_vmx_failInvalid(vcpu);
-               vmcs12 = get_shadow_vmcs12(vcpu);
-       }
-       offset = vmcs_field_to_offset(field);
-       if (offset < 0)
-               return nested_vmx_failValid(vcpu,
-                       VMXERR_UNSUPPORTED_VMCS_COMPONENT);
+       /*
+        * Ensure vmcs12 is up-to-date before any VMWRITE that dirties
+        * vmcs12, else we may crush a field or consume a stale value.
+        */
+       if (!is_guest_mode(vcpu) && !is_shadow_field_rw(field))
+               copy_vmcs02_to_vmcs12_rare(vcpu, vmcs12);
  
        /*
         * Some Intel CPUs intentionally drop the reserved bits of the AR byte
         * the stripped down value, L2 sees the full value as stored by KVM).
         */
        if (field >= GUEST_ES_AR_BYTES && field <= GUEST_TR_AR_BYTES)
-               field_value &= 0x1f0ff;
+               value &= 0x1f0ff;
  
-       vmcs12_write_any(vmcs12, field, offset, field_value);
+       vmcs12_write_any(vmcs12, field, offset, value);
  
        /*
         * Do not track vmcs12 dirty-state if in guest-mode as we actually
                        preempt_disable();
                        vmcs_load(vmx->vmcs01.shadow_vmcs);
  
-                       __vmcs_writel(field, field_value);
+                       __vmcs_writel(field, value);
  
                        vmcs_clear(vmx->vmcs01.shadow_vmcs);
                        vmcs_load(vmx->loaded_vmcs->vmcs);
@@@ -5524,10 -5505,10 +5505,10 @@@ bool nested_vmx_exit_reflected(struct k
                return false;
        case EXIT_REASON_TRIPLE_FAULT:
                return true;
-       case EXIT_REASON_PENDING_INTERRUPT:
-               return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
+       case EXIT_REASON_INTERRUPT_WINDOW:
+               return nested_cpu_has(vmcs12, CPU_BASED_INTR_WINDOW_EXITING);
        case EXIT_REASON_NMI_WINDOW:
-               return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
+               return nested_cpu_has(vmcs12, CPU_BASED_NMI_WINDOW_EXITING);
        case EXIT_REASON_TASK_SWITCH:
                return true;
        case EXIT_REASON_CPUID:
@@@ -6015,8 -5996,8 +5996,8 @@@ void nested_vmx_setup_ctls_msrs(struct 
        msrs->procbased_ctls_low =
                CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
        msrs->procbased_ctls_high &=
-               CPU_BASED_VIRTUAL_INTR_PENDING |
-               CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
+               CPU_BASED_INTR_WINDOW_EXITING |
+               CPU_BASED_NMI_WINDOW_EXITING | CPU_BASED_USE_TSC_OFFSETTING |
                CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
                CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
                CPU_BASED_CR3_STORE_EXITING |
diff --combined arch/x86/kvm/vmx/vmx.c
@@@ -1057,6 -1057,12 +1057,12 @@@ static unsigned long segment_base(u16 s
  }
  #endif
  
+ static inline bool pt_can_write_msr(struct vcpu_vmx *vmx)
+ {
+       return (pt_mode == PT_MODE_HOST_GUEST) &&
+              !(vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN);
+ }
  static inline void pt_load_msr(struct pt_ctx *ctx, u32 addr_range)
  {
        u32 i;
@@@ -1716,7 -1722,7 +1722,7 @@@ static u64 vmx_read_l1_tsc_offset(struc
        struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
  
        if (is_guest_mode(vcpu) &&
-           (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
+           (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
                return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
  
        return vcpu->arch.tsc_offset;
@@@ -1734,7 -1740,7 +1740,7 @@@ static u64 vmx_write_l1_tsc_offset(stru
         * to the newly set TSC to get L2's TSC.
         */
        if (is_guest_mode(vcpu) &&
-           (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
+           (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETTING))
                g_tsc_offset = vmcs12->tsc_offset;
  
        trace_kvm_write_tsc_offset(vcpu->vcpu_id,
@@@ -1773,8 -1779,6 +1779,6 @@@ static int vmx_get_msr_feature(struct k
        default:
                return 1;
        }
-       return 0;
  }
  
  /*
@@@ -1839,11 -1843,11 +1843,11 @@@ static int vmx_get_msr(struct kvm_vcpu 
        case MSR_IA32_MCG_EXT_CTL:
                if (!msr_info->host_initiated &&
                    !(vmx->msr_ia32_feature_control &
 -                    FEATURE_CONTROL_LMCE))
 +                    FEAT_CTL_LMCE_ENABLED))
                        return 1;
                msr_info->data = vcpu->arch.mcg_ext_ctl;
                break;
 -      case MSR_IA32_FEATURE_CONTROL:
 +      case MSR_IA32_FEAT_CTL:
                msr_info->data = vmx->msr_ia32_feature_control;
                break;
        case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
  }
  
  /*
-  * Writes msr value into into the appropriate "register".
+  * Writes msr value into the appropriate "register".
   * Returns 0 on success, non-0 otherwise.
   * Assumes vcpu_load() was already called.
   */
@@@ -1994,12 -1998,10 +1998,10 @@@ static int vmx_set_msr(struct kvm_vcpu 
                    !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
                        return 1;
  
-               /* The STIBP bit doesn't fault even if it's not advertised */
-               if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
+               if (data & ~kvm_spec_ctrl_valid_bits(vcpu))
                        return 1;
  
                vmx->spec_ctrl = data;
                if (!data)
                        break;
  
                 *
                 * For nested:
                 * The handling of the MSR bitmap for L2 guests is done in
-                * nested_vmx_merge_msr_bitmap. We should not touch the
+                * nested_vmx_prepare_msr_bitmap. We should not touch the
                 * vmcs02.msr_bitmap here since it gets completely overwritten
                 * in the merging. We update the vmcs01 here for L1 as well
                 * since it will end up touching the MSR anyway now.
  
                if (data & ~PRED_CMD_IBPB)
                        return 1;
+               if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL))
+                       return 1;
                if (!data)
                        break;
  
                 *
                 * For nested:
                 * The handling of the MSR bitmap for L2 guests is done in
-                * nested_vmx_merge_msr_bitmap. We should not touch the
+                * nested_vmx_prepare_msr_bitmap. We should not touch the
                 * vmcs02.msr_bitmap here since it gets completely overwritten
                 * in the merging.
                 */
        case MSR_IA32_MCG_EXT_CTL:
                if ((!msr_info->host_initiated &&
                     !(to_vmx(vcpu)->msr_ia32_feature_control &
 -                     FEATURE_CONTROL_LMCE)) ||
 +                     FEAT_CTL_LMCE_ENABLED)) ||
                    (data & ~MCG_EXT_CTL_LMCE_EN))
                        return 1;
                vcpu->arch.mcg_ext_ctl = data;
                break;
 -      case MSR_IA32_FEATURE_CONTROL:
 +      case MSR_IA32_FEAT_CTL:
                if (!vmx_feature_control_msr_valid(vcpu, data) ||
                    (to_vmx(vcpu)->msr_ia32_feature_control &
 -                   FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
 +                   FEAT_CTL_LOCKED && !msr_info->host_initiated))
                        return 1;
                vmx->msr_ia32_feature_control = data;
                if (msr_info->host_initiated && data == 0)
                pt_update_intercept_for_msr(vmx);
                break;
        case MSR_IA32_RTIT_STATUS:
-               if ((pt_mode != PT_MODE_HOST_GUEST) ||
-                       (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
-                       (data & MSR_IA32_RTIT_STATUS_MASK))
+               if (!pt_can_write_msr(vmx))
+                       return 1;
+               if (data & MSR_IA32_RTIT_STATUS_MASK)
                        return 1;
                vmx->pt_desc.guest.status = data;
                break;
        case MSR_IA32_RTIT_CR3_MATCH:
-               if ((pt_mode != PT_MODE_HOST_GUEST) ||
-                       (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
-                       !intel_pt_validate_cap(vmx->pt_desc.caps,
-                                               PT_CAP_cr3_filtering))
+               if (!pt_can_write_msr(vmx))
+                       return 1;
+               if (!intel_pt_validate_cap(vmx->pt_desc.caps,
+                                          PT_CAP_cr3_filtering))
                        return 1;
                vmx->pt_desc.guest.cr3_match = data;
                break;
        case MSR_IA32_RTIT_OUTPUT_BASE:
-               if ((pt_mode != PT_MODE_HOST_GUEST) ||
-                       (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
-                       (!intel_pt_validate_cap(vmx->pt_desc.caps,
-                                       PT_CAP_topa_output) &&
-                        !intel_pt_validate_cap(vmx->pt_desc.caps,
-                                       PT_CAP_single_range_output)) ||
-                       (data & MSR_IA32_RTIT_OUTPUT_BASE_MASK))
+               if (!pt_can_write_msr(vmx))
+                       return 1;
+               if (!intel_pt_validate_cap(vmx->pt_desc.caps,
+                                          PT_CAP_topa_output) &&
+                   !intel_pt_validate_cap(vmx->pt_desc.caps,
+                                          PT_CAP_single_range_output))
+                       return 1;
+               if (data & MSR_IA32_RTIT_OUTPUT_BASE_MASK)
                        return 1;
                vmx->pt_desc.guest.output_base = data;
                break;
        case MSR_IA32_RTIT_OUTPUT_MASK:
-               if ((pt_mode != PT_MODE_HOST_GUEST) ||
-                       (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
-                       (!intel_pt_validate_cap(vmx->pt_desc.caps,
-                                       PT_CAP_topa_output) &&
-                        !intel_pt_validate_cap(vmx->pt_desc.caps,
-                                       PT_CAP_single_range_output)))
+               if (!pt_can_write_msr(vmx))
+                       return 1;
+               if (!intel_pt_validate_cap(vmx->pt_desc.caps,
+                                          PT_CAP_topa_output) &&
+                   !intel_pt_validate_cap(vmx->pt_desc.caps,
+                                          PT_CAP_single_range_output))
                        return 1;
                vmx->pt_desc.guest.output_mask = data;
                break;
        case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
+               if (!pt_can_write_msr(vmx))
+                       return 1;
                index = msr_info->index - MSR_IA32_RTIT_ADDR0_A;
-               if ((pt_mode != PT_MODE_HOST_GUEST) ||
-                       (vmx->pt_desc.guest.ctl & RTIT_CTL_TRACEEN) ||
-                       (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
-                                       PT_CAP_num_address_ranges)))
+               if (index >= 2 * intel_pt_validate_cap(vmx->pt_desc.caps,
+                                                      PT_CAP_num_address_ranges))
+                       return 1;
+               if (is_noncanonical_address(data, vcpu))
                        return 1;
                if (index % 2)
                        vmx->pt_desc.guest.addr_b[index / 2] = data;
@@@ -2204,8 -2210,29 +2210,8 @@@ static __init int cpu_has_kvm_support(v
  
  static __init int vmx_disabled_by_bios(void)
  {
 -      u64 msr;
 -
 -      rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
 -      if (msr & FEATURE_CONTROL_LOCKED) {
 -              /* launched w/ TXT and VMX disabled */
 -              if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
 -                      && tboot_enabled())
 -                      return 1;
 -              /* launched w/o TXT and VMX only enabled w/ TXT */
 -              if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
 -                      && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
 -                      && !tboot_enabled()) {
 -                      printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
 -                              "activate TXT before enabling KVM\n");
 -                      return 1;
 -              }
 -              /* launched w/o TXT and VMX disabled */
 -              if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
 -                      && !tboot_enabled())
 -                      return 1;
 -      }
 -
 -      return 0;
 +      return !boot_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
 +             !boot_cpu_has(X86_FEATURE_VMX);
  }
  
  static void kvm_cpu_vmxon(u64 addr)
@@@ -2220,6 -2247,7 +2226,6 @@@ static int hardware_enable(void
  {
        int cpu = raw_smp_processor_id();
        u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
 -      u64 old, test_bits;
  
        if (cr4_read_shadow() & X86_CR4_VMXE)
                return -EBUSY;
         */
        crash_enable_local_vmclear(cpu);
  
 -      rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
 -
 -      test_bits = FEATURE_CONTROL_LOCKED;
 -      test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
 -      if (tboot_enabled())
 -              test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
 -
 -      if ((old & test_bits) != test_bits) {
 -              /* enable and lock */
 -              wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
 -      }
        kvm_cpu_vmxon(phys_addr);
        if (enable_ept)
                ept_sync_global();
@@@ -2322,7 -2361,7 +2328,7 @@@ static __init int setup_vmcs_config(str
              CPU_BASED_CR3_STORE_EXITING |
              CPU_BASED_UNCOND_IO_EXITING |
              CPU_BASED_MOV_DR_EXITING |
-             CPU_BASED_USE_TSC_OFFSETING |
+             CPU_BASED_USE_TSC_OFFSETTING |
              CPU_BASED_MWAIT_EXITING |
              CPU_BASED_MONITOR_EXITING |
              CPU_BASED_INVLPG_EXITING |
@@@ -2657,8 -2696,6 +2663,6 @@@ static void enter_pmode(struct kvm_vcp
  
        vmx->rmode.vm86_active = 0;
  
-       vmx_segment_cache_clear(vmx);
        vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
  
        flags = vmcs_readl(GUEST_RFLAGS);
@@@ -3444,7 -3481,7 +3448,7 @@@ out
  static int init_rmode_identity_map(struct kvm *kvm)
  {
        struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
-       int i, idx, r = 0;
+       int i, r = 0;
        kvm_pfn_t identity_map_pfn;
        u32 tmp;
  
        mutex_lock(&kvm->slots_lock);
  
        if (likely(kvm_vmx->ept_identity_pagetable_done))
-               goto out2;
+               goto out;
  
        if (!kvm_vmx->ept_identity_map_addr)
                kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
        r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
                                    kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
        if (r < 0)
-               goto out2;
+               goto out;
  
-       idx = srcu_read_lock(&kvm->srcu);
        r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
        if (r < 0)
                goto out;
        kvm_vmx->ept_identity_pagetable_done = true;
  
  out:
-       srcu_read_unlock(&kvm->srcu, idx);
- out2:
        mutex_unlock(&kvm->slots_lock);
        return r;
  }
@@@ -4009,6 -4042,7 +4009,7 @@@ static void vmx_compute_secondary_exec_
        if (vmx_xsaves_supported()) {
                /* Exposing XSAVES only when XSAVE is exposed */
                bool xsaves_enabled =
+                       boot_cpu_has(X86_FEATURE_XSAVE) &&
                        guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
                        guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
  
@@@ -4319,7 -4353,7 +4320,7 @@@ static void vmx_vcpu_reset(struct kvm_v
  
  static void enable_irq_window(struct kvm_vcpu *vcpu)
  {
-       exec_controls_setbit(to_vmx(vcpu), CPU_BASED_VIRTUAL_INTR_PENDING);
+       exec_controls_setbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
  }
  
  static void enable_nmi_window(struct kvm_vcpu *vcpu)
                return;
        }
  
-       exec_controls_setbit(to_vmx(vcpu), CPU_BASED_VIRTUAL_NMI_PENDING);
+       exec_controls_setbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
  }
  
  static void vmx_inject_irq(struct kvm_vcpu *vcpu)
@@@ -4455,8 -4489,11 +4456,11 @@@ static int vmx_set_tss_addr(struct kvm 
        if (enable_unrestricted_guest)
                return 0;
  
-       ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
-                                   PAGE_SIZE * 3);
+       mutex_lock(&kvm->slots_lock);
+       ret = __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
+                                     PAGE_SIZE * 3);
+       mutex_unlock(&kvm->slots_lock);
        if (ret)
                return ret;
        to_kvm_vmx(kvm)->tss_addr = addr;
@@@ -4938,7 -4975,7 +4942,7 @@@ static int handle_tpr_below_threshold(s
  
  static int handle_interrupt_window(struct kvm_vcpu *vcpu)
  {
-       exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_VIRTUAL_INTR_PENDING);
+       exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_INTR_WINDOW_EXITING);
  
        kvm_make_request(KVM_REQ_EVENT, vcpu);
  
@@@ -5151,7 -5188,7 +5155,7 @@@ static int handle_ept_misconfig(struct 
  static int handle_nmi_window(struct kvm_vcpu *vcpu)
  {
        WARN_ON_ONCE(!enable_vnmi);
-       exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_VIRTUAL_NMI_PENDING);
+       exec_controls_clearbit(to_vmx(vcpu), CPU_BASED_NMI_WINDOW_EXITING);
        ++vcpu->stat.nmi_window_exits;
        kvm_make_request(KVM_REQ_EVENT, vcpu);
  
@@@ -5172,7 -5209,7 +5176,7 @@@ static int handle_invalid_guest_state(s
        WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
  
        intr_window_requested = exec_controls_get(vmx) &
-                               CPU_BASED_VIRTUAL_INTR_PENDING;
+                               CPU_BASED_INTR_WINDOW_EXITING;
  
        while (vmx->emulation_required && count-- != 0) {
                if (intr_window_requested && vmx_interrupt_allowed(vcpu))
@@@ -5496,7 -5533,7 +5500,7 @@@ static int (*kvm_vmx_exit_handlers[])(s
        [EXIT_REASON_CPUID]                   = kvm_emulate_cpuid,
        [EXIT_REASON_MSR_READ]                = kvm_emulate_rdmsr,
        [EXIT_REASON_MSR_WRITE]               = kvm_emulate_wrmsr,
-       [EXIT_REASON_PENDING_INTERRUPT]       = handle_interrupt_window,
+       [EXIT_REASON_INTERRUPT_WINDOW]        = handle_interrupt_window,
        [EXIT_REASON_HLT]                     = kvm_emulate_halt,
        [EXIT_REASON_INVD]                    = handle_invd,
        [EXIT_REASON_INVLPG]                  = handle_invlpg,
@@@ -5783,7 -5820,8 +5787,8 @@@ void dump_vmcs(void
   * The guest has exited.  See if we can fix it or if we need userspace
   * assistance.
   */
- static int vmx_handle_exit(struct kvm_vcpu *vcpu)
+ static int vmx_handle_exit(struct kvm_vcpu *vcpu,
+       enum exit_fastpath_completion exit_fastpath)
  {
        struct vcpu_vmx *vmx = to_vmx(vcpu);
        u32 exit_reason = vmx->exit_reason;
                }
        }
  
-       if (exit_reason < kvm_vmx_max_exit_handlers
-           && kvm_vmx_exit_handlers[exit_reason]) {
+       if (exit_fastpath == EXIT_FASTPATH_SKIP_EMUL_INS) {
+               kvm_skip_emulated_instruction(vcpu);
+               return 1;
+       }
+       if (exit_reason >= kvm_vmx_max_exit_handlers)
+               goto unexpected_vmexit;
  #ifdef CONFIG_RETPOLINE
-               if (exit_reason == EXIT_REASON_MSR_WRITE)
-                       return kvm_emulate_wrmsr(vcpu);
-               else if (exit_reason == EXIT_REASON_PREEMPTION_TIMER)
-                       return handle_preemption_timer(vcpu);
-               else if (exit_reason == EXIT_REASON_PENDING_INTERRUPT)
-                       return handle_interrupt_window(vcpu);
-               else if (exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
-                       return handle_external_interrupt(vcpu);
-               else if (exit_reason == EXIT_REASON_HLT)
-                       return kvm_emulate_halt(vcpu);
-               else if (exit_reason == EXIT_REASON_EPT_MISCONFIG)
-                       return handle_ept_misconfig(vcpu);
+       if (exit_reason == EXIT_REASON_MSR_WRITE)
+               return kvm_emulate_wrmsr(vcpu);
+       else if (exit_reason == EXIT_REASON_PREEMPTION_TIMER)
+               return handle_preemption_timer(vcpu);
+       else if (exit_reason == EXIT_REASON_INTERRUPT_WINDOW)
+               return handle_interrupt_window(vcpu);
+       else if (exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
+               return handle_external_interrupt(vcpu);
+       else if (exit_reason == EXIT_REASON_HLT)
+               return kvm_emulate_halt(vcpu);
+       else if (exit_reason == EXIT_REASON_EPT_MISCONFIG)
+               return handle_ept_misconfig(vcpu);
  #endif
-               return kvm_vmx_exit_handlers[exit_reason](vcpu);
-       } else {
-               vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
-                               exit_reason);
-               dump_vmcs();
-               vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
-               vcpu->run->internal.suberror =
+       exit_reason = array_index_nospec(exit_reason,
+                                        kvm_vmx_max_exit_handlers);
+       if (!kvm_vmx_exit_handlers[exit_reason])
+               goto unexpected_vmexit;
+       return kvm_vmx_exit_handlers[exit_reason](vcpu);
+ unexpected_vmexit:
+       vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n", exit_reason);
+       dump_vmcs();
+       vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
+       vcpu->run->internal.suberror =
                        KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
-               vcpu->run->internal.ndata = 1;
-               vcpu->run->internal.data[0] = exit_reason;
-               return 0;
-       }
+       vcpu->run->internal.ndata = 1;
+       vcpu->run->internal.data[0] = exit_reason;
+       return 0;
  }
  
  /*
@@@ -6217,7 -6265,8 +6232,8 @@@ static void handle_external_interrupt_i
  }
  STACK_FRAME_NON_STANDARD(handle_external_interrupt_irqoff);
  
- static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu)
+ static void vmx_handle_exit_irqoff(struct kvm_vcpu *vcpu,
+       enum exit_fastpath_completion *exit_fastpath)
  {
        struct vcpu_vmx *vmx = to_vmx(vcpu);
  
                handle_external_interrupt_irqoff(vcpu);
        else if (vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI)
                handle_exception_nmi_irqoff(vmx);
+       else if (!is_guest_mode(vcpu) &&
+               vmx->exit_reason == EXIT_REASON_MSR_WRITE)
+               *exit_fastpath = handle_fastpath_set_msr_irqoff(vcpu);
  }
  
  static bool vmx_has_emulated_msr(int index)
@@@ -6633,60 -6685,31 +6652,31 @@@ static void vmx_free_vcpu(struct kvm_vc
        free_vpid(vmx->vpid);
        nested_vmx_free_vcpu(vcpu);
        free_loaded_vmcs(vmx->loaded_vmcs);
-       kvm_vcpu_uninit(vcpu);
-       kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.user_fpu);
-       kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
-       kmem_cache_free(kvm_vcpu_cache, vmx);
  }
  
- static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
+ static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
  {
-       int err;
        struct vcpu_vmx *vmx;
        unsigned long *msr_bitmap;
-       int i, cpu;
-       BUILD_BUG_ON_MSG(offsetof(struct vcpu_vmx, vcpu) != 0,
-               "struct kvm_vcpu must be at offset 0 for arch usercopy region");
-       vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
-       if (!vmx)
-               return ERR_PTR(-ENOMEM);
+       int i, cpu, err;
  
-       vmx->vcpu.arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
-                       GFP_KERNEL_ACCOUNT);
-       if (!vmx->vcpu.arch.user_fpu) {
-               printk(KERN_ERR "kvm: failed to allocate kvm userspace's fpu\n");
-               err = -ENOMEM;
-               goto free_partial_vcpu;
-       }
+       BUILD_BUG_ON(offsetof(struct vcpu_vmx, vcpu) != 0);
+       vmx = to_vmx(vcpu);
  
-       vmx->vcpu.arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
-                       GFP_KERNEL_ACCOUNT);
-       if (!vmx->vcpu.arch.guest_fpu) {
-               printk(KERN_ERR "kvm: failed to allocate vcpu's fpu\n");
-               err = -ENOMEM;
-               goto free_user_fpu;
-       }
+       err = -ENOMEM;
  
        vmx->vpid = allocate_vpid();
  
-       err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
-       if (err)
-               goto free_vcpu;
-       err = -ENOMEM;
        /*
         * If PML is turned on, failure on enabling PML just results in failure
         * of creating the vcpu, therefore we can simplify PML logic (by
         * avoiding dealing with cases, such as enabling PML partially on vcpus
-        * for the guest, etc.
+        * for the guest), etc.
         */
        if (enable_pml) {
                vmx->pml_pg = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
                if (!vmx->pml_pg)
-                       goto uninit_vcpu;
+                       goto free_vpid;
        }
  
        BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) != NR_SHARED_MSRS);
        vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
        vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
        vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
-       if (kvm_cstate_in_guest(kvm)) {
+       if (kvm_cstate_in_guest(vcpu->kvm)) {
                vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C1_RES, MSR_TYPE_R);
                vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C3_RESIDENCY, MSR_TYPE_R);
                vmx_disable_intercept_for_msr(msr_bitmap, MSR_CORE_C6_RESIDENCY, MSR_TYPE_R);
  
        vmx->loaded_vmcs = &vmx->vmcs01;
        cpu = get_cpu();
-       vmx_vcpu_load(&vmx->vcpu, cpu);
-       vmx->vcpu.cpu = cpu;
+       vmx_vcpu_load(vcpu, cpu);
+       vcpu->cpu = cpu;
        init_vmcs(vmx);
-       vmx_vcpu_put(&vmx->vcpu);
+       vmx_vcpu_put(vcpu);
        put_cpu();
-       if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
-               err = alloc_apic_access_page(kvm);
+       if (cpu_need_virtualize_apic_accesses(vcpu)) {
+               err = alloc_apic_access_page(vcpu->kvm);
                if (err)
                        goto free_vmcs;
        }
  
        if (enable_ept && !enable_unrestricted_guest) {
-               err = init_rmode_identity_map(kvm);
+               err = init_rmode_identity_map(vcpu->kvm);
                if (err)
                        goto free_vmcs;
        }
        if (nested)
                nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
                                           vmx_capability.ept,
-                                          kvm_vcpu_apicv_active(&vmx->vcpu));
+                                          kvm_vcpu_apicv_active(vcpu));
        else
                memset(&vmx->nested.msrs, 0, sizeof(vmx->nested.msrs));
  
        vmx->nested.posted_intr_nv = -1;
        vmx->nested.current_vmptr = -1ull;
  
 -      vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
 +      vmx->msr_ia32_feature_control_valid_bits = FEAT_CTL_LOCKED;
  
        /*
         * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
  
        vmx->ept_pointer = INVALID_PAGE;
  
-       return &vmx->vcpu;
+       return 0;
  
  free_vmcs:
        free_loaded_vmcs(vmx->loaded_vmcs);
  free_pml:
        vmx_destroy_pml_buffer(vmx);
- uninit_vcpu:
-       kvm_vcpu_uninit(&vmx->vcpu);
- free_vcpu:
+ free_vpid:
        free_vpid(vmx->vpid);
-       kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.guest_fpu);
- free_user_fpu:
-       kmem_cache_free(x86_fpu_cache, vmx->vcpu.arch.user_fpu);
- free_partial_vcpu:
-       kmem_cache_free(kvm_vcpu_cache, vmx);
-       return ERR_PTR(err);
+       return err;
  }
  
  #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/l1tf.html for details.\n"
@@@ -6838,12 -6854,6 +6821,12 @@@ static int __init vmx_check_processor_c
        struct vmcs_config vmcs_conf;
        struct vmx_capability vmx_cap;
  
 +      if (!this_cpu_has(X86_FEATURE_MSR_IA32_FEAT_CTL) ||
 +          !this_cpu_has(X86_FEATURE_VMX)) {
 +              pr_err("kvm: VMX is disabled on CPU %d\n", smp_processor_id());
 +              return -EIO;
 +      }
 +
        if (setup_vmcs_config(&vmcs_conf, &vmx_cap) < 0)
                return -EIO;
        if (nested)
@@@ -6946,28 -6956,28 +6929,28 @@@ static void nested_vmx_cr_fixed1_bits_u
  } while (0)
  
        entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
-       cr4_fixed1_update(X86_CR4_VME,        edx, bit(X86_FEATURE_VME));
-       cr4_fixed1_update(X86_CR4_PVI,        edx, bit(X86_FEATURE_VME));
-       cr4_fixed1_update(X86_CR4_TSD,        edx, bit(X86_FEATURE_TSC));
-       cr4_fixed1_update(X86_CR4_DE,         edx, bit(X86_FEATURE_DE));
-       cr4_fixed1_update(X86_CR4_PSE,        edx, bit(X86_FEATURE_PSE));
-       cr4_fixed1_update(X86_CR4_PAE,        edx, bit(X86_FEATURE_PAE));
-       cr4_fixed1_update(X86_CR4_MCE,        edx, bit(X86_FEATURE_MCE));
-       cr4_fixed1_update(X86_CR4_PGE,        edx, bit(X86_FEATURE_PGE));
-       cr4_fixed1_update(X86_CR4_OSFXSR,     edx, bit(X86_FEATURE_FXSR));
-       cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
-       cr4_fixed1_update(X86_CR4_VMXE,       ecx, bit(X86_FEATURE_VMX));
-       cr4_fixed1_update(X86_CR4_SMXE,       ecx, bit(X86_FEATURE_SMX));
-       cr4_fixed1_update(X86_CR4_PCIDE,      ecx, bit(X86_FEATURE_PCID));
-       cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, bit(X86_FEATURE_XSAVE));
+       cr4_fixed1_update(X86_CR4_VME,        edx, feature_bit(VME));
+       cr4_fixed1_update(X86_CR4_PVI,        edx, feature_bit(VME));
+       cr4_fixed1_update(X86_CR4_TSD,        edx, feature_bit(TSC));
+       cr4_fixed1_update(X86_CR4_DE,         edx, feature_bit(DE));
+       cr4_fixed1_update(X86_CR4_PSE,        edx, feature_bit(PSE));
+       cr4_fixed1_update(X86_CR4_PAE,        edx, feature_bit(PAE));
+       cr4_fixed1_update(X86_CR4_MCE,        edx, feature_bit(MCE));
+       cr4_fixed1_update(X86_CR4_PGE,        edx, feature_bit(PGE));
+       cr4_fixed1_update(X86_CR4_OSFXSR,     edx, feature_bit(FXSR));
+       cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, feature_bit(XMM));
+       cr4_fixed1_update(X86_CR4_VMXE,       ecx, feature_bit(VMX));
+       cr4_fixed1_update(X86_CR4_SMXE,       ecx, feature_bit(SMX));
+       cr4_fixed1_update(X86_CR4_PCIDE,      ecx, feature_bit(PCID));
+       cr4_fixed1_update(X86_CR4_OSXSAVE,    ecx, feature_bit(XSAVE));
  
        entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
-       cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, bit(X86_FEATURE_FSGSBASE));
-       cr4_fixed1_update(X86_CR4_SMEP,       ebx, bit(X86_FEATURE_SMEP));
-       cr4_fixed1_update(X86_CR4_SMAP,       ebx, bit(X86_FEATURE_SMAP));
-       cr4_fixed1_update(X86_CR4_PKE,        ecx, bit(X86_FEATURE_PKU));
-       cr4_fixed1_update(X86_CR4_UMIP,       ecx, bit(X86_FEATURE_UMIP));
-       cr4_fixed1_update(X86_CR4_LA57,       ecx, bit(X86_FEATURE_LA57));
+       cr4_fixed1_update(X86_CR4_FSGSBASE,   ebx, feature_bit(FSGSBASE));
+       cr4_fixed1_update(X86_CR4_SMEP,       ebx, feature_bit(SMEP));
+       cr4_fixed1_update(X86_CR4_SMAP,       ebx, feature_bit(SMAP));
+       cr4_fixed1_update(X86_CR4_PKE,        ecx, feature_bit(PKU));
+       cr4_fixed1_update(X86_CR4_UMIP,       ecx, feature_bit(UMIP));
+       cr4_fixed1_update(X86_CR4_LA57,       ecx, feature_bit(LA57));
  
  #undef cr4_fixed1_update
  }
@@@ -7072,12 -7082,12 +7055,12 @@@ static void vmx_cpuid_update(struct kvm
  
        if (nested_vmx_allowed(vcpu))
                to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
 -                      FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX |
 -                      FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
 +                      FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
 +                      FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX;
        else
                to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
 -                      ~(FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX |
 -                        FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX);
 +                      ~(FEAT_CTL_VMX_ENABLED_INSIDE_SMX |
 +                        FEAT_CTL_VMX_ENABLED_OUTSIDE_SMX);
  
        if (nested_vmx_allowed(vcpu)) {
                nested_vmx_cr_fixed1_bits_update(vcpu);
  static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
  {
        if (func == 1 && nested)
-               entry->ecx |= bit(X86_FEATURE_VMX);
+               entry->ecx |= feature_bit(VMX);
  }
  
  static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
@@@ -7496,10 -7506,10 +7479,10 @@@ static void vmx_setup_mce(struct kvm_vc
  {
        if (vcpu->arch.mcg_cap & MCG_LMCE_P)
                to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
 -                      FEATURE_CONTROL_LMCE;
 +                      FEAT_CTL_LMCE_ENABLED;
        else
                to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
 -                      ~FEATURE_CONTROL_LMCE;
 +                      ~FEAT_CTL_LMCE_ENABLED;
  }
  
  static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
@@@ -7843,6 -7853,7 +7826,7 @@@ static struct kvm_x86_ops vmx_x86_ops _
        .xsaves_supported = vmx_xsaves_supported,
        .umip_emulated = vmx_umip_emulated,
        .pt_supported = vmx_pt_supported,
+       .pku_supported = vmx_pku_supported,
  
        .request_immediate_exit = vmx_request_immediate_exit,
  
diff --combined arch/x86/kvm/x86.c
@@@ -93,6 -93,8 +93,8 @@@ u64 __read_mostly efer_reserved_bits = 
  static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
  #endif
  
+ static u64 __read_mostly cr4_reserved_bits = CR4_RESERVED_BITS;
  #define VM_STAT(x, ...) offsetof(struct kvm, stat.x), KVM_STAT_VM, ## __VA_ARGS__
  #define VCPU_STAT(x, ...) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU, ## __VA_ARGS__
  
@@@ -879,30 -881,44 +881,44 @@@ int kvm_set_xcr(struct kvm_vcpu *vcpu, 
  }
  EXPORT_SYMBOL_GPL(kvm_set_xcr);
  
- static int kvm_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
- {
-       if (cr4 & CR4_RESERVED_BITS)
-               return -EINVAL;
+ #define __cr4_reserved_bits(__cpu_has, __c)           \
+ ({                                                    \
+       u64 __reserved_bits = CR4_RESERVED_BITS;        \
+                                                       \
+       if (!__cpu_has(__c, X86_FEATURE_XSAVE))         \
+               __reserved_bits |= X86_CR4_OSXSAVE;     \
+       if (!__cpu_has(__c, X86_FEATURE_SMEP))          \
+               __reserved_bits |= X86_CR4_SMEP;        \
+       if (!__cpu_has(__c, X86_FEATURE_SMAP))          \
+               __reserved_bits |= X86_CR4_SMAP;        \
+       if (!__cpu_has(__c, X86_FEATURE_FSGSBASE))      \
+               __reserved_bits |= X86_CR4_FSGSBASE;    \
+       if (!__cpu_has(__c, X86_FEATURE_PKU))           \
+               __reserved_bits |= X86_CR4_PKE;         \
+       if (!__cpu_has(__c, X86_FEATURE_LA57))          \
+               __reserved_bits |= X86_CR4_LA57;        \
+       __reserved_bits;                                \
+ })
  
-       if (!guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) && (cr4 & X86_CR4_OSXSAVE))
-               return -EINVAL;
-       if (!guest_cpuid_has(vcpu, X86_FEATURE_SMEP) && (cr4 & X86_CR4_SMEP))
-               return -EINVAL;
+ static u64 kvm_host_cr4_reserved_bits(struct cpuinfo_x86 *c)
+ {
+       u64 reserved_bits = __cr4_reserved_bits(cpu_has, c);
  
-       if (!guest_cpuid_has(vcpu, X86_FEATURE_SMAP) && (cr4 & X86_CR4_SMAP))
-               return -EINVAL;
+       if (cpuid_ecx(0x7) & feature_bit(LA57))
+               reserved_bits &= ~X86_CR4_LA57;
  
-       if (!guest_cpuid_has(vcpu, X86_FEATURE_FSGSBASE) && (cr4 & X86_CR4_FSGSBASE))
-               return -EINVAL;
+       if (kvm_x86_ops->umip_emulated())
+               reserved_bits &= ~X86_CR4_UMIP;
  
-       if (!guest_cpuid_has(vcpu, X86_FEATURE_PKU) && (cr4 & X86_CR4_PKE))
-               return -EINVAL;
+       return reserved_bits;
+ }
  
-       if (!guest_cpuid_has(vcpu, X86_FEATURE_LA57) && (cr4 & X86_CR4_LA57))
+ static int kvm_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
+ {
+       if (cr4 & cr4_reserved_bits)
                return -EINVAL;
  
-       if (!guest_cpuid_has(vcpu, X86_FEATURE_UMIP) && (cr4 & X86_CR4_UMIP))
+       if (cr4 & __cr4_reserved_bits(guest_cpuid_has, vcpu))
                return -EINVAL;
  
        return 0;
@@@ -1047,9 -1063,11 +1063,11 @@@ static u64 kvm_dr6_fixed(struct kvm_vcp
  
  static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
  {
+       size_t size = ARRAY_SIZE(vcpu->arch.db);
        switch (dr) {
        case 0 ... 3:
-               vcpu->arch.db[dr] = val;
+               vcpu->arch.db[array_index_nospec(dr, size)] = val;
                if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
                        vcpu->arch.eff_db[dr] = val;
                break;
        case 5:
                /* fall through */
        default: /* 7 */
-               if (val & 0xffffffff00000000ULL)
+               if (!kvm_dr7_valid(val))
                        return -1; /* #GP */
                vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
                kvm_update_dr7(vcpu);
@@@ -1086,9 -1104,11 +1104,11 @@@ EXPORT_SYMBOL_GPL(kvm_set_dr)
  
  int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
  {
+       size_t size = ARRAY_SIZE(vcpu->arch.db);
        switch (dr) {
        case 0 ... 3:
-               *val = vcpu->arch.db[dr];
+               *val = vcpu->arch.db[array_index_nospec(dr, size)];
                break;
        case 4:
                /* fall through */
@@@ -1142,7 -1162,7 +1162,7 @@@ static const u32 msrs_to_save_all[] = 
        MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
  #endif
        MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
 -      MSR_IA32_FEATURE_CONTROL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
 +      MSR_IA32_FEAT_CTL, MSR_IA32_BNDCFGS, MSR_TSC_AUX,
        MSR_IA32_SPEC_CTRL,
        MSR_IA32_RTIT_CTL, MSR_IA32_RTIT_STATUS, MSR_IA32_RTIT_CR3_MATCH,
        MSR_IA32_RTIT_OUTPUT_BASE, MSR_IA32_RTIT_OUTPUT_MASK,
@@@ -1212,6 -1232,7 +1232,7 @@@ static const u32 emulated_msrs_all[] = 
        MSR_MISC_FEATURES_ENABLES,
        MSR_AMD64_VIRT_SPEC_CTRL,
        MSR_IA32_POWER_CTL,
+       MSR_IA32_UCODE_REV,
  
        /*
         * The following list leaves out MSRs whose values are determined
@@@ -1526,6 -1547,49 +1547,49 @@@ int kvm_emulate_wrmsr(struct kvm_vcpu *
  EXPORT_SYMBOL_GPL(kvm_emulate_wrmsr);
  
  /*
+  * The fast path for frequent and performance sensitive wrmsr emulation,
+  * i.e. the sending of IPI, sending IPI early in the VM-Exit flow reduces
+  * the latency of virtual IPI by avoiding the expensive bits of transitioning
+  * from guest to host, e.g. reacquiring KVM's SRCU lock. In contrast to the
+  * other cases which must be called after interrupts are enabled on the host.
+  */
+ static int handle_fastpath_set_x2apic_icr_irqoff(struct kvm_vcpu *vcpu, u64 data)
+ {
+       if (lapic_in_kernel(vcpu) && apic_x2apic_mode(vcpu->arch.apic) &&
+               ((data & APIC_DEST_MASK) == APIC_DEST_PHYSICAL) &&
+               ((data & APIC_MODE_MASK) == APIC_DM_FIXED)) {
+               kvm_lapic_set_reg(vcpu->arch.apic, APIC_ICR2, (u32)(data >> 32));
+               return kvm_lapic_reg_write(vcpu->arch.apic, APIC_ICR, (u32)data);
+       }
+       return 1;
+ }
+ enum exit_fastpath_completion handle_fastpath_set_msr_irqoff(struct kvm_vcpu *vcpu)
+ {
+       u32 msr = kvm_rcx_read(vcpu);
+       u64 data = kvm_read_edx_eax(vcpu);
+       int ret = 0;
+       switch (msr) {
+       case APIC_BASE_MSR + (APIC_ICR >> 4):
+               ret = handle_fastpath_set_x2apic_icr_irqoff(vcpu, data);
+               break;
+       default:
+               return EXIT_FASTPATH_NONE;
+       }
+       if (!ret) {
+               trace_kvm_msr_write(msr, data);
+               return EXIT_FASTPATH_SKIP_EMUL_INS;
+       }
+       return EXIT_FASTPATH_NONE;
+ }
+ EXPORT_SYMBOL_GPL(handle_fastpath_set_msr_irqoff);
+ /*
   * Adapt set_msr() to msr_io()'s calling convention
   */
  static int do_get_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
@@@ -2485,7 -2549,10 +2549,10 @@@ static int set_msr_mce(struct kvm_vcpu 
        default:
                if (msr >= MSR_IA32_MC0_CTL &&
                    msr < MSR_IA32_MCx_CTL(bank_num)) {
-                       u32 offset = msr - MSR_IA32_MC0_CTL;
+                       u32 offset = array_index_nospec(
+                               msr - MSR_IA32_MC0_CTL,
+                               MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
                        /* only 0 or all 1s can be written to IA32_MCi_CTL
                         * some Linux kernels though clear bit 10 in bank 4 to
                         * workaround a BIOS/GART TBL issue on AMD K8s, ignore
@@@ -2581,45 -2648,47 +2648,47 @@@ static void kvm_vcpu_flush_tlb(struct k
  
  static void record_steal_time(struct kvm_vcpu *vcpu)
  {
+       struct kvm_host_map map;
+       struct kvm_steal_time *st;
        if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
                return;
  
-       if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
-               &vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
+       /* -EAGAIN is returned in atomic context so we can just return. */
+       if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT,
+                       &map, &vcpu->arch.st.cache, false))
                return;
  
+       st = map.hva +
+               offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
        /*
         * Doing a TLB flush here, on the guest's behalf, can avoid
         * expensive IPIs.
         */
        trace_kvm_pv_tlb_flush(vcpu->vcpu_id,
-               vcpu->arch.st.steal.preempted & KVM_VCPU_FLUSH_TLB);
-       if (xchg(&vcpu->arch.st.steal.preempted, 0) & KVM_VCPU_FLUSH_TLB)
+               st->preempted & KVM_VCPU_FLUSH_TLB);
+       if (xchg(&st->preempted, 0) & KVM_VCPU_FLUSH_TLB)
                kvm_vcpu_flush_tlb(vcpu, false);
  
-       if (vcpu->arch.st.steal.version & 1)
-               vcpu->arch.st.steal.version += 1;  /* first time write, random junk */
+       vcpu->arch.st.preempted = 0;
  
-       vcpu->arch.st.steal.version += 1;
+       if (st->version & 1)
+               st->version += 1;  /* first time write, random junk */
  
-       kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
-               &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
+       st->version += 1;
  
        smp_wmb();
  
-       vcpu->arch.st.steal.steal += current->sched_info.run_delay -
+       st->steal += current->sched_info.run_delay -
                vcpu->arch.st.last_steal;
        vcpu->arch.st.last_steal = current->sched_info.run_delay;
  
-       kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
-               &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
        smp_wmb();
  
-       vcpu->arch.st.steal.version += 1;
+       st->version += 1;
  
-       kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
-               &vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
+       kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, false);
  }
  
  int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
                if (data & KVM_STEAL_RESERVED_MASK)
                        return 1;
  
-               if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
-                                               data & KVM_STEAL_VALID_BITS,
-                                               sizeof(struct kvm_steal_time)))
-                       return 1;
                vcpu->arch.st.msr_val = data;
  
                if (!(data & KVM_MSR_ENABLED))
@@@ -2926,7 -2990,10 +2990,10 @@@ static int get_msr_mce(struct kvm_vcpu 
        default:
                if (msr >= MSR_IA32_MC0_CTL &&
                    msr < MSR_IA32_MCx_CTL(bank_num)) {
-                       u32 offset = msr - MSR_IA32_MC0_CTL;
+                       u32 offset = array_index_nospec(
+                               msr - MSR_IA32_MC0_CTL,
+                               MSR_IA32_MCx_CTL(bank_num) - MSR_IA32_MC0_CTL);
                        data = vcpu->arch.mce_banks[offset];
                        break;
                }
@@@ -3458,10 -3525,6 +3525,6 @@@ void kvm_arch_vcpu_load(struct kvm_vcp
  
        kvm_x86_ops->vcpu_load(vcpu, cpu);
  
-       fpregs_assert_state_consistent();
-       if (test_thread_flag(TIF_NEED_FPU_LOAD))
-               switch_fpu_return();
        /* Apply any externally detected TSC adjustments (due to suspend) */
        if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
                adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
  
  static void kvm_steal_time_set_preempted(struct kvm_vcpu *vcpu)
  {
+       struct kvm_host_map map;
+       struct kvm_steal_time *st;
        if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
                return;
  
-       vcpu->arch.st.steal.preempted = KVM_VCPU_PREEMPTED;
+       if (vcpu->arch.st.preempted)
+               return;
+       if (kvm_map_gfn(vcpu, vcpu->arch.st.msr_val >> PAGE_SHIFT, &map,
+                       &vcpu->arch.st.cache, true))
+               return;
+       st = map.hva +
+               offset_in_page(vcpu->arch.st.msr_val & KVM_STEAL_VALID_BITS);
  
-       kvm_write_guest_offset_cached(vcpu->kvm, &vcpu->arch.st.stime,
-                       &vcpu->arch.st.steal.preempted,
-                       offsetof(struct kvm_steal_time, preempted),
-                       sizeof(vcpu->arch.st.steal.preempted));
+       st->preempted = vcpu->arch.st.preempted = KVM_VCPU_PREEMPTED;
+       kvm_unmap_gfn(vcpu, &map, &vcpu->arch.st.cache, true, true);
  }
  
  void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
@@@ -4660,9 -4733,6 +4733,6 @@@ static int kvm_vm_ioctl_reinject(struc
  {
        struct kvm_pit *pit = kvm->arch.vpit;
  
-       if (!pit)
-               return -ENXIO;
        /* pit->pit_state.lock was overloaded to prevent userspace from getting
         * an inconsistent state after running multiple KVM_REINJECT_CONTROL
         * ioctls in parallel.  Use a separate lock if that ioctl isn't rare.
@@@ -5029,6 -5099,9 +5099,9 @@@ set_identity_unlock
                r =  -EFAULT;
                if (copy_from_user(&control, argp, sizeof(control)))
                        goto out;
+               r = -ENXIO;
+               if (!kvm->arch.vpit)
+                       goto out;
                r = kvm_vm_ioctl_reinject(kvm, &control);
                break;
        }
@@@ -6186,6 -6259,21 +6259,21 @@@ static bool emulator_get_cpuid(struct x
        return kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx, check_limit);
  }
  
+ static bool emulator_guest_has_long_mode(struct x86_emulate_ctxt *ctxt)
+ {
+       return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_LM);
+ }
+ static bool emulator_guest_has_movbe(struct x86_emulate_ctxt *ctxt)
+ {
+       return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_MOVBE);
+ }
+ static bool emulator_guest_has_fxsr(struct x86_emulate_ctxt *ctxt)
+ {
+       return guest_cpuid_has(emul_to_vcpu(ctxt), X86_FEATURE_FXSR);
+ }
  static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
  {
        return kvm_register_read(emul_to_vcpu(ctxt), reg);
@@@ -6263,6 -6351,9 +6351,9 @@@ static const struct x86_emulate_ops emu
        .fix_hypercall       = emulator_fix_hypercall,
        .intercept           = emulator_intercept,
        .get_cpuid           = emulator_get_cpuid,
+       .guest_has_long_mode = emulator_guest_has_long_mode,
+       .guest_has_movbe     = emulator_guest_has_movbe,
+       .guest_has_fxsr      = emulator_guest_has_fxsr,
        .set_nmi_mask        = emulator_set_nmi_mask,
        .get_hflags          = emulator_get_hflags,
        .set_hflags          = emulator_set_hflags,
@@@ -6379,11 -6470,11 +6470,11 @@@ static int handle_emulation_failure(str
        return 1;
  }
  
- static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
+ static bool reexecute_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
                                  bool write_fault_to_shadow_pgtable,
                                  int emulation_type)
  {
-       gpa_t gpa = cr2;
+       gpa_t gpa = cr2_or_gpa;
        kvm_pfn_t pfn;
  
        if (!(emulation_type & EMULTYPE_ALLOW_RETRY))
                 * Write permission should be allowed since only
                 * write access need to be emulated.
                 */
-               gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
+               gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
  
                /*
                 * If the mapping is invalid in guest, let cpu retry
  }
  
  static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
-                             unsigned long cr2,  int emulation_type)
+                             gpa_t cr2_or_gpa,  int emulation_type)
  {
        struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
-       unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
+       unsigned long last_retry_eip, last_retry_addr, gpa = cr2_or_gpa;
  
        last_retry_eip = vcpu->arch.last_retry_eip;
        last_retry_addr = vcpu->arch.last_retry_addr;
        if (x86_page_table_writing_insn(ctxt))
                return false;
  
-       if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
+       if (ctxt->eip == last_retry_eip && last_retry_addr == cr2_or_gpa)
                return false;
  
        vcpu->arch.last_retry_eip = ctxt->eip;
-       vcpu->arch.last_retry_addr = cr2;
+       vcpu->arch.last_retry_addr = cr2_or_gpa;
  
        if (!vcpu->arch.mmu->direct_map)
-               gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
+               gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2_or_gpa, NULL);
  
        kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
  
@@@ -6639,11 -6730,8 +6730,8 @@@ static bool is_vmware_backdoor_opcode(s
        return false;
  }
  
- int x86_emulate_instruction(struct kvm_vcpu *vcpu,
-                           unsigned long cr2,
-                           int emulation_type,
-                           void *insn,
-                           int insn_len)
+ int x86_emulate_instruction(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
+                           int emulation_type, void *insn, int insn_len)
  {
        int r;
        struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
                                kvm_queue_exception(vcpu, UD_VECTOR);
                                return 1;
                        }
-                       if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
-                                               emulation_type))
+                       if (reexecute_instruction(vcpu, cr2_or_gpa,
+                                                 write_fault_to_spt,
+                                                 emulation_type))
                                return 1;
                        if (ctxt->have_exception) {
                                /*
                return 1;
        }
  
-       if (retry_instruction(ctxt, cr2, emulation_type))
+       if (retry_instruction(ctxt, cr2_or_gpa, emulation_type))
                return 1;
  
        /* this is needed for vmware backdoor interface to work since it
  
  restart:
        /* Save the faulting GPA (cr2) in the address field */
-       ctxt->exception.address = cr2;
+       ctxt->exception.address = cr2_or_gpa;
  
        r = x86_emulate_insn(ctxt);
  
                return 1;
  
        if (r == EMULATION_FAILED) {
-               if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
+               if (reexecute_instruction(vcpu, cr2_or_gpa, write_fault_to_spt,
                                        emulation_type))
                        return 1;
  
@@@ -7357,8 -7446,8 +7446,8 @@@ static void kvm_pv_kick_cpu_op(struct k
  {
        struct kvm_lapic_irq lapic_irq;
  
-       lapic_irq.shorthand = 0;
-       lapic_irq.dest_mode = 0;
+       lapic_irq.shorthand = APIC_DEST_NOSHORT;
+       lapic_irq.dest_mode = APIC_DEST_PHYSICAL;
        lapic_irq.level = 0;
        lapic_irq.dest_id = apicid;
        lapic_irq.msi_redir_hint = false;
@@@ -7997,6 -8086,7 +8086,7 @@@ static int vcpu_enter_guest(struct kvm_
        bool req_int_win =
                dm_request_for_irq_injection(vcpu) &&
                kvm_cpu_accept_dm_intr(vcpu);
+       enum exit_fastpath_completion exit_fastpath = EXIT_FASTPATH_NONE;
  
        bool req_immediate_exit = false;
  
        trace_kvm_entry(vcpu->vcpu_id);
        guest_enter_irqoff();
  
-       /* The preempt notifier should have taken care of the FPU already.  */
-       WARN_ON_ONCE(test_thread_flag(TIF_NEED_FPU_LOAD));
+       fpregs_assert_state_consistent();
+       if (test_thread_flag(TIF_NEED_FPU_LOAD))
+               switch_fpu_return();
  
        if (unlikely(vcpu->arch.switch_db_regs)) {
                set_debugreg(0, 7);
        vcpu->mode = OUTSIDE_GUEST_MODE;
        smp_wmb();
  
-       kvm_x86_ops->handle_exit_irqoff(vcpu);
+       kvm_x86_ops->handle_exit_irqoff(vcpu, &exit_fastpath);
  
        /*
         * Consume any pending interrupts, including the possible source of
                kvm_lapic_sync_from_vapic(vcpu);
  
        vcpu->arch.gpa_available = false;
-       r = kvm_x86_ops->handle_exit(vcpu);
+       r = kvm_x86_ops->handle_exit(vcpu, exit_fastpath);
        return r;
  
  cancel_injection:
@@@ -8471,12 -8562,26 +8562,26 @@@ static int complete_emulated_mmio(struc
        return 0;
  }
  
+ static void kvm_save_current_fpu(struct fpu *fpu)
+ {
+       /*
+        * If the target FPU state is not resident in the CPU registers, just
+        * memcpy() from current, else save CPU state directly to the target.
+        */
+       if (test_thread_flag(TIF_NEED_FPU_LOAD))
+               memcpy(&fpu->state, &current->thread.fpu.state,
+                      fpu_kernel_xstate_size);
+       else
+               copy_fpregs_to_fpstate(fpu);
+ }
  /* Swap (qemu) user FPU context for the guest FPU context. */
  static void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
  {
        fpregs_lock();
  
-       copy_fpregs_to_fpstate(vcpu->arch.user_fpu);
+       kvm_save_current_fpu(vcpu->arch.user_fpu);
        /* PKRU is separately restored in kvm_x86_ops->run.  */
        __copy_kernel_to_fpregs(&vcpu->arch.guest_fpu->state,
                                ~XFEATURE_MASK_PKRU);
@@@ -8492,7 -8597,8 +8597,8 @@@ static void kvm_put_guest_fpu(struct kv
  {
        fpregs_lock();
  
-       copy_fpregs_to_fpstate(vcpu->arch.guest_fpu);
+       kvm_save_current_fpu(vcpu->arch.guest_fpu);
        copy_kernel_to_fpregs(&vcpu->arch.user_fpu->state);
  
        fpregs_mark_activate();
@@@ -8714,6 -8820,8 +8820,8 @@@ int kvm_arch_vcpu_ioctl_get_mpstate(str
                                    struct kvm_mp_state *mp_state)
  {
        vcpu_load(vcpu);
+       if (kvm_mpx_supported())
+               kvm_load_guest_fpu(vcpu);
  
        kvm_apic_accept_events(vcpu);
        if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
        else
                mp_state->mp_state = vcpu->arch.mp_state;
  
+       if (kvm_mpx_supported())
+               kvm_put_guest_fpu(vcpu);
        vcpu_put(vcpu);
        return 0;
  }
@@@ -9082,33 -9192,90 +9192,90 @@@ static void fx_init(struct kvm_vcpu *vc
        vcpu->arch.cr0 |= X86_CR0_ET;
  }
  
void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id)
  {
-       void *wbinvd_dirty_mask = vcpu->arch.wbinvd_dirty_mask;
-       kvmclock_reset(vcpu);
+       if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
+               pr_warn_once("kvm: SMP vm created on host with unstable TSC; "
+                            "guest TSC will not be reliable\n");
  
-       kvm_x86_ops->vcpu_free(vcpu);
-       free_cpumask_var(wbinvd_dirty_mask);
+       return 0;
  }
  
- struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
-                                               unsigned int id)
+ int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu)
  {
-       struct kvm_vcpu *vcpu;
+       struct page *page;
+       int r;
  
-       if (kvm_check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
-               printk_once(KERN_WARNING
-               "kvm: SMP vm created on host with unstable TSC; "
-               "guest TSC will not be reliable\n");
+       vcpu->arch.emulate_ctxt.ops = &emulate_ops;
+       if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
+               vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
+       else
+               vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
  
-       vcpu = kvm_x86_ops->vcpu_create(kvm, id);
+       kvm_set_tsc_khz(vcpu, max_tsc_khz);
  
-       return vcpu;
- }
+       r = kvm_mmu_create(vcpu);
+       if (r < 0)
+               return r;
+       if (irqchip_in_kernel(vcpu->kvm)) {
+               vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv(vcpu->kvm);
+               r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
+               if (r < 0)
+                       goto fail_mmu_destroy;
+       } else
+               static_key_slow_inc(&kvm_no_apic_vcpu);
+       r = -ENOMEM;
+       page = alloc_page(GFP_KERNEL | __GFP_ZERO);
+       if (!page)
+               goto fail_free_lapic;
+       vcpu->arch.pio_data = page_address(page);
+       vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
+                                      GFP_KERNEL_ACCOUNT);
+       if (!vcpu->arch.mce_banks)
+               goto fail_free_pio_data;
+       vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
+       if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
+                               GFP_KERNEL_ACCOUNT))
+               goto fail_free_mce_banks;
+       vcpu->arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
+                                               GFP_KERNEL_ACCOUNT);
+       if (!vcpu->arch.user_fpu) {
+               pr_err("kvm: failed to allocate userspace's fpu\n");
+               goto free_wbinvd_dirty_mask;
+       }
+       vcpu->arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
+                                                GFP_KERNEL_ACCOUNT);
+       if (!vcpu->arch.guest_fpu) {
+               pr_err("kvm: failed to allocate vcpu's fpu\n");
+               goto free_user_fpu;
+       }
+       fx_init(vcpu);
+       vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
+       vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
+       vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
+       kvm_async_pf_hash_reset(vcpu);
+       kvm_pmu_init(vcpu);
+       vcpu->arch.pending_external_vector = -1;
+       vcpu->arch.preempted_in_kernel = false;
+       kvm_hv_vcpu_init(vcpu);
+       r = kvm_x86_ops->vcpu_create(vcpu);
+       if (r)
+               goto free_guest_fpu;
  
- int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
- {
        vcpu->arch.arch_capabilities = kvm_get_arch_capabilities();
        vcpu->arch.msr_platform_info = MSR_PLATFORM_INFO_CPUID_FAULT;
        kvm_vcpu_mtrr_init(vcpu);
        kvm_init_mmu(vcpu, false);
        vcpu_put(vcpu);
        return 0;
+ free_guest_fpu:
+       kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
+ free_user_fpu:
+       kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
+ free_wbinvd_dirty_mask:
+       free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
+ fail_free_mce_banks:
+       kfree(vcpu->arch.mce_banks);
+ fail_free_pio_data:
+       free_page((unsigned long)vcpu->arch.pio_data);
+ fail_free_lapic:
+       kvm_free_lapic(vcpu);
+ fail_mmu_destroy:
+       kvm_mmu_destroy(vcpu);
+       return r;
  }
  
  void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
  
  void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
  {
-       vcpu->arch.apf.msr_val = 0;
+       struct gfn_to_pfn_cache *cache = &vcpu->arch.st.cache;
+       int idx;
  
-       vcpu_load(vcpu);
-       kvm_mmu_unload(vcpu);
-       vcpu_put(vcpu);
+       kvm_release_pfn(cache->pfn, cache->dirty, cache);
+       kvmclock_reset(vcpu);
  
        kvm_x86_ops->vcpu_free(vcpu);
+       free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
+       kmem_cache_free(x86_fpu_cache, vcpu->arch.user_fpu);
+       kmem_cache_free(x86_fpu_cache, vcpu->arch.guest_fpu);
+       kvm_hv_vcpu_uninit(vcpu);
+       kvm_pmu_destroy(vcpu);
+       kfree(vcpu->arch.mce_banks);
+       kvm_free_lapic(vcpu);
+       idx = srcu_read_lock(&vcpu->kvm->srcu);
+       kvm_mmu_destroy(vcpu);
+       srcu_read_unlock(&vcpu->kvm->srcu, idx);
+       free_page((unsigned long)vcpu->arch.pio_data);
+       if (!lapic_in_kernel(vcpu))
+               static_key_slow_dec(&kvm_no_apic_vcpu);
  }
  
  void kvm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
        vcpu->arch.nmi_injected = false;
        kvm_clear_interrupt_queue(vcpu);
        kvm_clear_exception_queue(vcpu);
-       vcpu->arch.exception.pending = false;
  
        memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
        kvm_update_dr0123(vcpu);
@@@ -9347,6 -9545,8 +9545,8 @@@ int kvm_arch_hardware_setup(void
        if (r != 0)
                return r;
  
+       cr4_reserved_bits = kvm_host_cr4_reserved_bits(&boot_cpu_data);
        if (kvm_has_tsc_control) {
                /*
                 * Make sure the user can only configure tsc_khz values that
@@@ -9375,6 -9575,13 +9575,13 @@@ void kvm_arch_hardware_unsetup(void
  
  int kvm_arch_check_processor_compat(void)
  {
+       struct cpuinfo_x86 *c = &cpu_data(smp_processor_id());
+       WARN_ON(!irqs_disabled());
+       if (kvm_host_cr4_reserved_bits(c) != cr4_reserved_bits)
+               return -EIO;
        return kvm_x86_ops->check_processor_compatibility();
  }
  
@@@ -9392,98 -9599,6 +9599,6 @@@ bool kvm_vcpu_is_bsp(struct kvm_vcpu *v
  struct static_key kvm_no_apic_vcpu __read_mostly;
  EXPORT_SYMBOL_GPL(kvm_no_apic_vcpu);
  
- int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
- {
-       struct page *page;
-       int r;
-       vcpu->arch.emulate_ctxt.ops = &emulate_ops;
-       if (!irqchip_in_kernel(vcpu->kvm) || kvm_vcpu_is_reset_bsp(vcpu))
-               vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
-       else
-               vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
-       page = alloc_page(GFP_KERNEL | __GFP_ZERO);
-       if (!page) {
-               r = -ENOMEM;
-               goto fail;
-       }
-       vcpu->arch.pio_data = page_address(page);
-       kvm_set_tsc_khz(vcpu, max_tsc_khz);
-       r = kvm_mmu_create(vcpu);
-       if (r < 0)
-               goto fail_free_pio_data;
-       if (irqchip_in_kernel(vcpu->kvm)) {
-               vcpu->arch.apicv_active = kvm_x86_ops->get_enable_apicv(vcpu->kvm);
-               r = kvm_create_lapic(vcpu, lapic_timer_advance_ns);
-               if (r < 0)
-                       goto fail_mmu_destroy;
-       } else
-               static_key_slow_inc(&kvm_no_apic_vcpu);
-       vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
-                                      GFP_KERNEL_ACCOUNT);
-       if (!vcpu->arch.mce_banks) {
-               r = -ENOMEM;
-               goto fail_free_lapic;
-       }
-       vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
-       if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask,
-                               GFP_KERNEL_ACCOUNT)) {
-               r = -ENOMEM;
-               goto fail_free_mce_banks;
-       }
-       fx_init(vcpu);
-       vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
-       vcpu->arch.maxphyaddr = cpuid_query_maxphyaddr(vcpu);
-       vcpu->arch.pat = MSR_IA32_CR_PAT_DEFAULT;
-       kvm_async_pf_hash_reset(vcpu);
-       kvm_pmu_init(vcpu);
-       vcpu->arch.pending_external_vector = -1;
-       vcpu->arch.preempted_in_kernel = false;
-       kvm_hv_vcpu_init(vcpu);
-       return 0;
- fail_free_mce_banks:
-       kfree(vcpu->arch.mce_banks);
- fail_free_lapic:
-       kvm_free_lapic(vcpu);
- fail_mmu_destroy:
-       kvm_mmu_destroy(vcpu);
- fail_free_pio_data:
-       free_page((unsigned long)vcpu->arch.pio_data);
- fail:
-       return r;
- }
- void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
- {
-       int idx;
-       kvm_hv_vcpu_uninit(vcpu);
-       kvm_pmu_destroy(vcpu);
-       kfree(vcpu->arch.mce_banks);
-       kvm_free_lapic(vcpu);
-       idx = srcu_read_lock(&vcpu->kvm->srcu);
-       kvm_mmu_destroy(vcpu);
-       srcu_read_unlock(&vcpu->kvm->srcu, idx);
-       free_page((unsigned long)vcpu->arch.pio_data);
-       if (!lapic_in_kernel(vcpu))
-               static_key_slow_dec(&kvm_no_apic_vcpu);
- }
  void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu)
  {
        struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
@@@ -9558,7 -9673,7 +9673,7 @@@ static void kvm_free_vcpus(struct kvm *
                kvm_unload_vcpu_mmu(vcpu);
        }
        kvm_for_each_vcpu(i, vcpu, kvm)
-               kvm_arch_vcpu_free(vcpu);
+               kvm_vcpu_destroy(vcpu);
  
        mutex_lock(&kvm->lock);
        for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
@@@ -9627,18 -9742,6 +9742,6 @@@ int __x86_set_memory_region(struct kvm 
  }
  EXPORT_SYMBOL_GPL(__x86_set_memory_region);
  
- int x86_set_memory_region(struct kvm *kvm, int id, gpa_t gpa, u32 size)
- {
-       int r;
-       mutex_lock(&kvm->slots_lock);
-       r = __x86_set_memory_region(kvm, id, gpa, size);
-       mutex_unlock(&kvm->slots_lock);
-       return r;
- }
- EXPORT_SYMBOL_GPL(x86_set_memory_region);
  void kvm_arch_pre_destroy_vm(struct kvm *kvm)
  {
        kvm_mmu_pre_destroy_vm(kvm);
@@@ -9652,9 -9755,13 +9755,13 @@@ void kvm_arch_destroy_vm(struct kvm *kv
                 * unless the the memory map has changed due to process exit
                 * or fd copying.
                 */
-               x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT, 0, 0);
-               x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT, 0, 0);
-               x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
+               mutex_lock(&kvm->slots_lock);
+               __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
+                                       0, 0);
+               __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
+                                       0, 0);
+               __x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, 0, 0);
+               mutex_unlock(&kvm->slots_lock);
        }
        if (kvm_x86_ops->vm_destroy)
                kvm_x86_ops->vm_destroy(kvm);
@@@ -9758,11 -9865,18 +9865,18 @@@ out_free
  
  void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
  {
+       struct kvm_vcpu *vcpu;
+       int i;
        /*
         * memslots->generation has been incremented.
         * mmio generation may have reached its maximum value.
         */
        kvm_mmu_invalidate_mmio_sptes(kvm, gen);
+       /* Force re-initialization of steal_time cache */
+       kvm_for_each_vcpu(i, vcpu, kvm)
+               kvm_vcpu_kick(vcpu);
  }
  
  int kvm_arch_prepare_memory_region(struct kvm *kvm,
@@@ -9792,7 -9906,7 +9906,7 @@@ static void kvm_mmu_slot_apply_flags(st
         *
         * The reason is, in case of PML, we need to set D-bit for any slots
         * with dirty logging disabled in order to eliminate unnecessary GPA
-        * logging in PML buffer (and potential PML buffer full VMEXT). This
+        * logging in PML buffer (and potential PML buffer full VMEXIT). This
         * guarantees leaving PML enabled during guest's lifetime won't have
         * any additional overhead from PML when guest is running with dirty
         * logging disabled for memory slots.
@@@ -10014,7 -10128,7 +10128,7 @@@ void kvm_arch_async_page_ready(struct k
              work->arch.cr3 != vcpu->arch.mmu->get_cr3(vcpu))
                return;
  
-       vcpu->arch.mmu->page_fault(vcpu, work->gva, 0, true);
+       vcpu->arch.mmu->page_fault(vcpu, work->cr2_or_gpa, 0, true);
  }
  
  static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
@@@ -10127,7 -10241,7 +10241,7 @@@ void kvm_arch_async_page_not_present(st
  {
        struct x86_exception fault;
  
-       trace_kvm_async_pf_not_present(work->arch.token, work->gva);
+       trace_kvm_async_pf_not_present(work->arch.token, work->cr2_or_gpa);
        kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
  
        if (kvm_can_deliver_async_pf(vcpu) &&
@@@ -10162,7 -10276,7 +10276,7 @@@ void kvm_arch_async_page_present(struc
                work->arch.token = ~0; /* broadcast wakeup */
        else
                kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
-       trace_kvm_async_pf_ready(work->arch.token, work->gva);
+       trace_kvm_async_pf_ready(work->arch.token, work->cr2_or_gpa);
  
        if (vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED &&
            !apf_get_user(vcpu, &val)) {
@@@ -10284,7 -10398,6 +10398,6 @@@ bool kvm_vector_hashing_enabled(void
  {
        return vector_hashing;
  }
- EXPORT_SYMBOL_GPL(kvm_vector_hashing_enabled);
  
  bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
  {
  }
  EXPORT_SYMBOL_GPL(kvm_arch_no_poll);
  
+ u64 kvm_spec_ctrl_valid_bits(struct kvm_vcpu *vcpu)
+ {
+       uint64_t bits = SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD;
+       /* The STIBP bit doesn't fault even if it's not advertised */
+       if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
+           !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS))
+               bits &= ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP);
+       if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL) &&
+           !boot_cpu_has(X86_FEATURE_AMD_IBRS))
+               bits &= ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP);
+       if (!guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL_SSBD) &&
+           !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
+               bits &= ~SPEC_CTRL_SSBD;
+       if (!boot_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD) &&
+           !boot_cpu_has(X86_FEATURE_AMD_SSBD))
+               bits &= ~SPEC_CTRL_SSBD;
+       return bits;
+ }
+ EXPORT_SYMBOL_GPL(kvm_spec_ctrl_valid_bits);
  
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
  EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_fast_mmio);
index 62a8ebe,0000000..c4aedd0
mode 100644,000000..100644
--- /dev/null
@@@ -1,2279 -1,0 +1,2290 @@@
 +// SPDX-License-Identifier: GPL-2.0-only
 +/*
 + * Copyright 2002 Andi Kleen, SuSE Labs.
 + * Thanks to Ben LaHaise for precious feedback.
 + */
 +#include <linux/highmem.h>
 +#include <linux/memblock.h>
 +#include <linux/sched.h>
 +#include <linux/mm.h>
 +#include <linux/interrupt.h>
 +#include <linux/seq_file.h>
 +#include <linux/debugfs.h>
 +#include <linux/pfn.h>
 +#include <linux/percpu.h>
 +#include <linux/gfp.h>
 +#include <linux/pci.h>
 +#include <linux/vmalloc.h>
 +
 +#include <asm/e820/api.h>
 +#include <asm/processor.h>
 +#include <asm/tlbflush.h>
 +#include <asm/sections.h>
 +#include <asm/setup.h>
 +#include <linux/uaccess.h>
 +#include <asm/pgalloc.h>
 +#include <asm/proto.h>
 +#include <asm/memtype.h>
 +#include <asm/set_memory.h>
 +
 +#include "../mm_internal.h"
 +
 +/*
 + * The current flushing context - we pass it instead of 5 arguments:
 + */
 +struct cpa_data {
 +      unsigned long   *vaddr;
 +      pgd_t           *pgd;
 +      pgprot_t        mask_set;
 +      pgprot_t        mask_clr;
 +      unsigned long   numpages;
 +      unsigned long   curpage;
 +      unsigned long   pfn;
 +      unsigned int    flags;
 +      unsigned int    force_split             : 1,
 +                      force_static_prot       : 1;
 +      struct page     **pages;
 +};
 +
 +enum cpa_warn {
 +      CPA_CONFLICT,
 +      CPA_PROTECT,
 +      CPA_DETECT,
 +};
 +
 +static const int cpa_warn_level = CPA_PROTECT;
 +
 +/*
 + * Serialize cpa() (for !DEBUG_PAGEALLOC which uses large identity mappings)
 + * using cpa_lock. So that we don't allow any other cpu, with stale large tlb
 + * entries change the page attribute in parallel to some other cpu
 + * splitting a large page entry along with changing the attribute.
 + */
 +static DEFINE_SPINLOCK(cpa_lock);
 +
 +#define CPA_FLUSHTLB 1
 +#define CPA_ARRAY 2
 +#define CPA_PAGES_ARRAY 4
 +#define CPA_NO_CHECK_ALIAS 8 /* Do not search for aliases */
 +
 +#ifdef CONFIG_PROC_FS
 +static unsigned long direct_pages_count[PG_LEVEL_NUM];
 +
 +void update_page_count(int level, unsigned long pages)
 +{
 +      /* Protect against CPA */
 +      spin_lock(&pgd_lock);
 +      direct_pages_count[level] += pages;
 +      spin_unlock(&pgd_lock);
 +}
 +
 +static void split_page_count(int level)
 +{
 +      if (direct_pages_count[level] == 0)
 +              return;
 +
 +      direct_pages_count[level]--;
 +      direct_pages_count[level - 1] += PTRS_PER_PTE;
 +}
 +
 +void arch_report_meminfo(struct seq_file *m)
 +{
 +      seq_printf(m, "DirectMap4k:    %8lu kB\n",
 +                      direct_pages_count[PG_LEVEL_4K] << 2);
 +#if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
 +      seq_printf(m, "DirectMap2M:    %8lu kB\n",
 +                      direct_pages_count[PG_LEVEL_2M] << 11);
 +#else
 +      seq_printf(m, "DirectMap4M:    %8lu kB\n",
 +                      direct_pages_count[PG_LEVEL_2M] << 12);
 +#endif
 +      if (direct_gbpages)
 +              seq_printf(m, "DirectMap1G:    %8lu kB\n",
 +                      direct_pages_count[PG_LEVEL_1G] << 20);
 +}
 +#else
 +static inline void split_page_count(int level) { }
 +#endif
 +
 +#ifdef CONFIG_X86_CPA_STATISTICS
 +
 +static unsigned long cpa_1g_checked;
 +static unsigned long cpa_1g_sameprot;
 +static unsigned long cpa_1g_preserved;
 +static unsigned long cpa_2m_checked;
 +static unsigned long cpa_2m_sameprot;
 +static unsigned long cpa_2m_preserved;
 +static unsigned long cpa_4k_install;
 +
 +static inline void cpa_inc_1g_checked(void)
 +{
 +      cpa_1g_checked++;
 +}
 +
 +static inline void cpa_inc_2m_checked(void)
 +{
 +      cpa_2m_checked++;
 +}
 +
 +static inline void cpa_inc_4k_install(void)
 +{
 +      cpa_4k_install++;
 +}
 +
 +static inline void cpa_inc_lp_sameprot(int level)
 +{
 +      if (level == PG_LEVEL_1G)
 +              cpa_1g_sameprot++;
 +      else
 +              cpa_2m_sameprot++;
 +}
 +
 +static inline void cpa_inc_lp_preserved(int level)
 +{
 +      if (level == PG_LEVEL_1G)
 +              cpa_1g_preserved++;
 +      else
 +              cpa_2m_preserved++;
 +}
 +
 +static int cpastats_show(struct seq_file *m, void *p)
 +{
 +      seq_printf(m, "1G pages checked:     %16lu\n", cpa_1g_checked);
 +      seq_printf(m, "1G pages sameprot:    %16lu\n", cpa_1g_sameprot);
 +      seq_printf(m, "1G pages preserved:   %16lu\n", cpa_1g_preserved);
 +      seq_printf(m, "2M pages checked:     %16lu\n", cpa_2m_checked);
 +      seq_printf(m, "2M pages sameprot:    %16lu\n", cpa_2m_sameprot);
 +      seq_printf(m, "2M pages preserved:   %16lu\n", cpa_2m_preserved);
 +      seq_printf(m, "4K pages set-checked: %16lu\n", cpa_4k_install);
 +      return 0;
 +}
 +
 +static int cpastats_open(struct inode *inode, struct file *file)
 +{
 +      return single_open(file, cpastats_show, NULL);
 +}
 +
 +static const struct file_operations cpastats_fops = {
 +      .open           = cpastats_open,
 +      .read           = seq_read,
 +      .llseek         = seq_lseek,
 +      .release        = single_release,
 +};
 +
 +static int __init cpa_stats_init(void)
 +{
 +      debugfs_create_file("cpa_stats", S_IRUSR, arch_debugfs_dir, NULL,
 +                          &cpastats_fops);
 +      return 0;
 +}
 +late_initcall(cpa_stats_init);
 +#else
 +static inline void cpa_inc_1g_checked(void) { }
 +static inline void cpa_inc_2m_checked(void) { }
 +static inline void cpa_inc_4k_install(void) { }
 +static inline void cpa_inc_lp_sameprot(int level) { }
 +static inline void cpa_inc_lp_preserved(int level) { }
 +#endif
 +
 +
 +static inline int
 +within(unsigned long addr, unsigned long start, unsigned long end)
 +{
 +      return addr >= start && addr < end;
 +}
 +
 +static inline int
 +within_inclusive(unsigned long addr, unsigned long start, unsigned long end)
 +{
 +      return addr >= start && addr <= end;
 +}
 +
 +#ifdef CONFIG_X86_64
 +
 +static inline unsigned long highmap_start_pfn(void)
 +{
 +      return __pa_symbol(_text) >> PAGE_SHIFT;
 +}
 +
 +static inline unsigned long highmap_end_pfn(void)
 +{
 +      /* Do not reference physical address outside the kernel. */
 +      return __pa_symbol(roundup(_brk_end, PMD_SIZE) - 1) >> PAGE_SHIFT;
 +}
 +
 +static bool __cpa_pfn_in_highmap(unsigned long pfn)
 +{
 +      /*
 +       * Kernel text has an alias mapping at a high address, known
 +       * here as "highmap".
 +       */
 +      return within_inclusive(pfn, highmap_start_pfn(), highmap_end_pfn());
 +}
 +
 +#else
 +
 +static bool __cpa_pfn_in_highmap(unsigned long pfn)
 +{
 +      /* There is no highmap on 32-bit */
 +      return false;
 +}
 +
 +#endif
 +
 +/*
 + * See set_mce_nospec().
 + *
 + * Machine check recovery code needs to change cache mode of poisoned pages to
 + * UC to avoid speculative access logging another error. But passing the
 + * address of the 1:1 mapping to set_memory_uc() is a fine way to encourage a
 + * speculative access. So we cheat and flip the top bit of the address. This
 + * works fine for the code that updates the page tables. But at the end of the
 + * process we need to flush the TLB and cache and the non-canonical address
 + * causes a #GP fault when used by the INVLPG and CLFLUSH instructions.
 + *
 + * But in the common case we already have a canonical address. This code
 + * will fix the top bit if needed and is a no-op otherwise.
 + */
 +static inline unsigned long fix_addr(unsigned long addr)
 +{
 +#ifdef CONFIG_X86_64
 +      return (long)(addr << 1) >> 1;
 +#else
 +      return addr;
 +#endif
 +}
 +
 +static unsigned long __cpa_addr(struct cpa_data *cpa, unsigned long idx)
 +{
 +      if (cpa->flags & CPA_PAGES_ARRAY) {
 +              struct page *page = cpa->pages[idx];
 +
 +              if (unlikely(PageHighMem(page)))
 +                      return 0;
 +
 +              return (unsigned long)page_address(page);
 +      }
 +
 +      if (cpa->flags & CPA_ARRAY)
 +              return cpa->vaddr[idx];
 +
 +      return *cpa->vaddr + idx * PAGE_SIZE;
 +}
 +
 +/*
 + * Flushing functions
 + */
 +
 +static void clflush_cache_range_opt(void *vaddr, unsigned int size)
 +{
 +      const unsigned long clflush_size = boot_cpu_data.x86_clflush_size;
 +      void *p = (void *)((unsigned long)vaddr & ~(clflush_size - 1));
 +      void *vend = vaddr + size;
 +
 +      if (p >= vend)
 +              return;
 +
 +      for (; p < vend; p += clflush_size)
 +              clflushopt(p);
 +}
 +
 +/**
 + * clflush_cache_range - flush a cache range with clflush
 + * @vaddr:    virtual start address
 + * @size:     number of bytes to flush
 + *
 + * CLFLUSHOPT is an unordered instruction which needs fencing with MFENCE or
 + * SFENCE to avoid ordering issues.
 + */
 +void clflush_cache_range(void *vaddr, unsigned int size)
 +{
 +      mb();
 +      clflush_cache_range_opt(vaddr, size);
 +      mb();
 +}
 +EXPORT_SYMBOL_GPL(clflush_cache_range);
 +
 +void arch_invalidate_pmem(void *addr, size_t size)
 +{
 +      clflush_cache_range(addr, size);
 +}
 +EXPORT_SYMBOL_GPL(arch_invalidate_pmem);
 +
 +static void __cpa_flush_all(void *arg)
 +{
 +      unsigned long cache = (unsigned long)arg;
 +
 +      /*
 +       * Flush all to work around Errata in early athlons regarding
 +       * large page flushing.
 +       */
 +      __flush_tlb_all();
 +
 +      if (cache && boot_cpu_data.x86 >= 4)
 +              wbinvd();
 +}
 +
 +static void cpa_flush_all(unsigned long cache)
 +{
 +      BUG_ON(irqs_disabled() && !early_boot_irqs_disabled);
 +
 +      on_each_cpu(__cpa_flush_all, (void *) cache, 1);
 +}
 +
 +static void __cpa_flush_tlb(void *data)
 +{
 +      struct cpa_data *cpa = data;
 +      unsigned int i;
 +
 +      for (i = 0; i < cpa->numpages; i++)
 +              __flush_tlb_one_kernel(fix_addr(__cpa_addr(cpa, i)));
 +}
 +
 +static void cpa_flush(struct cpa_data *data, int cache)
 +{
 +      struct cpa_data *cpa = data;
 +      unsigned int i;
 +
 +      BUG_ON(irqs_disabled() && !early_boot_irqs_disabled);
 +
 +      if (cache && !static_cpu_has(X86_FEATURE_CLFLUSH)) {
 +              cpa_flush_all(cache);
 +              return;
 +      }
 +
 +      if (cpa->numpages <= tlb_single_page_flush_ceiling)
 +              on_each_cpu(__cpa_flush_tlb, cpa, 1);
 +      else
 +              flush_tlb_all();
 +
 +      if (!cache)
 +              return;
 +
 +      mb();
 +      for (i = 0; i < cpa->numpages; i++) {
 +              unsigned long addr = __cpa_addr(cpa, i);
 +              unsigned int level;
 +
 +              pte_t *pte = lookup_address(addr, &level);
 +
 +              /*
 +               * Only flush present addresses:
 +               */
 +              if (pte && (pte_val(*pte) & _PAGE_PRESENT))
 +                      clflush_cache_range_opt((void *)fix_addr(addr), PAGE_SIZE);
 +      }
 +      mb();
 +}
 +
 +static bool overlaps(unsigned long r1_start, unsigned long r1_end,
 +                   unsigned long r2_start, unsigned long r2_end)
 +{
 +      return (r1_start <= r2_end && r1_end >= r2_start) ||
 +              (r2_start <= r1_end && r2_end >= r1_start);
 +}
 +
 +#ifdef CONFIG_PCI_BIOS
 +/*
 + * The BIOS area between 640k and 1Mb needs to be executable for PCI BIOS
 + * based config access (CONFIG_PCI_GOBIOS) support.
 + */
 +#define BIOS_PFN      PFN_DOWN(BIOS_BEGIN)
 +#define BIOS_PFN_END  PFN_DOWN(BIOS_END - 1)
 +
 +static pgprotval_t protect_pci_bios(unsigned long spfn, unsigned long epfn)
 +{
 +      if (pcibios_enabled && overlaps(spfn, epfn, BIOS_PFN, BIOS_PFN_END))
 +              return _PAGE_NX;
 +      return 0;
 +}
 +#else
 +static pgprotval_t protect_pci_bios(unsigned long spfn, unsigned long epfn)
 +{
 +      return 0;
 +}
 +#endif
 +
 +/*
 + * The .rodata section needs to be read-only. Using the pfn catches all
 + * aliases.  This also includes __ro_after_init, so do not enforce until
 + * kernel_set_to_readonly is true.
 + */
 +static pgprotval_t protect_rodata(unsigned long spfn, unsigned long epfn)
 +{
 +      unsigned long epfn_ro, spfn_ro = PFN_DOWN(__pa_symbol(__start_rodata));
 +
 +      /*
 +       * Note: __end_rodata is at page aligned and not inclusive, so
 +       * subtract 1 to get the last enforced PFN in the rodata area.
 +       */
 +      epfn_ro = PFN_DOWN(__pa_symbol(__end_rodata)) - 1;
 +
 +      if (kernel_set_to_readonly && overlaps(spfn, epfn, spfn_ro, epfn_ro))
 +              return _PAGE_RW;
 +      return 0;
 +}
 +
 +/*
 + * Protect kernel text against becoming non executable by forbidding
 + * _PAGE_NX.  This protects only the high kernel mapping (_text -> _etext)
 + * out of which the kernel actually executes.  Do not protect the low
 + * mapping.
 + *
 + * This does not cover __inittext since that is gone after boot.
 + */
 +static pgprotval_t protect_kernel_text(unsigned long start, unsigned long end)
 +{
 +      unsigned long t_end = (unsigned long)_etext - 1;
 +      unsigned long t_start = (unsigned long)_text;
 +
 +      if (overlaps(start, end, t_start, t_end))
 +              return _PAGE_NX;
 +      return 0;
 +}
 +
 +#if defined(CONFIG_X86_64)
 +/*
 + * Once the kernel maps the text as RO (kernel_set_to_readonly is set),
 + * kernel text mappings for the large page aligned text, rodata sections
 + * will be always read-only. For the kernel identity mappings covering the
 + * holes caused by this alignment can be anything that user asks.
 + *
 + * This will preserve the large page mappings for kernel text/data at no
 + * extra cost.
 + */
 +static pgprotval_t protect_kernel_text_ro(unsigned long start,
 +                                        unsigned long end)
 +{
 +      unsigned long t_end = (unsigned long)__end_rodata_hpage_align - 1;
 +      unsigned long t_start = (unsigned long)_text;
 +      unsigned int level;
 +
 +      if (!kernel_set_to_readonly || !overlaps(start, end, t_start, t_end))
 +              return 0;
 +      /*
 +       * Don't enforce the !RW mapping for the kernel text mapping, if
 +       * the current mapping is already using small page mapping.  No
 +       * need to work hard to preserve large page mappings in this case.
 +       *
 +       * This also fixes the Linux Xen paravirt guest boot failure caused
 +       * by unexpected read-only mappings for kernel identity
 +       * mappings. In this paravirt guest case, the kernel text mapping
 +       * and the kernel identity mapping share the same page-table pages,
 +       * so the protections for kernel text and identity mappings have to
 +       * be the same.
 +       */
 +      if (lookup_address(start, &level) && (level != PG_LEVEL_4K))
 +              return _PAGE_RW;
 +      return 0;
 +}
 +#else
 +static pgprotval_t protect_kernel_text_ro(unsigned long start,
 +                                        unsigned long end)
 +{
 +      return 0;
 +}
 +#endif
 +
 +static inline bool conflicts(pgprot_t prot, pgprotval_t val)
 +{
 +      return (pgprot_val(prot) & ~val) != pgprot_val(prot);
 +}
 +
 +static inline void check_conflict(int warnlvl, pgprot_t prot, pgprotval_t val,
 +                                unsigned long start, unsigned long end,
 +                                unsigned long pfn, const char *txt)
 +{
 +      static const char *lvltxt[] = {
 +              [CPA_CONFLICT]  = "conflict",
 +              [CPA_PROTECT]   = "protect",
 +              [CPA_DETECT]    = "detect",
 +      };
 +
 +      if (warnlvl > cpa_warn_level || !conflicts(prot, val))
 +              return;
 +
 +      pr_warn("CPA %8s %10s: 0x%016lx - 0x%016lx PFN %lx req %016llx prevent %016llx\n",
 +              lvltxt[warnlvl], txt, start, end, pfn, (unsigned long long)pgprot_val(prot),
 +              (unsigned long long)val);
 +}
 +
 +/*
 + * Certain areas of memory on x86 require very specific protection flags,
 + * for example the BIOS area or kernel text. Callers don't always get this
 + * right (again, ioremap() on BIOS memory is not uncommon) so this function
 + * checks and fixes these known static required protection bits.
 + */
 +static inline pgprot_t static_protections(pgprot_t prot, unsigned long start,
 +                                        unsigned long pfn, unsigned long npg,
 +                                        unsigned long lpsize, int warnlvl)
 +{
 +      pgprotval_t forbidden, res;
 +      unsigned long end;
 +
 +      /*
 +       * There is no point in checking RW/NX conflicts when the requested
 +       * mapping is setting the page !PRESENT.
 +       */
 +      if (!(pgprot_val(prot) & _PAGE_PRESENT))
 +              return prot;
 +
 +      /* Operate on the virtual address */
 +      end = start + npg * PAGE_SIZE - 1;
 +
 +      res = protect_kernel_text(start, end);
 +      check_conflict(warnlvl, prot, res, start, end, pfn, "Text NX");
 +      forbidden = res;
 +
 +      /*
 +       * Special case to preserve a large page. If the change spawns the
 +       * full large page mapping then there is no point to split it
 +       * up. Happens with ftrace and is going to be removed once ftrace
 +       * switched to text_poke().
 +       */
 +      if (lpsize != (npg * PAGE_SIZE) || (start & (lpsize - 1))) {
 +              res = protect_kernel_text_ro(start, end);
 +              check_conflict(warnlvl, prot, res, start, end, pfn, "Text RO");
 +              forbidden |= res;
 +      }
 +
 +      /* Check the PFN directly */
 +      res = protect_pci_bios(pfn, pfn + npg - 1);
 +      check_conflict(warnlvl, prot, res, start, end, pfn, "PCIBIOS NX");
 +      forbidden |= res;
 +
 +      res = protect_rodata(pfn, pfn + npg - 1);
 +      check_conflict(warnlvl, prot, res, start, end, pfn, "Rodata RO");
 +      forbidden |= res;
 +
 +      return __pgprot(pgprot_val(prot) & ~forbidden);
 +}
 +
 +/*
 + * Lookup the page table entry for a virtual address in a specific pgd.
 + * Return a pointer to the entry and the level of the mapping.
 + */
 +pte_t *lookup_address_in_pgd(pgd_t *pgd, unsigned long address,
 +                           unsigned int *level)
 +{
 +      p4d_t *p4d;
 +      pud_t *pud;
 +      pmd_t *pmd;
 +
 +      *level = PG_LEVEL_NONE;
 +
 +      if (pgd_none(*pgd))
 +              return NULL;
 +
 +      p4d = p4d_offset(pgd, address);
 +      if (p4d_none(*p4d))
 +              return NULL;
 +
 +      *level = PG_LEVEL_512G;
 +      if (p4d_large(*p4d) || !p4d_present(*p4d))
 +              return (pte_t *)p4d;
 +
 +      pud = pud_offset(p4d, address);
 +      if (pud_none(*pud))
 +              return NULL;
 +
 +      *level = PG_LEVEL_1G;
 +      if (pud_large(*pud) || !pud_present(*pud))
 +              return (pte_t *)pud;
 +
 +      pmd = pmd_offset(pud, address);
 +      if (pmd_none(*pmd))
 +              return NULL;
 +
 +      *level = PG_LEVEL_2M;
 +      if (pmd_large(*pmd) || !pmd_present(*pmd))
 +              return (pte_t *)pmd;
 +
 +      *level = PG_LEVEL_4K;
 +
 +      return pte_offset_kernel(pmd, address);
 +}
 +
 +/*
 + * Lookup the page table entry for a virtual address. Return a pointer
 + * to the entry and the level of the mapping.
 + *
 + * Note: We return pud and pmd either when the entry is marked large
 + * or when the present bit is not set. Otherwise we would return a
 + * pointer to a nonexisting mapping.
 + */
 +pte_t *lookup_address(unsigned long address, unsigned int *level)
 +{
 +      return lookup_address_in_pgd(pgd_offset_k(address), address, level);
 +}
 +EXPORT_SYMBOL_GPL(lookup_address);
 +
++/*
++ * Lookup the page table entry for a virtual address in a given mm. Return a
++ * pointer to the entry and the level of the mapping.
++ */
++pte_t *lookup_address_in_mm(struct mm_struct *mm, unsigned long address,
++                          unsigned int *level)
++{
++      return lookup_address_in_pgd(pgd_offset(mm, address), address, level);
++}
++EXPORT_SYMBOL_GPL(lookup_address_in_mm);
++
 +static pte_t *_lookup_address_cpa(struct cpa_data *cpa, unsigned long address,
 +                                unsigned int *level)
 +{
 +      if (cpa->pgd)
 +              return lookup_address_in_pgd(cpa->pgd + pgd_index(address),
 +                                             address, level);
 +
 +      return lookup_address(address, level);
 +}
 +
 +/*
 + * Lookup the PMD entry for a virtual address. Return a pointer to the entry
 + * or NULL if not present.
 + */
 +pmd_t *lookup_pmd_address(unsigned long address)
 +{
 +      pgd_t *pgd;
 +      p4d_t *p4d;
 +      pud_t *pud;
 +
 +      pgd = pgd_offset_k(address);
 +      if (pgd_none(*pgd))
 +              return NULL;
 +
 +      p4d = p4d_offset(pgd, address);
 +      if (p4d_none(*p4d) || p4d_large(*p4d) || !p4d_present(*p4d))
 +              return NULL;
 +
 +      pud = pud_offset(p4d, address);
 +      if (pud_none(*pud) || pud_large(*pud) || !pud_present(*pud))
 +              return NULL;
 +
 +      return pmd_offset(pud, address);
 +}
 +
 +/*
 + * This is necessary because __pa() does not work on some
 + * kinds of memory, like vmalloc() or the alloc_remap()
 + * areas on 32-bit NUMA systems.  The percpu areas can
 + * end up in this kind of memory, for instance.
 + *
 + * This could be optimized, but it is only intended to be
 + * used at inititalization time, and keeping it
 + * unoptimized should increase the testing coverage for
 + * the more obscure platforms.
 + */
 +phys_addr_t slow_virt_to_phys(void *__virt_addr)
 +{
 +      unsigned long virt_addr = (unsigned long)__virt_addr;
 +      phys_addr_t phys_addr;
 +      unsigned long offset;
 +      enum pg_level level;
 +      pte_t *pte;
 +
 +      pte = lookup_address(virt_addr, &level);
 +      BUG_ON(!pte);
 +
 +      /*
 +       * pXX_pfn() returns unsigned long, which must be cast to phys_addr_t
 +       * before being left-shifted PAGE_SHIFT bits -- this trick is to
 +       * make 32-PAE kernel work correctly.
 +       */
 +      switch (level) {
 +      case PG_LEVEL_1G:
 +              phys_addr = (phys_addr_t)pud_pfn(*(pud_t *)pte) << PAGE_SHIFT;
 +              offset = virt_addr & ~PUD_PAGE_MASK;
 +              break;
 +      case PG_LEVEL_2M:
 +              phys_addr = (phys_addr_t)pmd_pfn(*(pmd_t *)pte) << PAGE_SHIFT;
 +              offset = virt_addr & ~PMD_PAGE_MASK;
 +              break;
 +      default:
 +              phys_addr = (phys_addr_t)pte_pfn(*pte) << PAGE_SHIFT;
 +              offset = virt_addr & ~PAGE_MASK;
 +      }
 +
 +      return (phys_addr_t)(phys_addr | offset);
 +}
 +EXPORT_SYMBOL_GPL(slow_virt_to_phys);
 +
 +/*
 + * Set the new pmd in all the pgds we know about:
 + */
 +static void __set_pmd_pte(pte_t *kpte, unsigned long address, pte_t pte)
 +{
 +      /* change init_mm */
 +      set_pte_atomic(kpte, pte);
 +#ifdef CONFIG_X86_32
 +      if (!SHARED_KERNEL_PMD) {
 +              struct page *page;
 +
 +              list_for_each_entry(page, &pgd_list, lru) {
 +                      pgd_t *pgd;
 +                      p4d_t *p4d;
 +                      pud_t *pud;
 +                      pmd_t *pmd;
 +
 +                      pgd = (pgd_t *)page_address(page) + pgd_index(address);
 +                      p4d = p4d_offset(pgd, address);
 +                      pud = pud_offset(p4d, address);
 +                      pmd = pmd_offset(pud, address);
 +                      set_pte_atomic((pte_t *)pmd, pte);
 +              }
 +      }
 +#endif
 +}
 +
 +static pgprot_t pgprot_clear_protnone_bits(pgprot_t prot)
 +{
 +      /*
 +       * _PAGE_GLOBAL means "global page" for present PTEs.
 +       * But, it is also used to indicate _PAGE_PROTNONE
 +       * for non-present PTEs.
 +       *
 +       * This ensures that a _PAGE_GLOBAL PTE going from
 +       * present to non-present is not confused as
 +       * _PAGE_PROTNONE.
 +       */
 +      if (!(pgprot_val(prot) & _PAGE_PRESENT))
 +              pgprot_val(prot) &= ~_PAGE_GLOBAL;
 +
 +      return prot;
 +}
 +
 +static int __should_split_large_page(pte_t *kpte, unsigned long address,
 +                                   struct cpa_data *cpa)
 +{
 +      unsigned long numpages, pmask, psize, lpaddr, pfn, old_pfn;
 +      pgprot_t old_prot, new_prot, req_prot, chk_prot;
 +      pte_t new_pte, *tmp;
 +      enum pg_level level;
 +
 +      /*
 +       * Check for races, another CPU might have split this page
 +       * up already:
 +       */
 +      tmp = _lookup_address_cpa(cpa, address, &level);
 +      if (tmp != kpte)
 +              return 1;
 +
 +      switch (level) {
 +      case PG_LEVEL_2M:
 +              old_prot = pmd_pgprot(*(pmd_t *)kpte);
 +              old_pfn = pmd_pfn(*(pmd_t *)kpte);
 +              cpa_inc_2m_checked();
 +              break;
 +      case PG_LEVEL_1G:
 +              old_prot = pud_pgprot(*(pud_t *)kpte);
 +              old_pfn = pud_pfn(*(pud_t *)kpte);
 +              cpa_inc_1g_checked();
 +              break;
 +      default:
 +              return -EINVAL;
 +      }
 +
 +      psize = page_level_size(level);
 +      pmask = page_level_mask(level);
 +
 +      /*
 +       * Calculate the number of pages, which fit into this large
 +       * page starting at address:
 +       */
 +      lpaddr = (address + psize) & pmask;
 +      numpages = (lpaddr - address) >> PAGE_SHIFT;
 +      if (numpages < cpa->numpages)
 +              cpa->numpages = numpages;
 +
 +      /*
 +       * We are safe now. Check whether the new pgprot is the same:
 +       * Convert protection attributes to 4k-format, as cpa->mask* are set
 +       * up accordingly.
 +       */
 +
 +      /* Clear PSE (aka _PAGE_PAT) and move PAT bit to correct position */
 +      req_prot = pgprot_large_2_4k(old_prot);
 +
 +      pgprot_val(req_prot) &= ~pgprot_val(cpa->mask_clr);
 +      pgprot_val(req_prot) |= pgprot_val(cpa->mask_set);
 +
 +      /*
 +       * req_prot is in format of 4k pages. It must be converted to large
 +       * page format: the caching mode includes the PAT bit located at
 +       * different bit positions in the two formats.
 +       */
 +      req_prot = pgprot_4k_2_large(req_prot);
 +      req_prot = pgprot_clear_protnone_bits(req_prot);
 +      if (pgprot_val(req_prot) & _PAGE_PRESENT)
 +              pgprot_val(req_prot) |= _PAGE_PSE;
 +
 +      /*
 +       * old_pfn points to the large page base pfn. So we need to add the
 +       * offset of the virtual address:
 +       */
 +      pfn = old_pfn + ((address & (psize - 1)) >> PAGE_SHIFT);
 +      cpa->pfn = pfn;
 +
 +      /*
 +       * Calculate the large page base address and the number of 4K pages
 +       * in the large page
 +       */
 +      lpaddr = address & pmask;
 +      numpages = psize >> PAGE_SHIFT;
 +
 +      /*
 +       * Sanity check that the existing mapping is correct versus the static
 +       * protections. static_protections() guards against !PRESENT, so no
 +       * extra conditional required here.
 +       */
 +      chk_prot = static_protections(old_prot, lpaddr, old_pfn, numpages,
 +                                    psize, CPA_CONFLICT);
 +
 +      if (WARN_ON_ONCE(pgprot_val(chk_prot) != pgprot_val(old_prot))) {
 +              /*
 +               * Split the large page and tell the split code to
 +               * enforce static protections.
 +               */
 +              cpa->force_static_prot = 1;
 +              return 1;
 +      }
 +
 +      /*
 +       * Optimization: If the requested pgprot is the same as the current
 +       * pgprot, then the large page can be preserved and no updates are
 +       * required independent of alignment and length of the requested
 +       * range. The above already established that the current pgprot is
 +       * correct, which in consequence makes the requested pgprot correct
 +       * as well if it is the same. The static protection scan below will
 +       * not come to a different conclusion.
 +       */
 +      if (pgprot_val(req_prot) == pgprot_val(old_prot)) {
 +              cpa_inc_lp_sameprot(level);
 +              return 0;
 +      }
 +
 +      /*
 +       * If the requested range does not cover the full page, split it up
 +       */
 +      if (address != lpaddr || cpa->numpages != numpages)
 +              return 1;
 +
 +      /*
 +       * Check whether the requested pgprot is conflicting with a static
 +       * protection requirement in the large page.
 +       */
 +      new_prot = static_protections(req_prot, lpaddr, old_pfn, numpages,
 +                                    psize, CPA_DETECT);
 +
 +      /*
 +       * If there is a conflict, split the large page.
 +       *
 +       * There used to be a 4k wise evaluation trying really hard to
 +       * preserve the large pages, but experimentation has shown, that this
 +       * does not help at all. There might be corner cases which would
 +       * preserve one large page occasionally, but it's really not worth the
 +       * extra code and cycles for the common case.
 +       */
 +      if (pgprot_val(req_prot) != pgprot_val(new_prot))
 +              return 1;
 +
 +      /* All checks passed. Update the large page mapping. */
 +      new_pte = pfn_pte(old_pfn, new_prot);
 +      __set_pmd_pte(kpte, address, new_pte);
 +      cpa->flags |= CPA_FLUSHTLB;
 +      cpa_inc_lp_preserved(level);
 +      return 0;
 +}
 +
 +static int should_split_large_page(pte_t *kpte, unsigned long address,
 +                                 struct cpa_data *cpa)
 +{
 +      int do_split;
 +
 +      if (cpa->force_split)
 +              return 1;
 +
 +      spin_lock(&pgd_lock);
 +      do_split = __should_split_large_page(kpte, address, cpa);
 +      spin_unlock(&pgd_lock);
 +
 +      return do_split;
 +}
 +
 +static void split_set_pte(struct cpa_data *cpa, pte_t *pte, unsigned long pfn,
 +                        pgprot_t ref_prot, unsigned long address,
 +                        unsigned long size)
 +{
 +      unsigned int npg = PFN_DOWN(size);
 +      pgprot_t prot;
 +
 +      /*
 +       * If should_split_large_page() discovered an inconsistent mapping,
 +       * remove the invalid protection in the split mapping.
 +       */
 +      if (!cpa->force_static_prot)
 +              goto set;
 +
 +      /* Hand in lpsize = 0 to enforce the protection mechanism */
 +      prot = static_protections(ref_prot, address, pfn, npg, 0, CPA_PROTECT);
 +
 +      if (pgprot_val(prot) == pgprot_val(ref_prot))
 +              goto set;
 +
 +      /*
 +       * If this is splitting a PMD, fix it up. PUD splits cannot be
 +       * fixed trivially as that would require to rescan the newly
 +       * installed PMD mappings after returning from split_large_page()
 +       * so an eventual further split can allocate the necessary PTE
 +       * pages. Warn for now and revisit it in case this actually
 +       * happens.
 +       */
 +      if (size == PAGE_SIZE)
 +              ref_prot = prot;
 +      else
 +              pr_warn_once("CPA: Cannot fixup static protections for PUD split\n");
 +set:
 +      set_pte(pte, pfn_pte(pfn, ref_prot));
 +}
 +
 +static int
 +__split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
 +                 struct page *base)
 +{
 +      unsigned long lpaddr, lpinc, ref_pfn, pfn, pfninc = 1;
 +      pte_t *pbase = (pte_t *)page_address(base);
 +      unsigned int i, level;
 +      pgprot_t ref_prot;
 +      pte_t *tmp;
 +
 +      spin_lock(&pgd_lock);
 +      /*
 +       * Check for races, another CPU might have split this page
 +       * up for us already:
 +       */
 +      tmp = _lookup_address_cpa(cpa, address, &level);
 +      if (tmp != kpte) {
 +              spin_unlock(&pgd_lock);
 +              return 1;
 +      }
 +
 +      paravirt_alloc_pte(&init_mm, page_to_pfn(base));
 +
 +      switch (level) {
 +      case PG_LEVEL_2M:
 +              ref_prot = pmd_pgprot(*(pmd_t *)kpte);
 +              /*
 +               * Clear PSE (aka _PAGE_PAT) and move
 +               * PAT bit to correct position.
 +               */
 +              ref_prot = pgprot_large_2_4k(ref_prot);
 +              ref_pfn = pmd_pfn(*(pmd_t *)kpte);
 +              lpaddr = address & PMD_MASK;
 +              lpinc = PAGE_SIZE;
 +              break;
 +
 +      case PG_LEVEL_1G:
 +              ref_prot = pud_pgprot(*(pud_t *)kpte);
 +              ref_pfn = pud_pfn(*(pud_t *)kpte);
 +              pfninc = PMD_PAGE_SIZE >> PAGE_SHIFT;
 +              lpaddr = address & PUD_MASK;
 +              lpinc = PMD_SIZE;
 +              /*
 +               * Clear the PSE flags if the PRESENT flag is not set
 +               * otherwise pmd_present/pmd_huge will return true
 +               * even on a non present pmd.
 +               */
 +              if (!(pgprot_val(ref_prot) & _PAGE_PRESENT))
 +                      pgprot_val(ref_prot) &= ~_PAGE_PSE;
 +              break;
 +
 +      default:
 +              spin_unlock(&pgd_lock);
 +              return 1;
 +      }
 +
 +      ref_prot = pgprot_clear_protnone_bits(ref_prot);
 +
 +      /*
 +       * Get the target pfn from the original entry:
 +       */
 +      pfn = ref_pfn;
 +      for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc, lpaddr += lpinc)
 +              split_set_pte(cpa, pbase + i, pfn, ref_prot, lpaddr, lpinc);
 +
 +      if (virt_addr_valid(address)) {
 +              unsigned long pfn = PFN_DOWN(__pa(address));
 +
 +              if (pfn_range_is_mapped(pfn, pfn + 1))
 +                      split_page_count(level);
 +      }
 +
 +      /*
 +       * Install the new, split up pagetable.
 +       *
 +       * We use the standard kernel pagetable protections for the new
 +       * pagetable protections, the actual ptes set above control the
 +       * primary protection behavior:
 +       */
 +      __set_pmd_pte(kpte, address, mk_pte(base, __pgprot(_KERNPG_TABLE)));
 +
 +      /*
 +       * Do a global flush tlb after splitting the large page
 +       * and before we do the actual change page attribute in the PTE.
 +       *
 +       * Without this, we violate the TLB application note, that says:
 +       * "The TLBs may contain both ordinary and large-page
 +       *  translations for a 4-KByte range of linear addresses. This
 +       *  may occur if software modifies the paging structures so that
 +       *  the page size used for the address range changes. If the two
 +       *  translations differ with respect to page frame or attributes
 +       *  (e.g., permissions), processor behavior is undefined and may
 +       *  be implementation-specific."
 +       *
 +       * We do this global tlb flush inside the cpa_lock, so that we
 +       * don't allow any other cpu, with stale tlb entries change the
 +       * page attribute in parallel, that also falls into the
 +       * just split large page entry.
 +       */
 +      flush_tlb_all();
 +      spin_unlock(&pgd_lock);
 +
 +      return 0;
 +}
 +
 +static int split_large_page(struct cpa_data *cpa, pte_t *kpte,
 +                          unsigned long address)
 +{
 +      struct page *base;
 +
 +      if (!debug_pagealloc_enabled())
 +              spin_unlock(&cpa_lock);
 +      base = alloc_pages(GFP_KERNEL, 0);
 +      if (!debug_pagealloc_enabled())
 +              spin_lock(&cpa_lock);
 +      if (!base)
 +              return -ENOMEM;
 +
 +      if (__split_large_page(cpa, kpte, address, base))
 +              __free_page(base);
 +
 +      return 0;
 +}
 +
 +static bool try_to_free_pte_page(pte_t *pte)
 +{
 +      int i;
 +
 +      for (i = 0; i < PTRS_PER_PTE; i++)
 +              if (!pte_none(pte[i]))
 +                      return false;
 +
 +      free_page((unsigned long)pte);
 +      return true;
 +}
 +
 +static bool try_to_free_pmd_page(pmd_t *pmd)
 +{
 +      int i;
 +
 +      for (i = 0; i < PTRS_PER_PMD; i++)
 +              if (!pmd_none(pmd[i]))
 +                      return false;
 +
 +      free_page((unsigned long)pmd);
 +      return true;
 +}
 +
 +static bool unmap_pte_range(pmd_t *pmd, unsigned long start, unsigned long end)
 +{
 +      pte_t *pte = pte_offset_kernel(pmd, start);
 +
 +      while (start < end) {
 +              set_pte(pte, __pte(0));
 +
 +              start += PAGE_SIZE;
 +              pte++;
 +      }
 +
 +      if (try_to_free_pte_page((pte_t *)pmd_page_vaddr(*pmd))) {
 +              pmd_clear(pmd);
 +              return true;
 +      }
 +      return false;
 +}
 +
 +static void __unmap_pmd_range(pud_t *pud, pmd_t *pmd,
 +                            unsigned long start, unsigned long end)
 +{
 +      if (unmap_pte_range(pmd, start, end))
 +              if (try_to_free_pmd_page((pmd_t *)pud_page_vaddr(*pud)))
 +                      pud_clear(pud);
 +}
 +
 +static void unmap_pmd_range(pud_t *pud, unsigned long start, unsigned long end)
 +{
 +      pmd_t *pmd = pmd_offset(pud, start);
 +
 +      /*
 +       * Not on a 2MB page boundary?
 +       */
 +      if (start & (PMD_SIZE - 1)) {
 +              unsigned long next_page = (start + PMD_SIZE) & PMD_MASK;
 +              unsigned long pre_end = min_t(unsigned long, end, next_page);
 +
 +              __unmap_pmd_range(pud, pmd, start, pre_end);
 +
 +              start = pre_end;
 +              pmd++;
 +      }
 +
 +      /*
 +       * Try to unmap in 2M chunks.
 +       */
 +      while (end - start >= PMD_SIZE) {
 +              if (pmd_large(*pmd))
 +                      pmd_clear(pmd);
 +              else
 +                      __unmap_pmd_range(pud, pmd, start, start + PMD_SIZE);
 +
 +              start += PMD_SIZE;
 +              pmd++;
 +      }
 +
 +      /*
 +       * 4K leftovers?
 +       */
 +      if (start < end)
 +              return __unmap_pmd_range(pud, pmd, start, end);
 +
 +      /*
 +       * Try again to free the PMD page if haven't succeeded above.
 +       */
 +      if (!pud_none(*pud))
 +              if (try_to_free_pmd_page((pmd_t *)pud_page_vaddr(*pud)))
 +                      pud_clear(pud);
 +}
 +
 +static void unmap_pud_range(p4d_t *p4d, unsigned long start, unsigned long end)
 +{
 +      pud_t *pud = pud_offset(p4d, start);
 +
 +      /*
 +       * Not on a GB page boundary?
 +       */
 +      if (start & (PUD_SIZE - 1)) {
 +              unsigned long next_page = (start + PUD_SIZE) & PUD_MASK;
 +              unsigned long pre_end   = min_t(unsigned long, end, next_page);
 +
 +              unmap_pmd_range(pud, start, pre_end);
 +
 +              start = pre_end;
 +              pud++;
 +      }
 +
 +      /*
 +       * Try to unmap in 1G chunks?
 +       */
 +      while (end - start >= PUD_SIZE) {
 +
 +              if (pud_large(*pud))
 +                      pud_clear(pud);
 +              else
 +                      unmap_pmd_range(pud, start, start + PUD_SIZE);
 +
 +              start += PUD_SIZE;
 +              pud++;
 +      }
 +
 +      /*
 +       * 2M leftovers?
 +       */
 +      if (start < end)
 +              unmap_pmd_range(pud, start, end);
 +
 +      /*
 +       * No need to try to free the PUD page because we'll free it in
 +       * populate_pgd's error path
 +       */
 +}
 +
 +static int alloc_pte_page(pmd_t *pmd)
 +{
 +      pte_t *pte = (pte_t *)get_zeroed_page(GFP_KERNEL);
 +      if (!pte)
 +              return -1;
 +
 +      set_pmd(pmd, __pmd(__pa(pte) | _KERNPG_TABLE));
 +      return 0;
 +}
 +
 +static int alloc_pmd_page(pud_t *pud)
 +{
 +      pmd_t *pmd = (pmd_t *)get_zeroed_page(GFP_KERNEL);
 +      if (!pmd)
 +              return -1;
 +
 +      set_pud(pud, __pud(__pa(pmd) | _KERNPG_TABLE));
 +      return 0;
 +}
 +
 +static void populate_pte(struct cpa_data *cpa,
 +                       unsigned long start, unsigned long end,
 +                       unsigned num_pages, pmd_t *pmd, pgprot_t pgprot)
 +{
 +      pte_t *pte;
 +
 +      pte = pte_offset_kernel(pmd, start);
 +
 +      pgprot = pgprot_clear_protnone_bits(pgprot);
 +
 +      while (num_pages-- && start < end) {
 +              set_pte(pte, pfn_pte(cpa->pfn, pgprot));
 +
 +              start    += PAGE_SIZE;
 +              cpa->pfn++;
 +              pte++;
 +      }
 +}
 +
 +static long populate_pmd(struct cpa_data *cpa,
 +                       unsigned long start, unsigned long end,
 +                       unsigned num_pages, pud_t *pud, pgprot_t pgprot)
 +{
 +      long cur_pages = 0;
 +      pmd_t *pmd;
 +      pgprot_t pmd_pgprot;
 +
 +      /*
 +       * Not on a 2M boundary?
 +       */
 +      if (start & (PMD_SIZE - 1)) {
 +              unsigned long pre_end = start + (num_pages << PAGE_SHIFT);
 +              unsigned long next_page = (start + PMD_SIZE) & PMD_MASK;
 +
 +              pre_end   = min_t(unsigned long, pre_end, next_page);
 +              cur_pages = (pre_end - start) >> PAGE_SHIFT;
 +              cur_pages = min_t(unsigned int, num_pages, cur_pages);
 +
 +              /*
 +               * Need a PTE page?
 +               */
 +              pmd = pmd_offset(pud, start);
 +              if (pmd_none(*pmd))
 +                      if (alloc_pte_page(pmd))
 +                              return -1;
 +
 +              populate_pte(cpa, start, pre_end, cur_pages, pmd, pgprot);
 +
 +              start = pre_end;
 +      }
 +
 +      /*
 +       * We mapped them all?
 +       */
 +      if (num_pages == cur_pages)
 +              return cur_pages;
 +
 +      pmd_pgprot = pgprot_4k_2_large(pgprot);
 +
 +      while (end - start >= PMD_SIZE) {
 +
 +              /*
 +               * We cannot use a 1G page so allocate a PMD page if needed.
 +               */
 +              if (pud_none(*pud))
 +                      if (alloc_pmd_page(pud))
 +                              return -1;
 +
 +              pmd = pmd_offset(pud, start);
 +
 +              set_pmd(pmd, pmd_mkhuge(pfn_pmd(cpa->pfn,
 +                                      canon_pgprot(pmd_pgprot))));
 +
 +              start     += PMD_SIZE;
 +              cpa->pfn  += PMD_SIZE >> PAGE_SHIFT;
 +              cur_pages += PMD_SIZE >> PAGE_SHIFT;
 +      }
 +
 +      /*
 +       * Map trailing 4K pages.
 +       */
 +      if (start < end) {
 +              pmd = pmd_offset(pud, start);
 +              if (pmd_none(*pmd))
 +                      if (alloc_pte_page(pmd))
 +                              return -1;
 +
 +              populate_pte(cpa, start, end, num_pages - cur_pages,
 +                           pmd, pgprot);
 +      }
 +      return num_pages;
 +}
 +
 +static int populate_pud(struct cpa_data *cpa, unsigned long start, p4d_t *p4d,
 +                      pgprot_t pgprot)
 +{
 +      pud_t *pud;
 +      unsigned long end;
 +      long cur_pages = 0;
 +      pgprot_t pud_pgprot;
 +
 +      end = start + (cpa->numpages << PAGE_SHIFT);
 +
 +      /*
 +       * Not on a Gb page boundary? => map everything up to it with
 +       * smaller pages.
 +       */
 +      if (start & (PUD_SIZE - 1)) {
 +              unsigned long pre_end;
 +              unsigned long next_page = (start + PUD_SIZE) & PUD_MASK;
 +
 +              pre_end   = min_t(unsigned long, end, next_page);
 +              cur_pages = (pre_end - start) >> PAGE_SHIFT;
 +              cur_pages = min_t(int, (int)cpa->numpages, cur_pages);
 +
 +              pud = pud_offset(p4d, start);
 +
 +              /*
 +               * Need a PMD page?
 +               */
 +              if (pud_none(*pud))
 +                      if (alloc_pmd_page(pud))
 +                              return -1;
 +
 +              cur_pages = populate_pmd(cpa, start, pre_end, cur_pages,
 +                                       pud, pgprot);
 +              if (cur_pages < 0)
 +                      return cur_pages;
 +
 +              start = pre_end;
 +      }
 +
 +      /* We mapped them all? */
 +      if (cpa->numpages == cur_pages)
 +              return cur_pages;
 +
 +      pud = pud_offset(p4d, start);
 +      pud_pgprot = pgprot_4k_2_large(pgprot);
 +
 +      /*
 +       * Map everything starting from the Gb boundary, possibly with 1G pages
 +       */
 +      while (boot_cpu_has(X86_FEATURE_GBPAGES) && end - start >= PUD_SIZE) {
 +              set_pud(pud, pud_mkhuge(pfn_pud(cpa->pfn,
 +                                 canon_pgprot(pud_pgprot))));
 +
 +              start     += PUD_SIZE;
 +              cpa->pfn  += PUD_SIZE >> PAGE_SHIFT;
 +              cur_pages += PUD_SIZE >> PAGE_SHIFT;
 +              pud++;
 +      }
 +
 +      /* Map trailing leftover */
 +      if (start < end) {
 +              long tmp;
 +
 +              pud = pud_offset(p4d, start);
 +              if (pud_none(*pud))
 +                      if (alloc_pmd_page(pud))
 +                              return -1;
 +
 +              tmp = populate_pmd(cpa, start, end, cpa->numpages - cur_pages,
 +                                 pud, pgprot);
 +              if (tmp < 0)
 +                      return cur_pages;
 +
 +              cur_pages += tmp;
 +      }
 +      return cur_pages;
 +}
 +
 +/*
 + * Restrictions for kernel page table do not necessarily apply when mapping in
 + * an alternate PGD.
 + */
 +static int populate_pgd(struct cpa_data *cpa, unsigned long addr)
 +{
 +      pgprot_t pgprot = __pgprot(_KERNPG_TABLE);
 +      pud_t *pud = NULL;      /* shut up gcc */
 +      p4d_t *p4d;
 +      pgd_t *pgd_entry;
 +      long ret;
 +
 +      pgd_entry = cpa->pgd + pgd_index(addr);
 +
 +      if (pgd_none(*pgd_entry)) {
 +              p4d = (p4d_t *)get_zeroed_page(GFP_KERNEL);
 +              if (!p4d)
 +                      return -1;
 +
 +              set_pgd(pgd_entry, __pgd(__pa(p4d) | _KERNPG_TABLE));
 +      }
 +
 +      /*
 +       * Allocate a PUD page and hand it down for mapping.
 +       */
 +      p4d = p4d_offset(pgd_entry, addr);
 +      if (p4d_none(*p4d)) {
 +              pud = (pud_t *)get_zeroed_page(GFP_KERNEL);
 +              if (!pud)
 +                      return -1;
 +
 +              set_p4d(p4d, __p4d(__pa(pud) | _KERNPG_TABLE));
 +      }
 +
 +      pgprot_val(pgprot) &= ~pgprot_val(cpa->mask_clr);
 +      pgprot_val(pgprot) |=  pgprot_val(cpa->mask_set);
 +
 +      ret = populate_pud(cpa, addr, p4d, pgprot);
 +      if (ret < 0) {
 +              /*
 +               * Leave the PUD page in place in case some other CPU or thread
 +               * already found it, but remove any useless entries we just
 +               * added to it.
 +               */
 +              unmap_pud_range(p4d, addr,
 +                              addr + (cpa->numpages << PAGE_SHIFT));
 +              return ret;
 +      }
 +
 +      cpa->numpages = ret;
 +      return 0;
 +}
 +
 +static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr,
 +                             int primary)
 +{
 +      if (cpa->pgd) {
 +              /*
 +               * Right now, we only execute this code path when mapping
 +               * the EFI virtual memory map regions, no other users
 +               * provide a ->pgd value. This may change in the future.
 +               */
 +              return populate_pgd(cpa, vaddr);
 +      }
 +
 +      /*
 +       * Ignore all non primary paths.
 +       */
 +      if (!primary) {
 +              cpa->numpages = 1;
 +              return 0;
 +      }
 +
 +      /*
 +       * Ignore the NULL PTE for kernel identity mapping, as it is expected
 +       * to have holes.
 +       * Also set numpages to '1' indicating that we processed cpa req for
 +       * one virtual address page and its pfn. TBD: numpages can be set based
 +       * on the initial value and the level returned by lookup_address().
 +       */
 +      if (within(vaddr, PAGE_OFFSET,
 +                 PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT))) {
 +              cpa->numpages = 1;
 +              cpa->pfn = __pa(vaddr) >> PAGE_SHIFT;
 +              return 0;
 +
 +      } else if (__cpa_pfn_in_highmap(cpa->pfn)) {
 +              /* Faults in the highmap are OK, so do not warn: */
 +              return -EFAULT;
 +      } else {
 +              WARN(1, KERN_WARNING "CPA: called for zero pte. "
 +                      "vaddr = %lx cpa->vaddr = %lx\n", vaddr,
 +                      *cpa->vaddr);
 +
 +              return -EFAULT;
 +      }
 +}
 +
 +static int __change_page_attr(struct cpa_data *cpa, int primary)
 +{
 +      unsigned long address;
 +      int do_split, err;
 +      unsigned int level;
 +      pte_t *kpte, old_pte;
 +
 +      address = __cpa_addr(cpa, cpa->curpage);
 +repeat:
 +      kpte = _lookup_address_cpa(cpa, address, &level);
 +      if (!kpte)
 +              return __cpa_process_fault(cpa, address, primary);
 +
 +      old_pte = *kpte;
 +      if (pte_none(old_pte))
 +              return __cpa_process_fault(cpa, address, primary);
 +
 +      if (level == PG_LEVEL_4K) {
 +              pte_t new_pte;
 +              pgprot_t new_prot = pte_pgprot(old_pte);
 +              unsigned long pfn = pte_pfn(old_pte);
 +
 +              pgprot_val(new_prot) &= ~pgprot_val(cpa->mask_clr);
 +              pgprot_val(new_prot) |= pgprot_val(cpa->mask_set);
 +
 +              cpa_inc_4k_install();
 +              /* Hand in lpsize = 0 to enforce the protection mechanism */
 +              new_prot = static_protections(new_prot, address, pfn, 1, 0,
 +                                            CPA_PROTECT);
 +
 +              new_prot = pgprot_clear_protnone_bits(new_prot);
 +
 +              /*
 +               * We need to keep the pfn from the existing PTE,
 +               * after all we're only going to change it's attributes
 +               * not the memory it points to
 +               */
 +              new_pte = pfn_pte(pfn, new_prot);
 +              cpa->pfn = pfn;
 +              /*
 +               * Do we really change anything ?
 +               */
 +              if (pte_val(old_pte) != pte_val(new_pte)) {
 +                      set_pte_atomic(kpte, new_pte);
 +                      cpa->flags |= CPA_FLUSHTLB;
 +              }
 +              cpa->numpages = 1;
 +              return 0;
 +      }
 +
 +      /*
 +       * Check, whether we can keep the large page intact
 +       * and just change the pte:
 +       */
 +      do_split = should_split_large_page(kpte, address, cpa);
 +      /*
 +       * When the range fits into the existing large page,
 +       * return. cp->numpages and cpa->tlbflush have been updated in
 +       * try_large_page:
 +       */
 +      if (do_split <= 0)
 +              return do_split;
 +
 +      /*
 +       * We have to split the large page:
 +       */
 +      err = split_large_page(cpa, kpte, address);
 +      if (!err)
 +              goto repeat;
 +
 +      return err;
 +}
 +
 +static int __change_page_attr_set_clr(struct cpa_data *cpa, int checkalias);
 +
 +static int cpa_process_alias(struct cpa_data *cpa)
 +{
 +      struct cpa_data alias_cpa;
 +      unsigned long laddr = (unsigned long)__va(cpa->pfn << PAGE_SHIFT);
 +      unsigned long vaddr;
 +      int ret;
 +
 +      if (!pfn_range_is_mapped(cpa->pfn, cpa->pfn + 1))
 +              return 0;
 +
 +      /*
 +       * No need to redo, when the primary call touched the direct
 +       * mapping already:
 +       */
 +      vaddr = __cpa_addr(cpa, cpa->curpage);
 +      if (!(within(vaddr, PAGE_OFFSET,
 +                  PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))) {
 +
 +              alias_cpa = *cpa;
 +              alias_cpa.vaddr = &laddr;
 +              alias_cpa.flags &= ~(CPA_PAGES_ARRAY | CPA_ARRAY);
 +              alias_cpa.curpage = 0;
 +
 +              ret = __change_page_attr_set_clr(&alias_cpa, 0);
 +              if (ret)
 +                      return ret;
 +      }
 +
 +#ifdef CONFIG_X86_64
 +      /*
 +       * If the primary call didn't touch the high mapping already
 +       * and the physical address is inside the kernel map, we need
 +       * to touch the high mapped kernel as well:
 +       */
 +      if (!within(vaddr, (unsigned long)_text, _brk_end) &&
 +          __cpa_pfn_in_highmap(cpa->pfn)) {
 +              unsigned long temp_cpa_vaddr = (cpa->pfn << PAGE_SHIFT) +
 +                                             __START_KERNEL_map - phys_base;
 +              alias_cpa = *cpa;
 +              alias_cpa.vaddr = &temp_cpa_vaddr;
 +              alias_cpa.flags &= ~(CPA_PAGES_ARRAY | CPA_ARRAY);
 +              alias_cpa.curpage = 0;
 +
 +              /*
 +               * The high mapping range is imprecise, so ignore the
 +               * return value.
 +               */
 +              __change_page_attr_set_clr(&alias_cpa, 0);
 +      }
 +#endif
 +
 +      return 0;
 +}
 +
 +static int __change_page_attr_set_clr(struct cpa_data *cpa, int checkalias)
 +{
 +      unsigned long numpages = cpa->numpages;
 +      unsigned long rempages = numpages;
 +      int ret = 0;
 +
 +      while (rempages) {
 +              /*
 +               * Store the remaining nr of pages for the large page
 +               * preservation check.
 +               */
 +              cpa->numpages = rempages;
 +              /* for array changes, we can't use large page */
 +              if (cpa->flags & (CPA_ARRAY | CPA_PAGES_ARRAY))
 +                      cpa->numpages = 1;
 +
 +              if (!debug_pagealloc_enabled())
 +                      spin_lock(&cpa_lock);
 +              ret = __change_page_attr(cpa, checkalias);
 +              if (!debug_pagealloc_enabled())
 +                      spin_unlock(&cpa_lock);
 +              if (ret)
 +                      goto out;
 +
 +              if (checkalias) {
 +                      ret = cpa_process_alias(cpa);
 +                      if (ret)
 +                              goto out;
 +              }
 +
 +              /*
 +               * Adjust the number of pages with the result of the
 +               * CPA operation. Either a large page has been
 +               * preserved or a single page update happened.
 +               */
 +              BUG_ON(cpa->numpages > rempages || !cpa->numpages);
 +              rempages -= cpa->numpages;
 +              cpa->curpage += cpa->numpages;
 +      }
 +
 +out:
 +      /* Restore the original numpages */
 +      cpa->numpages = numpages;
 +      return ret;
 +}
 +
 +static int change_page_attr_set_clr(unsigned long *addr, int numpages,
 +                                  pgprot_t mask_set, pgprot_t mask_clr,
 +                                  int force_split, int in_flag,
 +                                  struct page **pages)
 +{
 +      struct cpa_data cpa;
 +      int ret, cache, checkalias;
 +
 +      memset(&cpa, 0, sizeof(cpa));
 +
 +      /*
 +       * Check, if we are requested to set a not supported
 +       * feature.  Clearing non-supported features is OK.
 +       */
 +      mask_set = canon_pgprot(mask_set);
 +
 +      if (!pgprot_val(mask_set) && !pgprot_val(mask_clr) && !force_split)
 +              return 0;
 +
 +      /* Ensure we are PAGE_SIZE aligned */
 +      if (in_flag & CPA_ARRAY) {
 +              int i;
 +              for (i = 0; i < numpages; i++) {
 +                      if (addr[i] & ~PAGE_MASK) {
 +                              addr[i] &= PAGE_MASK;
 +                              WARN_ON_ONCE(1);
 +                      }
 +              }
 +      } else if (!(in_flag & CPA_PAGES_ARRAY)) {
 +              /*
 +               * in_flag of CPA_PAGES_ARRAY implies it is aligned.
 +               * No need to check in that case
 +               */
 +              if (*addr & ~PAGE_MASK) {
 +                      *addr &= PAGE_MASK;
 +                      /*
 +                       * People should not be passing in unaligned addresses:
 +                       */
 +                      WARN_ON_ONCE(1);
 +              }
 +      }
 +
 +      /* Must avoid aliasing mappings in the highmem code */
 +      kmap_flush_unused();
 +
 +      vm_unmap_aliases();
 +
 +      cpa.vaddr = addr;
 +      cpa.pages = pages;
 +      cpa.numpages = numpages;
 +      cpa.mask_set = mask_set;
 +      cpa.mask_clr = mask_clr;
 +      cpa.flags = 0;
 +      cpa.curpage = 0;
 +      cpa.force_split = force_split;
 +
 +      if (in_flag & (CPA_ARRAY | CPA_PAGES_ARRAY))
 +              cpa.flags |= in_flag;
 +
 +      /* No alias checking for _NX bit modifications */
 +      checkalias = (pgprot_val(mask_set) | pgprot_val(mask_clr)) != _PAGE_NX;
 +      /* Has caller explicitly disabled alias checking? */
 +      if (in_flag & CPA_NO_CHECK_ALIAS)
 +              checkalias = 0;
 +
 +      ret = __change_page_attr_set_clr(&cpa, checkalias);
 +
 +      /*
 +       * Check whether we really changed something:
 +       */
 +      if (!(cpa.flags & CPA_FLUSHTLB))
 +              goto out;
 +
 +      /*
 +       * No need to flush, when we did not set any of the caching
 +       * attributes:
 +       */
 +      cache = !!pgprot2cachemode(mask_set);
 +
 +      /*
 +       * On error; flush everything to be sure.
 +       */
 +      if (ret) {
 +              cpa_flush_all(cache);
 +              goto out;
 +      }
 +
 +      cpa_flush(&cpa, cache);
 +out:
 +      return ret;
 +}
 +
 +static inline int change_page_attr_set(unsigned long *addr, int numpages,
 +                                     pgprot_t mask, int array)
 +{
 +      return change_page_attr_set_clr(addr, numpages, mask, __pgprot(0), 0,
 +              (array ? CPA_ARRAY : 0), NULL);
 +}
 +
 +static inline int change_page_attr_clear(unsigned long *addr, int numpages,
 +                                       pgprot_t mask, int array)
 +{
 +      return change_page_attr_set_clr(addr, numpages, __pgprot(0), mask, 0,
 +              (array ? CPA_ARRAY : 0), NULL);
 +}
 +
 +static inline int cpa_set_pages_array(struct page **pages, int numpages,
 +                                     pgprot_t mask)
 +{
 +      return change_page_attr_set_clr(NULL, numpages, mask, __pgprot(0), 0,
 +              CPA_PAGES_ARRAY, pages);
 +}
 +
 +static inline int cpa_clear_pages_array(struct page **pages, int numpages,
 +                                       pgprot_t mask)
 +{
 +      return change_page_attr_set_clr(NULL, numpages, __pgprot(0), mask, 0,
 +              CPA_PAGES_ARRAY, pages);
 +}
 +
 +int _set_memory_uc(unsigned long addr, int numpages)
 +{
 +      /*
 +       * for now UC MINUS. see comments in ioremap()
 +       * If you really need strong UC use ioremap_uc(), but note
 +       * that you cannot override IO areas with set_memory_*() as
 +       * these helpers cannot work with IO memory.
 +       */
 +      return change_page_attr_set(&addr, numpages,
 +                                  cachemode2pgprot(_PAGE_CACHE_MODE_UC_MINUS),
 +                                  0);
 +}
 +
 +int set_memory_uc(unsigned long addr, int numpages)
 +{
 +      int ret;
 +
 +      /*
 +       * for now UC MINUS. see comments in ioremap()
 +       */
 +      ret = memtype_reserve(__pa(addr), __pa(addr) + numpages * PAGE_SIZE,
 +                            _PAGE_CACHE_MODE_UC_MINUS, NULL);
 +      if (ret)
 +              goto out_err;
 +
 +      ret = _set_memory_uc(addr, numpages);
 +      if (ret)
 +              goto out_free;
 +
 +      return 0;
 +
 +out_free:
 +      memtype_free(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
 +out_err:
 +      return ret;
 +}
 +EXPORT_SYMBOL(set_memory_uc);
 +
 +int _set_memory_wc(unsigned long addr, int numpages)
 +{
 +      int ret;
 +
 +      ret = change_page_attr_set(&addr, numpages,
 +                                 cachemode2pgprot(_PAGE_CACHE_MODE_UC_MINUS),
 +                                 0);
 +      if (!ret) {
 +              ret = change_page_attr_set_clr(&addr, numpages,
 +                                             cachemode2pgprot(_PAGE_CACHE_MODE_WC),
 +                                             __pgprot(_PAGE_CACHE_MASK),
 +                                             0, 0, NULL);
 +      }
 +      return ret;
 +}
 +
 +int set_memory_wc(unsigned long addr, int numpages)
 +{
 +      int ret;
 +
 +      ret = memtype_reserve(__pa(addr), __pa(addr) + numpages * PAGE_SIZE,
 +              _PAGE_CACHE_MODE_WC, NULL);
 +      if (ret)
 +              return ret;
 +
 +      ret = _set_memory_wc(addr, numpages);
 +      if (ret)
 +              memtype_free(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
 +
 +      return ret;
 +}
 +EXPORT_SYMBOL(set_memory_wc);
 +
 +int _set_memory_wt(unsigned long addr, int numpages)
 +{
 +      return change_page_attr_set(&addr, numpages,
 +                                  cachemode2pgprot(_PAGE_CACHE_MODE_WT), 0);
 +}
 +
 +int _set_memory_wb(unsigned long addr, int numpages)
 +{
 +      /* WB cache mode is hard wired to all cache attribute bits being 0 */
 +      return change_page_attr_clear(&addr, numpages,
 +                                    __pgprot(_PAGE_CACHE_MASK), 0);
 +}
 +
 +int set_memory_wb(unsigned long addr, int numpages)
 +{
 +      int ret;
 +
 +      ret = _set_memory_wb(addr, numpages);
 +      if (ret)
 +              return ret;
 +
 +      memtype_free(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
 +      return 0;
 +}
 +EXPORT_SYMBOL(set_memory_wb);
 +
 +int set_memory_x(unsigned long addr, int numpages)
 +{
 +      if (!(__supported_pte_mask & _PAGE_NX))
 +              return 0;
 +
 +      return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_NX), 0);
 +}
 +
 +int set_memory_nx(unsigned long addr, int numpages)
 +{
 +      if (!(__supported_pte_mask & _PAGE_NX))
 +              return 0;
 +
 +      return change_page_attr_set(&addr, numpages, __pgprot(_PAGE_NX), 0);
 +}
 +
 +int set_memory_ro(unsigned long addr, int numpages)
 +{
 +      return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_RW), 0);
 +}
 +
 +int set_memory_rw(unsigned long addr, int numpages)
 +{
 +      return change_page_attr_set(&addr, numpages, __pgprot(_PAGE_RW), 0);
 +}
 +
 +int set_memory_np(unsigned long addr, int numpages)
 +{
 +      return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_PRESENT), 0);
 +}
 +
 +int set_memory_np_noalias(unsigned long addr, int numpages)
 +{
 +      int cpa_flags = CPA_NO_CHECK_ALIAS;
 +
 +      return change_page_attr_set_clr(&addr, numpages, __pgprot(0),
 +                                      __pgprot(_PAGE_PRESENT), 0,
 +                                      cpa_flags, NULL);
 +}
 +
 +int set_memory_4k(unsigned long addr, int numpages)
 +{
 +      return change_page_attr_set_clr(&addr, numpages, __pgprot(0),
 +                                      __pgprot(0), 1, 0, NULL);
 +}
 +
 +int set_memory_nonglobal(unsigned long addr, int numpages)
 +{
 +      return change_page_attr_clear(&addr, numpages,
 +                                    __pgprot(_PAGE_GLOBAL), 0);
 +}
 +
 +int set_memory_global(unsigned long addr, int numpages)
 +{
 +      return change_page_attr_set(&addr, numpages,
 +                                  __pgprot(_PAGE_GLOBAL), 0);
 +}
 +
 +static int __set_memory_enc_dec(unsigned long addr, int numpages, bool enc)
 +{
 +      struct cpa_data cpa;
 +      int ret;
 +
 +      /* Nothing to do if memory encryption is not active */
 +      if (!mem_encrypt_active())
 +              return 0;
 +
 +      /* Should not be working on unaligned addresses */
 +      if (WARN_ONCE(addr & ~PAGE_MASK, "misaligned address: %#lx\n", addr))
 +              addr &= PAGE_MASK;
 +
 +      memset(&cpa, 0, sizeof(cpa));
 +      cpa.vaddr = &addr;
 +      cpa.numpages = numpages;
 +      cpa.mask_set = enc ? __pgprot(_PAGE_ENC) : __pgprot(0);
 +      cpa.mask_clr = enc ? __pgprot(0) : __pgprot(_PAGE_ENC);
 +      cpa.pgd = init_mm.pgd;
 +
 +      /* Must avoid aliasing mappings in the highmem code */
 +      kmap_flush_unused();
 +      vm_unmap_aliases();
 +
 +      /*
 +       * Before changing the encryption attribute, we need to flush caches.
 +       */
 +      cpa_flush(&cpa, 1);
 +
 +      ret = __change_page_attr_set_clr(&cpa, 1);
 +
 +      /*
 +       * After changing the encryption attribute, we need to flush TLBs again
 +       * in case any speculative TLB caching occurred (but no need to flush
 +       * caches again).  We could just use cpa_flush_all(), but in case TLB
 +       * flushing gets optimized in the cpa_flush() path use the same logic
 +       * as above.
 +       */
 +      cpa_flush(&cpa, 0);
 +
 +      return ret;
 +}
 +
 +int set_memory_encrypted(unsigned long addr, int numpages)
 +{
 +      return __set_memory_enc_dec(addr, numpages, true);
 +}
 +EXPORT_SYMBOL_GPL(set_memory_encrypted);
 +
 +int set_memory_decrypted(unsigned long addr, int numpages)
 +{
 +      return __set_memory_enc_dec(addr, numpages, false);
 +}
 +EXPORT_SYMBOL_GPL(set_memory_decrypted);
 +
 +int set_pages_uc(struct page *page, int numpages)
 +{
 +      unsigned long addr = (unsigned long)page_address(page);
 +
 +      return set_memory_uc(addr, numpages);
 +}
 +EXPORT_SYMBOL(set_pages_uc);
 +
 +static int _set_pages_array(struct page **pages, int numpages,
 +              enum page_cache_mode new_type)
 +{
 +      unsigned long start;
 +      unsigned long end;
 +      enum page_cache_mode set_type;
 +      int i;
 +      int free_idx;
 +      int ret;
 +
 +      for (i = 0; i < numpages; i++) {
 +              if (PageHighMem(pages[i]))
 +                      continue;
 +              start = page_to_pfn(pages[i]) << PAGE_SHIFT;
 +              end = start + PAGE_SIZE;
 +              if (memtype_reserve(start, end, new_type, NULL))
 +                      goto err_out;
 +      }
 +
 +      /* If WC, set to UC- first and then WC */
 +      set_type = (new_type == _PAGE_CACHE_MODE_WC) ?
 +                              _PAGE_CACHE_MODE_UC_MINUS : new_type;
 +
 +      ret = cpa_set_pages_array(pages, numpages,
 +                                cachemode2pgprot(set_type));
 +      if (!ret && new_type == _PAGE_CACHE_MODE_WC)
 +              ret = change_page_attr_set_clr(NULL, numpages,
 +                                             cachemode2pgprot(
 +                                              _PAGE_CACHE_MODE_WC),
 +                                             __pgprot(_PAGE_CACHE_MASK),
 +                                             0, CPA_PAGES_ARRAY, pages);
 +      if (ret)
 +              goto err_out;
 +      return 0; /* Success */
 +err_out:
 +      free_idx = i;
 +      for (i = 0; i < free_idx; i++) {
 +              if (PageHighMem(pages[i]))
 +                      continue;
 +              start = page_to_pfn(pages[i]) << PAGE_SHIFT;
 +              end = start + PAGE_SIZE;
 +              memtype_free(start, end);
 +      }
 +      return -EINVAL;
 +}
 +
 +int set_pages_array_uc(struct page **pages, int numpages)
 +{
 +      return _set_pages_array(pages, numpages, _PAGE_CACHE_MODE_UC_MINUS);
 +}
 +EXPORT_SYMBOL(set_pages_array_uc);
 +
 +int set_pages_array_wc(struct page **pages, int numpages)
 +{
 +      return _set_pages_array(pages, numpages, _PAGE_CACHE_MODE_WC);
 +}
 +EXPORT_SYMBOL(set_pages_array_wc);
 +
 +int set_pages_array_wt(struct page **pages, int numpages)
 +{
 +      return _set_pages_array(pages, numpages, _PAGE_CACHE_MODE_WT);
 +}
 +EXPORT_SYMBOL_GPL(set_pages_array_wt);
 +
 +int set_pages_wb(struct page *page, int numpages)
 +{
 +      unsigned long addr = (unsigned long)page_address(page);
 +
 +      return set_memory_wb(addr, numpages);
 +}
 +EXPORT_SYMBOL(set_pages_wb);
 +
 +int set_pages_array_wb(struct page **pages, int numpages)
 +{
 +      int retval;
 +      unsigned long start;
 +      unsigned long end;
 +      int i;
 +
 +      /* WB cache mode is hard wired to all cache attribute bits being 0 */
 +      retval = cpa_clear_pages_array(pages, numpages,
 +                      __pgprot(_PAGE_CACHE_MASK));
 +      if (retval)
 +              return retval;
 +
 +      for (i = 0; i < numpages; i++) {
 +              if (PageHighMem(pages[i]))
 +                      continue;
 +              start = page_to_pfn(pages[i]) << PAGE_SHIFT;
 +              end = start + PAGE_SIZE;
 +              memtype_free(start, end);
 +      }
 +
 +      return 0;
 +}
 +EXPORT_SYMBOL(set_pages_array_wb);
 +
 +int set_pages_ro(struct page *page, int numpages)
 +{
 +      unsigned long addr = (unsigned long)page_address(page);
 +
 +      return set_memory_ro(addr, numpages);
 +}
 +
 +int set_pages_rw(struct page *page, int numpages)
 +{
 +      unsigned long addr = (unsigned long)page_address(page);
 +
 +      return set_memory_rw(addr, numpages);
 +}
 +
 +static int __set_pages_p(struct page *page, int numpages)
 +{
 +      unsigned long tempaddr = (unsigned long) page_address(page);
 +      struct cpa_data cpa = { .vaddr = &tempaddr,
 +                              .pgd = NULL,
 +                              .numpages = numpages,
 +                              .mask_set = __pgprot(_PAGE_PRESENT | _PAGE_RW),
 +                              .mask_clr = __pgprot(0),
 +                              .flags = 0};
 +
 +      /*
 +       * No alias checking needed for setting present flag. otherwise,
 +       * we may need to break large pages for 64-bit kernel text
 +       * mappings (this adds to complexity if we want to do this from
 +       * atomic context especially). Let's keep it simple!
 +       */
 +      return __change_page_attr_set_clr(&cpa, 0);
 +}
 +
 +static int __set_pages_np(struct page *page, int numpages)
 +{
 +      unsigned long tempaddr = (unsigned long) page_address(page);
 +      struct cpa_data cpa = { .vaddr = &tempaddr,
 +                              .pgd = NULL,
 +                              .numpages = numpages,
 +                              .mask_set = __pgprot(0),
 +                              .mask_clr = __pgprot(_PAGE_PRESENT | _PAGE_RW),
 +                              .flags = 0};
 +
 +      /*
 +       * No alias checking needed for setting not present flag. otherwise,
 +       * we may need to break large pages for 64-bit kernel text
 +       * mappings (this adds to complexity if we want to do this from
 +       * atomic context especially). Let's keep it simple!
 +       */
 +      return __change_page_attr_set_clr(&cpa, 0);
 +}
 +
 +int set_direct_map_invalid_noflush(struct page *page)
 +{
 +      return __set_pages_np(page, 1);
 +}
 +
 +int set_direct_map_default_noflush(struct page *page)
 +{
 +      return __set_pages_p(page, 1);
 +}
 +
 +void __kernel_map_pages(struct page *page, int numpages, int enable)
 +{
 +      if (PageHighMem(page))
 +              return;
 +      if (!enable) {
 +              debug_check_no_locks_freed(page_address(page),
 +                                         numpages * PAGE_SIZE);
 +      }
 +
 +      /*
 +       * The return value is ignored as the calls cannot fail.
 +       * Large pages for identity mappings are not used at boot time
 +       * and hence no memory allocations during large page split.
 +       */
 +      if (enable)
 +              __set_pages_p(page, numpages);
 +      else
 +              __set_pages_np(page, numpages);
 +
 +      /*
 +       * We should perform an IPI and flush all tlbs,
 +       * but that can deadlock->flush only current cpu.
 +       * Preemption needs to be disabled around __flush_tlb_all() due to
 +       * CR3 reload in __native_flush_tlb().
 +       */
 +      preempt_disable();
 +      __flush_tlb_all();
 +      preempt_enable();
 +
 +      arch_flush_lazy_mmu_mode();
 +}
 +
 +#ifdef CONFIG_HIBERNATION
 +bool kernel_page_present(struct page *page)
 +{
 +      unsigned int level;
 +      pte_t *pte;
 +
 +      if (PageHighMem(page))
 +              return false;
 +
 +      pte = lookup_address((unsigned long)page_address(page), &level);
 +      return (pte_val(*pte) & _PAGE_PRESENT);
 +}
 +#endif /* CONFIG_HIBERNATION */
 +
 +int __init kernel_map_pages_in_pgd(pgd_t *pgd, u64 pfn, unsigned long address,
 +                                 unsigned numpages, unsigned long page_flags)
 +{
 +      int retval = -EINVAL;
 +
 +      struct cpa_data cpa = {
 +              .vaddr = &address,
 +              .pfn = pfn,
 +              .pgd = pgd,
 +              .numpages = numpages,
 +              .mask_set = __pgprot(0),
 +              .mask_clr = __pgprot(~page_flags & (_PAGE_NX|_PAGE_RW)),
 +              .flags = 0,
 +      };
 +
 +      WARN_ONCE(num_online_cpus() > 1, "Don't call after initializing SMP");
 +
 +      if (!(__supported_pte_mask & _PAGE_NX))
 +              goto out;
 +
 +      if (!(page_flags & _PAGE_ENC))
 +              cpa.mask_clr = pgprot_encrypted(cpa.mask_clr);
 +
 +      cpa.mask_set = __pgprot(_PAGE_PRESENT | page_flags);
 +
 +      retval = __change_page_attr_set_clr(&cpa, 0);
 +      __flush_tlb_all();
 +
 +out:
 +      return retval;
 +}
 +
 +/*
 + * __flush_tlb_all() flushes mappings only on current CPU and hence this
 + * function shouldn't be used in an SMP environment. Presently, it's used only
 + * during boot (way before smp_init()) by EFI subsystem and hence is ok.
 + */
 +int __init kernel_unmap_pages_in_pgd(pgd_t *pgd, unsigned long address,
 +                                   unsigned long numpages)
 +{
 +      int retval;
 +
 +      /*
 +       * The typical sequence for unmapping is to find a pte through
 +       * lookup_address_in_pgd() (ideally, it should never return NULL because
 +       * the address is already mapped) and change it's protections. As pfn is
 +       * the *target* of a mapping, it's not useful while unmapping.
 +       */
 +      struct cpa_data cpa = {
 +              .vaddr          = &address,
 +              .pfn            = 0,
 +              .pgd            = pgd,
 +              .numpages       = numpages,
 +              .mask_set       = __pgprot(0),
 +              .mask_clr       = __pgprot(_PAGE_PRESENT | _PAGE_RW),
 +              .flags          = 0,
 +      };
 +
 +      WARN_ONCE(num_online_cpus() > 1, "Don't call after initializing SMP");
 +
 +      retval = __change_page_attr_set_clr(&cpa, 0);
 +      __flush_tlb_all();
 +
 +      return retval;
 +}
 +
 +/*
 + * The testcases use internal knowledge of the implementation that shouldn't
 + * be exposed to the rest of the kernel. Include these directly here.
 + */
 +#ifdef CONFIG_CPA_DEBUG
 +#include "cpa-test.c"
 +#endif
diff --combined mm/huge_memory.c
@@@ -527,13 -527,24 +527,24 @@@ void prep_transhuge_page(struct page *p
        set_compound_page_dtor(page, TRANSHUGE_PAGE_DTOR);
  }
  
 -static unsigned long __thp_get_unmapped_area(struct file *filp, unsigned long len,
+ bool is_transparent_hugepage(struct page *page)
+ {
+       if (!PageCompound(page))
+               return 0;
+       page = compound_head(page);
+       return is_huge_zero_page(page) ||
+              page[1].compound_dtor == TRANSHUGE_PAGE_DTOR;
+ }
+ EXPORT_SYMBOL_GPL(is_transparent_hugepage);
 +static unsigned long __thp_get_unmapped_area(struct file *filp,
 +              unsigned long addr, unsigned long len,
                loff_t off, unsigned long flags, unsigned long size)
  {
 -      unsigned long addr;
        loff_t off_end = off + len;
        loff_t off_align = round_up(off, size);
 -      unsigned long len_pad;
 +      unsigned long len_pad, ret;
  
        if (off_end <= off_align || (off_end - off_align) < size)
                return 0;
        if (len_pad < len || (off + len_pad) < off)
                return 0;
  
 -      addr = current->mm->get_unmapped_area(filp, 0, len_pad,
 +      ret = current->mm->get_unmapped_area(filp, addr, len_pad,
                                              off >> PAGE_SHIFT, flags);
 -      if (IS_ERR_VALUE(addr))
 +
 +      /*
 +       * The failure might be due to length padding. The caller will retry
 +       * without the padding.
 +       */
 +      if (IS_ERR_VALUE(ret))
                return 0;
  
 -      addr += (off - addr) & (size - 1);
 -      return addr;
 +      /*
 +       * Do not try to align to THP boundary if allocation at the address
 +       * hint succeeds.
 +       */
 +      if (ret == addr)
 +              return addr;
 +
 +      ret += (off - ret) & (size - 1);
 +      return ret;
  }
  
  unsigned long thp_get_unmapped_area(struct file *filp, unsigned long addr,
                unsigned long len, unsigned long pgoff, unsigned long flags)
  {
 +      unsigned long ret;
        loff_t off = (loff_t)pgoff << PAGE_SHIFT;
  
 -      if (addr)
 -              goto out;
        if (!IS_DAX(filp->f_mapping->host) || !IS_ENABLED(CONFIG_FS_DAX_PMD))
                goto out;
  
 -      addr = __thp_get_unmapped_area(filp, len, off, flags, PMD_SIZE);
 -      if (addr)
 -              return addr;
 -
 - out:
 +      ret = __thp_get_unmapped_area(filp, addr, len, off, flags, PMD_SIZE);
 +      if (ret)
 +              return ret;
 +out:
        return current->mm->get_unmapped_area(filp, addr, len, pgoff, flags);
  }
  EXPORT_SYMBOL_GPL(thp_get_unmapped_area);