/* SPDX-License-Identifier: GPL-2.0 */1#ifndef __KVM_X86_MMU_INTERNAL_H2#define __KVM_X86_MMU_INTERNAL_H34#include <linux/types.h>5#include <linux/kvm_host.h>6#include <asm/kvm_host.h>78#include "mmu.h"910#ifdef CONFIG_KVM_PROVE_MMU11#define KVM_MMU_WARN_ON(x) WARN_ON_ONCE(x)12#else13#define KVM_MMU_WARN_ON(x) BUILD_BUG_ON_INVALID(x)14#endif1516/* Page table builder macros common to shadow (host) PTEs and guest PTEs. */17#define __PT_BASE_ADDR_MASK GENMASK_ULL(51, 12)18#define __PT_LEVEL_SHIFT(level, bits_per_level) \19(PAGE_SHIFT + ((level) - 1) * (bits_per_level))20#define __PT_INDEX(address, level, bits_per_level) \21(((address) >> __PT_LEVEL_SHIFT(level, bits_per_level)) & ((1 << (bits_per_level)) - 1))2223#define __PT_LVL_ADDR_MASK(base_addr_mask, level, bits_per_level) \24((base_addr_mask) & ~((1ULL << (PAGE_SHIFT + (((level) - 1) * (bits_per_level)))) - 1))2526#define __PT_LVL_OFFSET_MASK(base_addr_mask, level, bits_per_level) \27((base_addr_mask) & ((1ULL << (PAGE_SHIFT + (((level) - 1) * (bits_per_level)))) - 1))2829#define __PT_ENT_PER_PAGE(bits_per_level) (1 << (bits_per_level))3031/*32* Unlike regular MMU roots, PAE "roots", a.k.a. PDPTEs/PDPTRs, have a PRESENT33* bit, and thus are guaranteed to be non-zero when valid. And, when a guest34* PDPTR is !PRESENT, its corresponding PAE root cannot be set to INVALID_PAGE,35* as the CPU would treat that as PRESENT PDPTR with reserved bits set. Use36* '0' instead of INVALID_PAGE to indicate an invalid PAE root.37*/38#define INVALID_PAE_ROOT 039#define IS_VALID_PAE_ROOT(x) (!!(x))4041typedef u64 __rcu *tdp_ptep_t;4243struct kvm_mmu_page {44/*45* Note, "link" through "spt" fit in a single 64 byte cache line on46* 64-bit kernels, keep it that way unless there's a reason not to.47*/48struct list_head link;49struct hlist_node hash_link;5051bool tdp_mmu_page;52bool unsync;53union {54u8 mmu_valid_gen;5556/* Only accessed under slots_lock. */57bool tdp_mmu_scheduled_root_to_zap;58};5960/*61* The shadow page can't be replaced by an equivalent huge page62* because it is being used to map an executable page in the guest63* and the NX huge page mitigation is enabled.64*/65bool nx_huge_page_disallowed;6667/*68* The following two entries are used to key the shadow page in the69* hash table.70*/71union kvm_mmu_page_role role;72gfn_t gfn;7374u64 *spt;7576/*77* Stores the result of the guest translation being shadowed by each78* SPTE. KVM shadows two types of guest translations: nGPA -> GPA79* (shadow EPT/NPT) and GVA -> GPA (traditional shadow paging). In both80* cases the result of the translation is a GPA and a set of access81* constraints.82*83* The GFN is stored in the upper bits (PAGE_SHIFT) and the shadowed84* access permissions are stored in the lower bits. Note, for85* convenience and uniformity across guests, the access permissions are86* stored in KVM format (e.g. ACC_EXEC_MASK) not the raw guest format.87*/88u64 *shadowed_translation;8990/* Currently serving as active root */91union {92int root_count;93refcount_t tdp_mmu_root_count;94};9596bool has_mapped_host_mmio;9798union {99/* These two members aren't used for TDP MMU */100struct {101unsigned int unsync_children;102/*103* Number of writes since the last time traversal104* visited this page.105*/106atomic_t write_flooding_count;107};108/*109* Page table page of external PT.110* Passed to TDX module, not accessed by KVM.111*/112void *external_spt;113};114union {115struct kvm_rmap_head parent_ptes; /* rmap pointers to parent sptes */116tdp_ptep_t ptep;117};118DECLARE_BITMAP(unsync_child_bitmap, 512);119120/*121* Tracks shadow pages that, if zapped, would allow KVM to create an NX122* huge page. A shadow page will have nx_huge_page_disallowed set but123* not be on the list if a huge page is disallowed for other reasons,124* e.g. because KVM is shadowing a PTE at the same gfn, the memslot125* isn't properly aligned, etc...126*/127struct list_head possible_nx_huge_page_link;128#ifdef CONFIG_X86_32129/*130* Used out of the mmu-lock to avoid reading spte values while an131* update is in progress; see the comments in __get_spte_lockless().132*/133int clear_spte_count;134#endif135136#ifdef CONFIG_X86_64137/* Used for freeing the page asynchronously if it is a TDP MMU page. */138struct rcu_head rcu_head;139#endif140};141142extern struct kmem_cache *mmu_page_header_cache;143144static inline int kvm_mmu_role_as_id(union kvm_mmu_page_role role)145{146return role.smm ? 1 : 0;147}148149static inline int kvm_mmu_page_as_id(struct kvm_mmu_page *sp)150{151return kvm_mmu_role_as_id(sp->role);152}153154static inline bool is_mirror_sp(const struct kvm_mmu_page *sp)155{156return sp->role.is_mirror;157}158159static inline void kvm_mmu_alloc_external_spt(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)160{161/*162* external_spt is allocated for TDX module to hold private EPT mappings,163* TDX module will initialize the page by itself.164* Therefore, KVM does not need to initialize or access external_spt.165* KVM only interacts with sp->spt for private EPT operations.166*/167sp->external_spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_external_spt_cache);168}169170static inline gfn_t kvm_gfn_root_bits(const struct kvm *kvm, const struct kvm_mmu_page *root)171{172/*173* Since mirror SPs are used only for TDX, which maps private memory174* at its "natural" GFN, no mask needs to be applied to them - and, dually,175* we expect that the bits is only used for the shared PT.176*/177if (is_mirror_sp(root))178return 0;179return kvm_gfn_direct_bits(kvm);180}181182static inline bool kvm_mmu_page_ad_need_write_protect(struct kvm *kvm,183struct kvm_mmu_page *sp)184{185/*186* When using the EPT page-modification log, the GPAs in the CPU dirty187* log would come from L2 rather than L1. Therefore, we need to rely188* on write protection to record dirty pages, which bypasses PML, since189* writes now result in a vmexit. Note, the check on CPU dirty logging190* being enabled is mandatory as the bits used to denote WP-only SPTEs191* are reserved for PAE paging (32-bit KVM).192*/193return kvm->arch.cpu_dirty_log_size && sp->role.guest_mode;194}195196static inline gfn_t gfn_round_for_level(gfn_t gfn, int level)197{198return gfn & -KVM_PAGES_PER_HPAGE(level);199}200201int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,202gfn_t gfn, bool synchronizing, bool prefetch);203204void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn);205void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn);206bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,207struct kvm_memory_slot *slot, u64 gfn,208int min_level);209210/* Flush the given page (huge or not) of guest memory. */211static inline void kvm_flush_remote_tlbs_gfn(struct kvm *kvm, gfn_t gfn, int level)212{213kvm_flush_remote_tlbs_range(kvm, gfn_round_for_level(gfn, level),214KVM_PAGES_PER_HPAGE(level));215}216217unsigned int pte_list_count(struct kvm_rmap_head *rmap_head);218219extern int nx_huge_pages;220static inline bool is_nx_huge_page_enabled(struct kvm *kvm)221{222return READ_ONCE(nx_huge_pages) && !kvm->arch.disable_nx_huge_pages;223}224225struct kvm_page_fault {226/* arguments to kvm_mmu_do_page_fault. */227const gpa_t addr;228const u64 error_code;229const bool prefetch;230231/* Derived from error_code. */232const bool exec;233const bool write;234const bool present;235const bool rsvd;236const bool user;237238/* Derived from mmu and global state. */239const bool is_tdp;240const bool is_private;241const bool nx_huge_page_workaround_enabled;242243/*244* Whether a >4KB mapping can be created or is forbidden due to NX245* hugepages.246*/247bool huge_page_disallowed;248249/*250* Maximum page size that can be created for this fault; input to251* FNAME(fetch), direct_map() and kvm_tdp_mmu_map().252*/253u8 max_level;254255/*256* Page size that can be created based on the max_level and the257* page size used by the host mapping.258*/259u8 req_level;260261/*262* Page size that will be created based on the req_level and263* huge_page_disallowed.264*/265u8 goal_level;266267/*268* Shifted addr, or result of guest page table walk if addr is a gva. In269* the case of VM where memslot's can be mapped at multiple GPA aliases270* (i.e. TDX), the gfn field does not contain the bit that selects between271* the aliases (i.e. the shared bit for TDX).272*/273gfn_t gfn;274275/* The memslot containing gfn. May be NULL. */276struct kvm_memory_slot *slot;277278/* Outputs of kvm_mmu_faultin_pfn(). */279unsigned long mmu_seq;280kvm_pfn_t pfn;281struct page *refcounted_page;282bool map_writable;283284/*285* Indicates the guest is trying to write a gfn that contains one or286* more of the PTEs used to translate the write itself, i.e. the access287* is changing its own translation in the guest page tables.288*/289bool write_fault_to_shadow_pgtable;290};291292int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault);293294/*295* Return values of handle_mmio_page_fault(), mmu.page_fault(), fast_page_fault(),296* and of course kvm_mmu_do_page_fault().297*298* RET_PF_CONTINUE: So far, so good, keep handling the page fault.299* RET_PF_RETRY: let CPU fault again on the address.300* RET_PF_EMULATE: mmio page fault, emulate the instruction directly.301* RET_PF_WRITE_PROTECTED: the gfn is write-protected, either unprotected the302* gfn and retry, or emulate the instruction directly.303* RET_PF_INVALID: the spte is invalid, let the real page fault path update it.304* RET_PF_FIXED: The faulting entry has been fixed.305* RET_PF_SPURIOUS: The faulting entry was already fixed, e.g. by another vCPU.306*307* Any names added to this enum should be exported to userspace for use in308* tracepoints via TRACE_DEFINE_ENUM() in mmutrace.h309*310* Note, all values must be greater than or equal to zero so as not to encroach311* on -errno return values.312*/313enum {314RET_PF_CONTINUE = 0,315RET_PF_RETRY,316RET_PF_EMULATE,317RET_PF_WRITE_PROTECTED,318RET_PF_INVALID,319RET_PF_FIXED,320RET_PF_SPURIOUS,321};322323/*324* Define RET_PF_CONTINUE as 0 to allow for325* - efficient machine code when checking for CONTINUE, e.g.326* "TEST %rax, %rax, JNZ", as all "stop!" values are non-zero,327* - kvm_mmu_do_page_fault() to return other RET_PF_* as a positive value.328*/329static_assert(RET_PF_CONTINUE == 0);330331static inline void kvm_mmu_prepare_memory_fault_exit(struct kvm_vcpu *vcpu,332struct kvm_page_fault *fault)333{334kvm_prepare_memory_fault_exit(vcpu, fault->gfn << PAGE_SHIFT,335PAGE_SIZE, fault->write, fault->exec,336fault->is_private);337}338339static inline int kvm_mmu_do_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,340u64 err, bool prefetch,341int *emulation_type, u8 *level)342{343struct kvm_page_fault fault = {344.addr = cr2_or_gpa,345.error_code = err,346.exec = err & PFERR_FETCH_MASK,347.write = err & PFERR_WRITE_MASK,348.present = err & PFERR_PRESENT_MASK,349.rsvd = err & PFERR_RSVD_MASK,350.user = err & PFERR_USER_MASK,351.prefetch = prefetch,352.is_tdp = likely(vcpu->arch.mmu->page_fault == kvm_tdp_page_fault),353.nx_huge_page_workaround_enabled =354is_nx_huge_page_enabled(vcpu->kvm),355356.max_level = KVM_MAX_HUGEPAGE_LEVEL,357.req_level = PG_LEVEL_4K,358.goal_level = PG_LEVEL_4K,359.is_private = err & PFERR_PRIVATE_ACCESS,360361.pfn = KVM_PFN_ERR_FAULT,362};363int r;364365if (vcpu->arch.mmu->root_role.direct) {366/*367* Things like memslots don't understand the concept of a shared368* bit. Strip it so that the GFN can be used like normal, and the369* fault.addr can be used when the shared bit is needed.370*/371fault.gfn = gpa_to_gfn(fault.addr) & ~kvm_gfn_direct_bits(vcpu->kvm);372fault.slot = kvm_vcpu_gfn_to_memslot(vcpu, fault.gfn);373}374375/*376* With retpoline being active an indirect call is rather expensive,377* so do a direct call in the most common case.378*/379if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) && fault.is_tdp)380r = kvm_tdp_page_fault(vcpu, &fault);381else382r = vcpu->arch.mmu->page_fault(vcpu, &fault);383384/*385* Not sure what's happening, but punt to userspace and hope that386* they can fix it by changing memory to shared, or they can387* provide a better error.388*/389if (r == RET_PF_EMULATE && fault.is_private) {390pr_warn_ratelimited("kvm: unexpected emulation request on private memory\n");391kvm_mmu_prepare_memory_fault_exit(vcpu, &fault);392return -EFAULT;393}394395if (fault.write_fault_to_shadow_pgtable && emulation_type)396*emulation_type |= EMULTYPE_WRITE_PF_TO_SP;397if (level)398*level = fault.goal_level;399400return r;401}402403int kvm_mmu_max_mapping_level(struct kvm *kvm, struct kvm_page_fault *fault,404const struct kvm_memory_slot *slot, gfn_t gfn);405void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault);406void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level);407408void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,409enum kvm_mmu_type mmu_type);410void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,411enum kvm_mmu_type mmu_type);412413#endif /* __KVM_X86_MMU_INTERNAL_H */414415416