xref: /linux/arch/x86/kvm/mmu/mmu.c (revision 7bdbb820fee4429f889ed563929ce2d1c6ac36b6)
1c50d8ae3SPaolo Bonzini // SPDX-License-Identifier: GPL-2.0-only
2c50d8ae3SPaolo Bonzini /*
3c50d8ae3SPaolo Bonzini  * Kernel-based Virtual Machine driver for Linux
4c50d8ae3SPaolo Bonzini  *
5c50d8ae3SPaolo Bonzini  * This module enables machines with Intel VT-x extensions to run virtual
6c50d8ae3SPaolo Bonzini  * machines without emulation or binary translation.
7c50d8ae3SPaolo Bonzini  *
8c50d8ae3SPaolo Bonzini  * MMU support
9c50d8ae3SPaolo Bonzini  *
10c50d8ae3SPaolo Bonzini  * Copyright (C) 2006 Qumranet, Inc.
11c50d8ae3SPaolo Bonzini  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12c50d8ae3SPaolo Bonzini  *
13c50d8ae3SPaolo Bonzini  * Authors:
14c50d8ae3SPaolo Bonzini  *   Yaniv Kamay  <yaniv@qumranet.com>
15c50d8ae3SPaolo Bonzini  *   Avi Kivity   <avi@qumranet.com>
16c50d8ae3SPaolo Bonzini  */
178d20bd63SSean Christopherson #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18c50d8ae3SPaolo Bonzini 
19c50d8ae3SPaolo Bonzini #include "irq.h"
2088197e6aS彭浩(Richard) #include "ioapic.h"
21c50d8ae3SPaolo Bonzini #include "mmu.h"
226ca9a6f3SSean Christopherson #include "mmu_internal.h"
23fe5db27dSBen Gardon #include "tdp_mmu.h"
24c50d8ae3SPaolo Bonzini #include "x86.h"
25c50d8ae3SPaolo Bonzini #include "kvm_cache_regs.h"
26b0b42197SPaolo Bonzini #include "smm.h"
272f728d66SSean Christopherson #include "kvm_emulate.h"
2858ea7cf7SSean Christopherson #include "page_track.h"
29c50d8ae3SPaolo Bonzini #include "cpuid.h"
305a9624afSPaolo Bonzini #include "spte.h"
31c50d8ae3SPaolo Bonzini 
32c50d8ae3SPaolo Bonzini #include <linux/kvm_host.h>
33c50d8ae3SPaolo Bonzini #include <linux/types.h>
34c50d8ae3SPaolo Bonzini #include <linux/string.h>
35c50d8ae3SPaolo Bonzini #include <linux/mm.h>
36c50d8ae3SPaolo Bonzini #include <linux/highmem.h>
37c50d8ae3SPaolo Bonzini #include <linux/moduleparam.h>
38c50d8ae3SPaolo Bonzini #include <linux/export.h>
39c50d8ae3SPaolo Bonzini #include <linux/swap.h>
40c50d8ae3SPaolo Bonzini #include <linux/hugetlb.h>
41c50d8ae3SPaolo Bonzini #include <linux/compiler.h>
42c50d8ae3SPaolo Bonzini #include <linux/srcu.h>
43c50d8ae3SPaolo Bonzini #include <linux/slab.h>
44c50d8ae3SPaolo Bonzini #include <linux/sched/signal.h>
45c50d8ae3SPaolo Bonzini #include <linux/uaccess.h>
46c50d8ae3SPaolo Bonzini #include <linux/hash.h>
47c50d8ae3SPaolo Bonzini #include <linux/kern_levels.h>
4811b36fe7SChristophe JAILLET #include <linux/kstrtox.h>
49c50d8ae3SPaolo Bonzini #include <linux/kthread.h>
5066a5c40fSTanzir Hasan #include <linux/wordpart.h>
51c50d8ae3SPaolo Bonzini 
52c50d8ae3SPaolo Bonzini #include <asm/page.h>
53eb243d1dSIngo Molnar #include <asm/memtype.h>
54c50d8ae3SPaolo Bonzini #include <asm/cmpxchg.h>
55c50d8ae3SPaolo Bonzini #include <asm/io.h>
564a98623dSSean Christopherson #include <asm/set_memory.h>
5765efc4dcSThomas Gleixner #include <asm/spec-ctrl.h>
58c50d8ae3SPaolo Bonzini #include <asm/vmx.h>
5958ea7cf7SSean Christopherson 
60c50d8ae3SPaolo Bonzini #include "trace.h"
61c50d8ae3SPaolo Bonzini 
620b210fafSSean Christopherson static bool nx_hugepage_mitigation_hard_disabled;
630b210fafSSean Christopherson 
64a9d6496dSShaokun Zhang int __read_mostly nx_huge_pages = -1;
654dfe4f40SJunaid Shahid static uint __read_mostly nx_huge_pages_recovery_period_ms;
66c50d8ae3SPaolo Bonzini #ifdef CONFIG_PREEMPT_RT
67c50d8ae3SPaolo Bonzini /* Recovery can cause latency spikes, disable it for PREEMPT_RT.  */
68c50d8ae3SPaolo Bonzini static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
69c50d8ae3SPaolo Bonzini #else
70c50d8ae3SPaolo Bonzini static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
71c50d8ae3SPaolo Bonzini #endif
72c50d8ae3SPaolo Bonzini 
730b210fafSSean Christopherson static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp);
74c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
754dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp);
76c50d8ae3SPaolo Bonzini 
77d5d6c18dSJoe Perches static const struct kernel_param_ops nx_huge_pages_ops = {
78c50d8ae3SPaolo Bonzini 	.set = set_nx_huge_pages,
790b210fafSSean Christopherson 	.get = get_nx_huge_pages,
80c50d8ae3SPaolo Bonzini };
81c50d8ae3SPaolo Bonzini 
824dfe4f40SJunaid Shahid static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
834dfe4f40SJunaid Shahid 	.set = set_nx_huge_pages_recovery_param,
84c50d8ae3SPaolo Bonzini 	.get = param_get_uint,
85c50d8ae3SPaolo Bonzini };
86c50d8ae3SPaolo Bonzini 
87c50d8ae3SPaolo Bonzini module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
88c50d8ae3SPaolo Bonzini __MODULE_PARM_TYPE(nx_huge_pages, "bool");
894dfe4f40SJunaid Shahid module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_param_ops,
90c50d8ae3SPaolo Bonzini 		&nx_huge_pages_recovery_ratio, 0644);
91c50d8ae3SPaolo Bonzini __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
924dfe4f40SJunaid Shahid module_param_cb(nx_huge_pages_recovery_period_ms, &nx_huge_pages_recovery_param_ops,
934dfe4f40SJunaid Shahid 		&nx_huge_pages_recovery_period_ms, 0644);
944dfe4f40SJunaid Shahid __MODULE_PARM_TYPE(nx_huge_pages_recovery_period_ms, "uint");
95c50d8ae3SPaolo Bonzini 
9671fe7013SSean Christopherson static bool __read_mostly force_flush_and_sync_on_reuse;
9771fe7013SSean Christopherson module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
9871fe7013SSean Christopherson 
99c50d8ae3SPaolo Bonzini /*
100c50d8ae3SPaolo Bonzini  * When setting this variable to true it enables Two-Dimensional-Paging
101c50d8ae3SPaolo Bonzini  * where the hardware walks 2 page tables:
102c50d8ae3SPaolo Bonzini  * 1. the guest-virtual to guest-physical
103c50d8ae3SPaolo Bonzini  * 2. while doing 1. it walks guest-physical to host-physical
104c50d8ae3SPaolo Bonzini  * If the hardware supports that we don't need to do shadow paging.
105c50d8ae3SPaolo Bonzini  */
106c50d8ae3SPaolo Bonzini bool tdp_enabled = false;
107c50d8ae3SPaolo Bonzini 
1087f604e92SDavid Matlack static bool __ro_after_init tdp_mmu_allowed;
1091f98f2bdSDavid Matlack 
1101f98f2bdSDavid Matlack #ifdef CONFIG_X86_64
1111f98f2bdSDavid Matlack bool __read_mostly tdp_mmu_enabled = true;
1121f98f2bdSDavid Matlack module_param_named(tdp_mmu, tdp_mmu_enabled, bool, 0444);
1131f98f2bdSDavid Matlack #endif
1141f98f2bdSDavid Matlack 
1151d92d2e8SSean Christopherson static int max_huge_page_level __read_mostly;
116746700d2SWei Huang static int tdp_root_level __read_mostly;
11783013059SSean Christopherson static int max_tdp_level __read_mostly;
118703c335dSSean Christopherson 
119c50d8ae3SPaolo Bonzini #define PTE_PREFETCH_NUM		8
120c50d8ae3SPaolo Bonzini 
121c50d8ae3SPaolo Bonzini #include <trace/events/kvm.h>
122c50d8ae3SPaolo Bonzini 
123dc1cff96SPeter Xu /* make pte_list_desc fit well in cache lines */
12413236e25SPeter Xu #define PTE_LIST_EXT 14
125c50d8ae3SPaolo Bonzini 
12613236e25SPeter Xu /*
127141705b7SLai Jiangshan  * struct pte_list_desc is the core data structure used to implement a custom
128141705b7SLai Jiangshan  * list for tracking a set of related SPTEs, e.g. all the SPTEs that map a
129141705b7SLai Jiangshan  * given GFN when used in the context of rmaps.  Using a custom list allows KVM
130141705b7SLai Jiangshan  * to optimize for the common case where many GFNs will have at most a handful
131141705b7SLai Jiangshan  * of SPTEs pointing at them, i.e. allows packing multiple SPTEs into a small
132141705b7SLai Jiangshan  * memory footprint, which in turn improves runtime performance by exploiting
133141705b7SLai Jiangshan  * cache locality.
134141705b7SLai Jiangshan  *
135141705b7SLai Jiangshan  * A list is comprised of one or more pte_list_desc objects (descriptors).
136141705b7SLai Jiangshan  * Each individual descriptor stores up to PTE_LIST_EXT SPTEs.  If a descriptor
137141705b7SLai Jiangshan  * is full and a new SPTEs needs to be added, a new descriptor is allocated and
138141705b7SLai Jiangshan  * becomes the head of the list.  This means that by definitions, all tail
139141705b7SLai Jiangshan  * descriptors are full.
140141705b7SLai Jiangshan  *
141141705b7SLai Jiangshan  * Note, the meta data fields are deliberately placed at the start of the
142141705b7SLai Jiangshan  * structure to optimize the cacheline layout; accessing the descriptor will
143141705b7SLai Jiangshan  * touch only a single cacheline so long as @spte_count<=6 (or if only the
144141705b7SLai Jiangshan  * descriptors metadata is accessed).
14513236e25SPeter Xu  */
146c50d8ae3SPaolo Bonzini struct pte_list_desc {
147c50d8ae3SPaolo Bonzini 	struct pte_list_desc *more;
148141705b7SLai Jiangshan 	/* The number of PTEs stored in _this_ descriptor. */
149141705b7SLai Jiangshan 	u32 spte_count;
150141705b7SLai Jiangshan 	/* The number of PTEs stored in all tails of this descriptor. */
151141705b7SLai Jiangshan 	u32 tail_count;
15213236e25SPeter Xu 	u64 *sptes[PTE_LIST_EXT];
153c50d8ae3SPaolo Bonzini };
154c50d8ae3SPaolo Bonzini 
155c50d8ae3SPaolo Bonzini struct kvm_shadow_walk_iterator {
156c50d8ae3SPaolo Bonzini 	u64 addr;
157c50d8ae3SPaolo Bonzini 	hpa_t shadow_addr;
158c50d8ae3SPaolo Bonzini 	u64 *sptep;
159c50d8ae3SPaolo Bonzini 	int level;
160c50d8ae3SPaolo Bonzini 	unsigned index;
161c50d8ae3SPaolo Bonzini };
162c50d8ae3SPaolo Bonzini 
163c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
164c50d8ae3SPaolo Bonzini 	for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
165c50d8ae3SPaolo Bonzini 					 (_root), (_addr));                \
166c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			           \
167c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
168c50d8ae3SPaolo Bonzini 
169c50d8ae3SPaolo Bonzini #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
170c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);	\
171c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			\
172c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
173c50d8ae3SPaolo Bonzini 
174c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)	\
175c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);		\
176c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker)) &&				\
177c50d8ae3SPaolo Bonzini 		({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });	\
178c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&(_walker), spte))
179c50d8ae3SPaolo Bonzini 
180c50d8ae3SPaolo Bonzini static struct kmem_cache *pte_list_desc_cache;
18102c00b3aSBen Gardon struct kmem_cache *mmu_page_header_cache;
182c50d8ae3SPaolo Bonzini static struct percpu_counter kvm_total_used_mmu_pages;
183c50d8ae3SPaolo Bonzini 
184c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 spte);
185c50d8ae3SPaolo Bonzini 
186594e91a1SSean Christopherson struct kvm_mmu_role_regs {
187594e91a1SSean Christopherson 	const unsigned long cr0;
188594e91a1SSean Christopherson 	const unsigned long cr4;
189594e91a1SSean Christopherson 	const u64 efer;
190594e91a1SSean Christopherson };
191594e91a1SSean Christopherson 
192c50d8ae3SPaolo Bonzini #define CREATE_TRACE_POINTS
193c50d8ae3SPaolo Bonzini #include "mmutrace.h"
194c50d8ae3SPaolo Bonzini 
195594e91a1SSean Christopherson /*
196594e91a1SSean Christopherson  * Yes, lot's of underscores.  They're a hint that you probably shouldn't be
1977a458f0eSPaolo Bonzini  * reading from the role_regs.  Once the root_role is constructed, it becomes
198594e91a1SSean Christopherson  * the single source of truth for the MMU's state.
199594e91a1SSean Christopherson  */
200594e91a1SSean Christopherson #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag)			\
20182ffa13fSPaolo Bonzini static inline bool __maybe_unused					\
20282ffa13fSPaolo Bonzini ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs)		\
203594e91a1SSean Christopherson {									\
204594e91a1SSean Christopherson 	return !!(regs->reg & flag);					\
205594e91a1SSean Christopherson }
206594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
207594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
208594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
209594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
210594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
211594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
212594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
213594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
214594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
215594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
216594e91a1SSean Christopherson 
21760667724SSean Christopherson /*
21860667724SSean Christopherson  * The MMU itself (with a valid role) is the single source of truth for the
21960667724SSean Christopherson  * MMU.  Do not use the regs used to build the MMU/role, nor the vCPU.  The
22060667724SSean Christopherson  * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
22160667724SSean Christopherson  * and the vCPU may be incorrect/irrelevant.
22260667724SSean Christopherson  */
22360667724SSean Christopherson #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name)		\
2244ac21457SPaolo Bonzini static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu)	\
22560667724SSean Christopherson {								\
226e5ed0fb0SPaolo Bonzini 	return !!(mmu->cpu_role. base_or_ext . reg##_##name);	\
22760667724SSean Christopherson }
22860667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
22960667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pse);
23060667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smep);
23160667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smap);
23260667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pke);
23360667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, la57);
23460667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
23556b321f9SPaolo Bonzini BUILD_MMU_ROLE_ACCESSOR(ext,  efer, lma);
23660667724SSean Christopherson 
237faf72962SPaolo Bonzini static inline bool is_cr0_pg(struct kvm_mmu *mmu)
238faf72962SPaolo Bonzini {
239faf72962SPaolo Bonzini         return mmu->cpu_role.base.level > 0;
240faf72962SPaolo Bonzini }
241faf72962SPaolo Bonzini 
242faf72962SPaolo Bonzini static inline bool is_cr4_pae(struct kvm_mmu *mmu)
243faf72962SPaolo Bonzini {
244faf72962SPaolo Bonzini         return !mmu->cpu_role.base.has_4_byte_gpte;
245faf72962SPaolo Bonzini }
246faf72962SPaolo Bonzini 
247594e91a1SSean Christopherson static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
248594e91a1SSean Christopherson {
249594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
250594e91a1SSean Christopherson 		.cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
251594e91a1SSean Christopherson 		.cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
252594e91a1SSean Christopherson 		.efer = vcpu->arch.efer,
253594e91a1SSean Christopherson 	};
254594e91a1SSean Christopherson 
255594e91a1SSean Christopherson 	return regs;
256594e91a1SSean Christopherson }
257c50d8ae3SPaolo Bonzini 
2582fdcc1b3SPaolo Bonzini static unsigned long get_guest_cr3(struct kvm_vcpu *vcpu)
259c50d8ae3SPaolo Bonzini {
2602fdcc1b3SPaolo Bonzini 	return kvm_read_cr3(vcpu);
261c50d8ae3SPaolo Bonzini }
262c50d8ae3SPaolo Bonzini 
2632fdcc1b3SPaolo Bonzini static inline unsigned long kvm_mmu_get_guest_pgd(struct kvm_vcpu *vcpu,
2642fdcc1b3SPaolo Bonzini 						  struct kvm_mmu *mmu)
265c50d8ae3SPaolo Bonzini {
266aefb2f2eSBreno Leitao 	if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) && mmu->get_guest_pgd == get_guest_cr3)
2672fdcc1b3SPaolo Bonzini 		return kvm_read_cr3(vcpu);
268c50d8ae3SPaolo Bonzini 
2692fdcc1b3SPaolo Bonzini 	return mmu->get_guest_pgd(vcpu);
2702fdcc1b3SPaolo Bonzini }
271c50d8ae3SPaolo Bonzini 
2728a1300ffSSean Christopherson static inline bool kvm_available_flush_remote_tlbs_range(void)
273c50d8ae3SPaolo Bonzini {
2740277022aSSean Christopherson #if IS_ENABLED(CONFIG_HYPERV)
2758a1300ffSSean Christopherson 	return kvm_x86_ops.flush_remote_tlbs_range;
2760277022aSSean Christopherson #else
2770277022aSSean Christopherson 	return false;
2780277022aSSean Christopherson #endif
279c50d8ae3SPaolo Bonzini }
280c50d8ae3SPaolo Bonzini 
2811b2dc736SHou Wenlong static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index);
2821b2dc736SHou Wenlong 
2831b2dc736SHou Wenlong /* Flush the range of guest memory mapped by the given SPTE. */
2841b2dc736SHou Wenlong static void kvm_flush_remote_tlbs_sptep(struct kvm *kvm, u64 *sptep)
2851b2dc736SHou Wenlong {
2861b2dc736SHou Wenlong 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2871b2dc736SHou Wenlong 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, spte_index(sptep));
2881b2dc736SHou Wenlong 
2891b2dc736SHou Wenlong 	kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
2901b2dc736SHou Wenlong }
2911b2dc736SHou Wenlong 
2928f79b064SBen Gardon static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
2938f79b064SBen Gardon 			   unsigned int access)
2948f79b064SBen Gardon {
295c236d962SSean Christopherson 	u64 spte = make_mmio_spte(vcpu, gfn, access);
2968f79b064SBen Gardon 
297c236d962SSean Christopherson 	trace_mark_mmio_spte(sptep, gfn, spte);
298c236d962SSean Christopherson 	mmu_spte_set(sptep, spte);
299c50d8ae3SPaolo Bonzini }
300c50d8ae3SPaolo Bonzini 
301c50d8ae3SPaolo Bonzini static gfn_t get_mmio_spte_gfn(u64 spte)
302c50d8ae3SPaolo Bonzini {
303c50d8ae3SPaolo Bonzini 	u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
304c50d8ae3SPaolo Bonzini 
3058a967d65SPaolo Bonzini 	gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
306c50d8ae3SPaolo Bonzini 	       & shadow_nonpresent_or_rsvd_mask;
307c50d8ae3SPaolo Bonzini 
308c50d8ae3SPaolo Bonzini 	return gpa >> PAGE_SHIFT;
309c50d8ae3SPaolo Bonzini }
310c50d8ae3SPaolo Bonzini 
311c50d8ae3SPaolo Bonzini static unsigned get_mmio_spte_access(u64 spte)
312c50d8ae3SPaolo Bonzini {
313c50d8ae3SPaolo Bonzini 	return spte & shadow_mmio_access_mask;
314c50d8ae3SPaolo Bonzini }
315c50d8ae3SPaolo Bonzini 
316c50d8ae3SPaolo Bonzini static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
317c50d8ae3SPaolo Bonzini {
318c50d8ae3SPaolo Bonzini 	u64 kvm_gen, spte_gen, gen;
319c50d8ae3SPaolo Bonzini 
320c50d8ae3SPaolo Bonzini 	gen = kvm_vcpu_memslots(vcpu)->generation;
321c50d8ae3SPaolo Bonzini 	if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
322c50d8ae3SPaolo Bonzini 		return false;
323c50d8ae3SPaolo Bonzini 
324c50d8ae3SPaolo Bonzini 	kvm_gen = gen & MMIO_SPTE_GEN_MASK;
325c50d8ae3SPaolo Bonzini 	spte_gen = get_mmio_spte_generation(spte);
326c50d8ae3SPaolo Bonzini 
327c50d8ae3SPaolo Bonzini 	trace_check_mmio_spte(spte, kvm_gen, spte_gen);
328c50d8ae3SPaolo Bonzini 	return likely(kvm_gen == spte_gen);
329c50d8ae3SPaolo Bonzini }
330c50d8ae3SPaolo Bonzini 
331c50d8ae3SPaolo Bonzini static int is_cpuid_PSE36(void)
332c50d8ae3SPaolo Bonzini {
333c50d8ae3SPaolo Bonzini 	return 1;
334c50d8ae3SPaolo Bonzini }
335c50d8ae3SPaolo Bonzini 
336c50d8ae3SPaolo Bonzini #ifdef CONFIG_X86_64
337c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
338c50d8ae3SPaolo Bonzini {
339c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
340c50d8ae3SPaolo Bonzini }
341c50d8ae3SPaolo Bonzini 
342c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
343c50d8ae3SPaolo Bonzini {
344c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
345c50d8ae3SPaolo Bonzini }
346c50d8ae3SPaolo Bonzini 
347c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
348c50d8ae3SPaolo Bonzini {
349c50d8ae3SPaolo Bonzini 	return xchg(sptep, spte);
350c50d8ae3SPaolo Bonzini }
351c50d8ae3SPaolo Bonzini 
352c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
353c50d8ae3SPaolo Bonzini {
354c50d8ae3SPaolo Bonzini 	return READ_ONCE(*sptep);
355c50d8ae3SPaolo Bonzini }
356c50d8ae3SPaolo Bonzini #else
357c50d8ae3SPaolo Bonzini union split_spte {
358c50d8ae3SPaolo Bonzini 	struct {
359c50d8ae3SPaolo Bonzini 		u32 spte_low;
360c50d8ae3SPaolo Bonzini 		u32 spte_high;
361c50d8ae3SPaolo Bonzini 	};
362c50d8ae3SPaolo Bonzini 	u64 spte;
363c50d8ae3SPaolo Bonzini };
364c50d8ae3SPaolo Bonzini 
365c50d8ae3SPaolo Bonzini static void count_spte_clear(u64 *sptep, u64 spte)
366c50d8ae3SPaolo Bonzini {
36757354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
368c50d8ae3SPaolo Bonzini 
369c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(spte))
370c50d8ae3SPaolo Bonzini 		return;
371c50d8ae3SPaolo Bonzini 
372c50d8ae3SPaolo Bonzini 	/* Ensure the spte is completely set before we increase the count */
373c50d8ae3SPaolo Bonzini 	smp_wmb();
374c50d8ae3SPaolo Bonzini 	sp->clear_spte_count++;
375c50d8ae3SPaolo Bonzini }
376c50d8ae3SPaolo Bonzini 
377c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
378c50d8ae3SPaolo Bonzini {
379c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
380c50d8ae3SPaolo Bonzini 
381c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
382c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
383c50d8ae3SPaolo Bonzini 
384c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
385c50d8ae3SPaolo Bonzini 
386c50d8ae3SPaolo Bonzini 	/*
387c50d8ae3SPaolo Bonzini 	 * If we map the spte from nonpresent to present, We should store
388c50d8ae3SPaolo Bonzini 	 * the high bits firstly, then set present bit, so cpu can not
389c50d8ae3SPaolo Bonzini 	 * fetch this spte while we are setting the spte.
390c50d8ae3SPaolo Bonzini 	 */
391c50d8ae3SPaolo Bonzini 	smp_wmb();
392c50d8ae3SPaolo Bonzini 
393c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
394c50d8ae3SPaolo Bonzini }
395c50d8ae3SPaolo Bonzini 
396c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
397c50d8ae3SPaolo Bonzini {
398c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
399c50d8ae3SPaolo Bonzini 
400c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
401c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
402c50d8ae3SPaolo Bonzini 
403c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
404c50d8ae3SPaolo Bonzini 
405c50d8ae3SPaolo Bonzini 	/*
406c50d8ae3SPaolo Bonzini 	 * If we map the spte from present to nonpresent, we should clear
407c50d8ae3SPaolo Bonzini 	 * present bit firstly to avoid vcpu fetch the old high bits.
408c50d8ae3SPaolo Bonzini 	 */
409c50d8ae3SPaolo Bonzini 	smp_wmb();
410c50d8ae3SPaolo Bonzini 
411c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
412c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
413c50d8ae3SPaolo Bonzini }
414c50d8ae3SPaolo Bonzini 
415c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
416c50d8ae3SPaolo Bonzini {
417c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte, orig;
418c50d8ae3SPaolo Bonzini 
419c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
420c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
421c50d8ae3SPaolo Bonzini 
422c50d8ae3SPaolo Bonzini 	/* xchg acts as a barrier before the setting of the high bits */
423c50d8ae3SPaolo Bonzini 	orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
424c50d8ae3SPaolo Bonzini 	orig.spte_high = ssptep->spte_high;
425c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
426c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
427c50d8ae3SPaolo Bonzini 
428c50d8ae3SPaolo Bonzini 	return orig.spte;
429c50d8ae3SPaolo Bonzini }
430c50d8ae3SPaolo Bonzini 
431c50d8ae3SPaolo Bonzini /*
432c50d8ae3SPaolo Bonzini  * The idea using the light way get the spte on x86_32 guest is from
433c50d8ae3SPaolo Bonzini  * gup_get_pte (mm/gup.c).
434c50d8ae3SPaolo Bonzini  *
435f3b65bbaSPaolo Bonzini  * An spte tlb flush may be pending, because they are coalesced and
436f3b65bbaSPaolo Bonzini  * we are running out of the MMU lock.  Therefore
437c50d8ae3SPaolo Bonzini  * we need to protect against in-progress updates of the spte.
438c50d8ae3SPaolo Bonzini  *
439c50d8ae3SPaolo Bonzini  * Reading the spte while an update is in progress may get the old value
440c50d8ae3SPaolo Bonzini  * for the high part of the spte.  The race is fine for a present->non-present
441c50d8ae3SPaolo Bonzini  * change (because the high part of the spte is ignored for non-present spte),
442c50d8ae3SPaolo Bonzini  * but for a present->present change we must reread the spte.
443c50d8ae3SPaolo Bonzini  *
444c50d8ae3SPaolo Bonzini  * All such changes are done in two steps (present->non-present and
445c50d8ae3SPaolo Bonzini  * non-present->present), hence it is enough to count the number of
446c50d8ae3SPaolo Bonzini  * present->non-present updates: if it changed while reading the spte,
447c50d8ae3SPaolo Bonzini  * we might have hit the race.  This is done using clear_spte_count.
448c50d8ae3SPaolo Bonzini  */
449c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
450c50d8ae3SPaolo Bonzini {
45157354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
452c50d8ae3SPaolo Bonzini 	union split_spte spte, *orig = (union split_spte *)sptep;
453c50d8ae3SPaolo Bonzini 	int count;
454c50d8ae3SPaolo Bonzini 
455c50d8ae3SPaolo Bonzini retry:
456c50d8ae3SPaolo Bonzini 	count = sp->clear_spte_count;
457c50d8ae3SPaolo Bonzini 	smp_rmb();
458c50d8ae3SPaolo Bonzini 
459c50d8ae3SPaolo Bonzini 	spte.spte_low = orig->spte_low;
460c50d8ae3SPaolo Bonzini 	smp_rmb();
461c50d8ae3SPaolo Bonzini 
462c50d8ae3SPaolo Bonzini 	spte.spte_high = orig->spte_high;
463c50d8ae3SPaolo Bonzini 	smp_rmb();
464c50d8ae3SPaolo Bonzini 
465c50d8ae3SPaolo Bonzini 	if (unlikely(spte.spte_low != orig->spte_low ||
466c50d8ae3SPaolo Bonzini 	      count != sp->clear_spte_count))
467c50d8ae3SPaolo Bonzini 		goto retry;
468c50d8ae3SPaolo Bonzini 
469c50d8ae3SPaolo Bonzini 	return spte.spte;
470c50d8ae3SPaolo Bonzini }
471c50d8ae3SPaolo Bonzini #endif
472c50d8ae3SPaolo Bonzini 
473c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_set:
474c50d8ae3SPaolo Bonzini  * Set the sptep from nonpresent to present.
475c50d8ae3SPaolo Bonzini  * Note: the sptep being assigned *must* be either not present
476c50d8ae3SPaolo Bonzini  * or in a state where the hardware will not attempt to update
477c50d8ae3SPaolo Bonzini  * the spte.
478c50d8ae3SPaolo Bonzini  */
479c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 new_spte)
480c50d8ae3SPaolo Bonzini {
48120ba462dSSean Christopherson 	WARN_ON_ONCE(is_shadow_present_pte(*sptep));
482c50d8ae3SPaolo Bonzini 	__set_spte(sptep, new_spte);
483c50d8ae3SPaolo Bonzini }
484c50d8ae3SPaolo Bonzini 
485c50d8ae3SPaolo Bonzini /*
486c50d8ae3SPaolo Bonzini  * Update the SPTE (excluding the PFN), but do not track changes in its
487c50d8ae3SPaolo Bonzini  * accessed/dirty status.
488c50d8ae3SPaolo Bonzini  */
489c50d8ae3SPaolo Bonzini static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
490c50d8ae3SPaolo Bonzini {
491c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
492c50d8ae3SPaolo Bonzini 
49320ba462dSSean Christopherson 	WARN_ON_ONCE(!is_shadow_present_pte(new_spte));
494115111efSDavid Matlack 	check_spte_writable_invariants(new_spte);
495c50d8ae3SPaolo Bonzini 
496c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte)) {
497c50d8ae3SPaolo Bonzini 		mmu_spte_set(sptep, new_spte);
498c50d8ae3SPaolo Bonzini 		return old_spte;
499c50d8ae3SPaolo Bonzini 	}
500c50d8ae3SPaolo Bonzini 
501c50d8ae3SPaolo Bonzini 	if (!spte_has_volatile_bits(old_spte))
502c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, new_spte);
503c50d8ae3SPaolo Bonzini 	else
504c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, new_spte);
505c50d8ae3SPaolo Bonzini 
50620ba462dSSean Christopherson 	WARN_ON_ONCE(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
507c50d8ae3SPaolo Bonzini 
508c50d8ae3SPaolo Bonzini 	return old_spte;
509c50d8ae3SPaolo Bonzini }
510c50d8ae3SPaolo Bonzini 
511c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_update:
512c50d8ae3SPaolo Bonzini  * Update the state bits, it means the mapped pfn is not changed.
513c50d8ae3SPaolo Bonzini  *
51402844ac1SDavid Matlack  * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
51502844ac1SDavid Matlack  * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
51602844ac1SDavid Matlack  * spte, even though the writable spte might be cached on a CPU's TLB.
517c50d8ae3SPaolo Bonzini  *
518c50d8ae3SPaolo Bonzini  * Returns true if the TLB needs to be flushed
519c50d8ae3SPaolo Bonzini  */
520c50d8ae3SPaolo Bonzini static bool mmu_spte_update(u64 *sptep, u64 new_spte)
521c50d8ae3SPaolo Bonzini {
522c50d8ae3SPaolo Bonzini 	bool flush = false;
523c50d8ae3SPaolo Bonzini 	u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
524c50d8ae3SPaolo Bonzini 
525c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
526c50d8ae3SPaolo Bonzini 		return false;
527c50d8ae3SPaolo Bonzini 
528c50d8ae3SPaolo Bonzini 	/*
529c50d8ae3SPaolo Bonzini 	 * For the spte updated out of mmu-lock is safe, since
530c50d8ae3SPaolo Bonzini 	 * we always atomically update it, see the comments in
531c50d8ae3SPaolo Bonzini 	 * spte_has_volatile_bits().
532c50d8ae3SPaolo Bonzini 	 */
533706c9c55SSean Christopherson 	if (is_mmu_writable_spte(old_spte) &&
534c50d8ae3SPaolo Bonzini 	      !is_writable_pte(new_spte))
535c50d8ae3SPaolo Bonzini 		flush = true;
536c50d8ae3SPaolo Bonzini 
537c50d8ae3SPaolo Bonzini 	/*
538c50d8ae3SPaolo Bonzini 	 * Flush TLB when accessed/dirty states are changed in the page tables,
539c50d8ae3SPaolo Bonzini 	 * to guarantee consistency between TLB and page tables.
540c50d8ae3SPaolo Bonzini 	 */
541c50d8ae3SPaolo Bonzini 
542c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
543c50d8ae3SPaolo Bonzini 		flush = true;
544c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(spte_to_pfn(old_spte));
545c50d8ae3SPaolo Bonzini 	}
546c50d8ae3SPaolo Bonzini 
547c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
548c50d8ae3SPaolo Bonzini 		flush = true;
549c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(old_spte));
550c50d8ae3SPaolo Bonzini 	}
551c50d8ae3SPaolo Bonzini 
552c50d8ae3SPaolo Bonzini 	return flush;
553c50d8ae3SPaolo Bonzini }
554c50d8ae3SPaolo Bonzini 
555c50d8ae3SPaolo Bonzini /*
556c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_track_bits:
557c50d8ae3SPaolo Bonzini  * It sets the sptep from present to nonpresent, and track the
558c50d8ae3SPaolo Bonzini  * state bits, it is used to clear the last level sptep.
5597fa2a347SSean Christopherson  * Returns the old PTE.
560c50d8ae3SPaolo Bonzini  */
56135d539c3SSean Christopherson static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
562c50d8ae3SPaolo Bonzini {
563c50d8ae3SPaolo Bonzini 	kvm_pfn_t pfn;
564c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
56571f51d2cSMingwei Zhang 	int level = sptep_to_sp(sptep)->role.level;
566b14b2690SSean Christopherson 	struct page *page;
567c50d8ae3SPaolo Bonzini 
56854eb3ef5SSean Christopherson 	if (!is_shadow_present_pte(old_spte) ||
56954eb3ef5SSean Christopherson 	    !spte_has_volatile_bits(old_spte))
570c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, 0ull);
571c50d8ae3SPaolo Bonzini 	else
572c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, 0ull);
573c50d8ae3SPaolo Bonzini 
574c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
5757fa2a347SSean Christopherson 		return old_spte;
576c50d8ae3SPaolo Bonzini 
57771f51d2cSMingwei Zhang 	kvm_update_page_stats(kvm, level, -1);
57871f51d2cSMingwei Zhang 
579c50d8ae3SPaolo Bonzini 	pfn = spte_to_pfn(old_spte);
580c50d8ae3SPaolo Bonzini 
581c50d8ae3SPaolo Bonzini 	/*
582b14b2690SSean Christopherson 	 * KVM doesn't hold a reference to any pages mapped into the guest, and
583b14b2690SSean Christopherson 	 * instead uses the mmu_notifier to ensure that KVM unmaps any pages
584b14b2690SSean Christopherson 	 * before they are reclaimed.  Sanity check that, if the pfn is backed
585b14b2690SSean Christopherson 	 * by a refcounted page, the refcount is elevated.
586c50d8ae3SPaolo Bonzini 	 */
587b14b2690SSean Christopherson 	page = kvm_pfn_to_refcounted_page(pfn);
58820ba462dSSean Christopherson 	WARN_ON_ONCE(page && !page_count(page));
589c50d8ae3SPaolo Bonzini 
590c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte))
591c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(pfn);
592c50d8ae3SPaolo Bonzini 
593c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte))
594c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(pfn);
595c50d8ae3SPaolo Bonzini 
5967fa2a347SSean Christopherson 	return old_spte;
597c50d8ae3SPaolo Bonzini }
598c50d8ae3SPaolo Bonzini 
599c50d8ae3SPaolo Bonzini /*
600c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_no_track:
601c50d8ae3SPaolo Bonzini  * Directly clear spte without caring the state bits of sptep,
602c50d8ae3SPaolo Bonzini  * it is used to set the upper level spte.
603c50d8ae3SPaolo Bonzini  */
604c50d8ae3SPaolo Bonzini static void mmu_spte_clear_no_track(u64 *sptep)
605c50d8ae3SPaolo Bonzini {
606c50d8ae3SPaolo Bonzini 	__update_clear_spte_fast(sptep, 0ull);
607c50d8ae3SPaolo Bonzini }
608c50d8ae3SPaolo Bonzini 
609c50d8ae3SPaolo Bonzini static u64 mmu_spte_get_lockless(u64 *sptep)
610c50d8ae3SPaolo Bonzini {
611c50d8ae3SPaolo Bonzini 	return __get_spte_lockless(sptep);
612c50d8ae3SPaolo Bonzini }
613c50d8ae3SPaolo Bonzini 
614c50d8ae3SPaolo Bonzini /* Returns the Accessed status of the PTE and resets it at the same time. */
615c50d8ae3SPaolo Bonzini static bool mmu_spte_age(u64 *sptep)
616c50d8ae3SPaolo Bonzini {
617c50d8ae3SPaolo Bonzini 	u64 spte = mmu_spte_get_lockless(sptep);
618c50d8ae3SPaolo Bonzini 
619c50d8ae3SPaolo Bonzini 	if (!is_accessed_spte(spte))
620c50d8ae3SPaolo Bonzini 		return false;
621c50d8ae3SPaolo Bonzini 
622c50d8ae3SPaolo Bonzini 	if (spte_ad_enabled(spte)) {
623c50d8ae3SPaolo Bonzini 		clear_bit((ffs(shadow_accessed_mask) - 1),
624c50d8ae3SPaolo Bonzini 			  (unsigned long *)sptep);
625c50d8ae3SPaolo Bonzini 	} else {
626c50d8ae3SPaolo Bonzini 		/*
627c50d8ae3SPaolo Bonzini 		 * Capture the dirty status of the page, so that it doesn't get
628c50d8ae3SPaolo Bonzini 		 * lost when the SPTE is marked for access tracking.
629c50d8ae3SPaolo Bonzini 		 */
630c50d8ae3SPaolo Bonzini 		if (is_writable_pte(spte))
631c50d8ae3SPaolo Bonzini 			kvm_set_pfn_dirty(spte_to_pfn(spte));
632c50d8ae3SPaolo Bonzini 
633c50d8ae3SPaolo Bonzini 		spte = mark_spte_for_access_track(spte);
634c50d8ae3SPaolo Bonzini 		mmu_spte_update_no_track(sptep, spte);
635c50d8ae3SPaolo Bonzini 	}
636c50d8ae3SPaolo Bonzini 
637c50d8ae3SPaolo Bonzini 	return true;
638c50d8ae3SPaolo Bonzini }
639c50d8ae3SPaolo Bonzini 
64078fdd2f0SSean Christopherson static inline bool is_tdp_mmu_active(struct kvm_vcpu *vcpu)
64178fdd2f0SSean Christopherson {
64278fdd2f0SSean Christopherson 	return tdp_mmu_enabled && vcpu->arch.mmu->root_role.direct;
64378fdd2f0SSean Christopherson }
64478fdd2f0SSean Christopherson 
645c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
646c50d8ae3SPaolo Bonzini {
64778fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu)) {
648c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_begin();
649c5c8c7c5SDavid Matlack 	} else {
650c50d8ae3SPaolo Bonzini 		/*
651c50d8ae3SPaolo Bonzini 		 * Prevent page table teardown by making any free-er wait during
652c50d8ae3SPaolo Bonzini 		 * kvm_flush_remote_tlbs() IPI to all active vcpus.
653c50d8ae3SPaolo Bonzini 		 */
654c50d8ae3SPaolo Bonzini 		local_irq_disable();
655c50d8ae3SPaolo Bonzini 
656c50d8ae3SPaolo Bonzini 		/*
657c50d8ae3SPaolo Bonzini 		 * Make sure a following spte read is not reordered ahead of the write
658c50d8ae3SPaolo Bonzini 		 * to vcpu->mode.
659c50d8ae3SPaolo Bonzini 		 */
660c50d8ae3SPaolo Bonzini 		smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
661c50d8ae3SPaolo Bonzini 	}
662c5c8c7c5SDavid Matlack }
663c50d8ae3SPaolo Bonzini 
664c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
665c50d8ae3SPaolo Bonzini {
66678fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu)) {
667c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_end();
668c5c8c7c5SDavid Matlack 	} else {
669c50d8ae3SPaolo Bonzini 		/*
670c50d8ae3SPaolo Bonzini 		 * Make sure the write to vcpu->mode is not reordered in front of
671c50d8ae3SPaolo Bonzini 		 * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
672c50d8ae3SPaolo Bonzini 		 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
673c50d8ae3SPaolo Bonzini 		 */
674c50d8ae3SPaolo Bonzini 		smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
675c50d8ae3SPaolo Bonzini 		local_irq_enable();
676c50d8ae3SPaolo Bonzini 	}
677c5c8c7c5SDavid Matlack }
678c50d8ae3SPaolo Bonzini 
679378f5cd6SSean Christopherson static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
680c50d8ae3SPaolo Bonzini {
681c50d8ae3SPaolo Bonzini 	int r;
682c50d8ae3SPaolo Bonzini 
683531281adSSean Christopherson 	/* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
68494ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
685531281adSSean Christopherson 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
686c50d8ae3SPaolo Bonzini 	if (r)
687c50d8ae3SPaolo Bonzini 		return r;
68894ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
689171a90d7SSean Christopherson 				       PT64_ROOT_MAX_LEVEL);
690171a90d7SSean Christopherson 	if (r)
691171a90d7SSean Christopherson 		return r;
692378f5cd6SSean Christopherson 	if (maybe_indirect) {
6936a97575dSDavid Matlack 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
694171a90d7SSean Christopherson 					       PT64_ROOT_MAX_LEVEL);
695c50d8ae3SPaolo Bonzini 		if (r)
696c50d8ae3SPaolo Bonzini 			return r;
697378f5cd6SSean Christopherson 	}
69894ce87efSSean Christopherson 	return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
699531281adSSean Christopherson 					  PT64_ROOT_MAX_LEVEL);
700c50d8ae3SPaolo Bonzini }
701c50d8ae3SPaolo Bonzini 
702c50d8ae3SPaolo Bonzini static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
703c50d8ae3SPaolo Bonzini {
70494ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
70594ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
7066a97575dSDavid Matlack 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
70794ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
708c50d8ae3SPaolo Bonzini }
709c50d8ae3SPaolo Bonzini 
710c50d8ae3SPaolo Bonzini static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
711c50d8ae3SPaolo Bonzini {
712c50d8ae3SPaolo Bonzini 	kmem_cache_free(pte_list_desc_cache, pte_list_desc);
713c50d8ae3SPaolo Bonzini }
714c50d8ae3SPaolo Bonzini 
7156a97575dSDavid Matlack static bool sp_has_gptes(struct kvm_mmu_page *sp);
7166a97575dSDavid Matlack 
717c50d8ae3SPaolo Bonzini static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
718c50d8ae3SPaolo Bonzini {
71984e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
72084e5ffd0SLai Jiangshan 		return sp->gfn;
72184e5ffd0SLai Jiangshan 
722c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
7236a97575dSDavid Matlack 		return sp->shadowed_translation[index] >> PAGE_SHIFT;
724c50d8ae3SPaolo Bonzini 
7252ca3129eSSean Christopherson 	return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
726c50d8ae3SPaolo Bonzini }
727c50d8ae3SPaolo Bonzini 
7286a97575dSDavid Matlack /*
7296a97575dSDavid Matlack  * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
7306a97575dSDavid Matlack  * that the SPTE itself may have a more constrained access permissions that
7316a97575dSDavid Matlack  * what the guest enforces. For example, a guest may create an executable
7326a97575dSDavid Matlack  * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
7336a97575dSDavid Matlack  */
7346a97575dSDavid Matlack static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
735c50d8ae3SPaolo Bonzini {
7366a97575dSDavid Matlack 	if (sp_has_gptes(sp))
7376a97575dSDavid Matlack 		return sp->shadowed_translation[index] & ACC_ALL;
7386a97575dSDavid Matlack 
7396a97575dSDavid Matlack 	/*
7406a97575dSDavid Matlack 	 * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
7416a97575dSDavid Matlack 	 * KVM is not shadowing any guest page tables, so the "guest access
7426a97575dSDavid Matlack 	 * permissions" are just ACC_ALL.
7436a97575dSDavid Matlack 	 *
7446a97575dSDavid Matlack 	 * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
7456a97575dSDavid Matlack 	 * is shadowing a guest huge page with small pages, the guest access
7466a97575dSDavid Matlack 	 * permissions being shadowed are the access permissions of the huge
7476a97575dSDavid Matlack 	 * page.
7486a97575dSDavid Matlack 	 *
7496a97575dSDavid Matlack 	 * In both cases, sp->role.access contains the correct access bits.
7506a97575dSDavid Matlack 	 */
7516a97575dSDavid Matlack 	return sp->role.access;
7526a97575dSDavid Matlack }
7536a97575dSDavid Matlack 
75472ae5822SSean Christopherson static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
75572ae5822SSean Christopherson 					 gfn_t gfn, unsigned int access)
7566a97575dSDavid Matlack {
7576a97575dSDavid Matlack 	if (sp_has_gptes(sp)) {
7586a97575dSDavid Matlack 		sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
75984e5ffd0SLai Jiangshan 		return;
76084e5ffd0SLai Jiangshan 	}
76184e5ffd0SLai Jiangshan 
7626a97575dSDavid Matlack 	WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
7636a97575dSDavid Matlack 	          "access mismatch under %s page %llx (expected %u, got %u)\n",
7646a97575dSDavid Matlack 	          sp->role.passthrough ? "passthrough" : "direct",
7656a97575dSDavid Matlack 	          sp->gfn, kvm_mmu_page_get_access(sp, index), access);
7666a97575dSDavid Matlack 
7676a97575dSDavid Matlack 	WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
7686a97575dSDavid Matlack 	          "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
7696a97575dSDavid Matlack 	          sp->role.passthrough ? "passthrough" : "direct",
7706a97575dSDavid Matlack 	          sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
771c50d8ae3SPaolo Bonzini }
772c50d8ae3SPaolo Bonzini 
77372ae5822SSean Christopherson static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
77472ae5822SSean Christopherson 				    unsigned int access)
7756a97575dSDavid Matlack {
7766a97575dSDavid Matlack 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
7776a97575dSDavid Matlack 
7786a97575dSDavid Matlack 	kvm_mmu_page_set_translation(sp, index, gfn, access);
779c50d8ae3SPaolo Bonzini }
780c50d8ae3SPaolo Bonzini 
781c50d8ae3SPaolo Bonzini /*
782c50d8ae3SPaolo Bonzini  * Return the pointer to the large page information for a given gfn,
783c50d8ae3SPaolo Bonzini  * handling slots that are not large page aligned.
784c50d8ae3SPaolo Bonzini  */
785c50d8ae3SPaolo Bonzini static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
7868ca6f063SBen Gardon 		const struct kvm_memory_slot *slot, int level)
787c50d8ae3SPaolo Bonzini {
788c50d8ae3SPaolo Bonzini 	unsigned long idx;
789c50d8ae3SPaolo Bonzini 
790c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
791c50d8ae3SPaolo Bonzini 	return &slot->arch.lpage_info[level - 2][idx];
792c50d8ae3SPaolo Bonzini }
793c50d8ae3SPaolo Bonzini 
79490b4fe17SChao Peng /*
79590b4fe17SChao Peng  * The most significant bit in disallow_lpage tracks whether or not memory
79690b4fe17SChao Peng  * attributes are mixed, i.e. not identical for all gfns at the current level.
79790b4fe17SChao Peng  * The lower order bits are used to refcount other cases where a hugepage is
79890b4fe17SChao Peng  * disallowed, e.g. if KVM has shadow a page table at the gfn.
79990b4fe17SChao Peng  */
80090b4fe17SChao Peng #define KVM_LPAGE_MIXED_FLAG	BIT(31)
80190b4fe17SChao Peng 
802269e9552SHamza Mahfooz static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
803c50d8ae3SPaolo Bonzini 					    gfn_t gfn, int count)
804c50d8ae3SPaolo Bonzini {
805c50d8ae3SPaolo Bonzini 	struct kvm_lpage_info *linfo;
80690b4fe17SChao Peng 	int old, i;
807c50d8ae3SPaolo Bonzini 
8083bae0459SSean Christopherson 	for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
809c50d8ae3SPaolo Bonzini 		linfo = lpage_info_slot(gfn, slot, i);
81090b4fe17SChao Peng 
81190b4fe17SChao Peng 		old = linfo->disallow_lpage;
812c50d8ae3SPaolo Bonzini 		linfo->disallow_lpage += count;
81390b4fe17SChao Peng 		WARN_ON_ONCE((old ^ linfo->disallow_lpage) & KVM_LPAGE_MIXED_FLAG);
814c50d8ae3SPaolo Bonzini 	}
815c50d8ae3SPaolo Bonzini }
816c50d8ae3SPaolo Bonzini 
817269e9552SHamza Mahfooz void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
818c50d8ae3SPaolo Bonzini {
819c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, 1);
820c50d8ae3SPaolo Bonzini }
821c50d8ae3SPaolo Bonzini 
822269e9552SHamza Mahfooz void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
823c50d8ae3SPaolo Bonzini {
824c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, -1);
825c50d8ae3SPaolo Bonzini }
826c50d8ae3SPaolo Bonzini 
827c50d8ae3SPaolo Bonzini static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
828c50d8ae3SPaolo Bonzini {
829c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
830c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
831c50d8ae3SPaolo Bonzini 	gfn_t gfn;
832c50d8ae3SPaolo Bonzini 
833c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages++;
834c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
835c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
836c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
837c50d8ae3SPaolo Bonzini 
838c50d8ae3SPaolo Bonzini 	/* the non-leaf shadow pages are keeping readonly. */
8393bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
84096316a06SSean Christopherson 		return __kvm_write_track_add_gfn(kvm, slot, gfn);
841c50d8ae3SPaolo Bonzini 
842c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
843be911771SDavid Matlack 
844be911771SDavid Matlack 	if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
8454ad980aeSHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, PG_LEVEL_4K);
846c50d8ae3SPaolo Bonzini }
847c50d8ae3SPaolo Bonzini 
84861f94478SSean Christopherson void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
849c50d8ae3SPaolo Bonzini {
850428e9216SSean Christopherson 	/*
851428e9216SSean Christopherson 	 * If it's possible to replace the shadow page with an NX huge page,
852428e9216SSean Christopherson 	 * i.e. if the shadow page is the only thing currently preventing KVM
853428e9216SSean Christopherson 	 * from using a huge page, add the shadow page to the list of "to be
854428e9216SSean Christopherson 	 * zapped for NX recovery" pages.  Note, the shadow page can already be
855428e9216SSean Christopherson 	 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
856428e9216SSean Christopherson 	 * links a shadow page at multiple points.
857428e9216SSean Christopherson 	 */
85861f94478SSean Christopherson 	if (!list_empty(&sp->possible_nx_huge_page_link))
859c50d8ae3SPaolo Bonzini 		return;
860c50d8ae3SPaolo Bonzini 
861c50d8ae3SPaolo Bonzini 	++kvm->stat.nx_lpage_splits;
86255c510e2SSean Christopherson 	list_add_tail(&sp->possible_nx_huge_page_link,
86355c510e2SSean Christopherson 		      &kvm->arch.possible_nx_huge_pages);
864c50d8ae3SPaolo Bonzini }
865c50d8ae3SPaolo Bonzini 
86661f94478SSean Christopherson static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
86761f94478SSean Christopherson 				 bool nx_huge_page_possible)
86861f94478SSean Christopherson {
86961f94478SSean Christopherson 	sp->nx_huge_page_disallowed = true;
87061f94478SSean Christopherson 
87161f94478SSean Christopherson 	if (nx_huge_page_possible)
87261f94478SSean Christopherson 		track_possible_nx_huge_page(kvm, sp);
873c50d8ae3SPaolo Bonzini }
874c50d8ae3SPaolo Bonzini 
875c50d8ae3SPaolo Bonzini static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
876c50d8ae3SPaolo Bonzini {
877c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
878c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
879c50d8ae3SPaolo Bonzini 	gfn_t gfn;
880c50d8ae3SPaolo Bonzini 
881c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages--;
882c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
883c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
884c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
8853bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
88696316a06SSean Christopherson 		return __kvm_write_track_remove_gfn(kvm, slot, gfn);
887c50d8ae3SPaolo Bonzini 
888c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_allow_lpage(slot, gfn);
889c50d8ae3SPaolo Bonzini }
890c50d8ae3SPaolo Bonzini 
89161f94478SSean Christopherson void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
892c50d8ae3SPaolo Bonzini {
89355c510e2SSean Christopherson 	if (list_empty(&sp->possible_nx_huge_page_link))
894428e9216SSean Christopherson 		return;
895428e9216SSean Christopherson 
896c50d8ae3SPaolo Bonzini 	--kvm->stat.nx_lpage_splits;
89755c510e2SSean Christopherson 	list_del_init(&sp->possible_nx_huge_page_link);
898c50d8ae3SPaolo Bonzini }
899c50d8ae3SPaolo Bonzini 
90061f94478SSean Christopherson static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
90161f94478SSean Christopherson {
90261f94478SSean Christopherson 	sp->nx_huge_page_disallowed = false;
90361f94478SSean Christopherson 
90461f94478SSean Christopherson 	untrack_possible_nx_huge_page(kvm, sp);
905c50d8ae3SPaolo Bonzini }
906c50d8ae3SPaolo Bonzini 
907f3d90f90SSean Christopherson static struct kvm_memory_slot *gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu,
908f3d90f90SSean Christopherson 							   gfn_t gfn,
909c50d8ae3SPaolo Bonzini 							   bool no_dirty_log)
910c50d8ae3SPaolo Bonzini {
911c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
912c50d8ae3SPaolo Bonzini 
913c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
91491b0d268SPaolo Bonzini 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
91591b0d268SPaolo Bonzini 		return NULL;
916044c59c4SPeter Xu 	if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
91791b0d268SPaolo Bonzini 		return NULL;
918c50d8ae3SPaolo Bonzini 
919c50d8ae3SPaolo Bonzini 	return slot;
920c50d8ae3SPaolo Bonzini }
921c50d8ae3SPaolo Bonzini 
922c50d8ae3SPaolo Bonzini /*
923c50d8ae3SPaolo Bonzini  * About rmap_head encoding:
924c50d8ae3SPaolo Bonzini  *
925c50d8ae3SPaolo Bonzini  * If the bit zero of rmap_head->val is clear, then it points to the only spte
926c50d8ae3SPaolo Bonzini  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
927c50d8ae3SPaolo Bonzini  * pte_list_desc containing more mappings.
928c50d8ae3SPaolo Bonzini  */
929c50d8ae3SPaolo Bonzini 
930c50d8ae3SPaolo Bonzini /*
931c50d8ae3SPaolo Bonzini  * Returns the number of pointers in the rmap chain, not counting the new one.
932c50d8ae3SPaolo Bonzini  */
9332ff9039aSDavid Matlack static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
934c50d8ae3SPaolo Bonzini 			struct kvm_rmap_head *rmap_head)
935c50d8ae3SPaolo Bonzini {
936c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
93713236e25SPeter Xu 	int count = 0;
938c50d8ae3SPaolo Bonzini 
939c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
940c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)spte;
941c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
9422ff9039aSDavid Matlack 		desc = kvm_mmu_memory_cache_alloc(cache);
943c50d8ae3SPaolo Bonzini 		desc->sptes[0] = (u64 *)rmap_head->val;
944c50d8ae3SPaolo Bonzini 		desc->sptes[1] = spte;
94513236e25SPeter Xu 		desc->spte_count = 2;
946141705b7SLai Jiangshan 		desc->tail_count = 0;
947c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)desc | 1;
948c50d8ae3SPaolo Bonzini 		++count;
949c50d8ae3SPaolo Bonzini 	} else {
950c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
951141705b7SLai Jiangshan 		count = desc->tail_count + desc->spte_count;
952141705b7SLai Jiangshan 
953141705b7SLai Jiangshan 		/*
954141705b7SLai Jiangshan 		 * If the previous head is full, allocate a new head descriptor
955141705b7SLai Jiangshan 		 * as tail descriptors are always kept full.
956141705b7SLai Jiangshan 		 */
957141705b7SLai Jiangshan 		if (desc->spte_count == PTE_LIST_EXT) {
958141705b7SLai Jiangshan 			desc = kvm_mmu_memory_cache_alloc(cache);
959141705b7SLai Jiangshan 			desc->more = (struct pte_list_desc *)(rmap_head->val & ~1ul);
96013236e25SPeter Xu 			desc->spte_count = 0;
961141705b7SLai Jiangshan 			desc->tail_count = count;
962141705b7SLai Jiangshan 			rmap_head->val = (unsigned long)desc | 1;
963c6c4f961SLi RongQing 		}
96413236e25SPeter Xu 		desc->sptes[desc->spte_count++] = spte;
965c50d8ae3SPaolo Bonzini 	}
966c50d8ae3SPaolo Bonzini 	return count;
967c50d8ae3SPaolo Bonzini }
968c50d8ae3SPaolo Bonzini 
969069f30c6SMingwei Zhang static void pte_list_desc_remove_entry(struct kvm *kvm,
970069f30c6SMingwei Zhang 				       struct kvm_rmap_head *rmap_head,
971141705b7SLai Jiangshan 				       struct pte_list_desc *desc, int i)
972c50d8ae3SPaolo Bonzini {
973141705b7SLai Jiangshan 	struct pte_list_desc *head_desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
974141705b7SLai Jiangshan 	int j = head_desc->spte_count - 1;
975c50d8ae3SPaolo Bonzini 
976141705b7SLai Jiangshan 	/*
977141705b7SLai Jiangshan 	 * The head descriptor should never be empty.  A new head is added only
978141705b7SLai Jiangshan 	 * when adding an entry and the previous head is full, and heads are
979141705b7SLai Jiangshan 	 * removed (this flow) when they become empty.
980141705b7SLai Jiangshan 	 */
98152e322edSSean Christopherson 	KVM_BUG_ON_DATA_CORRUPTION(j < 0, kvm);
982141705b7SLai Jiangshan 
983141705b7SLai Jiangshan 	/*
984141705b7SLai Jiangshan 	 * Replace the to-be-freed SPTE with the last valid entry from the head
985141705b7SLai Jiangshan 	 * descriptor to ensure that tail descriptors are full at all times.
986141705b7SLai Jiangshan 	 * Note, this also means that tail_count is stable for each descriptor.
987141705b7SLai Jiangshan 	 */
988141705b7SLai Jiangshan 	desc->sptes[i] = head_desc->sptes[j];
989141705b7SLai Jiangshan 	head_desc->sptes[j] = NULL;
990141705b7SLai Jiangshan 	head_desc->spte_count--;
991141705b7SLai Jiangshan 	if (head_desc->spte_count)
992c50d8ae3SPaolo Bonzini 		return;
993141705b7SLai Jiangshan 
994141705b7SLai Jiangshan 	/*
995141705b7SLai Jiangshan 	 * The head descriptor is empty.  If there are no tail descriptors,
99654aa699eSBjorn Helgaas 	 * nullify the rmap head to mark the list as empty, else point the rmap
997141705b7SLai Jiangshan 	 * head at the next descriptor, i.e. the new head.
998141705b7SLai Jiangshan 	 */
999141705b7SLai Jiangshan 	if (!head_desc->more)
1000fe3c2b4cSMiaohe Lin 		rmap_head->val = 0;
1001c50d8ae3SPaolo Bonzini 	else
1002141705b7SLai Jiangshan 		rmap_head->val = (unsigned long)head_desc->more | 1;
1003141705b7SLai Jiangshan 	mmu_free_pte_list_desc(head_desc);
1004c50d8ae3SPaolo Bonzini }
1005c50d8ae3SPaolo Bonzini 
1006069f30c6SMingwei Zhang static void pte_list_remove(struct kvm *kvm, u64 *spte,
1007069f30c6SMingwei Zhang 			    struct kvm_rmap_head *rmap_head)
1008c50d8ae3SPaolo Bonzini {
1009c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
1010c50d8ae3SPaolo Bonzini 	int i;
1011c50d8ae3SPaolo Bonzini 
101252e322edSSean Christopherson 	if (KVM_BUG_ON_DATA_CORRUPTION(!rmap_head->val, kvm))
101352e322edSSean Christopherson 		return;
101452e322edSSean Christopherson 
101552e322edSSean Christopherson 	if (!(rmap_head->val & 1)) {
101652e322edSSean Christopherson 		if (KVM_BUG_ON_DATA_CORRUPTION((u64 *)rmap_head->val != spte, kvm))
101752e322edSSean Christopherson 			return;
101852e322edSSean Christopherson 
1019c50d8ae3SPaolo Bonzini 		rmap_head->val = 0;
1020c50d8ae3SPaolo Bonzini 	} else {
1021c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1022c50d8ae3SPaolo Bonzini 		while (desc) {
102313236e25SPeter Xu 			for (i = 0; i < desc->spte_count; ++i) {
1024c50d8ae3SPaolo Bonzini 				if (desc->sptes[i] == spte) {
1025069f30c6SMingwei Zhang 					pte_list_desc_remove_entry(kvm, rmap_head,
1026069f30c6SMingwei Zhang 								   desc, i);
1027c50d8ae3SPaolo Bonzini 					return;
1028c50d8ae3SPaolo Bonzini 				}
1029c50d8ae3SPaolo Bonzini 			}
1030c50d8ae3SPaolo Bonzini 			desc = desc->more;
1031c50d8ae3SPaolo Bonzini 		}
103252e322edSSean Christopherson 
103352e322edSSean Christopherson 		KVM_BUG_ON_DATA_CORRUPTION(true, kvm);
1034c50d8ae3SPaolo Bonzini 	}
1035c50d8ae3SPaolo Bonzini }
1036c50d8ae3SPaolo Bonzini 
10379202aee8SSean Christopherson static void kvm_zap_one_rmap_spte(struct kvm *kvm,
10389202aee8SSean Christopherson 				  struct kvm_rmap_head *rmap_head, u64 *sptep)
1039c50d8ae3SPaolo Bonzini {
104071f51d2cSMingwei Zhang 	mmu_spte_clear_track_bits(kvm, sptep);
1041069f30c6SMingwei Zhang 	pte_list_remove(kvm, sptep, rmap_head);
1042c50d8ae3SPaolo Bonzini }
1043c50d8ae3SPaolo Bonzini 
10449202aee8SSean Christopherson /* Return true if at least one SPTE was zapped, false otherwise */
10459202aee8SSean Christopherson static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
10469202aee8SSean Christopherson 				   struct kvm_rmap_head *rmap_head)
1047a75b5404SPeter Xu {
1048a75b5404SPeter Xu 	struct pte_list_desc *desc, *next;
1049a75b5404SPeter Xu 	int i;
1050a75b5404SPeter Xu 
1051a75b5404SPeter Xu 	if (!rmap_head->val)
1052a75b5404SPeter Xu 		return false;
1053a75b5404SPeter Xu 
1054a75b5404SPeter Xu 	if (!(rmap_head->val & 1)) {
105571f51d2cSMingwei Zhang 		mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
1056a75b5404SPeter Xu 		goto out;
1057a75b5404SPeter Xu 	}
1058a75b5404SPeter Xu 
1059a75b5404SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1060a75b5404SPeter Xu 
1061a75b5404SPeter Xu 	for (; desc; desc = next) {
1062a75b5404SPeter Xu 		for (i = 0; i < desc->spte_count; i++)
106371f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1064a75b5404SPeter Xu 		next = desc->more;
1065a75b5404SPeter Xu 		mmu_free_pte_list_desc(desc);
1066a75b5404SPeter Xu 	}
1067a75b5404SPeter Xu out:
1068a75b5404SPeter Xu 	/* rmap_head is meaningless now, remember to reset it */
1069a75b5404SPeter Xu 	rmap_head->val = 0;
1070a75b5404SPeter Xu 	return true;
1071a75b5404SPeter Xu }
1072a75b5404SPeter Xu 
10733bcd0662SPeter Xu unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
10743bcd0662SPeter Xu {
10753bcd0662SPeter Xu 	struct pte_list_desc *desc;
10763bcd0662SPeter Xu 
10773bcd0662SPeter Xu 	if (!rmap_head->val)
10783bcd0662SPeter Xu 		return 0;
10793bcd0662SPeter Xu 	else if (!(rmap_head->val & 1))
10803bcd0662SPeter Xu 		return 1;
10813bcd0662SPeter Xu 
10823bcd0662SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1083141705b7SLai Jiangshan 	return desc->tail_count + desc->spte_count;
10843bcd0662SPeter Xu }
10853bcd0662SPeter Xu 
108693e083d4SDavid Matlack static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1087269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
1088c50d8ae3SPaolo Bonzini {
1089c50d8ae3SPaolo Bonzini 	unsigned long idx;
1090c50d8ae3SPaolo Bonzini 
1091c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
10923bae0459SSean Christopherson 	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1093c50d8ae3SPaolo Bonzini }
1094c50d8ae3SPaolo Bonzini 
1095c50d8ae3SPaolo Bonzini static void rmap_remove(struct kvm *kvm, u64 *spte)
1096c50d8ae3SPaolo Bonzini {
1097601f8af0SDavid Matlack 	struct kvm_memslots *slots;
1098601f8af0SDavid Matlack 	struct kvm_memory_slot *slot;
1099c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1100c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1101c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1102c50d8ae3SPaolo Bonzini 
110357354682SSean Christopherson 	sp = sptep_to_sp(spte);
110479e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1105601f8af0SDavid Matlack 
1106601f8af0SDavid Matlack 	/*
110768be1306SDavid Matlack 	 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
110868be1306SDavid Matlack 	 * so we have to determine which memslots to use based on context
110968be1306SDavid Matlack 	 * information in sp->role.
1110601f8af0SDavid Matlack 	 */
1111601f8af0SDavid Matlack 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1112601f8af0SDavid Matlack 
1113601f8af0SDavid Matlack 	slot = __gfn_to_memslot(slots, gfn);
111493e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1115601f8af0SDavid Matlack 
1116069f30c6SMingwei Zhang 	pte_list_remove(kvm, spte, rmap_head);
1117c50d8ae3SPaolo Bonzini }
1118c50d8ae3SPaolo Bonzini 
1119c50d8ae3SPaolo Bonzini /*
1120c50d8ae3SPaolo Bonzini  * Used by the following functions to iterate through the sptes linked by a
1121c50d8ae3SPaolo Bonzini  * rmap.  All fields are private and not assumed to be used outside.
1122c50d8ae3SPaolo Bonzini  */
1123c50d8ae3SPaolo Bonzini struct rmap_iterator {
1124c50d8ae3SPaolo Bonzini 	/* private fields */
1125c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1126c50d8ae3SPaolo Bonzini 	int pos;			/* index of the sptep */
1127c50d8ae3SPaolo Bonzini };
1128c50d8ae3SPaolo Bonzini 
1129c50d8ae3SPaolo Bonzini /*
1130c50d8ae3SPaolo Bonzini  * Iteration must be started by this function.  This should also be used after
1131c50d8ae3SPaolo Bonzini  * removing/dropping sptes from the rmap link because in such cases the
11320a03cbdaSMiaohe Lin  * information in the iterator may not be valid.
1133c50d8ae3SPaolo Bonzini  *
1134c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1135c50d8ae3SPaolo Bonzini  */
1136c50d8ae3SPaolo Bonzini static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1137c50d8ae3SPaolo Bonzini 			   struct rmap_iterator *iter)
1138c50d8ae3SPaolo Bonzini {
1139c50d8ae3SPaolo Bonzini 	u64 *sptep;
1140c50d8ae3SPaolo Bonzini 
1141c50d8ae3SPaolo Bonzini 	if (!rmap_head->val)
1142c50d8ae3SPaolo Bonzini 		return NULL;
1143c50d8ae3SPaolo Bonzini 
1144c50d8ae3SPaolo Bonzini 	if (!(rmap_head->val & 1)) {
1145c50d8ae3SPaolo Bonzini 		iter->desc = NULL;
1146c50d8ae3SPaolo Bonzini 		sptep = (u64 *)rmap_head->val;
1147c50d8ae3SPaolo Bonzini 		goto out;
1148c50d8ae3SPaolo Bonzini 	}
1149c50d8ae3SPaolo Bonzini 
1150c50d8ae3SPaolo Bonzini 	iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1151c50d8ae3SPaolo Bonzini 	iter->pos = 0;
1152c50d8ae3SPaolo Bonzini 	sptep = iter->desc->sptes[iter->pos];
1153c50d8ae3SPaolo Bonzini out:
1154c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1155c50d8ae3SPaolo Bonzini 	return sptep;
1156c50d8ae3SPaolo Bonzini }
1157c50d8ae3SPaolo Bonzini 
1158c50d8ae3SPaolo Bonzini /*
1159c50d8ae3SPaolo Bonzini  * Must be used with a valid iterator: e.g. after rmap_get_first().
1160c50d8ae3SPaolo Bonzini  *
1161c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1162c50d8ae3SPaolo Bonzini  */
1163c50d8ae3SPaolo Bonzini static u64 *rmap_get_next(struct rmap_iterator *iter)
1164c50d8ae3SPaolo Bonzini {
1165c50d8ae3SPaolo Bonzini 	u64 *sptep;
1166c50d8ae3SPaolo Bonzini 
1167c50d8ae3SPaolo Bonzini 	if (iter->desc) {
1168c50d8ae3SPaolo Bonzini 		if (iter->pos < PTE_LIST_EXT - 1) {
1169c50d8ae3SPaolo Bonzini 			++iter->pos;
1170c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1171c50d8ae3SPaolo Bonzini 			if (sptep)
1172c50d8ae3SPaolo Bonzini 				goto out;
1173c50d8ae3SPaolo Bonzini 		}
1174c50d8ae3SPaolo Bonzini 
1175c50d8ae3SPaolo Bonzini 		iter->desc = iter->desc->more;
1176c50d8ae3SPaolo Bonzini 
1177c50d8ae3SPaolo Bonzini 		if (iter->desc) {
1178c50d8ae3SPaolo Bonzini 			iter->pos = 0;
1179c50d8ae3SPaolo Bonzini 			/* desc->sptes[0] cannot be NULL */
1180c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1181c50d8ae3SPaolo Bonzini 			goto out;
1182c50d8ae3SPaolo Bonzini 		}
1183c50d8ae3SPaolo Bonzini 	}
1184c50d8ae3SPaolo Bonzini 
1185c50d8ae3SPaolo Bonzini 	return NULL;
1186c50d8ae3SPaolo Bonzini out:
1187c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1188c50d8ae3SPaolo Bonzini 	return sptep;
1189c50d8ae3SPaolo Bonzini }
1190c50d8ae3SPaolo Bonzini 
1191c50d8ae3SPaolo Bonzini #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)			\
1192c50d8ae3SPaolo Bonzini 	for (_spte_ = rmap_get_first(_rmap_head_, _iter_);		\
1193c50d8ae3SPaolo Bonzini 	     _spte_; _spte_ = rmap_get_next(_iter_))
1194c50d8ae3SPaolo Bonzini 
1195c50d8ae3SPaolo Bonzini static void drop_spte(struct kvm *kvm, u64 *sptep)
1196c50d8ae3SPaolo Bonzini {
119771f51d2cSMingwei Zhang 	u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
11987fa2a347SSean Christopherson 
11997fa2a347SSean Christopherson 	if (is_shadow_present_pte(old_spte))
1200c50d8ae3SPaolo Bonzini 		rmap_remove(kvm, sptep);
1201c50d8ae3SPaolo Bonzini }
1202c50d8ae3SPaolo Bonzini 
120303787394SPaolo Bonzini static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1204c50d8ae3SPaolo Bonzini {
12050cd8dc73SPaolo Bonzini 	struct kvm_mmu_page *sp;
12060cd8dc73SPaolo Bonzini 
12070cd8dc73SPaolo Bonzini 	sp = sptep_to_sp(sptep);
120820ba462dSSean Christopherson 	WARN_ON_ONCE(sp->role.level == PG_LEVEL_4K);
12090cd8dc73SPaolo Bonzini 
1210c50d8ae3SPaolo Bonzini 	drop_spte(kvm, sptep);
121103787394SPaolo Bonzini 
121203787394SPaolo Bonzini 	if (flush)
12131b2dc736SHou Wenlong 		kvm_flush_remote_tlbs_sptep(kvm, sptep);
1214c50d8ae3SPaolo Bonzini }
1215c50d8ae3SPaolo Bonzini 
1216c50d8ae3SPaolo Bonzini /*
1217c50d8ae3SPaolo Bonzini  * Write-protect on the specified @sptep, @pt_protect indicates whether
1218c50d8ae3SPaolo Bonzini  * spte write-protection is caused by protecting shadow page table.
1219c50d8ae3SPaolo Bonzini  *
1220c50d8ae3SPaolo Bonzini  * Note: write protection is difference between dirty logging and spte
1221c50d8ae3SPaolo Bonzini  * protection:
1222c50d8ae3SPaolo Bonzini  * - for dirty logging, the spte can be set to writable at anytime if
1223c50d8ae3SPaolo Bonzini  *   its dirty bitmap is properly set.
1224c50d8ae3SPaolo Bonzini  * - for spte protection, the spte can be writable only after unsync-ing
1225c50d8ae3SPaolo Bonzini  *   shadow page.
1226c50d8ae3SPaolo Bonzini  *
1227c50d8ae3SPaolo Bonzini  * Return true if tlb need be flushed.
1228c50d8ae3SPaolo Bonzini  */
1229c50d8ae3SPaolo Bonzini static bool spte_write_protect(u64 *sptep, bool pt_protect)
1230c50d8ae3SPaolo Bonzini {
1231c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1232c50d8ae3SPaolo Bonzini 
1233c50d8ae3SPaolo Bonzini 	if (!is_writable_pte(spte) &&
1234706c9c55SSean Christopherson 	    !(pt_protect && is_mmu_writable_spte(spte)))
1235c50d8ae3SPaolo Bonzini 		return false;
1236c50d8ae3SPaolo Bonzini 
1237c50d8ae3SPaolo Bonzini 	if (pt_protect)
12385fc3424fSSean Christopherson 		spte &= ~shadow_mmu_writable_mask;
1239c50d8ae3SPaolo Bonzini 	spte = spte & ~PT_WRITABLE_MASK;
1240c50d8ae3SPaolo Bonzini 
1241c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1242c50d8ae3SPaolo Bonzini }
1243c50d8ae3SPaolo Bonzini 
12441346bbb6SDavid Matlack static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1245c50d8ae3SPaolo Bonzini 			       bool pt_protect)
1246c50d8ae3SPaolo Bonzini {
1247c50d8ae3SPaolo Bonzini 	u64 *sptep;
1248c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1249c50d8ae3SPaolo Bonzini 	bool flush = false;
1250c50d8ae3SPaolo Bonzini 
1251c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1252c50d8ae3SPaolo Bonzini 		flush |= spte_write_protect(sptep, pt_protect);
1253c50d8ae3SPaolo Bonzini 
1254c50d8ae3SPaolo Bonzini 	return flush;
1255c50d8ae3SPaolo Bonzini }
1256c50d8ae3SPaolo Bonzini 
1257c50d8ae3SPaolo Bonzini static bool spte_clear_dirty(u64 *sptep)
1258c50d8ae3SPaolo Bonzini {
1259c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1260c50d8ae3SPaolo Bonzini 
12610fe6370eSSean Christopherson 	KVM_MMU_WARN_ON(!spte_ad_enabled(spte));
1262c50d8ae3SPaolo Bonzini 	spte &= ~shadow_dirty_mask;
1263c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1264c50d8ae3SPaolo Bonzini }
1265c50d8ae3SPaolo Bonzini 
1266c50d8ae3SPaolo Bonzini static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1267c50d8ae3SPaolo Bonzini {
1268c50d8ae3SPaolo Bonzini 	bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1269c50d8ae3SPaolo Bonzini 					       (unsigned long *)sptep);
1270c50d8ae3SPaolo Bonzini 	if (was_writable && !spte_ad_enabled(*sptep))
1271c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1272c50d8ae3SPaolo Bonzini 
1273c50d8ae3SPaolo Bonzini 	return was_writable;
1274c50d8ae3SPaolo Bonzini }
1275c50d8ae3SPaolo Bonzini 
1276c50d8ae3SPaolo Bonzini /*
1277c50d8ae3SPaolo Bonzini  * Gets the GFN ready for another round of dirty logging by clearing the
1278c50d8ae3SPaolo Bonzini  *	- D bit on ad-enabled SPTEs, and
1279c50d8ae3SPaolo Bonzini  *	- W bit on ad-disabled SPTEs.
1280c50d8ae3SPaolo Bonzini  * Returns true iff any D or W bits were cleared.
1281c50d8ae3SPaolo Bonzini  */
12820a234f5dSSean Christopherson static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1283269e9552SHamza Mahfooz 			       const struct kvm_memory_slot *slot)
1284c50d8ae3SPaolo Bonzini {
1285c50d8ae3SPaolo Bonzini 	u64 *sptep;
1286c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1287c50d8ae3SPaolo Bonzini 	bool flush = false;
1288c50d8ae3SPaolo Bonzini 
1289c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1290c50d8ae3SPaolo Bonzini 		if (spte_ad_need_write_protect(*sptep))
1291c50d8ae3SPaolo Bonzini 			flush |= spte_wrprot_for_clear_dirty(sptep);
1292c50d8ae3SPaolo Bonzini 		else
1293c50d8ae3SPaolo Bonzini 			flush |= spte_clear_dirty(sptep);
1294c50d8ae3SPaolo Bonzini 
1295c50d8ae3SPaolo Bonzini 	return flush;
1296c50d8ae3SPaolo Bonzini }
1297c50d8ae3SPaolo Bonzini 
1298c50d8ae3SPaolo Bonzini /**
1299c50d8ae3SPaolo Bonzini  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1300c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1301c50d8ae3SPaolo Bonzini  * @slot: slot to protect
1302c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1303c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should protect
1304c50d8ae3SPaolo Bonzini  *
130589212919SKeqian Zhu  * Used when we do not need to care about huge page mappings.
1306c50d8ae3SPaolo Bonzini  */
1307c50d8ae3SPaolo Bonzini static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1308c50d8ae3SPaolo Bonzini 				     struct kvm_memory_slot *slot,
1309c50d8ae3SPaolo Bonzini 				     gfn_t gfn_offset, unsigned long mask)
1310c50d8ae3SPaolo Bonzini {
1311c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1312c50d8ae3SPaolo Bonzini 
13131f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1314a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1315a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, true);
1316e2209710SBen Gardon 
1317e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1318e2209710SBen Gardon 		return;
1319e2209710SBen Gardon 
1320c50d8ae3SPaolo Bonzini 	while (mask) {
132193e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13223bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13231346bbb6SDavid Matlack 		rmap_write_protect(rmap_head, false);
1324c50d8ae3SPaolo Bonzini 
1325c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1326c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1327c50d8ae3SPaolo Bonzini 	}
1328c50d8ae3SPaolo Bonzini }
1329c50d8ae3SPaolo Bonzini 
1330c50d8ae3SPaolo Bonzini /**
1331c50d8ae3SPaolo Bonzini  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1332c50d8ae3SPaolo Bonzini  * protect the page if the D-bit isn't supported.
1333c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1334c50d8ae3SPaolo Bonzini  * @slot: slot to clear D-bit
1335c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1336c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should clear D-bit
1337c50d8ae3SPaolo Bonzini  *
1338c50d8ae3SPaolo Bonzini  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1339c50d8ae3SPaolo Bonzini  */
1340a018eba5SSean Christopherson static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1341c50d8ae3SPaolo Bonzini 					 struct kvm_memory_slot *slot,
1342c50d8ae3SPaolo Bonzini 					 gfn_t gfn_offset, unsigned long mask)
1343c50d8ae3SPaolo Bonzini {
1344c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1345c50d8ae3SPaolo Bonzini 
13461f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1347a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1348a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, false);
1349e2209710SBen Gardon 
1350e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1351e2209710SBen Gardon 		return;
1352e2209710SBen Gardon 
1353c50d8ae3SPaolo Bonzini 	while (mask) {
135493e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13553bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13560a234f5dSSean Christopherson 		__rmap_clear_dirty(kvm, rmap_head, slot);
1357c50d8ae3SPaolo Bonzini 
1358c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1359c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1360c50d8ae3SPaolo Bonzini 	}
1361c50d8ae3SPaolo Bonzini }
1362c50d8ae3SPaolo Bonzini 
1363c50d8ae3SPaolo Bonzini /**
1364c50d8ae3SPaolo Bonzini  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1365c50d8ae3SPaolo Bonzini  * PT level pages.
1366c50d8ae3SPaolo Bonzini  *
1367c50d8ae3SPaolo Bonzini  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1368c50d8ae3SPaolo Bonzini  * enable dirty logging for them.
1369c50d8ae3SPaolo Bonzini  *
137089212919SKeqian Zhu  * We need to care about huge page mappings: e.g. during dirty logging we may
137189212919SKeqian Zhu  * have such mappings.
1372c50d8ae3SPaolo Bonzini  */
1373c50d8ae3SPaolo Bonzini void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1374c50d8ae3SPaolo Bonzini 				struct kvm_memory_slot *slot,
1375c50d8ae3SPaolo Bonzini 				gfn_t gfn_offset, unsigned long mask)
1376c50d8ae3SPaolo Bonzini {
137789212919SKeqian Zhu 	/*
137889212919SKeqian Zhu 	 * Huge pages are NOT write protected when we start dirty logging in
137989212919SKeqian Zhu 	 * initially-all-set mode; must write protect them here so that they
138089212919SKeqian Zhu 	 * are split to 4K on the first write.
138189212919SKeqian Zhu 	 *
138289212919SKeqian Zhu 	 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
138389212919SKeqian Zhu 	 * of memslot has no such restriction, so the range can cross two large
138489212919SKeqian Zhu 	 * pages.
138589212919SKeqian Zhu 	 */
138689212919SKeqian Zhu 	if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
138789212919SKeqian Zhu 		gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
138889212919SKeqian Zhu 		gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
138989212919SKeqian Zhu 
1390cb00a70bSDavid Matlack 		if (READ_ONCE(eager_page_split))
13911aa4bb91SDavid Matlack 			kvm_mmu_try_split_huge_pages(kvm, slot, start, end + 1, PG_LEVEL_4K);
1392cb00a70bSDavid Matlack 
139389212919SKeqian Zhu 		kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
139489212919SKeqian Zhu 
139589212919SKeqian Zhu 		/* Cross two large pages? */
139689212919SKeqian Zhu 		if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
139789212919SKeqian Zhu 		    ALIGN(end << PAGE_SHIFT, PMD_SIZE))
139889212919SKeqian Zhu 			kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
139989212919SKeqian Zhu 						       PG_LEVEL_2M);
140089212919SKeqian Zhu 	}
140189212919SKeqian Zhu 
140289212919SKeqian Zhu 	/* Now handle 4K PTEs.  */
1403a018eba5SSean Christopherson 	if (kvm_x86_ops.cpu_dirty_log_size)
1404a018eba5SSean Christopherson 		kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1405c50d8ae3SPaolo Bonzini 	else
1406c50d8ae3SPaolo Bonzini 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1407c50d8ae3SPaolo Bonzini }
1408c50d8ae3SPaolo Bonzini 
1409fb04a1edSPeter Xu int kvm_cpu_dirty_log_size(void)
1410fb04a1edSPeter Xu {
14116dd03800SSean Christopherson 	return kvm_x86_ops.cpu_dirty_log_size;
1412fb04a1edSPeter Xu }
1413fb04a1edSPeter Xu 
1414c50d8ae3SPaolo Bonzini bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
14153ad93562SKeqian Zhu 				    struct kvm_memory_slot *slot, u64 gfn,
14163ad93562SKeqian Zhu 				    int min_level)
1417c50d8ae3SPaolo Bonzini {
1418c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1419c50d8ae3SPaolo Bonzini 	int i;
1420c50d8ae3SPaolo Bonzini 	bool write_protected = false;
1421c50d8ae3SPaolo Bonzini 
1422e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
14233ad93562SKeqian Zhu 		for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
142493e083d4SDavid Matlack 			rmap_head = gfn_to_rmap(gfn, i, slot);
14251346bbb6SDavid Matlack 			write_protected |= rmap_write_protect(rmap_head, true);
1426c50d8ae3SPaolo Bonzini 		}
1427e2209710SBen Gardon 	}
1428c50d8ae3SPaolo Bonzini 
14291f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
143046044f72SBen Gardon 		write_protected |=
14313ad93562SKeqian Zhu 			kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
143246044f72SBen Gardon 
1433c50d8ae3SPaolo Bonzini 	return write_protected;
1434c50d8ae3SPaolo Bonzini }
1435c50d8ae3SPaolo Bonzini 
1436cf48f9e2SDavid Matlack static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1437c50d8ae3SPaolo Bonzini {
1438c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
1439c50d8ae3SPaolo Bonzini 
1440c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
14413ad93562SKeqian Zhu 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1442c50d8ae3SPaolo Bonzini }
1443c50d8ae3SPaolo Bonzini 
1444f8480721SSean Christopherson static bool __kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1445269e9552SHamza Mahfooz 			   const struct kvm_memory_slot *slot)
1446c50d8ae3SPaolo Bonzini {
14479202aee8SSean Christopherson 	return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1448c50d8ae3SPaolo Bonzini }
1449c50d8ae3SPaolo Bonzini 
1450f8480721SSean Christopherson static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1451f3b65bbaSPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level)
1452c50d8ae3SPaolo Bonzini {
1453f8480721SSean Christopherson 	return __kvm_zap_rmap(kvm, rmap_head, slot);
1454c50d8ae3SPaolo Bonzini }
1455c50d8ae3SPaolo Bonzini 
1456c50d8ae3SPaolo Bonzini struct slot_rmap_walk_iterator {
1457c50d8ae3SPaolo Bonzini 	/* input fields. */
1458269e9552SHamza Mahfooz 	const struct kvm_memory_slot *slot;
1459c50d8ae3SPaolo Bonzini 	gfn_t start_gfn;
1460c50d8ae3SPaolo Bonzini 	gfn_t end_gfn;
1461c50d8ae3SPaolo Bonzini 	int start_level;
1462c50d8ae3SPaolo Bonzini 	int end_level;
1463c50d8ae3SPaolo Bonzini 
1464c50d8ae3SPaolo Bonzini 	/* output fields. */
1465c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1466c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap;
1467c50d8ae3SPaolo Bonzini 	int level;
1468c50d8ae3SPaolo Bonzini 
1469c50d8ae3SPaolo Bonzini 	/* private field. */
1470c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *end_rmap;
1471c50d8ae3SPaolo Bonzini };
1472c50d8ae3SPaolo Bonzini 
1473f3d90f90SSean Christopherson static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,
1474f3d90f90SSean Christopherson 				 int level)
1475c50d8ae3SPaolo Bonzini {
1476c50d8ae3SPaolo Bonzini 	iterator->level = level;
1477c50d8ae3SPaolo Bonzini 	iterator->gfn = iterator->start_gfn;
147893e083d4SDavid Matlack 	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
147993e083d4SDavid Matlack 	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1480c50d8ae3SPaolo Bonzini }
1481c50d8ae3SPaolo Bonzini 
1482f3d90f90SSean Christopherson static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1483f3d90f90SSean Christopherson 				const struct kvm_memory_slot *slot,
1484f3d90f90SSean Christopherson 				int start_level, int end_level,
1485f3d90f90SSean Christopherson 				gfn_t start_gfn, gfn_t end_gfn)
1486c50d8ae3SPaolo Bonzini {
1487c50d8ae3SPaolo Bonzini 	iterator->slot = slot;
1488c50d8ae3SPaolo Bonzini 	iterator->start_level = start_level;
1489c50d8ae3SPaolo Bonzini 	iterator->end_level = end_level;
1490c50d8ae3SPaolo Bonzini 	iterator->start_gfn = start_gfn;
1491c50d8ae3SPaolo Bonzini 	iterator->end_gfn = end_gfn;
1492c50d8ae3SPaolo Bonzini 
1493c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->start_level);
1494c50d8ae3SPaolo Bonzini }
1495c50d8ae3SPaolo Bonzini 
1496c50d8ae3SPaolo Bonzini static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1497c50d8ae3SPaolo Bonzini {
1498c50d8ae3SPaolo Bonzini 	return !!iterator->rmap;
1499c50d8ae3SPaolo Bonzini }
1500c50d8ae3SPaolo Bonzini 
1501c50d8ae3SPaolo Bonzini static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1502c50d8ae3SPaolo Bonzini {
15036ba1e04fSVipin Sharma 	while (++iterator->rmap <= iterator->end_rmap) {
1504c50d8ae3SPaolo Bonzini 		iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
15056ba1e04fSVipin Sharma 
15066ba1e04fSVipin Sharma 		if (iterator->rmap->val)
1507c50d8ae3SPaolo Bonzini 			return;
1508c50d8ae3SPaolo Bonzini 	}
1509c50d8ae3SPaolo Bonzini 
1510c50d8ae3SPaolo Bonzini 	if (++iterator->level > iterator->end_level) {
1511c50d8ae3SPaolo Bonzini 		iterator->rmap = NULL;
1512c50d8ae3SPaolo Bonzini 		return;
1513c50d8ae3SPaolo Bonzini 	}
1514c50d8ae3SPaolo Bonzini 
1515c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->level);
1516c50d8ae3SPaolo Bonzini }
1517c50d8ae3SPaolo Bonzini 
1518c50d8ae3SPaolo Bonzini #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1519c50d8ae3SPaolo Bonzini 	   _start_gfn, _end_gfn, _iter_)				\
1520c50d8ae3SPaolo Bonzini 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1521c50d8ae3SPaolo Bonzini 				 _end_level_, _start_gfn, _end_gfn);	\
1522c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_okay(_iter_);				\
1523c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_next(_iter_))
1524c50d8ae3SPaolo Bonzini 
15253039bcc7SSean Christopherson typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1526c1b91493SSean Christopherson 			       struct kvm_memory_slot *slot, gfn_t gfn,
1527f3b65bbaSPaolo Bonzini 			       int level);
1528c1b91493SSean Christopherson 
15293039bcc7SSean Christopherson static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
15303039bcc7SSean Christopherson 						 struct kvm_gfn_range *range,
1531c1b91493SSean Christopherson 						 rmap_handler_t handler)
1532c50d8ae3SPaolo Bonzini {
1533c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
15343039bcc7SSean Christopherson 	bool ret = false;
1535c50d8ae3SPaolo Bonzini 
15363039bcc7SSean Christopherson 	for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
15373039bcc7SSean Christopherson 				 range->start, range->end - 1, &iterator)
15383039bcc7SSean Christopherson 		ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
1539f3b65bbaSPaolo Bonzini 			       iterator.level);
1540c50d8ae3SPaolo Bonzini 
1541c50d8ae3SPaolo Bonzini 	return ret;
1542c50d8ae3SPaolo Bonzini }
1543c50d8ae3SPaolo Bonzini 
15443039bcc7SSean Christopherson bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1545c50d8ae3SPaolo Bonzini {
1546e2209710SBen Gardon 	bool flush = false;
1547c50d8ae3SPaolo Bonzini 
1548e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1549f8480721SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
1550063afacdSBen Gardon 
15511f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1552c7785d85SHou Wenlong 		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1553063afacdSBen Gardon 
15540a3869e1SSean Christopherson 	if (kvm_x86_ops.set_apic_access_page_addr &&
15550a3869e1SSean Christopherson 	    range->slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT)
15560a8a5f2cSSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
15570a8a5f2cSSean Christopherson 
15583039bcc7SSean Christopherson 	return flush;
1559c50d8ae3SPaolo Bonzini }
1560c50d8ae3SPaolo Bonzini 
1561aed02fe3SSean Christopherson static bool kvm_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1562f3b65bbaSPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level)
1563c50d8ae3SPaolo Bonzini {
1564c50d8ae3SPaolo Bonzini 	u64 *sptep;
15653f649ab7SKees Cook 	struct rmap_iterator iter;
1566c50d8ae3SPaolo Bonzini 	int young = 0;
1567c50d8ae3SPaolo Bonzini 
1568c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1569c50d8ae3SPaolo Bonzini 		young |= mmu_spte_age(sptep);
1570c50d8ae3SPaolo Bonzini 
1571c50d8ae3SPaolo Bonzini 	return young;
1572c50d8ae3SPaolo Bonzini }
1573c50d8ae3SPaolo Bonzini 
1574aed02fe3SSean Christopherson static bool kvm_test_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1575f3b65bbaSPaolo Bonzini 			      struct kvm_memory_slot *slot, gfn_t gfn, int level)
1576c50d8ae3SPaolo Bonzini {
1577c50d8ae3SPaolo Bonzini 	u64 *sptep;
1578c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1579c50d8ae3SPaolo Bonzini 
1580c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1581c50d8ae3SPaolo Bonzini 		if (is_accessed_spte(*sptep))
158298a26b69SVihas Mak 			return true;
158398a26b69SVihas Mak 	return false;
1584c50d8ae3SPaolo Bonzini }
1585c50d8ae3SPaolo Bonzini 
1586c50d8ae3SPaolo Bonzini #define RMAP_RECYCLE_THRESHOLD 1000
1587c50d8ae3SPaolo Bonzini 
15882ff9039aSDavid Matlack static void __rmap_add(struct kvm *kvm,
15892ff9039aSDavid Matlack 		       struct kvm_mmu_memory_cache *cache,
15902ff9039aSDavid Matlack 		       const struct kvm_memory_slot *slot,
159172ae5822SSean Christopherson 		       u64 *spte, gfn_t gfn, unsigned int access)
1592c50d8ae3SPaolo Bonzini {
1593c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
159468be1306SDavid Matlack 	struct kvm_rmap_head *rmap_head;
159568be1306SDavid Matlack 	int rmap_count;
1596c50d8ae3SPaolo Bonzini 
159757354682SSean Christopherson 	sp = sptep_to_sp(spte);
159879e48cecSSean Christopherson 	kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
159981cb4657SDavid Matlack 	kvm_update_page_stats(kvm, sp->role.level, 1);
160081cb4657SDavid Matlack 
160193e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
16022ff9039aSDavid Matlack 	rmap_count = pte_list_add(cache, spte, rmap_head);
1603c50d8ae3SPaolo Bonzini 
1604604f5332SMiaohe Lin 	if (rmap_count > kvm->stat.max_mmu_rmap_size)
1605604f5332SMiaohe Lin 		kvm->stat.max_mmu_rmap_size = rmap_count;
160668be1306SDavid Matlack 	if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
16079202aee8SSean Christopherson 		kvm_zap_all_rmap_sptes(kvm, rmap_head);
16081b2dc736SHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
160968be1306SDavid Matlack 	}
1610c50d8ae3SPaolo Bonzini }
1611c50d8ae3SPaolo Bonzini 
16122ff9039aSDavid Matlack static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
161372ae5822SSean Christopherson 		     u64 *spte, gfn_t gfn, unsigned int access)
16142ff9039aSDavid Matlack {
16152ff9039aSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
16162ff9039aSDavid Matlack 
16176a97575dSDavid Matlack 	__rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
16182ff9039aSDavid Matlack }
16192ff9039aSDavid Matlack 
16203039bcc7SSean Christopherson bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1621c50d8ae3SPaolo Bonzini {
1622e2209710SBen Gardon 	bool young = false;
1623f8e14497SBen Gardon 
1624e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1625aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_age_rmap);
16263039bcc7SSean Christopherson 
16271f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16283039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1629f8e14497SBen Gardon 
1630f8e14497SBen Gardon 	return young;
1631c50d8ae3SPaolo Bonzini }
1632c50d8ae3SPaolo Bonzini 
16333039bcc7SSean Christopherson bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1634c50d8ae3SPaolo Bonzini {
1635e2209710SBen Gardon 	bool young = false;
1636f8e14497SBen Gardon 
1637e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1638aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmap);
16393039bcc7SSean Christopherson 
16401f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16413039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1642f8e14497SBen Gardon 
1643f8e14497SBen Gardon 	return young;
1644c50d8ae3SPaolo Bonzini }
1645c50d8ae3SPaolo Bonzini 
164658da926cSSean Christopherson static void kvm_mmu_check_sptes_at_free(struct kvm_mmu_page *sp)
1647c50d8ae3SPaolo Bonzini {
1648870d4d4eSSean Christopherson #ifdef CONFIG_KVM_PROVE_MMU
1649242a6dd8SSean Christopherson 	int i;
1650c50d8ae3SPaolo Bonzini 
1651242a6dd8SSean Christopherson 	for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
16520fe6370eSSean Christopherson 		if (KVM_MMU_WARN_ON(is_shadow_present_pte(sp->spt[i])))
165358da926cSSean Christopherson 			pr_err_ratelimited("SPTE %llx (@ %p) for gfn %llx shadow-present at free",
165458da926cSSean Christopherson 					   sp->spt[i], &sp->spt[i],
165558da926cSSean Christopherson 					   kvm_mmu_page_get_gfn(sp, i));
1656c50d8ae3SPaolo Bonzini 	}
1657c50d8ae3SPaolo Bonzini #endif
165858da926cSSean Christopherson }
1659c50d8ae3SPaolo Bonzini 
1660c50d8ae3SPaolo Bonzini /*
1661c50d8ae3SPaolo Bonzini  * This value is the sum of all of the kvm instances's
1662c50d8ae3SPaolo Bonzini  * kvm->arch.n_used_mmu_pages values.  We need a global,
1663c50d8ae3SPaolo Bonzini  * aggregate version in order to make the slab shrinker
1664c50d8ae3SPaolo Bonzini  * faster
1665c50d8ae3SPaolo Bonzini  */
1666d5aaad6fSSean Christopherson static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1667c50d8ae3SPaolo Bonzini {
1668c50d8ae3SPaolo Bonzini 	kvm->arch.n_used_mmu_pages += nr;
1669c50d8ae3SPaolo Bonzini 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1670c50d8ae3SPaolo Bonzini }
1671c50d8ae3SPaolo Bonzini 
167243a063caSYosry Ahmed static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
167343a063caSYosry Ahmed {
167443a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, +1);
167543a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, +1);
167643a063caSYosry Ahmed }
167743a063caSYosry Ahmed 
167843a063caSYosry Ahmed static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
167943a063caSYosry Ahmed {
168043a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, -1);
168143a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, -1);
168243a063caSYosry Ahmed }
168343a063caSYosry Ahmed 
168487654643SDavid Matlack static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1685c50d8ae3SPaolo Bonzini {
168658da926cSSean Christopherson 	kvm_mmu_check_sptes_at_free(sp);
168758da926cSSean Christopherson 
1688c50d8ae3SPaolo Bonzini 	hlist_del(&sp->hash_link);
1689c50d8ae3SPaolo Bonzini 	list_del(&sp->link);
1690c50d8ae3SPaolo Bonzini 	free_page((unsigned long)sp->spt);
1691c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
16926a97575dSDavid Matlack 		free_page((unsigned long)sp->shadowed_translation);
1693c50d8ae3SPaolo Bonzini 	kmem_cache_free(mmu_page_header_cache, sp);
1694c50d8ae3SPaolo Bonzini }
1695c50d8ae3SPaolo Bonzini 
1696c50d8ae3SPaolo Bonzini static unsigned kvm_page_table_hashfn(gfn_t gfn)
1697c50d8ae3SPaolo Bonzini {
1698c50d8ae3SPaolo Bonzini 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1699c50d8ae3SPaolo Bonzini }
1700c50d8ae3SPaolo Bonzini 
17012ff9039aSDavid Matlack static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
1702c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp, u64 *parent_pte)
1703c50d8ae3SPaolo Bonzini {
1704c50d8ae3SPaolo Bonzini 	if (!parent_pte)
1705c50d8ae3SPaolo Bonzini 		return;
1706c50d8ae3SPaolo Bonzini 
17072ff9039aSDavid Matlack 	pte_list_add(cache, parent_pte, &sp->parent_ptes);
1708c50d8ae3SPaolo Bonzini }
1709c50d8ae3SPaolo Bonzini 
1710069f30c6SMingwei Zhang static void mmu_page_remove_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1711c50d8ae3SPaolo Bonzini 				       u64 *parent_pte)
1712c50d8ae3SPaolo Bonzini {
1713069f30c6SMingwei Zhang 	pte_list_remove(kvm, parent_pte, &sp->parent_ptes);
1714c50d8ae3SPaolo Bonzini }
1715c50d8ae3SPaolo Bonzini 
1716069f30c6SMingwei Zhang static void drop_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1717c50d8ae3SPaolo Bonzini 			    u64 *parent_pte)
1718c50d8ae3SPaolo Bonzini {
1719069f30c6SMingwei Zhang 	mmu_page_remove_parent_pte(kvm, sp, parent_pte);
1720c50d8ae3SPaolo Bonzini 	mmu_spte_clear_no_track(parent_pte);
1721c50d8ae3SPaolo Bonzini }
1722c50d8ae3SPaolo Bonzini 
1723c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte);
1724c50d8ae3SPaolo Bonzini static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1725c50d8ae3SPaolo Bonzini {
1726c50d8ae3SPaolo Bonzini 	u64 *sptep;
1727c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1728c50d8ae3SPaolo Bonzini 
1729c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1730c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
1731c50d8ae3SPaolo Bonzini 	}
1732c50d8ae3SPaolo Bonzini }
1733c50d8ae3SPaolo Bonzini 
1734c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte)
1735c50d8ae3SPaolo Bonzini {
1736c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1737c50d8ae3SPaolo Bonzini 
173857354682SSean Christopherson 	sp = sptep_to_sp(spte);
173979e48cecSSean Christopherson 	if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1740c50d8ae3SPaolo Bonzini 		return;
1741c50d8ae3SPaolo Bonzini 	if (sp->unsync_children++)
1742c50d8ae3SPaolo Bonzini 		return;
1743c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
1744c50d8ae3SPaolo Bonzini }
1745c50d8ae3SPaolo Bonzini 
1746c50d8ae3SPaolo Bonzini #define KVM_PAGE_ARRAY_NR 16
1747c50d8ae3SPaolo Bonzini 
1748c50d8ae3SPaolo Bonzini struct kvm_mmu_pages {
1749c50d8ae3SPaolo Bonzini 	struct mmu_page_and_offset {
1750c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
1751c50d8ae3SPaolo Bonzini 		unsigned int idx;
1752c50d8ae3SPaolo Bonzini 	} page[KVM_PAGE_ARRAY_NR];
1753c50d8ae3SPaolo Bonzini 	unsigned int nr;
1754c50d8ae3SPaolo Bonzini };
1755c50d8ae3SPaolo Bonzini 
1756c50d8ae3SPaolo Bonzini static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1757c50d8ae3SPaolo Bonzini 			 int idx)
1758c50d8ae3SPaolo Bonzini {
1759c50d8ae3SPaolo Bonzini 	int i;
1760c50d8ae3SPaolo Bonzini 
1761c50d8ae3SPaolo Bonzini 	if (sp->unsync)
1762c50d8ae3SPaolo Bonzini 		for (i=0; i < pvec->nr; i++)
1763c50d8ae3SPaolo Bonzini 			if (pvec->page[i].sp == sp)
1764c50d8ae3SPaolo Bonzini 				return 0;
1765c50d8ae3SPaolo Bonzini 
1766c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].sp = sp;
1767c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].idx = idx;
1768c50d8ae3SPaolo Bonzini 	pvec->nr++;
1769c50d8ae3SPaolo Bonzini 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
1770c50d8ae3SPaolo Bonzini }
1771c50d8ae3SPaolo Bonzini 
1772c50d8ae3SPaolo Bonzini static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1773c50d8ae3SPaolo Bonzini {
1774c50d8ae3SPaolo Bonzini 	--sp->unsync_children;
177520ba462dSSean Christopherson 	WARN_ON_ONCE((int)sp->unsync_children < 0);
1776c50d8ae3SPaolo Bonzini 	__clear_bit(idx, sp->unsync_child_bitmap);
1777c50d8ae3SPaolo Bonzini }
1778c50d8ae3SPaolo Bonzini 
1779c50d8ae3SPaolo Bonzini static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1780c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1781c50d8ae3SPaolo Bonzini {
1782c50d8ae3SPaolo Bonzini 	int i, ret, nr_unsync_leaf = 0;
1783c50d8ae3SPaolo Bonzini 
1784c50d8ae3SPaolo Bonzini 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1785c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
1786c50d8ae3SPaolo Bonzini 		u64 ent = sp->spt[i];
1787c50d8ae3SPaolo Bonzini 
1788c50d8ae3SPaolo Bonzini 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1789c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1790c50d8ae3SPaolo Bonzini 			continue;
1791c50d8ae3SPaolo Bonzini 		}
1792c50d8ae3SPaolo Bonzini 
17935e3edd7eSSean Christopherson 		child = spte_to_child_sp(ent);
1794c50d8ae3SPaolo Bonzini 
1795c50d8ae3SPaolo Bonzini 		if (child->unsync_children) {
1796c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1797c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1798c50d8ae3SPaolo Bonzini 
1799c50d8ae3SPaolo Bonzini 			ret = __mmu_unsync_walk(child, pvec);
1800c50d8ae3SPaolo Bonzini 			if (!ret) {
1801c50d8ae3SPaolo Bonzini 				clear_unsync_child_bit(sp, i);
1802c50d8ae3SPaolo Bonzini 				continue;
1803c50d8ae3SPaolo Bonzini 			} else if (ret > 0) {
1804c50d8ae3SPaolo Bonzini 				nr_unsync_leaf += ret;
1805c50d8ae3SPaolo Bonzini 			} else
1806c50d8ae3SPaolo Bonzini 				return ret;
1807c50d8ae3SPaolo Bonzini 		} else if (child->unsync) {
1808c50d8ae3SPaolo Bonzini 			nr_unsync_leaf++;
1809c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1810c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1811c50d8ae3SPaolo Bonzini 		} else
1812c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1813c50d8ae3SPaolo Bonzini 	}
1814c50d8ae3SPaolo Bonzini 
1815c50d8ae3SPaolo Bonzini 	return nr_unsync_leaf;
1816c50d8ae3SPaolo Bonzini }
1817c50d8ae3SPaolo Bonzini 
1818c50d8ae3SPaolo Bonzini #define INVALID_INDEX (-1)
1819c50d8ae3SPaolo Bonzini 
1820c50d8ae3SPaolo Bonzini static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1821c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1822c50d8ae3SPaolo Bonzini {
1823c50d8ae3SPaolo Bonzini 	pvec->nr = 0;
1824c50d8ae3SPaolo Bonzini 	if (!sp->unsync_children)
1825c50d8ae3SPaolo Bonzini 		return 0;
1826c50d8ae3SPaolo Bonzini 
1827c50d8ae3SPaolo Bonzini 	mmu_pages_add(pvec, sp, INVALID_INDEX);
1828c50d8ae3SPaolo Bonzini 	return __mmu_unsync_walk(sp, pvec);
1829c50d8ae3SPaolo Bonzini }
1830c50d8ae3SPaolo Bonzini 
1831c50d8ae3SPaolo Bonzini static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1832c50d8ae3SPaolo Bonzini {
183320ba462dSSean Christopherson 	WARN_ON_ONCE(!sp->unsync);
1834c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_sync_page(sp);
1835c50d8ae3SPaolo Bonzini 	sp->unsync = 0;
1836c50d8ae3SPaolo Bonzini 	--kvm->stat.mmu_unsync;
1837c50d8ae3SPaolo Bonzini }
1838c50d8ae3SPaolo Bonzini 
1839c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1840c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list);
1841c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1842c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list);
1843c50d8ae3SPaolo Bonzini 
1844767d8d8dSLai Jiangshan static bool sp_has_gptes(struct kvm_mmu_page *sp)
1845767d8d8dSLai Jiangshan {
1846767d8d8dSLai Jiangshan 	if (sp->role.direct)
1847767d8d8dSLai Jiangshan 		return false;
1848767d8d8dSLai Jiangshan 
184984e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
185084e5ffd0SLai Jiangshan 		return false;
185184e5ffd0SLai Jiangshan 
1852767d8d8dSLai Jiangshan 	return true;
1853767d8d8dSLai Jiangshan }
1854767d8d8dSLai Jiangshan 
1855ac101b7cSSean Christopherson #define for_each_valid_sp(_kvm, _sp, _list)				\
1856ac101b7cSSean Christopherson 	hlist_for_each_entry(_sp, _list, hash_link)			\
1857c50d8ae3SPaolo Bonzini 		if (is_obsolete_sp((_kvm), (_sp))) {			\
1858c50d8ae3SPaolo Bonzini 		} else
1859c50d8ae3SPaolo Bonzini 
1860767d8d8dSLai Jiangshan #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn)		\
1861ac101b7cSSean Christopherson 	for_each_valid_sp(_kvm, _sp,					\
1862ac101b7cSSean Christopherson 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
1863767d8d8dSLai Jiangshan 		if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1864c50d8ae3SPaolo Bonzini 
186590e44470SLai Jiangshan static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
186690e44470SLai Jiangshan {
186790e44470SLai Jiangshan 	union kvm_mmu_page_role root_role = vcpu->arch.mmu->root_role;
186890e44470SLai Jiangshan 
186990e44470SLai Jiangshan 	/*
187090e44470SLai Jiangshan 	 * Ignore various flags when verifying that it's safe to sync a shadow
187190e44470SLai Jiangshan 	 * page using the current MMU context.
187290e44470SLai Jiangshan 	 *
187390e44470SLai Jiangshan 	 *  - level: not part of the overall MMU role and will never match as the MMU's
187490e44470SLai Jiangshan 	 *           level tracks the root level
187590e44470SLai Jiangshan 	 *  - access: updated based on the new guest PTE
187690e44470SLai Jiangshan 	 *  - quadrant: not part of the overall MMU role (similar to level)
187790e44470SLai Jiangshan 	 */
187890e44470SLai Jiangshan 	const union kvm_mmu_page_role sync_role_ign = {
187990e44470SLai Jiangshan 		.level = 0xf,
188090e44470SLai Jiangshan 		.access = 0x7,
188190e44470SLai Jiangshan 		.quadrant = 0x3,
188290e44470SLai Jiangshan 		.passthrough = 0x1,
188390e44470SLai Jiangshan 	};
188490e44470SLai Jiangshan 
188590e44470SLai Jiangshan 	/*
188690e44470SLai Jiangshan 	 * Direct pages can never be unsync, and KVM should never attempt to
188790e44470SLai Jiangshan 	 * sync a shadow page for a different MMU context, e.g. if the role
188890e44470SLai Jiangshan 	 * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
188990e44470SLai Jiangshan 	 * reserved bits checks will be wrong, etc...
189090e44470SLai Jiangshan 	 */
1891c3c6c9fcSLai Jiangshan 	if (WARN_ON_ONCE(sp->role.direct || !vcpu->arch.mmu->sync_spte ||
189290e44470SLai Jiangshan 			 (sp->role.word ^ root_role.word) & ~sync_role_ign.word))
189390e44470SLai Jiangshan 		return false;
189490e44470SLai Jiangshan 
189590e44470SLai Jiangshan 	return true;
189690e44470SLai Jiangshan }
189790e44470SLai Jiangshan 
189819ace7d6SLai Jiangshan static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
189919ace7d6SLai Jiangshan {
190019ace7d6SLai Jiangshan 	if (!sp->spt[i])
190119ace7d6SLai Jiangshan 		return 0;
190219ace7d6SLai Jiangshan 
190319ace7d6SLai Jiangshan 	return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
190419ace7d6SLai Jiangshan }
190519ace7d6SLai Jiangshan 
190690e44470SLai Jiangshan static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
190790e44470SLai Jiangshan {
1908c3c6c9fcSLai Jiangshan 	int flush = 0;
1909c3c6c9fcSLai Jiangshan 	int i;
1910c3c6c9fcSLai Jiangshan 
191190e44470SLai Jiangshan 	if (!kvm_sync_page_check(vcpu, sp))
191290e44470SLai Jiangshan 		return -1;
191390e44470SLai Jiangshan 
1914c3c6c9fcSLai Jiangshan 	for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
191519ace7d6SLai Jiangshan 		int ret = kvm_sync_spte(vcpu, sp, i);
1916c3c6c9fcSLai Jiangshan 
1917c3c6c9fcSLai Jiangshan 		if (ret < -1)
1918c3c6c9fcSLai Jiangshan 			return -1;
1919c3c6c9fcSLai Jiangshan 		flush |= ret;
1920c3c6c9fcSLai Jiangshan 	}
1921c3c6c9fcSLai Jiangshan 
1922c3c6c9fcSLai Jiangshan 	/*
1923c3c6c9fcSLai Jiangshan 	 * Note, any flush is purely for KVM's correctness, e.g. when dropping
1924c3c6c9fcSLai Jiangshan 	 * an existing SPTE or clearing W/A/D bits to ensure an mmu_notifier
1925c3c6c9fcSLai Jiangshan 	 * unmap or dirty logging event doesn't fail to flush.  The guest is
1926c3c6c9fcSLai Jiangshan 	 * responsible for flushing the TLB to ensure any changes in protection
1927c3c6c9fcSLai Jiangshan 	 * bits are recognized, i.e. until the guest flushes or page faults on
1928c3c6c9fcSLai Jiangshan 	 * a relevant address, KVM is architecturally allowed to let vCPUs use
1929c3c6c9fcSLai Jiangshan 	 * cached translations with the old protection bits.
1930c3c6c9fcSLai Jiangshan 	 */
1931c3c6c9fcSLai Jiangshan 	return flush;
193290e44470SLai Jiangshan }
193390e44470SLai Jiangshan 
19348d5678a7SHou Wenlong static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1935c50d8ae3SPaolo Bonzini 			 struct list_head *invalid_list)
1936c50d8ae3SPaolo Bonzini {
193790e44470SLai Jiangshan 	int ret = __kvm_sync_page(vcpu, sp);
1938c3e5e415SLai Jiangshan 
19398d5678a7SHou Wenlong 	if (ret < 0)
1940c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
19418d5678a7SHou Wenlong 	return ret;
1942c50d8ae3SPaolo Bonzini }
1943c50d8ae3SPaolo Bonzini 
1944c50d8ae3SPaolo Bonzini static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1945c50d8ae3SPaolo Bonzini 					struct list_head *invalid_list,
1946c50d8ae3SPaolo Bonzini 					bool remote_flush)
1947c50d8ae3SPaolo Bonzini {
1948c50d8ae3SPaolo Bonzini 	if (!remote_flush && list_empty(invalid_list))
1949c50d8ae3SPaolo Bonzini 		return false;
1950c50d8ae3SPaolo Bonzini 
1951c50d8ae3SPaolo Bonzini 	if (!list_empty(invalid_list))
1952c50d8ae3SPaolo Bonzini 		kvm_mmu_commit_zap_page(kvm, invalid_list);
1953c50d8ae3SPaolo Bonzini 	else
1954c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
1955c50d8ae3SPaolo Bonzini 	return true;
1956c50d8ae3SPaolo Bonzini }
1957c50d8ae3SPaolo Bonzini 
1958c50d8ae3SPaolo Bonzini static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
1959c50d8ae3SPaolo Bonzini {
1960a955cad8SSean Christopherson 	if (sp->role.invalid)
1961a955cad8SSean Christopherson 		return true;
1962a955cad8SSean Christopherson 
1963fa3e4203SMiaohe Lin 	/* TDP MMU pages do not use the MMU generation. */
1964de0322f5SSean Christopherson 	return !is_tdp_mmu_page(sp) &&
1965c50d8ae3SPaolo Bonzini 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
1966c50d8ae3SPaolo Bonzini }
1967c50d8ae3SPaolo Bonzini 
1968c50d8ae3SPaolo Bonzini struct mmu_page_path {
1969c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
1970c50d8ae3SPaolo Bonzini 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
1971c50d8ae3SPaolo Bonzini };
1972c50d8ae3SPaolo Bonzini 
1973c50d8ae3SPaolo Bonzini #define for_each_sp(pvec, sp, parents, i)			\
1974c50d8ae3SPaolo Bonzini 		for (i = mmu_pages_first(&pvec, &parents);	\
1975c50d8ae3SPaolo Bonzini 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
1976c50d8ae3SPaolo Bonzini 			i = mmu_pages_next(&pvec, &parents, i))
1977c50d8ae3SPaolo Bonzini 
1978c50d8ae3SPaolo Bonzini static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1979c50d8ae3SPaolo Bonzini 			  struct mmu_page_path *parents,
1980c50d8ae3SPaolo Bonzini 			  int i)
1981c50d8ae3SPaolo Bonzini {
1982c50d8ae3SPaolo Bonzini 	int n;
1983c50d8ae3SPaolo Bonzini 
1984c50d8ae3SPaolo Bonzini 	for (n = i+1; n < pvec->nr; n++) {
1985c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp = pvec->page[n].sp;
1986c50d8ae3SPaolo Bonzini 		unsigned idx = pvec->page[n].idx;
1987c50d8ae3SPaolo Bonzini 		int level = sp->role.level;
1988c50d8ae3SPaolo Bonzini 
1989c50d8ae3SPaolo Bonzini 		parents->idx[level-1] = idx;
19903bae0459SSean Christopherson 		if (level == PG_LEVEL_4K)
1991c50d8ae3SPaolo Bonzini 			break;
1992c50d8ae3SPaolo Bonzini 
1993c50d8ae3SPaolo Bonzini 		parents->parent[level-2] = sp;
1994c50d8ae3SPaolo Bonzini 	}
1995c50d8ae3SPaolo Bonzini 
1996c50d8ae3SPaolo Bonzini 	return n;
1997c50d8ae3SPaolo Bonzini }
1998c50d8ae3SPaolo Bonzini 
1999c50d8ae3SPaolo Bonzini static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2000c50d8ae3SPaolo Bonzini 			   struct mmu_page_path *parents)
2001c50d8ae3SPaolo Bonzini {
2002c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2003c50d8ae3SPaolo Bonzini 	int level;
2004c50d8ae3SPaolo Bonzini 
2005c50d8ae3SPaolo Bonzini 	if (pvec->nr == 0)
2006c50d8ae3SPaolo Bonzini 		return 0;
2007c50d8ae3SPaolo Bonzini 
200820ba462dSSean Christopherson 	WARN_ON_ONCE(pvec->page[0].idx != INVALID_INDEX);
2009c50d8ae3SPaolo Bonzini 
2010c50d8ae3SPaolo Bonzini 	sp = pvec->page[0].sp;
2011c50d8ae3SPaolo Bonzini 	level = sp->role.level;
201220ba462dSSean Christopherson 	WARN_ON_ONCE(level == PG_LEVEL_4K);
2013c50d8ae3SPaolo Bonzini 
2014c50d8ae3SPaolo Bonzini 	parents->parent[level-2] = sp;
2015c50d8ae3SPaolo Bonzini 
2016c50d8ae3SPaolo Bonzini 	/* Also set up a sentinel.  Further entries in pvec are all
2017c50d8ae3SPaolo Bonzini 	 * children of sp, so this element is never overwritten.
2018c50d8ae3SPaolo Bonzini 	 */
2019c50d8ae3SPaolo Bonzini 	parents->parent[level-1] = NULL;
2020c50d8ae3SPaolo Bonzini 	return mmu_pages_next(pvec, parents, 0);
2021c50d8ae3SPaolo Bonzini }
2022c50d8ae3SPaolo Bonzini 
2023c50d8ae3SPaolo Bonzini static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2024c50d8ae3SPaolo Bonzini {
2025c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2026c50d8ae3SPaolo Bonzini 	unsigned int level = 0;
2027c50d8ae3SPaolo Bonzini 
2028c50d8ae3SPaolo Bonzini 	do {
2029c50d8ae3SPaolo Bonzini 		unsigned int idx = parents->idx[level];
2030c50d8ae3SPaolo Bonzini 		sp = parents->parent[level];
2031c50d8ae3SPaolo Bonzini 		if (!sp)
2032c50d8ae3SPaolo Bonzini 			return;
2033c50d8ae3SPaolo Bonzini 
203420ba462dSSean Christopherson 		WARN_ON_ONCE(idx == INVALID_INDEX);
2035c50d8ae3SPaolo Bonzini 		clear_unsync_child_bit(sp, idx);
2036c50d8ae3SPaolo Bonzini 		level++;
2037c50d8ae3SPaolo Bonzini 	} while (!sp->unsync_children);
2038c50d8ae3SPaolo Bonzini }
2039c50d8ae3SPaolo Bonzini 
204065855ed8SLai Jiangshan static int mmu_sync_children(struct kvm_vcpu *vcpu,
204165855ed8SLai Jiangshan 			     struct kvm_mmu_page *parent, bool can_yield)
2042c50d8ae3SPaolo Bonzini {
2043c50d8ae3SPaolo Bonzini 	int i;
2044c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2045c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2046c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2047c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2048c50d8ae3SPaolo Bonzini 	bool flush = false;
2049c50d8ae3SPaolo Bonzini 
2050c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2051c50d8ae3SPaolo Bonzini 		bool protected = false;
2052c50d8ae3SPaolo Bonzini 
2053c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i)
2054cf48f9e2SDavid Matlack 			protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2055c50d8ae3SPaolo Bonzini 
2056c50d8ae3SPaolo Bonzini 		if (protected) {
20575591c069SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2058c50d8ae3SPaolo Bonzini 			flush = false;
2059c50d8ae3SPaolo Bonzini 		}
2060c50d8ae3SPaolo Bonzini 
2061c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2062479a1efcSSean Christopherson 			kvm_unlink_unsync_page(vcpu->kvm, sp);
20638d5678a7SHou Wenlong 			flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2064c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2065c50d8ae3SPaolo Bonzini 		}
2066531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2067c3e5e415SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
206865855ed8SLai Jiangshan 			if (!can_yield) {
206965855ed8SLai Jiangshan 				kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
207065855ed8SLai Jiangshan 				return -EINTR;
207165855ed8SLai Jiangshan 			}
207265855ed8SLai Jiangshan 
2073531810caSBen Gardon 			cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2074c50d8ae3SPaolo Bonzini 			flush = false;
2075c50d8ae3SPaolo Bonzini 		}
2076c50d8ae3SPaolo Bonzini 	}
2077c50d8ae3SPaolo Bonzini 
2078c3e5e415SLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
207965855ed8SLai Jiangshan 	return 0;
2080c50d8ae3SPaolo Bonzini }
2081c50d8ae3SPaolo Bonzini 
2082c50d8ae3SPaolo Bonzini static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2083c50d8ae3SPaolo Bonzini {
2084c50d8ae3SPaolo Bonzini 	atomic_set(&sp->write_flooding_count,  0);
2085c50d8ae3SPaolo Bonzini }
2086c50d8ae3SPaolo Bonzini 
2087c50d8ae3SPaolo Bonzini static void clear_sp_write_flooding_count(u64 *spte)
2088c50d8ae3SPaolo Bonzini {
208957354682SSean Christopherson 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
2090c50d8ae3SPaolo Bonzini }
2091c50d8ae3SPaolo Bonzini 
2092cbd858b1SDavid Matlack /*
2093cbd858b1SDavid Matlack  * The vCPU is required when finding indirect shadow pages; the shadow
2094cbd858b1SDavid Matlack  * page may already exist and syncing it needs the vCPU pointer in
2095cbd858b1SDavid Matlack  * order to read guest page tables.  Direct shadow pages are never
2096cbd858b1SDavid Matlack  * unsync, thus @vcpu can be NULL if @role.direct is true.
2097cbd858b1SDavid Matlack  */
20983cc736b3SDavid Matlack static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
20993cc736b3SDavid Matlack 						     struct kvm_vcpu *vcpu,
210094c81364SDavid Matlack 						     gfn_t gfn,
210194c81364SDavid Matlack 						     struct hlist_head *sp_list,
21022e65e842SDavid Matlack 						     union kvm_mmu_page_role role)
2103c50d8ae3SPaolo Bonzini {
2104c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
21058d5678a7SHou Wenlong 	int ret;
2106c50d8ae3SPaolo Bonzini 	int collisions = 0;
2107c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2108c50d8ae3SPaolo Bonzini 
21093cc736b3SDavid Matlack 	for_each_valid_sp(kvm, sp, sp_list) {
2110c50d8ae3SPaolo Bonzini 		if (sp->gfn != gfn) {
2111c50d8ae3SPaolo Bonzini 			collisions++;
2112c50d8ae3SPaolo Bonzini 			continue;
2113c50d8ae3SPaolo Bonzini 		}
2114c50d8ae3SPaolo Bonzini 
2115ddc16abbSSean Christopherson 		if (sp->role.word != role.word) {
2116ddc16abbSSean Christopherson 			/*
2117ddc16abbSSean Christopherson 			 * If the guest is creating an upper-level page, zap
2118ddc16abbSSean Christopherson 			 * unsync pages for the same gfn.  While it's possible
2119ddc16abbSSean Christopherson 			 * the guest is using recursive page tables, in all
2120ddc16abbSSean Christopherson 			 * likelihood the guest has stopped using the unsync
2121ddc16abbSSean Christopherson 			 * page and is installing a completely unrelated page.
2122ddc16abbSSean Christopherson 			 * Unsync pages must not be left as is, because the new
2123ddc16abbSSean Christopherson 			 * upper-level page will be write-protected.
2124ddc16abbSSean Christopherson 			 */
21252e65e842SDavid Matlack 			if (role.level > PG_LEVEL_4K && sp->unsync)
21263cc736b3SDavid Matlack 				kvm_mmu_prepare_zap_page(kvm, sp,
2127ddc16abbSSean Christopherson 							 &invalid_list);
2128c50d8ae3SPaolo Bonzini 			continue;
2129ddc16abbSSean Christopherson 		}
2130c50d8ae3SPaolo Bonzini 
2131bb924ca6SDavid Matlack 		/* unsync and write-flooding only apply to indirect SPs. */
2132bb924ca6SDavid Matlack 		if (sp->role.direct)
213394c81364SDavid Matlack 			goto out;
2134fb58a9c3SSean Christopherson 
2135c50d8ae3SPaolo Bonzini 		if (sp->unsync) {
2136cbd858b1SDavid Matlack 			if (KVM_BUG_ON(!vcpu, kvm))
2137cbd858b1SDavid Matlack 				break;
2138cbd858b1SDavid Matlack 
213907dc4f35SSean Christopherson 			/*
2140479a1efcSSean Christopherson 			 * The page is good, but is stale.  kvm_sync_page does
214107dc4f35SSean Christopherson 			 * get the latest guest state, but (unlike mmu_unsync_children)
214207dc4f35SSean Christopherson 			 * it doesn't write-protect the page or mark it synchronized!
214307dc4f35SSean Christopherson 			 * This way the validity of the mapping is ensured, but the
214407dc4f35SSean Christopherson 			 * overhead of write protection is not incurred until the
214507dc4f35SSean Christopherson 			 * guest invalidates the TLB mapping.  This allows multiple
214607dc4f35SSean Christopherson 			 * SPs for a single gfn to be unsync.
214707dc4f35SSean Christopherson 			 *
214807dc4f35SSean Christopherson 			 * If the sync fails, the page is zapped.  If so, break
214907dc4f35SSean Christopherson 			 * in order to rebuild it.
2150c50d8ae3SPaolo Bonzini 			 */
21518d5678a7SHou Wenlong 			ret = kvm_sync_page(vcpu, sp, &invalid_list);
21528d5678a7SHou Wenlong 			if (ret < 0)
2153c50d8ae3SPaolo Bonzini 				break;
2154c50d8ae3SPaolo Bonzini 
215520ba462dSSean Christopherson 			WARN_ON_ONCE(!list_empty(&invalid_list));
21568d5678a7SHou Wenlong 			if (ret > 0)
21573cc736b3SDavid Matlack 				kvm_flush_remote_tlbs(kvm);
2158c50d8ae3SPaolo Bonzini 		}
2159c50d8ae3SPaolo Bonzini 
2160c50d8ae3SPaolo Bonzini 		__clear_sp_write_flooding_count(sp);
2161fb58a9c3SSean Christopherson 
2162c50d8ae3SPaolo Bonzini 		goto out;
2163c50d8ae3SPaolo Bonzini 	}
2164c50d8ae3SPaolo Bonzini 
216594c81364SDavid Matlack 	sp = NULL;
21663cc736b3SDavid Matlack 	++kvm->stat.mmu_cache_miss;
2167c50d8ae3SPaolo Bonzini 
216894c81364SDavid Matlack out:
21693cc736b3SDavid Matlack 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
217094c81364SDavid Matlack 
21713cc736b3SDavid Matlack 	if (collisions > kvm->stat.max_mmu_page_hash_collisions)
21723cc736b3SDavid Matlack 		kvm->stat.max_mmu_page_hash_collisions = collisions;
217394c81364SDavid Matlack 	return sp;
217494c81364SDavid Matlack }
217594c81364SDavid Matlack 
21762f8b1b53SDavid Matlack /* Caches used when allocating a new shadow page. */
21772f8b1b53SDavid Matlack struct shadow_page_caches {
21782f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *page_header_cache;
21792f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *shadow_page_cache;
21806a97575dSDavid Matlack 	struct kvm_mmu_memory_cache *shadowed_info_cache;
21812f8b1b53SDavid Matlack };
21822f8b1b53SDavid Matlack 
2183336081fbSDavid Matlack static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
21842f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
218594c81364SDavid Matlack 						      gfn_t gfn,
218694c81364SDavid Matlack 						      struct hlist_head *sp_list,
218794c81364SDavid Matlack 						      union kvm_mmu_page_role role)
218894c81364SDavid Matlack {
2189c306aec8SDavid Matlack 	struct kvm_mmu_page *sp;
2190c306aec8SDavid Matlack 
21912f8b1b53SDavid Matlack 	sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
21922f8b1b53SDavid Matlack 	sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
2193c306aec8SDavid Matlack 	if (!role.direct)
21946a97575dSDavid Matlack 		sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2195c306aec8SDavid Matlack 
2196c306aec8SDavid Matlack 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2197c306aec8SDavid Matlack 
219855c510e2SSean Christopherson 	INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2199428e9216SSean Christopherson 
2200c306aec8SDavid Matlack 	/*
2201c306aec8SDavid Matlack 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2202c306aec8SDavid Matlack 	 * depends on valid pages being added to the head of the list.  See
2203c306aec8SDavid Matlack 	 * comments in kvm_zap_obsolete_pages().
2204c306aec8SDavid Matlack 	 */
2205336081fbSDavid Matlack 	sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2206336081fbSDavid Matlack 	list_add(&sp->link, &kvm->arch.active_mmu_pages);
220743a063caSYosry Ahmed 	kvm_account_mmu_page(kvm, sp);
2208c50d8ae3SPaolo Bonzini 
2209c50d8ae3SPaolo Bonzini 	sp->gfn = gfn;
2210c50d8ae3SPaolo Bonzini 	sp->role = role;
2211ac101b7cSSean Christopherson 	hlist_add_head(&sp->hash_link, sp_list);
2212be911771SDavid Matlack 	if (sp_has_gptes(sp))
2213336081fbSDavid Matlack 		account_shadowed(kvm, sp);
2214ddc16abbSSean Christopherson 
221594c81364SDavid Matlack 	return sp;
221694c81364SDavid Matlack }
221794c81364SDavid Matlack 
2218cbd858b1SDavid Matlack /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
22193cc736b3SDavid Matlack static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
22203cc736b3SDavid Matlack 						      struct kvm_vcpu *vcpu,
22212f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
222287654643SDavid Matlack 						      gfn_t gfn,
222394c81364SDavid Matlack 						      union kvm_mmu_page_role role)
222494c81364SDavid Matlack {
222594c81364SDavid Matlack 	struct hlist_head *sp_list;
222694c81364SDavid Matlack 	struct kvm_mmu_page *sp;
222794c81364SDavid Matlack 	bool created = false;
222894c81364SDavid Matlack 
22293cc736b3SDavid Matlack 	sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
223094c81364SDavid Matlack 
22313cc736b3SDavid Matlack 	sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
223294c81364SDavid Matlack 	if (!sp) {
223394c81364SDavid Matlack 		created = true;
22343cc736b3SDavid Matlack 		sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
223594c81364SDavid Matlack 	}
223694c81364SDavid Matlack 
223794c81364SDavid Matlack 	trace_kvm_mmu_get_page(sp, created);
2238c50d8ae3SPaolo Bonzini 	return sp;
2239c50d8ae3SPaolo Bonzini }
2240c50d8ae3SPaolo Bonzini 
22412f8b1b53SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
22422f8b1b53SDavid Matlack 						    gfn_t gfn,
22432f8b1b53SDavid Matlack 						    union kvm_mmu_page_role role)
22442f8b1b53SDavid Matlack {
22452f8b1b53SDavid Matlack 	struct shadow_page_caches caches = {
22462f8b1b53SDavid Matlack 		.page_header_cache = &vcpu->arch.mmu_page_header_cache,
22472f8b1b53SDavid Matlack 		.shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
22486a97575dSDavid Matlack 		.shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
22492f8b1b53SDavid Matlack 	};
22502f8b1b53SDavid Matlack 
22513cc736b3SDavid Matlack 	return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
22522f8b1b53SDavid Matlack }
22532f8b1b53SDavid Matlack 
225439944ab9SSean Christopherson static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
225539944ab9SSean Christopherson 						  unsigned int access)
22562e65e842SDavid Matlack {
22572e65e842SDavid Matlack 	struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
22582e65e842SDavid Matlack 	union kvm_mmu_page_role role;
22592e65e842SDavid Matlack 
22602e65e842SDavid Matlack 	role = parent_sp->role;
22612e65e842SDavid Matlack 	role.level--;
22622e65e842SDavid Matlack 	role.access = access;
22632e65e842SDavid Matlack 	role.direct = direct;
22642e65e842SDavid Matlack 	role.passthrough = 0;
22652e65e842SDavid Matlack 
22662e65e842SDavid Matlack 	/*
22672e65e842SDavid Matlack 	 * If the guest has 4-byte PTEs then that means it's using 32-bit,
22682e65e842SDavid Matlack 	 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
22692e65e842SDavid Matlack 	 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
22702e65e842SDavid Matlack 	 * shadow each guest page table with multiple shadow page tables, which
22712e65e842SDavid Matlack 	 * requires extra bookkeeping in the role.
22722e65e842SDavid Matlack 	 *
22732e65e842SDavid Matlack 	 * Specifically, to shadow the guest's page directory (which covers a
22742e65e842SDavid Matlack 	 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
22752e65e842SDavid Matlack 	 * 1GiB of the address space. @role.quadrant encodes which quarter of
22762e65e842SDavid Matlack 	 * the address space each maps.
22772e65e842SDavid Matlack 	 *
22782e65e842SDavid Matlack 	 * To shadow the guest's page tables (which each map a 4MiB region), KVM
22792e65e842SDavid Matlack 	 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
22802e65e842SDavid Matlack 	 * @role.quadrant encodes which half of the region they map.
22812e65e842SDavid Matlack 	 *
228239944ab9SSean Christopherson 	 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
228339944ab9SSean Christopherson 	 * consumes bits 29:21.  To consume bits 31:30, KVM's uses 4 shadow
228439944ab9SSean Christopherson 	 * PDPTEs; those 4 PAE page directories are pre-allocated and their
228539944ab9SSean Christopherson 	 * quadrant is assigned in mmu_alloc_root().   A 4-byte PTE consumes
228639944ab9SSean Christopherson 	 * bits 21:12, while an 8-byte PTE consumes bits 20:12.  To consume
228739944ab9SSean Christopherson 	 * bit 21 in the PTE (the child here), KVM propagates that bit to the
228839944ab9SSean Christopherson 	 * quadrant, i.e. sets quadrant to '0' or '1'.  The parent 8-byte PDE
228939944ab9SSean Christopherson 	 * covers bit 21 (see above), thus the quadrant is calculated from the
229039944ab9SSean Christopherson 	 * _least_ significant bit of the PDE index.
22912e65e842SDavid Matlack 	 */
22922e65e842SDavid Matlack 	if (role.has_4_byte_gpte) {
22932e65e842SDavid Matlack 		WARN_ON_ONCE(role.level != PG_LEVEL_4K);
229479e48cecSSean Christopherson 		role.quadrant = spte_index(sptep) & 1;
22952e65e842SDavid Matlack 	}
22962e65e842SDavid Matlack 
22972e65e842SDavid Matlack 	return role;
22982e65e842SDavid Matlack }
22992e65e842SDavid Matlack 
23002e65e842SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
23012e65e842SDavid Matlack 						 u64 *sptep, gfn_t gfn,
23022e65e842SDavid Matlack 						 bool direct, unsigned int access)
23032e65e842SDavid Matlack {
23042e65e842SDavid Matlack 	union kvm_mmu_page_role role;
23052e65e842SDavid Matlack 
23060cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
23070cd8dc73SPaolo Bonzini 		return ERR_PTR(-EEXIST);
23080cd8dc73SPaolo Bonzini 
23092e65e842SDavid Matlack 	role = kvm_mmu_child_role(sptep, direct, access);
231087654643SDavid Matlack 	return kvm_mmu_get_shadow_page(vcpu, gfn, role);
23112e65e842SDavid Matlack }
23122e65e842SDavid Matlack 
2313c50d8ae3SPaolo Bonzini static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2314c50d8ae3SPaolo Bonzini 					struct kvm_vcpu *vcpu, hpa_t root,
2315c50d8ae3SPaolo Bonzini 					u64 addr)
2316c50d8ae3SPaolo Bonzini {
2317c50d8ae3SPaolo Bonzini 	iterator->addr = addr;
2318c50d8ae3SPaolo Bonzini 	iterator->shadow_addr = root;
2319a972e29cSPaolo Bonzini 	iterator->level = vcpu->arch.mmu->root_role.level;
2320c50d8ae3SPaolo Bonzini 
232112ec33a7SLai Jiangshan 	if (iterator->level >= PT64_ROOT_4LEVEL &&
23224d25502aSPaolo Bonzini 	    vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2323347a0d0dSPaolo Bonzini 	    !vcpu->arch.mmu->root_role.direct)
232412ec33a7SLai Jiangshan 		iterator->level = PT32E_ROOT_LEVEL;
2325c50d8ae3SPaolo Bonzini 
2326c50d8ae3SPaolo Bonzini 	if (iterator->level == PT32E_ROOT_LEVEL) {
2327c50d8ae3SPaolo Bonzini 		/*
2328c50d8ae3SPaolo Bonzini 		 * prev_root is currently only used for 64-bit hosts. So only
2329c50d8ae3SPaolo Bonzini 		 * the active root_hpa is valid here.
2330c50d8ae3SPaolo Bonzini 		 */
2331b9e5603cSPaolo Bonzini 		BUG_ON(root != vcpu->arch.mmu->root.hpa);
2332c50d8ae3SPaolo Bonzini 
2333c50d8ae3SPaolo Bonzini 		iterator->shadow_addr
2334c50d8ae3SPaolo Bonzini 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
23352ca3129eSSean Christopherson 		iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2336c50d8ae3SPaolo Bonzini 		--iterator->level;
2337c50d8ae3SPaolo Bonzini 		if (!iterator->shadow_addr)
2338c50d8ae3SPaolo Bonzini 			iterator->level = 0;
2339c50d8ae3SPaolo Bonzini 	}
2340c50d8ae3SPaolo Bonzini }
2341c50d8ae3SPaolo Bonzini 
2342c50d8ae3SPaolo Bonzini static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2343c50d8ae3SPaolo Bonzini 			     struct kvm_vcpu *vcpu, u64 addr)
2344c50d8ae3SPaolo Bonzini {
2345b9e5603cSPaolo Bonzini 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2346c50d8ae3SPaolo Bonzini 				    addr);
2347c50d8ae3SPaolo Bonzini }
2348c50d8ae3SPaolo Bonzini 
2349c50d8ae3SPaolo Bonzini static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2350c50d8ae3SPaolo Bonzini {
23513bae0459SSean Christopherson 	if (iterator->level < PG_LEVEL_4K)
2352c50d8ae3SPaolo Bonzini 		return false;
2353c50d8ae3SPaolo Bonzini 
23542ca3129eSSean Christopherson 	iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2355c50d8ae3SPaolo Bonzini 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2356c50d8ae3SPaolo Bonzini 	return true;
2357c50d8ae3SPaolo Bonzini }
2358c50d8ae3SPaolo Bonzini 
2359c50d8ae3SPaolo Bonzini static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2360c50d8ae3SPaolo Bonzini 			       u64 spte)
2361c50d8ae3SPaolo Bonzini {
23623e44dce4SLai Jiangshan 	if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2363c50d8ae3SPaolo Bonzini 		iterator->level = 0;
2364c50d8ae3SPaolo Bonzini 		return;
2365c50d8ae3SPaolo Bonzini 	}
2366c50d8ae3SPaolo Bonzini 
23672ca3129eSSean Christopherson 	iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2368c50d8ae3SPaolo Bonzini 	--iterator->level;
2369c50d8ae3SPaolo Bonzini }
2370c50d8ae3SPaolo Bonzini 
2371c50d8ae3SPaolo Bonzini static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2372c50d8ae3SPaolo Bonzini {
2373c50d8ae3SPaolo Bonzini 	__shadow_walk_next(iterator, *iterator->sptep);
2374c50d8ae3SPaolo Bonzini }
2375c50d8ae3SPaolo Bonzini 
23760cd8dc73SPaolo Bonzini static void __link_shadow_page(struct kvm *kvm,
23770cd8dc73SPaolo Bonzini 			       struct kvm_mmu_memory_cache *cache, u64 *sptep,
237803787394SPaolo Bonzini 			       struct kvm_mmu_page *sp, bool flush)
2379c50d8ae3SPaolo Bonzini {
2380c50d8ae3SPaolo Bonzini 	u64 spte;
2381c50d8ae3SPaolo Bonzini 
2382c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2383c50d8ae3SPaolo Bonzini 
23840cd8dc73SPaolo Bonzini 	/*
23850cd8dc73SPaolo Bonzini 	 * If an SPTE is present already, it must be a leaf and therefore
238603787394SPaolo Bonzini 	 * a large one.  Drop it, and flush the TLB if needed, before
238703787394SPaolo Bonzini 	 * installing sp.
23880cd8dc73SPaolo Bonzini 	 */
23890cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep))
239003787394SPaolo Bonzini 		drop_large_spte(kvm, sptep, flush);
23910cd8dc73SPaolo Bonzini 
2392cc4674d0SBen Gardon 	spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2393c50d8ae3SPaolo Bonzini 
2394c50d8ae3SPaolo Bonzini 	mmu_spte_set(sptep, spte);
2395c50d8ae3SPaolo Bonzini 
23962ff9039aSDavid Matlack 	mmu_page_add_parent_pte(cache, sp, sptep);
2397c50d8ae3SPaolo Bonzini 
2398c4a48868SLai Jiangshan 	/*
2399c4a48868SLai Jiangshan 	 * The non-direct sub-pagetable must be updated before linking.  For
2400c4a48868SLai Jiangshan 	 * L1 sp, the pagetable is updated via kvm_sync_page() in
2401c4a48868SLai Jiangshan 	 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2402c4a48868SLai Jiangshan 	 * so sp->unsync can be true or false.  For higher level non-direct
2403c4a48868SLai Jiangshan 	 * sp, the pagetable is updated/synced via mmu_sync_children() in
2404c4a48868SLai Jiangshan 	 * FNAME(fetch)(), so sp->unsync_children can only be false.
2405c4a48868SLai Jiangshan 	 * WARN_ON_ONCE() if anything happens unexpectedly.
2406c4a48868SLai Jiangshan 	 */
2407c4a48868SLai Jiangshan 	if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2408c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
2409c50d8ae3SPaolo Bonzini }
2410c50d8ae3SPaolo Bonzini 
24112ff9039aSDavid Matlack static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
24122ff9039aSDavid Matlack 			     struct kvm_mmu_page *sp)
24132ff9039aSDavid Matlack {
241403787394SPaolo Bonzini 	__link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
24152ff9039aSDavid Matlack }
24162ff9039aSDavid Matlack 
2417c50d8ae3SPaolo Bonzini static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2418c50d8ae3SPaolo Bonzini 				   unsigned direct_access)
2419c50d8ae3SPaolo Bonzini {
2420c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2421c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
2422c50d8ae3SPaolo Bonzini 
2423c50d8ae3SPaolo Bonzini 		/*
2424c50d8ae3SPaolo Bonzini 		 * For the direct sp, if the guest pte's dirty bit
2425c50d8ae3SPaolo Bonzini 		 * changed form clean to dirty, it will corrupt the
2426c50d8ae3SPaolo Bonzini 		 * sp's access: allow writable in the read-only sp,
2427c50d8ae3SPaolo Bonzini 		 * so we should update the spte at this point to get
2428c50d8ae3SPaolo Bonzini 		 * a new sp with the correct access.
2429c50d8ae3SPaolo Bonzini 		 */
24305e3edd7eSSean Christopherson 		child = spte_to_child_sp(*sptep);
2431c50d8ae3SPaolo Bonzini 		if (child->role.access == direct_access)
2432c50d8ae3SPaolo Bonzini 			return;
2433c50d8ae3SPaolo Bonzini 
2434069f30c6SMingwei Zhang 		drop_parent_pte(vcpu->kvm, child, sptep);
24353cdf9374SHou Wenlong 		kvm_flush_remote_tlbs_sptep(vcpu->kvm, sptep);
2436c50d8ae3SPaolo Bonzini 	}
2437c50d8ae3SPaolo Bonzini }
2438c50d8ae3SPaolo Bonzini 
24392de4085cSBen Gardon /* Returns the number of zapped non-leaf child shadow pages. */
24402de4085cSBen Gardon static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
24412de4085cSBen Gardon 			    u64 *spte, struct list_head *invalid_list)
2442c50d8ae3SPaolo Bonzini {
2443c50d8ae3SPaolo Bonzini 	u64 pte;
2444c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *child;
2445c50d8ae3SPaolo Bonzini 
2446c50d8ae3SPaolo Bonzini 	pte = *spte;
2447c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(pte)) {
2448c50d8ae3SPaolo Bonzini 		if (is_last_spte(pte, sp->role.level)) {
2449c50d8ae3SPaolo Bonzini 			drop_spte(kvm, spte);
2450c50d8ae3SPaolo Bonzini 		} else {
24515e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2452069f30c6SMingwei Zhang 			drop_parent_pte(kvm, child, spte);
24532de4085cSBen Gardon 
24542de4085cSBen Gardon 			/*
24552de4085cSBen Gardon 			 * Recursively zap nested TDP SPs, parentless SPs are
24562de4085cSBen Gardon 			 * unlikely to be used again in the near future.  This
24572de4085cSBen Gardon 			 * avoids retaining a large number of stale nested SPs.
24582de4085cSBen Gardon 			 */
24592de4085cSBen Gardon 			if (tdp_enabled && invalid_list &&
24602de4085cSBen Gardon 			    child->role.guest_mode && !child->parent_ptes.val)
24612de4085cSBen Gardon 				return kvm_mmu_prepare_zap_page(kvm, child,
24622de4085cSBen Gardon 								invalid_list);
2463c50d8ae3SPaolo Bonzini 		}
2464ace569e0SSean Christopherson 	} else if (is_mmio_spte(pte)) {
2465c50d8ae3SPaolo Bonzini 		mmu_spte_clear_no_track(spte);
2466ace569e0SSean Christopherson 	}
24672de4085cSBen Gardon 	return 0;
2468c50d8ae3SPaolo Bonzini }
2469c50d8ae3SPaolo Bonzini 
24702de4085cSBen Gardon static int kvm_mmu_page_unlink_children(struct kvm *kvm,
24712de4085cSBen Gardon 					struct kvm_mmu_page *sp,
24722de4085cSBen Gardon 					struct list_head *invalid_list)
2473c50d8ae3SPaolo Bonzini {
24742de4085cSBen Gardon 	int zapped = 0;
2475c50d8ae3SPaolo Bonzini 	unsigned i;
2476c50d8ae3SPaolo Bonzini 
24772ca3129eSSean Christopherson 	for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
24782de4085cSBen Gardon 		zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
24792de4085cSBen Gardon 
24802de4085cSBen Gardon 	return zapped;
2481c50d8ae3SPaolo Bonzini }
2482c50d8ae3SPaolo Bonzini 
2483069f30c6SMingwei Zhang static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2484c50d8ae3SPaolo Bonzini {
2485c50d8ae3SPaolo Bonzini 	u64 *sptep;
2486c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
2487c50d8ae3SPaolo Bonzini 
2488c50d8ae3SPaolo Bonzini 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2489069f30c6SMingwei Zhang 		drop_parent_pte(kvm, sp, sptep);
2490c50d8ae3SPaolo Bonzini }
2491c50d8ae3SPaolo Bonzini 
2492c50d8ae3SPaolo Bonzini static int mmu_zap_unsync_children(struct kvm *kvm,
2493c50d8ae3SPaolo Bonzini 				   struct kvm_mmu_page *parent,
2494c50d8ae3SPaolo Bonzini 				   struct list_head *invalid_list)
2495c50d8ae3SPaolo Bonzini {
2496c50d8ae3SPaolo Bonzini 	int i, zapped = 0;
2497c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2498c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2499c50d8ae3SPaolo Bonzini 
25003bae0459SSean Christopherson 	if (parent->role.level == PG_LEVEL_4K)
2501c50d8ae3SPaolo Bonzini 		return 0;
2502c50d8ae3SPaolo Bonzini 
2503c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2504c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
2505c50d8ae3SPaolo Bonzini 
2506c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2507c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2508c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2509c50d8ae3SPaolo Bonzini 			zapped++;
2510c50d8ae3SPaolo Bonzini 		}
2511c50d8ae3SPaolo Bonzini 	}
2512c50d8ae3SPaolo Bonzini 
2513c50d8ae3SPaolo Bonzini 	return zapped;
2514c50d8ae3SPaolo Bonzini }
2515c50d8ae3SPaolo Bonzini 
2516c50d8ae3SPaolo Bonzini static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2517c50d8ae3SPaolo Bonzini 				       struct kvm_mmu_page *sp,
2518c50d8ae3SPaolo Bonzini 				       struct list_head *invalid_list,
2519c50d8ae3SPaolo Bonzini 				       int *nr_zapped)
2520c50d8ae3SPaolo Bonzini {
2521527d5cd7SSean Christopherson 	bool list_unstable, zapped_root = false;
2522c50d8ae3SPaolo Bonzini 
252347b0c2e4SKazuki Takiguchi 	lockdep_assert_held_write(&kvm->mmu_lock);
2524c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_prepare_zap_page(sp);
2525c50d8ae3SPaolo Bonzini 	++kvm->stat.mmu_shadow_zapped;
2526c50d8ae3SPaolo Bonzini 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
25272de4085cSBen Gardon 	*nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2528069f30c6SMingwei Zhang 	kvm_mmu_unlink_parents(kvm, sp);
2529c50d8ae3SPaolo Bonzini 
2530c50d8ae3SPaolo Bonzini 	/* Zapping children means active_mmu_pages has become unstable. */
2531c50d8ae3SPaolo Bonzini 	list_unstable = *nr_zapped;
2532c50d8ae3SPaolo Bonzini 
2533767d8d8dSLai Jiangshan 	if (!sp->role.invalid && sp_has_gptes(sp))
2534c50d8ae3SPaolo Bonzini 		unaccount_shadowed(kvm, sp);
2535c50d8ae3SPaolo Bonzini 
2536c50d8ae3SPaolo Bonzini 	if (sp->unsync)
2537c50d8ae3SPaolo Bonzini 		kvm_unlink_unsync_page(kvm, sp);
2538c50d8ae3SPaolo Bonzini 	if (!sp->root_count) {
2539c50d8ae3SPaolo Bonzini 		/* Count self */
2540c50d8ae3SPaolo Bonzini 		(*nr_zapped)++;
2541f95eec9bSSean Christopherson 
2542f95eec9bSSean Christopherson 		/*
2543f95eec9bSSean Christopherson 		 * Already invalid pages (previously active roots) are not on
2544f95eec9bSSean Christopherson 		 * the active page list.  See list_del() in the "else" case of
2545f95eec9bSSean Christopherson 		 * !sp->root_count.
2546f95eec9bSSean Christopherson 		 */
2547f95eec9bSSean Christopherson 		if (sp->role.invalid)
2548f95eec9bSSean Christopherson 			list_add(&sp->link, invalid_list);
2549f95eec9bSSean Christopherson 		else
2550c50d8ae3SPaolo Bonzini 			list_move(&sp->link, invalid_list);
255143a063caSYosry Ahmed 		kvm_unaccount_mmu_page(kvm, sp);
2552c50d8ae3SPaolo Bonzini 	} else {
2553f95eec9bSSean Christopherson 		/*
2554f95eec9bSSean Christopherson 		 * Remove the active root from the active page list, the root
2555f95eec9bSSean Christopherson 		 * will be explicitly freed when the root_count hits zero.
2556f95eec9bSSean Christopherson 		 */
2557f95eec9bSSean Christopherson 		list_del(&sp->link);
2558c50d8ae3SPaolo Bonzini 
2559c50d8ae3SPaolo Bonzini 		/*
2560c50d8ae3SPaolo Bonzini 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2561c50d8ae3SPaolo Bonzini 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2562c50d8ae3SPaolo Bonzini 		 * treats invalid shadow pages as being obsolete.
2563c50d8ae3SPaolo Bonzini 		 */
2564527d5cd7SSean Christopherson 		zapped_root = !is_obsolete_sp(kvm, sp);
2565c50d8ae3SPaolo Bonzini 	}
2566c50d8ae3SPaolo Bonzini 
256755c510e2SSean Christopherson 	if (sp->nx_huge_page_disallowed)
256855c510e2SSean Christopherson 		unaccount_nx_huge_page(kvm, sp);
2569c50d8ae3SPaolo Bonzini 
2570c50d8ae3SPaolo Bonzini 	sp->role.invalid = 1;
2571527d5cd7SSean Christopherson 
2572527d5cd7SSean Christopherson 	/*
2573527d5cd7SSean Christopherson 	 * Make the request to free obsolete roots after marking the root
2574527d5cd7SSean Christopherson 	 * invalid, otherwise other vCPUs may not see it as invalid.
2575527d5cd7SSean Christopherson 	 */
2576527d5cd7SSean Christopherson 	if (zapped_root)
2577527d5cd7SSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2578c50d8ae3SPaolo Bonzini 	return list_unstable;
2579c50d8ae3SPaolo Bonzini }
2580c50d8ae3SPaolo Bonzini 
2581c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2582c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list)
2583c50d8ae3SPaolo Bonzini {
2584c50d8ae3SPaolo Bonzini 	int nr_zapped;
2585c50d8ae3SPaolo Bonzini 
2586c50d8ae3SPaolo Bonzini 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2587c50d8ae3SPaolo Bonzini 	return nr_zapped;
2588c50d8ae3SPaolo Bonzini }
2589c50d8ae3SPaolo Bonzini 
2590c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2591c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list)
2592c50d8ae3SPaolo Bonzini {
2593c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *nsp;
2594c50d8ae3SPaolo Bonzini 
2595c50d8ae3SPaolo Bonzini 	if (list_empty(invalid_list))
2596c50d8ae3SPaolo Bonzini 		return;
2597c50d8ae3SPaolo Bonzini 
2598c50d8ae3SPaolo Bonzini 	/*
2599c50d8ae3SPaolo Bonzini 	 * We need to make sure everyone sees our modifications to
2600c50d8ae3SPaolo Bonzini 	 * the page tables and see changes to vcpu->mode here. The barrier
2601c50d8ae3SPaolo Bonzini 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2602c50d8ae3SPaolo Bonzini 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2603c50d8ae3SPaolo Bonzini 	 *
2604c50d8ae3SPaolo Bonzini 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2605c50d8ae3SPaolo Bonzini 	 * guest mode and/or lockless shadow page table walks.
2606c50d8ae3SPaolo Bonzini 	 */
2607c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs(kvm);
2608c50d8ae3SPaolo Bonzini 
2609c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
261020ba462dSSean Christopherson 		WARN_ON_ONCE(!sp->role.invalid || sp->root_count);
261187654643SDavid Matlack 		kvm_mmu_free_shadow_page(sp);
2612c50d8ae3SPaolo Bonzini 	}
2613c50d8ae3SPaolo Bonzini }
2614c50d8ae3SPaolo Bonzini 
26156b82ef2cSSean Christopherson static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
26166b82ef2cSSean Christopherson 						  unsigned long nr_to_zap)
2617c50d8ae3SPaolo Bonzini {
26186b82ef2cSSean Christopherson 	unsigned long total_zapped = 0;
26196b82ef2cSSean Christopherson 	struct kvm_mmu_page *sp, *tmp;
2620ba7888ddSSean Christopherson 	LIST_HEAD(invalid_list);
26216b82ef2cSSean Christopherson 	bool unstable;
26226b82ef2cSSean Christopherson 	int nr_zapped;
2623c50d8ae3SPaolo Bonzini 
2624c50d8ae3SPaolo Bonzini 	if (list_empty(&kvm->arch.active_mmu_pages))
2625ba7888ddSSean Christopherson 		return 0;
2626c50d8ae3SPaolo Bonzini 
26276b82ef2cSSean Christopherson restart:
26288fc51726SSean Christopherson 	list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
26296b82ef2cSSean Christopherson 		/*
26306b82ef2cSSean Christopherson 		 * Don't zap active root pages, the page itself can't be freed
26316b82ef2cSSean Christopherson 		 * and zapping it will just force vCPUs to realloc and reload.
26326b82ef2cSSean Christopherson 		 */
26336b82ef2cSSean Christopherson 		if (sp->root_count)
26346b82ef2cSSean Christopherson 			continue;
26356b82ef2cSSean Christopherson 
26366b82ef2cSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
26376b82ef2cSSean Christopherson 						      &nr_zapped);
26386b82ef2cSSean Christopherson 		total_zapped += nr_zapped;
26396b82ef2cSSean Christopherson 		if (total_zapped >= nr_to_zap)
2640ba7888ddSSean Christopherson 			break;
2641ba7888ddSSean Christopherson 
26426b82ef2cSSean Christopherson 		if (unstable)
26436b82ef2cSSean Christopherson 			goto restart;
2644ba7888ddSSean Christopherson 	}
26456b82ef2cSSean Christopherson 
26466b82ef2cSSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
26476b82ef2cSSean Christopherson 
26486b82ef2cSSean Christopherson 	kvm->stat.mmu_recycled += total_zapped;
26496b82ef2cSSean Christopherson 	return total_zapped;
26506b82ef2cSSean Christopherson }
26516b82ef2cSSean Christopherson 
2652afe8d7e6SSean Christopherson static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2653afe8d7e6SSean Christopherson {
2654afe8d7e6SSean Christopherson 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2655afe8d7e6SSean Christopherson 		return kvm->arch.n_max_mmu_pages -
2656afe8d7e6SSean Christopherson 			kvm->arch.n_used_mmu_pages;
2657afe8d7e6SSean Christopherson 
2658afe8d7e6SSean Christopherson 	return 0;
2659c50d8ae3SPaolo Bonzini }
2660c50d8ae3SPaolo Bonzini 
2661ba7888ddSSean Christopherson static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2662ba7888ddSSean Christopherson {
26636b82ef2cSSean Christopherson 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2664ba7888ddSSean Christopherson 
26656b82ef2cSSean Christopherson 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2666ba7888ddSSean Christopherson 		return 0;
2667ba7888ddSSean Christopherson 
26686b82ef2cSSean Christopherson 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2669ba7888ddSSean Christopherson 
26706e6ec584SSean Christopherson 	/*
26716e6ec584SSean Christopherson 	 * Note, this check is intentionally soft, it only guarantees that one
26726e6ec584SSean Christopherson 	 * page is available, while the caller may end up allocating as many as
26736e6ec584SSean Christopherson 	 * four pages, e.g. for PAE roots or for 5-level paging.  Temporarily
26746e6ec584SSean Christopherson 	 * exceeding the (arbitrary by default) limit will not harm the host,
2675c4342633SIngo Molnar 	 * being too aggressive may unnecessarily kill the guest, and getting an
26766e6ec584SSean Christopherson 	 * exact count is far more trouble than it's worth, especially in the
26776e6ec584SSean Christopherson 	 * page fault paths.
26786e6ec584SSean Christopherson 	 */
2679ba7888ddSSean Christopherson 	if (!kvm_mmu_available_pages(vcpu->kvm))
2680ba7888ddSSean Christopherson 		return -ENOSPC;
2681ba7888ddSSean Christopherson 	return 0;
2682ba7888ddSSean Christopherson }
2683ba7888ddSSean Christopherson 
2684c50d8ae3SPaolo Bonzini /*
2685c50d8ae3SPaolo Bonzini  * Changing the number of mmu pages allocated to the vm
2686c50d8ae3SPaolo Bonzini  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2687c50d8ae3SPaolo Bonzini  */
2688c50d8ae3SPaolo Bonzini void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2689c50d8ae3SPaolo Bonzini {
2690531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2691c50d8ae3SPaolo Bonzini 
2692c50d8ae3SPaolo Bonzini 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
26936b82ef2cSSean Christopherson 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
26946b82ef2cSSean Christopherson 						  goal_nr_mmu_pages);
2695c50d8ae3SPaolo Bonzini 
2696c50d8ae3SPaolo Bonzini 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2697c50d8ae3SPaolo Bonzini 	}
2698c50d8ae3SPaolo Bonzini 
2699c50d8ae3SPaolo Bonzini 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2700c50d8ae3SPaolo Bonzini 
2701531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2702c50d8ae3SPaolo Bonzini }
2703c50d8ae3SPaolo Bonzini 
2704c50d8ae3SPaolo Bonzini int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2705c50d8ae3SPaolo Bonzini {
2706c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2707c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2708c50d8ae3SPaolo Bonzini 	int r;
2709c50d8ae3SPaolo Bonzini 
2710c50d8ae3SPaolo Bonzini 	r = 0;
2711531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2712767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2713c50d8ae3SPaolo Bonzini 		r = 1;
2714c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2715c50d8ae3SPaolo Bonzini 	}
2716c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2717531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2718c50d8ae3SPaolo Bonzini 
2719c50d8ae3SPaolo Bonzini 	return r;
2720c50d8ae3SPaolo Bonzini }
272196ad91aeSSean Christopherson 
272296ad91aeSSean Christopherson static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
272396ad91aeSSean Christopherson {
272496ad91aeSSean Christopherson 	gpa_t gpa;
272596ad91aeSSean Christopherson 	int r;
272696ad91aeSSean Christopherson 
2727347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
272896ad91aeSSean Christopherson 		return 0;
272996ad91aeSSean Christopherson 
273096ad91aeSSean Christopherson 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
273196ad91aeSSean Christopherson 
273296ad91aeSSean Christopherson 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
273396ad91aeSSean Christopherson 
273496ad91aeSSean Christopherson 	return r;
273596ad91aeSSean Christopherson }
2736c50d8ae3SPaolo Bonzini 
27374d78d0b3SBen Gardon static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2738c50d8ae3SPaolo Bonzini {
2739c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_unsync_page(sp);
27404d78d0b3SBen Gardon 	++kvm->stat.mmu_unsync;
2741c50d8ae3SPaolo Bonzini 	sp->unsync = 1;
2742c50d8ae3SPaolo Bonzini 
2743c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
2744c50d8ae3SPaolo Bonzini }
2745c50d8ae3SPaolo Bonzini 
27460337f585SSean Christopherson /*
27470337f585SSean Christopherson  * Attempt to unsync any shadow pages that can be reached by the specified gfn,
27480337f585SSean Christopherson  * KVM is creating a writable mapping for said gfn.  Returns 0 if all pages
27490337f585SSean Christopherson  * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
27500337f585SSean Christopherson  * be write-protected.
27510337f585SSean Christopherson  */
27528283e36aSBen Gardon int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
27532839180cSPaolo Bonzini 			    gfn_t gfn, bool can_unsync, bool prefetch)
2754c50d8ae3SPaolo Bonzini {
2755c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2756ce25681dSSean Christopherson 	bool locked = false;
2757c50d8ae3SPaolo Bonzini 
27580337f585SSean Christopherson 	/*
27590337f585SSean Christopherson 	 * Force write-protection if the page is being tracked.  Note, the page
27600337f585SSean Christopherson 	 * track machinery is used to write-protect upper-level shadow pages,
27610337f585SSean Christopherson 	 * i.e. this guards the role.level == 4K assertion below!
27620337f585SSean Christopherson 	 */
27637b574863SSean Christopherson 	if (kvm_gfn_is_write_tracked(kvm, slot, gfn))
27640337f585SSean Christopherson 		return -EPERM;
2765c50d8ae3SPaolo Bonzini 
27660337f585SSean Christopherson 	/*
27670337f585SSean Christopherson 	 * The page is not write-tracked, mark existing shadow pages unsync
27680337f585SSean Christopherson 	 * unless KVM is synchronizing an unsync SP (can_unsync = false).  In
27690337f585SSean Christopherson 	 * that case, KVM must complete emulation of the guest TLB flush before
27700337f585SSean Christopherson 	 * allowing shadow pages to become unsync (writable by the guest).
27710337f585SSean Christopherson 	 */
2772767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2773c50d8ae3SPaolo Bonzini 		if (!can_unsync)
27740337f585SSean Christopherson 			return -EPERM;
2775c50d8ae3SPaolo Bonzini 
2776c50d8ae3SPaolo Bonzini 		if (sp->unsync)
2777c50d8ae3SPaolo Bonzini 			continue;
2778c50d8ae3SPaolo Bonzini 
27792839180cSPaolo Bonzini 		if (prefetch)
2780f1c4a88cSLai Jiangshan 			return -EEXIST;
2781f1c4a88cSLai Jiangshan 
2782ce25681dSSean Christopherson 		/*
2783ce25681dSSean Christopherson 		 * TDP MMU page faults require an additional spinlock as they
2784ce25681dSSean Christopherson 		 * run with mmu_lock held for read, not write, and the unsync
2785ce25681dSSean Christopherson 		 * logic is not thread safe.  Take the spinklock regardless of
2786ce25681dSSean Christopherson 		 * the MMU type to avoid extra conditionals/parameters, there's
2787ce25681dSSean Christopherson 		 * no meaningful penalty if mmu_lock is held for write.
2788ce25681dSSean Christopherson 		 */
2789ce25681dSSean Christopherson 		if (!locked) {
2790ce25681dSSean Christopherson 			locked = true;
27914d78d0b3SBen Gardon 			spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2792ce25681dSSean Christopherson 
2793ce25681dSSean Christopherson 			/*
2794ce25681dSSean Christopherson 			 * Recheck after taking the spinlock, a different vCPU
2795ce25681dSSean Christopherson 			 * may have since marked the page unsync.  A false
2796e59f75deSPaolo Bonzini 			 * negative on the unprotected check above is not
2797ce25681dSSean Christopherson 			 * possible as clearing sp->unsync _must_ hold mmu_lock
2798e59f75deSPaolo Bonzini 			 * for write, i.e. unsync cannot transition from 1->0
2799ce25681dSSean Christopherson 			 * while this CPU holds mmu_lock for read (or write).
2800ce25681dSSean Christopherson 			 */
2801ce25681dSSean Christopherson 			if (READ_ONCE(sp->unsync))
2802ce25681dSSean Christopherson 				continue;
2803ce25681dSSean Christopherson 		}
2804ce25681dSSean Christopherson 
280520ba462dSSean Christopherson 		WARN_ON_ONCE(sp->role.level != PG_LEVEL_4K);
28064d78d0b3SBen Gardon 		kvm_unsync_page(kvm, sp);
2807c50d8ae3SPaolo Bonzini 	}
2808ce25681dSSean Christopherson 	if (locked)
28094d78d0b3SBen Gardon 		spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2810c50d8ae3SPaolo Bonzini 
2811c50d8ae3SPaolo Bonzini 	/*
2812c50d8ae3SPaolo Bonzini 	 * We need to ensure that the marking of unsync pages is visible
2813c50d8ae3SPaolo Bonzini 	 * before the SPTE is updated to allow writes because
2814c50d8ae3SPaolo Bonzini 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2815c50d8ae3SPaolo Bonzini 	 * the MMU lock and so can race with this. If the SPTE was updated
2816c50d8ae3SPaolo Bonzini 	 * before the page had been marked as unsync-ed, something like the
2817c50d8ae3SPaolo Bonzini 	 * following could happen:
2818c50d8ae3SPaolo Bonzini 	 *
2819c50d8ae3SPaolo Bonzini 	 * CPU 1                    CPU 2
2820c50d8ae3SPaolo Bonzini 	 * ---------------------------------------------------------------------
2821c50d8ae3SPaolo Bonzini 	 * 1.2 Host updates SPTE
2822c50d8ae3SPaolo Bonzini 	 *     to be writable
2823c50d8ae3SPaolo Bonzini 	 *                      2.1 Guest writes a GPTE for GVA X.
2824c50d8ae3SPaolo Bonzini 	 *                          (GPTE being in the guest page table shadowed
2825c50d8ae3SPaolo Bonzini 	 *                           by the SP from CPU 1.)
2826c50d8ae3SPaolo Bonzini 	 *                          This reads SPTE during the page table walk.
2827c50d8ae3SPaolo Bonzini 	 *                          Since SPTE.W is read as 1, there is no
2828c50d8ae3SPaolo Bonzini 	 *                          fault.
2829c50d8ae3SPaolo Bonzini 	 *
2830c50d8ae3SPaolo Bonzini 	 *                      2.2 Guest issues TLB flush.
2831c50d8ae3SPaolo Bonzini 	 *                          That causes a VM Exit.
2832c50d8ae3SPaolo Bonzini 	 *
28330337f585SSean Christopherson 	 *                      2.3 Walking of unsync pages sees sp->unsync is
28340337f585SSean Christopherson 	 *                          false and skips the page.
2835c50d8ae3SPaolo Bonzini 	 *
2836c50d8ae3SPaolo Bonzini 	 *                      2.4 Guest accesses GVA X.
2837c50d8ae3SPaolo Bonzini 	 *                          Since the mapping in the SP was not updated,
2838c50d8ae3SPaolo Bonzini 	 *                          so the old mapping for GVA X incorrectly
2839c50d8ae3SPaolo Bonzini 	 *                          gets used.
2840c50d8ae3SPaolo Bonzini 	 * 1.1 Host marks SP
2841c50d8ae3SPaolo Bonzini 	 *     as unsync
2842c50d8ae3SPaolo Bonzini 	 *     (sp->unsync = true)
2843c50d8ae3SPaolo Bonzini 	 *
2844c50d8ae3SPaolo Bonzini 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2845264d3dc1SLai Jiangshan 	 * the situation in 2.4 does not arise.  It pairs with the read barrier
2846264d3dc1SLai Jiangshan 	 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2847c50d8ae3SPaolo Bonzini 	 */
2848c50d8ae3SPaolo Bonzini 	smp_wmb();
2849c50d8ae3SPaolo Bonzini 
28500337f585SSean Christopherson 	return 0;
2851c50d8ae3SPaolo Bonzini }
2852c50d8ae3SPaolo Bonzini 
28538a9f566aSDavid Matlack static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
28548a9f566aSDavid Matlack 			u64 *sptep, unsigned int pte_access, gfn_t gfn,
2855a12f4381SPaolo Bonzini 			kvm_pfn_t pfn, struct kvm_page_fault *fault)
2856799a4190SBen Gardon {
2857d786c778SPaolo Bonzini 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2858eb5cd7ffSPaolo Bonzini 	int level = sp->role.level;
2859c50d8ae3SPaolo Bonzini 	int was_rmapped = 0;
2860c4371c2aSSean Christopherson 	int ret = RET_PF_FIXED;
2861c50d8ae3SPaolo Bonzini 	bool flush = false;
2862ad67e480SPaolo Bonzini 	bool wrprot;
2863d786c778SPaolo Bonzini 	u64 spte;
2864c50d8ae3SPaolo Bonzini 
2865a12f4381SPaolo Bonzini 	/* Prefetching always gets a writable pfn.  */
2866a12f4381SPaolo Bonzini 	bool host_writable = !fault || fault->map_writable;
28672839180cSPaolo Bonzini 	bool prefetch = !fault || fault->prefetch;
2868a12f4381SPaolo Bonzini 	bool write_fault = fault && fault->write;
2869c50d8ae3SPaolo Bonzini 
2870a54aa15cSSean Christopherson 	if (unlikely(is_noslot_pfn(pfn))) {
28711075d41eSSean Christopherson 		vcpu->stat.pf_mmio_spte_created++;
2872a54aa15cSSean Christopherson 		mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2873a54aa15cSSean Christopherson 		return RET_PF_EMULATE;
2874a54aa15cSSean Christopherson 	}
2875a54aa15cSSean Christopherson 
2876c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep)) {
2877c50d8ae3SPaolo Bonzini 		/*
2878c50d8ae3SPaolo Bonzini 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2879c50d8ae3SPaolo Bonzini 		 * the parent of the now unreachable PTE.
2880c50d8ae3SPaolo Bonzini 		 */
28813bae0459SSean Christopherson 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2882c50d8ae3SPaolo Bonzini 			struct kvm_mmu_page *child;
2883c50d8ae3SPaolo Bonzini 			u64 pte = *sptep;
2884c50d8ae3SPaolo Bonzini 
28855e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2886069f30c6SMingwei Zhang 			drop_parent_pte(vcpu->kvm, child, sptep);
2887c50d8ae3SPaolo Bonzini 			flush = true;
2888c50d8ae3SPaolo Bonzini 		} else if (pfn != spte_to_pfn(*sptep)) {
2889c50d8ae3SPaolo Bonzini 			drop_spte(vcpu->kvm, sptep);
2890c50d8ae3SPaolo Bonzini 			flush = true;
2891c50d8ae3SPaolo Bonzini 		} else
2892c50d8ae3SPaolo Bonzini 			was_rmapped = 1;
2893c50d8ae3SPaolo Bonzini 	}
2894c50d8ae3SPaolo Bonzini 
28952839180cSPaolo Bonzini 	wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
28967158bee4SPaolo Bonzini 			   true, host_writable, &spte);
2897d786c778SPaolo Bonzini 
2898d786c778SPaolo Bonzini 	if (*sptep == spte) {
2899d786c778SPaolo Bonzini 		ret = RET_PF_SPURIOUS;
2900d786c778SPaolo Bonzini 	} else {
2901d786c778SPaolo Bonzini 		flush |= mmu_spte_update(sptep, spte);
29025959ff4aSMaxim Levitsky 		trace_kvm_mmu_set_spte(level, gfn, sptep);
2903c50d8ae3SPaolo Bonzini 	}
2904c50d8ae3SPaolo Bonzini 
2905ad67e480SPaolo Bonzini 	if (wrprot) {
2906c50d8ae3SPaolo Bonzini 		if (write_fault)
2907c50d8ae3SPaolo Bonzini 			ret = RET_PF_EMULATE;
2908c50d8ae3SPaolo Bonzini 	}
2909c50d8ae3SPaolo Bonzini 
2910d786c778SPaolo Bonzini 	if (flush)
29114ad980aeSHou Wenlong 		kvm_flush_remote_tlbs_gfn(vcpu->kvm, gfn, level);
2912c50d8ae3SPaolo Bonzini 
2913c50d8ae3SPaolo Bonzini 	if (!was_rmapped) {
2914d786c778SPaolo Bonzini 		WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
29156a97575dSDavid Matlack 		rmap_add(vcpu, slot, sptep, gfn, pte_access);
29166a97575dSDavid Matlack 	} else {
29176a97575dSDavid Matlack 		/* Already rmapped but the pte_access bits may have changed. */
291879e48cecSSean Christopherson 		kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
2919c50d8ae3SPaolo Bonzini 	}
2920c50d8ae3SPaolo Bonzini 
2921c50d8ae3SPaolo Bonzini 	return ret;
2922c50d8ae3SPaolo Bonzini }
2923c50d8ae3SPaolo Bonzini 
2924c50d8ae3SPaolo Bonzini static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2925c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp,
2926c50d8ae3SPaolo Bonzini 				    u64 *start, u64 *end)
2927c50d8ae3SPaolo Bonzini {
2928c50d8ae3SPaolo Bonzini 	struct page *pages[PTE_PREFETCH_NUM];
2929c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
29300a2b64c5SBen Gardon 	unsigned int access = sp->role.access;
2931c50d8ae3SPaolo Bonzini 	int i, ret;
2932c50d8ae3SPaolo Bonzini 	gfn_t gfn;
2933c50d8ae3SPaolo Bonzini 
293479e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
2935c50d8ae3SPaolo Bonzini 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2936c50d8ae3SPaolo Bonzini 	if (!slot)
2937c50d8ae3SPaolo Bonzini 		return -1;
2938c50d8ae3SPaolo Bonzini 
2939c50d8ae3SPaolo Bonzini 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2940c50d8ae3SPaolo Bonzini 	if (ret <= 0)
2941c50d8ae3SPaolo Bonzini 		return -1;
2942c50d8ae3SPaolo Bonzini 
2943c50d8ae3SPaolo Bonzini 	for (i = 0; i < ret; i++, gfn++, start++) {
29448a9f566aSDavid Matlack 		mmu_set_spte(vcpu, slot, start, access, gfn,
2945a12f4381SPaolo Bonzini 			     page_to_pfn(pages[i]), NULL);
2946c50d8ae3SPaolo Bonzini 		put_page(pages[i]);
2947c50d8ae3SPaolo Bonzini 	}
2948c50d8ae3SPaolo Bonzini 
2949c50d8ae3SPaolo Bonzini 	return 0;
2950c50d8ae3SPaolo Bonzini }
2951c50d8ae3SPaolo Bonzini 
2952c50d8ae3SPaolo Bonzini static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2953c50d8ae3SPaolo Bonzini 				  struct kvm_mmu_page *sp, u64 *sptep)
2954c50d8ae3SPaolo Bonzini {
2955c50d8ae3SPaolo Bonzini 	u64 *spte, *start = NULL;
2956c50d8ae3SPaolo Bonzini 	int i;
2957c50d8ae3SPaolo Bonzini 
295820ba462dSSean Christopherson 	WARN_ON_ONCE(!sp->role.direct);
2959c50d8ae3SPaolo Bonzini 
296079e48cecSSean Christopherson 	i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
2961c50d8ae3SPaolo Bonzini 	spte = sp->spt + i;
2962c50d8ae3SPaolo Bonzini 
2963c50d8ae3SPaolo Bonzini 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
2964c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*spte) || spte == sptep) {
2965c50d8ae3SPaolo Bonzini 			if (!start)
2966c50d8ae3SPaolo Bonzini 				continue;
2967c50d8ae3SPaolo Bonzini 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2968c6cecc4bSSean Christopherson 				return;
2969c50d8ae3SPaolo Bonzini 			start = NULL;
2970c50d8ae3SPaolo Bonzini 		} else if (!start)
2971c50d8ae3SPaolo Bonzini 			start = spte;
2972c50d8ae3SPaolo Bonzini 	}
2973c6cecc4bSSean Christopherson 	if (start)
2974c6cecc4bSSean Christopherson 		direct_pte_prefetch_many(vcpu, sp, start, spte);
2975c50d8ae3SPaolo Bonzini }
2976c50d8ae3SPaolo Bonzini 
2977c50d8ae3SPaolo Bonzini static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2978c50d8ae3SPaolo Bonzini {
2979c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2980c50d8ae3SPaolo Bonzini 
298157354682SSean Christopherson 	sp = sptep_to_sp(sptep);
2982c50d8ae3SPaolo Bonzini 
2983c50d8ae3SPaolo Bonzini 	/*
2984c50d8ae3SPaolo Bonzini 	 * Without accessed bits, there's no way to distinguish between
2985c50d8ae3SPaolo Bonzini 	 * actually accessed translations and prefetched, so disable pte
2986c50d8ae3SPaolo Bonzini 	 * prefetch if accessed bits aren't available.
2987c50d8ae3SPaolo Bonzini 	 */
2988c50d8ae3SPaolo Bonzini 	if (sp_ad_disabled(sp))
2989c50d8ae3SPaolo Bonzini 		return;
2990c50d8ae3SPaolo Bonzini 
29913bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
2992c50d8ae3SPaolo Bonzini 		return;
2993c50d8ae3SPaolo Bonzini 
29944a42d848SDavid Stevens 	/*
29954a42d848SDavid Stevens 	 * If addresses are being invalidated, skip prefetching to avoid
29964a42d848SDavid Stevens 	 * accidentally prefetching those addresses.
29974a42d848SDavid Stevens 	 */
299820ec3ebdSChao Peng 	if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
29994a42d848SDavid Stevens 		return;
30004a42d848SDavid Stevens 
3001c50d8ae3SPaolo Bonzini 	__direct_pte_prefetch(vcpu, sp, sptep);
3002c50d8ae3SPaolo Bonzini }
3003c50d8ae3SPaolo Bonzini 
300465e3b446SSean Christopherson /*
300565e3b446SSean Christopherson  * Lookup the mapping level for @gfn in the current mm.
300665e3b446SSean Christopherson  *
300765e3b446SSean Christopherson  * WARNING!  Use of host_pfn_mapping_level() requires the caller and the end
300865e3b446SSean Christopherson  * consumer to be tied into KVM's handlers for MMU notifier events!
300965e3b446SSean Christopherson  *
301065e3b446SSean Christopherson  * There are several ways to safely use this helper:
301165e3b446SSean Christopherson  *
30128569992dSChao Peng  * - Check mmu_invalidate_retry_gfn() after grabbing the mapping level, before
301365e3b446SSean Christopherson  *   consuming it.  In this case, mmu_lock doesn't need to be held during the
301465e3b446SSean Christopherson  *   lookup, but it does need to be held while checking the MMU notifier.
301565e3b446SSean Christopherson  *
301665e3b446SSean Christopherson  * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
301765e3b446SSean Christopherson  *   event for the hva.  This can be done by explicit checking the MMU notifier
301865e3b446SSean Christopherson  *   or by ensuring that KVM already has a valid mapping that covers the hva.
301965e3b446SSean Christopherson  *
302065e3b446SSean Christopherson  * - Do not use the result to install new mappings, e.g. use the host mapping
302165e3b446SSean Christopherson  *   level only to decide whether or not to zap an entry.  In this case, it's
302265e3b446SSean Christopherson  *   not required to hold mmu_lock (though it's highly likely the caller will
302365e3b446SSean Christopherson  *   want to hold mmu_lock anyways, e.g. to modify SPTEs).
302465e3b446SSean Christopherson  *
302565e3b446SSean Christopherson  * Note!  The lookup can still race with modifications to host page tables, but
302665e3b446SSean Christopherson  * the above "rules" ensure KVM will not _consume_ the result of the walk if a
302765e3b446SSean Christopherson  * race with the primary MMU occurs.
302865e3b446SSean Christopherson  */
3029a8ac499bSSean Christopherson static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
30308ca6f063SBen Gardon 				  const struct kvm_memory_slot *slot)
3031db543216SSean Christopherson {
3032284dc493SSean Christopherson 	int level = PG_LEVEL_4K;
3033db543216SSean Christopherson 	unsigned long hva;
303444187235SMingwei Zhang 	unsigned long flags;
303544187235SMingwei Zhang 	pgd_t pgd;
303644187235SMingwei Zhang 	p4d_t p4d;
303744187235SMingwei Zhang 	pud_t pud;
303844187235SMingwei Zhang 	pmd_t pmd;
3039db543216SSean Christopherson 
30405d49f08cSSean Christopherson 	/*
3041293e306eSSean Christopherson 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3042293e306eSSean Christopherson 	 * is not solely for performance, it's also necessary to avoid the
3043293e306eSSean Christopherson 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
3044293e306eSSean Christopherson 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
3045293e306eSSean Christopherson 	 * page fault steps have already verified the guest isn't writing a
3046293e306eSSean Christopherson 	 * read-only memslot.
3047293e306eSSean Christopherson 	 */
3048db543216SSean Christopherson 	hva = __gfn_to_hva_memslot(slot, gfn);
3049db543216SSean Christopherson 
305044187235SMingwei Zhang 	/*
305165e3b446SSean Christopherson 	 * Disable IRQs to prevent concurrent tear down of host page tables,
305265e3b446SSean Christopherson 	 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
305365e3b446SSean Christopherson 	 * the original page table.
305444187235SMingwei Zhang 	 */
305544187235SMingwei Zhang 	local_irq_save(flags);
3056db543216SSean Christopherson 
305765e3b446SSean Christopherson 	/*
305865e3b446SSean Christopherson 	 * Read each entry once.  As above, a non-leaf entry can be promoted to
305965e3b446SSean Christopherson 	 * a huge page _during_ this walk.  Re-reading the entry could send the
3060e72c7c2bSPeter Xu 	 * walk into the weeks, e.g. p*d_leaf() returns false (sees the old
306165e3b446SSean Christopherson 	 * value) and then p*d_offset() walks into the target huge page instead
306265e3b446SSean Christopherson 	 * of the old page table (sees the new value).
306365e3b446SSean Christopherson 	 */
306444187235SMingwei Zhang 	pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
306544187235SMingwei Zhang 	if (pgd_none(pgd))
306644187235SMingwei Zhang 		goto out;
306744187235SMingwei Zhang 
306844187235SMingwei Zhang 	p4d = READ_ONCE(*p4d_offset(&pgd, hva));
306944187235SMingwei Zhang 	if (p4d_none(p4d) || !p4d_present(p4d))
307044187235SMingwei Zhang 		goto out;
307144187235SMingwei Zhang 
307244187235SMingwei Zhang 	pud = READ_ONCE(*pud_offset(&p4d, hva));
307344187235SMingwei Zhang 	if (pud_none(pud) || !pud_present(pud))
307444187235SMingwei Zhang 		goto out;
307544187235SMingwei Zhang 
30760a845e0fSPeter Xu 	if (pud_leaf(pud)) {
307744187235SMingwei Zhang 		level = PG_LEVEL_1G;
307844187235SMingwei Zhang 		goto out;
307944187235SMingwei Zhang 	}
308044187235SMingwei Zhang 
308144187235SMingwei Zhang 	pmd = READ_ONCE(*pmd_offset(&pud, hva));
308244187235SMingwei Zhang 	if (pmd_none(pmd) || !pmd_present(pmd))
308344187235SMingwei Zhang 		goto out;
308444187235SMingwei Zhang 
30852f709f7bSPeter Xu 	if (pmd_leaf(pmd))
308644187235SMingwei Zhang 		level = PG_LEVEL_2M;
308744187235SMingwei Zhang 
308844187235SMingwei Zhang out:
308944187235SMingwei Zhang 	local_irq_restore(flags);
3090db543216SSean Christopherson 	return level;
3091db543216SSean Christopherson }
3092db543216SSean Christopherson 
30938dd2eee9SChao Peng static int __kvm_mmu_max_mapping_level(struct kvm *kvm,
30948dd2eee9SChao Peng 				       const struct kvm_memory_slot *slot,
30958dd2eee9SChao Peng 				       gfn_t gfn, int max_level, bool is_private)
30961b6d9d9eSSean Christopherson {
30971b6d9d9eSSean Christopherson 	struct kvm_lpage_info *linfo;
3098ec607a56SPaolo Bonzini 	int host_level;
30991b6d9d9eSSean Christopherson 
31001b6d9d9eSSean Christopherson 	max_level = min(max_level, max_huge_page_level);
31011b6d9d9eSSean Christopherson 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
31021b6d9d9eSSean Christopherson 		linfo = lpage_info_slot(gfn, slot, max_level);
31031b6d9d9eSSean Christopherson 		if (!linfo->disallow_lpage)
31041b6d9d9eSSean Christopherson 			break;
31051b6d9d9eSSean Christopherson 	}
31061b6d9d9eSSean Christopherson 
31078dd2eee9SChao Peng 	if (is_private)
31088dd2eee9SChao Peng 		return max_level;
31098dd2eee9SChao Peng 
31101b6d9d9eSSean Christopherson 	if (max_level == PG_LEVEL_4K)
31111b6d9d9eSSean Christopherson 		return PG_LEVEL_4K;
31121b6d9d9eSSean Christopherson 
3113a8ac499bSSean Christopherson 	host_level = host_pfn_mapping_level(kvm, gfn, slot);
3114ec607a56SPaolo Bonzini 	return min(host_level, max_level);
31151b6d9d9eSSean Christopherson }
31161b6d9d9eSSean Christopherson 
31178dd2eee9SChao Peng int kvm_mmu_max_mapping_level(struct kvm *kvm,
31188dd2eee9SChao Peng 			      const struct kvm_memory_slot *slot, gfn_t gfn,
31198dd2eee9SChao Peng 			      int max_level)
31208dd2eee9SChao Peng {
31218dd2eee9SChao Peng 	bool is_private = kvm_slot_can_be_private(slot) &&
31228dd2eee9SChao Peng 			  kvm_mem_is_private(kvm, gfn);
31238dd2eee9SChao Peng 
31248dd2eee9SChao Peng 	return __kvm_mmu_max_mapping_level(kvm, slot, gfn, max_level, is_private);
31258dd2eee9SChao Peng }
31268dd2eee9SChao Peng 
312773a3c659SPaolo Bonzini void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
31280885904dSSean Christopherson {
3129e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
313017eff019SSean Christopherson 	kvm_pfn_t mask;
31310885904dSSean Christopherson 
313273a3c659SPaolo Bonzini 	fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
31333cf06612SSean Christopherson 
313473a3c659SPaolo Bonzini 	if (unlikely(fault->max_level == PG_LEVEL_4K))
313573a3c659SPaolo Bonzini 		return;
313617eff019SSean Christopherson 
31375d49f08cSSean Christopherson 	if (is_error_noslot_pfn(fault->pfn))
313873a3c659SPaolo Bonzini 		return;
313917eff019SSean Christopherson 
3140e710c5f6SDavid Matlack 	if (kvm_slot_dirty_track_enabled(slot))
314173a3c659SPaolo Bonzini 		return;
3142293e306eSSean Christopherson 
31433cf06612SSean Christopherson 	/*
31443cf06612SSean Christopherson 	 * Enforce the iTLB multihit workaround after capturing the requested
31453cf06612SSean Christopherson 	 * level, which will be used to do precise, accurate accounting.
31463cf06612SSean Christopherson 	 */
31478dd2eee9SChao Peng 	fault->req_level = __kvm_mmu_max_mapping_level(vcpu->kvm, slot,
31488dd2eee9SChao Peng 						       fault->gfn, fault->max_level,
31498dd2eee9SChao Peng 						       fault->is_private);
315073a3c659SPaolo Bonzini 	if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
315173a3c659SPaolo Bonzini 		return;
31524cd071d1SSean Christopherson 
31530885904dSSean Christopherson 	/*
315420ec3ebdSChao Peng 	 * mmu_invalidate_retry() was successful and mmu_lock is held, so
31554cd071d1SSean Christopherson 	 * the pmd can't be split from under us.
31560885904dSSean Christopherson 	 */
315773a3c659SPaolo Bonzini 	fault->goal_level = fault->req_level;
315873a3c659SPaolo Bonzini 	mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
315973a3c659SPaolo Bonzini 	VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
316073a3c659SPaolo Bonzini 	fault->pfn &= ~mask;
31610885904dSSean Christopherson }
31620885904dSSean Christopherson 
3163536f0e6aSPaolo Bonzini void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3164c50d8ae3SPaolo Bonzini {
3165536f0e6aSPaolo Bonzini 	if (cur_level > PG_LEVEL_4K &&
3166536f0e6aSPaolo Bonzini 	    cur_level == fault->goal_level &&
3167c50d8ae3SPaolo Bonzini 	    is_shadow_present_pte(spte) &&
316876901e56SMingwei Zhang 	    !is_large_pte(spte) &&
316976901e56SMingwei Zhang 	    spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3170c50d8ae3SPaolo Bonzini 		/*
31716c882ef4SDavid Matlack 		 * A small SPTE exists for this pfn, but FNAME(fetch),
31726c882ef4SDavid Matlack 		 * direct_map(), or kvm_tdp_mmu_map() would like to create a
31736c882ef4SDavid Matlack 		 * large PTE instead: just force them to go down another level,
31746c882ef4SDavid Matlack 		 * patching back for them into pfn the next 9 bits of the
31756c882ef4SDavid Matlack 		 * address.
3176c50d8ae3SPaolo Bonzini 		 */
3177536f0e6aSPaolo Bonzini 		u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3178536f0e6aSPaolo Bonzini 				KVM_PAGES_PER_HPAGE(cur_level - 1);
3179536f0e6aSPaolo Bonzini 		fault->pfn |= fault->gfn & page_mask;
3180536f0e6aSPaolo Bonzini 		fault->goal_level--;
3181c50d8ae3SPaolo Bonzini 	}
3182c50d8ae3SPaolo Bonzini }
3183c50d8ae3SPaolo Bonzini 
31846c882ef4SDavid Matlack static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3185c50d8ae3SPaolo Bonzini {
3186c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator it;
3187c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
318873a3c659SPaolo Bonzini 	int ret;
318943b74355SPaolo Bonzini 	gfn_t base_gfn = fault->gfn;
3190c50d8ae3SPaolo Bonzini 
319173a3c659SPaolo Bonzini 	kvm_mmu_hugepage_adjust(vcpu, fault);
31924cd071d1SSean Christopherson 
3193f0066d94SPaolo Bonzini 	trace_kvm_mmu_spte_requested(fault);
319443b74355SPaolo Bonzini 	for_each_shadow_entry(vcpu, fault->addr, it) {
3195c50d8ae3SPaolo Bonzini 		/*
3196c50d8ae3SPaolo Bonzini 		 * We cannot overwrite existing page tables with an NX
3197c50d8ae3SPaolo Bonzini 		 * large page, as the leaf could be executable.
3198c50d8ae3SPaolo Bonzini 		 */
319973a3c659SPaolo Bonzini 		if (fault->nx_huge_page_workaround_enabled)
3200536f0e6aSPaolo Bonzini 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3201c50d8ae3SPaolo Bonzini 
3202c667a3baSHou Wenlong 		base_gfn = gfn_round_for_level(fault->gfn, it.level);
320373a3c659SPaolo Bonzini 		if (it.level == fault->goal_level)
3204c50d8ae3SPaolo Bonzini 			break;
3205c50d8ae3SPaolo Bonzini 
32062e65e842SDavid Matlack 		sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
32070cd8dc73SPaolo Bonzini 		if (sp == ERR_PTR(-EEXIST))
32080cd8dc73SPaolo Bonzini 			continue;
3209c50d8ae3SPaolo Bonzini 
3210c50d8ae3SPaolo Bonzini 		link_shadow_page(vcpu, it.sptep, sp);
3211b5b0977fSSean Christopherson 		if (fault->huge_page_disallowed)
321255c510e2SSean Christopherson 			account_nx_huge_page(vcpu->kvm, sp,
3213428e9216SSean Christopherson 					     fault->req_level >= it.level);
3214c50d8ae3SPaolo Bonzini 	}
3215c50d8ae3SPaolo Bonzini 
3216b1a429fbSSean Christopherson 	if (WARN_ON_ONCE(it.level != fault->goal_level))
3217b1a429fbSSean Christopherson 		return -EFAULT;
3218b1a429fbSSean Christopherson 
32198a9f566aSDavid Matlack 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3220a12f4381SPaolo Bonzini 			   base_gfn, fault->pfn, fault);
322112703759SSean Christopherson 	if (ret == RET_PF_SPURIOUS)
322212703759SSean Christopherson 		return ret;
322312703759SSean Christopherson 
3224c50d8ae3SPaolo Bonzini 	direct_pte_prefetch(vcpu, it.sptep);
3225c50d8ae3SPaolo Bonzini 	return ret;
3226c50d8ae3SPaolo Bonzini }
3227c50d8ae3SPaolo Bonzini 
3228cd08d178SDavid Matlack static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3229c50d8ae3SPaolo Bonzini {
3230cd08d178SDavid Matlack 	unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3231cd08d178SDavid Matlack 
3232cd08d178SDavid Matlack 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3233c50d8ae3SPaolo Bonzini }
3234c50d8ae3SPaolo Bonzini 
3235cd08d178SDavid Matlack static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3236c50d8ae3SPaolo Bonzini {
3237cd08d178SDavid Matlack 	if (is_sigpending_pfn(fault->pfn)) {
323876657687SPeter Xu 		kvm_handle_signal_exit(vcpu);
323976657687SPeter Xu 		return -EINTR;
324076657687SPeter Xu 	}
324176657687SPeter Xu 
3242c50d8ae3SPaolo Bonzini 	/*
3243c50d8ae3SPaolo Bonzini 	 * Do not cache the mmio info caused by writing the readonly gfn
3244c50d8ae3SPaolo Bonzini 	 * into the spte otherwise read access on readonly gfn also can
3245c50d8ae3SPaolo Bonzini 	 * caused mmio page fault and treat it as mmio access.
3246c50d8ae3SPaolo Bonzini 	 */
3247cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3248c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3249c50d8ae3SPaolo Bonzini 
3250cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3251cd08d178SDavid Matlack 		kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3252c50d8ae3SPaolo Bonzini 		return RET_PF_RETRY;
3253c50d8ae3SPaolo Bonzini 	}
3254c50d8ae3SPaolo Bonzini 
3255c50d8ae3SPaolo Bonzini 	return -EFAULT;
3256c50d8ae3SPaolo Bonzini }
3257c50d8ae3SPaolo Bonzini 
3258354c908cSDavid Matlack static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3259354c908cSDavid Matlack 				   struct kvm_page_fault *fault,
32605276c616SSean Christopherson 				   unsigned int access)
3261c50d8ae3SPaolo Bonzini {
32623a13f4feSPaolo Bonzini 	gva_t gva = fault->is_tdp ? 0 : fault->addr;
32633a13f4feSPaolo Bonzini 
32643a13f4feSPaolo Bonzini 	vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3265c50d8ae3SPaolo Bonzini 			     access & shadow_mmio_access_mask);
3266354c908cSDavid Matlack 
326730ab5901SSean Christopherson 	/*
326830ab5901SSean Christopherson 	 * If MMIO caching is disabled, emulate immediately without
326930ab5901SSean Christopherson 	 * touching the shadow page tables as attempting to install an
3270354c908cSDavid Matlack 	 * MMIO SPTE will just be an expensive nop.
327130ab5901SSean Christopherson 	 */
3272354c908cSDavid Matlack 	if (unlikely(!enable_mmio_caching))
32735276c616SSean Christopherson 		return RET_PF_EMULATE;
3274354c908cSDavid Matlack 
3275354c908cSDavid Matlack 	/*
3276354c908cSDavid Matlack 	 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3277354c908cSDavid Matlack 	 * any guest that generates such gfns is running nested and is being
3278354c908cSDavid Matlack 	 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3279354c908cSDavid Matlack 	 * only if L1's MAXPHYADDR is inaccurate with respect to the
3280354c908cSDavid Matlack 	 * hardware's).
3281354c908cSDavid Matlack 	 */
3282354c908cSDavid Matlack 	if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3283354c908cSDavid Matlack 		return RET_PF_EMULATE;
3284c50d8ae3SPaolo Bonzini 
32855276c616SSean Christopherson 	return RET_PF_CONTINUE;
3286c50d8ae3SPaolo Bonzini }
3287c50d8ae3SPaolo Bonzini 
32883c8ad5a6SPaolo Bonzini static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
3289c50d8ae3SPaolo Bonzini {
3290c50d8ae3SPaolo Bonzini 	/*
32915c64aba5SSean Christopherson 	 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
32925c64aba5SSean Christopherson 	 * reach the common page fault handler if the SPTE has an invalid MMIO
32935c64aba5SSean Christopherson 	 * generation number.  Refreshing the MMIO generation needs to go down
32945c64aba5SSean Christopherson 	 * the slow path.  Note, EPT Misconfigs do NOT set the PRESENT flag!
3295c50d8ae3SPaolo Bonzini 	 */
32963c8ad5a6SPaolo Bonzini 	if (fault->rsvd)
3297c50d8ae3SPaolo Bonzini 		return false;
3298c50d8ae3SPaolo Bonzini 
3299c50d8ae3SPaolo Bonzini 	/*
3300c50d8ae3SPaolo Bonzini 	 * #PF can be fast if:
3301c50d8ae3SPaolo Bonzini 	 *
330254275f74SSean Christopherson 	 * 1. The shadow page table entry is not present and A/D bits are
330354275f74SSean Christopherson 	 *    disabled _by KVM_, which could mean that the fault is potentially
330454275f74SSean Christopherson 	 *    caused by access tracking (if enabled).  If A/D bits are enabled
330554275f74SSean Christopherson 	 *    by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
330654275f74SSean Christopherson 	 *    bits for L2 and employ access tracking, but the fast page fault
330754275f74SSean Christopherson 	 *    mechanism only supports direct MMUs.
330854275f74SSean Christopherson 	 * 2. The shadow page table entry is present, the access is a write,
330954275f74SSean Christopherson 	 *    and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
331054275f74SSean Christopherson 	 *    the fault was caused by a write-protection violation.  If the
331154275f74SSean Christopherson 	 *    SPTE is MMU-writable (determined later), the fault can be fixed
331254275f74SSean Christopherson 	 *    by setting the Writable bit, which can be done out of mmu_lock.
3313c50d8ae3SPaolo Bonzini 	 */
33145c64aba5SSean Christopherson 	if (!fault->present)
33155c64aba5SSean Christopherson 		return !kvm_ad_enabled();
33165c64aba5SSean Christopherson 
33175c64aba5SSean Christopherson 	/*
33185c64aba5SSean Christopherson 	 * Note, instruction fetches and writes are mutually exclusive, ignore
33195c64aba5SSean Christopherson 	 * the "exec" flag.
33205c64aba5SSean Christopherson 	 */
33215c64aba5SSean Christopherson 	return fault->write;
3322c50d8ae3SPaolo Bonzini }
3323c50d8ae3SPaolo Bonzini 
3324c50d8ae3SPaolo Bonzini /*
3325c50d8ae3SPaolo Bonzini  * Returns true if the SPTE was fixed successfully. Otherwise,
3326c50d8ae3SPaolo Bonzini  * someone else modified the SPTE from its original value.
3327c50d8ae3SPaolo Bonzini  */
3328f3d90f90SSean Christopherson static bool fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu,
3329f3d90f90SSean Christopherson 				    struct kvm_page_fault *fault,
3330c50d8ae3SPaolo Bonzini 				    u64 *sptep, u64 old_spte, u64 new_spte)
3331c50d8ae3SPaolo Bonzini {
3332c50d8ae3SPaolo Bonzini 	/*
3333c50d8ae3SPaolo Bonzini 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3334c50d8ae3SPaolo Bonzini 	 * order to eliminate unnecessary PML logging. See comments in
3335c50d8ae3SPaolo Bonzini 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3336c50d8ae3SPaolo Bonzini 	 * enabled, so we do not do this. This might result in the same GPA
3337c50d8ae3SPaolo Bonzini 	 * to be logged in PML buffer again when the write really happens, and
3338c50d8ae3SPaolo Bonzini 	 * eventually to be called by mark_page_dirty twice. But it's also no
3339c50d8ae3SPaolo Bonzini 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3340c50d8ae3SPaolo Bonzini 	 * so non-PML cases won't be impacted.
3341c50d8ae3SPaolo Bonzini 	 *
3342c50d8ae3SPaolo Bonzini 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3343c50d8ae3SPaolo Bonzini 	 */
33442db2f46fSUros Bizjak 	if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3345c50d8ae3SPaolo Bonzini 		return false;
3346c50d8ae3SPaolo Bonzini 
3347e710c5f6SDavid Matlack 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3348e710c5f6SDavid Matlack 		mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3349c50d8ae3SPaolo Bonzini 
3350c50d8ae3SPaolo Bonzini 	return true;
3351c50d8ae3SPaolo Bonzini }
3352c50d8ae3SPaolo Bonzini 
33533c8ad5a6SPaolo Bonzini static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3354c50d8ae3SPaolo Bonzini {
33553c8ad5a6SPaolo Bonzini 	if (fault->exec)
3356c50d8ae3SPaolo Bonzini 		return is_executable_pte(spte);
3357c50d8ae3SPaolo Bonzini 
33583c8ad5a6SPaolo Bonzini 	if (fault->write)
3359c50d8ae3SPaolo Bonzini 		return is_writable_pte(spte);
3360c50d8ae3SPaolo Bonzini 
3361c50d8ae3SPaolo Bonzini 	/* Fault was on Read access */
3362c50d8ae3SPaolo Bonzini 	return spte & PT_PRESENT_MASK;
3363c50d8ae3SPaolo Bonzini }
3364c50d8ae3SPaolo Bonzini 
3365c50d8ae3SPaolo Bonzini /*
33666e8eb206SDavid Matlack  * Returns the last level spte pointer of the shadow page walk for the given
33676e8eb206SDavid Matlack  * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
33686e8eb206SDavid Matlack  * walk could be performed, returns NULL and *spte does not contain valid data.
33696e8eb206SDavid Matlack  *
33706e8eb206SDavid Matlack  * Contract:
33716e8eb206SDavid Matlack  *  - Must be called between walk_shadow_page_lockless_{begin,end}.
33726e8eb206SDavid Matlack  *  - The returned sptep must not be used after walk_shadow_page_lockless_end.
33736e8eb206SDavid Matlack  */
33746e8eb206SDavid Matlack static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
33756e8eb206SDavid Matlack {
33766e8eb206SDavid Matlack 	struct kvm_shadow_walk_iterator iterator;
33776e8eb206SDavid Matlack 	u64 old_spte;
33786e8eb206SDavid Matlack 	u64 *sptep = NULL;
33796e8eb206SDavid Matlack 
33806e8eb206SDavid Matlack 	for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
33816e8eb206SDavid Matlack 		sptep = iterator.sptep;
33826e8eb206SDavid Matlack 		*spte = old_spte;
33836e8eb206SDavid Matlack 	}
33846e8eb206SDavid Matlack 
33856e8eb206SDavid Matlack 	return sptep;
33866e8eb206SDavid Matlack }
33876e8eb206SDavid Matlack 
33886e8eb206SDavid Matlack /*
3389c4371c2aSSean Christopherson  * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3390c50d8ae3SPaolo Bonzini  */
33913c8ad5a6SPaolo Bonzini static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3392c50d8ae3SPaolo Bonzini {
3393c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3394c4371c2aSSean Christopherson 	int ret = RET_PF_INVALID;
33951de9992fSLi zeming 	u64 spte;
33961de9992fSLi zeming 	u64 *sptep;
3397c50d8ae3SPaolo Bonzini 	uint retry_count = 0;
3398c50d8ae3SPaolo Bonzini 
33993c8ad5a6SPaolo Bonzini 	if (!page_fault_can_be_fast(fault))
3400c4371c2aSSean Christopherson 		return ret;
3401c50d8ae3SPaolo Bonzini 
3402c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
3403c50d8ae3SPaolo Bonzini 
3404c50d8ae3SPaolo Bonzini 	do {
3405c50d8ae3SPaolo Bonzini 		u64 new_spte;
3406c50d8ae3SPaolo Bonzini 
3407dfe0ecc6SSean Christopherson 		if (tdp_mmu_enabled)
34083c8ad5a6SPaolo Bonzini 			sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
34096e8eb206SDavid Matlack 		else
34103c8ad5a6SPaolo Bonzini 			sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3411c50d8ae3SPaolo Bonzini 
34121de9992fSLi zeming 		/*
34131de9992fSLi zeming 		 * It's entirely possible for the mapping to have been zapped
34141de9992fSLi zeming 		 * by a different task, but the root page should always be
34151de9992fSLi zeming 		 * available as the vCPU holds a reference to its root(s).
34161de9992fSLi zeming 		 */
34171de9992fSLi zeming 		if (WARN_ON_ONCE(!sptep))
34181de9992fSLi zeming 			spte = REMOVED_SPTE;
34191de9992fSLi zeming 
3420ec89e643SSean Christopherson 		if (!is_shadow_present_pte(spte))
3421ec89e643SSean Christopherson 			break;
3422ec89e643SSean Christopherson 
34236e8eb206SDavid Matlack 		sp = sptep_to_sp(sptep);
3424c50d8ae3SPaolo Bonzini 		if (!is_last_spte(spte, sp->role.level))
3425c50d8ae3SPaolo Bonzini 			break;
3426c50d8ae3SPaolo Bonzini 
3427c50d8ae3SPaolo Bonzini 		/*
3428c50d8ae3SPaolo Bonzini 		 * Check whether the memory access that caused the fault would
3429c50d8ae3SPaolo Bonzini 		 * still cause it if it were to be performed right now. If not,
3430c50d8ae3SPaolo Bonzini 		 * then this is a spurious fault caused by TLB lazily flushed,
3431c50d8ae3SPaolo Bonzini 		 * or some other CPU has already fixed the PTE after the
3432c50d8ae3SPaolo Bonzini 		 * current CPU took the fault.
3433c50d8ae3SPaolo Bonzini 		 *
3434c50d8ae3SPaolo Bonzini 		 * Need not check the access of upper level table entries since
3435c50d8ae3SPaolo Bonzini 		 * they are always ACC_ALL.
3436c50d8ae3SPaolo Bonzini 		 */
34373c8ad5a6SPaolo Bonzini 		if (is_access_allowed(fault, spte)) {
3438c4371c2aSSean Christopherson 			ret = RET_PF_SPURIOUS;
3439c50d8ae3SPaolo Bonzini 			break;
3440c50d8ae3SPaolo Bonzini 		}
3441c50d8ae3SPaolo Bonzini 
3442c50d8ae3SPaolo Bonzini 		new_spte = spte;
3443c50d8ae3SPaolo Bonzini 
344454275f74SSean Christopherson 		/*
344554275f74SSean Christopherson 		 * KVM only supports fixing page faults outside of MMU lock for
344654275f74SSean Christopherson 		 * direct MMUs, nested MMUs are always indirect, and KVM always
344754275f74SSean Christopherson 		 * uses A/D bits for non-nested MMUs.  Thus, if A/D bits are
344854275f74SSean Christopherson 		 * enabled, the SPTE can't be an access-tracked SPTE.
344954275f74SSean Christopherson 		 */
345054275f74SSean Christopherson 		if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3451c50d8ae3SPaolo Bonzini 			new_spte = restore_acc_track_spte(new_spte);
3452c50d8ae3SPaolo Bonzini 
3453c50d8ae3SPaolo Bonzini 		/*
345454275f74SSean Christopherson 		 * To keep things simple, only SPTEs that are MMU-writable can
345554275f74SSean Christopherson 		 * be made fully writable outside of mmu_lock, e.g. only SPTEs
345654275f74SSean Christopherson 		 * that were write-protected for dirty-logging or access
345754275f74SSean Christopherson 		 * tracking are handled here.  Don't bother checking if the
345854275f74SSean Christopherson 		 * SPTE is writable to prioritize running with A/D bits enabled.
345954275f74SSean Christopherson 		 * The is_access_allowed() check above handles the common case
346054275f74SSean Christopherson 		 * of the fault being spurious, and the SPTE is known to be
346154275f74SSean Christopherson 		 * shadow-present, i.e. except for access tracking restoration
346254275f74SSean Christopherson 		 * making the new SPTE writable, the check is wasteful.
3463c50d8ae3SPaolo Bonzini 		 */
3464706c9c55SSean Christopherson 		if (fault->write && is_mmu_writable_spte(spte)) {
3465c50d8ae3SPaolo Bonzini 			new_spte |= PT_WRITABLE_MASK;
3466c50d8ae3SPaolo Bonzini 
3467c50d8ae3SPaolo Bonzini 			/*
346810c30de0SJunaid Shahid 			 * Do not fix write-permission on the large spte when
346910c30de0SJunaid Shahid 			 * dirty logging is enabled. Since we only dirty the
347010c30de0SJunaid Shahid 			 * first page into the dirty-bitmap in
3471c50d8ae3SPaolo Bonzini 			 * fast_pf_fix_direct_spte(), other pages are missed
3472c50d8ae3SPaolo Bonzini 			 * if its slot has dirty logging enabled.
3473c50d8ae3SPaolo Bonzini 			 *
3474c50d8ae3SPaolo Bonzini 			 * Instead, we let the slow page fault path create a
3475c50d8ae3SPaolo Bonzini 			 * normal spte to fix the access.
3476c50d8ae3SPaolo Bonzini 			 */
347710c30de0SJunaid Shahid 			if (sp->role.level > PG_LEVEL_4K &&
347810c30de0SJunaid Shahid 			    kvm_slot_dirty_track_enabled(fault->slot))
3479c50d8ae3SPaolo Bonzini 				break;
3480c50d8ae3SPaolo Bonzini 		}
3481c50d8ae3SPaolo Bonzini 
3482c50d8ae3SPaolo Bonzini 		/* Verify that the fault can be handled in the fast path */
3483c50d8ae3SPaolo Bonzini 		if (new_spte == spte ||
34843c8ad5a6SPaolo Bonzini 		    !is_access_allowed(fault, new_spte))
3485c50d8ae3SPaolo Bonzini 			break;
3486c50d8ae3SPaolo Bonzini 
3487c50d8ae3SPaolo Bonzini 		/*
3488c50d8ae3SPaolo Bonzini 		 * Currently, fast page fault only works for direct mapping
3489c50d8ae3SPaolo Bonzini 		 * since the gfn is not stable for indirect shadow page. See
34903ecad8c2SMauro Carvalho Chehab 		 * Documentation/virt/kvm/locking.rst to get more detail.
3491c50d8ae3SPaolo Bonzini 		 */
3492e710c5f6SDavid Matlack 		if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3493c4371c2aSSean Christopherson 			ret = RET_PF_FIXED;
3494c50d8ae3SPaolo Bonzini 			break;
3495c4371c2aSSean Christopherson 		}
3496c50d8ae3SPaolo Bonzini 
3497c50d8ae3SPaolo Bonzini 		if (++retry_count > 4) {
34988d20bd63SSean Christopherson 			pr_warn_once("Fast #PF retrying more than 4 times.\n");
3499c50d8ae3SPaolo Bonzini 			break;
3500c50d8ae3SPaolo Bonzini 		}
3501c50d8ae3SPaolo Bonzini 
3502c50d8ae3SPaolo Bonzini 	} while (true);
3503c50d8ae3SPaolo Bonzini 
3504f0066d94SPaolo Bonzini 	trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3505c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3506c50d8ae3SPaolo Bonzini 
35071075d41eSSean Christopherson 	if (ret != RET_PF_INVALID)
35081075d41eSSean Christopherson 		vcpu->stat.pf_fast++;
35091075d41eSSean Christopherson 
3510c4371c2aSSean Christopherson 	return ret;
3511c50d8ae3SPaolo Bonzini }
3512c50d8ae3SPaolo Bonzini 
3513c50d8ae3SPaolo Bonzini static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3514c50d8ae3SPaolo Bonzini 			       struct list_head *invalid_list)
3515c50d8ae3SPaolo Bonzini {
3516c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3517c50d8ae3SPaolo Bonzini 
3518c50d8ae3SPaolo Bonzini 	if (!VALID_PAGE(*root_hpa))
3519c50d8ae3SPaolo Bonzini 		return;
3520c50d8ae3SPaolo Bonzini 
3521c5f2d564SSean Christopherson 	sp = root_to_sp(*root_hpa);
352220ba462dSSean Christopherson 	if (WARN_ON_ONCE(!sp))
35239191b8f0SPaolo Bonzini 		return;
352402c00b3aSBen Gardon 
3525576a15deSSean Christopherson 	if (is_tdp_mmu_page(sp)) {
3526576a15deSSean Christopherson 		lockdep_assert_held_read(&kvm->mmu_lock);
35275f3c8c91SPaolo Bonzini 		kvm_tdp_mmu_put_root(kvm, sp);
3528576a15deSSean Christopherson 	} else {
3529576a15deSSean Christopherson 		lockdep_assert_held_write(&kvm->mmu_lock);
3530576a15deSSean Christopherson 		if (!--sp->root_count && sp->role.invalid)
3531c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3532576a15deSSean Christopherson 	}
3533c50d8ae3SPaolo Bonzini 
3534c50d8ae3SPaolo Bonzini 	*root_hpa = INVALID_PAGE;
3535c50d8ae3SPaolo Bonzini }
3536c50d8ae3SPaolo Bonzini 
3537c50d8ae3SPaolo Bonzini /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
35380c1c92f1SPaolo Bonzini void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3539c50d8ae3SPaolo Bonzini 			ulong roots_to_free)
3540c50d8ae3SPaolo Bonzini {
3541576a15deSSean Christopherson 	bool is_tdp_mmu = tdp_mmu_enabled && mmu->root_role.direct;
3542c50d8ae3SPaolo Bonzini 	int i;
3543c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
3544594bef79SPaolo Bonzini 	bool free_active_root;
3545c50d8ae3SPaolo Bonzini 
3546f94db0c8SSean Christopherson 	WARN_ON_ONCE(roots_to_free & ~KVM_MMU_ROOTS_ALL);
3547f94db0c8SSean Christopherson 
3548c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3549c50d8ae3SPaolo Bonzini 
3550c50d8ae3SPaolo Bonzini 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3551594bef79SPaolo Bonzini 	free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3552594bef79SPaolo Bonzini 		&& VALID_PAGE(mmu->root.hpa);
3553594bef79SPaolo Bonzini 
3554594bef79SPaolo Bonzini 	if (!free_active_root) {
3555c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3556c50d8ae3SPaolo Bonzini 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3557c50d8ae3SPaolo Bonzini 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3558c50d8ae3SPaolo Bonzini 				break;
3559c50d8ae3SPaolo Bonzini 
3560c50d8ae3SPaolo Bonzini 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3561c50d8ae3SPaolo Bonzini 			return;
3562c50d8ae3SPaolo Bonzini 	}
3563c50d8ae3SPaolo Bonzini 
3564576a15deSSean Christopherson 	if (is_tdp_mmu)
3565576a15deSSean Christopherson 		read_lock(&kvm->mmu_lock);
3566576a15deSSean Christopherson 	else
3567531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
3568c50d8ae3SPaolo Bonzini 
3569c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3570c50d8ae3SPaolo Bonzini 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
35714d710de9SSean Christopherson 			mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3572c50d8ae3SPaolo Bonzini 					   &invalid_list);
3573c50d8ae3SPaolo Bonzini 
3574c50d8ae3SPaolo Bonzini 	if (free_active_root) {
35750e3223d8SSean Christopherson 		if (kvm_mmu_is_dummy_root(mmu->root.hpa)) {
35760e3223d8SSean Christopherson 			/* Nothing to cleanup for dummy roots. */
35770e3223d8SSean Christopherson 		} else if (root_to_sp(mmu->root.hpa)) {
3578b9e5603cSPaolo Bonzini 			mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
357904d45551SSean Christopherson 		} else if (mmu->pae_root) {
3580c834e5e4SSean Christopherson 			for (i = 0; i < 4; ++i) {
3581c834e5e4SSean Christopherson 				if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3582c834e5e4SSean Christopherson 					continue;
3583c834e5e4SSean Christopherson 
3584c834e5e4SSean Christopherson 				mmu_free_root_page(kvm, &mmu->pae_root[i],
3585c50d8ae3SPaolo Bonzini 						   &invalid_list);
3586c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3587c50d8ae3SPaolo Bonzini 			}
3588c50d8ae3SPaolo Bonzini 		}
3589b9e5603cSPaolo Bonzini 		mmu->root.hpa = INVALID_PAGE;
3590b9e5603cSPaolo Bonzini 		mmu->root.pgd = 0;
3591c50d8ae3SPaolo Bonzini 	}
3592c50d8ae3SPaolo Bonzini 
3593576a15deSSean Christopherson 	if (is_tdp_mmu) {
3594576a15deSSean Christopherson 		read_unlock(&kvm->mmu_lock);
3595576a15deSSean Christopherson 		WARN_ON_ONCE(!list_empty(&invalid_list));
3596576a15deSSean Christopherson 	} else {
35974d710de9SSean Christopherson 		kvm_mmu_commit_zap_page(kvm, &invalid_list);
3598531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
3599c50d8ae3SPaolo Bonzini 	}
3600576a15deSSean Christopherson }
3601c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3602c50d8ae3SPaolo Bonzini 
36030c1c92f1SPaolo Bonzini void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
360425b62c62SSean Christopherson {
360525b62c62SSean Christopherson 	unsigned long roots_to_free = 0;
3606c5f2d564SSean Christopherson 	struct kvm_mmu_page *sp;
360725b62c62SSean Christopherson 	hpa_t root_hpa;
360825b62c62SSean Christopherson 	int i;
360925b62c62SSean Christopherson 
361025b62c62SSean Christopherson 	/*
361125b62c62SSean Christopherson 	 * This should not be called while L2 is active, L2 can't invalidate
361225b62c62SSean Christopherson 	 * _only_ its own roots, e.g. INVVPID unconditionally exits.
361325b62c62SSean Christopherson 	 */
36147a458f0eSPaolo Bonzini 	WARN_ON_ONCE(mmu->root_role.guest_mode);
361525b62c62SSean Christopherson 
361625b62c62SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
361725b62c62SSean Christopherson 		root_hpa = mmu->prev_roots[i].hpa;
361825b62c62SSean Christopherson 		if (!VALID_PAGE(root_hpa))
361925b62c62SSean Christopherson 			continue;
362025b62c62SSean Christopherson 
3621c5f2d564SSean Christopherson 		sp = root_to_sp(root_hpa);
3622c5f2d564SSean Christopherson 		if (!sp || sp->role.guest_mode)
362325b62c62SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
362425b62c62SSean Christopherson 	}
362525b62c62SSean Christopherson 
36260c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, roots_to_free);
362725b62c62SSean Christopherson }
362825b62c62SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
362925b62c62SSean Christopherson 
36302e65e842SDavid Matlack static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
363186938ab6SDavid Matlack 			    u8 level)
3632c50d8ae3SPaolo Bonzini {
36332e65e842SDavid Matlack 	union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3634c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
36358123f265SSean Christopherson 
36362e65e842SDavid Matlack 	role.level = level;
36372e65e842SDavid Matlack 	role.quadrant = quadrant;
36382e65e842SDavid Matlack 
36397f497775SDavid Matlack 	WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
36407f497775SDavid Matlack 	WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
36417f497775SDavid Matlack 
364287654643SDavid Matlack 	sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
36438123f265SSean Christopherson 	++sp->root_count;
36448123f265SSean Christopherson 
36458123f265SSean Christopherson 	return __pa(sp->spt);
36468123f265SSean Christopherson }
36478123f265SSean Christopherson 
36488123f265SSean Christopherson static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
36498123f265SSean Christopherson {
3650b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3651a972e29cSPaolo Bonzini 	u8 shadow_root_level = mmu->root_role.level;
36528123f265SSean Christopherson 	hpa_t root;
3653c50d8ae3SPaolo Bonzini 	unsigned i;
36544a38162eSPaolo Bonzini 	int r;
36554a38162eSPaolo Bonzini 
3656f5238c2aSSean Christopherson 	if (tdp_mmu_enabled)
3657f5238c2aSSean Christopherson 		return kvm_tdp_mmu_alloc_root(vcpu);
3658f5238c2aSSean Christopherson 
36594a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
36604a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
36614a38162eSPaolo Bonzini 	if (r < 0)
36624a38162eSPaolo Bonzini 		goto out_unlock;
3663c50d8ae3SPaolo Bonzini 
3664f5238c2aSSean Christopherson 	if (shadow_root_level >= PT64_ROOT_4LEVEL) {
366586938ab6SDavid Matlack 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3666b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
36678123f265SSean Christopherson 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
36684a38162eSPaolo Bonzini 		if (WARN_ON_ONCE(!mmu->pae_root)) {
36694a38162eSPaolo Bonzini 			r = -EIO;
36704a38162eSPaolo Bonzini 			goto out_unlock;
36714a38162eSPaolo Bonzini 		}
367273ad1606SSean Christopherson 
3673c50d8ae3SPaolo Bonzini 		for (i = 0; i < 4; ++i) {
3674c834e5e4SSean Christopherson 			WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3675c50d8ae3SPaolo Bonzini 
36767f497775SDavid Matlack 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
36772e65e842SDavid Matlack 					      PT32_ROOT_LEVEL);
367817e368d9SSean Christopherson 			mmu->pae_root[i] = root | PT_PRESENT_MASK |
3679d2263de1SYuan Yao 					   shadow_me_value;
3680c50d8ae3SPaolo Bonzini 		}
3681b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
368273ad1606SSean Christopherson 	} else {
368373ad1606SSean Christopherson 		WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
36844a38162eSPaolo Bonzini 		r = -EIO;
36854a38162eSPaolo Bonzini 		goto out_unlock;
368673ad1606SSean Christopherson 	}
36873651c7fcSSean Christopherson 
3688b9e5603cSPaolo Bonzini 	/* root.pgd is ignored for direct MMUs. */
3689b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
36904a38162eSPaolo Bonzini out_unlock:
36914a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
36924a38162eSPaolo Bonzini 	return r;
3693c50d8ae3SPaolo Bonzini }
3694c50d8ae3SPaolo Bonzini 
36951e76a3ceSDavid Stevens static int mmu_first_shadow_root_alloc(struct kvm *kvm)
36961e76a3ceSDavid Stevens {
36971e76a3ceSDavid Stevens 	struct kvm_memslots *slots;
36981e76a3ceSDavid Stevens 	struct kvm_memory_slot *slot;
3699a54d8066SMaciej S. Szmigiero 	int r = 0, i, bkt;
37001e76a3ceSDavid Stevens 
37011e76a3ceSDavid Stevens 	/*
37021e76a3ceSDavid Stevens 	 * Check if this is the first shadow root being allocated before
37031e76a3ceSDavid Stevens 	 * taking the lock.
37041e76a3ceSDavid Stevens 	 */
37051e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
37061e76a3ceSDavid Stevens 		return 0;
37071e76a3ceSDavid Stevens 
37081e76a3ceSDavid Stevens 	mutex_lock(&kvm->slots_arch_lock);
37091e76a3ceSDavid Stevens 
37101e76a3ceSDavid Stevens 	/* Recheck, under the lock, whether this is the first shadow root. */
37111e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
37121e76a3ceSDavid Stevens 		goto out_unlock;
37131e76a3ceSDavid Stevens 
37141e76a3ceSDavid Stevens 	/*
37151e76a3ceSDavid Stevens 	 * Check if anything actually needs to be allocated, e.g. all metadata
37161e76a3ceSDavid Stevens 	 * will be allocated upfront if TDP is disabled.
37171e76a3ceSDavid Stevens 	 */
37181e76a3ceSDavid Stevens 	if (kvm_memslots_have_rmaps(kvm) &&
37191e76a3ceSDavid Stevens 	    kvm_page_track_write_tracking_enabled(kvm))
37201e76a3ceSDavid Stevens 		goto out_success;
37211e76a3ceSDavid Stevens 
3722eed52e43SSean Christopherson 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
37231e76a3ceSDavid Stevens 		slots = __kvm_memslots(kvm, i);
3724a54d8066SMaciej S. Szmigiero 		kvm_for_each_memslot(slot, bkt, slots) {
37251e76a3ceSDavid Stevens 			/*
37261e76a3ceSDavid Stevens 			 * Both of these functions are no-ops if the target is
37271e76a3ceSDavid Stevens 			 * already allocated, so unconditionally calling both
37281e76a3ceSDavid Stevens 			 * is safe.  Intentionally do NOT free allocations on
37291e76a3ceSDavid Stevens 			 * failure to avoid having to track which allocations
37301e76a3ceSDavid Stevens 			 * were made now versus when the memslot was created.
37311e76a3ceSDavid Stevens 			 * The metadata is guaranteed to be freed when the slot
37321e76a3ceSDavid Stevens 			 * is freed, and will be kept/used if userspace retries
37331e76a3ceSDavid Stevens 			 * KVM_RUN instead of killing the VM.
37341e76a3ceSDavid Stevens 			 */
37351e76a3ceSDavid Stevens 			r = memslot_rmap_alloc(slot, slot->npages);
37361e76a3ceSDavid Stevens 			if (r)
37371e76a3ceSDavid Stevens 				goto out_unlock;
37381e76a3ceSDavid Stevens 			r = kvm_page_track_write_tracking_alloc(slot);
37391e76a3ceSDavid Stevens 			if (r)
37401e76a3ceSDavid Stevens 				goto out_unlock;
37411e76a3ceSDavid Stevens 		}
37421e76a3ceSDavid Stevens 	}
37431e76a3ceSDavid Stevens 
37441e76a3ceSDavid Stevens 	/*
37451e76a3ceSDavid Stevens 	 * Ensure that shadow_root_allocated becomes true strictly after
37461e76a3ceSDavid Stevens 	 * all the related pointers are set.
37471e76a3ceSDavid Stevens 	 */
37481e76a3ceSDavid Stevens out_success:
37491e76a3ceSDavid Stevens 	smp_store_release(&kvm->arch.shadow_root_allocated, true);
37501e76a3ceSDavid Stevens 
37511e76a3ceSDavid Stevens out_unlock:
37521e76a3ceSDavid Stevens 	mutex_unlock(&kvm->slots_arch_lock);
37531e76a3ceSDavid Stevens 	return r;
37541e76a3ceSDavid Stevens }
37551e76a3ceSDavid Stevens 
3756c50d8ae3SPaolo Bonzini static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3757c50d8ae3SPaolo Bonzini {
3758b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
37596e0918aeSSean Christopherson 	u64 pdptrs[4], pm_mask;
3760be01e8e2SSean Christopherson 	gfn_t root_gfn, root_pgd;
37617f497775SDavid Matlack 	int quadrant, i, r;
37628123f265SSean Christopherson 	hpa_t root;
3763c50d8ae3SPaolo Bonzini 
37642fdcc1b3SPaolo Bonzini 	root_pgd = kvm_mmu_get_guest_pgd(vcpu, mmu);
3765a130066fSBinbin Wu 	root_gfn = (root_pgd & __PT_BASE_ADDR_MASK) >> PAGE_SHIFT;
3766c50d8ae3SPaolo Bonzini 
37670e3223d8SSean Christopherson 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
37680e3223d8SSean Christopherson 		mmu->root.hpa = kvm_mmu_get_dummy_root();
37690e3223d8SSean Christopherson 		return 0;
37700e3223d8SSean Christopherson 	}
3771c50d8ae3SPaolo Bonzini 
3772c50d8ae3SPaolo Bonzini 	/*
37734a38162eSPaolo Bonzini 	 * On SVM, reading PDPTRs might access guest memory, which might fault
37744a38162eSPaolo Bonzini 	 * and thus might sleep.  Grab the PDPTRs before acquiring mmu_lock.
37754a38162eSPaolo Bonzini 	 */
37764d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
37776e0918aeSSean Christopherson 		for (i = 0; i < 4; ++i) {
37786e0918aeSSean Christopherson 			pdptrs[i] = mmu->get_pdptr(vcpu, i);
37796e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK))
37806e0918aeSSean Christopherson 				continue;
37816e0918aeSSean Christopherson 
37820e3223d8SSean Christopherson 			if (!kvm_vcpu_is_visible_gfn(vcpu, pdptrs[i] >> PAGE_SHIFT))
37830e3223d8SSean Christopherson 				pdptrs[i] = 0;
37846e0918aeSSean Christopherson 		}
37856e0918aeSSean Christopherson 	}
37866e0918aeSSean Christopherson 
37871e76a3ceSDavid Stevens 	r = mmu_first_shadow_root_alloc(vcpu->kvm);
3788d501f747SBen Gardon 	if (r)
3789d501f747SBen Gardon 		return r;
3790d501f747SBen Gardon 
37914a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
37924a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
37934a38162eSPaolo Bonzini 	if (r < 0)
37944a38162eSPaolo Bonzini 		goto out_unlock;
37954a38162eSPaolo Bonzini 
3796c50d8ae3SPaolo Bonzini 	/*
3797c50d8ae3SPaolo Bonzini 	 * Do we shadow a long mode page table? If so we need to
3798c50d8ae3SPaolo Bonzini 	 * write-protect the guests page table root.
3799c50d8ae3SPaolo Bonzini 	 */
38004d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
38018123f265SSean Christopherson 		root = mmu_alloc_root(vcpu, root_gfn, 0,
380286938ab6SDavid Matlack 				      mmu->root_role.level);
3803b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
3804be01e8e2SSean Christopherson 		goto set_root_pgd;
3805c50d8ae3SPaolo Bonzini 	}
3806c50d8ae3SPaolo Bonzini 
38074a38162eSPaolo Bonzini 	if (WARN_ON_ONCE(!mmu->pae_root)) {
38084a38162eSPaolo Bonzini 		r = -EIO;
38094a38162eSPaolo Bonzini 		goto out_unlock;
38104a38162eSPaolo Bonzini 	}
381173ad1606SSean Christopherson 
3812c50d8ae3SPaolo Bonzini 	/*
3813c50d8ae3SPaolo Bonzini 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3814c50d8ae3SPaolo Bonzini 	 * or a PAE 3-level page table. In either case we need to be aware that
3815c50d8ae3SPaolo Bonzini 	 * the shadow page table may be a PAE or a long mode page table.
3816c50d8ae3SPaolo Bonzini 	 */
3817e54f1ff2SKai Huang 	pm_mask = PT_PRESENT_MASK | shadow_me_value;
3818a972e29cSPaolo Bonzini 	if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3819c50d8ae3SPaolo Bonzini 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3820c50d8ae3SPaolo Bonzini 
382103ca4589SSean Christopherson 		if (WARN_ON_ONCE(!mmu->pml4_root)) {
38224a38162eSPaolo Bonzini 			r = -EIO;
38234a38162eSPaolo Bonzini 			goto out_unlock;
38244a38162eSPaolo Bonzini 		}
382503ca4589SSean Christopherson 		mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3826cb0f722aSWei Huang 
3827a972e29cSPaolo Bonzini 		if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3828cb0f722aSWei Huang 			if (WARN_ON_ONCE(!mmu->pml5_root)) {
3829cb0f722aSWei Huang 				r = -EIO;
3830cb0f722aSWei Huang 				goto out_unlock;
3831cb0f722aSWei Huang 			}
3832cb0f722aSWei Huang 			mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3833cb0f722aSWei Huang 		}
383404d45551SSean Christopherson 	}
383504d45551SSean Christopherson 
3836c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3837c834e5e4SSean Christopherson 		WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
38386e6ec584SSean Christopherson 
38394d25502aSPaolo Bonzini 		if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
38406e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3841c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3842c50d8ae3SPaolo Bonzini 				continue;
3843c50d8ae3SPaolo Bonzini 			}
38446e0918aeSSean Christopherson 			root_gfn = pdptrs[i] >> PAGE_SHIFT;
3845c50d8ae3SPaolo Bonzini 		}
3846c50d8ae3SPaolo Bonzini 
38477f497775SDavid Matlack 		/*
38487f497775SDavid Matlack 		 * If shadowing 32-bit non-PAE page tables, each PAE page
38497f497775SDavid Matlack 		 * directory maps one quarter of the guest's non-PAE page
38507f497775SDavid Matlack 		 * directory. Othwerise each PAE page direct shadows one guest
38517f497775SDavid Matlack 		 * PAE page directory so that quadrant should be 0.
38527f497775SDavid Matlack 		 */
38537f497775SDavid Matlack 		quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
38547f497775SDavid Matlack 
38557f497775SDavid Matlack 		root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3856b37233c9SSean Christopherson 		mmu->pae_root[i] = root | pm_mask;
3857c50d8ae3SPaolo Bonzini 	}
3858c50d8ae3SPaolo Bonzini 
3859a972e29cSPaolo Bonzini 	if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3860b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml5_root);
3861a972e29cSPaolo Bonzini 	else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3862b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml4_root);
3863ba0a194fSSean Christopherson 	else
3864b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
3865c50d8ae3SPaolo Bonzini 
3866be01e8e2SSean Christopherson set_root_pgd:
3867b9e5603cSPaolo Bonzini 	mmu->root.pgd = root_pgd;
38684a38162eSPaolo Bonzini out_unlock:
38694a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
3870c50d8ae3SPaolo Bonzini 
3871c6c937d6SLike Xu 	return r;
3872c50d8ae3SPaolo Bonzini }
3873c50d8ae3SPaolo Bonzini 
3874748e52b9SSean Christopherson static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3875c50d8ae3SPaolo Bonzini {
3876748e52b9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3877a972e29cSPaolo Bonzini 	bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3878cb0f722aSWei Huang 	u64 *pml5_root = NULL;
3879cb0f722aSWei Huang 	u64 *pml4_root = NULL;
3880cb0f722aSWei Huang 	u64 *pae_root;
3881748e52b9SSean Christopherson 
3882748e52b9SSean Christopherson 	/*
3883748e52b9SSean Christopherson 	 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3884748e52b9SSean Christopherson 	 * tables are allocated and initialized at root creation as there is no
3885748e52b9SSean Christopherson 	 * equivalent level in the guest's NPT to shadow.  Allocate the tables
3886748e52b9SSean Christopherson 	 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3887748e52b9SSean Christopherson 	 */
3888347a0d0dSPaolo Bonzini 	if (mmu->root_role.direct ||
3889347a0d0dSPaolo Bonzini 	    mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3890a972e29cSPaolo Bonzini 	    mmu->root_role.level < PT64_ROOT_4LEVEL)
3891748e52b9SSean Christopherson 		return 0;
3892748e52b9SSean Christopherson 
3893a717a780SSean Christopherson 	/*
3894a717a780SSean Christopherson 	 * NPT, the only paging mode that uses this horror, uses a fixed number
3895a717a780SSean Christopherson 	 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3896a717a780SSean Christopherson 	 * all MMus are 5-level.  Thus, this can safely require that pml5_root
3897a717a780SSean Christopherson 	 * is allocated if the other roots are valid and pml5 is needed, as any
3898a717a780SSean Christopherson 	 * prior MMU would also have required pml5.
3899a717a780SSean Christopherson 	 */
3900a717a780SSean Christopherson 	if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3901748e52b9SSean Christopherson 		return 0;
3902748e52b9SSean Christopherson 
3903748e52b9SSean Christopherson 	/*
3904748e52b9SSean Christopherson 	 * The special roots should always be allocated in concert.  Yell and
3905748e52b9SSean Christopherson 	 * bail if KVM ends up in a state where only one of the roots is valid.
3906748e52b9SSean Christopherson 	 */
3907cb0f722aSWei Huang 	if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3908a717a780SSean Christopherson 			 (need_pml5 && mmu->pml5_root)))
3909748e52b9SSean Christopherson 		return -EIO;
3910748e52b9SSean Christopherson 
39114a98623dSSean Christopherson 	/*
39124a98623dSSean Christopherson 	 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
39134a98623dSSean Christopherson 	 * doesn't need to be decrypted.
39144a98623dSSean Christopherson 	 */
3915748e52b9SSean Christopherson 	pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3916748e52b9SSean Christopherson 	if (!pae_root)
3917748e52b9SSean Christopherson 		return -ENOMEM;
3918748e52b9SSean Christopherson 
3919cb0f722aSWei Huang #ifdef CONFIG_X86_64
392003ca4589SSean Christopherson 	pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3921cb0f722aSWei Huang 	if (!pml4_root)
3922cb0f722aSWei Huang 		goto err_pml4;
3923cb0f722aSWei Huang 
3924a717a780SSean Christopherson 	if (need_pml5) {
3925cb0f722aSWei Huang 		pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3926cb0f722aSWei Huang 		if (!pml5_root)
3927cb0f722aSWei Huang 			goto err_pml5;
3928748e52b9SSean Christopherson 	}
3929cb0f722aSWei Huang #endif
3930748e52b9SSean Christopherson 
3931748e52b9SSean Christopherson 	mmu->pae_root = pae_root;
393203ca4589SSean Christopherson 	mmu->pml4_root = pml4_root;
3933cb0f722aSWei Huang 	mmu->pml5_root = pml5_root;
3934748e52b9SSean Christopherson 
3935748e52b9SSean Christopherson 	return 0;
3936cb0f722aSWei Huang 
3937cb0f722aSWei Huang #ifdef CONFIG_X86_64
3938cb0f722aSWei Huang err_pml5:
3939cb0f722aSWei Huang 	free_page((unsigned long)pml4_root);
3940cb0f722aSWei Huang err_pml4:
3941cb0f722aSWei Huang 	free_page((unsigned long)pae_root);
3942cb0f722aSWei Huang 	return -ENOMEM;
3943cb0f722aSWei Huang #endif
3944c50d8ae3SPaolo Bonzini }
3945c50d8ae3SPaolo Bonzini 
3946264d3dc1SLai Jiangshan static bool is_unsync_root(hpa_t root)
3947264d3dc1SLai Jiangshan {
3948264d3dc1SLai Jiangshan 	struct kvm_mmu_page *sp;
3949264d3dc1SLai Jiangshan 
39500e3223d8SSean Christopherson 	if (!VALID_PAGE(root) || kvm_mmu_is_dummy_root(root))
395161b05a9fSLai Jiangshan 		return false;
395261b05a9fSLai Jiangshan 
3953264d3dc1SLai Jiangshan 	/*
3954264d3dc1SLai Jiangshan 	 * The read barrier orders the CPU's read of SPTE.W during the page table
3955264d3dc1SLai Jiangshan 	 * walk before the reads of sp->unsync/sp->unsync_children here.
3956264d3dc1SLai Jiangshan 	 *
3957264d3dc1SLai Jiangshan 	 * Even if another CPU was marking the SP as unsync-ed simultaneously,
3958264d3dc1SLai Jiangshan 	 * any guest page table changes are not guaranteed to be visible anyway
3959264d3dc1SLai Jiangshan 	 * until this VCPU issues a TLB flush strictly after those changes are
3960264d3dc1SLai Jiangshan 	 * made.  We only need to ensure that the other CPU sets these flags
3961264d3dc1SLai Jiangshan 	 * before any actual changes to the page tables are made.  The comments
3962264d3dc1SLai Jiangshan 	 * in mmu_try_to_unsync_pages() describe what could go wrong if this
3963264d3dc1SLai Jiangshan 	 * requirement isn't satisfied.
3964264d3dc1SLai Jiangshan 	 */
3965264d3dc1SLai Jiangshan 	smp_rmb();
3966c5f2d564SSean Christopherson 	sp = root_to_sp(root);
39675d6a3221SSean Christopherson 
39685d6a3221SSean Christopherson 	/*
39695d6a3221SSean Christopherson 	 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
39705d6a3221SSean Christopherson 	 * PDPTEs for a given PAE root need to be synchronized individually.
39715d6a3221SSean Christopherson 	 */
39725d6a3221SSean Christopherson 	if (WARN_ON_ONCE(!sp))
39735d6a3221SSean Christopherson 		return false;
39745d6a3221SSean Christopherson 
3975264d3dc1SLai Jiangshan 	if (sp->unsync || sp->unsync_children)
3976264d3dc1SLai Jiangshan 		return true;
3977264d3dc1SLai Jiangshan 
3978264d3dc1SLai Jiangshan 	return false;
3979264d3dc1SLai Jiangshan }
3980264d3dc1SLai Jiangshan 
3981c50d8ae3SPaolo Bonzini void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3982c50d8ae3SPaolo Bonzini {
3983c50d8ae3SPaolo Bonzini 	int i;
3984c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3985c50d8ae3SPaolo Bonzini 
3986347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
3987c50d8ae3SPaolo Bonzini 		return;
3988c50d8ae3SPaolo Bonzini 
3989b9e5603cSPaolo Bonzini 	if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
3990c50d8ae3SPaolo Bonzini 		return;
3991c50d8ae3SPaolo Bonzini 
3992c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3993c50d8ae3SPaolo Bonzini 
39944d25502aSPaolo Bonzini 	if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
3995b9e5603cSPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->root.hpa;
3996c50d8ae3SPaolo Bonzini 
3997264d3dc1SLai Jiangshan 		if (!is_unsync_root(root))
3998c50d8ae3SPaolo Bonzini 			return;
3999c50d8ae3SPaolo Bonzini 
4000c5f2d564SSean Christopherson 		sp = root_to_sp(root);
4001c5f2d564SSean Christopherson 
4002531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
400365855ed8SLai Jiangshan 		mmu_sync_children(vcpu, sp, true);
4004531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
4005c50d8ae3SPaolo Bonzini 		return;
4006c50d8ae3SPaolo Bonzini 	}
4007c50d8ae3SPaolo Bonzini 
4008531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
4009c50d8ae3SPaolo Bonzini 
4010c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
4011c50d8ae3SPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->pae_root[i];
4012c50d8ae3SPaolo Bonzini 
4013c834e5e4SSean Christopherson 		if (IS_VALID_PAE_ROOT(root)) {
40145e3edd7eSSean Christopherson 			sp = spte_to_child_sp(root);
401565855ed8SLai Jiangshan 			mmu_sync_children(vcpu, sp, true);
4016c50d8ae3SPaolo Bonzini 		}
4017c50d8ae3SPaolo Bonzini 	}
4018c50d8ae3SPaolo Bonzini 
4019531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
4020c50d8ae3SPaolo Bonzini }
4021c50d8ae3SPaolo Bonzini 
402261b05a9fSLai Jiangshan void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
402361b05a9fSLai Jiangshan {
402461b05a9fSLai Jiangshan 	unsigned long roots_to_free = 0;
402561b05a9fSLai Jiangshan 	int i;
402661b05a9fSLai Jiangshan 
402761b05a9fSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
402861b05a9fSLai Jiangshan 		if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
402961b05a9fSLai Jiangshan 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
403061b05a9fSLai Jiangshan 
403161b05a9fSLai Jiangshan 	/* sync prev_roots by simply freeing them */
40320c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
403361b05a9fSLai Jiangshan }
403461b05a9fSLai Jiangshan 
40351f5a21eeSLai Jiangshan static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
40365b22bbe7SLai Jiangshan 				  gpa_t vaddr, u64 access,
4037c50d8ae3SPaolo Bonzini 				  struct x86_exception *exception)
4038c50d8ae3SPaolo Bonzini {
4039c50d8ae3SPaolo Bonzini 	if (exception)
4040c50d8ae3SPaolo Bonzini 		exception->error_code = 0;
4041c59a0f57SLai Jiangshan 	return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
4042c50d8ae3SPaolo Bonzini }
4043c50d8ae3SPaolo Bonzini 
4044c50d8ae3SPaolo Bonzini static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4045c50d8ae3SPaolo Bonzini {
4046c50d8ae3SPaolo Bonzini 	/*
4047c50d8ae3SPaolo Bonzini 	 * A nested guest cannot use the MMIO cache if it is using nested
4048c50d8ae3SPaolo Bonzini 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4049c50d8ae3SPaolo Bonzini 	 */
4050c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
4051c50d8ae3SPaolo Bonzini 		return false;
4052c50d8ae3SPaolo Bonzini 
4053c50d8ae3SPaolo Bonzini 	if (direct)
4054c50d8ae3SPaolo Bonzini 		return vcpu_match_mmio_gpa(vcpu, addr);
4055c50d8ae3SPaolo Bonzini 
4056c50d8ae3SPaolo Bonzini 	return vcpu_match_mmio_gva(vcpu, addr);
4057c50d8ae3SPaolo Bonzini }
4058c50d8ae3SPaolo Bonzini 
405995fb5b02SBen Gardon /*
406095fb5b02SBen Gardon  * Return the level of the lowest level SPTE added to sptes.
406195fb5b02SBen Gardon  * That SPTE may be non-present.
4062c5c8c7c5SDavid Matlack  *
4063c5c8c7c5SDavid Matlack  * Must be called between walk_shadow_page_lockless_{begin,end}.
406495fb5b02SBen Gardon  */
406539b4d43eSSean Christopherson static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4066c50d8ae3SPaolo Bonzini {
4067c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
40682aa07893SSean Christopherson 	int leaf = -1;
406995fb5b02SBen Gardon 	u64 spte;
4070c50d8ae3SPaolo Bonzini 
407139b4d43eSSean Christopherson 	for (shadow_walk_init(&iterator, vcpu, addr),
407239b4d43eSSean Christopherson 	     *root_level = iterator.level;
4073c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&iterator);
4074c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&iterator, spte)) {
407595fb5b02SBen Gardon 		leaf = iterator.level;
4076c50d8ae3SPaolo Bonzini 		spte = mmu_spte_get_lockless(iterator.sptep);
4077c50d8ae3SPaolo Bonzini 
4078dde81f94SSean Christopherson 		sptes[leaf] = spte;
407995fb5b02SBen Gardon 	}
408095fb5b02SBen Gardon 
408195fb5b02SBen Gardon 	return leaf;
408295fb5b02SBen Gardon }
408395fb5b02SBen Gardon 
40849aa41879SSean Christopherson /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
408595fb5b02SBen Gardon static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
408695fb5b02SBen Gardon {
4087dde81f94SSean Christopherson 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
408895fb5b02SBen Gardon 	struct rsvd_bits_validate *rsvd_check;
408939b4d43eSSean Christopherson 	int root, leaf, level;
409095fb5b02SBen Gardon 	bool reserved = false;
409195fb5b02SBen Gardon 
4092c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_begin(vcpu);
4093c5c8c7c5SDavid Matlack 
409478fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu))
409539b4d43eSSean Christopherson 		leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
409695fb5b02SBen Gardon 	else
409739b4d43eSSean Christopherson 		leaf = get_walk(vcpu, addr, sptes, &root);
409895fb5b02SBen Gardon 
4099c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_end(vcpu);
4100c5c8c7c5SDavid Matlack 
41012aa07893SSean Christopherson 	if (unlikely(leaf < 0)) {
41022aa07893SSean Christopherson 		*sptep = 0ull;
41032aa07893SSean Christopherson 		return reserved;
41042aa07893SSean Christopherson 	}
41052aa07893SSean Christopherson 
41069aa41879SSean Christopherson 	*sptep = sptes[leaf];
41079aa41879SSean Christopherson 
41089aa41879SSean Christopherson 	/*
41099aa41879SSean Christopherson 	 * Skip reserved bits checks on the terminal leaf if it's not a valid
41109aa41879SSean Christopherson 	 * SPTE.  Note, this also (intentionally) skips MMIO SPTEs, which, by
41119aa41879SSean Christopherson 	 * design, always have reserved bits set.  The purpose of the checks is
41129aa41879SSean Christopherson 	 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
41139aa41879SSean Christopherson 	 */
41149aa41879SSean Christopherson 	if (!is_shadow_present_pte(sptes[leaf]))
41159aa41879SSean Christopherson 		leaf++;
411695fb5b02SBen Gardon 
411795fb5b02SBen Gardon 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
411895fb5b02SBen Gardon 
41199aa41879SSean Christopherson 	for (level = root; level >= leaf; level--)
4120961f8445SSean Christopherson 		reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4121c50d8ae3SPaolo Bonzini 
4122c50d8ae3SPaolo Bonzini 	if (reserved) {
4123bb4cdf3aSSean Christopherson 		pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4124c50d8ae3SPaolo Bonzini 		       __func__, addr);
412595fb5b02SBen Gardon 		for (level = root; level >= leaf; level--)
4126bb4cdf3aSSean Christopherson 			pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4127bb4cdf3aSSean Christopherson 			       sptes[level], level,
4128961f8445SSean Christopherson 			       get_rsvd_bits(rsvd_check, sptes[level], level));
4129c50d8ae3SPaolo Bonzini 	}
4130ddce6208SSean Christopherson 
4131c50d8ae3SPaolo Bonzini 	return reserved;
4132c50d8ae3SPaolo Bonzini }
4133c50d8ae3SPaolo Bonzini 
4134c50d8ae3SPaolo Bonzini static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4135c50d8ae3SPaolo Bonzini {
4136c50d8ae3SPaolo Bonzini 	u64 spte;
4137c50d8ae3SPaolo Bonzini 	bool reserved;
4138c50d8ae3SPaolo Bonzini 
4139c50d8ae3SPaolo Bonzini 	if (mmio_info_in_cache(vcpu, addr, direct))
4140c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4141c50d8ae3SPaolo Bonzini 
414295fb5b02SBen Gardon 	reserved = get_mmio_spte(vcpu, addr, &spte);
414320ba462dSSean Christopherson 	if (WARN_ON_ONCE(reserved))
4144c50d8ae3SPaolo Bonzini 		return -EINVAL;
4145c50d8ae3SPaolo Bonzini 
4146c50d8ae3SPaolo Bonzini 	if (is_mmio_spte(spte)) {
4147c50d8ae3SPaolo Bonzini 		gfn_t gfn = get_mmio_spte_gfn(spte);
41480a2b64c5SBen Gardon 		unsigned int access = get_mmio_spte_access(spte);
4149c50d8ae3SPaolo Bonzini 
4150c50d8ae3SPaolo Bonzini 		if (!check_mmio_spte(vcpu, spte))
4151c50d8ae3SPaolo Bonzini 			return RET_PF_INVALID;
4152c50d8ae3SPaolo Bonzini 
4153c50d8ae3SPaolo Bonzini 		if (direct)
4154c50d8ae3SPaolo Bonzini 			addr = 0;
4155c50d8ae3SPaolo Bonzini 
4156c50d8ae3SPaolo Bonzini 		trace_handle_mmio_page_fault(addr, gfn, access);
4157c50d8ae3SPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4158c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4159c50d8ae3SPaolo Bonzini 	}
4160c50d8ae3SPaolo Bonzini 
4161c50d8ae3SPaolo Bonzini 	/*
4162c50d8ae3SPaolo Bonzini 	 * If the page table is zapped by other cpus, let CPU fault again on
4163c50d8ae3SPaolo Bonzini 	 * the address.
4164c50d8ae3SPaolo Bonzini 	 */
4165c50d8ae3SPaolo Bonzini 	return RET_PF_RETRY;
4166c50d8ae3SPaolo Bonzini }
4167c50d8ae3SPaolo Bonzini 
4168c50d8ae3SPaolo Bonzini static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4169b8a5d551SPaolo Bonzini 					 struct kvm_page_fault *fault)
4170c50d8ae3SPaolo Bonzini {
4171b8a5d551SPaolo Bonzini 	if (unlikely(fault->rsvd))
4172c50d8ae3SPaolo Bonzini 		return false;
4173c50d8ae3SPaolo Bonzini 
4174b8a5d551SPaolo Bonzini 	if (!fault->present || !fault->write)
4175c50d8ae3SPaolo Bonzini 		return false;
4176c50d8ae3SPaolo Bonzini 
4177c50d8ae3SPaolo Bonzini 	/*
4178c50d8ae3SPaolo Bonzini 	 * guest is writing the page which is write tracked which can
4179c50d8ae3SPaolo Bonzini 	 * not be fixed by page fault handler.
4180c50d8ae3SPaolo Bonzini 	 */
41817b574863SSean Christopherson 	if (kvm_gfn_is_write_tracked(vcpu->kvm, fault->slot, fault->gfn))
4182c50d8ae3SPaolo Bonzini 		return true;
4183c50d8ae3SPaolo Bonzini 
4184c50d8ae3SPaolo Bonzini 	return false;
4185c50d8ae3SPaolo Bonzini }
4186c50d8ae3SPaolo Bonzini 
4187c50d8ae3SPaolo Bonzini static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4188c50d8ae3SPaolo Bonzini {
4189c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
4190c50d8ae3SPaolo Bonzini 	u64 spte;
4191c50d8ae3SPaolo Bonzini 
4192c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
41933e44dce4SLai Jiangshan 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4194c50d8ae3SPaolo Bonzini 		clear_sp_write_flooding_count(iterator.sptep);
4195c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
4196c50d8ae3SPaolo Bonzini }
4197c50d8ae3SPaolo Bonzini 
41986f3c1fc5SLiang Zhang static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
41996f3c1fc5SLiang Zhang {
42006f3c1fc5SLiang Zhang 	/* make sure the token value is not 0 */
42016f3c1fc5SLiang Zhang 	u32 id = vcpu->arch.apf.id;
42026f3c1fc5SLiang Zhang 
42036f3c1fc5SLiang Zhang 	if (id << 12 == 0)
42046f3c1fc5SLiang Zhang 		vcpu->arch.apf.id = 1;
42056f3c1fc5SLiang Zhang 
42066f3c1fc5SLiang Zhang 	return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
42076f3c1fc5SLiang Zhang }
42086f3c1fc5SLiang Zhang 
4209e8c22266SVitaly Kuznetsov static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
42109f1a8526SSean Christopherson 				    gfn_t gfn)
4211c50d8ae3SPaolo Bonzini {
4212c50d8ae3SPaolo Bonzini 	struct kvm_arch_async_pf arch;
4213c50d8ae3SPaolo Bonzini 
42146f3c1fc5SLiang Zhang 	arch.token = alloc_apf_token(vcpu);
4215c50d8ae3SPaolo Bonzini 	arch.gfn = gfn;
4216347a0d0dSPaolo Bonzini 	arch.direct_map = vcpu->arch.mmu->root_role.direct;
42172fdcc1b3SPaolo Bonzini 	arch.cr3 = kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu);
4218c50d8ae3SPaolo Bonzini 
42199f1a8526SSean Christopherson 	return kvm_setup_async_pf(vcpu, cr2_or_gpa,
42209f1a8526SSean Christopherson 				  kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4221c50d8ae3SPaolo Bonzini }
4222c50d8ae3SPaolo Bonzini 
42238a009d5bSSean Christopherson void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
42248a009d5bSSean Christopherson {
42258a009d5bSSean Christopherson 	int r;
42268a009d5bSSean Christopherson 
42278a009d5bSSean Christopherson 	if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
42288a009d5bSSean Christopherson 	      work->wakeup_all)
42298a009d5bSSean Christopherson 		return;
42308a009d5bSSean Christopherson 
42318a009d5bSSean Christopherson 	r = kvm_mmu_reload(vcpu);
42328a009d5bSSean Christopherson 	if (unlikely(r))
42338a009d5bSSean Christopherson 		return;
42348a009d5bSSean Christopherson 
42358a009d5bSSean Christopherson 	if (!vcpu->arch.mmu->root_role.direct &&
42362fdcc1b3SPaolo Bonzini 	      work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
42378a009d5bSSean Christopherson 		return;
42388a009d5bSSean Christopherson 
4239258d985fSSean Christopherson 	kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true, NULL);
42408a009d5bSSean Christopherson }
42418a009d5bSSean Christopherson 
42428dd2eee9SChao Peng static inline u8 kvm_max_level_for_order(int order)
42438dd2eee9SChao Peng {
42448dd2eee9SChao Peng 	BUILD_BUG_ON(KVM_MAX_HUGEPAGE_LEVEL > PG_LEVEL_1G);
42458dd2eee9SChao Peng 
42468dd2eee9SChao Peng 	KVM_MMU_WARN_ON(order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G) &&
42478dd2eee9SChao Peng 			order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M) &&
42488dd2eee9SChao Peng 			order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_4K));
42498dd2eee9SChao Peng 
42508dd2eee9SChao Peng 	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G))
42518dd2eee9SChao Peng 		return PG_LEVEL_1G;
42528dd2eee9SChao Peng 
42538dd2eee9SChao Peng 	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M))
42548dd2eee9SChao Peng 		return PG_LEVEL_2M;
42558dd2eee9SChao Peng 
42568dd2eee9SChao Peng 	return PG_LEVEL_4K;
42578dd2eee9SChao Peng }
42588dd2eee9SChao Peng 
42598dd2eee9SChao Peng static int kvm_faultin_pfn_private(struct kvm_vcpu *vcpu,
42608dd2eee9SChao Peng 				   struct kvm_page_fault *fault)
42618dd2eee9SChao Peng {
42628dd2eee9SChao Peng 	int max_order, r;
42638dd2eee9SChao Peng 
42648dd2eee9SChao Peng 	if (!kvm_slot_can_be_private(fault->slot)) {
42658dd2eee9SChao Peng 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
42668dd2eee9SChao Peng 		return -EFAULT;
42678dd2eee9SChao Peng 	}
42688dd2eee9SChao Peng 
42698dd2eee9SChao Peng 	r = kvm_gmem_get_pfn(vcpu->kvm, fault->slot, fault->gfn, &fault->pfn,
42708dd2eee9SChao Peng 			     &max_order);
42718dd2eee9SChao Peng 	if (r) {
42728dd2eee9SChao Peng 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
42738dd2eee9SChao Peng 		return r;
42748dd2eee9SChao Peng 	}
42758dd2eee9SChao Peng 
42768dd2eee9SChao Peng 	fault->max_level = min(kvm_max_level_for_order(max_order),
42778dd2eee9SChao Peng 			       fault->max_level);
42788dd2eee9SChao Peng 	fault->map_writable = !(fault->slot->flags & KVM_MEM_READONLY);
42798dd2eee9SChao Peng 
42808dd2eee9SChao Peng 	return RET_PF_CONTINUE;
42818dd2eee9SChao Peng }
42828dd2eee9SChao Peng 
4283ba6e3fe2SDavid Matlack static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4284c50d8ae3SPaolo Bonzini {
4285e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
4286c50d8ae3SPaolo Bonzini 	bool async;
4287c50d8ae3SPaolo Bonzini 
4288e0c37868SSean Christopherson 	/*
4289e0c37868SSean Christopherson 	 * Retry the page fault if the gfn hit a memslot that is being deleted
4290e0c37868SSean Christopherson 	 * or moved.  This ensures any existing SPTEs for the old memslot will
4291e0c37868SSean Christopherson 	 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4292e0c37868SSean Christopherson 	 */
4293e0c37868SSean Christopherson 	if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
42945276c616SSean Christopherson 		return RET_PF_RETRY;
4295e0c37868SSean Christopherson 
42969cc13d60SMaxim Levitsky 	if (!kvm_is_visible_memslot(slot)) {
4297c36b7150SPaolo Bonzini 		/* Don't expose private memslots to L2. */
42989cc13d60SMaxim Levitsky 		if (is_guest_mode(vcpu)) {
4299e710c5f6SDavid Matlack 			fault->slot = NULL;
43003647cd04SPaolo Bonzini 			fault->pfn = KVM_PFN_NOSLOT;
43013647cd04SPaolo Bonzini 			fault->map_writable = false;
43025276c616SSean Christopherson 			return RET_PF_CONTINUE;
4303c50d8ae3SPaolo Bonzini 		}
43049cc13d60SMaxim Levitsky 		/*
43059cc13d60SMaxim Levitsky 		 * If the APIC access page exists but is disabled, go directly
43069cc13d60SMaxim Levitsky 		 * to emulation without caching the MMIO access or creating a
43079cc13d60SMaxim Levitsky 		 * MMIO SPTE.  That way the cache doesn't need to be purged
43089cc13d60SMaxim Levitsky 		 * when the AVIC is re-enabled.
43099cc13d60SMaxim Levitsky 		 */
43109cc13d60SMaxim Levitsky 		if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
43115276c616SSean Christopherson 		    !kvm_apicv_activated(vcpu->kvm))
43125276c616SSean Christopherson 			return RET_PF_EMULATE;
43139cc13d60SMaxim Levitsky 	}
4314c50d8ae3SPaolo Bonzini 
43158dd2eee9SChao Peng 	if (fault->is_private != kvm_mem_is_private(vcpu->kvm, fault->gfn)) {
43168dd2eee9SChao Peng 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
43178dd2eee9SChao Peng 		return -EFAULT;
43188dd2eee9SChao Peng 	}
43198dd2eee9SChao Peng 
43208dd2eee9SChao Peng 	if (fault->is_private)
43218dd2eee9SChao Peng 		return kvm_faultin_pfn_private(vcpu, fault);
43228dd2eee9SChao Peng 
4323c50d8ae3SPaolo Bonzini 	async = false;
4324c8b88b33SPeter Xu 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, false, &async,
43253647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
43263647cd04SPaolo Bonzini 					  &fault->hva);
4327c50d8ae3SPaolo Bonzini 	if (!async)
43285276c616SSean Christopherson 		return RET_PF_CONTINUE; /* *pfn has correct page already */
4329c50d8ae3SPaolo Bonzini 
43302839180cSPaolo Bonzini 	if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
43313647cd04SPaolo Bonzini 		trace_kvm_try_async_get_page(fault->addr, fault->gfn);
43323647cd04SPaolo Bonzini 		if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
43331685c0f3SMingwei Zhang 			trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4334c50d8ae3SPaolo Bonzini 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
43355276c616SSean Christopherson 			return RET_PF_RETRY;
43365276c616SSean Christopherson 		} else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn)) {
43375276c616SSean Christopherson 			return RET_PF_RETRY;
43385276c616SSean Christopherson 		}
4339c50d8ae3SPaolo Bonzini 	}
4340c50d8ae3SPaolo Bonzini 
434176657687SPeter Xu 	/*
434276657687SPeter Xu 	 * Allow gup to bail on pending non-fatal signals when it's also allowed
434376657687SPeter Xu 	 * to wait for IO.  Note, gup always bails if it is unable to quickly
434476657687SPeter Xu 	 * get a page and a fatal signal, i.e. SIGKILL, is pending.
434576657687SPeter Xu 	 */
434676657687SPeter Xu 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, true, NULL,
43473647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
43483647cd04SPaolo Bonzini 					  &fault->hva);
43495276c616SSean Christopherson 	return RET_PF_CONTINUE;
4350c50d8ae3SPaolo Bonzini }
4351c50d8ae3SPaolo Bonzini 
4352354c908cSDavid Matlack static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
4353354c908cSDavid Matlack 			   unsigned int access)
4354ba6e3fe2SDavid Matlack {
435556c3a4e4SDavid Matlack 	int ret;
435656c3a4e4SDavid Matlack 
4357ba6e3fe2SDavid Matlack 	fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4358ba6e3fe2SDavid Matlack 	smp_rmb();
4359ba6e3fe2SDavid Matlack 
4360d02c357eSSean Christopherson 	/*
4361d02c357eSSean Christopherson 	 * Check for a relevant mmu_notifier invalidation event before getting
4362d02c357eSSean Christopherson 	 * the pfn from the primary MMU, and before acquiring mmu_lock.
4363d02c357eSSean Christopherson 	 *
4364d02c357eSSean Christopherson 	 * For mmu_lock, if there is an in-progress invalidation and the kernel
4365d02c357eSSean Christopherson 	 * allows preemption, the invalidation task may drop mmu_lock and yield
4366d02c357eSSean Christopherson 	 * in response to mmu_lock being contended, which is *very* counter-
4367d02c357eSSean Christopherson 	 * productive as this vCPU can't actually make forward progress until
4368d02c357eSSean Christopherson 	 * the invalidation completes.
4369d02c357eSSean Christopherson 	 *
4370d02c357eSSean Christopherson 	 * Retrying now can also avoid unnessary lock contention in the primary
4371d02c357eSSean Christopherson 	 * MMU, as the primary MMU doesn't necessarily hold a single lock for
4372d02c357eSSean Christopherson 	 * the duration of the invalidation, i.e. faulting in a conflicting pfn
4373d02c357eSSean Christopherson 	 * can cause the invalidation to take longer by holding locks that are
4374d02c357eSSean Christopherson 	 * needed to complete the invalidation.
4375d02c357eSSean Christopherson 	 *
4376d02c357eSSean Christopherson 	 * Do the pre-check even for non-preemtible kernels, i.e. even if KVM
4377d02c357eSSean Christopherson 	 * will never yield mmu_lock in response to contention, as this vCPU is
4378d02c357eSSean Christopherson 	 * *guaranteed* to need to retry, i.e. waiting until mmu_lock is held
4379d02c357eSSean Christopherson 	 * to detect retry guarantees the worst case latency for the vCPU.
4380d02c357eSSean Christopherson 	 */
4381d02c357eSSean Christopherson 	if (fault->slot &&
4382d02c357eSSean Christopherson 	    mmu_invalidate_retry_gfn_unsafe(vcpu->kvm, fault->mmu_seq, fault->gfn))
4383d02c357eSSean Christopherson 		return RET_PF_RETRY;
4384d02c357eSSean Christopherson 
438556c3a4e4SDavid Matlack 	ret = __kvm_faultin_pfn(vcpu, fault);
438656c3a4e4SDavid Matlack 	if (ret != RET_PF_CONTINUE)
438756c3a4e4SDavid Matlack 		return ret;
438856c3a4e4SDavid Matlack 
438956c3a4e4SDavid Matlack 	if (unlikely(is_error_pfn(fault->pfn)))
4390cd08d178SDavid Matlack 		return kvm_handle_error_pfn(vcpu, fault);
439156c3a4e4SDavid Matlack 
4392354c908cSDavid Matlack 	if (unlikely(!fault->slot))
4393354c908cSDavid Matlack 		return kvm_handle_noslot_fault(vcpu, fault, access);
4394354c908cSDavid Matlack 
4395d02c357eSSean Christopherson 	/*
4396d02c357eSSean Christopherson 	 * Check again for a relevant mmu_notifier invalidation event purely to
4397d02c357eSSean Christopherson 	 * avoid contending mmu_lock.  Most invalidations will be detected by
4398d02c357eSSean Christopherson 	 * the previous check, but checking is extremely cheap relative to the
4399d02c357eSSean Christopherson 	 * overall cost of failing to detect the invalidation until after
4400d02c357eSSean Christopherson 	 * mmu_lock is acquired.
4401d02c357eSSean Christopherson 	 */
4402d02c357eSSean Christopherson 	if (mmu_invalidate_retry_gfn_unsafe(vcpu->kvm, fault->mmu_seq, fault->gfn)) {
4403d02c357eSSean Christopherson 		kvm_release_pfn_clean(fault->pfn);
4404d02c357eSSean Christopherson 		return RET_PF_RETRY;
4405d02c357eSSean Christopherson 	}
4406d02c357eSSean Christopherson 
440756c3a4e4SDavid Matlack 	return RET_PF_CONTINUE;
4408ba6e3fe2SDavid Matlack }
4409ba6e3fe2SDavid Matlack 
4410a955cad8SSean Christopherson /*
4411a955cad8SSean Christopherson  * Returns true if the page fault is stale and needs to be retried, i.e. if the
4412a955cad8SSean Christopherson  * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4413a955cad8SSean Christopherson  */
4414a955cad8SSean Christopherson static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4415ba6e3fe2SDavid Matlack 				struct kvm_page_fault *fault)
4416a955cad8SSean Christopherson {
4417c5f2d564SSean Christopherson 	struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
441818c841e1SSean Christopherson 
441918c841e1SSean Christopherson 	/* Special roots, e.g. pae_root, are not backed by shadow pages. */
442018c841e1SSean Christopherson 	if (sp && is_obsolete_sp(vcpu->kvm, sp))
442118c841e1SSean Christopherson 		return true;
442218c841e1SSean Christopherson 
442318c841e1SSean Christopherson 	/*
442418c841e1SSean Christopherson 	 * Roots without an associated shadow page are considered invalid if
442518c841e1SSean Christopherson 	 * there is a pending request to free obsolete roots.  The request is
442618c841e1SSean Christopherson 	 * only a hint that the current root _may_ be obsolete and needs to be
442718c841e1SSean Christopherson 	 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
442818c841e1SSean Christopherson 	 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
442918c841e1SSean Christopherson 	 * to reload even if no vCPU is actively using the root.
443018c841e1SSean Christopherson 	 */
4431527d5cd7SSean Christopherson 	if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4432a955cad8SSean Christopherson 		return true;
4433a955cad8SSean Christopherson 
4434d02c357eSSean Christopherson 	/*
4435d02c357eSSean Christopherson 	 * Check for a relevant mmu_notifier invalidation event one last time
4436d02c357eSSean Christopherson 	 * now that mmu_lock is held, as the "unsafe" checks performed without
4437d02c357eSSean Christopherson 	 * holding mmu_lock can get false negatives.
4438d02c357eSSean Christopherson 	 */
4439a955cad8SSean Christopherson 	return fault->slot &&
44408569992dSChao Peng 	       mmu_invalidate_retry_gfn(vcpu->kvm, fault->mmu_seq, fault->gfn);
4441a955cad8SSean Christopherson }
4442a955cad8SSean Christopherson 
44434326e57eSPaolo Bonzini static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4444c50d8ae3SPaolo Bonzini {
444583f06fa7SSean Christopherson 	int r;
4446c50d8ae3SPaolo Bonzini 
44470e3223d8SSean Christopherson 	/* Dummy roots are used only for shadowing bad guest roots. */
44480e3223d8SSean Christopherson 	if (WARN_ON_ONCE(kvm_mmu_is_dummy_root(vcpu->arch.mmu->root.hpa)))
44490e3223d8SSean Christopherson 		return RET_PF_RETRY;
44500e3223d8SSean Christopherson 
4451b8a5d551SPaolo Bonzini 	if (page_fault_handle_page_track(vcpu, fault))
4452c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4453c50d8ae3SPaolo Bonzini 
44543c8ad5a6SPaolo Bonzini 	r = fast_page_fault(vcpu, fault);
4455c4371c2aSSean Christopherson 	if (r != RET_PF_INVALID)
4456c4371c2aSSean Christopherson 		return r;
445783291445SSean Christopherson 
4458378f5cd6SSean Christopherson 	r = mmu_topup_memory_caches(vcpu, false);
4459c50d8ae3SPaolo Bonzini 	if (r)
4460c50d8ae3SPaolo Bonzini 		return r;
4461c50d8ae3SPaolo Bonzini 
4462354c908cSDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
44635276c616SSean Christopherson 	if (r != RET_PF_CONTINUE)
4464367fd790SSean Christopherson 		return r;
4465367fd790SSean Christopherson 
4466367fd790SSean Christopherson 	r = RET_PF_RETRY;
4467531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
4468a2855afcSBen Gardon 
4469ba6e3fe2SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
4470367fd790SSean Christopherson 		goto out_unlock;
4471a955cad8SSean Christopherson 
44727bd7ded6SSean Christopherson 	r = make_mmu_pages_available(vcpu);
44737bd7ded6SSean Christopherson 	if (r)
4474367fd790SSean Christopherson 		goto out_unlock;
4475bb18842eSBen Gardon 
44766c882ef4SDavid Matlack 	r = direct_map(vcpu, fault);
44770f90e1c1SSean Christopherson 
4478367fd790SSean Christopherson out_unlock:
4479531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
44803647cd04SPaolo Bonzini 	kvm_release_pfn_clean(fault->pfn);
4481367fd790SSean Christopherson 	return r;
4482c50d8ae3SPaolo Bonzini }
4483c50d8ae3SPaolo Bonzini 
4484c501040aSPaolo Bonzini static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4485c501040aSPaolo Bonzini 				struct kvm_page_fault *fault)
44860f90e1c1SSean Christopherson {
44870f90e1c1SSean Christopherson 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
44884326e57eSPaolo Bonzini 	fault->max_level = PG_LEVEL_2M;
44894326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
44900f90e1c1SSean Christopherson }
44910f90e1c1SSean Christopherson 
4492c50d8ae3SPaolo Bonzini int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4493c50d8ae3SPaolo Bonzini 				u64 fault_address, char *insn, int insn_len)
4494c50d8ae3SPaolo Bonzini {
4495c50d8ae3SPaolo Bonzini 	int r = 1;
44969ce372b3SVitaly Kuznetsov 	u32 flags = vcpu->arch.apf.host_apf_flags;
4497c50d8ae3SPaolo Bonzini 
4498736c291cSSean Christopherson #ifndef CONFIG_X86_64
4499736c291cSSean Christopherson 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4500736c291cSSean Christopherson 	if (WARN_ON_ONCE(fault_address >> 32))
4501736c291cSSean Christopherson 		return -EFAULT;
4502736c291cSSean Christopherson #endif
4503*7bdbb820SSean Christopherson 	/*
4504*7bdbb820SSean Christopherson 	 * Legacy #PF exception only have a 32-bit error code.  Simply drop the
4505*7bdbb820SSean Christopherson 	 * upper bits as KVM doesn't use them for #PF (because they are never
4506*7bdbb820SSean Christopherson 	 * set), and to ensure there are no collisions with KVM-defined bits.
4507*7bdbb820SSean Christopherson 	 */
4508*7bdbb820SSean Christopherson 	if (WARN_ON_ONCE(error_code >> 32))
4509*7bdbb820SSean Christopherson 		error_code = lower_32_bits(error_code);
4510736c291cSSean Christopherson 
4511dee281e4SSean Christopherson 	/* Ensure the above sanity check also covers KVM-defined flags. */
4512dee281e4SSean Christopherson 	BUILD_BUG_ON(lower_32_bits(PFERR_SYNTHETIC_MASK));
4513dee281e4SSean Christopherson 
4514c50d8ae3SPaolo Bonzini 	vcpu->arch.l1tf_flush_l1d = true;
45159ce372b3SVitaly Kuznetsov 	if (!flags) {
4516faa03b39SWonhyuk Yang 		trace_kvm_page_fault(vcpu, fault_address, error_code);
4517c50d8ae3SPaolo Bonzini 
4518c50d8ae3SPaolo Bonzini 		if (kvm_event_needs_reinjection(vcpu))
4519c50d8ae3SPaolo Bonzini 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4520c50d8ae3SPaolo Bonzini 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4521c50d8ae3SPaolo Bonzini 				insn_len);
45229ce372b3SVitaly Kuznetsov 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
452368fd66f1SVitaly Kuznetsov 		vcpu->arch.apf.host_apf_flags = 0;
4524c50d8ae3SPaolo Bonzini 		local_irq_disable();
45256bca69adSThomas Gleixner 		kvm_async_pf_task_wait_schedule(fault_address);
4526c50d8ae3SPaolo Bonzini 		local_irq_enable();
45279ce372b3SVitaly Kuznetsov 	} else {
45289ce372b3SVitaly Kuznetsov 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4529c50d8ae3SPaolo Bonzini 	}
45309ce372b3SVitaly Kuznetsov 
4531c50d8ae3SPaolo Bonzini 	return r;
4532c50d8ae3SPaolo Bonzini }
4533c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4534c50d8ae3SPaolo Bonzini 
45359aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
45369aa8ab43SDavid Matlack static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
45379aa8ab43SDavid Matlack 				  struct kvm_page_fault *fault)
45389aa8ab43SDavid Matlack {
45399aa8ab43SDavid Matlack 	int r;
45409aa8ab43SDavid Matlack 
45419aa8ab43SDavid Matlack 	if (page_fault_handle_page_track(vcpu, fault))
45429aa8ab43SDavid Matlack 		return RET_PF_EMULATE;
45439aa8ab43SDavid Matlack 
45449aa8ab43SDavid Matlack 	r = fast_page_fault(vcpu, fault);
45459aa8ab43SDavid Matlack 	if (r != RET_PF_INVALID)
45469aa8ab43SDavid Matlack 		return r;
45479aa8ab43SDavid Matlack 
45489aa8ab43SDavid Matlack 	r = mmu_topup_memory_caches(vcpu, false);
45499aa8ab43SDavid Matlack 	if (r)
45509aa8ab43SDavid Matlack 		return r;
45519aa8ab43SDavid Matlack 
45529aa8ab43SDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
45539aa8ab43SDavid Matlack 	if (r != RET_PF_CONTINUE)
45549aa8ab43SDavid Matlack 		return r;
45559aa8ab43SDavid Matlack 
45569aa8ab43SDavid Matlack 	r = RET_PF_RETRY;
45579aa8ab43SDavid Matlack 	read_lock(&vcpu->kvm->mmu_lock);
45589aa8ab43SDavid Matlack 
45599aa8ab43SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
45609aa8ab43SDavid Matlack 		goto out_unlock;
45619aa8ab43SDavid Matlack 
45629aa8ab43SDavid Matlack 	r = kvm_tdp_mmu_map(vcpu, fault);
45639aa8ab43SDavid Matlack 
45649aa8ab43SDavid Matlack out_unlock:
45659aa8ab43SDavid Matlack 	read_unlock(&vcpu->kvm->mmu_lock);
45669aa8ab43SDavid Matlack 	kvm_release_pfn_clean(fault->pfn);
45679aa8ab43SDavid Matlack 	return r;
45689aa8ab43SDavid Matlack }
45699aa8ab43SDavid Matlack #endif
45709aa8ab43SDavid Matlack 
45711affe455SYan Zhao bool __kvm_mmu_honors_guest_mtrrs(bool vm_has_noncoherent_dma)
45721affe455SYan Zhao {
45731affe455SYan Zhao 	/*
45741affe455SYan Zhao 	 * If host MTRRs are ignored (shadow_memtype_mask is non-zero), and the
45751affe455SYan Zhao 	 * VM has non-coherent DMA (DMA doesn't snoop CPU caches), KVM's ABI is
45761affe455SYan Zhao 	 * to honor the memtype from the guest's MTRRs so that guest accesses
45771affe455SYan Zhao 	 * to memory that is DMA'd aren't cached against the guest's wishes.
45781affe455SYan Zhao 	 *
45791affe455SYan Zhao 	 * Note, KVM may still ultimately ignore guest MTRRs for certain PFNs,
45801affe455SYan Zhao 	 * e.g. KVM will force UC memtype for host MMIO.
45811affe455SYan Zhao 	 */
45821affe455SYan Zhao 	return vm_has_noncoherent_dma && shadow_memtype_mask;
45831affe455SYan Zhao }
45841affe455SYan Zhao 
4585c501040aSPaolo Bonzini int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4586c50d8ae3SPaolo Bonzini {
4587d5e90a69SSean Christopherson 	/*
4588d5e90a69SSean Christopherson 	 * If the guest's MTRRs may be used to compute the "real" memtype,
4589d5e90a69SSean Christopherson 	 * restrict the mapping level to ensure KVM uses a consistent memtype
45901affe455SYan Zhao 	 * across the entire mapping.
4591d5e90a69SSean Christopherson 	 */
45921affe455SYan Zhao 	if (kvm_mmu_honors_guest_mtrrs(vcpu->kvm)) {
4593d5e90a69SSean Christopherson 		for ( ; fault->max_level > PG_LEVEL_4K; --fault->max_level) {
45944326e57eSPaolo Bonzini 			int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
4595c667a3baSHou Wenlong 			gfn_t base = gfn_round_for_level(fault->gfn,
4596c667a3baSHou Wenlong 							 fault->max_level);
4597c50d8ae3SPaolo Bonzini 
4598cb9b88c6SSean Christopherson 			if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4599cb9b88c6SSean Christopherson 				break;
4600d5e90a69SSean Christopherson 		}
4601c50d8ae3SPaolo Bonzini 	}
4602c50d8ae3SPaolo Bonzini 
46039aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
46049aa8ab43SDavid Matlack 	if (tdp_mmu_enabled)
46059aa8ab43SDavid Matlack 		return kvm_tdp_mmu_page_fault(vcpu, fault);
46069aa8ab43SDavid Matlack #endif
46079aa8ab43SDavid Matlack 
46084326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
4609c50d8ae3SPaolo Bonzini }
4610c50d8ae3SPaolo Bonzini 
461184a16226SSean Christopherson static void nonpaging_init_context(struct kvm_mmu *context)
4612c50d8ae3SPaolo Bonzini {
4613c50d8ae3SPaolo Bonzini 	context->page_fault = nonpaging_page_fault;
4614c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4615c3c6c9fcSLai Jiangshan 	context->sync_spte = NULL;
4616c50d8ae3SPaolo Bonzini }
4617c50d8ae3SPaolo Bonzini 
4618be01e8e2SSean Christopherson static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
46190be44352SSean Christopherson 				  union kvm_mmu_page_role role)
46200be44352SSean Christopherson {
4621c30e000eSSean Christopherson 	struct kvm_mmu_page *sp;
4622c30e000eSSean Christopherson 
4623c30e000eSSean Christopherson 	if (!VALID_PAGE(root->hpa))
4624c30e000eSSean Christopherson 		return false;
4625c30e000eSSean Christopherson 
4626c30e000eSSean Christopherson 	if (!role.direct && pgd != root->pgd)
4627c30e000eSSean Christopherson 		return false;
4628c30e000eSSean Christopherson 
4629c30e000eSSean Christopherson 	sp = root_to_sp(root->hpa);
4630c30e000eSSean Christopherson 	if (WARN_ON_ONCE(!sp))
4631c30e000eSSean Christopherson 		return false;
4632c30e000eSSean Christopherson 
4633c30e000eSSean Christopherson 	return role.word == sp->role.word;
46340be44352SSean Christopherson }
46350be44352SSean Christopherson 
4636c50d8ae3SPaolo Bonzini /*
46375499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available,
46385499ea73SPaolo Bonzini  * and insert the current root as the MRU in the cache.
46395499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root and
46405499ea73SPaolo Bonzini  * true is returned.
46415499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid, the LRU root is
46425499ea73SPaolo Bonzini  * evicted to make room for the current root, and false is returned.
4643c50d8ae3SPaolo Bonzini  */
46445499ea73SPaolo Bonzini static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
46455499ea73SPaolo Bonzini 					      gpa_t new_pgd,
4646c50d8ae3SPaolo Bonzini 					      union kvm_mmu_page_role new_role)
4647c50d8ae3SPaolo Bonzini {
4648c50d8ae3SPaolo Bonzini 	uint i;
4649c50d8ae3SPaolo Bonzini 
4650b9e5603cSPaolo Bonzini 	if (is_root_usable(&mmu->root, new_pgd, new_role))
46510be44352SSean Christopherson 		return true;
46520be44352SSean Christopherson 
4653c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
46545499ea73SPaolo Bonzini 		/*
46555499ea73SPaolo Bonzini 		 * The swaps end up rotating the cache like this:
46565499ea73SPaolo Bonzini 		 *   C   0 1 2 3   (on entry to the function)
46575499ea73SPaolo Bonzini 		 *   0   C 1 2 3
46585499ea73SPaolo Bonzini 		 *   1   C 0 2 3
46595499ea73SPaolo Bonzini 		 *   2   C 0 1 3
46605499ea73SPaolo Bonzini 		 *   3   C 0 1 2   (on exit from the loop)
46615499ea73SPaolo Bonzini 		 */
4662b9e5603cSPaolo Bonzini 		swap(mmu->root, mmu->prev_roots[i]);
4663b9e5603cSPaolo Bonzini 		if (is_root_usable(&mmu->root, new_pgd, new_role))
46645499ea73SPaolo Bonzini 			return true;
4665c50d8ae3SPaolo Bonzini 	}
4666c50d8ae3SPaolo Bonzini 
46675499ea73SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
46685499ea73SPaolo Bonzini 	return false;
4669c50d8ae3SPaolo Bonzini }
4670c50d8ae3SPaolo Bonzini 
4671c50d8ae3SPaolo Bonzini /*
46725499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available.
46735499ea73SPaolo Bonzini  * On entry, mmu->root is invalid.
46745499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
46755499ea73SPaolo Bonzini  * of the cache becomes invalid, and true is returned.
46765499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid and false is returned.
46775499ea73SPaolo Bonzini  */
46785499ea73SPaolo Bonzini static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
46795499ea73SPaolo Bonzini 					     gpa_t new_pgd,
46805499ea73SPaolo Bonzini 					     union kvm_mmu_page_role new_role)
46815499ea73SPaolo Bonzini {
46825499ea73SPaolo Bonzini 	uint i;
46835499ea73SPaolo Bonzini 
46845499ea73SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
46855499ea73SPaolo Bonzini 		if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
46865499ea73SPaolo Bonzini 			goto hit;
46875499ea73SPaolo Bonzini 
46885499ea73SPaolo Bonzini 	return false;
46895499ea73SPaolo Bonzini 
46905499ea73SPaolo Bonzini hit:
46915499ea73SPaolo Bonzini 	swap(mmu->root, mmu->prev_roots[i]);
46925499ea73SPaolo Bonzini 	/* Bubble up the remaining roots.  */
46935499ea73SPaolo Bonzini 	for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
46945499ea73SPaolo Bonzini 		mmu->prev_roots[i] = mmu->prev_roots[i + 1];
46955499ea73SPaolo Bonzini 	mmu->prev_roots[i].hpa = INVALID_PAGE;
46965499ea73SPaolo Bonzini 	return true;
46975499ea73SPaolo Bonzini }
46985499ea73SPaolo Bonzini 
46995499ea73SPaolo Bonzini static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
47005499ea73SPaolo Bonzini 			    gpa_t new_pgd, union kvm_mmu_page_role new_role)
47015499ea73SPaolo Bonzini {
47025499ea73SPaolo Bonzini 	/*
47030e3223d8SSean Christopherson 	 * Limit reuse to 64-bit hosts+VMs without "special" roots in order to
47040e3223d8SSean Christopherson 	 * avoid having to deal with PDPTEs and other complexities.
4705c50d8ae3SPaolo Bonzini 	 */
4706c5f2d564SSean Christopherson 	if (VALID_PAGE(mmu->root.hpa) && !root_to_sp(mmu->root.hpa))
47075499ea73SPaolo Bonzini 		kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4708c50d8ae3SPaolo Bonzini 
47095499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa))
47105499ea73SPaolo Bonzini 		return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
47115499ea73SPaolo Bonzini 	else
47125499ea73SPaolo Bonzini 		return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4713c50d8ae3SPaolo Bonzini }
4714c50d8ae3SPaolo Bonzini 
4715d2e5f333SPaolo Bonzini void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4716c50d8ae3SPaolo Bonzini {
47170c1c92f1SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
47187a458f0eSPaolo Bonzini 	union kvm_mmu_page_role new_role = mmu->root_role;
47190c1c92f1SPaolo Bonzini 
4720a7e48ef7SWei Liu 	/*
4721a7e48ef7SWei Liu 	 * Return immediately if no usable root was found, kvm_mmu_reload()
4722a7e48ef7SWei Liu 	 * will establish a valid root prior to the next VM-Enter.
4723a7e48ef7SWei Liu 	 */
4724a7e48ef7SWei Liu 	if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role))
4725b869855bSSean Christopherson 		return;
4726c50d8ae3SPaolo Bonzini 
4727c50d8ae3SPaolo Bonzini 	/*
4728b869855bSSean Christopherson 	 * It's possible that the cached previous root page is obsolete because
4729b869855bSSean Christopherson 	 * of a change in the MMU generation number. However, changing the
4730527d5cd7SSean Christopherson 	 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4731527d5cd7SSean Christopherson 	 * which will free the root set here and allocate a new one.
4732b869855bSSean Christopherson 	 */
4733b869855bSSean Christopherson 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4734b869855bSSean Christopherson 
4735b5129100SSean Christopherson 	if (force_flush_and_sync_on_reuse) {
4736b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4737b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4738b5129100SSean Christopherson 	}
4739b869855bSSean Christopherson 
4740b869855bSSean Christopherson 	/*
4741b869855bSSean Christopherson 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4742b869855bSSean Christopherson 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
4743b869855bSSean Christopherson 	 * valid. So clear any cached MMIO info even when we don't need to sync
4744b869855bSSean Christopherson 	 * the shadow page tables.
4745c50d8ae3SPaolo Bonzini 	 */
4746c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4747c50d8ae3SPaolo Bonzini 
4748daa5b6c1SBen Gardon 	/*
4749daa5b6c1SBen Gardon 	 * If this is a direct root page, it doesn't have a write flooding
4750daa5b6c1SBen Gardon 	 * count. Otherwise, clear the write flooding count.
4751daa5b6c1SBen Gardon 	 */
4752c30e000eSSean Christopherson 	if (!new_role.direct) {
4753c30e000eSSean Christopherson 		struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
4754c30e000eSSean Christopherson 
4755c30e000eSSean Christopherson 		if (!WARN_ON_ONCE(!sp))
4756c30e000eSSean Christopherson 			__clear_sp_write_flooding_count(sp);
4757c30e000eSSean Christopherson 	}
4758c50d8ae3SPaolo Bonzini }
4759be01e8e2SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4760c50d8ae3SPaolo Bonzini 
4761c50d8ae3SPaolo Bonzini static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4762c3e5e415SLai Jiangshan 			   unsigned int access)
4763c50d8ae3SPaolo Bonzini {
4764c50d8ae3SPaolo Bonzini 	if (unlikely(is_mmio_spte(*sptep))) {
4765c50d8ae3SPaolo Bonzini 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4766c50d8ae3SPaolo Bonzini 			mmu_spte_clear_no_track(sptep);
4767c50d8ae3SPaolo Bonzini 			return true;
4768c50d8ae3SPaolo Bonzini 		}
4769c50d8ae3SPaolo Bonzini 
4770c50d8ae3SPaolo Bonzini 		mark_mmio_spte(vcpu, sptep, gfn, access);
4771c50d8ae3SPaolo Bonzini 		return true;
4772c50d8ae3SPaolo Bonzini 	}
4773c50d8ae3SPaolo Bonzini 
4774c50d8ae3SPaolo Bonzini 	return false;
4775c50d8ae3SPaolo Bonzini }
4776c50d8ae3SPaolo Bonzini 
4777c50d8ae3SPaolo Bonzini #define PTTYPE_EPT 18 /* arbitrary */
4778c50d8ae3SPaolo Bonzini #define PTTYPE PTTYPE_EPT
4779c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4780c50d8ae3SPaolo Bonzini #undef PTTYPE
4781c50d8ae3SPaolo Bonzini 
4782c50d8ae3SPaolo Bonzini #define PTTYPE 64
4783c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4784c50d8ae3SPaolo Bonzini #undef PTTYPE
4785c50d8ae3SPaolo Bonzini 
4786c50d8ae3SPaolo Bonzini #define PTTYPE 32
4787c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4788c50d8ae3SPaolo Bonzini #undef PTTYPE
4789c50d8ae3SPaolo Bonzini 
4790f3d90f90SSean Christopherson static void __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
4791f3d90f90SSean Christopherson 				    u64 pa_bits_rsvd, int level, bool nx,
4792f3d90f90SSean Christopherson 				    bool gbpages, bool pse, bool amd)
4793c50d8ae3SPaolo Bonzini {
4794c50d8ae3SPaolo Bonzini 	u64 gbpages_bit_rsvd = 0;
4795c50d8ae3SPaolo Bonzini 	u64 nonleaf_bit8_rsvd = 0;
47965b7f575cSSean Christopherson 	u64 high_bits_rsvd;
4797c50d8ae3SPaolo Bonzini 
4798c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = 0;
4799c50d8ae3SPaolo Bonzini 
4800c50d8ae3SPaolo Bonzini 	if (!gbpages)
4801c50d8ae3SPaolo Bonzini 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4802c50d8ae3SPaolo Bonzini 
48035b7f575cSSean Christopherson 	if (level == PT32E_ROOT_LEVEL)
48045b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
48055b7f575cSSean Christopherson 	else
48065b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
48075b7f575cSSean Christopherson 
48085b7f575cSSean Christopherson 	/* Note, NX doesn't exist in PDPTEs, this is handled below. */
48095b7f575cSSean Christopherson 	if (!nx)
48105b7f575cSSean Christopherson 		high_bits_rsvd |= rsvd_bits(63, 63);
48115b7f575cSSean Christopherson 
4812c50d8ae3SPaolo Bonzini 	/*
4813c50d8ae3SPaolo Bonzini 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4814c50d8ae3SPaolo Bonzini 	 * leaf entries) on AMD CPUs only.
4815c50d8ae3SPaolo Bonzini 	 */
4816c50d8ae3SPaolo Bonzini 	if (amd)
4817c50d8ae3SPaolo Bonzini 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4818c50d8ae3SPaolo Bonzini 
4819c50d8ae3SPaolo Bonzini 	switch (level) {
4820c50d8ae3SPaolo Bonzini 	case PT32_ROOT_LEVEL:
4821c50d8ae3SPaolo Bonzini 		/* no rsvd bits for 2 level 4K page table entries */
4822c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4823c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4824c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4825c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4826c50d8ae3SPaolo Bonzini 
4827c50d8ae3SPaolo Bonzini 		if (!pse) {
4828c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4829c50d8ae3SPaolo Bonzini 			break;
4830c50d8ae3SPaolo Bonzini 		}
4831c50d8ae3SPaolo Bonzini 
4832c50d8ae3SPaolo Bonzini 		if (is_cpuid_PSE36())
4833c50d8ae3SPaolo Bonzini 			/* 36bits PSE 4MB page */
4834c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4835c50d8ae3SPaolo Bonzini 		else
4836c50d8ae3SPaolo Bonzini 			/* 32 bits PSE 4MB page */
4837c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4838c50d8ae3SPaolo Bonzini 		break;
4839c50d8ae3SPaolo Bonzini 	case PT32E_ROOT_LEVEL:
48405b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
48415b7f575cSSean Christopherson 						   high_bits_rsvd |
48425b7f575cSSean Christopherson 						   rsvd_bits(5, 8) |
48435b7f575cSSean Christopherson 						   rsvd_bits(1, 2);	/* PDPTE */
48445b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;	/* PDE */
48455b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;	/* PTE */
48465b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4847c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20);	/* large page */
4848c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4849c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4850c50d8ae3SPaolo Bonzini 		break;
4851c50d8ae3SPaolo Bonzini 	case PT64_ROOT_5LEVEL:
48525b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
48535b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
48545b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
4855c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][4] =
4856c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][4];
4857df561f66SGustavo A. R. Silva 		fallthrough;
4858c50d8ae3SPaolo Bonzini 	case PT64_ROOT_4LEVEL:
48595b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
48605b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
48615b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
48625b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
48635b7f575cSSean Christopherson 						   gbpages_bit_rsvd;
48645b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
48655b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4866c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][3] =
4867c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][3];
48685b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
48695b7f575cSSean Christopherson 						   gbpages_bit_rsvd |
4870c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 29);
48715b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4872c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20); /* large page */
4873c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4874c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4875c50d8ae3SPaolo Bonzini 		break;
4876c50d8ae3SPaolo Bonzini 	}
4877c50d8ae3SPaolo Bonzini }
4878c50d8ae3SPaolo Bonzini 
4879c919e881SKai Huang static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4880c50d8ae3SPaolo Bonzini 					struct kvm_mmu *context)
4881c50d8ae3SPaolo Bonzini {
4882b705a277SSean Christopherson 	__reset_rsvds_bits_mask(&context->guest_rsvd_check,
48835b7f575cSSean Christopherson 				vcpu->arch.reserved_gpa_bits,
48844d25502aSPaolo Bonzini 				context->cpu_role.base.level, is_efer_nx(context),
4885ccf31d6eSSean Christopherson 				guest_can_use(vcpu, X86_FEATURE_GBPAGES),
48864e9c0d80SSean Christopherson 				is_cr4_pse(context),
488723493d0aSSean Christopherson 				guest_cpuid_is_amd_or_hygon(vcpu));
4888c50d8ae3SPaolo Bonzini }
4889c50d8ae3SPaolo Bonzini 
4890f3d90f90SSean Christopherson static void __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4891f3d90f90SSean Christopherson 					u64 pa_bits_rsvd, bool execonly,
4892f3d90f90SSean Christopherson 					int huge_page_level)
4893c50d8ae3SPaolo Bonzini {
48945b7f575cSSean Christopherson 	u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
489584ea5c09SLai Jiangshan 	u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
4896c50d8ae3SPaolo Bonzini 	u64 bad_mt_xwr;
4897c50d8ae3SPaolo Bonzini 
489884ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_1G)
489984ea5c09SLai Jiangshan 		large_1g_rsvd = rsvd_bits(7, 7);
490084ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_2M)
490184ea5c09SLai Jiangshan 		large_2m_rsvd = rsvd_bits(7, 7);
490284ea5c09SLai Jiangshan 
49035b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
49045b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
490584ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
490684ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
49075b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4908c50d8ae3SPaolo Bonzini 
4909c50d8ae3SPaolo Bonzini 	/* large page */
4910c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4911c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
491284ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
491384ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
4914c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4915c50d8ae3SPaolo Bonzini 
4916c50d8ae3SPaolo Bonzini 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
4917c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
4918c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
4919c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
4920c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
4921c50d8ae3SPaolo Bonzini 	if (!execonly) {
4922c50d8ae3SPaolo Bonzini 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
4923c50d8ae3SPaolo Bonzini 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4924c50d8ae3SPaolo Bonzini 	}
4925c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
4926c50d8ae3SPaolo Bonzini }
4927c50d8ae3SPaolo Bonzini 
4928c50d8ae3SPaolo Bonzini static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
492984ea5c09SLai Jiangshan 		struct kvm_mmu *context, bool execonly, int huge_page_level)
4930c50d8ae3SPaolo Bonzini {
4931c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
493284ea5c09SLai Jiangshan 				    vcpu->arch.reserved_gpa_bits, execonly,
493384ea5c09SLai Jiangshan 				    huge_page_level);
4934c50d8ae3SPaolo Bonzini }
4935c50d8ae3SPaolo Bonzini 
49366f8e65a6SSean Christopherson static inline u64 reserved_hpa_bits(void)
49376f8e65a6SSean Christopherson {
49386f8e65a6SSean Christopherson 	return rsvd_bits(shadow_phys_bits, 63);
49396f8e65a6SSean Christopherson }
49406f8e65a6SSean Christopherson 
4941c50d8ae3SPaolo Bonzini /*
4942c50d8ae3SPaolo Bonzini  * the page table on host is the shadow page table for the page
4943c50d8ae3SPaolo Bonzini  * table in guest or amd nested guest, its mmu features completely
4944c50d8ae3SPaolo Bonzini  * follow the features in guest.
4945c50d8ae3SPaolo Bonzini  */
494616be1d12SSean Christopherson static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
494716be1d12SSean Christopherson 					struct kvm_mmu *context)
4948c50d8ae3SPaolo Bonzini {
49498c985b2dSSean Christopherson 	/* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
49508c985b2dSSean Christopherson 	bool is_amd = true;
49518c985b2dSSean Christopherson 	/* KVM doesn't use 2-level page tables for the shadow MMU. */
49528c985b2dSSean Christopherson 	bool is_pse = false;
4953c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4954c50d8ae3SPaolo Bonzini 	int i;
4955c50d8ae3SPaolo Bonzini 
4956a972e29cSPaolo Bonzini 	WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
49578c985b2dSSean Christopherson 
4958c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4959b705a277SSean Christopherson 	__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4960a972e29cSPaolo Bonzini 				context->root_role.level,
49617a458f0eSPaolo Bonzini 				context->root_role.efer_nx,
4962ccf31d6eSSean Christopherson 				guest_can_use(vcpu, X86_FEATURE_GBPAGES),
4963ccf31d6eSSean Christopherson 				is_pse, is_amd);
4964c50d8ae3SPaolo Bonzini 
4965c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4966c50d8ae3SPaolo Bonzini 		return;
4967c50d8ae3SPaolo Bonzini 
4968a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
4969e54f1ff2SKai Huang 		/*
4970e54f1ff2SKai Huang 		 * So far shadow_me_value is a constant during KVM's life
4971e54f1ff2SKai Huang 		 * time.  Bits in shadow_me_value are allowed to be set.
4972e54f1ff2SKai Huang 		 * Bits in shadow_me_mask but not in shadow_me_value are
4973e54f1ff2SKai Huang 		 * not allowed to be set.
4974e54f1ff2SKai Huang 		 */
4975e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
4976e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
4977e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
4978e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
4979c50d8ae3SPaolo Bonzini 	}
4980c50d8ae3SPaolo Bonzini 
4981c50d8ae3SPaolo Bonzini }
4982c50d8ae3SPaolo Bonzini 
4983c50d8ae3SPaolo Bonzini static inline bool boot_cpu_is_amd(void)
4984c50d8ae3SPaolo Bonzini {
4985c50d8ae3SPaolo Bonzini 	WARN_ON_ONCE(!tdp_enabled);
4986c50d8ae3SPaolo Bonzini 	return shadow_x_mask == 0;
4987c50d8ae3SPaolo Bonzini }
4988c50d8ae3SPaolo Bonzini 
4989c50d8ae3SPaolo Bonzini /*
4990c50d8ae3SPaolo Bonzini  * the direct page table on host, use as much mmu features as
4991c50d8ae3SPaolo Bonzini  * possible, however, kvm currently does not do execution-protection.
4992c50d8ae3SPaolo Bonzini  */
4993f3d90f90SSean Christopherson static void reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
4994c50d8ae3SPaolo Bonzini {
4995c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4996c50d8ae3SPaolo Bonzini 	int i;
4997c50d8ae3SPaolo Bonzini 
4998c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4999c50d8ae3SPaolo Bonzini 
5000c50d8ae3SPaolo Bonzini 	if (boot_cpu_is_amd())
5001b705a277SSean Christopherson 		__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
50026c6ab524SSean Christopherson 					context->root_role.level, true,
5003c50d8ae3SPaolo Bonzini 					boot_cpu_has(X86_FEATURE_GBPAGES),
50048c985b2dSSean Christopherson 					false, true);
5005c50d8ae3SPaolo Bonzini 	else
5006c50d8ae3SPaolo Bonzini 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
500784ea5c09SLai Jiangshan 					    reserved_hpa_bits(), false,
500884ea5c09SLai Jiangshan 					    max_huge_page_level);
5009c50d8ae3SPaolo Bonzini 
5010c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
5011c50d8ae3SPaolo Bonzini 		return;
5012c50d8ae3SPaolo Bonzini 
5013a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
5014c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
5015c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
5016c50d8ae3SPaolo Bonzini 	}
5017c50d8ae3SPaolo Bonzini }
5018c50d8ae3SPaolo Bonzini 
5019c50d8ae3SPaolo Bonzini /*
5020c50d8ae3SPaolo Bonzini  * as the comments in reset_shadow_zero_bits_mask() except it
5021c50d8ae3SPaolo Bonzini  * is the shadow page table for intel nested guest.
5022c50d8ae3SPaolo Bonzini  */
5023c50d8ae3SPaolo Bonzini static void
5024e8f6e738SJinrong Liang reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
5025c50d8ae3SPaolo Bonzini {
5026c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
502784ea5c09SLai Jiangshan 				    reserved_hpa_bits(), execonly,
502884ea5c09SLai Jiangshan 				    max_huge_page_level);
5029c50d8ae3SPaolo Bonzini }
5030c50d8ae3SPaolo Bonzini 
5031c50d8ae3SPaolo Bonzini #define BYTE_MASK(access) \
5032c50d8ae3SPaolo Bonzini 	((1 & (access) ? 2 : 0) | \
5033c50d8ae3SPaolo Bonzini 	 (2 & (access) ? 4 : 0) | \
5034c50d8ae3SPaolo Bonzini 	 (3 & (access) ? 8 : 0) | \
5035c50d8ae3SPaolo Bonzini 	 (4 & (access) ? 16 : 0) | \
5036c50d8ae3SPaolo Bonzini 	 (5 & (access) ? 32 : 0) | \
5037c50d8ae3SPaolo Bonzini 	 (6 & (access) ? 64 : 0) | \
5038c50d8ae3SPaolo Bonzini 	 (7 & (access) ? 128 : 0))
5039c50d8ae3SPaolo Bonzini 
5040c50d8ae3SPaolo Bonzini 
5041c596f147SSean Christopherson static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
5042c50d8ae3SPaolo Bonzini {
5043c50d8ae3SPaolo Bonzini 	unsigned byte;
5044c50d8ae3SPaolo Bonzini 
5045c50d8ae3SPaolo Bonzini 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
5046c50d8ae3SPaolo Bonzini 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
5047c50d8ae3SPaolo Bonzini 	const u8 u = BYTE_MASK(ACC_USER_MASK);
5048c50d8ae3SPaolo Bonzini 
5049c596f147SSean Christopherson 	bool cr4_smep = is_cr4_smep(mmu);
5050c596f147SSean Christopherson 	bool cr4_smap = is_cr4_smap(mmu);
5051c596f147SSean Christopherson 	bool cr0_wp = is_cr0_wp(mmu);
505290599c28SSean Christopherson 	bool efer_nx = is_efer_nx(mmu);
5053c50d8ae3SPaolo Bonzini 
5054c50d8ae3SPaolo Bonzini 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
5055c50d8ae3SPaolo Bonzini 		unsigned pfec = byte << 1;
5056c50d8ae3SPaolo Bonzini 
5057c50d8ae3SPaolo Bonzini 		/*
5058c50d8ae3SPaolo Bonzini 		 * Each "*f" variable has a 1 bit for each UWX value
5059c50d8ae3SPaolo Bonzini 		 * that causes a fault with the given PFEC.
5060c50d8ae3SPaolo Bonzini 		 */
5061c50d8ae3SPaolo Bonzini 
5062c50d8ae3SPaolo Bonzini 		/* Faults from writes to non-writable pages */
5063c50d8ae3SPaolo Bonzini 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
5064c50d8ae3SPaolo Bonzini 		/* Faults from user mode accesses to supervisor pages */
5065c50d8ae3SPaolo Bonzini 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
5066c50d8ae3SPaolo Bonzini 		/* Faults from fetches of non-executable pages*/
5067c50d8ae3SPaolo Bonzini 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
5068c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode fetches of user pages */
5069c50d8ae3SPaolo Bonzini 		u8 smepf = 0;
5070c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode accesses of user pages */
5071c50d8ae3SPaolo Bonzini 		u8 smapf = 0;
5072c50d8ae3SPaolo Bonzini 
5073c50d8ae3SPaolo Bonzini 		if (!ept) {
5074c50d8ae3SPaolo Bonzini 			/* Faults from kernel mode accesses to user pages */
5075c50d8ae3SPaolo Bonzini 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
5076c50d8ae3SPaolo Bonzini 
5077c50d8ae3SPaolo Bonzini 			/* Not really needed: !nx will cause pte.nx to fault */
507890599c28SSean Christopherson 			if (!efer_nx)
5079c50d8ae3SPaolo Bonzini 				ff = 0;
5080c50d8ae3SPaolo Bonzini 
5081c50d8ae3SPaolo Bonzini 			/* Allow supervisor writes if !cr0.wp */
5082c50d8ae3SPaolo Bonzini 			if (!cr0_wp)
5083c50d8ae3SPaolo Bonzini 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
5084c50d8ae3SPaolo Bonzini 
5085c50d8ae3SPaolo Bonzini 			/* Disallow supervisor fetches of user code if cr4.smep */
5086c50d8ae3SPaolo Bonzini 			if (cr4_smep)
5087c50d8ae3SPaolo Bonzini 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
5088c50d8ae3SPaolo Bonzini 
5089c50d8ae3SPaolo Bonzini 			/*
5090c50d8ae3SPaolo Bonzini 			 * SMAP:kernel-mode data accesses from user-mode
5091c50d8ae3SPaolo Bonzini 			 * mappings should fault. A fault is considered
5092c50d8ae3SPaolo Bonzini 			 * as a SMAP violation if all of the following
5093c50d8ae3SPaolo Bonzini 			 * conditions are true:
5094c50d8ae3SPaolo Bonzini 			 *   - X86_CR4_SMAP is set in CR4
5095c50d8ae3SPaolo Bonzini 			 *   - A user page is accessed
5096c50d8ae3SPaolo Bonzini 			 *   - The access is not a fetch
50974f4aa80eSLai Jiangshan 			 *   - The access is supervisor mode
50984f4aa80eSLai Jiangshan 			 *   - If implicit supervisor access or X86_EFLAGS_AC is clear
5099c50d8ae3SPaolo Bonzini 			 *
510094b4a2f1SLai Jiangshan 			 * Here, we cover the first four conditions.
510194b4a2f1SLai Jiangshan 			 * The fifth is computed dynamically in permission_fault();
5102c50d8ae3SPaolo Bonzini 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
5103c50d8ae3SPaolo Bonzini 			 * *not* subject to SMAP restrictions.
5104c50d8ae3SPaolo Bonzini 			 */
5105c50d8ae3SPaolo Bonzini 			if (cr4_smap)
5106c50d8ae3SPaolo Bonzini 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
5107c50d8ae3SPaolo Bonzini 		}
5108c50d8ae3SPaolo Bonzini 
5109c50d8ae3SPaolo Bonzini 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
5110c50d8ae3SPaolo Bonzini 	}
5111c50d8ae3SPaolo Bonzini }
5112c50d8ae3SPaolo Bonzini 
5113c50d8ae3SPaolo Bonzini /*
5114c50d8ae3SPaolo Bonzini * PKU is an additional mechanism by which the paging controls access to
5115c50d8ae3SPaolo Bonzini * user-mode addresses based on the value in the PKRU register.  Protection
5116c50d8ae3SPaolo Bonzini * key violations are reported through a bit in the page fault error code.
5117c50d8ae3SPaolo Bonzini * Unlike other bits of the error code, the PK bit is not known at the
5118c50d8ae3SPaolo Bonzini * call site of e.g. gva_to_gpa; it must be computed directly in
5119c50d8ae3SPaolo Bonzini * permission_fault based on two bits of PKRU, on some machine state (CR4,
5120c50d8ae3SPaolo Bonzini * CR0, EFER, CPL), and on other bits of the error code and the page tables.
5121c50d8ae3SPaolo Bonzini *
5122c50d8ae3SPaolo Bonzini * In particular the following conditions come from the error code, the
5123c50d8ae3SPaolo Bonzini * page tables and the machine state:
5124c50d8ae3SPaolo Bonzini * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
5125c50d8ae3SPaolo Bonzini * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
5126c50d8ae3SPaolo Bonzini * - PK is always zero if U=0 in the page tables
5127c50d8ae3SPaolo Bonzini * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
5128c50d8ae3SPaolo Bonzini *
5129c50d8ae3SPaolo Bonzini * The PKRU bitmask caches the result of these four conditions.  The error
5130c50d8ae3SPaolo Bonzini * code (minus the P bit) and the page table's U bit form an index into the
5131c50d8ae3SPaolo Bonzini * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
5132c50d8ae3SPaolo Bonzini * with the two bits of the PKRU register corresponding to the protection key.
5133c50d8ae3SPaolo Bonzini * For the first three conditions above the bits will be 00, thus masking
5134c50d8ae3SPaolo Bonzini * away both AD and WD.  For all reads or if the last condition holds, WD
5135c50d8ae3SPaolo Bonzini * only will be masked away.
5136c50d8ae3SPaolo Bonzini */
51372e4c0661SSean Christopherson static void update_pkru_bitmask(struct kvm_mmu *mmu)
5138c50d8ae3SPaolo Bonzini {
5139c50d8ae3SPaolo Bonzini 	unsigned bit;
5140c50d8ae3SPaolo Bonzini 	bool wp;
5141c50d8ae3SPaolo Bonzini 
5142c50d8ae3SPaolo Bonzini 	mmu->pkru_mask = 0;
5143a3ca5281SChenyi Qiang 
5144a3ca5281SChenyi Qiang 	if (!is_cr4_pke(mmu))
5145c50d8ae3SPaolo Bonzini 		return;
5146c50d8ae3SPaolo Bonzini 
51472e4c0661SSean Christopherson 	wp = is_cr0_wp(mmu);
5148c50d8ae3SPaolo Bonzini 
5149c50d8ae3SPaolo Bonzini 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5150c50d8ae3SPaolo Bonzini 		unsigned pfec, pkey_bits;
5151c50d8ae3SPaolo Bonzini 		bool check_pkey, check_write, ff, uf, wf, pte_user;
5152c50d8ae3SPaolo Bonzini 
5153c50d8ae3SPaolo Bonzini 		pfec = bit << 1;
5154c50d8ae3SPaolo Bonzini 		ff = pfec & PFERR_FETCH_MASK;
5155c50d8ae3SPaolo Bonzini 		uf = pfec & PFERR_USER_MASK;
5156c50d8ae3SPaolo Bonzini 		wf = pfec & PFERR_WRITE_MASK;
5157c50d8ae3SPaolo Bonzini 
5158c50d8ae3SPaolo Bonzini 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
5159c50d8ae3SPaolo Bonzini 		pte_user = pfec & PFERR_RSVD_MASK;
5160c50d8ae3SPaolo Bonzini 
5161c50d8ae3SPaolo Bonzini 		/*
5162c50d8ae3SPaolo Bonzini 		 * Only need to check the access which is not an
5163c50d8ae3SPaolo Bonzini 		 * instruction fetch and is to a user page.
5164c50d8ae3SPaolo Bonzini 		 */
5165c50d8ae3SPaolo Bonzini 		check_pkey = (!ff && pte_user);
5166c50d8ae3SPaolo Bonzini 		/*
5167c50d8ae3SPaolo Bonzini 		 * write access is controlled by PKRU if it is a
5168c50d8ae3SPaolo Bonzini 		 * user access or CR0.WP = 1.
5169c50d8ae3SPaolo Bonzini 		 */
5170c50d8ae3SPaolo Bonzini 		check_write = check_pkey && wf && (uf || wp);
5171c50d8ae3SPaolo Bonzini 
5172c50d8ae3SPaolo Bonzini 		/* PKRU.AD stops both read and write access. */
5173c50d8ae3SPaolo Bonzini 		pkey_bits = !!check_pkey;
5174c50d8ae3SPaolo Bonzini 		/* PKRU.WD stops write access. */
5175c50d8ae3SPaolo Bonzini 		pkey_bits |= (!!check_write) << 1;
5176c50d8ae3SPaolo Bonzini 
5177c50d8ae3SPaolo Bonzini 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5178c50d8ae3SPaolo Bonzini 	}
5179c50d8ae3SPaolo Bonzini }
5180c50d8ae3SPaolo Bonzini 
5181533f9a4bSSean Christopherson static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5182533f9a4bSSean Christopherson 					struct kvm_mmu *mmu)
5183c50d8ae3SPaolo Bonzini {
5184533f9a4bSSean Christopherson 	if (!is_cr0_pg(mmu))
5185533f9a4bSSean Christopherson 		return;
5186c50d8ae3SPaolo Bonzini 
5187c919e881SKai Huang 	reset_guest_rsvds_bits_mask(vcpu, mmu);
5188533f9a4bSSean Christopherson 	update_permission_bitmask(mmu, false);
5189533f9a4bSSean Christopherson 	update_pkru_bitmask(mmu);
5190c50d8ae3SPaolo Bonzini }
5191c50d8ae3SPaolo Bonzini 
5192fe660f72SSean Christopherson static void paging64_init_context(struct kvm_mmu *context)
5193c50d8ae3SPaolo Bonzini {
5194c50d8ae3SPaolo Bonzini 	context->page_fault = paging64_page_fault;
5195c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging64_gva_to_gpa;
5196c3c6c9fcSLai Jiangshan 	context->sync_spte = paging64_sync_spte;
5197c50d8ae3SPaolo Bonzini }
5198c50d8ae3SPaolo Bonzini 
519984a16226SSean Christopherson static void paging32_init_context(struct kvm_mmu *context)
5200c50d8ae3SPaolo Bonzini {
5201c50d8ae3SPaolo Bonzini 	context->page_fault = paging32_page_fault;
5202c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging32_gva_to_gpa;
5203c3c6c9fcSLai Jiangshan 	context->sync_spte = paging32_sync_spte;
5204c50d8ae3SPaolo Bonzini }
5205c50d8ae3SPaolo Bonzini 
5206f3d90f90SSean Christopherson static union kvm_cpu_role kvm_calc_cpu_role(struct kvm_vcpu *vcpu,
5207f3d90f90SSean Christopherson 					    const struct kvm_mmu_role_regs *regs)
5208e5ed0fb0SPaolo Bonzini {
52097a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5210e5ed0fb0SPaolo Bonzini 
5211e5ed0fb0SPaolo Bonzini 	role.base.access = ACC_ALL;
5212e5ed0fb0SPaolo Bonzini 	role.base.smm = is_smm(vcpu);
5213e5ed0fb0SPaolo Bonzini 	role.base.guest_mode = is_guest_mode(vcpu);
5214e5ed0fb0SPaolo Bonzini 	role.ext.valid = 1;
5215e5ed0fb0SPaolo Bonzini 
5216e5ed0fb0SPaolo Bonzini 	if (!____is_cr0_pg(regs)) {
5217e5ed0fb0SPaolo Bonzini 		role.base.direct = 1;
5218e5ed0fb0SPaolo Bonzini 		return role;
5219e5ed0fb0SPaolo Bonzini 	}
5220e5ed0fb0SPaolo Bonzini 
5221e5ed0fb0SPaolo Bonzini 	role.base.efer_nx = ____is_efer_nx(regs);
5222e5ed0fb0SPaolo Bonzini 	role.base.cr0_wp = ____is_cr0_wp(regs);
5223e5ed0fb0SPaolo Bonzini 	role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5224e5ed0fb0SPaolo Bonzini 	role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5225e5ed0fb0SPaolo Bonzini 	role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
522660f3cb60SPaolo Bonzini 
522760f3cb60SPaolo Bonzini 	if (____is_efer_lma(regs))
522860f3cb60SPaolo Bonzini 		role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
522960f3cb60SPaolo Bonzini 							: PT64_ROOT_4LEVEL;
523060f3cb60SPaolo Bonzini 	else if (____is_cr4_pae(regs))
523160f3cb60SPaolo Bonzini 		role.base.level = PT32E_ROOT_LEVEL;
523260f3cb60SPaolo Bonzini 	else
523360f3cb60SPaolo Bonzini 		role.base.level = PT32_ROOT_LEVEL;
5234e5ed0fb0SPaolo Bonzini 
5235e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smep = ____is_cr4_smep(regs);
5236e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smap = ____is_cr4_smap(regs);
5237e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pse = ____is_cr4_pse(regs);
5238e5ed0fb0SPaolo Bonzini 
5239e5ed0fb0SPaolo Bonzini 	/* PKEY and LA57 are active iff long mode is active. */
5240e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5241e5ed0fb0SPaolo Bonzini 	role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5242e5ed0fb0SPaolo Bonzini 	role.ext.efer_lma = ____is_efer_lma(regs);
5243e5ed0fb0SPaolo Bonzini 	return role;
5244e5ed0fb0SPaolo Bonzini }
5245e5ed0fb0SPaolo Bonzini 
5246cf9f4c0eSSean Christopherson void __kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
5247cf9f4c0eSSean Christopherson 					struct kvm_mmu *mmu)
5248cf9f4c0eSSean Christopherson {
5249cf9f4c0eSSean Christopherson 	const bool cr0_wp = kvm_is_cr0_bit_set(vcpu, X86_CR0_WP);
5250cf9f4c0eSSean Christopherson 
5251cf9f4c0eSSean Christopherson 	BUILD_BUG_ON((KVM_MMU_CR0_ROLE_BITS & KVM_POSSIBLE_CR0_GUEST_BITS) != X86_CR0_WP);
5252cf9f4c0eSSean Christopherson 	BUILD_BUG_ON((KVM_MMU_CR4_ROLE_BITS & KVM_POSSIBLE_CR4_GUEST_BITS));
5253cf9f4c0eSSean Christopherson 
5254cf9f4c0eSSean Christopherson 	if (is_cr0_wp(mmu) == cr0_wp)
5255cf9f4c0eSSean Christopherson 		return;
5256cf9f4c0eSSean Christopherson 
5257cf9f4c0eSSean Christopherson 	mmu->cpu_role.base.cr0_wp = cr0_wp;
5258cf9f4c0eSSean Christopherson 	reset_guest_paging_metadata(vcpu, mmu);
5259cf9f4c0eSSean Christopherson }
5260cf9f4c0eSSean Christopherson 
5261d468d94bSSean Christopherson static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5262d468d94bSSean Christopherson {
5263746700d2SWei Huang 	/* tdp_root_level is architecture forced level, use it if nonzero */
5264746700d2SWei Huang 	if (tdp_root_level)
5265746700d2SWei Huang 		return tdp_root_level;
5266746700d2SWei Huang 
5267d468d94bSSean Christopherson 	/* Use 5-level TDP if and only if it's useful/necessary. */
526883013059SSean Christopherson 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5269d468d94bSSean Christopherson 		return 4;
5270d468d94bSSean Christopherson 
527183013059SSean Christopherson 	return max_tdp_level;
5272d468d94bSSean Christopherson }
5273d468d94bSSean Christopherson 
52747a458f0eSPaolo Bonzini static union kvm_mmu_page_role
52758626c120SSean Christopherson kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
52767a7ae829SPaolo Bonzini 				union kvm_cpu_role cpu_role)
5277c50d8ae3SPaolo Bonzini {
52787a458f0eSPaolo Bonzini 	union kvm_mmu_page_role role = {0};
5279c50d8ae3SPaolo Bonzini 
52807a458f0eSPaolo Bonzini 	role.access = ACC_ALL;
52817a458f0eSPaolo Bonzini 	role.cr0_wp = true;
52827a458f0eSPaolo Bonzini 	role.efer_nx = true;
52837a458f0eSPaolo Bonzini 	role.smm = cpu_role.base.smm;
52847a458f0eSPaolo Bonzini 	role.guest_mode = cpu_role.base.guest_mode;
528554275f74SSean Christopherson 	role.ad_disabled = !kvm_ad_enabled();
52867a458f0eSPaolo Bonzini 	role.level = kvm_mmu_get_tdp_level(vcpu);
52877a458f0eSPaolo Bonzini 	role.direct = true;
52887a458f0eSPaolo Bonzini 	role.has_4_byte_gpte = false;
5289c50d8ae3SPaolo Bonzini 
5290c50d8ae3SPaolo Bonzini 	return role;
5291c50d8ae3SPaolo Bonzini }
5292c50d8ae3SPaolo Bonzini 
529339e7e2bfSPaolo Bonzini static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5294a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5295c50d8ae3SPaolo Bonzini {
52968c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
52977a458f0eSPaolo Bonzini 	union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5298c50d8ae3SPaolo Bonzini 
5299e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
53007a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
5301c50d8ae3SPaolo Bonzini 		return;
5302c50d8ae3SPaolo Bonzini 
5303e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
53047a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
53057a02674dSSean Christopherson 	context->page_fault = kvm_tdp_page_fault;
5306c3c6c9fcSLai Jiangshan 	context->sync_spte = NULL;
53072fdcc1b3SPaolo Bonzini 	context->get_guest_pgd = get_guest_cr3;
5308c50d8ae3SPaolo Bonzini 	context->get_pdptr = kvm_pdptr_read;
5309c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5310c50d8ae3SPaolo Bonzini 
531136f26787SSean Christopherson 	if (!is_cr0_pg(context))
5312c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = nonpaging_gva_to_gpa;
531336f26787SSean Christopherson 	else if (is_cr4_pae(context))
5314c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging64_gva_to_gpa;
5315f4bd6f73SSean Christopherson 	else
5316c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging32_gva_to_gpa;
5317c50d8ae3SPaolo Bonzini 
5318533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5319e8f6e738SJinrong Liang 	reset_tdp_shadow_zero_bits_mask(context);
5320c50d8ae3SPaolo Bonzini }
5321c50d8ae3SPaolo Bonzini 
53228c008659SPaolo Bonzini static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
53237a7ae829SPaolo Bonzini 				    union kvm_cpu_role cpu_role,
53247a458f0eSPaolo Bonzini 				    union kvm_mmu_page_role root_role)
5325c50d8ae3SPaolo Bonzini {
5326e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
53277a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
532818db1b17SSean Christopherson 		return;
5329c50d8ae3SPaolo Bonzini 
5330e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
53317a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
533218db1b17SSean Christopherson 
533336f26787SSean Christopherson 	if (!is_cr0_pg(context))
533484a16226SSean Christopherson 		nonpaging_init_context(context);
533536f26787SSean Christopherson 	else if (is_cr4_pae(context))
5336fe660f72SSean Christopherson 		paging64_init_context(context);
5337c50d8ae3SPaolo Bonzini 	else
533884a16226SSean Christopherson 		paging32_init_context(context);
5339c50d8ae3SPaolo Bonzini 
5340533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5341c50d8ae3SPaolo Bonzini 	reset_shadow_zero_bits_mask(vcpu, context);
5342c50d8ae3SPaolo Bonzini }
53430f04a2acSVitaly Kuznetsov 
5344594e91a1SSean Christopherson static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5345a7f1de9bSPaolo Bonzini 				union kvm_cpu_role cpu_role)
53460f04a2acSVitaly Kuznetsov {
53478c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
534856b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
534956b321f9SPaolo Bonzini 
535056b321f9SPaolo Bonzini 	root_role = cpu_role.base;
535156b321f9SPaolo Bonzini 
535256b321f9SPaolo Bonzini 	/* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
535356b321f9SPaolo Bonzini 	root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
535456b321f9SPaolo Bonzini 
535556b321f9SPaolo Bonzini 	/*
535656b321f9SPaolo Bonzini 	 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
535756b321f9SPaolo Bonzini 	 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
535856b321f9SPaolo Bonzini 	 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
535956b321f9SPaolo Bonzini 	 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
536056b321f9SPaolo Bonzini 	 * The iTLB multi-hit workaround can be toggled at any time, so assume
536156b321f9SPaolo Bonzini 	 * NX can be used by any non-nested shadow MMU to avoid having to reset
536256b321f9SPaolo Bonzini 	 * MMU contexts.
536356b321f9SPaolo Bonzini 	 */
536456b321f9SPaolo Bonzini 	root_role.efer_nx = true;
53650f04a2acSVitaly Kuznetsov 
53667a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
53670f04a2acSVitaly Kuznetsov }
53680f04a2acSVitaly Kuznetsov 
5369dbc4739bSSean Christopherson void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5370dbc4739bSSean Christopherson 			     unsigned long cr4, u64 efer, gpa_t nested_cr3)
53710f04a2acSVitaly Kuznetsov {
53728c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5373594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
5374594e91a1SSean Christopherson 		.cr0 = cr0,
537528f091bcSPaolo Bonzini 		.cr4 = cr4 & ~X86_CR4_PKE,
5376594e91a1SSean Christopherson 		.efer = efer,
5377594e91a1SSean Christopherson 	};
53787a7ae829SPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
537956b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
538056b321f9SPaolo Bonzini 
538156b321f9SPaolo Bonzini 	/* NPT requires CR0.PG=1. */
538256b321f9SPaolo Bonzini 	WARN_ON_ONCE(cpu_role.base.direct);
538356b321f9SPaolo Bonzini 
538456b321f9SPaolo Bonzini 	root_role = cpu_role.base;
538556b321f9SPaolo Bonzini 	root_role.level = kvm_mmu_get_tdp_level(vcpu);
538684e5ffd0SLai Jiangshan 	if (root_role.level == PT64_ROOT_5LEVEL &&
538784e5ffd0SLai Jiangshan 	    cpu_role.base.level == PT64_ROOT_4LEVEL)
538884e5ffd0SLai Jiangshan 		root_role.passthrough = 1;
53890f04a2acSVitaly Kuznetsov 
53907a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5391d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, nested_cr3);
53920f04a2acSVitaly Kuznetsov }
53930f04a2acSVitaly Kuznetsov EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5394c50d8ae3SPaolo Bonzini 
53957a7ae829SPaolo Bonzini static union kvm_cpu_role
5396c50d8ae3SPaolo Bonzini kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5397bb1fcc70SSean Christopherson 				   bool execonly, u8 level)
5398c50d8ae3SPaolo Bonzini {
53997a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5400c50d8ae3SPaolo Bonzini 
5401daed87b8SPaolo Bonzini 	/*
5402daed87b8SPaolo Bonzini 	 * KVM does not support SMM transfer monitors, and consequently does not
5403daed87b8SPaolo Bonzini 	 * support the "entry to SMM" control either.  role.base.smm is always 0.
5404daed87b8SPaolo Bonzini 	 */
5405daed87b8SPaolo Bonzini 	WARN_ON_ONCE(is_smm(vcpu));
5406bb1fcc70SSean Christopherson 	role.base.level = level;
5407bb3b394dSLai Jiangshan 	role.base.has_4_byte_gpte = false;
5408c50d8ae3SPaolo Bonzini 	role.base.direct = false;
5409c50d8ae3SPaolo Bonzini 	role.base.ad_disabled = !accessed_dirty;
5410c50d8ae3SPaolo Bonzini 	role.base.guest_mode = true;
5411c50d8ae3SPaolo Bonzini 	role.base.access = ACC_ALL;
5412c50d8ae3SPaolo Bonzini 
5413cd6767c3SSean Christopherson 	role.ext.word = 0;
5414c50d8ae3SPaolo Bonzini 	role.ext.execonly = execonly;
5415cd6767c3SSean Christopherson 	role.ext.valid = 1;
5416c50d8ae3SPaolo Bonzini 
5417c50d8ae3SPaolo Bonzini 	return role;
5418c50d8ae3SPaolo Bonzini }
5419c50d8ae3SPaolo Bonzini 
5420c50d8ae3SPaolo Bonzini void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5421cc022ae1SLai Jiangshan 			     int huge_page_level, bool accessed_dirty,
5422cc022ae1SLai Jiangshan 			     gpa_t new_eptp)
5423c50d8ae3SPaolo Bonzini {
54248c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5425bb1fcc70SSean Christopherson 	u8 level = vmx_eptp_page_walk_level(new_eptp);
54267a7ae829SPaolo Bonzini 	union kvm_cpu_role new_mode =
5427c50d8ae3SPaolo Bonzini 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5428bb1fcc70SSean Christopherson 						   execonly, level);
5429c50d8ae3SPaolo Bonzini 
5430e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 != context->cpu_role.as_u64) {
5431e5ed0fb0SPaolo Bonzini 		/* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5432e5ed0fb0SPaolo Bonzini 		context->cpu_role.as_u64 = new_mode.as_u64;
54337a458f0eSPaolo Bonzini 		context->root_role.word = new_mode.base.word;
543418db1b17SSean Christopherson 
5435c50d8ae3SPaolo Bonzini 		context->page_fault = ept_page_fault;
5436c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = ept_gva_to_gpa;
5437c3c6c9fcSLai Jiangshan 		context->sync_spte = ept_sync_spte;
5438347a0d0dSPaolo Bonzini 
5439c596f147SSean Christopherson 		update_permission_bitmask(context, true);
544028f091bcSPaolo Bonzini 		context->pkru_mask = 0;
5441cc022ae1SLai Jiangshan 		reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5442e8f6e738SJinrong Liang 		reset_ept_shadow_zero_bits_mask(context, execonly);
5443c50d8ae3SPaolo Bonzini 	}
54443cffc89dSPaolo Bonzini 
5445d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, new_eptp);
54463cffc89dSPaolo Bonzini }
5447c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5448c50d8ae3SPaolo Bonzini 
544939e7e2bfSPaolo Bonzini static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5450a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5451c50d8ae3SPaolo Bonzini {
54528c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5453c50d8ae3SPaolo Bonzini 
5454a7f1de9bSPaolo Bonzini 	kvm_init_shadow_mmu(vcpu, cpu_role);
5455929d1cfaSPaolo Bonzini 
54562fdcc1b3SPaolo Bonzini 	context->get_guest_pgd     = get_guest_cr3;
5457c50d8ae3SPaolo Bonzini 	context->get_pdptr         = kvm_pdptr_read;
5458c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5459c50d8ae3SPaolo Bonzini }
5460c50d8ae3SPaolo Bonzini 
546139e7e2bfSPaolo Bonzini static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5462a7f1de9bSPaolo Bonzini 				union kvm_cpu_role new_mode)
5463c50d8ae3SPaolo Bonzini {
5464c50d8ae3SPaolo Bonzini 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5465c50d8ae3SPaolo Bonzini 
5466e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5467c50d8ae3SPaolo Bonzini 		return;
5468c50d8ae3SPaolo Bonzini 
5469e5ed0fb0SPaolo Bonzini 	g_context->cpu_role.as_u64   = new_mode.as_u64;
54702fdcc1b3SPaolo Bonzini 	g_context->get_guest_pgd     = get_guest_cr3;
5471c50d8ae3SPaolo Bonzini 	g_context->get_pdptr         = kvm_pdptr_read;
5472c50d8ae3SPaolo Bonzini 	g_context->inject_page_fault = kvm_inject_page_fault;
5473c50d8ae3SPaolo Bonzini 
5474c50d8ae3SPaolo Bonzini 	/*
54755efac074SPaolo Bonzini 	 * L2 page tables are never shadowed, so there is no need to sync
54765efac074SPaolo Bonzini 	 * SPTEs.
54775efac074SPaolo Bonzini 	 */
54789fd4a4e3SLai Jiangshan 	g_context->sync_spte         = NULL;
54795efac074SPaolo Bonzini 
54805efac074SPaolo Bonzini 	/*
5481c50d8ae3SPaolo Bonzini 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5482c50d8ae3SPaolo Bonzini 	 * L1's nested page tables (e.g. EPT12). The nested translation
5483c50d8ae3SPaolo Bonzini 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5484c50d8ae3SPaolo Bonzini 	 * L2's page tables as the first level of translation and L1's
5485c50d8ae3SPaolo Bonzini 	 * nested page tables as the second level of translation. Basically
5486c50d8ae3SPaolo Bonzini 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5487c50d8ae3SPaolo Bonzini 	 */
5488fa4b5588SSean Christopherson 	if (!is_paging(vcpu))
54891f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5490fa4b5588SSean Christopherson 	else if (is_long_mode(vcpu))
54911f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5492fa4b5588SSean Christopherson 	else if (is_pae(vcpu))
54931f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5494fa4b5588SSean Christopherson 	else
54951f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging32_gva_to_gpa;
5496fa4b5588SSean Christopherson 
5497533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, g_context);
5498c50d8ae3SPaolo Bonzini }
5499c50d8ae3SPaolo Bonzini 
5500c9060662SSean Christopherson void kvm_init_mmu(struct kvm_vcpu *vcpu)
5501c50d8ae3SPaolo Bonzini {
550239e7e2bfSPaolo Bonzini 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5503a7f1de9bSPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
550439e7e2bfSPaolo Bonzini 
5505c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
5506a7f1de9bSPaolo Bonzini 		init_kvm_nested_mmu(vcpu, cpu_role);
5507c50d8ae3SPaolo Bonzini 	else if (tdp_enabled)
5508a7f1de9bSPaolo Bonzini 		init_kvm_tdp_mmu(vcpu, cpu_role);
5509c50d8ae3SPaolo Bonzini 	else
5510a7f1de9bSPaolo Bonzini 		init_kvm_softmmu(vcpu, cpu_role);
5511c50d8ae3SPaolo Bonzini }
5512c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_mmu);
5513c50d8ae3SPaolo Bonzini 
551449c6f875SSean Christopherson void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
551549c6f875SSean Christopherson {
551649c6f875SSean Christopherson 	/*
551749c6f875SSean Christopherson 	 * Invalidate all MMU roles to force them to reinitialize as CPUID
551849c6f875SSean Christopherson 	 * information is factored into reserved bit calculations.
5519feb627e8SVitaly Kuznetsov 	 *
5520feb627e8SVitaly Kuznetsov 	 * Correctly handling multiple vCPU models with respect to paging and
5521feb627e8SVitaly Kuznetsov 	 * physical address properties) in a single VM would require tracking
5522feb627e8SVitaly Kuznetsov 	 * all relevant CPUID information in kvm_mmu_page_role. That is very
5523feb627e8SVitaly Kuznetsov 	 * undesirable as it would increase the memory requirements for
5524338068b5SSean Christopherson 	 * gfn_write_track (see struct kvm_mmu_page_role comments).  For now
5525338068b5SSean Christopherson 	 * that problem is swept under the rug; KVM's CPUID API is horrific and
5526feb627e8SVitaly Kuznetsov 	 * it's all but impossible to solve it without introducing a new API.
552749c6f875SSean Christopherson 	 */
55287a458f0eSPaolo Bonzini 	vcpu->arch.root_mmu.root_role.word = 0;
55297a458f0eSPaolo Bonzini 	vcpu->arch.guest_mmu.root_role.word = 0;
55307a458f0eSPaolo Bonzini 	vcpu->arch.nested_mmu.root_role.word = 0;
5531e5ed0fb0SPaolo Bonzini 	vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5532e5ed0fb0SPaolo Bonzini 	vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5533e5ed0fb0SPaolo Bonzini 	vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
553449c6f875SSean Christopherson 	kvm_mmu_reset_context(vcpu);
553563f5a190SSean Christopherson 
553663f5a190SSean Christopherson 	/*
5537feb627e8SVitaly Kuznetsov 	 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5538feb627e8SVitaly Kuznetsov 	 * kvm_arch_vcpu_ioctl().
553963f5a190SSean Christopherson 	 */
5540fb3146b4SSean Christopherson 	KVM_BUG_ON(kvm_vcpu_has_run(vcpu), vcpu->kvm);
554149c6f875SSean Christopherson }
554249c6f875SSean Christopherson 
5543c50d8ae3SPaolo Bonzini void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5544c50d8ae3SPaolo Bonzini {
5545c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
5546c9060662SSean Christopherson 	kvm_init_mmu(vcpu);
5547c50d8ae3SPaolo Bonzini }
5548c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5549c50d8ae3SPaolo Bonzini 
5550c50d8ae3SPaolo Bonzini int kvm_mmu_load(struct kvm_vcpu *vcpu)
5551c50d8ae3SPaolo Bonzini {
5552c50d8ae3SPaolo Bonzini 	int r;
5553c50d8ae3SPaolo Bonzini 
5554347a0d0dSPaolo Bonzini 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5555c50d8ae3SPaolo Bonzini 	if (r)
5556c50d8ae3SPaolo Bonzini 		goto out;
5557748e52b9SSean Christopherson 	r = mmu_alloc_special_roots(vcpu);
5558c50d8ae3SPaolo Bonzini 	if (r)
5559c50d8ae3SPaolo Bonzini 		goto out;
5560347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
55616e6ec584SSean Christopherson 		r = mmu_alloc_direct_roots(vcpu);
55626e6ec584SSean Christopherson 	else
55636e6ec584SSean Christopherson 		r = mmu_alloc_shadow_roots(vcpu);
5564c50d8ae3SPaolo Bonzini 	if (r)
5565c50d8ae3SPaolo Bonzini 		goto out;
5566a91f387bSSean Christopherson 
5567a91f387bSSean Christopherson 	kvm_mmu_sync_roots(vcpu);
5568a91f387bSSean Christopherson 
5569727a7e27SPaolo Bonzini 	kvm_mmu_load_pgd(vcpu);
5570db01416bSSean Christopherson 
5571db01416bSSean Christopherson 	/*
5572db01416bSSean Christopherson 	 * Flush any TLB entries for the new root, the provenance of the root
5573db01416bSSean Christopherson 	 * is unknown.  Even if KVM ensures there are no stale TLB entries
5574db01416bSSean Christopherson 	 * for a freed root, in theory another hypervisor could have left
5575db01416bSSean Christopherson 	 * stale entries.  Flushing on alloc also allows KVM to skip the TLB
5576db01416bSSean Christopherson 	 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5577db01416bSSean Christopherson 	 */
5578e27bc044SSean Christopherson 	static_call(kvm_x86_flush_tlb_current)(vcpu);
5579c50d8ae3SPaolo Bonzini out:
5580c50d8ae3SPaolo Bonzini 	return r;
5581c50d8ae3SPaolo Bonzini }
5582c50d8ae3SPaolo Bonzini 
5583c50d8ae3SPaolo Bonzini void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5584c50d8ae3SPaolo Bonzini {
55850c1c92f1SPaolo Bonzini 	struct kvm *kvm = vcpu->kvm;
55860c1c92f1SPaolo Bonzini 
55870c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
558820ba462dSSean Christopherson 	WARN_ON_ONCE(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
55890c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
559020ba462dSSean Christopherson 	WARN_ON_ONCE(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
55916d58f275SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5592c50d8ae3SPaolo Bonzini }
5593c50d8ae3SPaolo Bonzini 
5594527d5cd7SSean Christopherson static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5595527d5cd7SSean Christopherson {
5596527d5cd7SSean Christopherson 	struct kvm_mmu_page *sp;
5597527d5cd7SSean Christopherson 
5598527d5cd7SSean Christopherson 	if (!VALID_PAGE(root_hpa))
5599527d5cd7SSean Christopherson 		return false;
5600527d5cd7SSean Christopherson 
5601527d5cd7SSean Christopherson 	/*
5602527d5cd7SSean Christopherson 	 * When freeing obsolete roots, treat roots as obsolete if they don't
56030e3223d8SSean Christopherson 	 * have an associated shadow page, as it's impossible to determine if
56040e3223d8SSean Christopherson 	 * such roots are fresh or stale.  This does mean KVM will get false
5605527d5cd7SSean Christopherson 	 * positives and free roots that don't strictly need to be freed, but
5606527d5cd7SSean Christopherson 	 * such false positives are relatively rare:
5607527d5cd7SSean Christopherson 	 *
56080e3223d8SSean Christopherson 	 *  (a) only PAE paging and nested NPT have roots without shadow pages
56090e3223d8SSean Christopherson 	 *      (or any shadow paging flavor with a dummy root, see note below)
5610527d5cd7SSean Christopherson 	 *  (b) remote reloads due to a memslot update obsoletes _all_ roots
5611527d5cd7SSean Christopherson 	 *  (c) KVM doesn't track previous roots for PAE paging, and the guest
5612527d5cd7SSean Christopherson 	 *      is unlikely to zap an in-use PGD.
56130e3223d8SSean Christopherson 	 *
56140e3223d8SSean Christopherson 	 * Note!  Dummy roots are unique in that they are obsoleted by memslot
56150e3223d8SSean Christopherson 	 * _creation_!  See also FNAME(fetch).
5616527d5cd7SSean Christopherson 	 */
5617c5f2d564SSean Christopherson 	sp = root_to_sp(root_hpa);
5618527d5cd7SSean Christopherson 	return !sp || is_obsolete_sp(kvm, sp);
5619527d5cd7SSean Christopherson }
5620527d5cd7SSean Christopherson 
5621527d5cd7SSean Christopherson static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5622527d5cd7SSean Christopherson {
5623527d5cd7SSean Christopherson 	unsigned long roots_to_free = 0;
5624527d5cd7SSean Christopherson 	int i;
5625527d5cd7SSean Christopherson 
5626527d5cd7SSean Christopherson 	if (is_obsolete_root(kvm, mmu->root.hpa))
5627527d5cd7SSean Christopherson 		roots_to_free |= KVM_MMU_ROOT_CURRENT;
5628527d5cd7SSean Christopherson 
5629527d5cd7SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5630cf4a8693SShaoqin Huang 		if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5631527d5cd7SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5632527d5cd7SSean Christopherson 	}
5633527d5cd7SSean Christopherson 
5634527d5cd7SSean Christopherson 	if (roots_to_free)
5635527d5cd7SSean Christopherson 		kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5636527d5cd7SSean Christopherson }
5637527d5cd7SSean Christopherson 
5638527d5cd7SSean Christopherson void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5639527d5cd7SSean Christopherson {
5640527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5641527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5642527d5cd7SSean Christopherson }
5643527d5cd7SSean Christopherson 
5644c50d8ae3SPaolo Bonzini static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5645c50d8ae3SPaolo Bonzini 				    int *bytes)
5646c50d8ae3SPaolo Bonzini {
5647c50d8ae3SPaolo Bonzini 	u64 gentry = 0;
5648c50d8ae3SPaolo Bonzini 	int r;
5649c50d8ae3SPaolo Bonzini 
5650c50d8ae3SPaolo Bonzini 	/*
5651c50d8ae3SPaolo Bonzini 	 * Assume that the pte write on a page table of the same type
5652c50d8ae3SPaolo Bonzini 	 * as the current vcpu paging mode since we update the sptes only
5653c50d8ae3SPaolo Bonzini 	 * when they have the same mode.
5654c50d8ae3SPaolo Bonzini 	 */
5655c50d8ae3SPaolo Bonzini 	if (is_pae(vcpu) && *bytes == 4) {
5656c50d8ae3SPaolo Bonzini 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5657c50d8ae3SPaolo Bonzini 		*gpa &= ~(gpa_t)7;
5658c50d8ae3SPaolo Bonzini 		*bytes = 8;
5659c50d8ae3SPaolo Bonzini 	}
5660c50d8ae3SPaolo Bonzini 
5661c50d8ae3SPaolo Bonzini 	if (*bytes == 4 || *bytes == 8) {
5662c50d8ae3SPaolo Bonzini 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5663c50d8ae3SPaolo Bonzini 		if (r)
5664c50d8ae3SPaolo Bonzini 			gentry = 0;
5665c50d8ae3SPaolo Bonzini 	}
5666c50d8ae3SPaolo Bonzini 
5667c50d8ae3SPaolo Bonzini 	return gentry;
5668c50d8ae3SPaolo Bonzini }
5669c50d8ae3SPaolo Bonzini 
5670c50d8ae3SPaolo Bonzini /*
5671c50d8ae3SPaolo Bonzini  * If we're seeing too many writes to a page, it may no longer be a page table,
5672c50d8ae3SPaolo Bonzini  * or we may be forking, in which case it is better to unmap the page.
5673c50d8ae3SPaolo Bonzini  */
5674c50d8ae3SPaolo Bonzini static bool detect_write_flooding(struct kvm_mmu_page *sp)
5675c50d8ae3SPaolo Bonzini {
5676c50d8ae3SPaolo Bonzini 	/*
5677c50d8ae3SPaolo Bonzini 	 * Skip write-flooding detected for the sp whose level is 1, because
5678c50d8ae3SPaolo Bonzini 	 * it can become unsync, then the guest page is not write-protected.
5679c50d8ae3SPaolo Bonzini 	 */
56803bae0459SSean Christopherson 	if (sp->role.level == PG_LEVEL_4K)
5681c50d8ae3SPaolo Bonzini 		return false;
5682c50d8ae3SPaolo Bonzini 
5683c50d8ae3SPaolo Bonzini 	atomic_inc(&sp->write_flooding_count);
5684c50d8ae3SPaolo Bonzini 	return atomic_read(&sp->write_flooding_count) >= 3;
5685c50d8ae3SPaolo Bonzini }
5686c50d8ae3SPaolo Bonzini 
5687c50d8ae3SPaolo Bonzini /*
5688c50d8ae3SPaolo Bonzini  * Misaligned accesses are too much trouble to fix up; also, they usually
5689c50d8ae3SPaolo Bonzini  * indicate a page is not used as a page table.
5690c50d8ae3SPaolo Bonzini  */
5691c50d8ae3SPaolo Bonzini static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5692c50d8ae3SPaolo Bonzini 				    int bytes)
5693c50d8ae3SPaolo Bonzini {
5694c50d8ae3SPaolo Bonzini 	unsigned offset, pte_size, misaligned;
5695c50d8ae3SPaolo Bonzini 
5696c50d8ae3SPaolo Bonzini 	offset = offset_in_page(gpa);
5697bb3b394dSLai Jiangshan 	pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5698c50d8ae3SPaolo Bonzini 
5699c50d8ae3SPaolo Bonzini 	/*
5700c50d8ae3SPaolo Bonzini 	 * Sometimes, the OS only writes the last one bytes to update status
5701c50d8ae3SPaolo Bonzini 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5702c50d8ae3SPaolo Bonzini 	 */
5703c50d8ae3SPaolo Bonzini 	if (!(offset & (pte_size - 1)) && bytes == 1)
5704c50d8ae3SPaolo Bonzini 		return false;
5705c50d8ae3SPaolo Bonzini 
5706c50d8ae3SPaolo Bonzini 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5707c50d8ae3SPaolo Bonzini 	misaligned |= bytes < 4;
5708c50d8ae3SPaolo Bonzini 
5709c50d8ae3SPaolo Bonzini 	return misaligned;
5710c50d8ae3SPaolo Bonzini }
5711c50d8ae3SPaolo Bonzini 
5712c50d8ae3SPaolo Bonzini static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5713c50d8ae3SPaolo Bonzini {
5714c50d8ae3SPaolo Bonzini 	unsigned page_offset, quadrant;
5715c50d8ae3SPaolo Bonzini 	u64 *spte;
5716c50d8ae3SPaolo Bonzini 	int level;
5717c50d8ae3SPaolo Bonzini 
5718c50d8ae3SPaolo Bonzini 	page_offset = offset_in_page(gpa);
5719c50d8ae3SPaolo Bonzini 	level = sp->role.level;
5720c50d8ae3SPaolo Bonzini 	*nspte = 1;
5721bb3b394dSLai Jiangshan 	if (sp->role.has_4_byte_gpte) {
5722c50d8ae3SPaolo Bonzini 		page_offset <<= 1;	/* 32->64 */
5723c50d8ae3SPaolo Bonzini 		/*
5724c50d8ae3SPaolo Bonzini 		 * A 32-bit pde maps 4MB while the shadow pdes map
5725c50d8ae3SPaolo Bonzini 		 * only 2MB.  So we need to double the offset again
5726c50d8ae3SPaolo Bonzini 		 * and zap two pdes instead of one.
5727c50d8ae3SPaolo Bonzini 		 */
5728c50d8ae3SPaolo Bonzini 		if (level == PT32_ROOT_LEVEL) {
5729c50d8ae3SPaolo Bonzini 			page_offset &= ~7; /* kill rounding error */
5730c50d8ae3SPaolo Bonzini 			page_offset <<= 1;
5731c50d8ae3SPaolo Bonzini 			*nspte = 2;
5732c50d8ae3SPaolo Bonzini 		}
5733c50d8ae3SPaolo Bonzini 		quadrant = page_offset >> PAGE_SHIFT;
5734c50d8ae3SPaolo Bonzini 		page_offset &= ~PAGE_MASK;
5735c50d8ae3SPaolo Bonzini 		if (quadrant != sp->role.quadrant)
5736c50d8ae3SPaolo Bonzini 			return NULL;
5737c50d8ae3SPaolo Bonzini 	}
5738c50d8ae3SPaolo Bonzini 
5739c50d8ae3SPaolo Bonzini 	spte = &sp->spt[page_offset / sizeof(*spte)];
5740c50d8ae3SPaolo Bonzini 	return spte;
5741c50d8ae3SPaolo Bonzini }
5742c50d8ae3SPaolo Bonzini 
574393284446SSean Christopherson void kvm_mmu_track_write(struct kvm_vcpu *vcpu, gpa_t gpa, const u8 *new,
574493284446SSean Christopherson 			 int bytes)
5745c50d8ae3SPaolo Bonzini {
5746c50d8ae3SPaolo Bonzini 	gfn_t gfn = gpa >> PAGE_SHIFT;
5747c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
5748c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
5749c50d8ae3SPaolo Bonzini 	u64 entry, gentry, *spte;
5750c50d8ae3SPaolo Bonzini 	int npte;
575106152b2dSLai Jiangshan 	bool flush = false;
5752c50d8ae3SPaolo Bonzini 
5753c50d8ae3SPaolo Bonzini 	/*
5754c50d8ae3SPaolo Bonzini 	 * If we don't have indirect shadow pages, it means no page is
5755c50d8ae3SPaolo Bonzini 	 * write-protected, so we can exit simply.
5756c50d8ae3SPaolo Bonzini 	 */
5757c50d8ae3SPaolo Bonzini 	if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5758c50d8ae3SPaolo Bonzini 		return;
5759c50d8ae3SPaolo Bonzini 
5760531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
5761c50d8ae3SPaolo Bonzini 
5762c50d8ae3SPaolo Bonzini 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5763c50d8ae3SPaolo Bonzini 
5764c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_pte_write;
5765c50d8ae3SPaolo Bonzini 
5766767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5767c50d8ae3SPaolo Bonzini 		if (detect_write_misaligned(sp, gpa, bytes) ||
5768c50d8ae3SPaolo Bonzini 		      detect_write_flooding(sp)) {
5769c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5770c50d8ae3SPaolo Bonzini 			++vcpu->kvm->stat.mmu_flooded;
5771c50d8ae3SPaolo Bonzini 			continue;
5772c50d8ae3SPaolo Bonzini 		}
5773c50d8ae3SPaolo Bonzini 
5774c50d8ae3SPaolo Bonzini 		spte = get_written_sptes(sp, gpa, &npte);
5775c50d8ae3SPaolo Bonzini 		if (!spte)
5776c50d8ae3SPaolo Bonzini 			continue;
5777c50d8ae3SPaolo Bonzini 
5778c50d8ae3SPaolo Bonzini 		while (npte--) {
5779c50d8ae3SPaolo Bonzini 			entry = *spte;
57802de4085cSBen Gardon 			mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5781c5e2184dSSean Christopherson 			if (gentry && sp->role.level != PG_LEVEL_4K)
5782c5e2184dSSean Christopherson 				++vcpu->kvm->stat.mmu_pde_zapped;
57831441ca14SJunaid Shahid 			if (is_shadow_present_pte(entry))
578406152b2dSLai Jiangshan 				flush = true;
5785c50d8ae3SPaolo Bonzini 			++spte;
5786c50d8ae3SPaolo Bonzini 		}
5787c50d8ae3SPaolo Bonzini 	}
578806152b2dSLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5789531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
5790c50d8ae3SPaolo Bonzini }
5791c50d8ae3SPaolo Bonzini 
57921075d41eSSean Christopherson int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5793c50d8ae3SPaolo Bonzini 		       void *insn, int insn_len)
5794c50d8ae3SPaolo Bonzini {
579592daa48bSSean Christopherson 	int r, emulation_type = EMULTYPE_PF;
5796347a0d0dSPaolo Bonzini 	bool direct = vcpu->arch.mmu->root_role.direct;
5797c50d8ae3SPaolo Bonzini 
579820ba462dSSean Christopherson 	if (WARN_ON_ONCE(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5799ddce6208SSean Christopherson 		return RET_PF_RETRY;
5800ddce6208SSean Christopherson 
5801c50d8ae3SPaolo Bonzini 	r = RET_PF_INVALID;
5802c50d8ae3SPaolo Bonzini 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
5803736c291cSSean Christopherson 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5804c50d8ae3SPaolo Bonzini 		if (r == RET_PF_EMULATE)
5805c50d8ae3SPaolo Bonzini 			goto emulate;
5806c50d8ae3SPaolo Bonzini 	}
5807c50d8ae3SPaolo Bonzini 
5808c50d8ae3SPaolo Bonzini 	if (r == RET_PF_INVALID) {
5809c9710130SIsaku Yamahata 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa, error_code, false,
5810258d985fSSean Christopherson 					  &emulation_type);
581119025e7bSSean Christopherson 		if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
58127b367bc9SSean Christopherson 			return -EIO;
5813c50d8ae3SPaolo Bonzini 	}
5814c50d8ae3SPaolo Bonzini 
5815c50d8ae3SPaolo Bonzini 	if (r < 0)
5816c50d8ae3SPaolo Bonzini 		return r;
581783a2ba4cSSean Christopherson 	if (r != RET_PF_EMULATE)
581883a2ba4cSSean Christopherson 		return 1;
5819c50d8ae3SPaolo Bonzini 
5820c50d8ae3SPaolo Bonzini 	/*
5821c50d8ae3SPaolo Bonzini 	 * Before emulating the instruction, check if the error code
5822c50d8ae3SPaolo Bonzini 	 * was due to a RO violation while translating the guest page.
5823c50d8ae3SPaolo Bonzini 	 * This can occur when using nested virtualization with nested
5824c50d8ae3SPaolo Bonzini 	 * paging in both guests. If true, we simply unprotect the page
5825c50d8ae3SPaolo Bonzini 	 * and resume the guest.
5826c50d8ae3SPaolo Bonzini 	 */
5827347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct &&
5828c50d8ae3SPaolo Bonzini 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5829736c291cSSean Christopherson 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5830c50d8ae3SPaolo Bonzini 		return 1;
5831c50d8ae3SPaolo Bonzini 	}
5832c50d8ae3SPaolo Bonzini 
5833c50d8ae3SPaolo Bonzini 	/*
5834c50d8ae3SPaolo Bonzini 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5835c50d8ae3SPaolo Bonzini 	 * optimistically try to just unprotect the page and let the processor
5836c50d8ae3SPaolo Bonzini 	 * re-execute the instruction that caused the page fault.  Do not allow
5837c50d8ae3SPaolo Bonzini 	 * retrying MMIO emulation, as it's not only pointless but could also
5838c50d8ae3SPaolo Bonzini 	 * cause us to enter an infinite loop because the processor will keep
5839c50d8ae3SPaolo Bonzini 	 * faulting on the non-existent MMIO address.  Retrying an instruction
5840c50d8ae3SPaolo Bonzini 	 * from a nested guest is also pointless and dangerous as we are only
5841c50d8ae3SPaolo Bonzini 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
5842c50d8ae3SPaolo Bonzini 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5843c50d8ae3SPaolo Bonzini 	 */
5844736c291cSSean Christopherson 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
584592daa48bSSean Christopherson 		emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5846c50d8ae3SPaolo Bonzini emulate:
5847736c291cSSean Christopherson 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5848c50d8ae3SPaolo Bonzini 				       insn_len);
5849c50d8ae3SPaolo Bonzini }
5850c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5851c50d8ae3SPaolo Bonzini 
58529fd4a4e3SLai Jiangshan static void __kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
58539fd4a4e3SLai Jiangshan 				      u64 addr, hpa_t root_hpa)
58549fd4a4e3SLai Jiangshan {
58559fd4a4e3SLai Jiangshan 	struct kvm_shadow_walk_iterator iterator;
58569fd4a4e3SLai Jiangshan 
58579fd4a4e3SLai Jiangshan 	vcpu_clear_mmio_info(vcpu, addr);
58589fd4a4e3SLai Jiangshan 
5859762b33ebSLike Xu 	/*
5860762b33ebSLike Xu 	 * Walking and synchronizing SPTEs both assume they are operating in
5861762b33ebSLike Xu 	 * the context of the current MMU, and would need to be reworked if
5862762b33ebSLike Xu 	 * this is ever used to sync the guest_mmu, e.g. to emulate INVEPT.
5863762b33ebSLike Xu 	 */
5864762b33ebSLike Xu 	if (WARN_ON_ONCE(mmu != vcpu->arch.mmu))
5865762b33ebSLike Xu 		return;
5866762b33ebSLike Xu 
58679fd4a4e3SLai Jiangshan 	if (!VALID_PAGE(root_hpa))
58689fd4a4e3SLai Jiangshan 		return;
58699fd4a4e3SLai Jiangshan 
58709fd4a4e3SLai Jiangshan 	write_lock(&vcpu->kvm->mmu_lock);
58719fd4a4e3SLai Jiangshan 	for_each_shadow_entry_using_root(vcpu, root_hpa, addr, iterator) {
58729fd4a4e3SLai Jiangshan 		struct kvm_mmu_page *sp = sptep_to_sp(iterator.sptep);
58739fd4a4e3SLai Jiangshan 
58749fd4a4e3SLai Jiangshan 		if (sp->unsync) {
587519ace7d6SLai Jiangshan 			int ret = kvm_sync_spte(vcpu, sp, iterator.index);
58769fd4a4e3SLai Jiangshan 
58779fd4a4e3SLai Jiangshan 			if (ret < 0)
58789fd4a4e3SLai Jiangshan 				mmu_page_zap_pte(vcpu->kvm, sp, iterator.sptep, NULL);
58799fd4a4e3SLai Jiangshan 			if (ret)
58809fd4a4e3SLai Jiangshan 				kvm_flush_remote_tlbs_sptep(vcpu->kvm, iterator.sptep);
58819fd4a4e3SLai Jiangshan 		}
58829fd4a4e3SLai Jiangshan 
58839fd4a4e3SLai Jiangshan 		if (!sp->unsync_children)
58849fd4a4e3SLai Jiangshan 			break;
58859fd4a4e3SLai Jiangshan 	}
58869fd4a4e3SLai Jiangshan 	write_unlock(&vcpu->kvm->mmu_lock);
58879fd4a4e3SLai Jiangshan }
58889fd4a4e3SLai Jiangshan 
5889753b43c9SLai Jiangshan void kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5890cd42853eSLai Jiangshan 			     u64 addr, unsigned long roots)
5891c50d8ae3SPaolo Bonzini {
5892c50d8ae3SPaolo Bonzini 	int i;
5893c50d8ae3SPaolo Bonzini 
5894cd42853eSLai Jiangshan 	WARN_ON_ONCE(roots & ~KVM_MMU_ROOTS_ALL);
5895cd42853eSLai Jiangshan 
58965efac074SPaolo Bonzini 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
58975efac074SPaolo Bonzini 	if (mmu != &vcpu->arch.guest_mmu) {
58985efac074SPaolo Bonzini 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
5899753b43c9SLai Jiangshan 		if (is_noncanonical_address(addr, vcpu))
5900c50d8ae3SPaolo Bonzini 			return;
5901c50d8ae3SPaolo Bonzini 
5902753b43c9SLai Jiangshan 		static_call(kvm_x86_flush_tlb_gva)(vcpu, addr);
59035efac074SPaolo Bonzini 	}
59045efac074SPaolo Bonzini 
59059fd4a4e3SLai Jiangshan 	if (!mmu->sync_spte)
59065efac074SPaolo Bonzini 		return;
59075efac074SPaolo Bonzini 
5908cd42853eSLai Jiangshan 	if (roots & KVM_MMU_ROOT_CURRENT)
59099fd4a4e3SLai Jiangshan 		__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->root.hpa);
5910c50d8ae3SPaolo Bonzini 
5911cd42853eSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5912ed335278SLai Jiangshan 		if (roots & KVM_MMU_ROOT_PREVIOUS(i))
59139fd4a4e3SLai Jiangshan 			__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->prev_roots[i].hpa);
59145efac074SPaolo Bonzini 	}
59155efac074SPaolo Bonzini }
59162c86c444SLai Jiangshan EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_addr);
5917c50d8ae3SPaolo Bonzini 
59185efac074SPaolo Bonzini void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
59195efac074SPaolo Bonzini {
5920cd42853eSLai Jiangshan 	/*
5921cd42853eSLai Jiangshan 	 * INVLPG is required to invalidate any global mappings for the VA,
5922cd42853eSLai Jiangshan 	 * irrespective of PCID.  Blindly sync all roots as it would take
5923cd42853eSLai Jiangshan 	 * roughly the same amount of work/time to determine whether any of the
5924cd42853eSLai Jiangshan 	 * previous roots have a global mapping.
5925cd42853eSLai Jiangshan 	 *
5926cd42853eSLai Jiangshan 	 * Mappings not reachable via the current or previous cached roots will
5927cd42853eSLai Jiangshan 	 * be synced when switching to that new cr3, so nothing needs to be
5928cd42853eSLai Jiangshan 	 * done here for them.
5929cd42853eSLai Jiangshan 	 */
5930cd42853eSLai Jiangshan 	kvm_mmu_invalidate_addr(vcpu, vcpu->arch.walk_mmu, gva, KVM_MMU_ROOTS_ALL);
5931c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5932c50d8ae3SPaolo Bonzini }
5933c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5934c50d8ae3SPaolo Bonzini 
59355efac074SPaolo Bonzini 
5936c50d8ae3SPaolo Bonzini void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5937c50d8ae3SPaolo Bonzini {
5938c50d8ae3SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
59399ebc3f51SLai Jiangshan 	unsigned long roots = 0;
5940c50d8ae3SPaolo Bonzini 	uint i;
5941c50d8ae3SPaolo Bonzini 
59429ebc3f51SLai Jiangshan 	if (pcid == kvm_get_active_pcid(vcpu))
59439ebc3f51SLai Jiangshan 		roots |= KVM_MMU_ROOT_CURRENT;
5944c50d8ae3SPaolo Bonzini 
5945c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5946c50d8ae3SPaolo Bonzini 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
59479ebc3f51SLai Jiangshan 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd))
59489ebc3f51SLai Jiangshan 			roots |= KVM_MMU_ROOT_PREVIOUS(i);
5949c50d8ae3SPaolo Bonzini 	}
5950c50d8ae3SPaolo Bonzini 
59519ebc3f51SLai Jiangshan 	if (roots)
59529ebc3f51SLai Jiangshan 		kvm_mmu_invalidate_addr(vcpu, mmu, gva, roots);
5953c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5954c50d8ae3SPaolo Bonzini 
5955c50d8ae3SPaolo Bonzini 	/*
5956c50d8ae3SPaolo Bonzini 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5957c50d8ae3SPaolo Bonzini 	 * synced when switching to that cr3, so nothing needs to be done here
5958c50d8ae3SPaolo Bonzini 	 * for them.
5959c50d8ae3SPaolo Bonzini 	 */
5960c50d8ae3SPaolo Bonzini }
5961c50d8ae3SPaolo Bonzini 
5962746700d2SWei Huang void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
5963746700d2SWei Huang 		       int tdp_max_root_level, int tdp_huge_page_level)
5964c50d8ae3SPaolo Bonzini {
5965bde77235SSean Christopherson 	tdp_enabled = enable_tdp;
5966746700d2SWei Huang 	tdp_root_level = tdp_forced_root_level;
596783013059SSean Christopherson 	max_tdp_level = tdp_max_root_level;
5968703c335dSSean Christopherson 
59691f98f2bdSDavid Matlack #ifdef CONFIG_X86_64
59701f98f2bdSDavid Matlack 	tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
59711f98f2bdSDavid Matlack #endif
5972703c335dSSean Christopherson 	/*
59731d92d2e8SSean Christopherson 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5974703c335dSSean Christopherson 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5975703c335dSSean Christopherson 	 * the kernel is not.  But, KVM never creates a page size greater than
5976703c335dSSean Christopherson 	 * what is used by the kernel for any given HVA, i.e. the kernel's
5977703c335dSSean Christopherson 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5978703c335dSSean Christopherson 	 */
5979703c335dSSean Christopherson 	if (tdp_enabled)
59801d92d2e8SSean Christopherson 		max_huge_page_level = tdp_huge_page_level;
5981703c335dSSean Christopherson 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
59821d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_1G;
5983703c335dSSean Christopherson 	else
59841d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_2M;
5985c50d8ae3SPaolo Bonzini }
5986bde77235SSean Christopherson EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5987c50d8ae3SPaolo Bonzini 
5988c50d8ae3SPaolo Bonzini /* The return value indicates if tlb flush on all vcpus is needed. */
5989727ae377SSean Christopherson typedef bool (*slot_rmaps_handler) (struct kvm *kvm,
5990269e9552SHamza Mahfooz 				    struct kvm_rmap_head *rmap_head,
5991269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot);
5992c50d8ae3SPaolo Bonzini 
5993727ae377SSean Christopherson static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,
5994727ae377SSean Christopherson 					      const struct kvm_memory_slot *slot,
5995727ae377SSean Christopherson 					      slot_rmaps_handler fn,
5996727ae377SSean Christopherson 					      int start_level, int end_level,
5997727ae377SSean Christopherson 					      gfn_t start_gfn, gfn_t end_gfn,
5998727ae377SSean Christopherson 					      bool flush_on_yield, bool flush)
5999c50d8ae3SPaolo Bonzini {
6000c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
6001c50d8ae3SPaolo Bonzini 
6002eddd9e83SSean Christopherson 	lockdep_assert_held_write(&kvm->mmu_lock);
6003eddd9e83SSean Christopherson 
6004727ae377SSean Christopherson 	for_each_slot_rmap_range(slot, start_level, end_level, start_gfn,
6005c50d8ae3SPaolo Bonzini 			end_gfn, &iterator) {
6006c50d8ae3SPaolo Bonzini 		if (iterator.rmap)
6007727ae377SSean Christopherson 			flush |= fn(kvm, iterator.rmap, slot);
6008c50d8ae3SPaolo Bonzini 
6009531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
6010302695a5SSean Christopherson 			if (flush && flush_on_yield) {
60118c63e8c2SDavid Matlack 				kvm_flush_remote_tlbs_range(kvm, start_gfn,
6012c50d8ae3SPaolo Bonzini 							    iterator.gfn - start_gfn + 1);
6013c50d8ae3SPaolo Bonzini 				flush = false;
6014c50d8ae3SPaolo Bonzini 			}
6015531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
6016c50d8ae3SPaolo Bonzini 		}
6017c50d8ae3SPaolo Bonzini 	}
6018c50d8ae3SPaolo Bonzini 
6019c50d8ae3SPaolo Bonzini 	return flush;
6020c50d8ae3SPaolo Bonzini }
6021c50d8ae3SPaolo Bonzini 
6022727ae377SSean Christopherson static __always_inline bool walk_slot_rmaps(struct kvm *kvm,
6023727ae377SSean Christopherson 					    const struct kvm_memory_slot *slot,
6024727ae377SSean Christopherson 					    slot_rmaps_handler fn,
6025727ae377SSean Christopherson 					    int start_level, int end_level,
6026302695a5SSean Christopherson 					    bool flush_on_yield)
6027c50d8ae3SPaolo Bonzini {
6028727ae377SSean Christopherson 	return __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,
6029727ae377SSean Christopherson 				 slot->base_gfn, slot->base_gfn + slot->npages - 1,
60301a61b7dbSSean Christopherson 				 flush_on_yield, false);
6031c50d8ae3SPaolo Bonzini }
6032c50d8ae3SPaolo Bonzini 
6033727ae377SSean Christopherson static __always_inline bool walk_slot_rmaps_4k(struct kvm *kvm,
6034727ae377SSean Christopherson 					       const struct kvm_memory_slot *slot,
6035727ae377SSean Christopherson 					       slot_rmaps_handler fn,
6036727ae377SSean Christopherson 					       bool flush_on_yield)
6037c50d8ae3SPaolo Bonzini {
6038727ae377SSean Christopherson 	return walk_slot_rmaps(kvm, slot, fn, PG_LEVEL_4K, PG_LEVEL_4K, flush_on_yield);
6039c50d8ae3SPaolo Bonzini }
6040c50d8ae3SPaolo Bonzini 
6041c50d8ae3SPaolo Bonzini static void free_mmu_pages(struct kvm_mmu *mmu)
6042c50d8ae3SPaolo Bonzini {
60434a98623dSSean Christopherson 	if (!tdp_enabled && mmu->pae_root)
60444a98623dSSean Christopherson 		set_memory_encrypted((unsigned long)mmu->pae_root, 1);
6045c50d8ae3SPaolo Bonzini 	free_page((unsigned long)mmu->pae_root);
604603ca4589SSean Christopherson 	free_page((unsigned long)mmu->pml4_root);
6047cb0f722aSWei Huang 	free_page((unsigned long)mmu->pml5_root);
6048c50d8ae3SPaolo Bonzini }
6049c50d8ae3SPaolo Bonzini 
605004d28e37SSean Christopherson static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
6051c50d8ae3SPaolo Bonzini {
6052c50d8ae3SPaolo Bonzini 	struct page *page;
6053c50d8ae3SPaolo Bonzini 	int i;
6054c50d8ae3SPaolo Bonzini 
6055b9e5603cSPaolo Bonzini 	mmu->root.hpa = INVALID_PAGE;
6056b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
605704d28e37SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
605804d28e37SSean Christopherson 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
605904d28e37SSean Christopherson 
606027f4fca2SLai Jiangshan 	/* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
606127f4fca2SLai Jiangshan 	if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
606227f4fca2SLai Jiangshan 		return 0;
606327f4fca2SLai Jiangshan 
6064c50d8ae3SPaolo Bonzini 	/*
6065c50d8ae3SPaolo Bonzini 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
6066c50d8ae3SPaolo Bonzini 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
6067c50d8ae3SPaolo Bonzini 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
6068c50d8ae3SPaolo Bonzini 	 * x86_64.  Therefore we need to allocate the PDP table in the first
606904d45551SSean Christopherson 	 * 4GB of memory, which happens to fit the DMA32 zone.  TDP paging
607004d45551SSean Christopherson 	 * generally doesn't use PAE paging and can skip allocating the PDP
607104d45551SSean Christopherson 	 * table.  The main exception, handled here, is SVM's 32-bit NPT.  The
607204d45551SSean Christopherson 	 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
607384432316SLai Jiangshan 	 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
6074c50d8ae3SPaolo Bonzini 	 */
6075d468d94bSSean Christopherson 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
6076c50d8ae3SPaolo Bonzini 		return 0;
6077c50d8ae3SPaolo Bonzini 
6078c50d8ae3SPaolo Bonzini 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
6079c50d8ae3SPaolo Bonzini 	if (!page)
6080c50d8ae3SPaolo Bonzini 		return -ENOMEM;
6081c50d8ae3SPaolo Bonzini 
6082c50d8ae3SPaolo Bonzini 	mmu->pae_root = page_address(page);
60834a98623dSSean Christopherson 
60844a98623dSSean Christopherson 	/*
60854a98623dSSean Christopherson 	 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
60864a98623dSSean Christopherson 	 * get the CPU to treat the PDPTEs as encrypted.  Decrypt the page so
60874a98623dSSean Christopherson 	 * that KVM's writes and the CPU's reads get along.  Note, this is
60884a98623dSSean Christopherson 	 * only necessary when using shadow paging, as 64-bit NPT can get at
60894a98623dSSean Christopherson 	 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
60904a98623dSSean Christopherson 	 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
60914a98623dSSean Christopherson 	 */
60924a98623dSSean Christopherson 	if (!tdp_enabled)
60934a98623dSSean Christopherson 		set_memory_decrypted((unsigned long)mmu->pae_root, 1);
60944a98623dSSean Christopherson 	else
6095e54f1ff2SKai Huang 		WARN_ON_ONCE(shadow_me_value);
60964a98623dSSean Christopherson 
6097c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i)
6098c834e5e4SSean Christopherson 		mmu->pae_root[i] = INVALID_PAE_ROOT;
6099c50d8ae3SPaolo Bonzini 
6100c50d8ae3SPaolo Bonzini 	return 0;
6101c50d8ae3SPaolo Bonzini }
6102c50d8ae3SPaolo Bonzini 
6103c50d8ae3SPaolo Bonzini int kvm_mmu_create(struct kvm_vcpu *vcpu)
6104c50d8ae3SPaolo Bonzini {
6105c50d8ae3SPaolo Bonzini 	int ret;
6106c50d8ae3SPaolo Bonzini 
61075962bfb7SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
61085f6078f9SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
61095f6078f9SSean Christopherson 
61105962bfb7SSean Christopherson 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
61115f6078f9SSean Christopherson 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
61125962bfb7SSean Christopherson 
611396880883SSean Christopherson 	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
611496880883SSean Christopherson 
6115c50d8ae3SPaolo Bonzini 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
6116c50d8ae3SPaolo Bonzini 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6117c50d8ae3SPaolo Bonzini 
611804d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
6119c50d8ae3SPaolo Bonzini 	if (ret)
6120c50d8ae3SPaolo Bonzini 		return ret;
6121c50d8ae3SPaolo Bonzini 
612204d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
6123c50d8ae3SPaolo Bonzini 	if (ret)
6124c50d8ae3SPaolo Bonzini 		goto fail_allocate_root;
6125c50d8ae3SPaolo Bonzini 
6126c50d8ae3SPaolo Bonzini 	return ret;
6127c50d8ae3SPaolo Bonzini  fail_allocate_root:
6128c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
6129c50d8ae3SPaolo Bonzini 	return ret;
6130c50d8ae3SPaolo Bonzini }
6131c50d8ae3SPaolo Bonzini 
6132c50d8ae3SPaolo Bonzini #define BATCH_ZAP_PAGES	10
6133c50d8ae3SPaolo Bonzini static void kvm_zap_obsolete_pages(struct kvm *kvm)
6134c50d8ae3SPaolo Bonzini {
6135c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6136c50d8ae3SPaolo Bonzini 	int nr_zapped, batch = 0;
6137b28cb0cdSSean Christopherson 	bool unstable;
6138c50d8ae3SPaolo Bonzini 
6139c50d8ae3SPaolo Bonzini restart:
6140c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe_reverse(sp, node,
6141c50d8ae3SPaolo Bonzini 	      &kvm->arch.active_mmu_pages, link) {
6142c50d8ae3SPaolo Bonzini 		/*
6143c50d8ae3SPaolo Bonzini 		 * No obsolete valid page exists before a newly created page
6144c50d8ae3SPaolo Bonzini 		 * since active_mmu_pages is a FIFO list.
6145c50d8ae3SPaolo Bonzini 		 */
6146c50d8ae3SPaolo Bonzini 		if (!is_obsolete_sp(kvm, sp))
6147c50d8ae3SPaolo Bonzini 			break;
6148c50d8ae3SPaolo Bonzini 
6149c50d8ae3SPaolo Bonzini 		/*
6150f95eec9bSSean Christopherson 		 * Invalid pages should never land back on the list of active
6151f95eec9bSSean Christopherson 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
6152f95eec9bSSean Christopherson 		 * infinite loop if the page gets put back on the list (again).
6153c50d8ae3SPaolo Bonzini 		 */
615420ba462dSSean Christopherson 		if (WARN_ON_ONCE(sp->role.invalid))
6155c50d8ae3SPaolo Bonzini 			continue;
6156c50d8ae3SPaolo Bonzini 
6157c50d8ae3SPaolo Bonzini 		/*
6158c50d8ae3SPaolo Bonzini 		 * No need to flush the TLB since we're only zapping shadow
6159c50d8ae3SPaolo Bonzini 		 * pages with an obsolete generation number and all vCPUS have
6160c50d8ae3SPaolo Bonzini 		 * loaded a new root, i.e. the shadow pages being zapped cannot
6161c50d8ae3SPaolo Bonzini 		 * be in active use by the guest.
6162c50d8ae3SPaolo Bonzini 		 */
6163c50d8ae3SPaolo Bonzini 		if (batch >= BATCH_ZAP_PAGES &&
6164531810caSBen Gardon 		    cond_resched_rwlock_write(&kvm->mmu_lock)) {
6165c50d8ae3SPaolo Bonzini 			batch = 0;
6166c50d8ae3SPaolo Bonzini 			goto restart;
6167c50d8ae3SPaolo Bonzini 		}
6168c50d8ae3SPaolo Bonzini 
6169b28cb0cdSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
6170b28cb0cdSSean Christopherson 				&kvm->arch.zapped_obsolete_pages, &nr_zapped);
6171c50d8ae3SPaolo Bonzini 		batch += nr_zapped;
6172b28cb0cdSSean Christopherson 
6173b28cb0cdSSean Christopherson 		if (unstable)
6174c50d8ae3SPaolo Bonzini 			goto restart;
6175c50d8ae3SPaolo Bonzini 	}
6176c50d8ae3SPaolo Bonzini 
6177c50d8ae3SPaolo Bonzini 	/*
61787ae5840eSSean Christopherson 	 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
61797ae5840eSSean Christopherson 	 * to ensure KVM is not in the middle of a lockless shadow page table
61807ae5840eSSean Christopherson 	 * walk, which may reference the pages.  The remote TLB flush itself is
61817ae5840eSSean Christopherson 	 * not required and is simply a convenient way to kick vCPUs as needed.
61827ae5840eSSean Christopherson 	 * KVM performs a local TLB flush when allocating a new root (see
61837ae5840eSSean Christopherson 	 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
61847ae5840eSSean Christopherson 	 * running with an obsolete MMU.
6185c50d8ae3SPaolo Bonzini 	 */
6186c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
6187c50d8ae3SPaolo Bonzini }
6188c50d8ae3SPaolo Bonzini 
6189c50d8ae3SPaolo Bonzini /*
6190c50d8ae3SPaolo Bonzini  * Fast invalidate all shadow pages and use lock-break technique
6191c50d8ae3SPaolo Bonzini  * to zap obsolete pages.
6192c50d8ae3SPaolo Bonzini  *
6193c50d8ae3SPaolo Bonzini  * It's required when memslot is being deleted or VM is being
6194c50d8ae3SPaolo Bonzini  * destroyed, in these cases, we should ensure that KVM MMU does
6195c50d8ae3SPaolo Bonzini  * not use any resource of the being-deleted slot or all slots
6196c50d8ae3SPaolo Bonzini  * after calling the function.
6197c50d8ae3SPaolo Bonzini  */
6198c50d8ae3SPaolo Bonzini static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6199c50d8ae3SPaolo Bonzini {
6200c50d8ae3SPaolo Bonzini 	lockdep_assert_held(&kvm->slots_lock);
6201c50d8ae3SPaolo Bonzini 
6202531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6203c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_zap_all_fast(kvm);
6204c50d8ae3SPaolo Bonzini 
6205c50d8ae3SPaolo Bonzini 	/*
6206c50d8ae3SPaolo Bonzini 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
6207c50d8ae3SPaolo Bonzini 	 * held for the entire duration of zapping obsolete pages, it's
6208c50d8ae3SPaolo Bonzini 	 * impossible for there to be multiple invalid generations associated
6209c50d8ae3SPaolo Bonzini 	 * with *valid* shadow pages at any given time, i.e. there is exactly
6210c50d8ae3SPaolo Bonzini 	 * one valid generation and (at most) one invalid generation.
6211c50d8ae3SPaolo Bonzini 	 */
6212c50d8ae3SPaolo Bonzini 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6213c50d8ae3SPaolo Bonzini 
62142f6f66ccSSean Christopherson 	/*
62152f6f66ccSSean Christopherson 	 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
62162f6f66ccSSean Christopherson 	 * invalidating TDP MMU roots must be done while holding mmu_lock for
62172f6f66ccSSean Christopherson 	 * write and in the same critical section as making the reload request,
62182f6f66ccSSean Christopherson 	 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6219b7cccd39SBen Gardon 	 */
62201f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6221b7cccd39SBen Gardon 		kvm_tdp_mmu_invalidate_all_roots(kvm);
6222b7cccd39SBen Gardon 
6223c50d8ae3SPaolo Bonzini 	/*
6224c50d8ae3SPaolo Bonzini 	 * Notify all vcpus to reload its shadow page table and flush TLB.
6225c50d8ae3SPaolo Bonzini 	 * Then all vcpus will switch to new shadow page table with the new
6226c50d8ae3SPaolo Bonzini 	 * mmu_valid_gen.
6227c50d8ae3SPaolo Bonzini 	 *
6228c50d8ae3SPaolo Bonzini 	 * Note: we need to do this under the protection of mmu_lock,
6229c50d8ae3SPaolo Bonzini 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
6230c50d8ae3SPaolo Bonzini 	 */
6231527d5cd7SSean Christopherson 	kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6232c50d8ae3SPaolo Bonzini 
6233c50d8ae3SPaolo Bonzini 	kvm_zap_obsolete_pages(kvm);
6234faaf05b0SBen Gardon 
6235531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
62364c6654bdSBen Gardon 
6237f28e9c7fSSean Christopherson 	/*
6238f28e9c7fSSean Christopherson 	 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6239f28e9c7fSSean Christopherson 	 * returning to the caller, e.g. if the zap is in response to a memslot
6240f28e9c7fSSean Christopherson 	 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6241f28e9c7fSSean Christopherson 	 * associated with the deleted memslot once the update completes, and
6242f28e9c7fSSean Christopherson 	 * Deferring the zap until the final reference to the root is put would
6243f28e9c7fSSean Christopherson 	 * lead to use-after-free.
6244f28e9c7fSSean Christopherson 	 */
62451f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
62464c6654bdSBen Gardon 		kvm_tdp_mmu_zap_invalidated_roots(kvm);
6247c50d8ae3SPaolo Bonzini }
6248c50d8ae3SPaolo Bonzini 
6249c50d8ae3SPaolo Bonzini static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
6250c50d8ae3SPaolo Bonzini {
6251c50d8ae3SPaolo Bonzini 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
6252c50d8ae3SPaolo Bonzini }
6253c50d8ae3SPaolo Bonzini 
62540df9dab8SSean Christopherson void kvm_mmu_init_vm(struct kvm *kvm)
6255c50d8ae3SPaolo Bonzini {
6256a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6257a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
625855c510e2SSean Christopherson 	INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6259ce25681dSSean Christopherson 	spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6260ce25681dSSean Christopherson 
62610df9dab8SSean Christopherson 	if (tdp_mmu_enabled)
62620df9dab8SSean Christopherson 		kvm_mmu_init_tdp_mmu(kvm);
6263fe5db27dSBen Gardon 
6264ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6265ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6266ada51a9dSDavid Matlack 
6267ada51a9dSDavid Matlack 	kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6268ada51a9dSDavid Matlack 
6269ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6270ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6271c50d8ae3SPaolo Bonzini }
6272c50d8ae3SPaolo Bonzini 
6273ada51a9dSDavid Matlack static void mmu_free_vm_memory_caches(struct kvm *kvm)
6274ada51a9dSDavid Matlack {
6275ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6276ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6277ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6278ada51a9dSDavid Matlack }
6279ada51a9dSDavid Matlack 
6280c50d8ae3SPaolo Bonzini void kvm_mmu_uninit_vm(struct kvm *kvm)
6281c50d8ae3SPaolo Bonzini {
628209732d2bSDavid Matlack 	if (tdp_mmu_enabled)
6283fe5db27dSBen Gardon 		kvm_mmu_uninit_tdp_mmu(kvm);
6284ada51a9dSDavid Matlack 
6285ada51a9dSDavid Matlack 	mmu_free_vm_memory_caches(kvm);
6286c50d8ae3SPaolo Bonzini }
6287c50d8ae3SPaolo Bonzini 
62882833eda0SSean Christopherson static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
628921fa3246SSean Christopherson {
629021fa3246SSean Christopherson 	const struct kvm_memory_slot *memslot;
629121fa3246SSean Christopherson 	struct kvm_memslots *slots;
6292f4209439SMaciej S. Szmigiero 	struct kvm_memslot_iter iter;
629321fa3246SSean Christopherson 	bool flush = false;
629421fa3246SSean Christopherson 	gfn_t start, end;
6295f4209439SMaciej S. Szmigiero 	int i;
629621fa3246SSean Christopherson 
629721fa3246SSean Christopherson 	if (!kvm_memslots_have_rmaps(kvm))
629821fa3246SSean Christopherson 		return flush;
629921fa3246SSean Christopherson 
6300eed52e43SSean Christopherson 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
630121fa3246SSean Christopherson 		slots = __kvm_memslots(kvm, i);
6302f4209439SMaciej S. Szmigiero 
6303f4209439SMaciej S. Szmigiero 		kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6304f4209439SMaciej S. Szmigiero 			memslot = iter.slot;
630521fa3246SSean Christopherson 			start = max(gfn_start, memslot->base_gfn);
630621fa3246SSean Christopherson 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
6307f4209439SMaciej S. Szmigiero 			if (WARN_ON_ONCE(start >= end))
630821fa3246SSean Christopherson 				continue;
630921fa3246SSean Christopherson 
6310727ae377SSean Christopherson 			flush = __walk_slot_rmaps(kvm, memslot, __kvm_zap_rmap,
631121fa3246SSean Christopherson 						  PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
631221fa3246SSean Christopherson 						  start, end - 1, true, flush);
631321fa3246SSean Christopherson 		}
631421fa3246SSean Christopherson 	}
631521fa3246SSean Christopherson 
631621fa3246SSean Christopherson 	return flush;
631721fa3246SSean Christopherson }
631821fa3246SSean Christopherson 
631988f58535SMaxim Levitsky /*
632088f58535SMaxim Levitsky  * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
632188f58535SMaxim Levitsky  * (not including it)
632288f58535SMaxim Levitsky  */
6323c50d8ae3SPaolo Bonzini void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6324c50d8ae3SPaolo Bonzini {
632521fa3246SSean Christopherson 	bool flush;
6326c50d8ae3SPaolo Bonzini 
6327f4209439SMaciej S. Szmigiero 	if (WARN_ON_ONCE(gfn_end <= gfn_start))
6328f4209439SMaciej S. Szmigiero 		return;
6329f4209439SMaciej S. Szmigiero 
6330531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
63315a324c24SSean Christopherson 
63328569992dSChao Peng 	kvm_mmu_invalidate_begin(kvm);
63338569992dSChao Peng 
63348569992dSChao Peng 	kvm_mmu_invalidate_range_add(kvm, gfn_start, gfn_end);
6335edb298c6SMaxim Levitsky 
63362833eda0SSean Christopherson 	flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
63376103bc07SBen Gardon 
6338441a5dfcSPaolo Bonzini 	if (tdp_mmu_enabled)
6339441a5dfcSPaolo Bonzini 		flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush);
63405a324c24SSean Christopherson 
63415a324c24SSean Christopherson 	if (flush)
63428c63e8c2SDavid Matlack 		kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);
63435a324c24SSean Christopherson 
63448569992dSChao Peng 	kvm_mmu_invalidate_end(kvm);
6345edb298c6SMaxim Levitsky 
63465a324c24SSean Christopherson 	write_unlock(&kvm->mmu_lock);
6347c50d8ae3SPaolo Bonzini }
6348c50d8ae3SPaolo Bonzini 
6349c50d8ae3SPaolo Bonzini static bool slot_rmap_write_protect(struct kvm *kvm,
63500a234f5dSSean Christopherson 				    struct kvm_rmap_head *rmap_head,
6351269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot)
6352c50d8ae3SPaolo Bonzini {
63531346bbb6SDavid Matlack 	return rmap_write_protect(rmap_head, false);
6354c50d8ae3SPaolo Bonzini }
6355c50d8ae3SPaolo Bonzini 
6356c50d8ae3SPaolo Bonzini void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6357269e9552SHamza Mahfooz 				      const struct kvm_memory_slot *memslot,
63583c9bd400SJay Zhou 				      int start_level)
6359c50d8ae3SPaolo Bonzini {
6360e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6361531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6362727ae377SSean Christopherson 		walk_slot_rmaps(kvm, memslot, slot_rmap_write_protect,
6363b64d740eSJunaid Shahid 				start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6364531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6365e2209710SBen Gardon 	}
6366c50d8ae3SPaolo Bonzini 
63671f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
636824ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6369b64d740eSJunaid Shahid 		kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
637024ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
637124ae4cfaSBen Gardon 	}
6372c50d8ae3SPaolo Bonzini }
6373c50d8ae3SPaolo Bonzini 
6374ada51a9dSDavid Matlack static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6375ada51a9dSDavid Matlack {
6376ada51a9dSDavid Matlack 	return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6377ada51a9dSDavid Matlack }
6378ada51a9dSDavid Matlack 
6379ada51a9dSDavid Matlack static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6380ada51a9dSDavid Matlack {
6381ada51a9dSDavid Matlack 	if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6382ada51a9dSDavid Matlack 		return true;
6383ada51a9dSDavid Matlack 
6384ada51a9dSDavid Matlack 	/*
6385ada51a9dSDavid Matlack 	 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6386ada51a9dSDavid Matlack 	 * to split a single huge page. Calculating how many are actually needed
6387ada51a9dSDavid Matlack 	 * is possible but not worth the complexity.
6388ada51a9dSDavid Matlack 	 */
6389ada51a9dSDavid Matlack 	return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6390ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_page_header_cache, 1) ||
6391ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_shadow_page_cache, 1);
6392ada51a9dSDavid Matlack }
6393ada51a9dSDavid Matlack 
6394ada51a9dSDavid Matlack static int topup_split_caches(struct kvm *kvm)
6395ada51a9dSDavid Matlack {
6396b9b71f43SSean Christopherson 	/*
6397b9b71f43SSean Christopherson 	 * Allocating rmap list entries when splitting huge pages for nested
6398dfd4eb44SSean Christopherson 	 * MMUs is uncommon as KVM needs to use a list if and only if there is
6399b9b71f43SSean Christopherson 	 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6400dfd4eb44SSean Christopherson 	 * aliased by multiple L2 gfns and/or from multiple nested roots with
6401dfd4eb44SSean Christopherson 	 * different roles.  Aliasing gfns when using TDP is atypical for VMMs;
6402dfd4eb44SSean Christopherson 	 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6403dfd4eb44SSean Christopherson 	 * but aliasing rarely occurs post-boot or for many gfns.  If there is
6404dfd4eb44SSean Christopherson 	 * only one rmap entry, rmap->val points directly at that one entry and
6405dfd4eb44SSean Christopherson 	 * doesn't need to allocate a list.  Buffer the cache by the default
6406dfd4eb44SSean Christopherson 	 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6407b9b71f43SSean Christopherson 	 * encounters an aliased gfn or two.
6408b9b71f43SSean Christopherson 	 */
6409b9b71f43SSean Christopherson 	const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6410b9b71f43SSean Christopherson 			     KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6411ada51a9dSDavid Matlack 	int r;
6412ada51a9dSDavid Matlack 
6413ada51a9dSDavid Matlack 	lockdep_assert_held(&kvm->slots_lock);
6414ada51a9dSDavid Matlack 
6415b9b71f43SSean Christopherson 	r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6416ada51a9dSDavid Matlack 					 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6417ada51a9dSDavid Matlack 	if (r)
6418ada51a9dSDavid Matlack 		return r;
6419ada51a9dSDavid Matlack 
6420ada51a9dSDavid Matlack 	r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6421ada51a9dSDavid Matlack 	if (r)
6422ada51a9dSDavid Matlack 		return r;
6423ada51a9dSDavid Matlack 
6424ada51a9dSDavid Matlack 	return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6425ada51a9dSDavid Matlack }
6426ada51a9dSDavid Matlack 
6427ada51a9dSDavid Matlack static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6428ada51a9dSDavid Matlack {
6429ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6430ada51a9dSDavid Matlack 	struct shadow_page_caches caches = {};
6431ada51a9dSDavid Matlack 	union kvm_mmu_page_role role;
6432ada51a9dSDavid Matlack 	unsigned int access;
6433ada51a9dSDavid Matlack 	gfn_t gfn;
6434ada51a9dSDavid Matlack 
643579e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
643679e48cecSSean Christopherson 	access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6437ada51a9dSDavid Matlack 
6438ada51a9dSDavid Matlack 	/*
6439ada51a9dSDavid Matlack 	 * Note, huge page splitting always uses direct shadow pages, regardless
6440ada51a9dSDavid Matlack 	 * of whether the huge page itself is mapped by a direct or indirect
6441ada51a9dSDavid Matlack 	 * shadow page, since the huge page region itself is being directly
6442ada51a9dSDavid Matlack 	 * mapped with smaller pages.
6443ada51a9dSDavid Matlack 	 */
6444ada51a9dSDavid Matlack 	role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6445ada51a9dSDavid Matlack 
6446ada51a9dSDavid Matlack 	/* Direct SPs do not require a shadowed_info_cache. */
6447ada51a9dSDavid Matlack 	caches.page_header_cache = &kvm->arch.split_page_header_cache;
6448ada51a9dSDavid Matlack 	caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6449ada51a9dSDavid Matlack 
6450ada51a9dSDavid Matlack 	/* Safe to pass NULL for vCPU since requesting a direct SP. */
6451ada51a9dSDavid Matlack 	return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6452ada51a9dSDavid Matlack }
6453ada51a9dSDavid Matlack 
6454ada51a9dSDavid Matlack static void shadow_mmu_split_huge_page(struct kvm *kvm,
6455ada51a9dSDavid Matlack 				       const struct kvm_memory_slot *slot,
6456ada51a9dSDavid Matlack 				       u64 *huge_sptep)
6457ada51a9dSDavid Matlack 
6458ada51a9dSDavid Matlack {
6459ada51a9dSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6460ada51a9dSDavid Matlack 	u64 huge_spte = READ_ONCE(*huge_sptep);
6461ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
646203787394SPaolo Bonzini 	bool flush = false;
6463ada51a9dSDavid Matlack 	u64 *sptep, spte;
6464ada51a9dSDavid Matlack 	gfn_t gfn;
6465ada51a9dSDavid Matlack 	int index;
6466ada51a9dSDavid Matlack 
6467ada51a9dSDavid Matlack 	sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6468ada51a9dSDavid Matlack 
6469ada51a9dSDavid Matlack 	for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6470ada51a9dSDavid Matlack 		sptep = &sp->spt[index];
6471ada51a9dSDavid Matlack 		gfn = kvm_mmu_page_get_gfn(sp, index);
6472ada51a9dSDavid Matlack 
6473ada51a9dSDavid Matlack 		/*
6474ada51a9dSDavid Matlack 		 * The SP may already have populated SPTEs, e.g. if this huge
6475ada51a9dSDavid Matlack 		 * page is aliased by multiple sptes with the same access
6476ada51a9dSDavid Matlack 		 * permissions. These entries are guaranteed to map the same
6477ada51a9dSDavid Matlack 		 * gfn-to-pfn translation since the SP is direct, so no need to
6478ada51a9dSDavid Matlack 		 * modify them.
6479ada51a9dSDavid Matlack 		 *
648003787394SPaolo Bonzini 		 * However, if a given SPTE points to a lower level page table,
648103787394SPaolo Bonzini 		 * that lower level page table may only be partially populated.
648203787394SPaolo Bonzini 		 * Installing such SPTEs would effectively unmap a potion of the
648303787394SPaolo Bonzini 		 * huge page. Unmapping guest memory always requires a TLB flush
648403787394SPaolo Bonzini 		 * since a subsequent operation on the unmapped regions would
648503787394SPaolo Bonzini 		 * fail to detect the need to flush.
6486ada51a9dSDavid Matlack 		 */
648703787394SPaolo Bonzini 		if (is_shadow_present_pte(*sptep)) {
648803787394SPaolo Bonzini 			flush |= !is_last_spte(*sptep, sp->role.level);
6489ada51a9dSDavid Matlack 			continue;
649003787394SPaolo Bonzini 		}
6491ada51a9dSDavid Matlack 
6492ada51a9dSDavid Matlack 		spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
6493ada51a9dSDavid Matlack 		mmu_spte_set(sptep, spte);
6494ada51a9dSDavid Matlack 		__rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6495ada51a9dSDavid Matlack 	}
6496ada51a9dSDavid Matlack 
649703787394SPaolo Bonzini 	__link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6498ada51a9dSDavid Matlack }
6499ada51a9dSDavid Matlack 
6500ada51a9dSDavid Matlack static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6501ada51a9dSDavid Matlack 					  const struct kvm_memory_slot *slot,
6502ada51a9dSDavid Matlack 					  u64 *huge_sptep)
6503ada51a9dSDavid Matlack {
6504ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6505ada51a9dSDavid Matlack 	int level, r = 0;
6506ada51a9dSDavid Matlack 	gfn_t gfn;
6507ada51a9dSDavid Matlack 	u64 spte;
6508ada51a9dSDavid Matlack 
6509ada51a9dSDavid Matlack 	/* Grab information for the tracepoint before dropping the MMU lock. */
651079e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6511ada51a9dSDavid Matlack 	level = huge_sp->role.level;
6512ada51a9dSDavid Matlack 	spte = *huge_sptep;
6513ada51a9dSDavid Matlack 
6514ada51a9dSDavid Matlack 	if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6515ada51a9dSDavid Matlack 		r = -ENOSPC;
6516ada51a9dSDavid Matlack 		goto out;
6517ada51a9dSDavid Matlack 	}
6518ada51a9dSDavid Matlack 
6519ada51a9dSDavid Matlack 	if (need_topup_split_caches_or_resched(kvm)) {
6520ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6521ada51a9dSDavid Matlack 		cond_resched();
6522ada51a9dSDavid Matlack 		/*
6523ada51a9dSDavid Matlack 		 * If the topup succeeds, return -EAGAIN to indicate that the
6524ada51a9dSDavid Matlack 		 * rmap iterator should be restarted because the MMU lock was
6525ada51a9dSDavid Matlack 		 * dropped.
6526ada51a9dSDavid Matlack 		 */
6527ada51a9dSDavid Matlack 		r = topup_split_caches(kvm) ?: -EAGAIN;
6528ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6529ada51a9dSDavid Matlack 		goto out;
6530ada51a9dSDavid Matlack 	}
6531ada51a9dSDavid Matlack 
6532ada51a9dSDavid Matlack 	shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6533ada51a9dSDavid Matlack 
6534ada51a9dSDavid Matlack out:
6535ada51a9dSDavid Matlack 	trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6536ada51a9dSDavid Matlack 	return r;
6537ada51a9dSDavid Matlack }
6538ada51a9dSDavid Matlack 
6539ada51a9dSDavid Matlack static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6540ada51a9dSDavid Matlack 					    struct kvm_rmap_head *rmap_head,
6541ada51a9dSDavid Matlack 					    const struct kvm_memory_slot *slot)
6542ada51a9dSDavid Matlack {
6543ada51a9dSDavid Matlack 	struct rmap_iterator iter;
6544ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
6545ada51a9dSDavid Matlack 	u64 *huge_sptep;
6546ada51a9dSDavid Matlack 	int r;
6547ada51a9dSDavid Matlack 
6548ada51a9dSDavid Matlack restart:
6549ada51a9dSDavid Matlack 	for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6550ada51a9dSDavid Matlack 		sp = sptep_to_sp(huge_sptep);
6551ada51a9dSDavid Matlack 
6552ada51a9dSDavid Matlack 		/* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6553ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!sp->role.guest_mode))
6554ada51a9dSDavid Matlack 			continue;
6555ada51a9dSDavid Matlack 
6556ada51a9dSDavid Matlack 		/* The rmaps should never contain non-leaf SPTEs. */
6557ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6558ada51a9dSDavid Matlack 			continue;
6559ada51a9dSDavid Matlack 
6560ada51a9dSDavid Matlack 		/* SPs with level >PG_LEVEL_4K should never by unsync. */
6561ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(sp->unsync))
6562ada51a9dSDavid Matlack 			continue;
6563ada51a9dSDavid Matlack 
6564ada51a9dSDavid Matlack 		/* Don't bother splitting huge pages on invalid SPs. */
6565ada51a9dSDavid Matlack 		if (sp->role.invalid)
6566ada51a9dSDavid Matlack 			continue;
6567ada51a9dSDavid Matlack 
6568ada51a9dSDavid Matlack 		r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6569ada51a9dSDavid Matlack 
6570ada51a9dSDavid Matlack 		/*
6571ada51a9dSDavid Matlack 		 * The split succeeded or needs to be retried because the MMU
6572ada51a9dSDavid Matlack 		 * lock was dropped. Either way, restart the iterator to get it
6573ada51a9dSDavid Matlack 		 * back into a consistent state.
6574ada51a9dSDavid Matlack 		 */
6575ada51a9dSDavid Matlack 		if (!r || r == -EAGAIN)
6576ada51a9dSDavid Matlack 			goto restart;
6577ada51a9dSDavid Matlack 
6578ada51a9dSDavid Matlack 		/* The split failed and shouldn't be retried (e.g. -ENOMEM). */
6579ada51a9dSDavid Matlack 		break;
6580ada51a9dSDavid Matlack 	}
6581ada51a9dSDavid Matlack 
6582ada51a9dSDavid Matlack 	return false;
6583ada51a9dSDavid Matlack }
6584ada51a9dSDavid Matlack 
6585ada51a9dSDavid Matlack static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6586ada51a9dSDavid Matlack 						const struct kvm_memory_slot *slot,
6587ada51a9dSDavid Matlack 						gfn_t start, gfn_t end,
6588ada51a9dSDavid Matlack 						int target_level)
6589ada51a9dSDavid Matlack {
6590ada51a9dSDavid Matlack 	int level;
6591ada51a9dSDavid Matlack 
6592ada51a9dSDavid Matlack 	/*
6593ada51a9dSDavid Matlack 	 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
6594ada51a9dSDavid Matlack 	 * down to the target level. This ensures pages are recursively split
6595ada51a9dSDavid Matlack 	 * all the way to the target level. There's no need to split pages
6596ada51a9dSDavid Matlack 	 * already at the target level.
6597ada51a9dSDavid Matlack 	 */
6598727ae377SSean Christopherson 	for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--)
6599727ae377SSean Christopherson 		__walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,
6600ada51a9dSDavid Matlack 				  level, level, start, end - 1, true, false);
6601ada51a9dSDavid Matlack }
6602ada51a9dSDavid Matlack 
6603cb00a70bSDavid Matlack /* Must be called with the mmu_lock held in write-mode. */
6604cb00a70bSDavid Matlack void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6605cb00a70bSDavid Matlack 				   const struct kvm_memory_slot *memslot,
6606cb00a70bSDavid Matlack 				   u64 start, u64 end,
6607cb00a70bSDavid Matlack 				   int target_level)
6608cb00a70bSDavid Matlack {
66091f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6610ada51a9dSDavid Matlack 		return;
6611ada51a9dSDavid Matlack 
6612ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm))
6613ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6614ada51a9dSDavid Matlack 
6615ada51a9dSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
6616cb00a70bSDavid Matlack 
6617cb00a70bSDavid Matlack 	/*
661854aa699eSBjorn Helgaas 	 * A TLB flush is unnecessary at this point for the same reasons as in
6619cb00a70bSDavid Matlack 	 * kvm_mmu_slot_try_split_huge_pages().
6620cb00a70bSDavid Matlack 	 */
6621cb00a70bSDavid Matlack }
6622cb00a70bSDavid Matlack 
6623a3fe5dbdSDavid Matlack void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6624a3fe5dbdSDavid Matlack 					const struct kvm_memory_slot *memslot,
6625a3fe5dbdSDavid Matlack 					int target_level)
6626a3fe5dbdSDavid Matlack {
6627a3fe5dbdSDavid Matlack 	u64 start = memslot->base_gfn;
6628a3fe5dbdSDavid Matlack 	u64 end = start + memslot->npages;
6629a3fe5dbdSDavid Matlack 
66301f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6631ada51a9dSDavid Matlack 		return;
6632ada51a9dSDavid Matlack 
6633ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm)) {
6634ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6635ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6636ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6637ada51a9dSDavid Matlack 	}
6638ada51a9dSDavid Matlack 
6639a3fe5dbdSDavid Matlack 	read_lock(&kvm->mmu_lock);
6640cb00a70bSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6641a3fe5dbdSDavid Matlack 	read_unlock(&kvm->mmu_lock);
6642a3fe5dbdSDavid Matlack 
6643a3fe5dbdSDavid Matlack 	/*
6644a3fe5dbdSDavid Matlack 	 * No TLB flush is necessary here. KVM will flush TLBs after
6645a3fe5dbdSDavid Matlack 	 * write-protecting and/or clearing dirty on the newly split SPTEs to
6646a3fe5dbdSDavid Matlack 	 * ensure that guest writes are reflected in the dirty log before the
6647a3fe5dbdSDavid Matlack 	 * ioctl to enable dirty logging on this memslot completes. Since the
6648a3fe5dbdSDavid Matlack 	 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6649a3fe5dbdSDavid Matlack 	 * safe for KVM to decide if a TLB flush is necessary based on the split
6650a3fe5dbdSDavid Matlack 	 * SPTEs.
6651a3fe5dbdSDavid Matlack 	 */
6652a3fe5dbdSDavid Matlack }
6653a3fe5dbdSDavid Matlack 
6654c50d8ae3SPaolo Bonzini static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
66550a234f5dSSean Christopherson 					 struct kvm_rmap_head *rmap_head,
6656269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
6657c50d8ae3SPaolo Bonzini {
6658c50d8ae3SPaolo Bonzini 	u64 *sptep;
6659c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
6660c50d8ae3SPaolo Bonzini 	int need_tlb_flush = 0;
6661c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6662c50d8ae3SPaolo Bonzini 
6663c50d8ae3SPaolo Bonzini restart:
6664c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
666557354682SSean Christopherson 		sp = sptep_to_sp(sptep);
6666c50d8ae3SPaolo Bonzini 
6667c50d8ae3SPaolo Bonzini 		/*
6668c50d8ae3SPaolo Bonzini 		 * We cannot do huge page mapping for indirect shadow pages,
6669c50d8ae3SPaolo Bonzini 		 * which are found on the last rmap (level = 1) when not using
6670c50d8ae3SPaolo Bonzini 		 * tdp; such shadow pages are synced with the page table in
6671c50d8ae3SPaolo Bonzini 		 * the guest, and the guest page table is using 4K page size
6672c50d8ae3SPaolo Bonzini 		 * mapping if the indirect sp has level = 1.
6673c50d8ae3SPaolo Bonzini 		 */
66745d49f08cSSean Christopherson 		if (sp->role.direct &&
66759eba50f8SSean Christopherson 		    sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
6676a8ac499bSSean Christopherson 							       PG_LEVEL_NUM)) {
66779202aee8SSean Christopherson 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
6678c50d8ae3SPaolo Bonzini 
66798a1300ffSSean Christopherson 			if (kvm_available_flush_remote_tlbs_range())
66801b2dc736SHou Wenlong 				kvm_flush_remote_tlbs_sptep(kvm, sptep);
6681c50d8ae3SPaolo Bonzini 			else
6682c50d8ae3SPaolo Bonzini 				need_tlb_flush = 1;
6683c50d8ae3SPaolo Bonzini 
6684c50d8ae3SPaolo Bonzini 			goto restart;
6685c50d8ae3SPaolo Bonzini 		}
6686c50d8ae3SPaolo Bonzini 	}
6687c50d8ae3SPaolo Bonzini 
6688c50d8ae3SPaolo Bonzini 	return need_tlb_flush;
6689c50d8ae3SPaolo Bonzini }
6690c50d8ae3SPaolo Bonzini 
669120d49186SDavid Matlack static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
669220d49186SDavid Matlack 					   const struct kvm_memory_slot *slot)
669320d49186SDavid Matlack {
669420d49186SDavid Matlack 	/*
669520d49186SDavid Matlack 	 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
669620d49186SDavid Matlack 	 * pages that are already mapped at the maximum hugepage level.
669720d49186SDavid Matlack 	 */
6698727ae377SSean Christopherson 	if (walk_slot_rmaps(kvm, slot, kvm_mmu_zap_collapsible_spte,
669920d49186SDavid Matlack 			    PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
6700619b5072SDavid Matlack 		kvm_flush_remote_tlbs_memslot(kvm, slot);
670120d49186SDavid Matlack }
670220d49186SDavid Matlack 
6703c50d8ae3SPaolo Bonzini void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6704269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *slot)
6705c50d8ae3SPaolo Bonzini {
6706e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6707531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
670820d49186SDavid Matlack 		kvm_rmap_zap_collapsible_sptes(kvm, slot);
6709531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6710e2209710SBen Gardon 	}
67112db6f772SBen Gardon 
67121f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
67132db6f772SBen Gardon 		read_lock(&kvm->mmu_lock);
67144b85c921SSean Christopherson 		kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
67152db6f772SBen Gardon 		read_unlock(&kvm->mmu_lock);
67162db6f772SBen Gardon 	}
6717c50d8ae3SPaolo Bonzini }
6718c50d8ae3SPaolo Bonzini 
6719c50d8ae3SPaolo Bonzini void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6720269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *memslot)
6721c50d8ae3SPaolo Bonzini {
6722e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6723531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6724610265eaSDavid Matlack 		/*
6725610265eaSDavid Matlack 		 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6726610265eaSDavid Matlack 		 * support dirty logging at a 4k granularity.
6727610265eaSDavid Matlack 		 */
6728727ae377SSean Christopherson 		walk_slot_rmaps_4k(kvm, memslot, __rmap_clear_dirty, false);
6729531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6730e2209710SBen Gardon 	}
6731c50d8ae3SPaolo Bonzini 
67321f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
673324ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6734b64d740eSJunaid Shahid 		kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
673524ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
673624ae4cfaSBen Gardon 	}
673724ae4cfaSBen Gardon 
6738c50d8ae3SPaolo Bonzini 	/*
6739b64d740eSJunaid Shahid 	 * The caller will flush the TLBs after this function returns.
6740b64d740eSJunaid Shahid 	 *
6741c50d8ae3SPaolo Bonzini 	 * It's also safe to flush TLBs out of mmu lock here as currently this
6742c50d8ae3SPaolo Bonzini 	 * function is only used for dirty logging, in which case flushing TLB
6743c50d8ae3SPaolo Bonzini 	 * out of mmu lock also guarantees no dirty pages will be lost in
6744c50d8ae3SPaolo Bonzini 	 * dirty_bitmap.
6745c50d8ae3SPaolo Bonzini 	 */
6746c50d8ae3SPaolo Bonzini }
6747c50d8ae3SPaolo Bonzini 
6748db0d70e6SSean Christopherson static void kvm_mmu_zap_all(struct kvm *kvm)
6749c50d8ae3SPaolo Bonzini {
6750c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6751c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6752c50d8ae3SPaolo Bonzini 	int ign;
6753c50d8ae3SPaolo Bonzini 
6754531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6755c50d8ae3SPaolo Bonzini restart:
6756c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
675720ba462dSSean Christopherson 		if (WARN_ON_ONCE(sp->role.invalid))
6758c50d8ae3SPaolo Bonzini 			continue;
6759c50d8ae3SPaolo Bonzini 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6760c50d8ae3SPaolo Bonzini 			goto restart;
6761531810caSBen Gardon 		if (cond_resched_rwlock_write(&kvm->mmu_lock))
6762c50d8ae3SPaolo Bonzini 			goto restart;
6763c50d8ae3SPaolo Bonzini 	}
6764c50d8ae3SPaolo Bonzini 
6765c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6766faaf05b0SBen Gardon 
67671f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6768faaf05b0SBen Gardon 		kvm_tdp_mmu_zap_all(kvm);
6769faaf05b0SBen Gardon 
6770531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
6771c50d8ae3SPaolo Bonzini }
6772c50d8ae3SPaolo Bonzini 
6773db0d70e6SSean Christopherson void kvm_arch_flush_shadow_all(struct kvm *kvm)
6774db0d70e6SSean Christopherson {
6775db0d70e6SSean Christopherson 	kvm_mmu_zap_all(kvm);
6776db0d70e6SSean Christopherson }
6777db0d70e6SSean Christopherson 
6778db0d70e6SSean Christopherson void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
6779db0d70e6SSean Christopherson 				   struct kvm_memory_slot *slot)
6780db0d70e6SSean Christopherson {
6781eeb87272SSean Christopherson 	kvm_mmu_zap_all_fast(kvm);
6782db0d70e6SSean Christopherson }
6783db0d70e6SSean Christopherson 
6784c50d8ae3SPaolo Bonzini void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6785c50d8ae3SPaolo Bonzini {
678620ba462dSSean Christopherson 	WARN_ON_ONCE(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6787c50d8ae3SPaolo Bonzini 
6788c50d8ae3SPaolo Bonzini 	gen &= MMIO_SPTE_GEN_MASK;
6789c50d8ae3SPaolo Bonzini 
6790c50d8ae3SPaolo Bonzini 	/*
6791c50d8ae3SPaolo Bonzini 	 * Generation numbers are incremented in multiples of the number of
6792c50d8ae3SPaolo Bonzini 	 * address spaces in order to provide unique generations across all
6793c50d8ae3SPaolo Bonzini 	 * address spaces.  Strip what is effectively the address space
6794c50d8ae3SPaolo Bonzini 	 * modifier prior to checking for a wrap of the MMIO generation so
6795c50d8ae3SPaolo Bonzini 	 * that a wrap in any address space is detected.
6796c50d8ae3SPaolo Bonzini 	 */
6797eed52e43SSean Christopherson 	gen &= ~((u64)kvm_arch_nr_memslot_as_ids(kvm) - 1);
6798c50d8ae3SPaolo Bonzini 
6799c50d8ae3SPaolo Bonzini 	/*
6800c50d8ae3SPaolo Bonzini 	 * The very rare case: if the MMIO generation number has wrapped,
6801c50d8ae3SPaolo Bonzini 	 * zap all shadow pages.
6802c50d8ae3SPaolo Bonzini 	 */
6803c50d8ae3SPaolo Bonzini 	if (unlikely(gen == 0)) {
68048d20bd63SSean Christopherson 		kvm_debug_ratelimited("zapping shadow pages for mmio generation wraparound\n");
6805c50d8ae3SPaolo Bonzini 		kvm_mmu_zap_all_fast(kvm);
6806c50d8ae3SPaolo Bonzini 	}
6807c50d8ae3SPaolo Bonzini }
6808c50d8ae3SPaolo Bonzini 
6809f3d90f90SSean Christopherson static unsigned long mmu_shrink_scan(struct shrinker *shrink,
6810f3d90f90SSean Christopherson 				     struct shrink_control *sc)
6811c50d8ae3SPaolo Bonzini {
6812c50d8ae3SPaolo Bonzini 	struct kvm *kvm;
6813c50d8ae3SPaolo Bonzini 	int nr_to_scan = sc->nr_to_scan;
6814c50d8ae3SPaolo Bonzini 	unsigned long freed = 0;
6815c50d8ae3SPaolo Bonzini 
6816c50d8ae3SPaolo Bonzini 	mutex_lock(&kvm_lock);
6817c50d8ae3SPaolo Bonzini 
6818c50d8ae3SPaolo Bonzini 	list_for_each_entry(kvm, &vm_list, vm_list) {
6819c50d8ae3SPaolo Bonzini 		int idx;
6820c50d8ae3SPaolo Bonzini 		LIST_HEAD(invalid_list);
6821c50d8ae3SPaolo Bonzini 
6822c50d8ae3SPaolo Bonzini 		/*
6823c50d8ae3SPaolo Bonzini 		 * Never scan more than sc->nr_to_scan VM instances.
6824c50d8ae3SPaolo Bonzini 		 * Will not hit this condition practically since we do not try
6825c50d8ae3SPaolo Bonzini 		 * to shrink more than one VM and it is very unlikely to see
6826c50d8ae3SPaolo Bonzini 		 * !n_used_mmu_pages so many times.
6827c50d8ae3SPaolo Bonzini 		 */
6828c50d8ae3SPaolo Bonzini 		if (!nr_to_scan--)
6829c50d8ae3SPaolo Bonzini 			break;
6830c50d8ae3SPaolo Bonzini 		/*
6831c50d8ae3SPaolo Bonzini 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6832c50d8ae3SPaolo Bonzini 		 * here. We may skip a VM instance errorneosly, but we do not
6833c50d8ae3SPaolo Bonzini 		 * want to shrink a VM that only started to populate its MMU
6834c50d8ae3SPaolo Bonzini 		 * anyway.
6835c50d8ae3SPaolo Bonzini 		 */
6836c50d8ae3SPaolo Bonzini 		if (!kvm->arch.n_used_mmu_pages &&
6837c50d8ae3SPaolo Bonzini 		    !kvm_has_zapped_obsolete_pages(kvm))
6838c50d8ae3SPaolo Bonzini 			continue;
6839c50d8ae3SPaolo Bonzini 
6840c50d8ae3SPaolo Bonzini 		idx = srcu_read_lock(&kvm->srcu);
6841531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6842c50d8ae3SPaolo Bonzini 
6843c50d8ae3SPaolo Bonzini 		if (kvm_has_zapped_obsolete_pages(kvm)) {
6844c50d8ae3SPaolo Bonzini 			kvm_mmu_commit_zap_page(kvm,
6845c50d8ae3SPaolo Bonzini 			      &kvm->arch.zapped_obsolete_pages);
6846c50d8ae3SPaolo Bonzini 			goto unlock;
6847c50d8ae3SPaolo Bonzini 		}
6848c50d8ae3SPaolo Bonzini 
6849ebdb292dSSean Christopherson 		freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6850c50d8ae3SPaolo Bonzini 
6851c50d8ae3SPaolo Bonzini unlock:
6852531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6853c50d8ae3SPaolo Bonzini 		srcu_read_unlock(&kvm->srcu, idx);
6854c50d8ae3SPaolo Bonzini 
6855c50d8ae3SPaolo Bonzini 		/*
6856c50d8ae3SPaolo Bonzini 		 * unfair on small ones
6857c50d8ae3SPaolo Bonzini 		 * per-vm shrinkers cry out
6858c50d8ae3SPaolo Bonzini 		 * sadness comes quickly
6859c50d8ae3SPaolo Bonzini 		 */
6860c50d8ae3SPaolo Bonzini 		list_move_tail(&kvm->vm_list, &vm_list);
6861c50d8ae3SPaolo Bonzini 		break;
6862c50d8ae3SPaolo Bonzini 	}
6863c50d8ae3SPaolo Bonzini 
6864c50d8ae3SPaolo Bonzini 	mutex_unlock(&kvm_lock);
6865c50d8ae3SPaolo Bonzini 	return freed;
6866c50d8ae3SPaolo Bonzini }
6867c50d8ae3SPaolo Bonzini 
6868f3d90f90SSean Christopherson static unsigned long mmu_shrink_count(struct shrinker *shrink,
6869f3d90f90SSean Christopherson 				      struct shrink_control *sc)
6870c50d8ae3SPaolo Bonzini {
6871c50d8ae3SPaolo Bonzini 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6872c50d8ae3SPaolo Bonzini }
6873c50d8ae3SPaolo Bonzini 
6874e5985c40SQi Zheng static struct shrinker *mmu_shrinker;
6875c50d8ae3SPaolo Bonzini 
6876c50d8ae3SPaolo Bonzini static void mmu_destroy_caches(void)
6877c50d8ae3SPaolo Bonzini {
6878c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(pte_list_desc_cache);
6879c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(mmu_page_header_cache);
6880c50d8ae3SPaolo Bonzini }
6881c50d8ae3SPaolo Bonzini 
68820b210fafSSean Christopherson static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp)
68830b210fafSSean Christopherson {
68840b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
68851d6664faSLike Xu 		return sysfs_emit(buffer, "never\n");
68860b210fafSSean Christopherson 
68870b210fafSSean Christopherson 	return param_get_bool(buffer, kp);
68880b210fafSSean Christopherson }
68890b210fafSSean Christopherson 
6890c50d8ae3SPaolo Bonzini static bool get_nx_auto_mode(void)
6891c50d8ae3SPaolo Bonzini {
6892c50d8ae3SPaolo Bonzini 	/* Return true when CPU has the bug, and mitigations are ON */
6893c50d8ae3SPaolo Bonzini 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6894c50d8ae3SPaolo Bonzini }
6895c50d8ae3SPaolo Bonzini 
6896c50d8ae3SPaolo Bonzini static void __set_nx_huge_pages(bool val)
6897c50d8ae3SPaolo Bonzini {
6898c50d8ae3SPaolo Bonzini 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6899c50d8ae3SPaolo Bonzini }
6900c50d8ae3SPaolo Bonzini 
6901c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6902c50d8ae3SPaolo Bonzini {
6903c50d8ae3SPaolo Bonzini 	bool old_val = nx_huge_pages;
6904c50d8ae3SPaolo Bonzini 	bool new_val;
6905c50d8ae3SPaolo Bonzini 
69060b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
69070b210fafSSean Christopherson 		return -EPERM;
69080b210fafSSean Christopherson 
6909c50d8ae3SPaolo Bonzini 	/* In "auto" mode deploy workaround only if CPU has the bug. */
69100b210fafSSean Christopherson 	if (sysfs_streq(val, "off")) {
6911c50d8ae3SPaolo Bonzini 		new_val = 0;
69120b210fafSSean Christopherson 	} else if (sysfs_streq(val, "force")) {
6913c50d8ae3SPaolo Bonzini 		new_val = 1;
69140b210fafSSean Christopherson 	} else if (sysfs_streq(val, "auto")) {
6915c50d8ae3SPaolo Bonzini 		new_val = get_nx_auto_mode();
69160b210fafSSean Christopherson 	} else if (sysfs_streq(val, "never")) {
69170b210fafSSean Christopherson 		new_val = 0;
69180b210fafSSean Christopherson 
69190b210fafSSean Christopherson 		mutex_lock(&kvm_lock);
69200b210fafSSean Christopherson 		if (!list_empty(&vm_list)) {
69210b210fafSSean Christopherson 			mutex_unlock(&kvm_lock);
69220b210fafSSean Christopherson 			return -EBUSY;
69230b210fafSSean Christopherson 		}
69240b210fafSSean Christopherson 		nx_hugepage_mitigation_hard_disabled = true;
69250b210fafSSean Christopherson 		mutex_unlock(&kvm_lock);
69260b210fafSSean Christopherson 	} else if (kstrtobool(val, &new_val) < 0) {
6927c50d8ae3SPaolo Bonzini 		return -EINVAL;
69280b210fafSSean Christopherson 	}
6929c50d8ae3SPaolo Bonzini 
6930c50d8ae3SPaolo Bonzini 	__set_nx_huge_pages(new_val);
6931c50d8ae3SPaolo Bonzini 
6932c50d8ae3SPaolo Bonzini 	if (new_val != old_val) {
6933c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6934c50d8ae3SPaolo Bonzini 
6935c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6936c50d8ae3SPaolo Bonzini 
6937c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list) {
6938c50d8ae3SPaolo Bonzini 			mutex_lock(&kvm->slots_lock);
6939c50d8ae3SPaolo Bonzini 			kvm_mmu_zap_all_fast(kvm);
6940c50d8ae3SPaolo Bonzini 			mutex_unlock(&kvm->slots_lock);
6941c50d8ae3SPaolo Bonzini 
694255c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
6943c50d8ae3SPaolo Bonzini 		}
6944c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6945c50d8ae3SPaolo Bonzini 	}
6946c50d8ae3SPaolo Bonzini 
6947c50d8ae3SPaolo Bonzini 	return 0;
6948c50d8ae3SPaolo Bonzini }
6949c50d8ae3SPaolo Bonzini 
69501d0e8480SSean Christopherson /*
69511d0e8480SSean Christopherson  * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
69521d0e8480SSean Christopherson  * its default value of -1 is technically undefined behavior for a boolean.
6953c3e0c8c2SSean Christopherson  * Forward the module init call to SPTE code so that it too can handle module
6954c3e0c8c2SSean Christopherson  * params that need to be resolved/snapshot.
69551d0e8480SSean Christopherson  */
6956982bae43SSean Christopherson void __init kvm_mmu_x86_module_init(void)
6957c50d8ae3SPaolo Bonzini {
6958c50d8ae3SPaolo Bonzini 	if (nx_huge_pages == -1)
6959c50d8ae3SPaolo Bonzini 		__set_nx_huge_pages(get_nx_auto_mode());
6960c3e0c8c2SSean Christopherson 
69611f98f2bdSDavid Matlack 	/*
69621f98f2bdSDavid Matlack 	 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
69631f98f2bdSDavid Matlack 	 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
69641f98f2bdSDavid Matlack 	 * when the vendor module is loaded.
69651f98f2bdSDavid Matlack 	 */
69661f98f2bdSDavid Matlack 	tdp_mmu_allowed = tdp_mmu_enabled;
69671f98f2bdSDavid Matlack 
6968c3e0c8c2SSean Christopherson 	kvm_mmu_spte_module_init();
69691d0e8480SSean Christopherson }
69701d0e8480SSean Christopherson 
69711d0e8480SSean Christopherson /*
69721d0e8480SSean Christopherson  * The bulk of the MMU initialization is deferred until the vendor module is
69731d0e8480SSean Christopherson  * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
69741d0e8480SSean Christopherson  * to be reset when a potentially different vendor module is loaded.
69751d0e8480SSean Christopherson  */
69761d0e8480SSean Christopherson int kvm_mmu_vendor_module_init(void)
69771d0e8480SSean Christopherson {
69781d0e8480SSean Christopherson 	int ret = -ENOMEM;
6979c50d8ae3SPaolo Bonzini 
6980c50d8ae3SPaolo Bonzini 	/*
6981c50d8ae3SPaolo Bonzini 	 * MMU roles use union aliasing which is, generally speaking, an
6982c50d8ae3SPaolo Bonzini 	 * undefined behavior. However, we supposedly know how compilers behave
6983c50d8ae3SPaolo Bonzini 	 * and the current status quo is unlikely to change. Guardians below are
6984c50d8ae3SPaolo Bonzini 	 * supposed to let us know if the assumption becomes false.
6985c50d8ae3SPaolo Bonzini 	 */
6986c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6987c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
69887a7ae829SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
6989c50d8ae3SPaolo Bonzini 
6990c50d8ae3SPaolo Bonzini 	kvm_mmu_reset_all_pte_masks();
6991c50d8ae3SPaolo Bonzini 
69920dbd0546SKunwu Chan 	pte_list_desc_cache = KMEM_CACHE(pte_list_desc, SLAB_ACCOUNT);
6993c50d8ae3SPaolo Bonzini 	if (!pte_list_desc_cache)
6994c50d8ae3SPaolo Bonzini 		goto out;
6995c50d8ae3SPaolo Bonzini 
6996c50d8ae3SPaolo Bonzini 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6997c50d8ae3SPaolo Bonzini 						  sizeof(struct kvm_mmu_page),
6998c50d8ae3SPaolo Bonzini 						  0, SLAB_ACCOUNT, NULL);
6999c50d8ae3SPaolo Bonzini 	if (!mmu_page_header_cache)
7000c50d8ae3SPaolo Bonzini 		goto out;
7001c50d8ae3SPaolo Bonzini 
7002c50d8ae3SPaolo Bonzini 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
7003c50d8ae3SPaolo Bonzini 		goto out;
7004c50d8ae3SPaolo Bonzini 
7005e5985c40SQi Zheng 	mmu_shrinker = shrinker_alloc(0, "x86-mmu");
7006e5985c40SQi Zheng 	if (!mmu_shrinker)
7007d7c9bfb9SMiaohe Lin 		goto out_shrinker;
7008c50d8ae3SPaolo Bonzini 
7009e5985c40SQi Zheng 	mmu_shrinker->count_objects = mmu_shrink_count;
7010e5985c40SQi Zheng 	mmu_shrinker->scan_objects = mmu_shrink_scan;
7011e5985c40SQi Zheng 	mmu_shrinker->seeks = DEFAULT_SEEKS * 10;
7012e5985c40SQi Zheng 
7013e5985c40SQi Zheng 	shrinker_register(mmu_shrinker);
7014e5985c40SQi Zheng 
7015c50d8ae3SPaolo Bonzini 	return 0;
7016c50d8ae3SPaolo Bonzini 
7017d7c9bfb9SMiaohe Lin out_shrinker:
7018d7c9bfb9SMiaohe Lin 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
7019c50d8ae3SPaolo Bonzini out:
7020c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
7021c50d8ae3SPaolo Bonzini 	return ret;
7022c50d8ae3SPaolo Bonzini }
7023c50d8ae3SPaolo Bonzini 
7024c50d8ae3SPaolo Bonzini void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
7025c50d8ae3SPaolo Bonzini {
7026c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
7027c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.root_mmu);
7028c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
7029c50d8ae3SPaolo Bonzini 	mmu_free_memory_caches(vcpu);
7030c50d8ae3SPaolo Bonzini }
7031c50d8ae3SPaolo Bonzini 
70321d0e8480SSean Christopherson void kvm_mmu_vendor_module_exit(void)
7033c50d8ae3SPaolo Bonzini {
7034c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
7035c50d8ae3SPaolo Bonzini 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
7036e5985c40SQi Zheng 	shrinker_free(mmu_shrinker);
7037c50d8ae3SPaolo Bonzini }
7038c50d8ae3SPaolo Bonzini 
7039f47491d7SSean Christopherson /*
7040f47491d7SSean Christopherson  * Calculate the effective recovery period, accounting for '0' meaning "let KVM
7041f47491d7SSean Christopherson  * select a halving time of 1 hour".  Returns true if recovery is enabled.
7042f47491d7SSean Christopherson  */
7043f47491d7SSean Christopherson static bool calc_nx_huge_pages_recovery_period(uint *period)
7044f47491d7SSean Christopherson {
7045f47491d7SSean Christopherson 	/*
7046f47491d7SSean Christopherson 	 * Use READ_ONCE to get the params, this may be called outside of the
7047f47491d7SSean Christopherson 	 * param setters, e.g. by the kthread to compute its next timeout.
7048f47491d7SSean Christopherson 	 */
7049f47491d7SSean Christopherson 	bool enabled = READ_ONCE(nx_huge_pages);
7050f47491d7SSean Christopherson 	uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7051f47491d7SSean Christopherson 
7052f47491d7SSean Christopherson 	if (!enabled || !ratio)
7053f47491d7SSean Christopherson 		return false;
7054f47491d7SSean Christopherson 
7055f47491d7SSean Christopherson 	*period = READ_ONCE(nx_huge_pages_recovery_period_ms);
7056f47491d7SSean Christopherson 	if (!*period) {
7057f47491d7SSean Christopherson 		/* Make sure the period is not less than one second.  */
7058f47491d7SSean Christopherson 		ratio = min(ratio, 3600u);
7059f47491d7SSean Christopherson 		*period = 60 * 60 * 1000 / ratio;
7060f47491d7SSean Christopherson 	}
7061f47491d7SSean Christopherson 	return true;
7062f47491d7SSean Christopherson }
7063f47491d7SSean Christopherson 
70644dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
7065c50d8ae3SPaolo Bonzini {
70664dfe4f40SJunaid Shahid 	bool was_recovery_enabled, is_recovery_enabled;
70674dfe4f40SJunaid Shahid 	uint old_period, new_period;
7068c50d8ae3SPaolo Bonzini 	int err;
7069c50d8ae3SPaolo Bonzini 
70700b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
70710b210fafSSean Christopherson 		return -EPERM;
70720b210fafSSean Christopherson 
7073f47491d7SSean Christopherson 	was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
70744dfe4f40SJunaid Shahid 
7075c50d8ae3SPaolo Bonzini 	err = param_set_uint(val, kp);
7076c50d8ae3SPaolo Bonzini 	if (err)
7077c50d8ae3SPaolo Bonzini 		return err;
7078c50d8ae3SPaolo Bonzini 
7079f47491d7SSean Christopherson 	is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
70804dfe4f40SJunaid Shahid 
7081f47491d7SSean Christopherson 	if (is_recovery_enabled &&
70824dfe4f40SJunaid Shahid 	    (!was_recovery_enabled || old_period > new_period)) {
7083c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
7084c50d8ae3SPaolo Bonzini 
7085c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
7086c50d8ae3SPaolo Bonzini 
7087c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list)
708855c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
7089c50d8ae3SPaolo Bonzini 
7090c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
7091c50d8ae3SPaolo Bonzini 	}
7092c50d8ae3SPaolo Bonzini 
7093c50d8ae3SPaolo Bonzini 	return err;
7094c50d8ae3SPaolo Bonzini }
7095c50d8ae3SPaolo Bonzini 
709655c510e2SSean Christopherson static void kvm_recover_nx_huge_pages(struct kvm *kvm)
7097c50d8ae3SPaolo Bonzini {
7098ade74e14SSean Christopherson 	unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
7099eb298605SDavid Matlack 	struct kvm_memory_slot *slot;
7100c50d8ae3SPaolo Bonzini 	int rcu_idx;
7101c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
7102c50d8ae3SPaolo Bonzini 	unsigned int ratio;
7103c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
7104048f4980SSean Christopherson 	bool flush = false;
7105c50d8ae3SPaolo Bonzini 	ulong to_zap;
7106c50d8ae3SPaolo Bonzini 
7107c50d8ae3SPaolo Bonzini 	rcu_idx = srcu_read_lock(&kvm->srcu);
7108531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
7109c50d8ae3SPaolo Bonzini 
7110bb95dfb9SSean Christopherson 	/*
7111bb95dfb9SSean Christopherson 	 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
7112bb95dfb9SSean Christopherson 	 * be done under RCU protection, because the pages are freed via RCU
7113bb95dfb9SSean Christopherson 	 * callback.
7114bb95dfb9SSean Christopherson 	 */
7115bb95dfb9SSean Christopherson 	rcu_read_lock();
7116bb95dfb9SSean Christopherson 
7117c50d8ae3SPaolo Bonzini 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7118ade74e14SSean Christopherson 	to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
71197d919c7aSSean Christopherson 	for ( ; to_zap; --to_zap) {
712055c510e2SSean Christopherson 		if (list_empty(&kvm->arch.possible_nx_huge_pages))
71217d919c7aSSean Christopherson 			break;
71227d919c7aSSean Christopherson 
7123c50d8ae3SPaolo Bonzini 		/*
7124c50d8ae3SPaolo Bonzini 		 * We use a separate list instead of just using active_mmu_pages
712555c510e2SSean Christopherson 		 * because the number of shadow pages that be replaced with an
712655c510e2SSean Christopherson 		 * NX huge page is expected to be relatively small compared to
712755c510e2SSean Christopherson 		 * the total number of shadow pages.  And because the TDP MMU
712855c510e2SSean Christopherson 		 * doesn't use active_mmu_pages.
7129c50d8ae3SPaolo Bonzini 		 */
713055c510e2SSean Christopherson 		sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
7131c50d8ae3SPaolo Bonzini 				      struct kvm_mmu_page,
713255c510e2SSean Christopherson 				      possible_nx_huge_page_link);
713355c510e2SSean Christopherson 		WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
7134eb298605SDavid Matlack 		WARN_ON_ONCE(!sp->role.direct);
7135eb298605SDavid Matlack 
7136eb298605SDavid Matlack 		/*
7137eb298605SDavid Matlack 		 * Unaccount and do not attempt to recover any NX Huge Pages
7138eb298605SDavid Matlack 		 * that are being dirty tracked, as they would just be faulted
7139eb298605SDavid Matlack 		 * back in as 4KiB pages. The NX Huge Pages in this slot will be
7140eb298605SDavid Matlack 		 * recovered, along with all the other huge pages in the slot,
7141eb298605SDavid Matlack 		 * when dirty logging is disabled.
71426c7b2202SPaolo Bonzini 		 *
71436c7b2202SPaolo Bonzini 		 * Since gfn_to_memslot() is relatively expensive, it helps to
71446c7b2202SPaolo Bonzini 		 * skip it if it the test cannot possibly return true.  On the
71456c7b2202SPaolo Bonzini 		 * other hand, if any memslot has logging enabled, chances are
71466c7b2202SPaolo Bonzini 		 * good that all of them do, in which case unaccount_nx_huge_page()
71476c7b2202SPaolo Bonzini 		 * is much cheaper than zapping the page.
71486c7b2202SPaolo Bonzini 		 *
71496c7b2202SPaolo Bonzini 		 * If a memslot update is in progress, reading an incorrect value
71506c7b2202SPaolo Bonzini 		 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
71516c7b2202SPaolo Bonzini 		 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
71526c7b2202SPaolo Bonzini 		 * it is becoming nonzero, the page will be zapped unnecessarily.
71536c7b2202SPaolo Bonzini 		 * Either way, this only affects efficiency in racy situations,
71546c7b2202SPaolo Bonzini 		 * and not correctness.
7155eb298605SDavid Matlack 		 */
71566c7b2202SPaolo Bonzini 		slot = NULL;
71576c7b2202SPaolo Bonzini 		if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
7158817fa998SSean Christopherson 			struct kvm_memslots *slots;
7159817fa998SSean Christopherson 
7160817fa998SSean Christopherson 			slots = kvm_memslots_for_spte_role(kvm, sp->role);
7161817fa998SSean Christopherson 			slot = __gfn_to_memslot(slots, sp->gfn);
71626c7b2202SPaolo Bonzini 			WARN_ON_ONCE(!slot);
716329cf0f50SBen Gardon 		}
7164c50d8ae3SPaolo Bonzini 
7165eb298605SDavid Matlack 		if (slot && kvm_slot_dirty_track_enabled(slot))
7166eb298605SDavid Matlack 			unaccount_nx_huge_page(kvm, sp);
7167eb298605SDavid Matlack 		else if (is_tdp_mmu_page(sp))
7168c50d8ae3SPaolo Bonzini 			flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
71693a056757SSean Christopherson 		else
7170c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
717155c510e2SSean Christopherson 		WARN_ON_ONCE(sp->nx_huge_page_disallowed);
7172c50d8ae3SPaolo Bonzini 
7173531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7174048f4980SSean Christopherson 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7175bb95dfb9SSean Christopherson 			rcu_read_unlock();
7176bb95dfb9SSean Christopherson 
7177531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
7178048f4980SSean Christopherson 			flush = false;
7179bb95dfb9SSean Christopherson 
7180bb95dfb9SSean Christopherson 			rcu_read_lock();
7181c50d8ae3SPaolo Bonzini 		}
7182c50d8ae3SPaolo Bonzini 	}
7183048f4980SSean Christopherson 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7184c50d8ae3SPaolo Bonzini 
7185bb95dfb9SSean Christopherson 	rcu_read_unlock();
7186bb95dfb9SSean Christopherson 
7187531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
7188c50d8ae3SPaolo Bonzini 	srcu_read_unlock(&kvm->srcu, rcu_idx);
7189c50d8ae3SPaolo Bonzini }
7190c50d8ae3SPaolo Bonzini 
719155c510e2SSean Christopherson static long get_nx_huge_page_recovery_timeout(u64 start_time)
7192c50d8ae3SPaolo Bonzini {
7193f47491d7SSean Christopherson 	bool enabled;
7194f47491d7SSean Christopherson 	uint period;
71954dfe4f40SJunaid Shahid 
7196f47491d7SSean Christopherson 	enabled = calc_nx_huge_pages_recovery_period(&period);
71974dfe4f40SJunaid Shahid 
7198f47491d7SSean Christopherson 	return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
7199c50d8ae3SPaolo Bonzini 		       : MAX_SCHEDULE_TIMEOUT;
7200c50d8ae3SPaolo Bonzini }
7201c50d8ae3SPaolo Bonzini 
720255c510e2SSean Christopherson static int kvm_nx_huge_page_recovery_worker(struct kvm *kvm, uintptr_t data)
7203c50d8ae3SPaolo Bonzini {
7204c50d8ae3SPaolo Bonzini 	u64 start_time;
7205c50d8ae3SPaolo Bonzini 	long remaining_time;
7206c50d8ae3SPaolo Bonzini 
7207c50d8ae3SPaolo Bonzini 	while (true) {
7208c50d8ae3SPaolo Bonzini 		start_time = get_jiffies_64();
720955c510e2SSean Christopherson 		remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7210c50d8ae3SPaolo Bonzini 
7211c50d8ae3SPaolo Bonzini 		set_current_state(TASK_INTERRUPTIBLE);
7212c50d8ae3SPaolo Bonzini 		while (!kthread_should_stop() && remaining_time > 0) {
7213c50d8ae3SPaolo Bonzini 			schedule_timeout(remaining_time);
721455c510e2SSean Christopherson 			remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7215c50d8ae3SPaolo Bonzini 			set_current_state(TASK_INTERRUPTIBLE);
7216c50d8ae3SPaolo Bonzini 		}
7217c50d8ae3SPaolo Bonzini 
7218c50d8ae3SPaolo Bonzini 		set_current_state(TASK_RUNNING);
7219c50d8ae3SPaolo Bonzini 
7220c50d8ae3SPaolo Bonzini 		if (kthread_should_stop())
7221c50d8ae3SPaolo Bonzini 			return 0;
7222c50d8ae3SPaolo Bonzini 
722355c510e2SSean Christopherson 		kvm_recover_nx_huge_pages(kvm);
7224c50d8ae3SPaolo Bonzini 	}
7225c50d8ae3SPaolo Bonzini }
7226c50d8ae3SPaolo Bonzini 
7227c50d8ae3SPaolo Bonzini int kvm_mmu_post_init_vm(struct kvm *kvm)
7228c50d8ae3SPaolo Bonzini {
7229c50d8ae3SPaolo Bonzini 	int err;
7230c50d8ae3SPaolo Bonzini 
72310b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
72320b210fafSSean Christopherson 		return 0;
72330b210fafSSean Christopherson 
723455c510e2SSean Christopherson 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_huge_page_recovery_worker, 0,
7235c50d8ae3SPaolo Bonzini 					  "kvm-nx-lpage-recovery",
723655c510e2SSean Christopherson 					  &kvm->arch.nx_huge_page_recovery_thread);
7237c50d8ae3SPaolo Bonzini 	if (!err)
723855c510e2SSean Christopherson 		kthread_unpark(kvm->arch.nx_huge_page_recovery_thread);
7239c50d8ae3SPaolo Bonzini 
7240c50d8ae3SPaolo Bonzini 	return err;
7241c50d8ae3SPaolo Bonzini }
7242c50d8ae3SPaolo Bonzini 
7243c50d8ae3SPaolo Bonzini void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7244c50d8ae3SPaolo Bonzini {
724555c510e2SSean Christopherson 	if (kvm->arch.nx_huge_page_recovery_thread)
724655c510e2SSean Christopherson 		kthread_stop(kvm->arch.nx_huge_page_recovery_thread);
7247c50d8ae3SPaolo Bonzini }
724890b4fe17SChao Peng 
724990b4fe17SChao Peng #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
72508dd2eee9SChao Peng bool kvm_arch_pre_set_memory_attributes(struct kvm *kvm,
72518dd2eee9SChao Peng 					struct kvm_gfn_range *range)
72528dd2eee9SChao Peng {
72538dd2eee9SChao Peng 	/*
72548dd2eee9SChao Peng 	 * Zap SPTEs even if the slot can't be mapped PRIVATE.  KVM x86 only
72558dd2eee9SChao Peng 	 * supports KVM_MEMORY_ATTRIBUTE_PRIVATE, and so it *seems* like KVM
72568dd2eee9SChao Peng 	 * can simply ignore such slots.  But if userspace is making memory
72578dd2eee9SChao Peng 	 * PRIVATE, then KVM must prevent the guest from accessing the memory
72588dd2eee9SChao Peng 	 * as shared.  And if userspace is making memory SHARED and this point
72598dd2eee9SChao Peng 	 * is reached, then at least one page within the range was previously
72608dd2eee9SChao Peng 	 * PRIVATE, i.e. the slot's possible hugepage ranges are changing.
72618dd2eee9SChao Peng 	 * Zapping SPTEs in this case ensures KVM will reassess whether or not
72628dd2eee9SChao Peng 	 * a hugepage can be used for affected ranges.
72638dd2eee9SChao Peng 	 */
72648dd2eee9SChao Peng 	if (WARN_ON_ONCE(!kvm_arch_has_private_mem(kvm)))
72658dd2eee9SChao Peng 		return false;
72668dd2eee9SChao Peng 
72678dd2eee9SChao Peng 	return kvm_unmap_gfn_range(kvm, range);
72688dd2eee9SChao Peng }
72698dd2eee9SChao Peng 
727090b4fe17SChao Peng static bool hugepage_test_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
727190b4fe17SChao Peng 				int level)
727290b4fe17SChao Peng {
727390b4fe17SChao Peng 	return lpage_info_slot(gfn, slot, level)->disallow_lpage & KVM_LPAGE_MIXED_FLAG;
727490b4fe17SChao Peng }
727590b4fe17SChao Peng 
727690b4fe17SChao Peng static void hugepage_clear_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
727790b4fe17SChao Peng 				 int level)
727890b4fe17SChao Peng {
727990b4fe17SChao Peng 	lpage_info_slot(gfn, slot, level)->disallow_lpage &= ~KVM_LPAGE_MIXED_FLAG;
728090b4fe17SChao Peng }
728190b4fe17SChao Peng 
728290b4fe17SChao Peng static void hugepage_set_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
728390b4fe17SChao Peng 			       int level)
728490b4fe17SChao Peng {
728590b4fe17SChao Peng 	lpage_info_slot(gfn, slot, level)->disallow_lpage |= KVM_LPAGE_MIXED_FLAG;
728690b4fe17SChao Peng }
728790b4fe17SChao Peng 
728890b4fe17SChao Peng static bool hugepage_has_attrs(struct kvm *kvm, struct kvm_memory_slot *slot,
728990b4fe17SChao Peng 			       gfn_t gfn, int level, unsigned long attrs)
729090b4fe17SChao Peng {
729190b4fe17SChao Peng 	const unsigned long start = gfn;
729290b4fe17SChao Peng 	const unsigned long end = start + KVM_PAGES_PER_HPAGE(level);
729390b4fe17SChao Peng 
729490b4fe17SChao Peng 	if (level == PG_LEVEL_2M)
729590b4fe17SChao Peng 		return kvm_range_has_memory_attributes(kvm, start, end, attrs);
729690b4fe17SChao Peng 
729790b4fe17SChao Peng 	for (gfn = start; gfn < end; gfn += KVM_PAGES_PER_HPAGE(level - 1)) {
729890b4fe17SChao Peng 		if (hugepage_test_mixed(slot, gfn, level - 1) ||
729990b4fe17SChao Peng 		    attrs != kvm_get_memory_attributes(kvm, gfn))
730090b4fe17SChao Peng 			return false;
730190b4fe17SChao Peng 	}
730290b4fe17SChao Peng 	return true;
730390b4fe17SChao Peng }
730490b4fe17SChao Peng 
730590b4fe17SChao Peng bool kvm_arch_post_set_memory_attributes(struct kvm *kvm,
730690b4fe17SChao Peng 					 struct kvm_gfn_range *range)
730790b4fe17SChao Peng {
730890b4fe17SChao Peng 	unsigned long attrs = range->arg.attributes;
730990b4fe17SChao Peng 	struct kvm_memory_slot *slot = range->slot;
731090b4fe17SChao Peng 	int level;
731190b4fe17SChao Peng 
731290b4fe17SChao Peng 	lockdep_assert_held_write(&kvm->mmu_lock);
731390b4fe17SChao Peng 	lockdep_assert_held(&kvm->slots_lock);
731490b4fe17SChao Peng 
731590b4fe17SChao Peng 	/*
731690b4fe17SChao Peng 	 * Calculate which ranges can be mapped with hugepages even if the slot
731790b4fe17SChao Peng 	 * can't map memory PRIVATE.  KVM mustn't create a SHARED hugepage over
731890b4fe17SChao Peng 	 * a range that has PRIVATE GFNs, and conversely converting a range to
731990b4fe17SChao Peng 	 * SHARED may now allow hugepages.
732090b4fe17SChao Peng 	 */
732190b4fe17SChao Peng 	if (WARN_ON_ONCE(!kvm_arch_has_private_mem(kvm)))
732290b4fe17SChao Peng 		return false;
732390b4fe17SChao Peng 
732490b4fe17SChao Peng 	/*
732590b4fe17SChao Peng 	 * The sequence matters here: upper levels consume the result of lower
732690b4fe17SChao Peng 	 * level's scanning.
732790b4fe17SChao Peng 	 */
732890b4fe17SChao Peng 	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
732990b4fe17SChao Peng 		gfn_t nr_pages = KVM_PAGES_PER_HPAGE(level);
733090b4fe17SChao Peng 		gfn_t gfn = gfn_round_for_level(range->start, level);
733190b4fe17SChao Peng 
733290b4fe17SChao Peng 		/* Process the head page if it straddles the range. */
733390b4fe17SChao Peng 		if (gfn != range->start || gfn + nr_pages > range->end) {
733490b4fe17SChao Peng 			/*
733590b4fe17SChao Peng 			 * Skip mixed tracking if the aligned gfn isn't covered
733690b4fe17SChao Peng 			 * by the memslot, KVM can't use a hugepage due to the
733790b4fe17SChao Peng 			 * misaligned address regardless of memory attributes.
733890b4fe17SChao Peng 			 */
733990b4fe17SChao Peng 			if (gfn >= slot->base_gfn) {
734090b4fe17SChao Peng 				if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
734190b4fe17SChao Peng 					hugepage_clear_mixed(slot, gfn, level);
734290b4fe17SChao Peng 				else
734390b4fe17SChao Peng 					hugepage_set_mixed(slot, gfn, level);
734490b4fe17SChao Peng 			}
734590b4fe17SChao Peng 			gfn += nr_pages;
734690b4fe17SChao Peng 		}
734790b4fe17SChao Peng 
734890b4fe17SChao Peng 		/*
734990b4fe17SChao Peng 		 * Pages entirely covered by the range are guaranteed to have
735090b4fe17SChao Peng 		 * only the attributes which were just set.
735190b4fe17SChao Peng 		 */
735290b4fe17SChao Peng 		for ( ; gfn + nr_pages <= range->end; gfn += nr_pages)
735390b4fe17SChao Peng 			hugepage_clear_mixed(slot, gfn, level);
735490b4fe17SChao Peng 
735590b4fe17SChao Peng 		/*
735690b4fe17SChao Peng 		 * Process the last tail page if it straddles the range and is
735790b4fe17SChao Peng 		 * contained by the memslot.  Like the head page, KVM can't
735890b4fe17SChao Peng 		 * create a hugepage if the slot size is misaligned.
735990b4fe17SChao Peng 		 */
736090b4fe17SChao Peng 		if (gfn < range->end &&
736190b4fe17SChao Peng 		    (gfn + nr_pages) <= (slot->base_gfn + slot->npages)) {
736290b4fe17SChao Peng 			if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
736390b4fe17SChao Peng 				hugepage_clear_mixed(slot, gfn, level);
736490b4fe17SChao Peng 			else
736590b4fe17SChao Peng 				hugepage_set_mixed(slot, gfn, level);
736690b4fe17SChao Peng 		}
736790b4fe17SChao Peng 	}
736890b4fe17SChao Peng 	return false;
736990b4fe17SChao Peng }
737090b4fe17SChao Peng 
737190b4fe17SChao Peng void kvm_mmu_init_memslot_memory_attributes(struct kvm *kvm,
737290b4fe17SChao Peng 					    struct kvm_memory_slot *slot)
737390b4fe17SChao Peng {
737490b4fe17SChao Peng 	int level;
737590b4fe17SChao Peng 
737690b4fe17SChao Peng 	if (!kvm_arch_has_private_mem(kvm))
737790b4fe17SChao Peng 		return;
737890b4fe17SChao Peng 
737990b4fe17SChao Peng 	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
738090b4fe17SChao Peng 		/*
738190b4fe17SChao Peng 		 * Don't bother tracking mixed attributes for pages that can't
738290b4fe17SChao Peng 		 * be huge due to alignment, i.e. process only pages that are
738390b4fe17SChao Peng 		 * entirely contained by the memslot.
738490b4fe17SChao Peng 		 */
738590b4fe17SChao Peng 		gfn_t end = gfn_round_for_level(slot->base_gfn + slot->npages, level);
738690b4fe17SChao Peng 		gfn_t start = gfn_round_for_level(slot->base_gfn, level);
738790b4fe17SChao Peng 		gfn_t nr_pages = KVM_PAGES_PER_HPAGE(level);
738890b4fe17SChao Peng 		gfn_t gfn;
738990b4fe17SChao Peng 
739090b4fe17SChao Peng 		if (start < slot->base_gfn)
739190b4fe17SChao Peng 			start += nr_pages;
739290b4fe17SChao Peng 
739390b4fe17SChao Peng 		/*
739490b4fe17SChao Peng 		 * Unlike setting attributes, every potential hugepage needs to
739590b4fe17SChao Peng 		 * be manually checked as the attributes may already be mixed.
739690b4fe17SChao Peng 		 */
739790b4fe17SChao Peng 		for (gfn = start; gfn < end; gfn += nr_pages) {
739890b4fe17SChao Peng 			unsigned long attrs = kvm_get_memory_attributes(kvm, gfn);
739990b4fe17SChao Peng 
740090b4fe17SChao Peng 			if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
740190b4fe17SChao Peng 				hugepage_clear_mixed(slot, gfn, level);
740290b4fe17SChao Peng 			else
740390b4fe17SChao Peng 				hugepage_set_mixed(slot, gfn, level);
740490b4fe17SChao Peng 		}
740590b4fe17SChao Peng 	}
740690b4fe17SChao Peng }
740790b4fe17SChao Peng #endif
7408