Back to home page

OSCL-LXR

 
 

    


0001 /* SPDX-License-Identifier: GPL-2.0-only */
0002 /*
0003  * Kernel-based Virtual Machine driver for Linux
0004  *
0005  * This module enables machines with Intel VT-x extensions to run virtual
0006  * machines without emulation or binary translation.
0007  *
0008  * MMU support
0009  *
0010  * Copyright (C) 2006 Qumranet, Inc.
0011  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
0012  *
0013  * Authors:
0014  *   Yaniv Kamay  <yaniv@qumranet.com>
0015  *   Avi Kivity   <avi@qumranet.com>
0016  */
0017 
0018 /*
0019  * The MMU needs to be able to access/walk 32-bit and 64-bit guest page tables,
0020  * as well as guest EPT tables, so the code in this file is compiled thrice,
0021  * once per guest PTE type.  The per-type defines are #undef'd at the end.
0022  */
0023 
0024 #if PTTYPE == 64
0025     #define pt_element_t u64
0026     #define guest_walker guest_walker64
0027     #define FNAME(name) paging##64_##name
0028     #define PT_LEVEL_BITS 9
0029     #define PT_GUEST_DIRTY_SHIFT PT_DIRTY_SHIFT
0030     #define PT_GUEST_ACCESSED_SHIFT PT_ACCESSED_SHIFT
0031     #define PT_HAVE_ACCESSED_DIRTY(mmu) true
0032     #ifdef CONFIG_X86_64
0033     #define PT_MAX_FULL_LEVELS PT64_ROOT_MAX_LEVEL
0034     #else
0035     #define PT_MAX_FULL_LEVELS 2
0036     #endif
0037 #elif PTTYPE == 32
0038     #define pt_element_t u32
0039     #define guest_walker guest_walker32
0040     #define FNAME(name) paging##32_##name
0041     #define PT_LEVEL_BITS 10
0042     #define PT_MAX_FULL_LEVELS 2
0043     #define PT_GUEST_DIRTY_SHIFT PT_DIRTY_SHIFT
0044     #define PT_GUEST_ACCESSED_SHIFT PT_ACCESSED_SHIFT
0045     #define PT_HAVE_ACCESSED_DIRTY(mmu) true
0046 
0047     #define PT32_DIR_PSE36_SIZE 4
0048     #define PT32_DIR_PSE36_SHIFT 13
0049     #define PT32_DIR_PSE36_MASK \
0050         (((1ULL << PT32_DIR_PSE36_SIZE) - 1) << PT32_DIR_PSE36_SHIFT)
0051 #elif PTTYPE == PTTYPE_EPT
0052     #define pt_element_t u64
0053     #define guest_walker guest_walkerEPT
0054     #define FNAME(name) ept_##name
0055     #define PT_LEVEL_BITS 9
0056     #define PT_GUEST_DIRTY_SHIFT 9
0057     #define PT_GUEST_ACCESSED_SHIFT 8
0058     #define PT_HAVE_ACCESSED_DIRTY(mmu) (!(mmu)->cpu_role.base.ad_disabled)
0059     #define PT_MAX_FULL_LEVELS PT64_ROOT_MAX_LEVEL
0060 #else
0061     #error Invalid PTTYPE value
0062 #endif
0063 
0064 /* Common logic, but per-type values.  These also need to be undefined. */
0065 #define PT_BASE_ADDR_MASK   ((pt_element_t)(((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1)))
0066 #define PT_LVL_ADDR_MASK(lvl)   __PT_LVL_ADDR_MASK(PT_BASE_ADDR_MASK, lvl, PT_LEVEL_BITS)
0067 #define PT_LVL_OFFSET_MASK(lvl) __PT_LVL_OFFSET_MASK(PT_BASE_ADDR_MASK, lvl, PT_LEVEL_BITS)
0068 #define PT_INDEX(addr, lvl) __PT_INDEX(addr, lvl, PT_LEVEL_BITS)
0069 
0070 #define PT_GUEST_DIRTY_MASK    (1 << PT_GUEST_DIRTY_SHIFT)
0071 #define PT_GUEST_ACCESSED_MASK (1 << PT_GUEST_ACCESSED_SHIFT)
0072 
0073 #define gpte_to_gfn_lvl FNAME(gpte_to_gfn_lvl)
0074 #define gpte_to_gfn(pte) gpte_to_gfn_lvl((pte), PG_LEVEL_4K)
0075 
0076 /*
0077  * The guest_walker structure emulates the behavior of the hardware page
0078  * table walker.
0079  */
0080 struct guest_walker {
0081     int level;
0082     unsigned max_level;
0083     gfn_t table_gfn[PT_MAX_FULL_LEVELS];
0084     pt_element_t ptes[PT_MAX_FULL_LEVELS];
0085     pt_element_t prefetch_ptes[PTE_PREFETCH_NUM];
0086     gpa_t pte_gpa[PT_MAX_FULL_LEVELS];
0087     pt_element_t __user *ptep_user[PT_MAX_FULL_LEVELS];
0088     bool pte_writable[PT_MAX_FULL_LEVELS];
0089     unsigned int pt_access[PT_MAX_FULL_LEVELS];
0090     unsigned int pte_access;
0091     gfn_t gfn;
0092     struct x86_exception fault;
0093 };
0094 
0095 #if PTTYPE == 32
0096 static inline gfn_t pse36_gfn_delta(u32 gpte)
0097 {
0098     int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
0099 
0100     return (gpte & PT32_DIR_PSE36_MASK) << shift;
0101 }
0102 #endif
0103 
0104 static gfn_t gpte_to_gfn_lvl(pt_element_t gpte, int lvl)
0105 {
0106     return (gpte & PT_LVL_ADDR_MASK(lvl)) >> PAGE_SHIFT;
0107 }
0108 
0109 static inline void FNAME(protect_clean_gpte)(struct kvm_mmu *mmu, unsigned *access,
0110                          unsigned gpte)
0111 {
0112     unsigned mask;
0113 
0114     /* dirty bit is not supported, so no need to track it */
0115     if (!PT_HAVE_ACCESSED_DIRTY(mmu))
0116         return;
0117 
0118     BUILD_BUG_ON(PT_WRITABLE_MASK != ACC_WRITE_MASK);
0119 
0120     mask = (unsigned)~ACC_WRITE_MASK;
0121     /* Allow write access to dirty gptes */
0122     mask |= (gpte >> (PT_GUEST_DIRTY_SHIFT - PT_WRITABLE_SHIFT)) &
0123         PT_WRITABLE_MASK;
0124     *access &= mask;
0125 }
0126 
0127 static inline int FNAME(is_present_gpte)(unsigned long pte)
0128 {
0129 #if PTTYPE != PTTYPE_EPT
0130     return pte & PT_PRESENT_MASK;
0131 #else
0132     return pte & 7;
0133 #endif
0134 }
0135 
0136 static bool FNAME(is_bad_mt_xwr)(struct rsvd_bits_validate *rsvd_check, u64 gpte)
0137 {
0138 #if PTTYPE != PTTYPE_EPT
0139     return false;
0140 #else
0141     return __is_bad_mt_xwr(rsvd_check, gpte);
0142 #endif
0143 }
0144 
0145 static bool FNAME(is_rsvd_bits_set)(struct kvm_mmu *mmu, u64 gpte, int level)
0146 {
0147     return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level) ||
0148            FNAME(is_bad_mt_xwr)(&mmu->guest_rsvd_check, gpte);
0149 }
0150 
0151 static bool FNAME(prefetch_invalid_gpte)(struct kvm_vcpu *vcpu,
0152                   struct kvm_mmu_page *sp, u64 *spte,
0153                   u64 gpte)
0154 {
0155     if (!FNAME(is_present_gpte)(gpte))
0156         goto no_present;
0157 
0158     /* Prefetch only accessed entries (unless A/D bits are disabled). */
0159     if (PT_HAVE_ACCESSED_DIRTY(vcpu->arch.mmu) &&
0160         !(gpte & PT_GUEST_ACCESSED_MASK))
0161         goto no_present;
0162 
0163     if (FNAME(is_rsvd_bits_set)(vcpu->arch.mmu, gpte, PG_LEVEL_4K))
0164         goto no_present;
0165 
0166     return false;
0167 
0168 no_present:
0169     drop_spte(vcpu->kvm, spte);
0170     return true;
0171 }
0172 
0173 /*
0174  * For PTTYPE_EPT, a page table can be executable but not readable
0175  * on supported processors. Therefore, set_spte does not automatically
0176  * set bit 0 if execute only is supported. Here, we repurpose ACC_USER_MASK
0177  * to signify readability since it isn't used in the EPT case
0178  */
0179 static inline unsigned FNAME(gpte_access)(u64 gpte)
0180 {
0181     unsigned access;
0182 #if PTTYPE == PTTYPE_EPT
0183     access = ((gpte & VMX_EPT_WRITABLE_MASK) ? ACC_WRITE_MASK : 0) |
0184         ((gpte & VMX_EPT_EXECUTABLE_MASK) ? ACC_EXEC_MASK : 0) |
0185         ((gpte & VMX_EPT_READABLE_MASK) ? ACC_USER_MASK : 0);
0186 #else
0187     BUILD_BUG_ON(ACC_EXEC_MASK != PT_PRESENT_MASK);
0188     BUILD_BUG_ON(ACC_EXEC_MASK != 1);
0189     access = gpte & (PT_WRITABLE_MASK | PT_USER_MASK | PT_PRESENT_MASK);
0190     /* Combine NX with P (which is set here) to get ACC_EXEC_MASK.  */
0191     access ^= (gpte >> PT64_NX_SHIFT);
0192 #endif
0193 
0194     return access;
0195 }
0196 
0197 static int FNAME(update_accessed_dirty_bits)(struct kvm_vcpu *vcpu,
0198                          struct kvm_mmu *mmu,
0199                          struct guest_walker *walker,
0200                          gpa_t addr, int write_fault)
0201 {
0202     unsigned level, index;
0203     pt_element_t pte, orig_pte;
0204     pt_element_t __user *ptep_user;
0205     gfn_t table_gfn;
0206     int ret;
0207 
0208     /* dirty/accessed bits are not supported, so no need to update them */
0209     if (!PT_HAVE_ACCESSED_DIRTY(mmu))
0210         return 0;
0211 
0212     for (level = walker->max_level; level >= walker->level; --level) {
0213         pte = orig_pte = walker->ptes[level - 1];
0214         table_gfn = walker->table_gfn[level - 1];
0215         ptep_user = walker->ptep_user[level - 1];
0216         index = offset_in_page(ptep_user) / sizeof(pt_element_t);
0217         if (!(pte & PT_GUEST_ACCESSED_MASK)) {
0218             trace_kvm_mmu_set_accessed_bit(table_gfn, index, sizeof(pte));
0219             pte |= PT_GUEST_ACCESSED_MASK;
0220         }
0221         if (level == walker->level && write_fault &&
0222                 !(pte & PT_GUEST_DIRTY_MASK)) {
0223             trace_kvm_mmu_set_dirty_bit(table_gfn, index, sizeof(pte));
0224 #if PTTYPE == PTTYPE_EPT
0225             if (kvm_x86_ops.nested_ops->write_log_dirty(vcpu, addr))
0226                 return -EINVAL;
0227 #endif
0228             pte |= PT_GUEST_DIRTY_MASK;
0229         }
0230         if (pte == orig_pte)
0231             continue;
0232 
0233         /*
0234          * If the slot is read-only, simply do not process the accessed
0235          * and dirty bits.  This is the correct thing to do if the slot
0236          * is ROM, and page tables in read-as-ROM/write-as-MMIO slots
0237          * are only supported if the accessed and dirty bits are already
0238          * set in the ROM (so that MMIO writes are never needed).
0239          *
0240          * Note that NPT does not allow this at all and faults, since
0241          * it always wants nested page table entries for the guest
0242          * page tables to be writable.  And EPT works but will simply
0243          * overwrite the read-only memory to set the accessed and dirty
0244          * bits.
0245          */
0246         if (unlikely(!walker->pte_writable[level - 1]))
0247             continue;
0248 
0249         ret = __try_cmpxchg_user(ptep_user, &orig_pte, pte, fault);
0250         if (ret)
0251             return ret;
0252 
0253         kvm_vcpu_mark_page_dirty(vcpu, table_gfn);
0254         walker->ptes[level - 1] = pte;
0255     }
0256     return 0;
0257 }
0258 
0259 static inline unsigned FNAME(gpte_pkeys)(struct kvm_vcpu *vcpu, u64 gpte)
0260 {
0261     unsigned pkeys = 0;
0262 #if PTTYPE == 64
0263     pte_t pte = {.pte = gpte};
0264 
0265     pkeys = pte_flags_pkey(pte_flags(pte));
0266 #endif
0267     return pkeys;
0268 }
0269 
0270 static inline bool FNAME(is_last_gpte)(struct kvm_mmu *mmu,
0271                        unsigned int level, unsigned int gpte)
0272 {
0273     /*
0274      * For EPT and PAE paging (both variants), bit 7 is either reserved at
0275      * all level or indicates a huge page (ignoring CR3/EPTP).  In either
0276      * case, bit 7 being set terminates the walk.
0277      */
0278 #if PTTYPE == 32
0279     /*
0280      * 32-bit paging requires special handling because bit 7 is ignored if
0281      * CR4.PSE=0, not reserved.  Clear bit 7 in the gpte if the level is
0282      * greater than the last level for which bit 7 is the PAGE_SIZE bit.
0283      *
0284      * The RHS has bit 7 set iff level < (2 + PSE).  If it is clear, bit 7
0285      * is not reserved and does not indicate a large page at this level,
0286      * so clear PT_PAGE_SIZE_MASK in gpte if that is the case.
0287      */
0288     gpte &= level - (PT32_ROOT_LEVEL + mmu->cpu_role.ext.cr4_pse);
0289 #endif
0290     /*
0291      * PG_LEVEL_4K always terminates.  The RHS has bit 7 set
0292      * iff level <= PG_LEVEL_4K, which for our purpose means
0293      * level == PG_LEVEL_4K; set PT_PAGE_SIZE_MASK in gpte then.
0294      */
0295     gpte |= level - PG_LEVEL_4K - 1;
0296 
0297     return gpte & PT_PAGE_SIZE_MASK;
0298 }
0299 /*
0300  * Fetch a guest pte for a guest virtual address, or for an L2's GPA.
0301  */
0302 static int FNAME(walk_addr_generic)(struct guest_walker *walker,
0303                     struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
0304                     gpa_t addr, u64 access)
0305 {
0306     int ret;
0307     pt_element_t pte;
0308     pt_element_t __user *ptep_user;
0309     gfn_t table_gfn;
0310     u64 pt_access, pte_access;
0311     unsigned index, accessed_dirty, pte_pkey;
0312     u64 nested_access;
0313     gpa_t pte_gpa;
0314     bool have_ad;
0315     int offset;
0316     u64 walk_nx_mask = 0;
0317     const int write_fault = access & PFERR_WRITE_MASK;
0318     const int user_fault  = access & PFERR_USER_MASK;
0319     const int fetch_fault = access & PFERR_FETCH_MASK;
0320     u16 errcode = 0;
0321     gpa_t real_gpa;
0322     gfn_t gfn;
0323 
0324     trace_kvm_mmu_pagetable_walk(addr, access);
0325 retry_walk:
0326     walker->level = mmu->cpu_role.base.level;
0327     pte           = mmu->get_guest_pgd(vcpu);
0328     have_ad       = PT_HAVE_ACCESSED_DIRTY(mmu);
0329 
0330 #if PTTYPE == 64
0331     walk_nx_mask = 1ULL << PT64_NX_SHIFT;
0332     if (walker->level == PT32E_ROOT_LEVEL) {
0333         pte = mmu->get_pdptr(vcpu, (addr >> 30) & 3);
0334         trace_kvm_mmu_paging_element(pte, walker->level);
0335         if (!FNAME(is_present_gpte)(pte))
0336             goto error;
0337         --walker->level;
0338     }
0339 #endif
0340     walker->max_level = walker->level;
0341     ASSERT(!(is_long_mode(vcpu) && !is_pae(vcpu)));
0342 
0343     /*
0344      * FIXME: on Intel processors, loads of the PDPTE registers for PAE paging
0345      * by the MOV to CR instruction are treated as reads and do not cause the
0346      * processor to set the dirty flag in any EPT paging-structure entry.
0347      */
0348     nested_access = (have_ad ? PFERR_WRITE_MASK : 0) | PFERR_USER_MASK;
0349 
0350     pte_access = ~0;
0351     ++walker->level;
0352 
0353     do {
0354         unsigned long host_addr;
0355 
0356         pt_access = pte_access;
0357         --walker->level;
0358 
0359         index = PT_INDEX(addr, walker->level);
0360         table_gfn = gpte_to_gfn(pte);
0361         offset    = index * sizeof(pt_element_t);
0362         pte_gpa   = gfn_to_gpa(table_gfn) + offset;
0363 
0364         BUG_ON(walker->level < 1);
0365         walker->table_gfn[walker->level - 1] = table_gfn;
0366         walker->pte_gpa[walker->level - 1] = pte_gpa;
0367 
0368         real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(table_gfn),
0369                          nested_access, &walker->fault);
0370 
0371         /*
0372          * FIXME: This can happen if emulation (for of an INS/OUTS
0373          * instruction) triggers a nested page fault.  The exit
0374          * qualification / exit info field will incorrectly have
0375          * "guest page access" as the nested page fault's cause,
0376          * instead of "guest page structure access".  To fix this,
0377          * the x86_exception struct should be augmented with enough
0378          * information to fix the exit_qualification or exit_info_1
0379          * fields.
0380          */
0381         if (unlikely(real_gpa == INVALID_GPA))
0382             return 0;
0383 
0384         host_addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gpa_to_gfn(real_gpa),
0385                         &walker->pte_writable[walker->level - 1]);
0386         if (unlikely(kvm_is_error_hva(host_addr)))
0387             goto error;
0388 
0389         ptep_user = (pt_element_t __user *)((void *)host_addr + offset);
0390         if (unlikely(__get_user(pte, ptep_user)))
0391             goto error;
0392         walker->ptep_user[walker->level - 1] = ptep_user;
0393 
0394         trace_kvm_mmu_paging_element(pte, walker->level);
0395 
0396         /*
0397          * Inverting the NX it lets us AND it like other
0398          * permission bits.
0399          */
0400         pte_access = pt_access & (pte ^ walk_nx_mask);
0401 
0402         if (unlikely(!FNAME(is_present_gpte)(pte)))
0403             goto error;
0404 
0405         if (unlikely(FNAME(is_rsvd_bits_set)(mmu, pte, walker->level))) {
0406             errcode = PFERR_RSVD_MASK | PFERR_PRESENT_MASK;
0407             goto error;
0408         }
0409 
0410         walker->ptes[walker->level - 1] = pte;
0411 
0412         /* Convert to ACC_*_MASK flags for struct guest_walker.  */
0413         walker->pt_access[walker->level - 1] = FNAME(gpte_access)(pt_access ^ walk_nx_mask);
0414     } while (!FNAME(is_last_gpte)(mmu, walker->level, pte));
0415 
0416     pte_pkey = FNAME(gpte_pkeys)(vcpu, pte);
0417     accessed_dirty = have_ad ? pte_access & PT_GUEST_ACCESSED_MASK : 0;
0418 
0419     /* Convert to ACC_*_MASK flags for struct guest_walker.  */
0420     walker->pte_access = FNAME(gpte_access)(pte_access ^ walk_nx_mask);
0421     errcode = permission_fault(vcpu, mmu, walker->pte_access, pte_pkey, access);
0422     if (unlikely(errcode))
0423         goto error;
0424 
0425     gfn = gpte_to_gfn_lvl(pte, walker->level);
0426     gfn += (addr & PT_LVL_OFFSET_MASK(walker->level)) >> PAGE_SHIFT;
0427 
0428 #if PTTYPE == 32
0429     if (walker->level > PG_LEVEL_4K && is_cpuid_PSE36())
0430         gfn += pse36_gfn_delta(pte);
0431 #endif
0432 
0433     real_gpa = kvm_translate_gpa(vcpu, mmu, gfn_to_gpa(gfn), access, &walker->fault);
0434     if (real_gpa == INVALID_GPA)
0435         return 0;
0436 
0437     walker->gfn = real_gpa >> PAGE_SHIFT;
0438 
0439     if (!write_fault)
0440         FNAME(protect_clean_gpte)(mmu, &walker->pte_access, pte);
0441     else
0442         /*
0443          * On a write fault, fold the dirty bit into accessed_dirty.
0444          * For modes without A/D bits support accessed_dirty will be
0445          * always clear.
0446          */
0447         accessed_dirty &= pte >>
0448             (PT_GUEST_DIRTY_SHIFT - PT_GUEST_ACCESSED_SHIFT);
0449 
0450     if (unlikely(!accessed_dirty)) {
0451         ret = FNAME(update_accessed_dirty_bits)(vcpu, mmu, walker,
0452                             addr, write_fault);
0453         if (unlikely(ret < 0))
0454             goto error;
0455         else if (ret)
0456             goto retry_walk;
0457     }
0458 
0459     pgprintk("%s: pte %llx pte_access %x pt_access %x\n",
0460          __func__, (u64)pte, walker->pte_access,
0461          walker->pt_access[walker->level - 1]);
0462     return 1;
0463 
0464 error:
0465     errcode |= write_fault | user_fault;
0466     if (fetch_fault && (is_efer_nx(mmu) || is_cr4_smep(mmu)))
0467         errcode |= PFERR_FETCH_MASK;
0468 
0469     walker->fault.vector = PF_VECTOR;
0470     walker->fault.error_code_valid = true;
0471     walker->fault.error_code = errcode;
0472 
0473 #if PTTYPE == PTTYPE_EPT
0474     /*
0475      * Use PFERR_RSVD_MASK in error_code to to tell if EPT
0476      * misconfiguration requires to be injected. The detection is
0477      * done by is_rsvd_bits_set() above.
0478      *
0479      * We set up the value of exit_qualification to inject:
0480      * [2:0] - Derive from the access bits. The exit_qualification might be
0481      *         out of date if it is serving an EPT misconfiguration.
0482      * [5:3] - Calculated by the page walk of the guest EPT page tables
0483      * [7:8] - Derived from [7:8] of real exit_qualification
0484      *
0485      * The other bits are set to 0.
0486      */
0487     if (!(errcode & PFERR_RSVD_MASK)) {
0488         vcpu->arch.exit_qualification &= (EPT_VIOLATION_GVA_IS_VALID |
0489                           EPT_VIOLATION_GVA_TRANSLATED);
0490         if (write_fault)
0491             vcpu->arch.exit_qualification |= EPT_VIOLATION_ACC_WRITE;
0492         if (user_fault)
0493             vcpu->arch.exit_qualification |= EPT_VIOLATION_ACC_READ;
0494         if (fetch_fault)
0495             vcpu->arch.exit_qualification |= EPT_VIOLATION_ACC_INSTR;
0496 
0497         /*
0498          * Note, pte_access holds the raw RWX bits from the EPTE, not
0499          * ACC_*_MASK flags!
0500          */
0501         vcpu->arch.exit_qualification |= (pte_access & VMX_EPT_RWX_MASK) <<
0502                          EPT_VIOLATION_RWX_SHIFT;
0503     }
0504 #endif
0505     walker->fault.address = addr;
0506     walker->fault.nested_page_fault = mmu != vcpu->arch.walk_mmu;
0507     walker->fault.async_page_fault = false;
0508 
0509     trace_kvm_mmu_walker_error(walker->fault.error_code);
0510     return 0;
0511 }
0512 
0513 static int FNAME(walk_addr)(struct guest_walker *walker,
0514                 struct kvm_vcpu *vcpu, gpa_t addr, u64 access)
0515 {
0516     return FNAME(walk_addr_generic)(walker, vcpu, vcpu->arch.mmu, addr,
0517                     access);
0518 }
0519 
0520 static bool
0521 FNAME(prefetch_gpte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
0522              u64 *spte, pt_element_t gpte, bool no_dirty_log)
0523 {
0524     struct kvm_memory_slot *slot;
0525     unsigned pte_access;
0526     gfn_t gfn;
0527     kvm_pfn_t pfn;
0528 
0529     if (FNAME(prefetch_invalid_gpte)(vcpu, sp, spte, gpte))
0530         return false;
0531 
0532     pgprintk("%s: gpte %llx spte %p\n", __func__, (u64)gpte, spte);
0533 
0534     gfn = gpte_to_gfn(gpte);
0535     pte_access = sp->role.access & FNAME(gpte_access)(gpte);
0536     FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);
0537 
0538     slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn,
0539             no_dirty_log && (pte_access & ACC_WRITE_MASK));
0540     if (!slot)
0541         return false;
0542 
0543     pfn = gfn_to_pfn_memslot_atomic(slot, gfn);
0544     if (is_error_pfn(pfn))
0545         return false;
0546 
0547     mmu_set_spte(vcpu, slot, spte, pte_access, gfn, pfn, NULL);
0548     kvm_release_pfn_clean(pfn);
0549     return true;
0550 }
0551 
0552 static bool FNAME(gpte_changed)(struct kvm_vcpu *vcpu,
0553                 struct guest_walker *gw, int level)
0554 {
0555     pt_element_t curr_pte;
0556     gpa_t base_gpa, pte_gpa = gw->pte_gpa[level - 1];
0557     u64 mask;
0558     int r, index;
0559 
0560     if (level == PG_LEVEL_4K) {
0561         mask = PTE_PREFETCH_NUM * sizeof(pt_element_t) - 1;
0562         base_gpa = pte_gpa & ~mask;
0563         index = (pte_gpa - base_gpa) / sizeof(pt_element_t);
0564 
0565         r = kvm_vcpu_read_guest_atomic(vcpu, base_gpa,
0566                 gw->prefetch_ptes, sizeof(gw->prefetch_ptes));
0567         curr_pte = gw->prefetch_ptes[index];
0568     } else
0569         r = kvm_vcpu_read_guest_atomic(vcpu, pte_gpa,
0570                   &curr_pte, sizeof(curr_pte));
0571 
0572     return r || curr_pte != gw->ptes[level - 1];
0573 }
0574 
0575 static void FNAME(pte_prefetch)(struct kvm_vcpu *vcpu, struct guest_walker *gw,
0576                 u64 *sptep)
0577 {
0578     struct kvm_mmu_page *sp;
0579     pt_element_t *gptep = gw->prefetch_ptes;
0580     u64 *spte;
0581     int i;
0582 
0583     sp = sptep_to_sp(sptep);
0584 
0585     if (sp->role.level > PG_LEVEL_4K)
0586         return;
0587 
0588     /*
0589      * If addresses are being invalidated, skip prefetching to avoid
0590      * accidentally prefetching those addresses.
0591      */
0592     if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
0593         return;
0594 
0595     if (sp->role.direct)
0596         return __direct_pte_prefetch(vcpu, sp, sptep);
0597 
0598     i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
0599     spte = sp->spt + i;
0600 
0601     for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
0602         if (spte == sptep)
0603             continue;
0604 
0605         if (is_shadow_present_pte(*spte))
0606             continue;
0607 
0608         if (!FNAME(prefetch_gpte)(vcpu, sp, spte, gptep[i], true))
0609             break;
0610     }
0611 }
0612 
0613 /*
0614  * Fetch a shadow pte for a specific level in the paging hierarchy.
0615  * If the guest tries to write a write-protected page, we need to
0616  * emulate this operation, return 1 to indicate this case.
0617  */
0618 static int FNAME(fetch)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
0619              struct guest_walker *gw)
0620 {
0621     struct kvm_mmu_page *sp = NULL;
0622     struct kvm_shadow_walk_iterator it;
0623     unsigned int direct_access, access;
0624     int top_level, ret;
0625     gfn_t base_gfn = fault->gfn;
0626 
0627     WARN_ON_ONCE(gw->gfn != base_gfn);
0628     direct_access = gw->pte_access;
0629 
0630     top_level = vcpu->arch.mmu->cpu_role.base.level;
0631     if (top_level == PT32E_ROOT_LEVEL)
0632         top_level = PT32_ROOT_LEVEL;
0633     /*
0634      * Verify that the top-level gpte is still there.  Since the page
0635      * is a root page, it is either write protected (and cannot be
0636      * changed from now on) or it is invalid (in which case, we don't
0637      * really care if it changes underneath us after this point).
0638      */
0639     if (FNAME(gpte_changed)(vcpu, gw, top_level))
0640         goto out_gpte_changed;
0641 
0642     if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
0643         goto out_gpte_changed;
0644 
0645     for (shadow_walk_init(&it, vcpu, fault->addr);
0646          shadow_walk_okay(&it) && it.level > gw->level;
0647          shadow_walk_next(&it)) {
0648         gfn_t table_gfn;
0649 
0650         clear_sp_write_flooding_count(it.sptep);
0651 
0652         table_gfn = gw->table_gfn[it.level - 2];
0653         access = gw->pt_access[it.level - 2];
0654         sp = kvm_mmu_get_child_sp(vcpu, it.sptep, table_gfn,
0655                       false, access);
0656 
0657         if (sp != ERR_PTR(-EEXIST)) {
0658             /*
0659              * We must synchronize the pagetable before linking it
0660              * because the guest doesn't need to flush tlb when
0661              * the gpte is changed from non-present to present.
0662              * Otherwise, the guest may use the wrong mapping.
0663              *
0664              * For PG_LEVEL_4K, kvm_mmu_get_page() has already
0665              * synchronized it transiently via kvm_sync_page().
0666              *
0667              * For higher level pagetable, we synchronize it via
0668              * the slower mmu_sync_children().  If it needs to
0669              * break, some progress has been made; return
0670              * RET_PF_RETRY and retry on the next #PF.
0671              * KVM_REQ_MMU_SYNC is not necessary but it
0672              * expedites the process.
0673              */
0674             if (sp->unsync_children &&
0675                 mmu_sync_children(vcpu, sp, false))
0676                 return RET_PF_RETRY;
0677         }
0678 
0679         /*
0680          * Verify that the gpte in the page we've just write
0681          * protected is still there.
0682          */
0683         if (FNAME(gpte_changed)(vcpu, gw, it.level - 1))
0684             goto out_gpte_changed;
0685 
0686         if (sp != ERR_PTR(-EEXIST))
0687             link_shadow_page(vcpu, it.sptep, sp);
0688     }
0689 
0690     kvm_mmu_hugepage_adjust(vcpu, fault);
0691 
0692     trace_kvm_mmu_spte_requested(fault);
0693 
0694     for (; shadow_walk_okay(&it); shadow_walk_next(&it)) {
0695         clear_sp_write_flooding_count(it.sptep);
0696 
0697         /*
0698          * We cannot overwrite existing page tables with an NX
0699          * large page, as the leaf could be executable.
0700          */
0701         if (fault->nx_huge_page_workaround_enabled)
0702             disallowed_hugepage_adjust(fault, *it.sptep, it.level);
0703 
0704         base_gfn = fault->gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
0705         if (it.level == fault->goal_level)
0706             break;
0707 
0708         validate_direct_spte(vcpu, it.sptep, direct_access);
0709 
0710         sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn,
0711                       true, direct_access);
0712         if (sp == ERR_PTR(-EEXIST))
0713             continue;
0714 
0715         link_shadow_page(vcpu, it.sptep, sp);
0716         if (fault->huge_page_disallowed &&
0717             fault->req_level >= it.level)
0718             account_huge_nx_page(vcpu->kvm, sp);
0719     }
0720 
0721     if (WARN_ON_ONCE(it.level != fault->goal_level))
0722         return -EFAULT;
0723 
0724     ret = mmu_set_spte(vcpu, fault->slot, it.sptep, gw->pte_access,
0725                base_gfn, fault->pfn, fault);
0726     if (ret == RET_PF_SPURIOUS)
0727         return ret;
0728 
0729     FNAME(pte_prefetch)(vcpu, gw, it.sptep);
0730     return ret;
0731 
0732 out_gpte_changed:
0733     return RET_PF_RETRY;
0734 }
0735 
0736  /*
0737  * To see whether the mapped gfn can write its page table in the current
0738  * mapping.
0739  *
0740  * It is the helper function of FNAME(page_fault). When guest uses large page
0741  * size to map the writable gfn which is used as current page table, we should
0742  * force kvm to use small page size to map it because new shadow page will be
0743  * created when kvm establishes shadow page table that stop kvm using large
0744  * page size. Do it early can avoid unnecessary #PF and emulation.
0745  *
0746  * @write_fault_to_shadow_pgtable will return true if the fault gfn is
0747  * currently used as its page table.
0748  *
0749  * Note: the PDPT page table is not checked for PAE-32 bit guest. It is ok
0750  * since the PDPT is always shadowed, that means, we can not use large page
0751  * size to map the gfn which is used as PDPT.
0752  */
0753 static bool
0754 FNAME(is_self_change_mapping)(struct kvm_vcpu *vcpu,
0755                   struct guest_walker *walker, bool user_fault,
0756                   bool *write_fault_to_shadow_pgtable)
0757 {
0758     int level;
0759     gfn_t mask = ~(KVM_PAGES_PER_HPAGE(walker->level) - 1);
0760     bool self_changed = false;
0761 
0762     if (!(walker->pte_access & ACC_WRITE_MASK ||
0763         (!is_cr0_wp(vcpu->arch.mmu) && !user_fault)))
0764         return false;
0765 
0766     for (level = walker->level; level <= walker->max_level; level++) {
0767         gfn_t gfn = walker->gfn ^ walker->table_gfn[level - 1];
0768 
0769         self_changed |= !(gfn & mask);
0770         *write_fault_to_shadow_pgtable |= !gfn;
0771     }
0772 
0773     return self_changed;
0774 }
0775 
0776 /*
0777  * Page fault handler.  There are several causes for a page fault:
0778  *   - there is no shadow pte for the guest pte
0779  *   - write access through a shadow pte marked read only so that we can set
0780  *     the dirty bit
0781  *   - write access to a shadow pte marked read only so we can update the page
0782  *     dirty bitmap, when userspace requests it
0783  *   - mmio access; in this case we will never install a present shadow pte
0784  *   - normal guest page fault due to the guest pte marked not present, not
0785  *     writable, or not executable
0786  *
0787  *  Returns: 1 if we need to emulate the instruction, 0 otherwise, or
0788  *           a negative value on error.
0789  */
0790 static int FNAME(page_fault)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
0791 {
0792     struct guest_walker walker;
0793     int r;
0794     unsigned long mmu_seq;
0795     bool is_self_change_mapping;
0796 
0797     pgprintk("%s: addr %lx err %x\n", __func__, fault->addr, fault->error_code);
0798     WARN_ON_ONCE(fault->is_tdp);
0799 
0800     /*
0801      * Look up the guest pte for the faulting address.
0802      * If PFEC.RSVD is set, this is a shadow page fault.
0803      * The bit needs to be cleared before walking guest page tables.
0804      */
0805     r = FNAME(walk_addr)(&walker, vcpu, fault->addr,
0806                  fault->error_code & ~PFERR_RSVD_MASK);
0807 
0808     /*
0809      * The page is not mapped by the guest.  Let the guest handle it.
0810      */
0811     if (!r) {
0812         pgprintk("%s: guest page fault\n", __func__);
0813         if (!fault->prefetch)
0814             kvm_inject_emulated_page_fault(vcpu, &walker.fault);
0815 
0816         return RET_PF_RETRY;
0817     }
0818 
0819     fault->gfn = walker.gfn;
0820     fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);
0821 
0822     if (page_fault_handle_page_track(vcpu, fault)) {
0823         shadow_page_table_clear_flood(vcpu, fault->addr);
0824         return RET_PF_EMULATE;
0825     }
0826 
0827     r = mmu_topup_memory_caches(vcpu, true);
0828     if (r)
0829         return r;
0830 
0831     vcpu->arch.write_fault_to_shadow_pgtable = false;
0832 
0833     is_self_change_mapping = FNAME(is_self_change_mapping)(vcpu,
0834           &walker, fault->user, &vcpu->arch.write_fault_to_shadow_pgtable);
0835 
0836     if (is_self_change_mapping)
0837         fault->max_level = PG_LEVEL_4K;
0838     else
0839         fault->max_level = walker.level;
0840 
0841     mmu_seq = vcpu->kvm->mmu_invalidate_seq;
0842     smp_rmb();
0843 
0844     r = kvm_faultin_pfn(vcpu, fault);
0845     if (r != RET_PF_CONTINUE)
0846         return r;
0847 
0848     r = handle_abnormal_pfn(vcpu, fault, walker.pte_access);
0849     if (r != RET_PF_CONTINUE)
0850         return r;
0851 
0852     /*
0853      * Do not change pte_access if the pfn is a mmio page, otherwise
0854      * we will cache the incorrect access into mmio spte.
0855      */
0856     if (fault->write && !(walker.pte_access & ACC_WRITE_MASK) &&
0857         !is_cr0_wp(vcpu->arch.mmu) && !fault->user && fault->slot) {
0858         walker.pte_access |= ACC_WRITE_MASK;
0859         walker.pte_access &= ~ACC_USER_MASK;
0860 
0861         /*
0862          * If we converted a user page to a kernel page,
0863          * so that the kernel can write to it when cr0.wp=0,
0864          * then we should prevent the kernel from executing it
0865          * if SMEP is enabled.
0866          */
0867         if (is_cr4_smep(vcpu->arch.mmu))
0868             walker.pte_access &= ~ACC_EXEC_MASK;
0869     }
0870 
0871     r = RET_PF_RETRY;
0872     write_lock(&vcpu->kvm->mmu_lock);
0873 
0874     if (is_page_fault_stale(vcpu, fault, mmu_seq))
0875         goto out_unlock;
0876 
0877     r = make_mmu_pages_available(vcpu);
0878     if (r)
0879         goto out_unlock;
0880     r = FNAME(fetch)(vcpu, fault, &walker);
0881 
0882 out_unlock:
0883     write_unlock(&vcpu->kvm->mmu_lock);
0884     kvm_release_pfn_clean(fault->pfn);
0885     return r;
0886 }
0887 
0888 static gpa_t FNAME(get_level1_sp_gpa)(struct kvm_mmu_page *sp)
0889 {
0890     int offset = 0;
0891 
0892     WARN_ON(sp->role.level != PG_LEVEL_4K);
0893 
0894     if (PTTYPE == 32)
0895         offset = sp->role.quadrant << SPTE_LEVEL_BITS;
0896 
0897     return gfn_to_gpa(sp->gfn) + offset * sizeof(pt_element_t);
0898 }
0899 
0900 static void FNAME(invlpg)(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root_hpa)
0901 {
0902     struct kvm_shadow_walk_iterator iterator;
0903     struct kvm_mmu_page *sp;
0904     u64 old_spte;
0905     int level;
0906     u64 *sptep;
0907 
0908     vcpu_clear_mmio_info(vcpu, gva);
0909 
0910     /*
0911      * No need to check return value here, rmap_can_add() can
0912      * help us to skip pte prefetch later.
0913      */
0914     mmu_topup_memory_caches(vcpu, true);
0915 
0916     if (!VALID_PAGE(root_hpa)) {
0917         WARN_ON(1);
0918         return;
0919     }
0920 
0921     write_lock(&vcpu->kvm->mmu_lock);
0922     for_each_shadow_entry_using_root(vcpu, root_hpa, gva, iterator) {
0923         level = iterator.level;
0924         sptep = iterator.sptep;
0925 
0926         sp = sptep_to_sp(sptep);
0927         old_spte = *sptep;
0928         if (is_last_spte(old_spte, level)) {
0929             pt_element_t gpte;
0930             gpa_t pte_gpa;
0931 
0932             if (!sp->unsync)
0933                 break;
0934 
0935             pte_gpa = FNAME(get_level1_sp_gpa)(sp);
0936             pte_gpa += spte_index(sptep) * sizeof(pt_element_t);
0937 
0938             mmu_page_zap_pte(vcpu->kvm, sp, sptep, NULL);
0939             if (is_shadow_present_pte(old_spte))
0940                 kvm_flush_remote_tlbs_with_address(vcpu->kvm,
0941                     sp->gfn, KVM_PAGES_PER_HPAGE(sp->role.level));
0942 
0943             if (!rmap_can_add(vcpu))
0944                 break;
0945 
0946             if (kvm_vcpu_read_guest_atomic(vcpu, pte_gpa, &gpte,
0947                                sizeof(pt_element_t)))
0948                 break;
0949 
0950             FNAME(prefetch_gpte)(vcpu, sp, sptep, gpte, false);
0951         }
0952 
0953         if (!sp->unsync_children)
0954             break;
0955     }
0956     write_unlock(&vcpu->kvm->mmu_lock);
0957 }
0958 
0959 /* Note, @addr is a GPA when gva_to_gpa() translates an L2 GPA to an L1 GPA. */
0960 static gpa_t FNAME(gva_to_gpa)(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
0961                    gpa_t addr, u64 access,
0962                    struct x86_exception *exception)
0963 {
0964     struct guest_walker walker;
0965     gpa_t gpa = INVALID_GPA;
0966     int r;
0967 
0968 #ifndef CONFIG_X86_64
0969     /* A 64-bit GVA should be impossible on 32-bit KVM. */
0970     WARN_ON_ONCE((addr >> 32) && mmu == vcpu->arch.walk_mmu);
0971 #endif
0972 
0973     r = FNAME(walk_addr_generic)(&walker, vcpu, mmu, addr, access);
0974 
0975     if (r) {
0976         gpa = gfn_to_gpa(walker.gfn);
0977         gpa |= addr & ~PAGE_MASK;
0978     } else if (exception)
0979         *exception = walker.fault;
0980 
0981     return gpa;
0982 }
0983 
0984 /*
0985  * Using the information in sp->shadowed_translation (kvm_mmu_page_get_gfn()) is
0986  * safe because:
0987  * - The spte has a reference to the struct page, so the pfn for a given gfn
0988  *   can't change unless all sptes pointing to it are nuked first.
0989  *
0990  * Returns
0991  * < 0: the sp should be zapped
0992  *   0: the sp is synced and no tlb flushing is required
0993  * > 0: the sp is synced and tlb flushing is required
0994  */
0995 static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
0996 {
0997     union kvm_mmu_page_role root_role = vcpu->arch.mmu->root_role;
0998     int i;
0999     bool host_writable;
1000     gpa_t first_pte_gpa;
1001     bool flush = false;
1002 
1003     /*
1004      * Ignore various flags when verifying that it's safe to sync a shadow
1005      * page using the current MMU context.
1006      *
1007      *  - level: not part of the overall MMU role and will never match as the MMU's
1008      *           level tracks the root level
1009      *  - access: updated based on the new guest PTE
1010      *  - quadrant: not part of the overall MMU role (similar to level)
1011      */
1012     const union kvm_mmu_page_role sync_role_ign = {
1013         .level = 0xf,
1014         .access = 0x7,
1015         .quadrant = 0x3,
1016         .passthrough = 0x1,
1017     };
1018 
1019     /*
1020      * Direct pages can never be unsync, and KVM should never attempt to
1021      * sync a shadow page for a different MMU context, e.g. if the role
1022      * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
1023      * reserved bits checks will be wrong, etc...
1024      */
1025     if (WARN_ON_ONCE(sp->role.direct ||
1026              (sp->role.word ^ root_role.word) & ~sync_role_ign.word))
1027         return -1;
1028 
1029     first_pte_gpa = FNAME(get_level1_sp_gpa)(sp);
1030 
1031     for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
1032         u64 *sptep, spte;
1033         struct kvm_memory_slot *slot;
1034         unsigned pte_access;
1035         pt_element_t gpte;
1036         gpa_t pte_gpa;
1037         gfn_t gfn;
1038 
1039         if (!sp->spt[i])
1040             continue;
1041 
1042         pte_gpa = first_pte_gpa + i * sizeof(pt_element_t);
1043 
1044         if (kvm_vcpu_read_guest_atomic(vcpu, pte_gpa, &gpte,
1045                            sizeof(pt_element_t)))
1046             return -1;
1047 
1048         if (FNAME(prefetch_invalid_gpte)(vcpu, sp, &sp->spt[i], gpte)) {
1049             flush = true;
1050             continue;
1051         }
1052 
1053         gfn = gpte_to_gfn(gpte);
1054         pte_access = sp->role.access;
1055         pte_access &= FNAME(gpte_access)(gpte);
1056         FNAME(protect_clean_gpte)(vcpu->arch.mmu, &pte_access, gpte);
1057 
1058         if (sync_mmio_spte(vcpu, &sp->spt[i], gfn, pte_access))
1059             continue;
1060 
1061         /*
1062          * Drop the SPTE if the new protections would result in a RWX=0
1063          * SPTE or if the gfn is changing.  The RWX=0 case only affects
1064          * EPT with execute-only support, i.e. EPT without an effective
1065          * "present" bit, as all other paging modes will create a
1066          * read-only SPTE if pte_access is zero.
1067          */
1068         if ((!pte_access && !shadow_present_mask) ||
1069             gfn != kvm_mmu_page_get_gfn(sp, i)) {
1070             drop_spte(vcpu->kvm, &sp->spt[i]);
1071             flush = true;
1072             continue;
1073         }
1074 
1075         /* Update the shadowed access bits in case they changed. */
1076         kvm_mmu_page_set_access(sp, i, pte_access);
1077 
1078         sptep = &sp->spt[i];
1079         spte = *sptep;
1080         host_writable = spte & shadow_host_writable_mask;
1081         slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1082         make_spte(vcpu, sp, slot, pte_access, gfn,
1083               spte_to_pfn(spte), spte, true, false,
1084               host_writable, &spte);
1085 
1086         flush |= mmu_spte_update(sptep, spte);
1087     }
1088 
1089     /*
1090      * Note, any flush is purely for KVM's correctness, e.g. when dropping
1091      * an existing SPTE or clearing W/A/D bits to ensure an mmu_notifier
1092      * unmap or dirty logging event doesn't fail to flush.  The guest is
1093      * responsible for flushing the TLB to ensure any changes in protection
1094      * bits are recognized, i.e. until the guest flushes or page faults on
1095      * a relevant address, KVM is architecturally allowed to let vCPUs use
1096      * cached translations with the old protection bits.
1097      */
1098     return flush;
1099 }
1100 
1101 #undef pt_element_t
1102 #undef guest_walker
1103 #undef FNAME
1104 #undef PT_BASE_ADDR_MASK
1105 #undef PT_INDEX
1106 #undef PT_LVL_ADDR_MASK
1107 #undef PT_LVL_OFFSET_MASK
1108 #undef PT_LEVEL_BITS
1109 #undef PT_MAX_FULL_LEVELS
1110 #undef gpte_to_gfn
1111 #undef gpte_to_gfn_lvl
1112 #undef PT_GUEST_ACCESSED_MASK
1113 #undef PT_GUEST_DIRTY_MASK
1114 #undef PT_GUEST_DIRTY_SHIFT
1115 #undef PT_GUEST_ACCESSED_SHIFT
1116 #undef PT_HAVE_ACCESSED_DIRTY