xref: /linux/arch/x86/kvm/mmu/mmu.c (revision c30e000e690af74f61a161fa60be140f23948cb1)
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>
50c50d8ae3SPaolo Bonzini 
51c50d8ae3SPaolo Bonzini #include <asm/page.h>
52eb243d1dSIngo Molnar #include <asm/memtype.h>
53c50d8ae3SPaolo Bonzini #include <asm/cmpxchg.h>
54c50d8ae3SPaolo Bonzini #include <asm/io.h>
554a98623dSSean Christopherson #include <asm/set_memory.h>
56c50d8ae3SPaolo Bonzini #include <asm/vmx.h>
5758ea7cf7SSean Christopherson 
58c50d8ae3SPaolo Bonzini #include "trace.h"
59c50d8ae3SPaolo Bonzini 
60c50d8ae3SPaolo Bonzini extern bool itlb_multihit_kvm_mitigation;
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 {
2662fdcc1b3SPaolo Bonzini 	if (IS_ENABLED(CONFIG_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 {
2748a1300ffSSean Christopherson 	return kvm_x86_ops.flush_remote_tlbs_range;
275c50d8ae3SPaolo Bonzini }
276c50d8ae3SPaolo Bonzini 
277d4788996SDavid Matlack int kvm_arch_flush_remote_tlbs_range(struct kvm *kvm, gfn_t gfn, u64 nr_pages)
278c50d8ae3SPaolo Bonzini {
279d4788996SDavid Matlack 	if (!kvm_x86_ops.flush_remote_tlbs_range)
280d4788996SDavid Matlack 		return -EOPNOTSUPP;
281c50d8ae3SPaolo Bonzini 
282d4788996SDavid Matlack 	return static_call(kvm_x86_flush_remote_tlbs_range)(kvm, gfn, nr_pages);
283c50d8ae3SPaolo Bonzini }
284c50d8ae3SPaolo Bonzini 
2851b2dc736SHou Wenlong static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index);
2861b2dc736SHou Wenlong 
2871b2dc736SHou Wenlong /* Flush the range of guest memory mapped by the given SPTE. */
2881b2dc736SHou Wenlong static void kvm_flush_remote_tlbs_sptep(struct kvm *kvm, u64 *sptep)
2891b2dc736SHou Wenlong {
2901b2dc736SHou Wenlong 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2911b2dc736SHou Wenlong 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, spte_index(sptep));
2921b2dc736SHou Wenlong 
2931b2dc736SHou Wenlong 	kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
2941b2dc736SHou Wenlong }
2951b2dc736SHou Wenlong 
2968f79b064SBen Gardon static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
2978f79b064SBen Gardon 			   unsigned int access)
2988f79b064SBen Gardon {
299c236d962SSean Christopherson 	u64 spte = make_mmio_spte(vcpu, gfn, access);
3008f79b064SBen Gardon 
301c236d962SSean Christopherson 	trace_mark_mmio_spte(sptep, gfn, spte);
302c236d962SSean Christopherson 	mmu_spte_set(sptep, spte);
303c50d8ae3SPaolo Bonzini }
304c50d8ae3SPaolo Bonzini 
305c50d8ae3SPaolo Bonzini static gfn_t get_mmio_spte_gfn(u64 spte)
306c50d8ae3SPaolo Bonzini {
307c50d8ae3SPaolo Bonzini 	u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
308c50d8ae3SPaolo Bonzini 
3098a967d65SPaolo Bonzini 	gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
310c50d8ae3SPaolo Bonzini 	       & shadow_nonpresent_or_rsvd_mask;
311c50d8ae3SPaolo Bonzini 
312c50d8ae3SPaolo Bonzini 	return gpa >> PAGE_SHIFT;
313c50d8ae3SPaolo Bonzini }
314c50d8ae3SPaolo Bonzini 
315c50d8ae3SPaolo Bonzini static unsigned get_mmio_spte_access(u64 spte)
316c50d8ae3SPaolo Bonzini {
317c50d8ae3SPaolo Bonzini 	return spte & shadow_mmio_access_mask;
318c50d8ae3SPaolo Bonzini }
319c50d8ae3SPaolo Bonzini 
320c50d8ae3SPaolo Bonzini static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
321c50d8ae3SPaolo Bonzini {
322c50d8ae3SPaolo Bonzini 	u64 kvm_gen, spte_gen, gen;
323c50d8ae3SPaolo Bonzini 
324c50d8ae3SPaolo Bonzini 	gen = kvm_vcpu_memslots(vcpu)->generation;
325c50d8ae3SPaolo Bonzini 	if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
326c50d8ae3SPaolo Bonzini 		return false;
327c50d8ae3SPaolo Bonzini 
328c50d8ae3SPaolo Bonzini 	kvm_gen = gen & MMIO_SPTE_GEN_MASK;
329c50d8ae3SPaolo Bonzini 	spte_gen = get_mmio_spte_generation(spte);
330c50d8ae3SPaolo Bonzini 
331c50d8ae3SPaolo Bonzini 	trace_check_mmio_spte(spte, kvm_gen, spte_gen);
332c50d8ae3SPaolo Bonzini 	return likely(kvm_gen == spte_gen);
333c50d8ae3SPaolo Bonzini }
334c50d8ae3SPaolo Bonzini 
335c50d8ae3SPaolo Bonzini static int is_cpuid_PSE36(void)
336c50d8ae3SPaolo Bonzini {
337c50d8ae3SPaolo Bonzini 	return 1;
338c50d8ae3SPaolo Bonzini }
339c50d8ae3SPaolo Bonzini 
340c50d8ae3SPaolo Bonzini #ifdef CONFIG_X86_64
341c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
342c50d8ae3SPaolo Bonzini {
343c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
344c50d8ae3SPaolo Bonzini }
345c50d8ae3SPaolo Bonzini 
346c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
347c50d8ae3SPaolo Bonzini {
348c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
349c50d8ae3SPaolo Bonzini }
350c50d8ae3SPaolo Bonzini 
351c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
352c50d8ae3SPaolo Bonzini {
353c50d8ae3SPaolo Bonzini 	return xchg(sptep, spte);
354c50d8ae3SPaolo Bonzini }
355c50d8ae3SPaolo Bonzini 
356c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
357c50d8ae3SPaolo Bonzini {
358c50d8ae3SPaolo Bonzini 	return READ_ONCE(*sptep);
359c50d8ae3SPaolo Bonzini }
360c50d8ae3SPaolo Bonzini #else
361c50d8ae3SPaolo Bonzini union split_spte {
362c50d8ae3SPaolo Bonzini 	struct {
363c50d8ae3SPaolo Bonzini 		u32 spte_low;
364c50d8ae3SPaolo Bonzini 		u32 spte_high;
365c50d8ae3SPaolo Bonzini 	};
366c50d8ae3SPaolo Bonzini 	u64 spte;
367c50d8ae3SPaolo Bonzini };
368c50d8ae3SPaolo Bonzini 
369c50d8ae3SPaolo Bonzini static void count_spte_clear(u64 *sptep, u64 spte)
370c50d8ae3SPaolo Bonzini {
37157354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
372c50d8ae3SPaolo Bonzini 
373c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(spte))
374c50d8ae3SPaolo Bonzini 		return;
375c50d8ae3SPaolo Bonzini 
376c50d8ae3SPaolo Bonzini 	/* Ensure the spte is completely set before we increase the count */
377c50d8ae3SPaolo Bonzini 	smp_wmb();
378c50d8ae3SPaolo Bonzini 	sp->clear_spte_count++;
379c50d8ae3SPaolo Bonzini }
380c50d8ae3SPaolo Bonzini 
381c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
382c50d8ae3SPaolo Bonzini {
383c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
384c50d8ae3SPaolo Bonzini 
385c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
386c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
387c50d8ae3SPaolo Bonzini 
388c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
389c50d8ae3SPaolo Bonzini 
390c50d8ae3SPaolo Bonzini 	/*
391c50d8ae3SPaolo Bonzini 	 * If we map the spte from nonpresent to present, We should store
392c50d8ae3SPaolo Bonzini 	 * the high bits firstly, then set present bit, so cpu can not
393c50d8ae3SPaolo Bonzini 	 * fetch this spte while we are setting the spte.
394c50d8ae3SPaolo Bonzini 	 */
395c50d8ae3SPaolo Bonzini 	smp_wmb();
396c50d8ae3SPaolo Bonzini 
397c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
398c50d8ae3SPaolo Bonzini }
399c50d8ae3SPaolo Bonzini 
400c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
401c50d8ae3SPaolo Bonzini {
402c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
403c50d8ae3SPaolo Bonzini 
404c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
405c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
406c50d8ae3SPaolo Bonzini 
407c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
408c50d8ae3SPaolo Bonzini 
409c50d8ae3SPaolo Bonzini 	/*
410c50d8ae3SPaolo Bonzini 	 * If we map the spte from present to nonpresent, we should clear
411c50d8ae3SPaolo Bonzini 	 * present bit firstly to avoid vcpu fetch the old high bits.
412c50d8ae3SPaolo Bonzini 	 */
413c50d8ae3SPaolo Bonzini 	smp_wmb();
414c50d8ae3SPaolo Bonzini 
415c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
416c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
417c50d8ae3SPaolo Bonzini }
418c50d8ae3SPaolo Bonzini 
419c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
420c50d8ae3SPaolo Bonzini {
421c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte, orig;
422c50d8ae3SPaolo Bonzini 
423c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
424c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
425c50d8ae3SPaolo Bonzini 
426c50d8ae3SPaolo Bonzini 	/* xchg acts as a barrier before the setting of the high bits */
427c50d8ae3SPaolo Bonzini 	orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
428c50d8ae3SPaolo Bonzini 	orig.spte_high = ssptep->spte_high;
429c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
430c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
431c50d8ae3SPaolo Bonzini 
432c50d8ae3SPaolo Bonzini 	return orig.spte;
433c50d8ae3SPaolo Bonzini }
434c50d8ae3SPaolo Bonzini 
435c50d8ae3SPaolo Bonzini /*
436c50d8ae3SPaolo Bonzini  * The idea using the light way get the spte on x86_32 guest is from
437c50d8ae3SPaolo Bonzini  * gup_get_pte (mm/gup.c).
438c50d8ae3SPaolo Bonzini  *
439aed02fe3SSean Christopherson  * An spte tlb flush may be pending, because kvm_set_pte_rmap
440c50d8ae3SPaolo Bonzini  * coalesces them and we are running out of the MMU lock.  Therefore
441c50d8ae3SPaolo Bonzini  * we need to protect against in-progress updates of the spte.
442c50d8ae3SPaolo Bonzini  *
443c50d8ae3SPaolo Bonzini  * Reading the spte while an update is in progress may get the old value
444c50d8ae3SPaolo Bonzini  * for the high part of the spte.  The race is fine for a present->non-present
445c50d8ae3SPaolo Bonzini  * change (because the high part of the spte is ignored for non-present spte),
446c50d8ae3SPaolo Bonzini  * but for a present->present change we must reread the spte.
447c50d8ae3SPaolo Bonzini  *
448c50d8ae3SPaolo Bonzini  * All such changes are done in two steps (present->non-present and
449c50d8ae3SPaolo Bonzini  * non-present->present), hence it is enough to count the number of
450c50d8ae3SPaolo Bonzini  * present->non-present updates: if it changed while reading the spte,
451c50d8ae3SPaolo Bonzini  * we might have hit the race.  This is done using clear_spte_count.
452c50d8ae3SPaolo Bonzini  */
453c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
454c50d8ae3SPaolo Bonzini {
45557354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
456c50d8ae3SPaolo Bonzini 	union split_spte spte, *orig = (union split_spte *)sptep;
457c50d8ae3SPaolo Bonzini 	int count;
458c50d8ae3SPaolo Bonzini 
459c50d8ae3SPaolo Bonzini retry:
460c50d8ae3SPaolo Bonzini 	count = sp->clear_spte_count;
461c50d8ae3SPaolo Bonzini 	smp_rmb();
462c50d8ae3SPaolo Bonzini 
463c50d8ae3SPaolo Bonzini 	spte.spte_low = orig->spte_low;
464c50d8ae3SPaolo Bonzini 	smp_rmb();
465c50d8ae3SPaolo Bonzini 
466c50d8ae3SPaolo Bonzini 	spte.spte_high = orig->spte_high;
467c50d8ae3SPaolo Bonzini 	smp_rmb();
468c50d8ae3SPaolo Bonzini 
469c50d8ae3SPaolo Bonzini 	if (unlikely(spte.spte_low != orig->spte_low ||
470c50d8ae3SPaolo Bonzini 	      count != sp->clear_spte_count))
471c50d8ae3SPaolo Bonzini 		goto retry;
472c50d8ae3SPaolo Bonzini 
473c50d8ae3SPaolo Bonzini 	return spte.spte;
474c50d8ae3SPaolo Bonzini }
475c50d8ae3SPaolo Bonzini #endif
476c50d8ae3SPaolo Bonzini 
477c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_set:
478c50d8ae3SPaolo Bonzini  * Set the sptep from nonpresent to present.
479c50d8ae3SPaolo Bonzini  * Note: the sptep being assigned *must* be either not present
480c50d8ae3SPaolo Bonzini  * or in a state where the hardware will not attempt to update
481c50d8ae3SPaolo Bonzini  * the spte.
482c50d8ae3SPaolo Bonzini  */
483c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 new_spte)
484c50d8ae3SPaolo Bonzini {
48520ba462dSSean Christopherson 	WARN_ON_ONCE(is_shadow_present_pte(*sptep));
486c50d8ae3SPaolo Bonzini 	__set_spte(sptep, new_spte);
487c50d8ae3SPaolo Bonzini }
488c50d8ae3SPaolo Bonzini 
489c50d8ae3SPaolo Bonzini /*
490c50d8ae3SPaolo Bonzini  * Update the SPTE (excluding the PFN), but do not track changes in its
491c50d8ae3SPaolo Bonzini  * accessed/dirty status.
492c50d8ae3SPaolo Bonzini  */
493c50d8ae3SPaolo Bonzini static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
494c50d8ae3SPaolo Bonzini {
495c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
496c50d8ae3SPaolo Bonzini 
49720ba462dSSean Christopherson 	WARN_ON_ONCE(!is_shadow_present_pte(new_spte));
498115111efSDavid Matlack 	check_spte_writable_invariants(new_spte);
499c50d8ae3SPaolo Bonzini 
500c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte)) {
501c50d8ae3SPaolo Bonzini 		mmu_spte_set(sptep, new_spte);
502c50d8ae3SPaolo Bonzini 		return old_spte;
503c50d8ae3SPaolo Bonzini 	}
504c50d8ae3SPaolo Bonzini 
505c50d8ae3SPaolo Bonzini 	if (!spte_has_volatile_bits(old_spte))
506c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, new_spte);
507c50d8ae3SPaolo Bonzini 	else
508c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, new_spte);
509c50d8ae3SPaolo Bonzini 
51020ba462dSSean Christopherson 	WARN_ON_ONCE(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
511c50d8ae3SPaolo Bonzini 
512c50d8ae3SPaolo Bonzini 	return old_spte;
513c50d8ae3SPaolo Bonzini }
514c50d8ae3SPaolo Bonzini 
515c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_update:
516c50d8ae3SPaolo Bonzini  * Update the state bits, it means the mapped pfn is not changed.
517c50d8ae3SPaolo Bonzini  *
51802844ac1SDavid Matlack  * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
51902844ac1SDavid Matlack  * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
52002844ac1SDavid Matlack  * spte, even though the writable spte might be cached on a CPU's TLB.
521c50d8ae3SPaolo Bonzini  *
522c50d8ae3SPaolo Bonzini  * Returns true if the TLB needs to be flushed
523c50d8ae3SPaolo Bonzini  */
524c50d8ae3SPaolo Bonzini static bool mmu_spte_update(u64 *sptep, u64 new_spte)
525c50d8ae3SPaolo Bonzini {
526c50d8ae3SPaolo Bonzini 	bool flush = false;
527c50d8ae3SPaolo Bonzini 	u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
528c50d8ae3SPaolo Bonzini 
529c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
530c50d8ae3SPaolo Bonzini 		return false;
531c50d8ae3SPaolo Bonzini 
532c50d8ae3SPaolo Bonzini 	/*
533c50d8ae3SPaolo Bonzini 	 * For the spte updated out of mmu-lock is safe, since
534c50d8ae3SPaolo Bonzini 	 * we always atomically update it, see the comments in
535c50d8ae3SPaolo Bonzini 	 * spte_has_volatile_bits().
536c50d8ae3SPaolo Bonzini 	 */
537706c9c55SSean Christopherson 	if (is_mmu_writable_spte(old_spte) &&
538c50d8ae3SPaolo Bonzini 	      !is_writable_pte(new_spte))
539c50d8ae3SPaolo Bonzini 		flush = true;
540c50d8ae3SPaolo Bonzini 
541c50d8ae3SPaolo Bonzini 	/*
542c50d8ae3SPaolo Bonzini 	 * Flush TLB when accessed/dirty states are changed in the page tables,
543c50d8ae3SPaolo Bonzini 	 * to guarantee consistency between TLB and page tables.
544c50d8ae3SPaolo Bonzini 	 */
545c50d8ae3SPaolo Bonzini 
546c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
547c50d8ae3SPaolo Bonzini 		flush = true;
548c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(spte_to_pfn(old_spte));
549c50d8ae3SPaolo Bonzini 	}
550c50d8ae3SPaolo Bonzini 
551c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
552c50d8ae3SPaolo Bonzini 		flush = true;
553c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(old_spte));
554c50d8ae3SPaolo Bonzini 	}
555c50d8ae3SPaolo Bonzini 
556c50d8ae3SPaolo Bonzini 	return flush;
557c50d8ae3SPaolo Bonzini }
558c50d8ae3SPaolo Bonzini 
559c50d8ae3SPaolo Bonzini /*
560c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_track_bits:
561c50d8ae3SPaolo Bonzini  * It sets the sptep from present to nonpresent, and track the
562c50d8ae3SPaolo Bonzini  * state bits, it is used to clear the last level sptep.
5637fa2a347SSean Christopherson  * Returns the old PTE.
564c50d8ae3SPaolo Bonzini  */
56535d539c3SSean Christopherson static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
566c50d8ae3SPaolo Bonzini {
567c50d8ae3SPaolo Bonzini 	kvm_pfn_t pfn;
568c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
56971f51d2cSMingwei Zhang 	int level = sptep_to_sp(sptep)->role.level;
570b14b2690SSean Christopherson 	struct page *page;
571c50d8ae3SPaolo Bonzini 
57254eb3ef5SSean Christopherson 	if (!is_shadow_present_pte(old_spte) ||
57354eb3ef5SSean Christopherson 	    !spte_has_volatile_bits(old_spte))
574c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, 0ull);
575c50d8ae3SPaolo Bonzini 	else
576c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, 0ull);
577c50d8ae3SPaolo Bonzini 
578c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
5797fa2a347SSean Christopherson 		return old_spte;
580c50d8ae3SPaolo Bonzini 
58171f51d2cSMingwei Zhang 	kvm_update_page_stats(kvm, level, -1);
58271f51d2cSMingwei Zhang 
583c50d8ae3SPaolo Bonzini 	pfn = spte_to_pfn(old_spte);
584c50d8ae3SPaolo Bonzini 
585c50d8ae3SPaolo Bonzini 	/*
586b14b2690SSean Christopherson 	 * KVM doesn't hold a reference to any pages mapped into the guest, and
587b14b2690SSean Christopherson 	 * instead uses the mmu_notifier to ensure that KVM unmaps any pages
588b14b2690SSean Christopherson 	 * before they are reclaimed.  Sanity check that, if the pfn is backed
589b14b2690SSean Christopherson 	 * by a refcounted page, the refcount is elevated.
590c50d8ae3SPaolo Bonzini 	 */
591b14b2690SSean Christopherson 	page = kvm_pfn_to_refcounted_page(pfn);
59220ba462dSSean Christopherson 	WARN_ON_ONCE(page && !page_count(page));
593c50d8ae3SPaolo Bonzini 
594c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte))
595c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(pfn);
596c50d8ae3SPaolo Bonzini 
597c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte))
598c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(pfn);
599c50d8ae3SPaolo Bonzini 
6007fa2a347SSean Christopherson 	return old_spte;
601c50d8ae3SPaolo Bonzini }
602c50d8ae3SPaolo Bonzini 
603c50d8ae3SPaolo Bonzini /*
604c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_no_track:
605c50d8ae3SPaolo Bonzini  * Directly clear spte without caring the state bits of sptep,
606c50d8ae3SPaolo Bonzini  * it is used to set the upper level spte.
607c50d8ae3SPaolo Bonzini  */
608c50d8ae3SPaolo Bonzini static void mmu_spte_clear_no_track(u64 *sptep)
609c50d8ae3SPaolo Bonzini {
610c50d8ae3SPaolo Bonzini 	__update_clear_spte_fast(sptep, 0ull);
611c50d8ae3SPaolo Bonzini }
612c50d8ae3SPaolo Bonzini 
613c50d8ae3SPaolo Bonzini static u64 mmu_spte_get_lockless(u64 *sptep)
614c50d8ae3SPaolo Bonzini {
615c50d8ae3SPaolo Bonzini 	return __get_spte_lockless(sptep);
616c50d8ae3SPaolo Bonzini }
617c50d8ae3SPaolo Bonzini 
618c50d8ae3SPaolo Bonzini /* Returns the Accessed status of the PTE and resets it at the same time. */
619c50d8ae3SPaolo Bonzini static bool mmu_spte_age(u64 *sptep)
620c50d8ae3SPaolo Bonzini {
621c50d8ae3SPaolo Bonzini 	u64 spte = mmu_spte_get_lockless(sptep);
622c50d8ae3SPaolo Bonzini 
623c50d8ae3SPaolo Bonzini 	if (!is_accessed_spte(spte))
624c50d8ae3SPaolo Bonzini 		return false;
625c50d8ae3SPaolo Bonzini 
626c50d8ae3SPaolo Bonzini 	if (spte_ad_enabled(spte)) {
627c50d8ae3SPaolo Bonzini 		clear_bit((ffs(shadow_accessed_mask) - 1),
628c50d8ae3SPaolo Bonzini 			  (unsigned long *)sptep);
629c50d8ae3SPaolo Bonzini 	} else {
630c50d8ae3SPaolo Bonzini 		/*
631c50d8ae3SPaolo Bonzini 		 * Capture the dirty status of the page, so that it doesn't get
632c50d8ae3SPaolo Bonzini 		 * lost when the SPTE is marked for access tracking.
633c50d8ae3SPaolo Bonzini 		 */
634c50d8ae3SPaolo Bonzini 		if (is_writable_pte(spte))
635c50d8ae3SPaolo Bonzini 			kvm_set_pfn_dirty(spte_to_pfn(spte));
636c50d8ae3SPaolo Bonzini 
637c50d8ae3SPaolo Bonzini 		spte = mark_spte_for_access_track(spte);
638c50d8ae3SPaolo Bonzini 		mmu_spte_update_no_track(sptep, spte);
639c50d8ae3SPaolo Bonzini 	}
640c50d8ae3SPaolo Bonzini 
641c50d8ae3SPaolo Bonzini 	return true;
642c50d8ae3SPaolo Bonzini }
643c50d8ae3SPaolo Bonzini 
64478fdd2f0SSean Christopherson static inline bool is_tdp_mmu_active(struct kvm_vcpu *vcpu)
64578fdd2f0SSean Christopherson {
64678fdd2f0SSean Christopherson 	return tdp_mmu_enabled && vcpu->arch.mmu->root_role.direct;
64778fdd2f0SSean Christopherson }
64878fdd2f0SSean Christopherson 
649c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
650c50d8ae3SPaolo Bonzini {
65178fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu)) {
652c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_begin();
653c5c8c7c5SDavid Matlack 	} else {
654c50d8ae3SPaolo Bonzini 		/*
655c50d8ae3SPaolo Bonzini 		 * Prevent page table teardown by making any free-er wait during
656c50d8ae3SPaolo Bonzini 		 * kvm_flush_remote_tlbs() IPI to all active vcpus.
657c50d8ae3SPaolo Bonzini 		 */
658c50d8ae3SPaolo Bonzini 		local_irq_disable();
659c50d8ae3SPaolo Bonzini 
660c50d8ae3SPaolo Bonzini 		/*
661c50d8ae3SPaolo Bonzini 		 * Make sure a following spte read is not reordered ahead of the write
662c50d8ae3SPaolo Bonzini 		 * to vcpu->mode.
663c50d8ae3SPaolo Bonzini 		 */
664c50d8ae3SPaolo Bonzini 		smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
665c50d8ae3SPaolo Bonzini 	}
666c5c8c7c5SDavid Matlack }
667c50d8ae3SPaolo Bonzini 
668c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
669c50d8ae3SPaolo Bonzini {
67078fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu)) {
671c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_end();
672c5c8c7c5SDavid Matlack 	} else {
673c50d8ae3SPaolo Bonzini 		/*
674c50d8ae3SPaolo Bonzini 		 * Make sure the write to vcpu->mode is not reordered in front of
675c50d8ae3SPaolo Bonzini 		 * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
676c50d8ae3SPaolo Bonzini 		 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
677c50d8ae3SPaolo Bonzini 		 */
678c50d8ae3SPaolo Bonzini 		smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
679c50d8ae3SPaolo Bonzini 		local_irq_enable();
680c50d8ae3SPaolo Bonzini 	}
681c5c8c7c5SDavid Matlack }
682c50d8ae3SPaolo Bonzini 
683378f5cd6SSean Christopherson static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
684c50d8ae3SPaolo Bonzini {
685c50d8ae3SPaolo Bonzini 	int r;
686c50d8ae3SPaolo Bonzini 
687531281adSSean Christopherson 	/* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
68894ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
689531281adSSean Christopherson 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
690c50d8ae3SPaolo Bonzini 	if (r)
691c50d8ae3SPaolo Bonzini 		return r;
69294ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
693171a90d7SSean Christopherson 				       PT64_ROOT_MAX_LEVEL);
694171a90d7SSean Christopherson 	if (r)
695171a90d7SSean Christopherson 		return r;
696378f5cd6SSean Christopherson 	if (maybe_indirect) {
6976a97575dSDavid Matlack 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
698171a90d7SSean Christopherson 					       PT64_ROOT_MAX_LEVEL);
699c50d8ae3SPaolo Bonzini 		if (r)
700c50d8ae3SPaolo Bonzini 			return r;
701378f5cd6SSean Christopherson 	}
70294ce87efSSean Christopherson 	return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
703531281adSSean Christopherson 					  PT64_ROOT_MAX_LEVEL);
704c50d8ae3SPaolo Bonzini }
705c50d8ae3SPaolo Bonzini 
706c50d8ae3SPaolo Bonzini static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
707c50d8ae3SPaolo Bonzini {
70894ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
70994ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
7106a97575dSDavid Matlack 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
71194ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
712c50d8ae3SPaolo Bonzini }
713c50d8ae3SPaolo Bonzini 
714c50d8ae3SPaolo Bonzini static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
715c50d8ae3SPaolo Bonzini {
716c50d8ae3SPaolo Bonzini 	kmem_cache_free(pte_list_desc_cache, pte_list_desc);
717c50d8ae3SPaolo Bonzini }
718c50d8ae3SPaolo Bonzini 
7196a97575dSDavid Matlack static bool sp_has_gptes(struct kvm_mmu_page *sp);
7206a97575dSDavid Matlack 
721c50d8ae3SPaolo Bonzini static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
722c50d8ae3SPaolo Bonzini {
72384e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
72484e5ffd0SLai Jiangshan 		return sp->gfn;
72584e5ffd0SLai Jiangshan 
726c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
7276a97575dSDavid Matlack 		return sp->shadowed_translation[index] >> PAGE_SHIFT;
728c50d8ae3SPaolo Bonzini 
7292ca3129eSSean Christopherson 	return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
730c50d8ae3SPaolo Bonzini }
731c50d8ae3SPaolo Bonzini 
7326a97575dSDavid Matlack /*
7336a97575dSDavid Matlack  * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
7346a97575dSDavid Matlack  * that the SPTE itself may have a more constrained access permissions that
7356a97575dSDavid Matlack  * what the guest enforces. For example, a guest may create an executable
7366a97575dSDavid Matlack  * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
7376a97575dSDavid Matlack  */
7386a97575dSDavid Matlack static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
739c50d8ae3SPaolo Bonzini {
7406a97575dSDavid Matlack 	if (sp_has_gptes(sp))
7416a97575dSDavid Matlack 		return sp->shadowed_translation[index] & ACC_ALL;
7426a97575dSDavid Matlack 
7436a97575dSDavid Matlack 	/*
7446a97575dSDavid Matlack 	 * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
7456a97575dSDavid Matlack 	 * KVM is not shadowing any guest page tables, so the "guest access
7466a97575dSDavid Matlack 	 * permissions" are just ACC_ALL.
7476a97575dSDavid Matlack 	 *
7486a97575dSDavid Matlack 	 * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
7496a97575dSDavid Matlack 	 * is shadowing a guest huge page with small pages, the guest access
7506a97575dSDavid Matlack 	 * permissions being shadowed are the access permissions of the huge
7516a97575dSDavid Matlack 	 * page.
7526a97575dSDavid Matlack 	 *
7536a97575dSDavid Matlack 	 * In both cases, sp->role.access contains the correct access bits.
7546a97575dSDavid Matlack 	 */
7556a97575dSDavid Matlack 	return sp->role.access;
7566a97575dSDavid Matlack }
7576a97575dSDavid Matlack 
75872ae5822SSean Christopherson static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
75972ae5822SSean Christopherson 					 gfn_t gfn, unsigned int access)
7606a97575dSDavid Matlack {
7616a97575dSDavid Matlack 	if (sp_has_gptes(sp)) {
7626a97575dSDavid Matlack 		sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
76384e5ffd0SLai Jiangshan 		return;
76484e5ffd0SLai Jiangshan 	}
76584e5ffd0SLai Jiangshan 
7666a97575dSDavid Matlack 	WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
7676a97575dSDavid Matlack 	          "access mismatch under %s page %llx (expected %u, got %u)\n",
7686a97575dSDavid Matlack 	          sp->role.passthrough ? "passthrough" : "direct",
7696a97575dSDavid Matlack 	          sp->gfn, kvm_mmu_page_get_access(sp, index), access);
7706a97575dSDavid Matlack 
7716a97575dSDavid Matlack 	WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
7726a97575dSDavid Matlack 	          "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
7736a97575dSDavid Matlack 	          sp->role.passthrough ? "passthrough" : "direct",
7746a97575dSDavid Matlack 	          sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
775c50d8ae3SPaolo Bonzini }
776c50d8ae3SPaolo Bonzini 
77772ae5822SSean Christopherson static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
77872ae5822SSean Christopherson 				    unsigned int access)
7796a97575dSDavid Matlack {
7806a97575dSDavid Matlack 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
7816a97575dSDavid Matlack 
7826a97575dSDavid Matlack 	kvm_mmu_page_set_translation(sp, index, gfn, access);
783c50d8ae3SPaolo Bonzini }
784c50d8ae3SPaolo Bonzini 
785c50d8ae3SPaolo Bonzini /*
786c50d8ae3SPaolo Bonzini  * Return the pointer to the large page information for a given gfn,
787c50d8ae3SPaolo Bonzini  * handling slots that are not large page aligned.
788c50d8ae3SPaolo Bonzini  */
789c50d8ae3SPaolo Bonzini static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
7908ca6f063SBen Gardon 		const struct kvm_memory_slot *slot, int level)
791c50d8ae3SPaolo Bonzini {
792c50d8ae3SPaolo Bonzini 	unsigned long idx;
793c50d8ae3SPaolo Bonzini 
794c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
795c50d8ae3SPaolo Bonzini 	return &slot->arch.lpage_info[level - 2][idx];
796c50d8ae3SPaolo Bonzini }
797c50d8ae3SPaolo Bonzini 
798269e9552SHamza Mahfooz static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
799c50d8ae3SPaolo Bonzini 					    gfn_t gfn, int count)
800c50d8ae3SPaolo Bonzini {
801c50d8ae3SPaolo Bonzini 	struct kvm_lpage_info *linfo;
802c50d8ae3SPaolo Bonzini 	int i;
803c50d8ae3SPaolo Bonzini 
8043bae0459SSean Christopherson 	for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
805c50d8ae3SPaolo Bonzini 		linfo = lpage_info_slot(gfn, slot, i);
806c50d8ae3SPaolo Bonzini 		linfo->disallow_lpage += count;
80720ba462dSSean Christopherson 		WARN_ON_ONCE(linfo->disallow_lpage < 0);
808c50d8ae3SPaolo Bonzini 	}
809c50d8ae3SPaolo Bonzini }
810c50d8ae3SPaolo Bonzini 
811269e9552SHamza Mahfooz void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
812c50d8ae3SPaolo Bonzini {
813c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, 1);
814c50d8ae3SPaolo Bonzini }
815c50d8ae3SPaolo Bonzini 
816269e9552SHamza Mahfooz void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
817c50d8ae3SPaolo Bonzini {
818c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, -1);
819c50d8ae3SPaolo Bonzini }
820c50d8ae3SPaolo Bonzini 
821c50d8ae3SPaolo Bonzini static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
822c50d8ae3SPaolo Bonzini {
823c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
824c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
825c50d8ae3SPaolo Bonzini 	gfn_t gfn;
826c50d8ae3SPaolo Bonzini 
827c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages++;
828c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
829c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
830c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
831c50d8ae3SPaolo Bonzini 
832c50d8ae3SPaolo Bonzini 	/* the non-leaf shadow pages are keeping readonly. */
8333bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
83496316a06SSean Christopherson 		return __kvm_write_track_add_gfn(kvm, slot, gfn);
835c50d8ae3SPaolo Bonzini 
836c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
837be911771SDavid Matlack 
838be911771SDavid Matlack 	if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
8394ad980aeSHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, PG_LEVEL_4K);
840c50d8ae3SPaolo Bonzini }
841c50d8ae3SPaolo Bonzini 
84261f94478SSean Christopherson void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
843c50d8ae3SPaolo Bonzini {
844428e9216SSean Christopherson 	/*
845428e9216SSean Christopherson 	 * If it's possible to replace the shadow page with an NX huge page,
846428e9216SSean Christopherson 	 * i.e. if the shadow page is the only thing currently preventing KVM
847428e9216SSean Christopherson 	 * from using a huge page, add the shadow page to the list of "to be
848428e9216SSean Christopherson 	 * zapped for NX recovery" pages.  Note, the shadow page can already be
849428e9216SSean Christopherson 	 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
850428e9216SSean Christopherson 	 * links a shadow page at multiple points.
851428e9216SSean Christopherson 	 */
85261f94478SSean Christopherson 	if (!list_empty(&sp->possible_nx_huge_page_link))
853c50d8ae3SPaolo Bonzini 		return;
854c50d8ae3SPaolo Bonzini 
855c50d8ae3SPaolo Bonzini 	++kvm->stat.nx_lpage_splits;
85655c510e2SSean Christopherson 	list_add_tail(&sp->possible_nx_huge_page_link,
85755c510e2SSean Christopherson 		      &kvm->arch.possible_nx_huge_pages);
858c50d8ae3SPaolo Bonzini }
859c50d8ae3SPaolo Bonzini 
86061f94478SSean Christopherson static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
86161f94478SSean Christopherson 				 bool nx_huge_page_possible)
86261f94478SSean Christopherson {
86361f94478SSean Christopherson 	sp->nx_huge_page_disallowed = true;
86461f94478SSean Christopherson 
86561f94478SSean Christopherson 	if (nx_huge_page_possible)
86661f94478SSean Christopherson 		track_possible_nx_huge_page(kvm, sp);
867c50d8ae3SPaolo Bonzini }
868c50d8ae3SPaolo Bonzini 
869c50d8ae3SPaolo Bonzini static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
870c50d8ae3SPaolo Bonzini {
871c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
872c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
873c50d8ae3SPaolo Bonzini 	gfn_t gfn;
874c50d8ae3SPaolo Bonzini 
875c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages--;
876c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
877c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
878c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
8793bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
88096316a06SSean Christopherson 		return __kvm_write_track_remove_gfn(kvm, slot, gfn);
881c50d8ae3SPaolo Bonzini 
882c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_allow_lpage(slot, gfn);
883c50d8ae3SPaolo Bonzini }
884c50d8ae3SPaolo Bonzini 
88561f94478SSean Christopherson void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
886c50d8ae3SPaolo Bonzini {
88755c510e2SSean Christopherson 	if (list_empty(&sp->possible_nx_huge_page_link))
888428e9216SSean Christopherson 		return;
889428e9216SSean Christopherson 
890c50d8ae3SPaolo Bonzini 	--kvm->stat.nx_lpage_splits;
89155c510e2SSean Christopherson 	list_del_init(&sp->possible_nx_huge_page_link);
892c50d8ae3SPaolo Bonzini }
893c50d8ae3SPaolo Bonzini 
89461f94478SSean Christopherson static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
89561f94478SSean Christopherson {
89661f94478SSean Christopherson 	sp->nx_huge_page_disallowed = false;
89761f94478SSean Christopherson 
89861f94478SSean Christopherson 	untrack_possible_nx_huge_page(kvm, sp);
899c50d8ae3SPaolo Bonzini }
900c50d8ae3SPaolo Bonzini 
901f3d90f90SSean Christopherson static struct kvm_memory_slot *gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu,
902f3d90f90SSean Christopherson 							   gfn_t gfn,
903c50d8ae3SPaolo Bonzini 							   bool no_dirty_log)
904c50d8ae3SPaolo Bonzini {
905c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
906c50d8ae3SPaolo Bonzini 
907c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
90891b0d268SPaolo Bonzini 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
90991b0d268SPaolo Bonzini 		return NULL;
910044c59c4SPeter Xu 	if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
91191b0d268SPaolo Bonzini 		return NULL;
912c50d8ae3SPaolo Bonzini 
913c50d8ae3SPaolo Bonzini 	return slot;
914c50d8ae3SPaolo Bonzini }
915c50d8ae3SPaolo Bonzini 
916c50d8ae3SPaolo Bonzini /*
917c50d8ae3SPaolo Bonzini  * About rmap_head encoding:
918c50d8ae3SPaolo Bonzini  *
919c50d8ae3SPaolo Bonzini  * If the bit zero of rmap_head->val is clear, then it points to the only spte
920c50d8ae3SPaolo Bonzini  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
921c50d8ae3SPaolo Bonzini  * pte_list_desc containing more mappings.
922c50d8ae3SPaolo Bonzini  */
923c50d8ae3SPaolo Bonzini 
924c50d8ae3SPaolo Bonzini /*
925c50d8ae3SPaolo Bonzini  * Returns the number of pointers in the rmap chain, not counting the new one.
926c50d8ae3SPaolo Bonzini  */
9272ff9039aSDavid Matlack static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
928c50d8ae3SPaolo Bonzini 			struct kvm_rmap_head *rmap_head)
929c50d8ae3SPaolo Bonzini {
930c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
93113236e25SPeter Xu 	int count = 0;
932c50d8ae3SPaolo Bonzini 
933c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
934c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)spte;
935c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
9362ff9039aSDavid Matlack 		desc = kvm_mmu_memory_cache_alloc(cache);
937c50d8ae3SPaolo Bonzini 		desc->sptes[0] = (u64 *)rmap_head->val;
938c50d8ae3SPaolo Bonzini 		desc->sptes[1] = spte;
93913236e25SPeter Xu 		desc->spte_count = 2;
940141705b7SLai Jiangshan 		desc->tail_count = 0;
941c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)desc | 1;
942c50d8ae3SPaolo Bonzini 		++count;
943c50d8ae3SPaolo Bonzini 	} else {
944c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
945141705b7SLai Jiangshan 		count = desc->tail_count + desc->spte_count;
946141705b7SLai Jiangshan 
947141705b7SLai Jiangshan 		/*
948141705b7SLai Jiangshan 		 * If the previous head is full, allocate a new head descriptor
949141705b7SLai Jiangshan 		 * as tail descriptors are always kept full.
950141705b7SLai Jiangshan 		 */
951141705b7SLai Jiangshan 		if (desc->spte_count == PTE_LIST_EXT) {
952141705b7SLai Jiangshan 			desc = kvm_mmu_memory_cache_alloc(cache);
953141705b7SLai Jiangshan 			desc->more = (struct pte_list_desc *)(rmap_head->val & ~1ul);
95413236e25SPeter Xu 			desc->spte_count = 0;
955141705b7SLai Jiangshan 			desc->tail_count = count;
956141705b7SLai Jiangshan 			rmap_head->val = (unsigned long)desc | 1;
957c6c4f961SLi RongQing 		}
95813236e25SPeter Xu 		desc->sptes[desc->spte_count++] = spte;
959c50d8ae3SPaolo Bonzini 	}
960c50d8ae3SPaolo Bonzini 	return count;
961c50d8ae3SPaolo Bonzini }
962c50d8ae3SPaolo Bonzini 
963069f30c6SMingwei Zhang static void pte_list_desc_remove_entry(struct kvm *kvm,
964069f30c6SMingwei Zhang 				       struct kvm_rmap_head *rmap_head,
965141705b7SLai Jiangshan 				       struct pte_list_desc *desc, int i)
966c50d8ae3SPaolo Bonzini {
967141705b7SLai Jiangshan 	struct pte_list_desc *head_desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
968141705b7SLai Jiangshan 	int j = head_desc->spte_count - 1;
969c50d8ae3SPaolo Bonzini 
970141705b7SLai Jiangshan 	/*
971141705b7SLai Jiangshan 	 * The head descriptor should never be empty.  A new head is added only
972141705b7SLai Jiangshan 	 * when adding an entry and the previous head is full, and heads are
973141705b7SLai Jiangshan 	 * removed (this flow) when they become empty.
974141705b7SLai Jiangshan 	 */
97552e322edSSean Christopherson 	KVM_BUG_ON_DATA_CORRUPTION(j < 0, kvm);
976141705b7SLai Jiangshan 
977141705b7SLai Jiangshan 	/*
978141705b7SLai Jiangshan 	 * Replace the to-be-freed SPTE with the last valid entry from the head
979141705b7SLai Jiangshan 	 * descriptor to ensure that tail descriptors are full at all times.
980141705b7SLai Jiangshan 	 * Note, this also means that tail_count is stable for each descriptor.
981141705b7SLai Jiangshan 	 */
982141705b7SLai Jiangshan 	desc->sptes[i] = head_desc->sptes[j];
983141705b7SLai Jiangshan 	head_desc->sptes[j] = NULL;
984141705b7SLai Jiangshan 	head_desc->spte_count--;
985141705b7SLai Jiangshan 	if (head_desc->spte_count)
986c50d8ae3SPaolo Bonzini 		return;
987141705b7SLai Jiangshan 
988141705b7SLai Jiangshan 	/*
989141705b7SLai Jiangshan 	 * The head descriptor is empty.  If there are no tail descriptors,
990141705b7SLai Jiangshan 	 * nullify the rmap head to mark the list as emtpy, else point the rmap
991141705b7SLai Jiangshan 	 * head at the next descriptor, i.e. the new head.
992141705b7SLai Jiangshan 	 */
993141705b7SLai Jiangshan 	if (!head_desc->more)
994fe3c2b4cSMiaohe Lin 		rmap_head->val = 0;
995c50d8ae3SPaolo Bonzini 	else
996141705b7SLai Jiangshan 		rmap_head->val = (unsigned long)head_desc->more | 1;
997141705b7SLai Jiangshan 	mmu_free_pte_list_desc(head_desc);
998c50d8ae3SPaolo Bonzini }
999c50d8ae3SPaolo Bonzini 
1000069f30c6SMingwei Zhang static void pte_list_remove(struct kvm *kvm, u64 *spte,
1001069f30c6SMingwei Zhang 			    struct kvm_rmap_head *rmap_head)
1002c50d8ae3SPaolo Bonzini {
1003c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
1004c50d8ae3SPaolo Bonzini 	int i;
1005c50d8ae3SPaolo Bonzini 
100652e322edSSean Christopherson 	if (KVM_BUG_ON_DATA_CORRUPTION(!rmap_head->val, kvm))
100752e322edSSean Christopherson 		return;
100852e322edSSean Christopherson 
100952e322edSSean Christopherson 	if (!(rmap_head->val & 1)) {
101052e322edSSean Christopherson 		if (KVM_BUG_ON_DATA_CORRUPTION((u64 *)rmap_head->val != spte, kvm))
101152e322edSSean Christopherson 			return;
101252e322edSSean Christopherson 
1013c50d8ae3SPaolo Bonzini 		rmap_head->val = 0;
1014c50d8ae3SPaolo Bonzini 	} else {
1015c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1016c50d8ae3SPaolo Bonzini 		while (desc) {
101713236e25SPeter Xu 			for (i = 0; i < desc->spte_count; ++i) {
1018c50d8ae3SPaolo Bonzini 				if (desc->sptes[i] == spte) {
1019069f30c6SMingwei Zhang 					pte_list_desc_remove_entry(kvm, rmap_head,
1020069f30c6SMingwei Zhang 								   desc, i);
1021c50d8ae3SPaolo Bonzini 					return;
1022c50d8ae3SPaolo Bonzini 				}
1023c50d8ae3SPaolo Bonzini 			}
1024c50d8ae3SPaolo Bonzini 			desc = desc->more;
1025c50d8ae3SPaolo Bonzini 		}
102652e322edSSean Christopherson 
102752e322edSSean Christopherson 		KVM_BUG_ON_DATA_CORRUPTION(true, kvm);
1028c50d8ae3SPaolo Bonzini 	}
1029c50d8ae3SPaolo Bonzini }
1030c50d8ae3SPaolo Bonzini 
10319202aee8SSean Christopherson static void kvm_zap_one_rmap_spte(struct kvm *kvm,
10329202aee8SSean Christopherson 				  struct kvm_rmap_head *rmap_head, u64 *sptep)
1033c50d8ae3SPaolo Bonzini {
103471f51d2cSMingwei Zhang 	mmu_spte_clear_track_bits(kvm, sptep);
1035069f30c6SMingwei Zhang 	pte_list_remove(kvm, sptep, rmap_head);
1036c50d8ae3SPaolo Bonzini }
1037c50d8ae3SPaolo Bonzini 
10389202aee8SSean Christopherson /* Return true if at least one SPTE was zapped, false otherwise */
10399202aee8SSean Christopherson static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
10409202aee8SSean Christopherson 				   struct kvm_rmap_head *rmap_head)
1041a75b5404SPeter Xu {
1042a75b5404SPeter Xu 	struct pte_list_desc *desc, *next;
1043a75b5404SPeter Xu 	int i;
1044a75b5404SPeter Xu 
1045a75b5404SPeter Xu 	if (!rmap_head->val)
1046a75b5404SPeter Xu 		return false;
1047a75b5404SPeter Xu 
1048a75b5404SPeter Xu 	if (!(rmap_head->val & 1)) {
104971f51d2cSMingwei Zhang 		mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
1050a75b5404SPeter Xu 		goto out;
1051a75b5404SPeter Xu 	}
1052a75b5404SPeter Xu 
1053a75b5404SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1054a75b5404SPeter Xu 
1055a75b5404SPeter Xu 	for (; desc; desc = next) {
1056a75b5404SPeter Xu 		for (i = 0; i < desc->spte_count; i++)
105771f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1058a75b5404SPeter Xu 		next = desc->more;
1059a75b5404SPeter Xu 		mmu_free_pte_list_desc(desc);
1060a75b5404SPeter Xu 	}
1061a75b5404SPeter Xu out:
1062a75b5404SPeter Xu 	/* rmap_head is meaningless now, remember to reset it */
1063a75b5404SPeter Xu 	rmap_head->val = 0;
1064a75b5404SPeter Xu 	return true;
1065a75b5404SPeter Xu }
1066a75b5404SPeter Xu 
10673bcd0662SPeter Xu unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
10683bcd0662SPeter Xu {
10693bcd0662SPeter Xu 	struct pte_list_desc *desc;
10703bcd0662SPeter Xu 
10713bcd0662SPeter Xu 	if (!rmap_head->val)
10723bcd0662SPeter Xu 		return 0;
10733bcd0662SPeter Xu 	else if (!(rmap_head->val & 1))
10743bcd0662SPeter Xu 		return 1;
10753bcd0662SPeter Xu 
10763bcd0662SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1077141705b7SLai Jiangshan 	return desc->tail_count + desc->spte_count;
10783bcd0662SPeter Xu }
10793bcd0662SPeter Xu 
108093e083d4SDavid Matlack static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1081269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
1082c50d8ae3SPaolo Bonzini {
1083c50d8ae3SPaolo Bonzini 	unsigned long idx;
1084c50d8ae3SPaolo Bonzini 
1085c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
10863bae0459SSean Christopherson 	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1087c50d8ae3SPaolo Bonzini }
1088c50d8ae3SPaolo Bonzini 
1089c50d8ae3SPaolo Bonzini static void rmap_remove(struct kvm *kvm, u64 *spte)
1090c50d8ae3SPaolo Bonzini {
1091601f8af0SDavid Matlack 	struct kvm_memslots *slots;
1092601f8af0SDavid Matlack 	struct kvm_memory_slot *slot;
1093c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1094c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1095c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1096c50d8ae3SPaolo Bonzini 
109757354682SSean Christopherson 	sp = sptep_to_sp(spte);
109879e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1099601f8af0SDavid Matlack 
1100601f8af0SDavid Matlack 	/*
110168be1306SDavid Matlack 	 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
110268be1306SDavid Matlack 	 * so we have to determine which memslots to use based on context
110368be1306SDavid Matlack 	 * information in sp->role.
1104601f8af0SDavid Matlack 	 */
1105601f8af0SDavid Matlack 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1106601f8af0SDavid Matlack 
1107601f8af0SDavid Matlack 	slot = __gfn_to_memslot(slots, gfn);
110893e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1109601f8af0SDavid Matlack 
1110069f30c6SMingwei Zhang 	pte_list_remove(kvm, spte, rmap_head);
1111c50d8ae3SPaolo Bonzini }
1112c50d8ae3SPaolo Bonzini 
1113c50d8ae3SPaolo Bonzini /*
1114c50d8ae3SPaolo Bonzini  * Used by the following functions to iterate through the sptes linked by a
1115c50d8ae3SPaolo Bonzini  * rmap.  All fields are private and not assumed to be used outside.
1116c50d8ae3SPaolo Bonzini  */
1117c50d8ae3SPaolo Bonzini struct rmap_iterator {
1118c50d8ae3SPaolo Bonzini 	/* private fields */
1119c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1120c50d8ae3SPaolo Bonzini 	int pos;			/* index of the sptep */
1121c50d8ae3SPaolo Bonzini };
1122c50d8ae3SPaolo Bonzini 
1123c50d8ae3SPaolo Bonzini /*
1124c50d8ae3SPaolo Bonzini  * Iteration must be started by this function.  This should also be used after
1125c50d8ae3SPaolo Bonzini  * removing/dropping sptes from the rmap link because in such cases the
11260a03cbdaSMiaohe Lin  * information in the iterator may not be valid.
1127c50d8ae3SPaolo Bonzini  *
1128c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1129c50d8ae3SPaolo Bonzini  */
1130c50d8ae3SPaolo Bonzini static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1131c50d8ae3SPaolo Bonzini 			   struct rmap_iterator *iter)
1132c50d8ae3SPaolo Bonzini {
1133c50d8ae3SPaolo Bonzini 	u64 *sptep;
1134c50d8ae3SPaolo Bonzini 
1135c50d8ae3SPaolo Bonzini 	if (!rmap_head->val)
1136c50d8ae3SPaolo Bonzini 		return NULL;
1137c50d8ae3SPaolo Bonzini 
1138c50d8ae3SPaolo Bonzini 	if (!(rmap_head->val & 1)) {
1139c50d8ae3SPaolo Bonzini 		iter->desc = NULL;
1140c50d8ae3SPaolo Bonzini 		sptep = (u64 *)rmap_head->val;
1141c50d8ae3SPaolo Bonzini 		goto out;
1142c50d8ae3SPaolo Bonzini 	}
1143c50d8ae3SPaolo Bonzini 
1144c50d8ae3SPaolo Bonzini 	iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1145c50d8ae3SPaolo Bonzini 	iter->pos = 0;
1146c50d8ae3SPaolo Bonzini 	sptep = iter->desc->sptes[iter->pos];
1147c50d8ae3SPaolo Bonzini out:
1148c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1149c50d8ae3SPaolo Bonzini 	return sptep;
1150c50d8ae3SPaolo Bonzini }
1151c50d8ae3SPaolo Bonzini 
1152c50d8ae3SPaolo Bonzini /*
1153c50d8ae3SPaolo Bonzini  * Must be used with a valid iterator: e.g. after rmap_get_first().
1154c50d8ae3SPaolo Bonzini  *
1155c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1156c50d8ae3SPaolo Bonzini  */
1157c50d8ae3SPaolo Bonzini static u64 *rmap_get_next(struct rmap_iterator *iter)
1158c50d8ae3SPaolo Bonzini {
1159c50d8ae3SPaolo Bonzini 	u64 *sptep;
1160c50d8ae3SPaolo Bonzini 
1161c50d8ae3SPaolo Bonzini 	if (iter->desc) {
1162c50d8ae3SPaolo Bonzini 		if (iter->pos < PTE_LIST_EXT - 1) {
1163c50d8ae3SPaolo Bonzini 			++iter->pos;
1164c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1165c50d8ae3SPaolo Bonzini 			if (sptep)
1166c50d8ae3SPaolo Bonzini 				goto out;
1167c50d8ae3SPaolo Bonzini 		}
1168c50d8ae3SPaolo Bonzini 
1169c50d8ae3SPaolo Bonzini 		iter->desc = iter->desc->more;
1170c50d8ae3SPaolo Bonzini 
1171c50d8ae3SPaolo Bonzini 		if (iter->desc) {
1172c50d8ae3SPaolo Bonzini 			iter->pos = 0;
1173c50d8ae3SPaolo Bonzini 			/* desc->sptes[0] cannot be NULL */
1174c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1175c50d8ae3SPaolo Bonzini 			goto out;
1176c50d8ae3SPaolo Bonzini 		}
1177c50d8ae3SPaolo Bonzini 	}
1178c50d8ae3SPaolo Bonzini 
1179c50d8ae3SPaolo Bonzini 	return NULL;
1180c50d8ae3SPaolo Bonzini out:
1181c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1182c50d8ae3SPaolo Bonzini 	return sptep;
1183c50d8ae3SPaolo Bonzini }
1184c50d8ae3SPaolo Bonzini 
1185c50d8ae3SPaolo Bonzini #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)			\
1186c50d8ae3SPaolo Bonzini 	for (_spte_ = rmap_get_first(_rmap_head_, _iter_);		\
1187c50d8ae3SPaolo Bonzini 	     _spte_; _spte_ = rmap_get_next(_iter_))
1188c50d8ae3SPaolo Bonzini 
1189c50d8ae3SPaolo Bonzini static void drop_spte(struct kvm *kvm, u64 *sptep)
1190c50d8ae3SPaolo Bonzini {
119171f51d2cSMingwei Zhang 	u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
11927fa2a347SSean Christopherson 
11937fa2a347SSean Christopherson 	if (is_shadow_present_pte(old_spte))
1194c50d8ae3SPaolo Bonzini 		rmap_remove(kvm, sptep);
1195c50d8ae3SPaolo Bonzini }
1196c50d8ae3SPaolo Bonzini 
119703787394SPaolo Bonzini static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1198c50d8ae3SPaolo Bonzini {
11990cd8dc73SPaolo Bonzini 	struct kvm_mmu_page *sp;
12000cd8dc73SPaolo Bonzini 
12010cd8dc73SPaolo Bonzini 	sp = sptep_to_sp(sptep);
120220ba462dSSean Christopherson 	WARN_ON_ONCE(sp->role.level == PG_LEVEL_4K);
12030cd8dc73SPaolo Bonzini 
1204c50d8ae3SPaolo Bonzini 	drop_spte(kvm, sptep);
120503787394SPaolo Bonzini 
120603787394SPaolo Bonzini 	if (flush)
12071b2dc736SHou Wenlong 		kvm_flush_remote_tlbs_sptep(kvm, sptep);
1208c50d8ae3SPaolo Bonzini }
1209c50d8ae3SPaolo Bonzini 
1210c50d8ae3SPaolo Bonzini /*
1211c50d8ae3SPaolo Bonzini  * Write-protect on the specified @sptep, @pt_protect indicates whether
1212c50d8ae3SPaolo Bonzini  * spte write-protection is caused by protecting shadow page table.
1213c50d8ae3SPaolo Bonzini  *
1214c50d8ae3SPaolo Bonzini  * Note: write protection is difference between dirty logging and spte
1215c50d8ae3SPaolo Bonzini  * protection:
1216c50d8ae3SPaolo Bonzini  * - for dirty logging, the spte can be set to writable at anytime if
1217c50d8ae3SPaolo Bonzini  *   its dirty bitmap is properly set.
1218c50d8ae3SPaolo Bonzini  * - for spte protection, the spte can be writable only after unsync-ing
1219c50d8ae3SPaolo Bonzini  *   shadow page.
1220c50d8ae3SPaolo Bonzini  *
1221c50d8ae3SPaolo Bonzini  * Return true if tlb need be flushed.
1222c50d8ae3SPaolo Bonzini  */
1223c50d8ae3SPaolo Bonzini static bool spte_write_protect(u64 *sptep, bool pt_protect)
1224c50d8ae3SPaolo Bonzini {
1225c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1226c50d8ae3SPaolo Bonzini 
1227c50d8ae3SPaolo Bonzini 	if (!is_writable_pte(spte) &&
1228706c9c55SSean Christopherson 	    !(pt_protect && is_mmu_writable_spte(spte)))
1229c50d8ae3SPaolo Bonzini 		return false;
1230c50d8ae3SPaolo Bonzini 
1231c50d8ae3SPaolo Bonzini 	if (pt_protect)
12325fc3424fSSean Christopherson 		spte &= ~shadow_mmu_writable_mask;
1233c50d8ae3SPaolo Bonzini 	spte = spte & ~PT_WRITABLE_MASK;
1234c50d8ae3SPaolo Bonzini 
1235c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1236c50d8ae3SPaolo Bonzini }
1237c50d8ae3SPaolo Bonzini 
12381346bbb6SDavid Matlack static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1239c50d8ae3SPaolo Bonzini 			       bool pt_protect)
1240c50d8ae3SPaolo Bonzini {
1241c50d8ae3SPaolo Bonzini 	u64 *sptep;
1242c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1243c50d8ae3SPaolo Bonzini 	bool flush = false;
1244c50d8ae3SPaolo Bonzini 
1245c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1246c50d8ae3SPaolo Bonzini 		flush |= spte_write_protect(sptep, pt_protect);
1247c50d8ae3SPaolo Bonzini 
1248c50d8ae3SPaolo Bonzini 	return flush;
1249c50d8ae3SPaolo Bonzini }
1250c50d8ae3SPaolo Bonzini 
1251c50d8ae3SPaolo Bonzini static bool spte_clear_dirty(u64 *sptep)
1252c50d8ae3SPaolo Bonzini {
1253c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1254c50d8ae3SPaolo Bonzini 
12550fe6370eSSean Christopherson 	KVM_MMU_WARN_ON(!spte_ad_enabled(spte));
1256c50d8ae3SPaolo Bonzini 	spte &= ~shadow_dirty_mask;
1257c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1258c50d8ae3SPaolo Bonzini }
1259c50d8ae3SPaolo Bonzini 
1260c50d8ae3SPaolo Bonzini static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1261c50d8ae3SPaolo Bonzini {
1262c50d8ae3SPaolo Bonzini 	bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1263c50d8ae3SPaolo Bonzini 					       (unsigned long *)sptep);
1264c50d8ae3SPaolo Bonzini 	if (was_writable && !spte_ad_enabled(*sptep))
1265c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1266c50d8ae3SPaolo Bonzini 
1267c50d8ae3SPaolo Bonzini 	return was_writable;
1268c50d8ae3SPaolo Bonzini }
1269c50d8ae3SPaolo Bonzini 
1270c50d8ae3SPaolo Bonzini /*
1271c50d8ae3SPaolo Bonzini  * Gets the GFN ready for another round of dirty logging by clearing the
1272c50d8ae3SPaolo Bonzini  *	- D bit on ad-enabled SPTEs, and
1273c50d8ae3SPaolo Bonzini  *	- W bit on ad-disabled SPTEs.
1274c50d8ae3SPaolo Bonzini  * Returns true iff any D or W bits were cleared.
1275c50d8ae3SPaolo Bonzini  */
12760a234f5dSSean Christopherson static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1277269e9552SHamza Mahfooz 			       const struct kvm_memory_slot *slot)
1278c50d8ae3SPaolo Bonzini {
1279c50d8ae3SPaolo Bonzini 	u64 *sptep;
1280c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1281c50d8ae3SPaolo Bonzini 	bool flush = false;
1282c50d8ae3SPaolo Bonzini 
1283c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1284c50d8ae3SPaolo Bonzini 		if (spte_ad_need_write_protect(*sptep))
1285c50d8ae3SPaolo Bonzini 			flush |= spte_wrprot_for_clear_dirty(sptep);
1286c50d8ae3SPaolo Bonzini 		else
1287c50d8ae3SPaolo Bonzini 			flush |= spte_clear_dirty(sptep);
1288c50d8ae3SPaolo Bonzini 
1289c50d8ae3SPaolo Bonzini 	return flush;
1290c50d8ae3SPaolo Bonzini }
1291c50d8ae3SPaolo Bonzini 
1292c50d8ae3SPaolo Bonzini /**
1293c50d8ae3SPaolo Bonzini  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1294c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1295c50d8ae3SPaolo Bonzini  * @slot: slot to protect
1296c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1297c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should protect
1298c50d8ae3SPaolo Bonzini  *
129989212919SKeqian Zhu  * Used when we do not need to care about huge page mappings.
1300c50d8ae3SPaolo Bonzini  */
1301c50d8ae3SPaolo Bonzini static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1302c50d8ae3SPaolo Bonzini 				     struct kvm_memory_slot *slot,
1303c50d8ae3SPaolo Bonzini 				     gfn_t gfn_offset, unsigned long mask)
1304c50d8ae3SPaolo Bonzini {
1305c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1306c50d8ae3SPaolo Bonzini 
13071f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1308a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1309a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, true);
1310e2209710SBen Gardon 
1311e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1312e2209710SBen Gardon 		return;
1313e2209710SBen Gardon 
1314c50d8ae3SPaolo Bonzini 	while (mask) {
131593e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13163bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13171346bbb6SDavid Matlack 		rmap_write_protect(rmap_head, false);
1318c50d8ae3SPaolo Bonzini 
1319c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1320c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1321c50d8ae3SPaolo Bonzini 	}
1322c50d8ae3SPaolo Bonzini }
1323c50d8ae3SPaolo Bonzini 
1324c50d8ae3SPaolo Bonzini /**
1325c50d8ae3SPaolo Bonzini  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1326c50d8ae3SPaolo Bonzini  * protect the page if the D-bit isn't supported.
1327c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1328c50d8ae3SPaolo Bonzini  * @slot: slot to clear D-bit
1329c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1330c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should clear D-bit
1331c50d8ae3SPaolo Bonzini  *
1332c50d8ae3SPaolo Bonzini  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1333c50d8ae3SPaolo Bonzini  */
1334a018eba5SSean Christopherson static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1335c50d8ae3SPaolo Bonzini 					 struct kvm_memory_slot *slot,
1336c50d8ae3SPaolo Bonzini 					 gfn_t gfn_offset, unsigned long mask)
1337c50d8ae3SPaolo Bonzini {
1338c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1339c50d8ae3SPaolo Bonzini 
13401f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1341a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1342a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, false);
1343e2209710SBen Gardon 
1344e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1345e2209710SBen Gardon 		return;
1346e2209710SBen Gardon 
1347c50d8ae3SPaolo Bonzini 	while (mask) {
134893e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13493bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13500a234f5dSSean Christopherson 		__rmap_clear_dirty(kvm, rmap_head, slot);
1351c50d8ae3SPaolo Bonzini 
1352c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1353c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1354c50d8ae3SPaolo Bonzini 	}
1355c50d8ae3SPaolo Bonzini }
1356c50d8ae3SPaolo Bonzini 
1357c50d8ae3SPaolo Bonzini /**
1358c50d8ae3SPaolo Bonzini  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1359c50d8ae3SPaolo Bonzini  * PT level pages.
1360c50d8ae3SPaolo Bonzini  *
1361c50d8ae3SPaolo Bonzini  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1362c50d8ae3SPaolo Bonzini  * enable dirty logging for them.
1363c50d8ae3SPaolo Bonzini  *
136489212919SKeqian Zhu  * We need to care about huge page mappings: e.g. during dirty logging we may
136589212919SKeqian Zhu  * have such mappings.
1366c50d8ae3SPaolo Bonzini  */
1367c50d8ae3SPaolo Bonzini void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1368c50d8ae3SPaolo Bonzini 				struct kvm_memory_slot *slot,
1369c50d8ae3SPaolo Bonzini 				gfn_t gfn_offset, unsigned long mask)
1370c50d8ae3SPaolo Bonzini {
137189212919SKeqian Zhu 	/*
137289212919SKeqian Zhu 	 * Huge pages are NOT write protected when we start dirty logging in
137389212919SKeqian Zhu 	 * initially-all-set mode; must write protect them here so that they
137489212919SKeqian Zhu 	 * are split to 4K on the first write.
137589212919SKeqian Zhu 	 *
137689212919SKeqian Zhu 	 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
137789212919SKeqian Zhu 	 * of memslot has no such restriction, so the range can cross two large
137889212919SKeqian Zhu 	 * pages.
137989212919SKeqian Zhu 	 */
138089212919SKeqian Zhu 	if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
138189212919SKeqian Zhu 		gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
138289212919SKeqian Zhu 		gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
138389212919SKeqian Zhu 
1384cb00a70bSDavid Matlack 		if (READ_ONCE(eager_page_split))
1385cb00a70bSDavid Matlack 			kvm_mmu_try_split_huge_pages(kvm, slot, start, end, PG_LEVEL_4K);
1386cb00a70bSDavid Matlack 
138789212919SKeqian Zhu 		kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
138889212919SKeqian Zhu 
138989212919SKeqian Zhu 		/* Cross two large pages? */
139089212919SKeqian Zhu 		if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
139189212919SKeqian Zhu 		    ALIGN(end << PAGE_SHIFT, PMD_SIZE))
139289212919SKeqian Zhu 			kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
139389212919SKeqian Zhu 						       PG_LEVEL_2M);
139489212919SKeqian Zhu 	}
139589212919SKeqian Zhu 
139689212919SKeqian Zhu 	/* Now handle 4K PTEs.  */
1397a018eba5SSean Christopherson 	if (kvm_x86_ops.cpu_dirty_log_size)
1398a018eba5SSean Christopherson 		kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1399c50d8ae3SPaolo Bonzini 	else
1400c50d8ae3SPaolo Bonzini 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1401c50d8ae3SPaolo Bonzini }
1402c50d8ae3SPaolo Bonzini 
1403fb04a1edSPeter Xu int kvm_cpu_dirty_log_size(void)
1404fb04a1edSPeter Xu {
14056dd03800SSean Christopherson 	return kvm_x86_ops.cpu_dirty_log_size;
1406fb04a1edSPeter Xu }
1407fb04a1edSPeter Xu 
1408c50d8ae3SPaolo Bonzini bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
14093ad93562SKeqian Zhu 				    struct kvm_memory_slot *slot, u64 gfn,
14103ad93562SKeqian Zhu 				    int min_level)
1411c50d8ae3SPaolo Bonzini {
1412c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1413c50d8ae3SPaolo Bonzini 	int i;
1414c50d8ae3SPaolo Bonzini 	bool write_protected = false;
1415c50d8ae3SPaolo Bonzini 
1416e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
14173ad93562SKeqian Zhu 		for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
141893e083d4SDavid Matlack 			rmap_head = gfn_to_rmap(gfn, i, slot);
14191346bbb6SDavid Matlack 			write_protected |= rmap_write_protect(rmap_head, true);
1420c50d8ae3SPaolo Bonzini 		}
1421e2209710SBen Gardon 	}
1422c50d8ae3SPaolo Bonzini 
14231f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
142446044f72SBen Gardon 		write_protected |=
14253ad93562SKeqian Zhu 			kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
142646044f72SBen Gardon 
1427c50d8ae3SPaolo Bonzini 	return write_protected;
1428c50d8ae3SPaolo Bonzini }
1429c50d8ae3SPaolo Bonzini 
1430cf48f9e2SDavid Matlack static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1431c50d8ae3SPaolo Bonzini {
1432c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
1433c50d8ae3SPaolo Bonzini 
1434c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
14353ad93562SKeqian Zhu 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1436c50d8ae3SPaolo Bonzini }
1437c50d8ae3SPaolo Bonzini 
1438f8480721SSean Christopherson static bool __kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1439269e9552SHamza Mahfooz 			   const struct kvm_memory_slot *slot)
1440c50d8ae3SPaolo Bonzini {
14419202aee8SSean Christopherson 	return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1442c50d8ae3SPaolo Bonzini }
1443c50d8ae3SPaolo Bonzini 
1444f8480721SSean Christopherson static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1445c50d8ae3SPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
14463039bcc7SSean Christopherson 			 pte_t unused)
1447c50d8ae3SPaolo Bonzini {
1448f8480721SSean Christopherson 	return __kvm_zap_rmap(kvm, rmap_head, slot);
1449c50d8ae3SPaolo Bonzini }
1450c50d8ae3SPaolo Bonzini 
1451aed02fe3SSean Christopherson static bool kvm_set_pte_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1452c50d8ae3SPaolo Bonzini 			     struct kvm_memory_slot *slot, gfn_t gfn, int level,
14533039bcc7SSean Christopherson 			     pte_t pte)
1454c50d8ae3SPaolo Bonzini {
1455c50d8ae3SPaolo Bonzini 	u64 *sptep;
1456c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
145798a26b69SVihas Mak 	bool need_flush = false;
1458c50d8ae3SPaolo Bonzini 	u64 new_spte;
1459c50d8ae3SPaolo Bonzini 	kvm_pfn_t new_pfn;
1460c50d8ae3SPaolo Bonzini 
146120ba462dSSean Christopherson 	WARN_ON_ONCE(pte_huge(pte));
14623039bcc7SSean Christopherson 	new_pfn = pte_pfn(pte);
1463c50d8ae3SPaolo Bonzini 
1464c50d8ae3SPaolo Bonzini restart:
1465c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
146698a26b69SVihas Mak 		need_flush = true;
1467c50d8ae3SPaolo Bonzini 
14683039bcc7SSean Christopherson 		if (pte_write(pte)) {
14699202aee8SSean Christopherson 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
1470c50d8ae3SPaolo Bonzini 			goto restart;
1471c50d8ae3SPaolo Bonzini 		} else {
1472cb3eedabSPaolo Bonzini 			new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1473cb3eedabSPaolo Bonzini 					*sptep, new_pfn);
1474c50d8ae3SPaolo Bonzini 
147571f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, sptep);
1476c50d8ae3SPaolo Bonzini 			mmu_spte_set(sptep, new_spte);
1477c50d8ae3SPaolo Bonzini 		}
1478c50d8ae3SPaolo Bonzini 	}
1479c50d8ae3SPaolo Bonzini 
14808a1300ffSSean Christopherson 	if (need_flush && kvm_available_flush_remote_tlbs_range()) {
14819ffe9265SHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, level);
148298a26b69SVihas Mak 		return false;
1483c50d8ae3SPaolo Bonzini 	}
1484c50d8ae3SPaolo Bonzini 
1485c50d8ae3SPaolo Bonzini 	return need_flush;
1486c50d8ae3SPaolo Bonzini }
1487c50d8ae3SPaolo Bonzini 
1488c50d8ae3SPaolo Bonzini struct slot_rmap_walk_iterator {
1489c50d8ae3SPaolo Bonzini 	/* input fields. */
1490269e9552SHamza Mahfooz 	const struct kvm_memory_slot *slot;
1491c50d8ae3SPaolo Bonzini 	gfn_t start_gfn;
1492c50d8ae3SPaolo Bonzini 	gfn_t end_gfn;
1493c50d8ae3SPaolo Bonzini 	int start_level;
1494c50d8ae3SPaolo Bonzini 	int end_level;
1495c50d8ae3SPaolo Bonzini 
1496c50d8ae3SPaolo Bonzini 	/* output fields. */
1497c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1498c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap;
1499c50d8ae3SPaolo Bonzini 	int level;
1500c50d8ae3SPaolo Bonzini 
1501c50d8ae3SPaolo Bonzini 	/* private field. */
1502c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *end_rmap;
1503c50d8ae3SPaolo Bonzini };
1504c50d8ae3SPaolo Bonzini 
1505f3d90f90SSean Christopherson static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,
1506f3d90f90SSean Christopherson 				 int level)
1507c50d8ae3SPaolo Bonzini {
1508c50d8ae3SPaolo Bonzini 	iterator->level = level;
1509c50d8ae3SPaolo Bonzini 	iterator->gfn = iterator->start_gfn;
151093e083d4SDavid Matlack 	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
151193e083d4SDavid Matlack 	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1512c50d8ae3SPaolo Bonzini }
1513c50d8ae3SPaolo Bonzini 
1514f3d90f90SSean Christopherson static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1515f3d90f90SSean Christopherson 				const struct kvm_memory_slot *slot,
1516f3d90f90SSean Christopherson 				int start_level, int end_level,
1517f3d90f90SSean Christopherson 				gfn_t start_gfn, gfn_t end_gfn)
1518c50d8ae3SPaolo Bonzini {
1519c50d8ae3SPaolo Bonzini 	iterator->slot = slot;
1520c50d8ae3SPaolo Bonzini 	iterator->start_level = start_level;
1521c50d8ae3SPaolo Bonzini 	iterator->end_level = end_level;
1522c50d8ae3SPaolo Bonzini 	iterator->start_gfn = start_gfn;
1523c50d8ae3SPaolo Bonzini 	iterator->end_gfn = end_gfn;
1524c50d8ae3SPaolo Bonzini 
1525c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->start_level);
1526c50d8ae3SPaolo Bonzini }
1527c50d8ae3SPaolo Bonzini 
1528c50d8ae3SPaolo Bonzini static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1529c50d8ae3SPaolo Bonzini {
1530c50d8ae3SPaolo Bonzini 	return !!iterator->rmap;
1531c50d8ae3SPaolo Bonzini }
1532c50d8ae3SPaolo Bonzini 
1533c50d8ae3SPaolo Bonzini static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1534c50d8ae3SPaolo Bonzini {
15356ba1e04fSVipin Sharma 	while (++iterator->rmap <= iterator->end_rmap) {
1536c50d8ae3SPaolo Bonzini 		iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
15376ba1e04fSVipin Sharma 
15386ba1e04fSVipin Sharma 		if (iterator->rmap->val)
1539c50d8ae3SPaolo Bonzini 			return;
1540c50d8ae3SPaolo Bonzini 	}
1541c50d8ae3SPaolo Bonzini 
1542c50d8ae3SPaolo Bonzini 	if (++iterator->level > iterator->end_level) {
1543c50d8ae3SPaolo Bonzini 		iterator->rmap = NULL;
1544c50d8ae3SPaolo Bonzini 		return;
1545c50d8ae3SPaolo Bonzini 	}
1546c50d8ae3SPaolo Bonzini 
1547c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->level);
1548c50d8ae3SPaolo Bonzini }
1549c50d8ae3SPaolo Bonzini 
1550c50d8ae3SPaolo Bonzini #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1551c50d8ae3SPaolo Bonzini 	   _start_gfn, _end_gfn, _iter_)				\
1552c50d8ae3SPaolo Bonzini 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1553c50d8ae3SPaolo Bonzini 				 _end_level_, _start_gfn, _end_gfn);	\
1554c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_okay(_iter_);				\
1555c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_next(_iter_))
1556c50d8ae3SPaolo Bonzini 
15573039bcc7SSean Christopherson typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1558c1b91493SSean Christopherson 			       struct kvm_memory_slot *slot, gfn_t gfn,
15593039bcc7SSean Christopherson 			       int level, pte_t pte);
1560c1b91493SSean Christopherson 
15613039bcc7SSean Christopherson static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
15623039bcc7SSean Christopherson 						 struct kvm_gfn_range *range,
1563c1b91493SSean Christopherson 						 rmap_handler_t handler)
1564c50d8ae3SPaolo Bonzini {
1565c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
15663039bcc7SSean Christopherson 	bool ret = false;
1567c50d8ae3SPaolo Bonzini 
15683039bcc7SSean Christopherson 	for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
15693039bcc7SSean Christopherson 				 range->start, range->end - 1, &iterator)
15703039bcc7SSean Christopherson 		ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
15713e1efe2bSSean Christopherson 			       iterator.level, range->arg.pte);
1572c50d8ae3SPaolo Bonzini 
1573c50d8ae3SPaolo Bonzini 	return ret;
1574c50d8ae3SPaolo Bonzini }
1575c50d8ae3SPaolo Bonzini 
15763039bcc7SSean Christopherson bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1577c50d8ae3SPaolo Bonzini {
1578e2209710SBen Gardon 	bool flush = false;
1579c50d8ae3SPaolo Bonzini 
1580e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1581f8480721SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
1582063afacdSBen Gardon 
15831f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1584c7785d85SHou Wenlong 		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1585063afacdSBen Gardon 
15860a3869e1SSean Christopherson 	if (kvm_x86_ops.set_apic_access_page_addr &&
15870a3869e1SSean Christopherson 	    range->slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT)
15880a8a5f2cSSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
15890a8a5f2cSSean Christopherson 
15903039bcc7SSean Christopherson 	return flush;
1591c50d8ae3SPaolo Bonzini }
1592c50d8ae3SPaolo Bonzini 
15933039bcc7SSean Christopherson bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1594c50d8ae3SPaolo Bonzini {
1595e2209710SBen Gardon 	bool flush = false;
15961d8dd6b3SBen Gardon 
1597e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1598aed02fe3SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmap);
15991d8dd6b3SBen Gardon 
16001f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16013039bcc7SSean Christopherson 		flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
16021d8dd6b3SBen Gardon 
16033039bcc7SSean Christopherson 	return flush;
1604c50d8ae3SPaolo Bonzini }
1605c50d8ae3SPaolo Bonzini 
1606aed02fe3SSean Christopherson static bool kvm_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1607c50d8ae3SPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
16083039bcc7SSean Christopherson 			 pte_t unused)
1609c50d8ae3SPaolo Bonzini {
1610c50d8ae3SPaolo Bonzini 	u64 *sptep;
16113f649ab7SKees Cook 	struct rmap_iterator iter;
1612c50d8ae3SPaolo Bonzini 	int young = 0;
1613c50d8ae3SPaolo Bonzini 
1614c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1615c50d8ae3SPaolo Bonzini 		young |= mmu_spte_age(sptep);
1616c50d8ae3SPaolo Bonzini 
1617c50d8ae3SPaolo Bonzini 	return young;
1618c50d8ae3SPaolo Bonzini }
1619c50d8ae3SPaolo Bonzini 
1620aed02fe3SSean Christopherson static bool kvm_test_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1621c50d8ae3SPaolo Bonzini 			      struct kvm_memory_slot *slot, gfn_t gfn,
16223039bcc7SSean Christopherson 			      int level, pte_t unused)
1623c50d8ae3SPaolo Bonzini {
1624c50d8ae3SPaolo Bonzini 	u64 *sptep;
1625c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1626c50d8ae3SPaolo Bonzini 
1627c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1628c50d8ae3SPaolo Bonzini 		if (is_accessed_spte(*sptep))
162998a26b69SVihas Mak 			return true;
163098a26b69SVihas Mak 	return false;
1631c50d8ae3SPaolo Bonzini }
1632c50d8ae3SPaolo Bonzini 
1633c50d8ae3SPaolo Bonzini #define RMAP_RECYCLE_THRESHOLD 1000
1634c50d8ae3SPaolo Bonzini 
16352ff9039aSDavid Matlack static void __rmap_add(struct kvm *kvm,
16362ff9039aSDavid Matlack 		       struct kvm_mmu_memory_cache *cache,
16372ff9039aSDavid Matlack 		       const struct kvm_memory_slot *slot,
163872ae5822SSean Christopherson 		       u64 *spte, gfn_t gfn, unsigned int access)
1639c50d8ae3SPaolo Bonzini {
1640c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
164168be1306SDavid Matlack 	struct kvm_rmap_head *rmap_head;
164268be1306SDavid Matlack 	int rmap_count;
1643c50d8ae3SPaolo Bonzini 
164457354682SSean Christopherson 	sp = sptep_to_sp(spte);
164579e48cecSSean Christopherson 	kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
164681cb4657SDavid Matlack 	kvm_update_page_stats(kvm, sp->role.level, 1);
164781cb4657SDavid Matlack 
164893e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
16492ff9039aSDavid Matlack 	rmap_count = pte_list_add(cache, spte, rmap_head);
1650c50d8ae3SPaolo Bonzini 
1651604f5332SMiaohe Lin 	if (rmap_count > kvm->stat.max_mmu_rmap_size)
1652604f5332SMiaohe Lin 		kvm->stat.max_mmu_rmap_size = rmap_count;
165368be1306SDavid Matlack 	if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
16549202aee8SSean Christopherson 		kvm_zap_all_rmap_sptes(kvm, rmap_head);
16551b2dc736SHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
165668be1306SDavid Matlack 	}
1657c50d8ae3SPaolo Bonzini }
1658c50d8ae3SPaolo Bonzini 
16592ff9039aSDavid Matlack static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
166072ae5822SSean Christopherson 		     u64 *spte, gfn_t gfn, unsigned int access)
16612ff9039aSDavid Matlack {
16622ff9039aSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
16632ff9039aSDavid Matlack 
16646a97575dSDavid Matlack 	__rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
16652ff9039aSDavid Matlack }
16662ff9039aSDavid Matlack 
16673039bcc7SSean Christopherson bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1668c50d8ae3SPaolo Bonzini {
1669e2209710SBen Gardon 	bool young = false;
1670f8e14497SBen Gardon 
1671e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1672aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_age_rmap);
16733039bcc7SSean Christopherson 
16741f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16753039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1676f8e14497SBen Gardon 
1677f8e14497SBen Gardon 	return young;
1678c50d8ae3SPaolo Bonzini }
1679c50d8ae3SPaolo Bonzini 
16803039bcc7SSean Christopherson bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1681c50d8ae3SPaolo Bonzini {
1682e2209710SBen Gardon 	bool young = false;
1683f8e14497SBen Gardon 
1684e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1685aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmap);
16863039bcc7SSean Christopherson 
16871f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16883039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1689f8e14497SBen Gardon 
1690f8e14497SBen Gardon 	return young;
1691c50d8ae3SPaolo Bonzini }
1692c50d8ae3SPaolo Bonzini 
169358da926cSSean Christopherson static void kvm_mmu_check_sptes_at_free(struct kvm_mmu_page *sp)
1694c50d8ae3SPaolo Bonzini {
1695870d4d4eSSean Christopherson #ifdef CONFIG_KVM_PROVE_MMU
1696242a6dd8SSean Christopherson 	int i;
1697c50d8ae3SPaolo Bonzini 
1698242a6dd8SSean Christopherson 	for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
16990fe6370eSSean Christopherson 		if (KVM_MMU_WARN_ON(is_shadow_present_pte(sp->spt[i])))
170058da926cSSean Christopherson 			pr_err_ratelimited("SPTE %llx (@ %p) for gfn %llx shadow-present at free",
170158da926cSSean Christopherson 					   sp->spt[i], &sp->spt[i],
170258da926cSSean Christopherson 					   kvm_mmu_page_get_gfn(sp, i));
1703c50d8ae3SPaolo Bonzini 	}
1704c50d8ae3SPaolo Bonzini #endif
170558da926cSSean Christopherson }
1706c50d8ae3SPaolo Bonzini 
1707c50d8ae3SPaolo Bonzini /*
1708c50d8ae3SPaolo Bonzini  * This value is the sum of all of the kvm instances's
1709c50d8ae3SPaolo Bonzini  * kvm->arch.n_used_mmu_pages values.  We need a global,
1710c50d8ae3SPaolo Bonzini  * aggregate version in order to make the slab shrinker
1711c50d8ae3SPaolo Bonzini  * faster
1712c50d8ae3SPaolo Bonzini  */
1713d5aaad6fSSean Christopherson static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1714c50d8ae3SPaolo Bonzini {
1715c50d8ae3SPaolo Bonzini 	kvm->arch.n_used_mmu_pages += nr;
1716c50d8ae3SPaolo Bonzini 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1717c50d8ae3SPaolo Bonzini }
1718c50d8ae3SPaolo Bonzini 
171943a063caSYosry Ahmed static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
172043a063caSYosry Ahmed {
172143a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, +1);
172243a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, +1);
172343a063caSYosry Ahmed }
172443a063caSYosry Ahmed 
172543a063caSYosry Ahmed static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
172643a063caSYosry Ahmed {
172743a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, -1);
172843a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, -1);
172943a063caSYosry Ahmed }
173043a063caSYosry Ahmed 
173187654643SDavid Matlack static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1732c50d8ae3SPaolo Bonzini {
173358da926cSSean Christopherson 	kvm_mmu_check_sptes_at_free(sp);
173458da926cSSean Christopherson 
1735c50d8ae3SPaolo Bonzini 	hlist_del(&sp->hash_link);
1736c50d8ae3SPaolo Bonzini 	list_del(&sp->link);
1737c50d8ae3SPaolo Bonzini 	free_page((unsigned long)sp->spt);
1738c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
17396a97575dSDavid Matlack 		free_page((unsigned long)sp->shadowed_translation);
1740c50d8ae3SPaolo Bonzini 	kmem_cache_free(mmu_page_header_cache, sp);
1741c50d8ae3SPaolo Bonzini }
1742c50d8ae3SPaolo Bonzini 
1743c50d8ae3SPaolo Bonzini static unsigned kvm_page_table_hashfn(gfn_t gfn)
1744c50d8ae3SPaolo Bonzini {
1745c50d8ae3SPaolo Bonzini 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1746c50d8ae3SPaolo Bonzini }
1747c50d8ae3SPaolo Bonzini 
17482ff9039aSDavid Matlack static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
1749c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp, u64 *parent_pte)
1750c50d8ae3SPaolo Bonzini {
1751c50d8ae3SPaolo Bonzini 	if (!parent_pte)
1752c50d8ae3SPaolo Bonzini 		return;
1753c50d8ae3SPaolo Bonzini 
17542ff9039aSDavid Matlack 	pte_list_add(cache, parent_pte, &sp->parent_ptes);
1755c50d8ae3SPaolo Bonzini }
1756c50d8ae3SPaolo Bonzini 
1757069f30c6SMingwei Zhang static void mmu_page_remove_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1758c50d8ae3SPaolo Bonzini 				       u64 *parent_pte)
1759c50d8ae3SPaolo Bonzini {
1760069f30c6SMingwei Zhang 	pte_list_remove(kvm, parent_pte, &sp->parent_ptes);
1761c50d8ae3SPaolo Bonzini }
1762c50d8ae3SPaolo Bonzini 
1763069f30c6SMingwei Zhang static void drop_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1764c50d8ae3SPaolo Bonzini 			    u64 *parent_pte)
1765c50d8ae3SPaolo Bonzini {
1766069f30c6SMingwei Zhang 	mmu_page_remove_parent_pte(kvm, sp, parent_pte);
1767c50d8ae3SPaolo Bonzini 	mmu_spte_clear_no_track(parent_pte);
1768c50d8ae3SPaolo Bonzini }
1769c50d8ae3SPaolo Bonzini 
1770c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte);
1771c50d8ae3SPaolo Bonzini static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1772c50d8ae3SPaolo Bonzini {
1773c50d8ae3SPaolo Bonzini 	u64 *sptep;
1774c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1775c50d8ae3SPaolo Bonzini 
1776c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1777c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
1778c50d8ae3SPaolo Bonzini 	}
1779c50d8ae3SPaolo Bonzini }
1780c50d8ae3SPaolo Bonzini 
1781c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte)
1782c50d8ae3SPaolo Bonzini {
1783c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1784c50d8ae3SPaolo Bonzini 
178557354682SSean Christopherson 	sp = sptep_to_sp(spte);
178679e48cecSSean Christopherson 	if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1787c50d8ae3SPaolo Bonzini 		return;
1788c50d8ae3SPaolo Bonzini 	if (sp->unsync_children++)
1789c50d8ae3SPaolo Bonzini 		return;
1790c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
1791c50d8ae3SPaolo Bonzini }
1792c50d8ae3SPaolo Bonzini 
1793c50d8ae3SPaolo Bonzini #define KVM_PAGE_ARRAY_NR 16
1794c50d8ae3SPaolo Bonzini 
1795c50d8ae3SPaolo Bonzini struct kvm_mmu_pages {
1796c50d8ae3SPaolo Bonzini 	struct mmu_page_and_offset {
1797c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
1798c50d8ae3SPaolo Bonzini 		unsigned int idx;
1799c50d8ae3SPaolo Bonzini 	} page[KVM_PAGE_ARRAY_NR];
1800c50d8ae3SPaolo Bonzini 	unsigned int nr;
1801c50d8ae3SPaolo Bonzini };
1802c50d8ae3SPaolo Bonzini 
1803c50d8ae3SPaolo Bonzini static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1804c50d8ae3SPaolo Bonzini 			 int idx)
1805c50d8ae3SPaolo Bonzini {
1806c50d8ae3SPaolo Bonzini 	int i;
1807c50d8ae3SPaolo Bonzini 
1808c50d8ae3SPaolo Bonzini 	if (sp->unsync)
1809c50d8ae3SPaolo Bonzini 		for (i=0; i < pvec->nr; i++)
1810c50d8ae3SPaolo Bonzini 			if (pvec->page[i].sp == sp)
1811c50d8ae3SPaolo Bonzini 				return 0;
1812c50d8ae3SPaolo Bonzini 
1813c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].sp = sp;
1814c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].idx = idx;
1815c50d8ae3SPaolo Bonzini 	pvec->nr++;
1816c50d8ae3SPaolo Bonzini 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
1817c50d8ae3SPaolo Bonzini }
1818c50d8ae3SPaolo Bonzini 
1819c50d8ae3SPaolo Bonzini static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1820c50d8ae3SPaolo Bonzini {
1821c50d8ae3SPaolo Bonzini 	--sp->unsync_children;
182220ba462dSSean Christopherson 	WARN_ON_ONCE((int)sp->unsync_children < 0);
1823c50d8ae3SPaolo Bonzini 	__clear_bit(idx, sp->unsync_child_bitmap);
1824c50d8ae3SPaolo Bonzini }
1825c50d8ae3SPaolo Bonzini 
1826c50d8ae3SPaolo Bonzini static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1827c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1828c50d8ae3SPaolo Bonzini {
1829c50d8ae3SPaolo Bonzini 	int i, ret, nr_unsync_leaf = 0;
1830c50d8ae3SPaolo Bonzini 
1831c50d8ae3SPaolo Bonzini 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1832c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
1833c50d8ae3SPaolo Bonzini 		u64 ent = sp->spt[i];
1834c50d8ae3SPaolo Bonzini 
1835c50d8ae3SPaolo Bonzini 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1836c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1837c50d8ae3SPaolo Bonzini 			continue;
1838c50d8ae3SPaolo Bonzini 		}
1839c50d8ae3SPaolo Bonzini 
18405e3edd7eSSean Christopherson 		child = spte_to_child_sp(ent);
1841c50d8ae3SPaolo Bonzini 
1842c50d8ae3SPaolo Bonzini 		if (child->unsync_children) {
1843c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1844c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1845c50d8ae3SPaolo Bonzini 
1846c50d8ae3SPaolo Bonzini 			ret = __mmu_unsync_walk(child, pvec);
1847c50d8ae3SPaolo Bonzini 			if (!ret) {
1848c50d8ae3SPaolo Bonzini 				clear_unsync_child_bit(sp, i);
1849c50d8ae3SPaolo Bonzini 				continue;
1850c50d8ae3SPaolo Bonzini 			} else if (ret > 0) {
1851c50d8ae3SPaolo Bonzini 				nr_unsync_leaf += ret;
1852c50d8ae3SPaolo Bonzini 			} else
1853c50d8ae3SPaolo Bonzini 				return ret;
1854c50d8ae3SPaolo Bonzini 		} else if (child->unsync) {
1855c50d8ae3SPaolo Bonzini 			nr_unsync_leaf++;
1856c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1857c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1858c50d8ae3SPaolo Bonzini 		} else
1859c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1860c50d8ae3SPaolo Bonzini 	}
1861c50d8ae3SPaolo Bonzini 
1862c50d8ae3SPaolo Bonzini 	return nr_unsync_leaf;
1863c50d8ae3SPaolo Bonzini }
1864c50d8ae3SPaolo Bonzini 
1865c50d8ae3SPaolo Bonzini #define INVALID_INDEX (-1)
1866c50d8ae3SPaolo Bonzini 
1867c50d8ae3SPaolo Bonzini static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1868c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1869c50d8ae3SPaolo Bonzini {
1870c50d8ae3SPaolo Bonzini 	pvec->nr = 0;
1871c50d8ae3SPaolo Bonzini 	if (!sp->unsync_children)
1872c50d8ae3SPaolo Bonzini 		return 0;
1873c50d8ae3SPaolo Bonzini 
1874c50d8ae3SPaolo Bonzini 	mmu_pages_add(pvec, sp, INVALID_INDEX);
1875c50d8ae3SPaolo Bonzini 	return __mmu_unsync_walk(sp, pvec);
1876c50d8ae3SPaolo Bonzini }
1877c50d8ae3SPaolo Bonzini 
1878c50d8ae3SPaolo Bonzini static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1879c50d8ae3SPaolo Bonzini {
188020ba462dSSean Christopherson 	WARN_ON_ONCE(!sp->unsync);
1881c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_sync_page(sp);
1882c50d8ae3SPaolo Bonzini 	sp->unsync = 0;
1883c50d8ae3SPaolo Bonzini 	--kvm->stat.mmu_unsync;
1884c50d8ae3SPaolo Bonzini }
1885c50d8ae3SPaolo Bonzini 
1886c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1887c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list);
1888c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1889c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list);
1890c50d8ae3SPaolo Bonzini 
1891767d8d8dSLai Jiangshan static bool sp_has_gptes(struct kvm_mmu_page *sp)
1892767d8d8dSLai Jiangshan {
1893767d8d8dSLai Jiangshan 	if (sp->role.direct)
1894767d8d8dSLai Jiangshan 		return false;
1895767d8d8dSLai Jiangshan 
189684e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
189784e5ffd0SLai Jiangshan 		return false;
189884e5ffd0SLai Jiangshan 
1899767d8d8dSLai Jiangshan 	return true;
1900767d8d8dSLai Jiangshan }
1901767d8d8dSLai Jiangshan 
1902ac101b7cSSean Christopherson #define for_each_valid_sp(_kvm, _sp, _list)				\
1903ac101b7cSSean Christopherson 	hlist_for_each_entry(_sp, _list, hash_link)			\
1904c50d8ae3SPaolo Bonzini 		if (is_obsolete_sp((_kvm), (_sp))) {			\
1905c50d8ae3SPaolo Bonzini 		} else
1906c50d8ae3SPaolo Bonzini 
1907767d8d8dSLai Jiangshan #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn)		\
1908ac101b7cSSean Christopherson 	for_each_valid_sp(_kvm, _sp,					\
1909ac101b7cSSean Christopherson 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
1910767d8d8dSLai Jiangshan 		if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1911c50d8ae3SPaolo Bonzini 
191290e44470SLai Jiangshan static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
191390e44470SLai Jiangshan {
191490e44470SLai Jiangshan 	union kvm_mmu_page_role root_role = vcpu->arch.mmu->root_role;
191590e44470SLai Jiangshan 
191690e44470SLai Jiangshan 	/*
191790e44470SLai Jiangshan 	 * Ignore various flags when verifying that it's safe to sync a shadow
191890e44470SLai Jiangshan 	 * page using the current MMU context.
191990e44470SLai Jiangshan 	 *
192090e44470SLai Jiangshan 	 *  - level: not part of the overall MMU role and will never match as the MMU's
192190e44470SLai Jiangshan 	 *           level tracks the root level
192290e44470SLai Jiangshan 	 *  - access: updated based on the new guest PTE
192390e44470SLai Jiangshan 	 *  - quadrant: not part of the overall MMU role (similar to level)
192490e44470SLai Jiangshan 	 */
192590e44470SLai Jiangshan 	const union kvm_mmu_page_role sync_role_ign = {
192690e44470SLai Jiangshan 		.level = 0xf,
192790e44470SLai Jiangshan 		.access = 0x7,
192890e44470SLai Jiangshan 		.quadrant = 0x3,
192990e44470SLai Jiangshan 		.passthrough = 0x1,
193090e44470SLai Jiangshan 	};
193190e44470SLai Jiangshan 
193290e44470SLai Jiangshan 	/*
193390e44470SLai Jiangshan 	 * Direct pages can never be unsync, and KVM should never attempt to
193490e44470SLai Jiangshan 	 * sync a shadow page for a different MMU context, e.g. if the role
193590e44470SLai Jiangshan 	 * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
193690e44470SLai Jiangshan 	 * reserved bits checks will be wrong, etc...
193790e44470SLai Jiangshan 	 */
1938c3c6c9fcSLai Jiangshan 	if (WARN_ON_ONCE(sp->role.direct || !vcpu->arch.mmu->sync_spte ||
193990e44470SLai Jiangshan 			 (sp->role.word ^ root_role.word) & ~sync_role_ign.word))
194090e44470SLai Jiangshan 		return false;
194190e44470SLai Jiangshan 
194290e44470SLai Jiangshan 	return true;
194390e44470SLai Jiangshan }
194490e44470SLai Jiangshan 
194519ace7d6SLai Jiangshan static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
194619ace7d6SLai Jiangshan {
194719ace7d6SLai Jiangshan 	if (!sp->spt[i])
194819ace7d6SLai Jiangshan 		return 0;
194919ace7d6SLai Jiangshan 
195019ace7d6SLai Jiangshan 	return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
195119ace7d6SLai Jiangshan }
195219ace7d6SLai Jiangshan 
195390e44470SLai Jiangshan static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
195490e44470SLai Jiangshan {
1955c3c6c9fcSLai Jiangshan 	int flush = 0;
1956c3c6c9fcSLai Jiangshan 	int i;
1957c3c6c9fcSLai Jiangshan 
195890e44470SLai Jiangshan 	if (!kvm_sync_page_check(vcpu, sp))
195990e44470SLai Jiangshan 		return -1;
196090e44470SLai Jiangshan 
1961c3c6c9fcSLai Jiangshan 	for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
196219ace7d6SLai Jiangshan 		int ret = kvm_sync_spte(vcpu, sp, i);
1963c3c6c9fcSLai Jiangshan 
1964c3c6c9fcSLai Jiangshan 		if (ret < -1)
1965c3c6c9fcSLai Jiangshan 			return -1;
1966c3c6c9fcSLai Jiangshan 		flush |= ret;
1967c3c6c9fcSLai Jiangshan 	}
1968c3c6c9fcSLai Jiangshan 
1969c3c6c9fcSLai Jiangshan 	/*
1970c3c6c9fcSLai Jiangshan 	 * Note, any flush is purely for KVM's correctness, e.g. when dropping
1971c3c6c9fcSLai Jiangshan 	 * an existing SPTE or clearing W/A/D bits to ensure an mmu_notifier
1972c3c6c9fcSLai Jiangshan 	 * unmap or dirty logging event doesn't fail to flush.  The guest is
1973c3c6c9fcSLai Jiangshan 	 * responsible for flushing the TLB to ensure any changes in protection
1974c3c6c9fcSLai Jiangshan 	 * bits are recognized, i.e. until the guest flushes or page faults on
1975c3c6c9fcSLai Jiangshan 	 * a relevant address, KVM is architecturally allowed to let vCPUs use
1976c3c6c9fcSLai Jiangshan 	 * cached translations with the old protection bits.
1977c3c6c9fcSLai Jiangshan 	 */
1978c3c6c9fcSLai Jiangshan 	return flush;
197990e44470SLai Jiangshan }
198090e44470SLai Jiangshan 
19818d5678a7SHou Wenlong static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1982c50d8ae3SPaolo Bonzini 			 struct list_head *invalid_list)
1983c50d8ae3SPaolo Bonzini {
198490e44470SLai Jiangshan 	int ret = __kvm_sync_page(vcpu, sp);
1985c3e5e415SLai Jiangshan 
19868d5678a7SHou Wenlong 	if (ret < 0)
1987c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
19888d5678a7SHou Wenlong 	return ret;
1989c50d8ae3SPaolo Bonzini }
1990c50d8ae3SPaolo Bonzini 
1991c50d8ae3SPaolo Bonzini static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1992c50d8ae3SPaolo Bonzini 					struct list_head *invalid_list,
1993c50d8ae3SPaolo Bonzini 					bool remote_flush)
1994c50d8ae3SPaolo Bonzini {
1995c50d8ae3SPaolo Bonzini 	if (!remote_flush && list_empty(invalid_list))
1996c50d8ae3SPaolo Bonzini 		return false;
1997c50d8ae3SPaolo Bonzini 
1998c50d8ae3SPaolo Bonzini 	if (!list_empty(invalid_list))
1999c50d8ae3SPaolo Bonzini 		kvm_mmu_commit_zap_page(kvm, invalid_list);
2000c50d8ae3SPaolo Bonzini 	else
2001c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
2002c50d8ae3SPaolo Bonzini 	return true;
2003c50d8ae3SPaolo Bonzini }
2004c50d8ae3SPaolo Bonzini 
2005c50d8ae3SPaolo Bonzini static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2006c50d8ae3SPaolo Bonzini {
2007a955cad8SSean Christopherson 	if (sp->role.invalid)
2008a955cad8SSean Christopherson 		return true;
2009a955cad8SSean Christopherson 
2010fa3e4203SMiaohe Lin 	/* TDP MMU pages do not use the MMU generation. */
2011de0322f5SSean Christopherson 	return !is_tdp_mmu_page(sp) &&
2012c50d8ae3SPaolo Bonzini 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2013c50d8ae3SPaolo Bonzini }
2014c50d8ae3SPaolo Bonzini 
2015c50d8ae3SPaolo Bonzini struct mmu_page_path {
2016c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2017c50d8ae3SPaolo Bonzini 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
2018c50d8ae3SPaolo Bonzini };
2019c50d8ae3SPaolo Bonzini 
2020c50d8ae3SPaolo Bonzini #define for_each_sp(pvec, sp, parents, i)			\
2021c50d8ae3SPaolo Bonzini 		for (i = mmu_pages_first(&pvec, &parents);	\
2022c50d8ae3SPaolo Bonzini 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
2023c50d8ae3SPaolo Bonzini 			i = mmu_pages_next(&pvec, &parents, i))
2024c50d8ae3SPaolo Bonzini 
2025c50d8ae3SPaolo Bonzini static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2026c50d8ae3SPaolo Bonzini 			  struct mmu_page_path *parents,
2027c50d8ae3SPaolo Bonzini 			  int i)
2028c50d8ae3SPaolo Bonzini {
2029c50d8ae3SPaolo Bonzini 	int n;
2030c50d8ae3SPaolo Bonzini 
2031c50d8ae3SPaolo Bonzini 	for (n = i+1; n < pvec->nr; n++) {
2032c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp = pvec->page[n].sp;
2033c50d8ae3SPaolo Bonzini 		unsigned idx = pvec->page[n].idx;
2034c50d8ae3SPaolo Bonzini 		int level = sp->role.level;
2035c50d8ae3SPaolo Bonzini 
2036c50d8ae3SPaolo Bonzini 		parents->idx[level-1] = idx;
20373bae0459SSean Christopherson 		if (level == PG_LEVEL_4K)
2038c50d8ae3SPaolo Bonzini 			break;
2039c50d8ae3SPaolo Bonzini 
2040c50d8ae3SPaolo Bonzini 		parents->parent[level-2] = sp;
2041c50d8ae3SPaolo Bonzini 	}
2042c50d8ae3SPaolo Bonzini 
2043c50d8ae3SPaolo Bonzini 	return n;
2044c50d8ae3SPaolo Bonzini }
2045c50d8ae3SPaolo Bonzini 
2046c50d8ae3SPaolo Bonzini static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2047c50d8ae3SPaolo Bonzini 			   struct mmu_page_path *parents)
2048c50d8ae3SPaolo Bonzini {
2049c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2050c50d8ae3SPaolo Bonzini 	int level;
2051c50d8ae3SPaolo Bonzini 
2052c50d8ae3SPaolo Bonzini 	if (pvec->nr == 0)
2053c50d8ae3SPaolo Bonzini 		return 0;
2054c50d8ae3SPaolo Bonzini 
205520ba462dSSean Christopherson 	WARN_ON_ONCE(pvec->page[0].idx != INVALID_INDEX);
2056c50d8ae3SPaolo Bonzini 
2057c50d8ae3SPaolo Bonzini 	sp = pvec->page[0].sp;
2058c50d8ae3SPaolo Bonzini 	level = sp->role.level;
205920ba462dSSean Christopherson 	WARN_ON_ONCE(level == PG_LEVEL_4K);
2060c50d8ae3SPaolo Bonzini 
2061c50d8ae3SPaolo Bonzini 	parents->parent[level-2] = sp;
2062c50d8ae3SPaolo Bonzini 
2063c50d8ae3SPaolo Bonzini 	/* Also set up a sentinel.  Further entries in pvec are all
2064c50d8ae3SPaolo Bonzini 	 * children of sp, so this element is never overwritten.
2065c50d8ae3SPaolo Bonzini 	 */
2066c50d8ae3SPaolo Bonzini 	parents->parent[level-1] = NULL;
2067c50d8ae3SPaolo Bonzini 	return mmu_pages_next(pvec, parents, 0);
2068c50d8ae3SPaolo Bonzini }
2069c50d8ae3SPaolo Bonzini 
2070c50d8ae3SPaolo Bonzini static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2071c50d8ae3SPaolo Bonzini {
2072c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2073c50d8ae3SPaolo Bonzini 	unsigned int level = 0;
2074c50d8ae3SPaolo Bonzini 
2075c50d8ae3SPaolo Bonzini 	do {
2076c50d8ae3SPaolo Bonzini 		unsigned int idx = parents->idx[level];
2077c50d8ae3SPaolo Bonzini 		sp = parents->parent[level];
2078c50d8ae3SPaolo Bonzini 		if (!sp)
2079c50d8ae3SPaolo Bonzini 			return;
2080c50d8ae3SPaolo Bonzini 
208120ba462dSSean Christopherson 		WARN_ON_ONCE(idx == INVALID_INDEX);
2082c50d8ae3SPaolo Bonzini 		clear_unsync_child_bit(sp, idx);
2083c50d8ae3SPaolo Bonzini 		level++;
2084c50d8ae3SPaolo Bonzini 	} while (!sp->unsync_children);
2085c50d8ae3SPaolo Bonzini }
2086c50d8ae3SPaolo Bonzini 
208765855ed8SLai Jiangshan static int mmu_sync_children(struct kvm_vcpu *vcpu,
208865855ed8SLai Jiangshan 			     struct kvm_mmu_page *parent, bool can_yield)
2089c50d8ae3SPaolo Bonzini {
2090c50d8ae3SPaolo Bonzini 	int i;
2091c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2092c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2093c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2094c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2095c50d8ae3SPaolo Bonzini 	bool flush = false;
2096c50d8ae3SPaolo Bonzini 
2097c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2098c50d8ae3SPaolo Bonzini 		bool protected = false;
2099c50d8ae3SPaolo Bonzini 
2100c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i)
2101cf48f9e2SDavid Matlack 			protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2102c50d8ae3SPaolo Bonzini 
2103c50d8ae3SPaolo Bonzini 		if (protected) {
21045591c069SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2105c50d8ae3SPaolo Bonzini 			flush = false;
2106c50d8ae3SPaolo Bonzini 		}
2107c50d8ae3SPaolo Bonzini 
2108c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2109479a1efcSSean Christopherson 			kvm_unlink_unsync_page(vcpu->kvm, sp);
21108d5678a7SHou Wenlong 			flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2111c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2112c50d8ae3SPaolo Bonzini 		}
2113531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2114c3e5e415SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
211565855ed8SLai Jiangshan 			if (!can_yield) {
211665855ed8SLai Jiangshan 				kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
211765855ed8SLai Jiangshan 				return -EINTR;
211865855ed8SLai Jiangshan 			}
211965855ed8SLai Jiangshan 
2120531810caSBen Gardon 			cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2121c50d8ae3SPaolo Bonzini 			flush = false;
2122c50d8ae3SPaolo Bonzini 		}
2123c50d8ae3SPaolo Bonzini 	}
2124c50d8ae3SPaolo Bonzini 
2125c3e5e415SLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
212665855ed8SLai Jiangshan 	return 0;
2127c50d8ae3SPaolo Bonzini }
2128c50d8ae3SPaolo Bonzini 
2129c50d8ae3SPaolo Bonzini static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2130c50d8ae3SPaolo Bonzini {
2131c50d8ae3SPaolo Bonzini 	atomic_set(&sp->write_flooding_count,  0);
2132c50d8ae3SPaolo Bonzini }
2133c50d8ae3SPaolo Bonzini 
2134c50d8ae3SPaolo Bonzini static void clear_sp_write_flooding_count(u64 *spte)
2135c50d8ae3SPaolo Bonzini {
213657354682SSean Christopherson 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
2137c50d8ae3SPaolo Bonzini }
2138c50d8ae3SPaolo Bonzini 
2139cbd858b1SDavid Matlack /*
2140cbd858b1SDavid Matlack  * The vCPU is required when finding indirect shadow pages; the shadow
2141cbd858b1SDavid Matlack  * page may already exist and syncing it needs the vCPU pointer in
2142cbd858b1SDavid Matlack  * order to read guest page tables.  Direct shadow pages are never
2143cbd858b1SDavid Matlack  * unsync, thus @vcpu can be NULL if @role.direct is true.
2144cbd858b1SDavid Matlack  */
21453cc736b3SDavid Matlack static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
21463cc736b3SDavid Matlack 						     struct kvm_vcpu *vcpu,
214794c81364SDavid Matlack 						     gfn_t gfn,
214894c81364SDavid Matlack 						     struct hlist_head *sp_list,
21492e65e842SDavid Matlack 						     union kvm_mmu_page_role role)
2150c50d8ae3SPaolo Bonzini {
2151c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
21528d5678a7SHou Wenlong 	int ret;
2153c50d8ae3SPaolo Bonzini 	int collisions = 0;
2154c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2155c50d8ae3SPaolo Bonzini 
21563cc736b3SDavid Matlack 	for_each_valid_sp(kvm, sp, sp_list) {
2157c50d8ae3SPaolo Bonzini 		if (sp->gfn != gfn) {
2158c50d8ae3SPaolo Bonzini 			collisions++;
2159c50d8ae3SPaolo Bonzini 			continue;
2160c50d8ae3SPaolo Bonzini 		}
2161c50d8ae3SPaolo Bonzini 
2162ddc16abbSSean Christopherson 		if (sp->role.word != role.word) {
2163ddc16abbSSean Christopherson 			/*
2164ddc16abbSSean Christopherson 			 * If the guest is creating an upper-level page, zap
2165ddc16abbSSean Christopherson 			 * unsync pages for the same gfn.  While it's possible
2166ddc16abbSSean Christopherson 			 * the guest is using recursive page tables, in all
2167ddc16abbSSean Christopherson 			 * likelihood the guest has stopped using the unsync
2168ddc16abbSSean Christopherson 			 * page and is installing a completely unrelated page.
2169ddc16abbSSean Christopherson 			 * Unsync pages must not be left as is, because the new
2170ddc16abbSSean Christopherson 			 * upper-level page will be write-protected.
2171ddc16abbSSean Christopherson 			 */
21722e65e842SDavid Matlack 			if (role.level > PG_LEVEL_4K && sp->unsync)
21733cc736b3SDavid Matlack 				kvm_mmu_prepare_zap_page(kvm, sp,
2174ddc16abbSSean Christopherson 							 &invalid_list);
2175c50d8ae3SPaolo Bonzini 			continue;
2176ddc16abbSSean Christopherson 		}
2177c50d8ae3SPaolo Bonzini 
2178bb924ca6SDavid Matlack 		/* unsync and write-flooding only apply to indirect SPs. */
2179bb924ca6SDavid Matlack 		if (sp->role.direct)
218094c81364SDavid Matlack 			goto out;
2181fb58a9c3SSean Christopherson 
2182c50d8ae3SPaolo Bonzini 		if (sp->unsync) {
2183cbd858b1SDavid Matlack 			if (KVM_BUG_ON(!vcpu, kvm))
2184cbd858b1SDavid Matlack 				break;
2185cbd858b1SDavid Matlack 
218607dc4f35SSean Christopherson 			/*
2187479a1efcSSean Christopherson 			 * The page is good, but is stale.  kvm_sync_page does
218807dc4f35SSean Christopherson 			 * get the latest guest state, but (unlike mmu_unsync_children)
218907dc4f35SSean Christopherson 			 * it doesn't write-protect the page or mark it synchronized!
219007dc4f35SSean Christopherson 			 * This way the validity of the mapping is ensured, but the
219107dc4f35SSean Christopherson 			 * overhead of write protection is not incurred until the
219207dc4f35SSean Christopherson 			 * guest invalidates the TLB mapping.  This allows multiple
219307dc4f35SSean Christopherson 			 * SPs for a single gfn to be unsync.
219407dc4f35SSean Christopherson 			 *
219507dc4f35SSean Christopherson 			 * If the sync fails, the page is zapped.  If so, break
219607dc4f35SSean Christopherson 			 * in order to rebuild it.
2197c50d8ae3SPaolo Bonzini 			 */
21988d5678a7SHou Wenlong 			ret = kvm_sync_page(vcpu, sp, &invalid_list);
21998d5678a7SHou Wenlong 			if (ret < 0)
2200c50d8ae3SPaolo Bonzini 				break;
2201c50d8ae3SPaolo Bonzini 
220220ba462dSSean Christopherson 			WARN_ON_ONCE(!list_empty(&invalid_list));
22038d5678a7SHou Wenlong 			if (ret > 0)
22043cc736b3SDavid Matlack 				kvm_flush_remote_tlbs(kvm);
2205c50d8ae3SPaolo Bonzini 		}
2206c50d8ae3SPaolo Bonzini 
2207c50d8ae3SPaolo Bonzini 		__clear_sp_write_flooding_count(sp);
2208fb58a9c3SSean Christopherson 
2209c50d8ae3SPaolo Bonzini 		goto out;
2210c50d8ae3SPaolo Bonzini 	}
2211c50d8ae3SPaolo Bonzini 
221294c81364SDavid Matlack 	sp = NULL;
22133cc736b3SDavid Matlack 	++kvm->stat.mmu_cache_miss;
2214c50d8ae3SPaolo Bonzini 
221594c81364SDavid Matlack out:
22163cc736b3SDavid Matlack 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
221794c81364SDavid Matlack 
22183cc736b3SDavid Matlack 	if (collisions > kvm->stat.max_mmu_page_hash_collisions)
22193cc736b3SDavid Matlack 		kvm->stat.max_mmu_page_hash_collisions = collisions;
222094c81364SDavid Matlack 	return sp;
222194c81364SDavid Matlack }
222294c81364SDavid Matlack 
22232f8b1b53SDavid Matlack /* Caches used when allocating a new shadow page. */
22242f8b1b53SDavid Matlack struct shadow_page_caches {
22252f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *page_header_cache;
22262f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *shadow_page_cache;
22276a97575dSDavid Matlack 	struct kvm_mmu_memory_cache *shadowed_info_cache;
22282f8b1b53SDavid Matlack };
22292f8b1b53SDavid Matlack 
2230336081fbSDavid Matlack static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
22312f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
223294c81364SDavid Matlack 						      gfn_t gfn,
223394c81364SDavid Matlack 						      struct hlist_head *sp_list,
223494c81364SDavid Matlack 						      union kvm_mmu_page_role role)
223594c81364SDavid Matlack {
2236c306aec8SDavid Matlack 	struct kvm_mmu_page *sp;
2237c306aec8SDavid Matlack 
22382f8b1b53SDavid Matlack 	sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
22392f8b1b53SDavid Matlack 	sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
2240c306aec8SDavid Matlack 	if (!role.direct)
22416a97575dSDavid Matlack 		sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2242c306aec8SDavid Matlack 
2243c306aec8SDavid Matlack 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2244c306aec8SDavid Matlack 
224555c510e2SSean Christopherson 	INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2246428e9216SSean Christopherson 
2247c306aec8SDavid Matlack 	/*
2248c306aec8SDavid Matlack 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2249c306aec8SDavid Matlack 	 * depends on valid pages being added to the head of the list.  See
2250c306aec8SDavid Matlack 	 * comments in kvm_zap_obsolete_pages().
2251c306aec8SDavid Matlack 	 */
2252336081fbSDavid Matlack 	sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2253336081fbSDavid Matlack 	list_add(&sp->link, &kvm->arch.active_mmu_pages);
225443a063caSYosry Ahmed 	kvm_account_mmu_page(kvm, sp);
2255c50d8ae3SPaolo Bonzini 
2256c50d8ae3SPaolo Bonzini 	sp->gfn = gfn;
2257c50d8ae3SPaolo Bonzini 	sp->role = role;
2258ac101b7cSSean Christopherson 	hlist_add_head(&sp->hash_link, sp_list);
2259be911771SDavid Matlack 	if (sp_has_gptes(sp))
2260336081fbSDavid Matlack 		account_shadowed(kvm, sp);
2261ddc16abbSSean Christopherson 
226294c81364SDavid Matlack 	return sp;
226394c81364SDavid Matlack }
226494c81364SDavid Matlack 
2265cbd858b1SDavid Matlack /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
22663cc736b3SDavid Matlack static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
22673cc736b3SDavid Matlack 						      struct kvm_vcpu *vcpu,
22682f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
226987654643SDavid Matlack 						      gfn_t gfn,
227094c81364SDavid Matlack 						      union kvm_mmu_page_role role)
227194c81364SDavid Matlack {
227294c81364SDavid Matlack 	struct hlist_head *sp_list;
227394c81364SDavid Matlack 	struct kvm_mmu_page *sp;
227494c81364SDavid Matlack 	bool created = false;
227594c81364SDavid Matlack 
22763cc736b3SDavid Matlack 	sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
227794c81364SDavid Matlack 
22783cc736b3SDavid Matlack 	sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
227994c81364SDavid Matlack 	if (!sp) {
228094c81364SDavid Matlack 		created = true;
22813cc736b3SDavid Matlack 		sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
228294c81364SDavid Matlack 	}
228394c81364SDavid Matlack 
228494c81364SDavid Matlack 	trace_kvm_mmu_get_page(sp, created);
2285c50d8ae3SPaolo Bonzini 	return sp;
2286c50d8ae3SPaolo Bonzini }
2287c50d8ae3SPaolo Bonzini 
22882f8b1b53SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
22892f8b1b53SDavid Matlack 						    gfn_t gfn,
22902f8b1b53SDavid Matlack 						    union kvm_mmu_page_role role)
22912f8b1b53SDavid Matlack {
22922f8b1b53SDavid Matlack 	struct shadow_page_caches caches = {
22932f8b1b53SDavid Matlack 		.page_header_cache = &vcpu->arch.mmu_page_header_cache,
22942f8b1b53SDavid Matlack 		.shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
22956a97575dSDavid Matlack 		.shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
22962f8b1b53SDavid Matlack 	};
22972f8b1b53SDavid Matlack 
22983cc736b3SDavid Matlack 	return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
22992f8b1b53SDavid Matlack }
23002f8b1b53SDavid Matlack 
230139944ab9SSean Christopherson static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
230239944ab9SSean Christopherson 						  unsigned int access)
23032e65e842SDavid Matlack {
23042e65e842SDavid Matlack 	struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
23052e65e842SDavid Matlack 	union kvm_mmu_page_role role;
23062e65e842SDavid Matlack 
23072e65e842SDavid Matlack 	role = parent_sp->role;
23082e65e842SDavid Matlack 	role.level--;
23092e65e842SDavid Matlack 	role.access = access;
23102e65e842SDavid Matlack 	role.direct = direct;
23112e65e842SDavid Matlack 	role.passthrough = 0;
23122e65e842SDavid Matlack 
23132e65e842SDavid Matlack 	/*
23142e65e842SDavid Matlack 	 * If the guest has 4-byte PTEs then that means it's using 32-bit,
23152e65e842SDavid Matlack 	 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
23162e65e842SDavid Matlack 	 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
23172e65e842SDavid Matlack 	 * shadow each guest page table with multiple shadow page tables, which
23182e65e842SDavid Matlack 	 * requires extra bookkeeping in the role.
23192e65e842SDavid Matlack 	 *
23202e65e842SDavid Matlack 	 * Specifically, to shadow the guest's page directory (which covers a
23212e65e842SDavid Matlack 	 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
23222e65e842SDavid Matlack 	 * 1GiB of the address space. @role.quadrant encodes which quarter of
23232e65e842SDavid Matlack 	 * the address space each maps.
23242e65e842SDavid Matlack 	 *
23252e65e842SDavid Matlack 	 * To shadow the guest's page tables (which each map a 4MiB region), KVM
23262e65e842SDavid Matlack 	 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
23272e65e842SDavid Matlack 	 * @role.quadrant encodes which half of the region they map.
23282e65e842SDavid Matlack 	 *
232939944ab9SSean Christopherson 	 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
233039944ab9SSean Christopherson 	 * consumes bits 29:21.  To consume bits 31:30, KVM's uses 4 shadow
233139944ab9SSean Christopherson 	 * PDPTEs; those 4 PAE page directories are pre-allocated and their
233239944ab9SSean Christopherson 	 * quadrant is assigned in mmu_alloc_root().   A 4-byte PTE consumes
233339944ab9SSean Christopherson 	 * bits 21:12, while an 8-byte PTE consumes bits 20:12.  To consume
233439944ab9SSean Christopherson 	 * bit 21 in the PTE (the child here), KVM propagates that bit to the
233539944ab9SSean Christopherson 	 * quadrant, i.e. sets quadrant to '0' or '1'.  The parent 8-byte PDE
233639944ab9SSean Christopherson 	 * covers bit 21 (see above), thus the quadrant is calculated from the
233739944ab9SSean Christopherson 	 * _least_ significant bit of the PDE index.
23382e65e842SDavid Matlack 	 */
23392e65e842SDavid Matlack 	if (role.has_4_byte_gpte) {
23402e65e842SDavid Matlack 		WARN_ON_ONCE(role.level != PG_LEVEL_4K);
234179e48cecSSean Christopherson 		role.quadrant = spte_index(sptep) & 1;
23422e65e842SDavid Matlack 	}
23432e65e842SDavid Matlack 
23442e65e842SDavid Matlack 	return role;
23452e65e842SDavid Matlack }
23462e65e842SDavid Matlack 
23472e65e842SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
23482e65e842SDavid Matlack 						 u64 *sptep, gfn_t gfn,
23492e65e842SDavid Matlack 						 bool direct, unsigned int access)
23502e65e842SDavid Matlack {
23512e65e842SDavid Matlack 	union kvm_mmu_page_role role;
23522e65e842SDavid Matlack 
23530cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
23540cd8dc73SPaolo Bonzini 		return ERR_PTR(-EEXIST);
23550cd8dc73SPaolo Bonzini 
23562e65e842SDavid Matlack 	role = kvm_mmu_child_role(sptep, direct, access);
235787654643SDavid Matlack 	return kvm_mmu_get_shadow_page(vcpu, gfn, role);
23582e65e842SDavid Matlack }
23592e65e842SDavid Matlack 
2360c50d8ae3SPaolo Bonzini static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2361c50d8ae3SPaolo Bonzini 					struct kvm_vcpu *vcpu, hpa_t root,
2362c50d8ae3SPaolo Bonzini 					u64 addr)
2363c50d8ae3SPaolo Bonzini {
2364c50d8ae3SPaolo Bonzini 	iterator->addr = addr;
2365c50d8ae3SPaolo Bonzini 	iterator->shadow_addr = root;
2366a972e29cSPaolo Bonzini 	iterator->level = vcpu->arch.mmu->root_role.level;
2367c50d8ae3SPaolo Bonzini 
236812ec33a7SLai Jiangshan 	if (iterator->level >= PT64_ROOT_4LEVEL &&
23694d25502aSPaolo Bonzini 	    vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2370347a0d0dSPaolo Bonzini 	    !vcpu->arch.mmu->root_role.direct)
237112ec33a7SLai Jiangshan 		iterator->level = PT32E_ROOT_LEVEL;
2372c50d8ae3SPaolo Bonzini 
2373c50d8ae3SPaolo Bonzini 	if (iterator->level == PT32E_ROOT_LEVEL) {
2374c50d8ae3SPaolo Bonzini 		/*
2375c50d8ae3SPaolo Bonzini 		 * prev_root is currently only used for 64-bit hosts. So only
2376c50d8ae3SPaolo Bonzini 		 * the active root_hpa is valid here.
2377c50d8ae3SPaolo Bonzini 		 */
2378b9e5603cSPaolo Bonzini 		BUG_ON(root != vcpu->arch.mmu->root.hpa);
2379c50d8ae3SPaolo Bonzini 
2380c50d8ae3SPaolo Bonzini 		iterator->shadow_addr
2381c50d8ae3SPaolo Bonzini 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
23822ca3129eSSean Christopherson 		iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2383c50d8ae3SPaolo Bonzini 		--iterator->level;
2384c50d8ae3SPaolo Bonzini 		if (!iterator->shadow_addr)
2385c50d8ae3SPaolo Bonzini 			iterator->level = 0;
2386c50d8ae3SPaolo Bonzini 	}
2387c50d8ae3SPaolo Bonzini }
2388c50d8ae3SPaolo Bonzini 
2389c50d8ae3SPaolo Bonzini static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2390c50d8ae3SPaolo Bonzini 			     struct kvm_vcpu *vcpu, u64 addr)
2391c50d8ae3SPaolo Bonzini {
2392b9e5603cSPaolo Bonzini 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2393c50d8ae3SPaolo Bonzini 				    addr);
2394c50d8ae3SPaolo Bonzini }
2395c50d8ae3SPaolo Bonzini 
2396c50d8ae3SPaolo Bonzini static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2397c50d8ae3SPaolo Bonzini {
23983bae0459SSean Christopherson 	if (iterator->level < PG_LEVEL_4K)
2399c50d8ae3SPaolo Bonzini 		return false;
2400c50d8ae3SPaolo Bonzini 
24012ca3129eSSean Christopherson 	iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2402c50d8ae3SPaolo Bonzini 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2403c50d8ae3SPaolo Bonzini 	return true;
2404c50d8ae3SPaolo Bonzini }
2405c50d8ae3SPaolo Bonzini 
2406c50d8ae3SPaolo Bonzini static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2407c50d8ae3SPaolo Bonzini 			       u64 spte)
2408c50d8ae3SPaolo Bonzini {
24093e44dce4SLai Jiangshan 	if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2410c50d8ae3SPaolo Bonzini 		iterator->level = 0;
2411c50d8ae3SPaolo Bonzini 		return;
2412c50d8ae3SPaolo Bonzini 	}
2413c50d8ae3SPaolo Bonzini 
24142ca3129eSSean Christopherson 	iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2415c50d8ae3SPaolo Bonzini 	--iterator->level;
2416c50d8ae3SPaolo Bonzini }
2417c50d8ae3SPaolo Bonzini 
2418c50d8ae3SPaolo Bonzini static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2419c50d8ae3SPaolo Bonzini {
2420c50d8ae3SPaolo Bonzini 	__shadow_walk_next(iterator, *iterator->sptep);
2421c50d8ae3SPaolo Bonzini }
2422c50d8ae3SPaolo Bonzini 
24230cd8dc73SPaolo Bonzini static void __link_shadow_page(struct kvm *kvm,
24240cd8dc73SPaolo Bonzini 			       struct kvm_mmu_memory_cache *cache, u64 *sptep,
242503787394SPaolo Bonzini 			       struct kvm_mmu_page *sp, bool flush)
2426c50d8ae3SPaolo Bonzini {
2427c50d8ae3SPaolo Bonzini 	u64 spte;
2428c50d8ae3SPaolo Bonzini 
2429c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2430c50d8ae3SPaolo Bonzini 
24310cd8dc73SPaolo Bonzini 	/*
24320cd8dc73SPaolo Bonzini 	 * If an SPTE is present already, it must be a leaf and therefore
243303787394SPaolo Bonzini 	 * a large one.  Drop it, and flush the TLB if needed, before
243403787394SPaolo Bonzini 	 * installing sp.
24350cd8dc73SPaolo Bonzini 	 */
24360cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep))
243703787394SPaolo Bonzini 		drop_large_spte(kvm, sptep, flush);
24380cd8dc73SPaolo Bonzini 
2439cc4674d0SBen Gardon 	spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2440c50d8ae3SPaolo Bonzini 
2441c50d8ae3SPaolo Bonzini 	mmu_spte_set(sptep, spte);
2442c50d8ae3SPaolo Bonzini 
24432ff9039aSDavid Matlack 	mmu_page_add_parent_pte(cache, sp, sptep);
2444c50d8ae3SPaolo Bonzini 
2445c4a48868SLai Jiangshan 	/*
2446c4a48868SLai Jiangshan 	 * The non-direct sub-pagetable must be updated before linking.  For
2447c4a48868SLai Jiangshan 	 * L1 sp, the pagetable is updated via kvm_sync_page() in
2448c4a48868SLai Jiangshan 	 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2449c4a48868SLai Jiangshan 	 * so sp->unsync can be true or false.  For higher level non-direct
2450c4a48868SLai Jiangshan 	 * sp, the pagetable is updated/synced via mmu_sync_children() in
2451c4a48868SLai Jiangshan 	 * FNAME(fetch)(), so sp->unsync_children can only be false.
2452c4a48868SLai Jiangshan 	 * WARN_ON_ONCE() if anything happens unexpectedly.
2453c4a48868SLai Jiangshan 	 */
2454c4a48868SLai Jiangshan 	if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2455c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
2456c50d8ae3SPaolo Bonzini }
2457c50d8ae3SPaolo Bonzini 
24582ff9039aSDavid Matlack static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
24592ff9039aSDavid Matlack 			     struct kvm_mmu_page *sp)
24602ff9039aSDavid Matlack {
246103787394SPaolo Bonzini 	__link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
24622ff9039aSDavid Matlack }
24632ff9039aSDavid Matlack 
2464c50d8ae3SPaolo Bonzini static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2465c50d8ae3SPaolo Bonzini 				   unsigned direct_access)
2466c50d8ae3SPaolo Bonzini {
2467c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2468c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
2469c50d8ae3SPaolo Bonzini 
2470c50d8ae3SPaolo Bonzini 		/*
2471c50d8ae3SPaolo Bonzini 		 * For the direct sp, if the guest pte's dirty bit
2472c50d8ae3SPaolo Bonzini 		 * changed form clean to dirty, it will corrupt the
2473c50d8ae3SPaolo Bonzini 		 * sp's access: allow writable in the read-only sp,
2474c50d8ae3SPaolo Bonzini 		 * so we should update the spte at this point to get
2475c50d8ae3SPaolo Bonzini 		 * a new sp with the correct access.
2476c50d8ae3SPaolo Bonzini 		 */
24775e3edd7eSSean Christopherson 		child = spte_to_child_sp(*sptep);
2478c50d8ae3SPaolo Bonzini 		if (child->role.access == direct_access)
2479c50d8ae3SPaolo Bonzini 			return;
2480c50d8ae3SPaolo Bonzini 
2481069f30c6SMingwei Zhang 		drop_parent_pte(vcpu->kvm, child, sptep);
24823cdf9374SHou Wenlong 		kvm_flush_remote_tlbs_sptep(vcpu->kvm, sptep);
2483c50d8ae3SPaolo Bonzini 	}
2484c50d8ae3SPaolo Bonzini }
2485c50d8ae3SPaolo Bonzini 
24862de4085cSBen Gardon /* Returns the number of zapped non-leaf child shadow pages. */
24872de4085cSBen Gardon static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
24882de4085cSBen Gardon 			    u64 *spte, struct list_head *invalid_list)
2489c50d8ae3SPaolo Bonzini {
2490c50d8ae3SPaolo Bonzini 	u64 pte;
2491c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *child;
2492c50d8ae3SPaolo Bonzini 
2493c50d8ae3SPaolo Bonzini 	pte = *spte;
2494c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(pte)) {
2495c50d8ae3SPaolo Bonzini 		if (is_last_spte(pte, sp->role.level)) {
2496c50d8ae3SPaolo Bonzini 			drop_spte(kvm, spte);
2497c50d8ae3SPaolo Bonzini 		} else {
24985e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2499069f30c6SMingwei Zhang 			drop_parent_pte(kvm, child, spte);
25002de4085cSBen Gardon 
25012de4085cSBen Gardon 			/*
25022de4085cSBen Gardon 			 * Recursively zap nested TDP SPs, parentless SPs are
25032de4085cSBen Gardon 			 * unlikely to be used again in the near future.  This
25042de4085cSBen Gardon 			 * avoids retaining a large number of stale nested SPs.
25052de4085cSBen Gardon 			 */
25062de4085cSBen Gardon 			if (tdp_enabled && invalid_list &&
25072de4085cSBen Gardon 			    child->role.guest_mode && !child->parent_ptes.val)
25082de4085cSBen Gardon 				return kvm_mmu_prepare_zap_page(kvm, child,
25092de4085cSBen Gardon 								invalid_list);
2510c50d8ae3SPaolo Bonzini 		}
2511ace569e0SSean Christopherson 	} else if (is_mmio_spte(pte)) {
2512c50d8ae3SPaolo Bonzini 		mmu_spte_clear_no_track(spte);
2513ace569e0SSean Christopherson 	}
25142de4085cSBen Gardon 	return 0;
2515c50d8ae3SPaolo Bonzini }
2516c50d8ae3SPaolo Bonzini 
25172de4085cSBen Gardon static int kvm_mmu_page_unlink_children(struct kvm *kvm,
25182de4085cSBen Gardon 					struct kvm_mmu_page *sp,
25192de4085cSBen Gardon 					struct list_head *invalid_list)
2520c50d8ae3SPaolo Bonzini {
25212de4085cSBen Gardon 	int zapped = 0;
2522c50d8ae3SPaolo Bonzini 	unsigned i;
2523c50d8ae3SPaolo Bonzini 
25242ca3129eSSean Christopherson 	for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
25252de4085cSBen Gardon 		zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
25262de4085cSBen Gardon 
25272de4085cSBen Gardon 	return zapped;
2528c50d8ae3SPaolo Bonzini }
2529c50d8ae3SPaolo Bonzini 
2530069f30c6SMingwei Zhang static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2531c50d8ae3SPaolo Bonzini {
2532c50d8ae3SPaolo Bonzini 	u64 *sptep;
2533c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
2534c50d8ae3SPaolo Bonzini 
2535c50d8ae3SPaolo Bonzini 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2536069f30c6SMingwei Zhang 		drop_parent_pte(kvm, sp, sptep);
2537c50d8ae3SPaolo Bonzini }
2538c50d8ae3SPaolo Bonzini 
2539c50d8ae3SPaolo Bonzini static int mmu_zap_unsync_children(struct kvm *kvm,
2540c50d8ae3SPaolo Bonzini 				   struct kvm_mmu_page *parent,
2541c50d8ae3SPaolo Bonzini 				   struct list_head *invalid_list)
2542c50d8ae3SPaolo Bonzini {
2543c50d8ae3SPaolo Bonzini 	int i, zapped = 0;
2544c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2545c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2546c50d8ae3SPaolo Bonzini 
25473bae0459SSean Christopherson 	if (parent->role.level == PG_LEVEL_4K)
2548c50d8ae3SPaolo Bonzini 		return 0;
2549c50d8ae3SPaolo Bonzini 
2550c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2551c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
2552c50d8ae3SPaolo Bonzini 
2553c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2554c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2555c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2556c50d8ae3SPaolo Bonzini 			zapped++;
2557c50d8ae3SPaolo Bonzini 		}
2558c50d8ae3SPaolo Bonzini 	}
2559c50d8ae3SPaolo Bonzini 
2560c50d8ae3SPaolo Bonzini 	return zapped;
2561c50d8ae3SPaolo Bonzini }
2562c50d8ae3SPaolo Bonzini 
2563c50d8ae3SPaolo Bonzini static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2564c50d8ae3SPaolo Bonzini 				       struct kvm_mmu_page *sp,
2565c50d8ae3SPaolo Bonzini 				       struct list_head *invalid_list,
2566c50d8ae3SPaolo Bonzini 				       int *nr_zapped)
2567c50d8ae3SPaolo Bonzini {
2568527d5cd7SSean Christopherson 	bool list_unstable, zapped_root = false;
2569c50d8ae3SPaolo Bonzini 
257047b0c2e4SKazuki Takiguchi 	lockdep_assert_held_write(&kvm->mmu_lock);
2571c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_prepare_zap_page(sp);
2572c50d8ae3SPaolo Bonzini 	++kvm->stat.mmu_shadow_zapped;
2573c50d8ae3SPaolo Bonzini 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
25742de4085cSBen Gardon 	*nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2575069f30c6SMingwei Zhang 	kvm_mmu_unlink_parents(kvm, sp);
2576c50d8ae3SPaolo Bonzini 
2577c50d8ae3SPaolo Bonzini 	/* Zapping children means active_mmu_pages has become unstable. */
2578c50d8ae3SPaolo Bonzini 	list_unstable = *nr_zapped;
2579c50d8ae3SPaolo Bonzini 
2580767d8d8dSLai Jiangshan 	if (!sp->role.invalid && sp_has_gptes(sp))
2581c50d8ae3SPaolo Bonzini 		unaccount_shadowed(kvm, sp);
2582c50d8ae3SPaolo Bonzini 
2583c50d8ae3SPaolo Bonzini 	if (sp->unsync)
2584c50d8ae3SPaolo Bonzini 		kvm_unlink_unsync_page(kvm, sp);
2585c50d8ae3SPaolo Bonzini 	if (!sp->root_count) {
2586c50d8ae3SPaolo Bonzini 		/* Count self */
2587c50d8ae3SPaolo Bonzini 		(*nr_zapped)++;
2588f95eec9bSSean Christopherson 
2589f95eec9bSSean Christopherson 		/*
2590f95eec9bSSean Christopherson 		 * Already invalid pages (previously active roots) are not on
2591f95eec9bSSean Christopherson 		 * the active page list.  See list_del() in the "else" case of
2592f95eec9bSSean Christopherson 		 * !sp->root_count.
2593f95eec9bSSean Christopherson 		 */
2594f95eec9bSSean Christopherson 		if (sp->role.invalid)
2595f95eec9bSSean Christopherson 			list_add(&sp->link, invalid_list);
2596f95eec9bSSean Christopherson 		else
2597c50d8ae3SPaolo Bonzini 			list_move(&sp->link, invalid_list);
259843a063caSYosry Ahmed 		kvm_unaccount_mmu_page(kvm, sp);
2599c50d8ae3SPaolo Bonzini 	} else {
2600f95eec9bSSean Christopherson 		/*
2601f95eec9bSSean Christopherson 		 * Remove the active root from the active page list, the root
2602f95eec9bSSean Christopherson 		 * will be explicitly freed when the root_count hits zero.
2603f95eec9bSSean Christopherson 		 */
2604f95eec9bSSean Christopherson 		list_del(&sp->link);
2605c50d8ae3SPaolo Bonzini 
2606c50d8ae3SPaolo Bonzini 		/*
2607c50d8ae3SPaolo Bonzini 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2608c50d8ae3SPaolo Bonzini 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2609c50d8ae3SPaolo Bonzini 		 * treats invalid shadow pages as being obsolete.
2610c50d8ae3SPaolo Bonzini 		 */
2611527d5cd7SSean Christopherson 		zapped_root = !is_obsolete_sp(kvm, sp);
2612c50d8ae3SPaolo Bonzini 	}
2613c50d8ae3SPaolo Bonzini 
261455c510e2SSean Christopherson 	if (sp->nx_huge_page_disallowed)
261555c510e2SSean Christopherson 		unaccount_nx_huge_page(kvm, sp);
2616c50d8ae3SPaolo Bonzini 
2617c50d8ae3SPaolo Bonzini 	sp->role.invalid = 1;
2618527d5cd7SSean Christopherson 
2619527d5cd7SSean Christopherson 	/*
2620527d5cd7SSean Christopherson 	 * Make the request to free obsolete roots after marking the root
2621527d5cd7SSean Christopherson 	 * invalid, otherwise other vCPUs may not see it as invalid.
2622527d5cd7SSean Christopherson 	 */
2623527d5cd7SSean Christopherson 	if (zapped_root)
2624527d5cd7SSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2625c50d8ae3SPaolo Bonzini 	return list_unstable;
2626c50d8ae3SPaolo Bonzini }
2627c50d8ae3SPaolo Bonzini 
2628c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2629c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list)
2630c50d8ae3SPaolo Bonzini {
2631c50d8ae3SPaolo Bonzini 	int nr_zapped;
2632c50d8ae3SPaolo Bonzini 
2633c50d8ae3SPaolo Bonzini 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2634c50d8ae3SPaolo Bonzini 	return nr_zapped;
2635c50d8ae3SPaolo Bonzini }
2636c50d8ae3SPaolo Bonzini 
2637c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2638c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list)
2639c50d8ae3SPaolo Bonzini {
2640c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *nsp;
2641c50d8ae3SPaolo Bonzini 
2642c50d8ae3SPaolo Bonzini 	if (list_empty(invalid_list))
2643c50d8ae3SPaolo Bonzini 		return;
2644c50d8ae3SPaolo Bonzini 
2645c50d8ae3SPaolo Bonzini 	/*
2646c50d8ae3SPaolo Bonzini 	 * We need to make sure everyone sees our modifications to
2647c50d8ae3SPaolo Bonzini 	 * the page tables and see changes to vcpu->mode here. The barrier
2648c50d8ae3SPaolo Bonzini 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2649c50d8ae3SPaolo Bonzini 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2650c50d8ae3SPaolo Bonzini 	 *
2651c50d8ae3SPaolo Bonzini 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2652c50d8ae3SPaolo Bonzini 	 * guest mode and/or lockless shadow page table walks.
2653c50d8ae3SPaolo Bonzini 	 */
2654c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs(kvm);
2655c50d8ae3SPaolo Bonzini 
2656c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
265720ba462dSSean Christopherson 		WARN_ON_ONCE(!sp->role.invalid || sp->root_count);
265887654643SDavid Matlack 		kvm_mmu_free_shadow_page(sp);
2659c50d8ae3SPaolo Bonzini 	}
2660c50d8ae3SPaolo Bonzini }
2661c50d8ae3SPaolo Bonzini 
26626b82ef2cSSean Christopherson static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
26636b82ef2cSSean Christopherson 						  unsigned long nr_to_zap)
2664c50d8ae3SPaolo Bonzini {
26656b82ef2cSSean Christopherson 	unsigned long total_zapped = 0;
26666b82ef2cSSean Christopherson 	struct kvm_mmu_page *sp, *tmp;
2667ba7888ddSSean Christopherson 	LIST_HEAD(invalid_list);
26686b82ef2cSSean Christopherson 	bool unstable;
26696b82ef2cSSean Christopherson 	int nr_zapped;
2670c50d8ae3SPaolo Bonzini 
2671c50d8ae3SPaolo Bonzini 	if (list_empty(&kvm->arch.active_mmu_pages))
2672ba7888ddSSean Christopherson 		return 0;
2673c50d8ae3SPaolo Bonzini 
26746b82ef2cSSean Christopherson restart:
26758fc51726SSean Christopherson 	list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
26766b82ef2cSSean Christopherson 		/*
26776b82ef2cSSean Christopherson 		 * Don't zap active root pages, the page itself can't be freed
26786b82ef2cSSean Christopherson 		 * and zapping it will just force vCPUs to realloc and reload.
26796b82ef2cSSean Christopherson 		 */
26806b82ef2cSSean Christopherson 		if (sp->root_count)
26816b82ef2cSSean Christopherson 			continue;
26826b82ef2cSSean Christopherson 
26836b82ef2cSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
26846b82ef2cSSean Christopherson 						      &nr_zapped);
26856b82ef2cSSean Christopherson 		total_zapped += nr_zapped;
26866b82ef2cSSean Christopherson 		if (total_zapped >= nr_to_zap)
2687ba7888ddSSean Christopherson 			break;
2688ba7888ddSSean Christopherson 
26896b82ef2cSSean Christopherson 		if (unstable)
26906b82ef2cSSean Christopherson 			goto restart;
2691ba7888ddSSean Christopherson 	}
26926b82ef2cSSean Christopherson 
26936b82ef2cSSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
26946b82ef2cSSean Christopherson 
26956b82ef2cSSean Christopherson 	kvm->stat.mmu_recycled += total_zapped;
26966b82ef2cSSean Christopherson 	return total_zapped;
26976b82ef2cSSean Christopherson }
26986b82ef2cSSean Christopherson 
2699afe8d7e6SSean Christopherson static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2700afe8d7e6SSean Christopherson {
2701afe8d7e6SSean Christopherson 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2702afe8d7e6SSean Christopherson 		return kvm->arch.n_max_mmu_pages -
2703afe8d7e6SSean Christopherson 			kvm->arch.n_used_mmu_pages;
2704afe8d7e6SSean Christopherson 
2705afe8d7e6SSean Christopherson 	return 0;
2706c50d8ae3SPaolo Bonzini }
2707c50d8ae3SPaolo Bonzini 
2708ba7888ddSSean Christopherson static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2709ba7888ddSSean Christopherson {
27106b82ef2cSSean Christopherson 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2711ba7888ddSSean Christopherson 
27126b82ef2cSSean Christopherson 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2713ba7888ddSSean Christopherson 		return 0;
2714ba7888ddSSean Christopherson 
27156b82ef2cSSean Christopherson 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2716ba7888ddSSean Christopherson 
27176e6ec584SSean Christopherson 	/*
27186e6ec584SSean Christopherson 	 * Note, this check is intentionally soft, it only guarantees that one
27196e6ec584SSean Christopherson 	 * page is available, while the caller may end up allocating as many as
27206e6ec584SSean Christopherson 	 * four pages, e.g. for PAE roots or for 5-level paging.  Temporarily
27216e6ec584SSean Christopherson 	 * exceeding the (arbitrary by default) limit will not harm the host,
2722c4342633SIngo Molnar 	 * being too aggressive may unnecessarily kill the guest, and getting an
27236e6ec584SSean Christopherson 	 * exact count is far more trouble than it's worth, especially in the
27246e6ec584SSean Christopherson 	 * page fault paths.
27256e6ec584SSean Christopherson 	 */
2726ba7888ddSSean Christopherson 	if (!kvm_mmu_available_pages(vcpu->kvm))
2727ba7888ddSSean Christopherson 		return -ENOSPC;
2728ba7888ddSSean Christopherson 	return 0;
2729ba7888ddSSean Christopherson }
2730ba7888ddSSean Christopherson 
2731c50d8ae3SPaolo Bonzini /*
2732c50d8ae3SPaolo Bonzini  * Changing the number of mmu pages allocated to the vm
2733c50d8ae3SPaolo Bonzini  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2734c50d8ae3SPaolo Bonzini  */
2735c50d8ae3SPaolo Bonzini void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2736c50d8ae3SPaolo Bonzini {
2737531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2738c50d8ae3SPaolo Bonzini 
2739c50d8ae3SPaolo Bonzini 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
27406b82ef2cSSean Christopherson 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
27416b82ef2cSSean Christopherson 						  goal_nr_mmu_pages);
2742c50d8ae3SPaolo Bonzini 
2743c50d8ae3SPaolo Bonzini 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2744c50d8ae3SPaolo Bonzini 	}
2745c50d8ae3SPaolo Bonzini 
2746c50d8ae3SPaolo Bonzini 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2747c50d8ae3SPaolo Bonzini 
2748531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2749c50d8ae3SPaolo Bonzini }
2750c50d8ae3SPaolo Bonzini 
2751c50d8ae3SPaolo Bonzini int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2752c50d8ae3SPaolo Bonzini {
2753c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2754c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2755c50d8ae3SPaolo Bonzini 	int r;
2756c50d8ae3SPaolo Bonzini 
2757c50d8ae3SPaolo Bonzini 	r = 0;
2758531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2759767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2760c50d8ae3SPaolo Bonzini 		r = 1;
2761c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2762c50d8ae3SPaolo Bonzini 	}
2763c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2764531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2765c50d8ae3SPaolo Bonzini 
2766c50d8ae3SPaolo Bonzini 	return r;
2767c50d8ae3SPaolo Bonzini }
276896ad91aeSSean Christopherson 
276996ad91aeSSean Christopherson static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
277096ad91aeSSean Christopherson {
277196ad91aeSSean Christopherson 	gpa_t gpa;
277296ad91aeSSean Christopherson 	int r;
277396ad91aeSSean Christopherson 
2774347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
277596ad91aeSSean Christopherson 		return 0;
277696ad91aeSSean Christopherson 
277796ad91aeSSean Christopherson 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
277896ad91aeSSean Christopherson 
277996ad91aeSSean Christopherson 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
278096ad91aeSSean Christopherson 
278196ad91aeSSean Christopherson 	return r;
278296ad91aeSSean Christopherson }
2783c50d8ae3SPaolo Bonzini 
27844d78d0b3SBen Gardon static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2785c50d8ae3SPaolo Bonzini {
2786c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_unsync_page(sp);
27874d78d0b3SBen Gardon 	++kvm->stat.mmu_unsync;
2788c50d8ae3SPaolo Bonzini 	sp->unsync = 1;
2789c50d8ae3SPaolo Bonzini 
2790c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
2791c50d8ae3SPaolo Bonzini }
2792c50d8ae3SPaolo Bonzini 
27930337f585SSean Christopherson /*
27940337f585SSean Christopherson  * Attempt to unsync any shadow pages that can be reached by the specified gfn,
27950337f585SSean Christopherson  * KVM is creating a writable mapping for said gfn.  Returns 0 if all pages
27960337f585SSean Christopherson  * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
27970337f585SSean Christopherson  * be write-protected.
27980337f585SSean Christopherson  */
27998283e36aSBen Gardon int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
28002839180cSPaolo Bonzini 			    gfn_t gfn, bool can_unsync, bool prefetch)
2801c50d8ae3SPaolo Bonzini {
2802c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2803ce25681dSSean Christopherson 	bool locked = false;
2804c50d8ae3SPaolo Bonzini 
28050337f585SSean Christopherson 	/*
28060337f585SSean Christopherson 	 * Force write-protection if the page is being tracked.  Note, the page
28070337f585SSean Christopherson 	 * track machinery is used to write-protect upper-level shadow pages,
28080337f585SSean Christopherson 	 * i.e. this guards the role.level == 4K assertion below!
28090337f585SSean Christopherson 	 */
28107b574863SSean Christopherson 	if (kvm_gfn_is_write_tracked(kvm, slot, gfn))
28110337f585SSean Christopherson 		return -EPERM;
2812c50d8ae3SPaolo Bonzini 
28130337f585SSean Christopherson 	/*
28140337f585SSean Christopherson 	 * The page is not write-tracked, mark existing shadow pages unsync
28150337f585SSean Christopherson 	 * unless KVM is synchronizing an unsync SP (can_unsync = false).  In
28160337f585SSean Christopherson 	 * that case, KVM must complete emulation of the guest TLB flush before
28170337f585SSean Christopherson 	 * allowing shadow pages to become unsync (writable by the guest).
28180337f585SSean Christopherson 	 */
2819767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2820c50d8ae3SPaolo Bonzini 		if (!can_unsync)
28210337f585SSean Christopherson 			return -EPERM;
2822c50d8ae3SPaolo Bonzini 
2823c50d8ae3SPaolo Bonzini 		if (sp->unsync)
2824c50d8ae3SPaolo Bonzini 			continue;
2825c50d8ae3SPaolo Bonzini 
28262839180cSPaolo Bonzini 		if (prefetch)
2827f1c4a88cSLai Jiangshan 			return -EEXIST;
2828f1c4a88cSLai Jiangshan 
2829ce25681dSSean Christopherson 		/*
2830ce25681dSSean Christopherson 		 * TDP MMU page faults require an additional spinlock as they
2831ce25681dSSean Christopherson 		 * run with mmu_lock held for read, not write, and the unsync
2832ce25681dSSean Christopherson 		 * logic is not thread safe.  Take the spinklock regardless of
2833ce25681dSSean Christopherson 		 * the MMU type to avoid extra conditionals/parameters, there's
2834ce25681dSSean Christopherson 		 * no meaningful penalty if mmu_lock is held for write.
2835ce25681dSSean Christopherson 		 */
2836ce25681dSSean Christopherson 		if (!locked) {
2837ce25681dSSean Christopherson 			locked = true;
28384d78d0b3SBen Gardon 			spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2839ce25681dSSean Christopherson 
2840ce25681dSSean Christopherson 			/*
2841ce25681dSSean Christopherson 			 * Recheck after taking the spinlock, a different vCPU
2842ce25681dSSean Christopherson 			 * may have since marked the page unsync.  A false
2843ce25681dSSean Christopherson 			 * positive on the unprotected check above is not
2844ce25681dSSean Christopherson 			 * possible as clearing sp->unsync _must_ hold mmu_lock
2845ce25681dSSean Christopherson 			 * for write, i.e. unsync cannot transition from 0->1
2846ce25681dSSean Christopherson 			 * while this CPU holds mmu_lock for read (or write).
2847ce25681dSSean Christopherson 			 */
2848ce25681dSSean Christopherson 			if (READ_ONCE(sp->unsync))
2849ce25681dSSean Christopherson 				continue;
2850ce25681dSSean Christopherson 		}
2851ce25681dSSean Christopherson 
285220ba462dSSean Christopherson 		WARN_ON_ONCE(sp->role.level != PG_LEVEL_4K);
28534d78d0b3SBen Gardon 		kvm_unsync_page(kvm, sp);
2854c50d8ae3SPaolo Bonzini 	}
2855ce25681dSSean Christopherson 	if (locked)
28564d78d0b3SBen Gardon 		spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2857c50d8ae3SPaolo Bonzini 
2858c50d8ae3SPaolo Bonzini 	/*
2859c50d8ae3SPaolo Bonzini 	 * We need to ensure that the marking of unsync pages is visible
2860c50d8ae3SPaolo Bonzini 	 * before the SPTE is updated to allow writes because
2861c50d8ae3SPaolo Bonzini 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2862c50d8ae3SPaolo Bonzini 	 * the MMU lock and so can race with this. If the SPTE was updated
2863c50d8ae3SPaolo Bonzini 	 * before the page had been marked as unsync-ed, something like the
2864c50d8ae3SPaolo Bonzini 	 * following could happen:
2865c50d8ae3SPaolo Bonzini 	 *
2866c50d8ae3SPaolo Bonzini 	 * CPU 1                    CPU 2
2867c50d8ae3SPaolo Bonzini 	 * ---------------------------------------------------------------------
2868c50d8ae3SPaolo Bonzini 	 * 1.2 Host updates SPTE
2869c50d8ae3SPaolo Bonzini 	 *     to be writable
2870c50d8ae3SPaolo Bonzini 	 *                      2.1 Guest writes a GPTE for GVA X.
2871c50d8ae3SPaolo Bonzini 	 *                          (GPTE being in the guest page table shadowed
2872c50d8ae3SPaolo Bonzini 	 *                           by the SP from CPU 1.)
2873c50d8ae3SPaolo Bonzini 	 *                          This reads SPTE during the page table walk.
2874c50d8ae3SPaolo Bonzini 	 *                          Since SPTE.W is read as 1, there is no
2875c50d8ae3SPaolo Bonzini 	 *                          fault.
2876c50d8ae3SPaolo Bonzini 	 *
2877c50d8ae3SPaolo Bonzini 	 *                      2.2 Guest issues TLB flush.
2878c50d8ae3SPaolo Bonzini 	 *                          That causes a VM Exit.
2879c50d8ae3SPaolo Bonzini 	 *
28800337f585SSean Christopherson 	 *                      2.3 Walking of unsync pages sees sp->unsync is
28810337f585SSean Christopherson 	 *                          false and skips the page.
2882c50d8ae3SPaolo Bonzini 	 *
2883c50d8ae3SPaolo Bonzini 	 *                      2.4 Guest accesses GVA X.
2884c50d8ae3SPaolo Bonzini 	 *                          Since the mapping in the SP was not updated,
2885c50d8ae3SPaolo Bonzini 	 *                          so the old mapping for GVA X incorrectly
2886c50d8ae3SPaolo Bonzini 	 *                          gets used.
2887c50d8ae3SPaolo Bonzini 	 * 1.1 Host marks SP
2888c50d8ae3SPaolo Bonzini 	 *     as unsync
2889c50d8ae3SPaolo Bonzini 	 *     (sp->unsync = true)
2890c50d8ae3SPaolo Bonzini 	 *
2891c50d8ae3SPaolo Bonzini 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2892264d3dc1SLai Jiangshan 	 * the situation in 2.4 does not arise.  It pairs with the read barrier
2893264d3dc1SLai Jiangshan 	 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2894c50d8ae3SPaolo Bonzini 	 */
2895c50d8ae3SPaolo Bonzini 	smp_wmb();
2896c50d8ae3SPaolo Bonzini 
28970337f585SSean Christopherson 	return 0;
2898c50d8ae3SPaolo Bonzini }
2899c50d8ae3SPaolo Bonzini 
29008a9f566aSDavid Matlack static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
29018a9f566aSDavid Matlack 			u64 *sptep, unsigned int pte_access, gfn_t gfn,
2902a12f4381SPaolo Bonzini 			kvm_pfn_t pfn, struct kvm_page_fault *fault)
2903799a4190SBen Gardon {
2904d786c778SPaolo Bonzini 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2905eb5cd7ffSPaolo Bonzini 	int level = sp->role.level;
2906c50d8ae3SPaolo Bonzini 	int was_rmapped = 0;
2907c4371c2aSSean Christopherson 	int ret = RET_PF_FIXED;
2908c50d8ae3SPaolo Bonzini 	bool flush = false;
2909ad67e480SPaolo Bonzini 	bool wrprot;
2910d786c778SPaolo Bonzini 	u64 spte;
2911c50d8ae3SPaolo Bonzini 
2912a12f4381SPaolo Bonzini 	/* Prefetching always gets a writable pfn.  */
2913a12f4381SPaolo Bonzini 	bool host_writable = !fault || fault->map_writable;
29142839180cSPaolo Bonzini 	bool prefetch = !fault || fault->prefetch;
2915a12f4381SPaolo Bonzini 	bool write_fault = fault && fault->write;
2916c50d8ae3SPaolo Bonzini 
2917a54aa15cSSean Christopherson 	if (unlikely(is_noslot_pfn(pfn))) {
29181075d41eSSean Christopherson 		vcpu->stat.pf_mmio_spte_created++;
2919a54aa15cSSean Christopherson 		mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2920a54aa15cSSean Christopherson 		return RET_PF_EMULATE;
2921a54aa15cSSean Christopherson 	}
2922a54aa15cSSean Christopherson 
2923c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep)) {
2924c50d8ae3SPaolo Bonzini 		/*
2925c50d8ae3SPaolo Bonzini 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2926c50d8ae3SPaolo Bonzini 		 * the parent of the now unreachable PTE.
2927c50d8ae3SPaolo Bonzini 		 */
29283bae0459SSean Christopherson 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2929c50d8ae3SPaolo Bonzini 			struct kvm_mmu_page *child;
2930c50d8ae3SPaolo Bonzini 			u64 pte = *sptep;
2931c50d8ae3SPaolo Bonzini 
29325e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2933069f30c6SMingwei Zhang 			drop_parent_pte(vcpu->kvm, child, sptep);
2934c50d8ae3SPaolo Bonzini 			flush = true;
2935c50d8ae3SPaolo Bonzini 		} else if (pfn != spte_to_pfn(*sptep)) {
2936c50d8ae3SPaolo Bonzini 			drop_spte(vcpu->kvm, sptep);
2937c50d8ae3SPaolo Bonzini 			flush = true;
2938c50d8ae3SPaolo Bonzini 		} else
2939c50d8ae3SPaolo Bonzini 			was_rmapped = 1;
2940c50d8ae3SPaolo Bonzini 	}
2941c50d8ae3SPaolo Bonzini 
29422839180cSPaolo Bonzini 	wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
29437158bee4SPaolo Bonzini 			   true, host_writable, &spte);
2944d786c778SPaolo Bonzini 
2945d786c778SPaolo Bonzini 	if (*sptep == spte) {
2946d786c778SPaolo Bonzini 		ret = RET_PF_SPURIOUS;
2947d786c778SPaolo Bonzini 	} else {
2948d786c778SPaolo Bonzini 		flush |= mmu_spte_update(sptep, spte);
29495959ff4aSMaxim Levitsky 		trace_kvm_mmu_set_spte(level, gfn, sptep);
2950c50d8ae3SPaolo Bonzini 	}
2951c50d8ae3SPaolo Bonzini 
2952ad67e480SPaolo Bonzini 	if (wrprot) {
2953c50d8ae3SPaolo Bonzini 		if (write_fault)
2954c50d8ae3SPaolo Bonzini 			ret = RET_PF_EMULATE;
2955c50d8ae3SPaolo Bonzini 	}
2956c50d8ae3SPaolo Bonzini 
2957d786c778SPaolo Bonzini 	if (flush)
29584ad980aeSHou Wenlong 		kvm_flush_remote_tlbs_gfn(vcpu->kvm, gfn, level);
2959c50d8ae3SPaolo Bonzini 
2960c50d8ae3SPaolo Bonzini 	if (!was_rmapped) {
2961d786c778SPaolo Bonzini 		WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
29626a97575dSDavid Matlack 		rmap_add(vcpu, slot, sptep, gfn, pte_access);
29636a97575dSDavid Matlack 	} else {
29646a97575dSDavid Matlack 		/* Already rmapped but the pte_access bits may have changed. */
296579e48cecSSean Christopherson 		kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
2966c50d8ae3SPaolo Bonzini 	}
2967c50d8ae3SPaolo Bonzini 
2968c50d8ae3SPaolo Bonzini 	return ret;
2969c50d8ae3SPaolo Bonzini }
2970c50d8ae3SPaolo Bonzini 
2971c50d8ae3SPaolo Bonzini static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2972c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp,
2973c50d8ae3SPaolo Bonzini 				    u64 *start, u64 *end)
2974c50d8ae3SPaolo Bonzini {
2975c50d8ae3SPaolo Bonzini 	struct page *pages[PTE_PREFETCH_NUM];
2976c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
29770a2b64c5SBen Gardon 	unsigned int access = sp->role.access;
2978c50d8ae3SPaolo Bonzini 	int i, ret;
2979c50d8ae3SPaolo Bonzini 	gfn_t gfn;
2980c50d8ae3SPaolo Bonzini 
298179e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
2982c50d8ae3SPaolo Bonzini 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2983c50d8ae3SPaolo Bonzini 	if (!slot)
2984c50d8ae3SPaolo Bonzini 		return -1;
2985c50d8ae3SPaolo Bonzini 
2986c50d8ae3SPaolo Bonzini 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2987c50d8ae3SPaolo Bonzini 	if (ret <= 0)
2988c50d8ae3SPaolo Bonzini 		return -1;
2989c50d8ae3SPaolo Bonzini 
2990c50d8ae3SPaolo Bonzini 	for (i = 0; i < ret; i++, gfn++, start++) {
29918a9f566aSDavid Matlack 		mmu_set_spte(vcpu, slot, start, access, gfn,
2992a12f4381SPaolo Bonzini 			     page_to_pfn(pages[i]), NULL);
2993c50d8ae3SPaolo Bonzini 		put_page(pages[i]);
2994c50d8ae3SPaolo Bonzini 	}
2995c50d8ae3SPaolo Bonzini 
2996c50d8ae3SPaolo Bonzini 	return 0;
2997c50d8ae3SPaolo Bonzini }
2998c50d8ae3SPaolo Bonzini 
2999c50d8ae3SPaolo Bonzini static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3000c50d8ae3SPaolo Bonzini 				  struct kvm_mmu_page *sp, u64 *sptep)
3001c50d8ae3SPaolo Bonzini {
3002c50d8ae3SPaolo Bonzini 	u64 *spte, *start = NULL;
3003c50d8ae3SPaolo Bonzini 	int i;
3004c50d8ae3SPaolo Bonzini 
300520ba462dSSean Christopherson 	WARN_ON_ONCE(!sp->role.direct);
3006c50d8ae3SPaolo Bonzini 
300779e48cecSSean Christopherson 	i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
3008c50d8ae3SPaolo Bonzini 	spte = sp->spt + i;
3009c50d8ae3SPaolo Bonzini 
3010c50d8ae3SPaolo Bonzini 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3011c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*spte) || spte == sptep) {
3012c50d8ae3SPaolo Bonzini 			if (!start)
3013c50d8ae3SPaolo Bonzini 				continue;
3014c50d8ae3SPaolo Bonzini 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3015c6cecc4bSSean Christopherson 				return;
3016c50d8ae3SPaolo Bonzini 			start = NULL;
3017c50d8ae3SPaolo Bonzini 		} else if (!start)
3018c50d8ae3SPaolo Bonzini 			start = spte;
3019c50d8ae3SPaolo Bonzini 	}
3020c6cecc4bSSean Christopherson 	if (start)
3021c6cecc4bSSean Christopherson 		direct_pte_prefetch_many(vcpu, sp, start, spte);
3022c50d8ae3SPaolo Bonzini }
3023c50d8ae3SPaolo Bonzini 
3024c50d8ae3SPaolo Bonzini static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3025c50d8ae3SPaolo Bonzini {
3026c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3027c50d8ae3SPaolo Bonzini 
302857354682SSean Christopherson 	sp = sptep_to_sp(sptep);
3029c50d8ae3SPaolo Bonzini 
3030c50d8ae3SPaolo Bonzini 	/*
3031c50d8ae3SPaolo Bonzini 	 * Without accessed bits, there's no way to distinguish between
3032c50d8ae3SPaolo Bonzini 	 * actually accessed translations and prefetched, so disable pte
3033c50d8ae3SPaolo Bonzini 	 * prefetch if accessed bits aren't available.
3034c50d8ae3SPaolo Bonzini 	 */
3035c50d8ae3SPaolo Bonzini 	if (sp_ad_disabled(sp))
3036c50d8ae3SPaolo Bonzini 		return;
3037c50d8ae3SPaolo Bonzini 
30383bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
3039c50d8ae3SPaolo Bonzini 		return;
3040c50d8ae3SPaolo Bonzini 
30414a42d848SDavid Stevens 	/*
30424a42d848SDavid Stevens 	 * If addresses are being invalidated, skip prefetching to avoid
30434a42d848SDavid Stevens 	 * accidentally prefetching those addresses.
30444a42d848SDavid Stevens 	 */
304520ec3ebdSChao Peng 	if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
30464a42d848SDavid Stevens 		return;
30474a42d848SDavid Stevens 
3048c50d8ae3SPaolo Bonzini 	__direct_pte_prefetch(vcpu, sp, sptep);
3049c50d8ae3SPaolo Bonzini }
3050c50d8ae3SPaolo Bonzini 
305165e3b446SSean Christopherson /*
305265e3b446SSean Christopherson  * Lookup the mapping level for @gfn in the current mm.
305365e3b446SSean Christopherson  *
305465e3b446SSean Christopherson  * WARNING!  Use of host_pfn_mapping_level() requires the caller and the end
305565e3b446SSean Christopherson  * consumer to be tied into KVM's handlers for MMU notifier events!
305665e3b446SSean Christopherson  *
305765e3b446SSean Christopherson  * There are several ways to safely use this helper:
305865e3b446SSean Christopherson  *
305920ec3ebdSChao Peng  * - Check mmu_invalidate_retry_hva() after grabbing the mapping level, before
306065e3b446SSean Christopherson  *   consuming it.  In this case, mmu_lock doesn't need to be held during the
306165e3b446SSean Christopherson  *   lookup, but it does need to be held while checking the MMU notifier.
306265e3b446SSean Christopherson  *
306365e3b446SSean Christopherson  * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
306465e3b446SSean Christopherson  *   event for the hva.  This can be done by explicit checking the MMU notifier
306565e3b446SSean Christopherson  *   or by ensuring that KVM already has a valid mapping that covers the hva.
306665e3b446SSean Christopherson  *
306765e3b446SSean Christopherson  * - Do not use the result to install new mappings, e.g. use the host mapping
306865e3b446SSean Christopherson  *   level only to decide whether or not to zap an entry.  In this case, it's
306965e3b446SSean Christopherson  *   not required to hold mmu_lock (though it's highly likely the caller will
307065e3b446SSean Christopherson  *   want to hold mmu_lock anyways, e.g. to modify SPTEs).
307165e3b446SSean Christopherson  *
307265e3b446SSean Christopherson  * Note!  The lookup can still race with modifications to host page tables, but
307365e3b446SSean Christopherson  * the above "rules" ensure KVM will not _consume_ the result of the walk if a
307465e3b446SSean Christopherson  * race with the primary MMU occurs.
307565e3b446SSean Christopherson  */
3076a8ac499bSSean Christopherson static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
30778ca6f063SBen Gardon 				  const struct kvm_memory_slot *slot)
3078db543216SSean Christopherson {
3079284dc493SSean Christopherson 	int level = PG_LEVEL_4K;
3080db543216SSean Christopherson 	unsigned long hva;
308144187235SMingwei Zhang 	unsigned long flags;
308244187235SMingwei Zhang 	pgd_t pgd;
308344187235SMingwei Zhang 	p4d_t p4d;
308444187235SMingwei Zhang 	pud_t pud;
308544187235SMingwei Zhang 	pmd_t pmd;
3086db543216SSean Christopherson 
30875d49f08cSSean Christopherson 	/*
3088293e306eSSean Christopherson 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3089293e306eSSean Christopherson 	 * is not solely for performance, it's also necessary to avoid the
3090293e306eSSean Christopherson 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
3091293e306eSSean Christopherson 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
3092293e306eSSean Christopherson 	 * page fault steps have already verified the guest isn't writing a
3093293e306eSSean Christopherson 	 * read-only memslot.
3094293e306eSSean Christopherson 	 */
3095db543216SSean Christopherson 	hva = __gfn_to_hva_memslot(slot, gfn);
3096db543216SSean Christopherson 
309744187235SMingwei Zhang 	/*
309865e3b446SSean Christopherson 	 * Disable IRQs to prevent concurrent tear down of host page tables,
309965e3b446SSean Christopherson 	 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
310065e3b446SSean Christopherson 	 * the original page table.
310144187235SMingwei Zhang 	 */
310244187235SMingwei Zhang 	local_irq_save(flags);
3103db543216SSean Christopherson 
310465e3b446SSean Christopherson 	/*
310565e3b446SSean Christopherson 	 * Read each entry once.  As above, a non-leaf entry can be promoted to
310665e3b446SSean Christopherson 	 * a huge page _during_ this walk.  Re-reading the entry could send the
310765e3b446SSean Christopherson 	 * walk into the weeks, e.g. p*d_large() returns false (sees the old
310865e3b446SSean Christopherson 	 * value) and then p*d_offset() walks into the target huge page instead
310965e3b446SSean Christopherson 	 * of the old page table (sees the new value).
311065e3b446SSean Christopherson 	 */
311144187235SMingwei Zhang 	pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
311244187235SMingwei Zhang 	if (pgd_none(pgd))
311344187235SMingwei Zhang 		goto out;
311444187235SMingwei Zhang 
311544187235SMingwei Zhang 	p4d = READ_ONCE(*p4d_offset(&pgd, hva));
311644187235SMingwei Zhang 	if (p4d_none(p4d) || !p4d_present(p4d))
311744187235SMingwei Zhang 		goto out;
311844187235SMingwei Zhang 
311944187235SMingwei Zhang 	pud = READ_ONCE(*pud_offset(&p4d, hva));
312044187235SMingwei Zhang 	if (pud_none(pud) || !pud_present(pud))
312144187235SMingwei Zhang 		goto out;
312244187235SMingwei Zhang 
312344187235SMingwei Zhang 	if (pud_large(pud)) {
312444187235SMingwei Zhang 		level = PG_LEVEL_1G;
312544187235SMingwei Zhang 		goto out;
312644187235SMingwei Zhang 	}
312744187235SMingwei Zhang 
312844187235SMingwei Zhang 	pmd = READ_ONCE(*pmd_offset(&pud, hva));
312944187235SMingwei Zhang 	if (pmd_none(pmd) || !pmd_present(pmd))
313044187235SMingwei Zhang 		goto out;
313144187235SMingwei Zhang 
313244187235SMingwei Zhang 	if (pmd_large(pmd))
313344187235SMingwei Zhang 		level = PG_LEVEL_2M;
313444187235SMingwei Zhang 
313544187235SMingwei Zhang out:
313644187235SMingwei Zhang 	local_irq_restore(flags);
3137db543216SSean Christopherson 	return level;
3138db543216SSean Christopherson }
3139db543216SSean Christopherson 
31408ca6f063SBen Gardon int kvm_mmu_max_mapping_level(struct kvm *kvm,
31418ca6f063SBen Gardon 			      const struct kvm_memory_slot *slot, gfn_t gfn,
3142a8ac499bSSean Christopherson 			      int max_level)
31431b6d9d9eSSean Christopherson {
31441b6d9d9eSSean Christopherson 	struct kvm_lpage_info *linfo;
3145ec607a56SPaolo Bonzini 	int host_level;
31461b6d9d9eSSean Christopherson 
31471b6d9d9eSSean Christopherson 	max_level = min(max_level, max_huge_page_level);
31481b6d9d9eSSean Christopherson 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
31491b6d9d9eSSean Christopherson 		linfo = lpage_info_slot(gfn, slot, max_level);
31501b6d9d9eSSean Christopherson 		if (!linfo->disallow_lpage)
31511b6d9d9eSSean Christopherson 			break;
31521b6d9d9eSSean Christopherson 	}
31531b6d9d9eSSean Christopherson 
31541b6d9d9eSSean Christopherson 	if (max_level == PG_LEVEL_4K)
31551b6d9d9eSSean Christopherson 		return PG_LEVEL_4K;
31561b6d9d9eSSean Christopherson 
3157a8ac499bSSean Christopherson 	host_level = host_pfn_mapping_level(kvm, gfn, slot);
3158ec607a56SPaolo Bonzini 	return min(host_level, max_level);
31591b6d9d9eSSean Christopherson }
31601b6d9d9eSSean Christopherson 
316173a3c659SPaolo Bonzini void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
31620885904dSSean Christopherson {
3163e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
316417eff019SSean Christopherson 	kvm_pfn_t mask;
31650885904dSSean Christopherson 
316673a3c659SPaolo Bonzini 	fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
31673cf06612SSean Christopherson 
316873a3c659SPaolo Bonzini 	if (unlikely(fault->max_level == PG_LEVEL_4K))
316973a3c659SPaolo Bonzini 		return;
317017eff019SSean Christopherson 
31715d49f08cSSean Christopherson 	if (is_error_noslot_pfn(fault->pfn))
317273a3c659SPaolo Bonzini 		return;
317317eff019SSean Christopherson 
3174e710c5f6SDavid Matlack 	if (kvm_slot_dirty_track_enabled(slot))
317573a3c659SPaolo Bonzini 		return;
3176293e306eSSean Christopherson 
31773cf06612SSean Christopherson 	/*
31783cf06612SSean Christopherson 	 * Enforce the iTLB multihit workaround after capturing the requested
31793cf06612SSean Christopherson 	 * level, which will be used to do precise, accurate accounting.
31803cf06612SSean Christopherson 	 */
318173a3c659SPaolo Bonzini 	fault->req_level = kvm_mmu_max_mapping_level(vcpu->kvm, slot,
3182a8ac499bSSean Christopherson 						     fault->gfn, fault->max_level);
318373a3c659SPaolo Bonzini 	if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
318473a3c659SPaolo Bonzini 		return;
31854cd071d1SSean Christopherson 
31860885904dSSean Christopherson 	/*
318720ec3ebdSChao Peng 	 * mmu_invalidate_retry() was successful and mmu_lock is held, so
31884cd071d1SSean Christopherson 	 * the pmd can't be split from under us.
31890885904dSSean Christopherson 	 */
319073a3c659SPaolo Bonzini 	fault->goal_level = fault->req_level;
319173a3c659SPaolo Bonzini 	mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
319273a3c659SPaolo Bonzini 	VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
319373a3c659SPaolo Bonzini 	fault->pfn &= ~mask;
31940885904dSSean Christopherson }
31950885904dSSean Christopherson 
3196536f0e6aSPaolo Bonzini void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3197c50d8ae3SPaolo Bonzini {
3198536f0e6aSPaolo Bonzini 	if (cur_level > PG_LEVEL_4K &&
3199536f0e6aSPaolo Bonzini 	    cur_level == fault->goal_level &&
3200c50d8ae3SPaolo Bonzini 	    is_shadow_present_pte(spte) &&
320176901e56SMingwei Zhang 	    !is_large_pte(spte) &&
320276901e56SMingwei Zhang 	    spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3203c50d8ae3SPaolo Bonzini 		/*
32046c882ef4SDavid Matlack 		 * A small SPTE exists for this pfn, but FNAME(fetch),
32056c882ef4SDavid Matlack 		 * direct_map(), or kvm_tdp_mmu_map() would like to create a
32066c882ef4SDavid Matlack 		 * large PTE instead: just force them to go down another level,
32076c882ef4SDavid Matlack 		 * patching back for them into pfn the next 9 bits of the
32086c882ef4SDavid Matlack 		 * address.
3209c50d8ae3SPaolo Bonzini 		 */
3210536f0e6aSPaolo Bonzini 		u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3211536f0e6aSPaolo Bonzini 				KVM_PAGES_PER_HPAGE(cur_level - 1);
3212536f0e6aSPaolo Bonzini 		fault->pfn |= fault->gfn & page_mask;
3213536f0e6aSPaolo Bonzini 		fault->goal_level--;
3214c50d8ae3SPaolo Bonzini 	}
3215c50d8ae3SPaolo Bonzini }
3216c50d8ae3SPaolo Bonzini 
32176c882ef4SDavid Matlack static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3218c50d8ae3SPaolo Bonzini {
3219c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator it;
3220c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
322173a3c659SPaolo Bonzini 	int ret;
322243b74355SPaolo Bonzini 	gfn_t base_gfn = fault->gfn;
3223c50d8ae3SPaolo Bonzini 
322473a3c659SPaolo Bonzini 	kvm_mmu_hugepage_adjust(vcpu, fault);
32254cd071d1SSean Christopherson 
3226f0066d94SPaolo Bonzini 	trace_kvm_mmu_spte_requested(fault);
322743b74355SPaolo Bonzini 	for_each_shadow_entry(vcpu, fault->addr, it) {
3228c50d8ae3SPaolo Bonzini 		/*
3229c50d8ae3SPaolo Bonzini 		 * We cannot overwrite existing page tables with an NX
3230c50d8ae3SPaolo Bonzini 		 * large page, as the leaf could be executable.
3231c50d8ae3SPaolo Bonzini 		 */
323273a3c659SPaolo Bonzini 		if (fault->nx_huge_page_workaround_enabled)
3233536f0e6aSPaolo Bonzini 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3234c50d8ae3SPaolo Bonzini 
3235c667a3baSHou Wenlong 		base_gfn = gfn_round_for_level(fault->gfn, it.level);
323673a3c659SPaolo Bonzini 		if (it.level == fault->goal_level)
3237c50d8ae3SPaolo Bonzini 			break;
3238c50d8ae3SPaolo Bonzini 
32392e65e842SDavid Matlack 		sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
32400cd8dc73SPaolo Bonzini 		if (sp == ERR_PTR(-EEXIST))
32410cd8dc73SPaolo Bonzini 			continue;
3242c50d8ae3SPaolo Bonzini 
3243c50d8ae3SPaolo Bonzini 		link_shadow_page(vcpu, it.sptep, sp);
3244b5b0977fSSean Christopherson 		if (fault->huge_page_disallowed)
324555c510e2SSean Christopherson 			account_nx_huge_page(vcpu->kvm, sp,
3246428e9216SSean Christopherson 					     fault->req_level >= it.level);
3247c50d8ae3SPaolo Bonzini 	}
3248c50d8ae3SPaolo Bonzini 
3249b1a429fbSSean Christopherson 	if (WARN_ON_ONCE(it.level != fault->goal_level))
3250b1a429fbSSean Christopherson 		return -EFAULT;
3251b1a429fbSSean Christopherson 
32528a9f566aSDavid Matlack 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3253a12f4381SPaolo Bonzini 			   base_gfn, fault->pfn, fault);
325412703759SSean Christopherson 	if (ret == RET_PF_SPURIOUS)
325512703759SSean Christopherson 		return ret;
325612703759SSean Christopherson 
3257c50d8ae3SPaolo Bonzini 	direct_pte_prefetch(vcpu, it.sptep);
3258c50d8ae3SPaolo Bonzini 	return ret;
3259c50d8ae3SPaolo Bonzini }
3260c50d8ae3SPaolo Bonzini 
3261cd08d178SDavid Matlack static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3262c50d8ae3SPaolo Bonzini {
3263cd08d178SDavid Matlack 	unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3264cd08d178SDavid Matlack 
3265cd08d178SDavid Matlack 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3266c50d8ae3SPaolo Bonzini }
3267c50d8ae3SPaolo Bonzini 
3268cd08d178SDavid Matlack static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3269c50d8ae3SPaolo Bonzini {
3270cd08d178SDavid Matlack 	if (is_sigpending_pfn(fault->pfn)) {
327176657687SPeter Xu 		kvm_handle_signal_exit(vcpu);
327276657687SPeter Xu 		return -EINTR;
327376657687SPeter Xu 	}
327476657687SPeter Xu 
3275c50d8ae3SPaolo Bonzini 	/*
3276c50d8ae3SPaolo Bonzini 	 * Do not cache the mmio info caused by writing the readonly gfn
3277c50d8ae3SPaolo Bonzini 	 * into the spte otherwise read access on readonly gfn also can
3278c50d8ae3SPaolo Bonzini 	 * caused mmio page fault and treat it as mmio access.
3279c50d8ae3SPaolo Bonzini 	 */
3280cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3281c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3282c50d8ae3SPaolo Bonzini 
3283cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3284cd08d178SDavid Matlack 		kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3285c50d8ae3SPaolo Bonzini 		return RET_PF_RETRY;
3286c50d8ae3SPaolo Bonzini 	}
3287c50d8ae3SPaolo Bonzini 
3288c50d8ae3SPaolo Bonzini 	return -EFAULT;
3289c50d8ae3SPaolo Bonzini }
3290c50d8ae3SPaolo Bonzini 
3291354c908cSDavid Matlack static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3292354c908cSDavid Matlack 				   struct kvm_page_fault *fault,
32935276c616SSean Christopherson 				   unsigned int access)
3294c50d8ae3SPaolo Bonzini {
32953a13f4feSPaolo Bonzini 	gva_t gva = fault->is_tdp ? 0 : fault->addr;
32963a13f4feSPaolo Bonzini 
32973a13f4feSPaolo Bonzini 	vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3298c50d8ae3SPaolo Bonzini 			     access & shadow_mmio_access_mask);
3299354c908cSDavid Matlack 
330030ab5901SSean Christopherson 	/*
330130ab5901SSean Christopherson 	 * If MMIO caching is disabled, emulate immediately without
330230ab5901SSean Christopherson 	 * touching the shadow page tables as attempting to install an
3303354c908cSDavid Matlack 	 * MMIO SPTE will just be an expensive nop.
330430ab5901SSean Christopherson 	 */
3305354c908cSDavid Matlack 	if (unlikely(!enable_mmio_caching))
33065276c616SSean Christopherson 		return RET_PF_EMULATE;
3307354c908cSDavid Matlack 
3308354c908cSDavid Matlack 	/*
3309354c908cSDavid Matlack 	 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3310354c908cSDavid Matlack 	 * any guest that generates such gfns is running nested and is being
3311354c908cSDavid Matlack 	 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3312354c908cSDavid Matlack 	 * only if L1's MAXPHYADDR is inaccurate with respect to the
3313354c908cSDavid Matlack 	 * hardware's).
3314354c908cSDavid Matlack 	 */
3315354c908cSDavid Matlack 	if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3316354c908cSDavid Matlack 		return RET_PF_EMULATE;
3317c50d8ae3SPaolo Bonzini 
33185276c616SSean Christopherson 	return RET_PF_CONTINUE;
3319c50d8ae3SPaolo Bonzini }
3320c50d8ae3SPaolo Bonzini 
33213c8ad5a6SPaolo Bonzini static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
3322c50d8ae3SPaolo Bonzini {
3323c50d8ae3SPaolo Bonzini 	/*
33245c64aba5SSean Christopherson 	 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
33255c64aba5SSean Christopherson 	 * reach the common page fault handler if the SPTE has an invalid MMIO
33265c64aba5SSean Christopherson 	 * generation number.  Refreshing the MMIO generation needs to go down
33275c64aba5SSean Christopherson 	 * the slow path.  Note, EPT Misconfigs do NOT set the PRESENT flag!
3328c50d8ae3SPaolo Bonzini 	 */
33293c8ad5a6SPaolo Bonzini 	if (fault->rsvd)
3330c50d8ae3SPaolo Bonzini 		return false;
3331c50d8ae3SPaolo Bonzini 
3332c50d8ae3SPaolo Bonzini 	/*
3333c50d8ae3SPaolo Bonzini 	 * #PF can be fast if:
3334c50d8ae3SPaolo Bonzini 	 *
333554275f74SSean Christopherson 	 * 1. The shadow page table entry is not present and A/D bits are
333654275f74SSean Christopherson 	 *    disabled _by KVM_, which could mean that the fault is potentially
333754275f74SSean Christopherson 	 *    caused by access tracking (if enabled).  If A/D bits are enabled
333854275f74SSean Christopherson 	 *    by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
333954275f74SSean Christopherson 	 *    bits for L2 and employ access tracking, but the fast page fault
334054275f74SSean Christopherson 	 *    mechanism only supports direct MMUs.
334154275f74SSean Christopherson 	 * 2. The shadow page table entry is present, the access is a write,
334254275f74SSean Christopherson 	 *    and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
334354275f74SSean Christopherson 	 *    the fault was caused by a write-protection violation.  If the
334454275f74SSean Christopherson 	 *    SPTE is MMU-writable (determined later), the fault can be fixed
334554275f74SSean Christopherson 	 *    by setting the Writable bit, which can be done out of mmu_lock.
3346c50d8ae3SPaolo Bonzini 	 */
33475c64aba5SSean Christopherson 	if (!fault->present)
33485c64aba5SSean Christopherson 		return !kvm_ad_enabled();
33495c64aba5SSean Christopherson 
33505c64aba5SSean Christopherson 	/*
33515c64aba5SSean Christopherson 	 * Note, instruction fetches and writes are mutually exclusive, ignore
33525c64aba5SSean Christopherson 	 * the "exec" flag.
33535c64aba5SSean Christopherson 	 */
33545c64aba5SSean Christopherson 	return fault->write;
3355c50d8ae3SPaolo Bonzini }
3356c50d8ae3SPaolo Bonzini 
3357c50d8ae3SPaolo Bonzini /*
3358c50d8ae3SPaolo Bonzini  * Returns true if the SPTE was fixed successfully. Otherwise,
3359c50d8ae3SPaolo Bonzini  * someone else modified the SPTE from its original value.
3360c50d8ae3SPaolo Bonzini  */
3361f3d90f90SSean Christopherson static bool fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu,
3362f3d90f90SSean Christopherson 				    struct kvm_page_fault *fault,
3363c50d8ae3SPaolo Bonzini 				    u64 *sptep, u64 old_spte, u64 new_spte)
3364c50d8ae3SPaolo Bonzini {
3365c50d8ae3SPaolo Bonzini 	/*
3366c50d8ae3SPaolo Bonzini 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3367c50d8ae3SPaolo Bonzini 	 * order to eliminate unnecessary PML logging. See comments in
3368c50d8ae3SPaolo Bonzini 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3369c50d8ae3SPaolo Bonzini 	 * enabled, so we do not do this. This might result in the same GPA
3370c50d8ae3SPaolo Bonzini 	 * to be logged in PML buffer again when the write really happens, and
3371c50d8ae3SPaolo Bonzini 	 * eventually to be called by mark_page_dirty twice. But it's also no
3372c50d8ae3SPaolo Bonzini 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3373c50d8ae3SPaolo Bonzini 	 * so non-PML cases won't be impacted.
3374c50d8ae3SPaolo Bonzini 	 *
3375c50d8ae3SPaolo Bonzini 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3376c50d8ae3SPaolo Bonzini 	 */
33772db2f46fSUros Bizjak 	if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3378c50d8ae3SPaolo Bonzini 		return false;
3379c50d8ae3SPaolo Bonzini 
3380e710c5f6SDavid Matlack 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3381e710c5f6SDavid Matlack 		mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3382c50d8ae3SPaolo Bonzini 
3383c50d8ae3SPaolo Bonzini 	return true;
3384c50d8ae3SPaolo Bonzini }
3385c50d8ae3SPaolo Bonzini 
33863c8ad5a6SPaolo Bonzini static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3387c50d8ae3SPaolo Bonzini {
33883c8ad5a6SPaolo Bonzini 	if (fault->exec)
3389c50d8ae3SPaolo Bonzini 		return is_executable_pte(spte);
3390c50d8ae3SPaolo Bonzini 
33913c8ad5a6SPaolo Bonzini 	if (fault->write)
3392c50d8ae3SPaolo Bonzini 		return is_writable_pte(spte);
3393c50d8ae3SPaolo Bonzini 
3394c50d8ae3SPaolo Bonzini 	/* Fault was on Read access */
3395c50d8ae3SPaolo Bonzini 	return spte & PT_PRESENT_MASK;
3396c50d8ae3SPaolo Bonzini }
3397c50d8ae3SPaolo Bonzini 
3398c50d8ae3SPaolo Bonzini /*
33996e8eb206SDavid Matlack  * Returns the last level spte pointer of the shadow page walk for the given
34006e8eb206SDavid Matlack  * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
34016e8eb206SDavid Matlack  * walk could be performed, returns NULL and *spte does not contain valid data.
34026e8eb206SDavid Matlack  *
34036e8eb206SDavid Matlack  * Contract:
34046e8eb206SDavid Matlack  *  - Must be called between walk_shadow_page_lockless_{begin,end}.
34056e8eb206SDavid Matlack  *  - The returned sptep must not be used after walk_shadow_page_lockless_end.
34066e8eb206SDavid Matlack  */
34076e8eb206SDavid Matlack static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
34086e8eb206SDavid Matlack {
34096e8eb206SDavid Matlack 	struct kvm_shadow_walk_iterator iterator;
34106e8eb206SDavid Matlack 	u64 old_spte;
34116e8eb206SDavid Matlack 	u64 *sptep = NULL;
34126e8eb206SDavid Matlack 
34136e8eb206SDavid Matlack 	for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
34146e8eb206SDavid Matlack 		sptep = iterator.sptep;
34156e8eb206SDavid Matlack 		*spte = old_spte;
34166e8eb206SDavid Matlack 	}
34176e8eb206SDavid Matlack 
34186e8eb206SDavid Matlack 	return sptep;
34196e8eb206SDavid Matlack }
34206e8eb206SDavid Matlack 
34216e8eb206SDavid Matlack /*
3422c4371c2aSSean Christopherson  * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3423c50d8ae3SPaolo Bonzini  */
34243c8ad5a6SPaolo Bonzini static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3425c50d8ae3SPaolo Bonzini {
3426c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3427c4371c2aSSean Christopherson 	int ret = RET_PF_INVALID;
3428c50d8ae3SPaolo Bonzini 	u64 spte = 0ull;
34296e8eb206SDavid Matlack 	u64 *sptep = NULL;
3430c50d8ae3SPaolo Bonzini 	uint retry_count = 0;
3431c50d8ae3SPaolo Bonzini 
34323c8ad5a6SPaolo Bonzini 	if (!page_fault_can_be_fast(fault))
3433c4371c2aSSean Christopherson 		return ret;
3434c50d8ae3SPaolo Bonzini 
3435c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
3436c50d8ae3SPaolo Bonzini 
3437c50d8ae3SPaolo Bonzini 	do {
3438c50d8ae3SPaolo Bonzini 		u64 new_spte;
3439c50d8ae3SPaolo Bonzini 
3440dfe0ecc6SSean Christopherson 		if (tdp_mmu_enabled)
34413c8ad5a6SPaolo Bonzini 			sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
34426e8eb206SDavid Matlack 		else
34433c8ad5a6SPaolo Bonzini 			sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3444c50d8ae3SPaolo Bonzini 
3445ec89e643SSean Christopherson 		if (!is_shadow_present_pte(spte))
3446ec89e643SSean Christopherson 			break;
3447ec89e643SSean Christopherson 
34486e8eb206SDavid Matlack 		sp = sptep_to_sp(sptep);
3449c50d8ae3SPaolo Bonzini 		if (!is_last_spte(spte, sp->role.level))
3450c50d8ae3SPaolo Bonzini 			break;
3451c50d8ae3SPaolo Bonzini 
3452c50d8ae3SPaolo Bonzini 		/*
3453c50d8ae3SPaolo Bonzini 		 * Check whether the memory access that caused the fault would
3454c50d8ae3SPaolo Bonzini 		 * still cause it if it were to be performed right now. If not,
3455c50d8ae3SPaolo Bonzini 		 * then this is a spurious fault caused by TLB lazily flushed,
3456c50d8ae3SPaolo Bonzini 		 * or some other CPU has already fixed the PTE after the
3457c50d8ae3SPaolo Bonzini 		 * current CPU took the fault.
3458c50d8ae3SPaolo Bonzini 		 *
3459c50d8ae3SPaolo Bonzini 		 * Need not check the access of upper level table entries since
3460c50d8ae3SPaolo Bonzini 		 * they are always ACC_ALL.
3461c50d8ae3SPaolo Bonzini 		 */
34623c8ad5a6SPaolo Bonzini 		if (is_access_allowed(fault, spte)) {
3463c4371c2aSSean Christopherson 			ret = RET_PF_SPURIOUS;
3464c50d8ae3SPaolo Bonzini 			break;
3465c50d8ae3SPaolo Bonzini 		}
3466c50d8ae3SPaolo Bonzini 
3467c50d8ae3SPaolo Bonzini 		new_spte = spte;
3468c50d8ae3SPaolo Bonzini 
346954275f74SSean Christopherson 		/*
347054275f74SSean Christopherson 		 * KVM only supports fixing page faults outside of MMU lock for
347154275f74SSean Christopherson 		 * direct MMUs, nested MMUs are always indirect, and KVM always
347254275f74SSean Christopherson 		 * uses A/D bits for non-nested MMUs.  Thus, if A/D bits are
347354275f74SSean Christopherson 		 * enabled, the SPTE can't be an access-tracked SPTE.
347454275f74SSean Christopherson 		 */
347554275f74SSean Christopherson 		if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3476c50d8ae3SPaolo Bonzini 			new_spte = restore_acc_track_spte(new_spte);
3477c50d8ae3SPaolo Bonzini 
3478c50d8ae3SPaolo Bonzini 		/*
347954275f74SSean Christopherson 		 * To keep things simple, only SPTEs that are MMU-writable can
348054275f74SSean Christopherson 		 * be made fully writable outside of mmu_lock, e.g. only SPTEs
348154275f74SSean Christopherson 		 * that were write-protected for dirty-logging or access
348254275f74SSean Christopherson 		 * tracking are handled here.  Don't bother checking if the
348354275f74SSean Christopherson 		 * SPTE is writable to prioritize running with A/D bits enabled.
348454275f74SSean Christopherson 		 * The is_access_allowed() check above handles the common case
348554275f74SSean Christopherson 		 * of the fault being spurious, and the SPTE is known to be
348654275f74SSean Christopherson 		 * shadow-present, i.e. except for access tracking restoration
348754275f74SSean Christopherson 		 * making the new SPTE writable, the check is wasteful.
3488c50d8ae3SPaolo Bonzini 		 */
3489706c9c55SSean Christopherson 		if (fault->write && is_mmu_writable_spte(spte)) {
3490c50d8ae3SPaolo Bonzini 			new_spte |= PT_WRITABLE_MASK;
3491c50d8ae3SPaolo Bonzini 
3492c50d8ae3SPaolo Bonzini 			/*
349310c30de0SJunaid Shahid 			 * Do not fix write-permission on the large spte when
349410c30de0SJunaid Shahid 			 * dirty logging is enabled. Since we only dirty the
349510c30de0SJunaid Shahid 			 * first page into the dirty-bitmap in
3496c50d8ae3SPaolo Bonzini 			 * fast_pf_fix_direct_spte(), other pages are missed
3497c50d8ae3SPaolo Bonzini 			 * if its slot has dirty logging enabled.
3498c50d8ae3SPaolo Bonzini 			 *
3499c50d8ae3SPaolo Bonzini 			 * Instead, we let the slow page fault path create a
3500c50d8ae3SPaolo Bonzini 			 * normal spte to fix the access.
3501c50d8ae3SPaolo Bonzini 			 */
350210c30de0SJunaid Shahid 			if (sp->role.level > PG_LEVEL_4K &&
350310c30de0SJunaid Shahid 			    kvm_slot_dirty_track_enabled(fault->slot))
3504c50d8ae3SPaolo Bonzini 				break;
3505c50d8ae3SPaolo Bonzini 		}
3506c50d8ae3SPaolo Bonzini 
3507c50d8ae3SPaolo Bonzini 		/* Verify that the fault can be handled in the fast path */
3508c50d8ae3SPaolo Bonzini 		if (new_spte == spte ||
35093c8ad5a6SPaolo Bonzini 		    !is_access_allowed(fault, new_spte))
3510c50d8ae3SPaolo Bonzini 			break;
3511c50d8ae3SPaolo Bonzini 
3512c50d8ae3SPaolo Bonzini 		/*
3513c50d8ae3SPaolo Bonzini 		 * Currently, fast page fault only works for direct mapping
3514c50d8ae3SPaolo Bonzini 		 * since the gfn is not stable for indirect shadow page. See
35153ecad8c2SMauro Carvalho Chehab 		 * Documentation/virt/kvm/locking.rst to get more detail.
3516c50d8ae3SPaolo Bonzini 		 */
3517e710c5f6SDavid Matlack 		if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3518c4371c2aSSean Christopherson 			ret = RET_PF_FIXED;
3519c50d8ae3SPaolo Bonzini 			break;
3520c4371c2aSSean Christopherson 		}
3521c50d8ae3SPaolo Bonzini 
3522c50d8ae3SPaolo Bonzini 		if (++retry_count > 4) {
35238d20bd63SSean Christopherson 			pr_warn_once("Fast #PF retrying more than 4 times.\n");
3524c50d8ae3SPaolo Bonzini 			break;
3525c50d8ae3SPaolo Bonzini 		}
3526c50d8ae3SPaolo Bonzini 
3527c50d8ae3SPaolo Bonzini 	} while (true);
3528c50d8ae3SPaolo Bonzini 
3529f0066d94SPaolo Bonzini 	trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3530c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3531c50d8ae3SPaolo Bonzini 
35321075d41eSSean Christopherson 	if (ret != RET_PF_INVALID)
35331075d41eSSean Christopherson 		vcpu->stat.pf_fast++;
35341075d41eSSean Christopherson 
3535c4371c2aSSean Christopherson 	return ret;
3536c50d8ae3SPaolo Bonzini }
3537c50d8ae3SPaolo Bonzini 
3538c50d8ae3SPaolo Bonzini static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3539c50d8ae3SPaolo Bonzini 			       struct list_head *invalid_list)
3540c50d8ae3SPaolo Bonzini {
3541c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3542c50d8ae3SPaolo Bonzini 
3543c50d8ae3SPaolo Bonzini 	if (!VALID_PAGE(*root_hpa))
3544c50d8ae3SPaolo Bonzini 		return;
3545c50d8ae3SPaolo Bonzini 
3546c5f2d564SSean Christopherson 	sp = root_to_sp(*root_hpa);
354720ba462dSSean Christopherson 	if (WARN_ON_ONCE(!sp))
35489191b8f0SPaolo Bonzini 		return;
354902c00b3aSBen Gardon 
3550897218ffSPaolo Bonzini 	if (is_tdp_mmu_page(sp))
35516103bc07SBen Gardon 		kvm_tdp_mmu_put_root(kvm, sp, false);
355276eb54e7SBen Gardon 	else if (!--sp->root_count && sp->role.invalid)
3553c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3554c50d8ae3SPaolo Bonzini 
3555c50d8ae3SPaolo Bonzini 	*root_hpa = INVALID_PAGE;
3556c50d8ae3SPaolo Bonzini }
3557c50d8ae3SPaolo Bonzini 
3558c50d8ae3SPaolo Bonzini /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
35590c1c92f1SPaolo Bonzini void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3560c50d8ae3SPaolo Bonzini 			ulong roots_to_free)
3561c50d8ae3SPaolo Bonzini {
3562c50d8ae3SPaolo Bonzini 	int i;
3563c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
3564594bef79SPaolo Bonzini 	bool free_active_root;
3565c50d8ae3SPaolo Bonzini 
3566f94db0c8SSean Christopherson 	WARN_ON_ONCE(roots_to_free & ~KVM_MMU_ROOTS_ALL);
3567f94db0c8SSean Christopherson 
3568c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3569c50d8ae3SPaolo Bonzini 
3570c50d8ae3SPaolo Bonzini 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3571594bef79SPaolo Bonzini 	free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3572594bef79SPaolo Bonzini 		&& VALID_PAGE(mmu->root.hpa);
3573594bef79SPaolo Bonzini 
3574594bef79SPaolo Bonzini 	if (!free_active_root) {
3575c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3576c50d8ae3SPaolo Bonzini 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3577c50d8ae3SPaolo Bonzini 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3578c50d8ae3SPaolo Bonzini 				break;
3579c50d8ae3SPaolo Bonzini 
3580c50d8ae3SPaolo Bonzini 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3581c50d8ae3SPaolo Bonzini 			return;
3582c50d8ae3SPaolo Bonzini 	}
3583c50d8ae3SPaolo Bonzini 
3584531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
3585c50d8ae3SPaolo Bonzini 
3586c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3587c50d8ae3SPaolo Bonzini 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
35884d710de9SSean Christopherson 			mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3589c50d8ae3SPaolo Bonzini 					   &invalid_list);
3590c50d8ae3SPaolo Bonzini 
3591c50d8ae3SPaolo Bonzini 	if (free_active_root) {
3592c5f2d564SSean Christopherson 		if (root_to_sp(mmu->root.hpa)) {
3593b9e5603cSPaolo Bonzini 			mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
359404d45551SSean Christopherson 		} else if (mmu->pae_root) {
3595c834e5e4SSean Christopherson 			for (i = 0; i < 4; ++i) {
3596c834e5e4SSean Christopherson 				if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3597c834e5e4SSean Christopherson 					continue;
3598c834e5e4SSean Christopherson 
3599c834e5e4SSean Christopherson 				mmu_free_root_page(kvm, &mmu->pae_root[i],
3600c50d8ae3SPaolo Bonzini 						   &invalid_list);
3601c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3602c50d8ae3SPaolo Bonzini 			}
3603c50d8ae3SPaolo Bonzini 		}
3604b9e5603cSPaolo Bonzini 		mmu->root.hpa = INVALID_PAGE;
3605b9e5603cSPaolo Bonzini 		mmu->root.pgd = 0;
3606c50d8ae3SPaolo Bonzini 	}
3607c50d8ae3SPaolo Bonzini 
36084d710de9SSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
3609531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
3610c50d8ae3SPaolo Bonzini }
3611c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3612c50d8ae3SPaolo Bonzini 
36130c1c92f1SPaolo Bonzini void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
361425b62c62SSean Christopherson {
361525b62c62SSean Christopherson 	unsigned long roots_to_free = 0;
3616c5f2d564SSean Christopherson 	struct kvm_mmu_page *sp;
361725b62c62SSean Christopherson 	hpa_t root_hpa;
361825b62c62SSean Christopherson 	int i;
361925b62c62SSean Christopherson 
362025b62c62SSean Christopherson 	/*
362125b62c62SSean Christopherson 	 * This should not be called while L2 is active, L2 can't invalidate
362225b62c62SSean Christopherson 	 * _only_ its own roots, e.g. INVVPID unconditionally exits.
362325b62c62SSean Christopherson 	 */
36247a458f0eSPaolo Bonzini 	WARN_ON_ONCE(mmu->root_role.guest_mode);
362525b62c62SSean Christopherson 
362625b62c62SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
362725b62c62SSean Christopherson 		root_hpa = mmu->prev_roots[i].hpa;
362825b62c62SSean Christopherson 		if (!VALID_PAGE(root_hpa))
362925b62c62SSean Christopherson 			continue;
363025b62c62SSean Christopherson 
3631c5f2d564SSean Christopherson 		sp = root_to_sp(root_hpa);
3632c5f2d564SSean Christopherson 		if (!sp || sp->role.guest_mode)
363325b62c62SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
363425b62c62SSean Christopherson 	}
363525b62c62SSean Christopherson 
36360c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, roots_to_free);
363725b62c62SSean Christopherson }
363825b62c62SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
363925b62c62SSean Christopherson 
364025b62c62SSean Christopherson 
3641c50d8ae3SPaolo Bonzini static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3642c50d8ae3SPaolo Bonzini {
3643c50d8ae3SPaolo Bonzini 	int ret = 0;
3644c50d8ae3SPaolo Bonzini 
3645995decb6SVitaly Kuznetsov 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3646c50d8ae3SPaolo Bonzini 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3647c50d8ae3SPaolo Bonzini 		ret = 1;
3648c50d8ae3SPaolo Bonzini 	}
3649c50d8ae3SPaolo Bonzini 
3650c50d8ae3SPaolo Bonzini 	return ret;
3651c50d8ae3SPaolo Bonzini }
3652c50d8ae3SPaolo Bonzini 
36532e65e842SDavid Matlack static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
365486938ab6SDavid Matlack 			    u8 level)
3655c50d8ae3SPaolo Bonzini {
36562e65e842SDavid Matlack 	union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3657c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
36588123f265SSean Christopherson 
36592e65e842SDavid Matlack 	role.level = level;
36602e65e842SDavid Matlack 	role.quadrant = quadrant;
36612e65e842SDavid Matlack 
36627f497775SDavid Matlack 	WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
36637f497775SDavid Matlack 	WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
36647f497775SDavid Matlack 
366587654643SDavid Matlack 	sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
36668123f265SSean Christopherson 	++sp->root_count;
36678123f265SSean Christopherson 
36688123f265SSean Christopherson 	return __pa(sp->spt);
36698123f265SSean Christopherson }
36708123f265SSean Christopherson 
36718123f265SSean Christopherson static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
36728123f265SSean Christopherson {
3673b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3674a972e29cSPaolo Bonzini 	u8 shadow_root_level = mmu->root_role.level;
36758123f265SSean Christopherson 	hpa_t root;
3676c50d8ae3SPaolo Bonzini 	unsigned i;
36774a38162eSPaolo Bonzini 	int r;
36784a38162eSPaolo Bonzini 
36794a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
36804a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
36814a38162eSPaolo Bonzini 	if (r < 0)
36824a38162eSPaolo Bonzini 		goto out_unlock;
3683c50d8ae3SPaolo Bonzini 
36841f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
368502c00b3aSBen Gardon 		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
3686b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
368702c00b3aSBen Gardon 	} else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
368886938ab6SDavid Matlack 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3689b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
36908123f265SSean Christopherson 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
36914a38162eSPaolo Bonzini 		if (WARN_ON_ONCE(!mmu->pae_root)) {
36924a38162eSPaolo Bonzini 			r = -EIO;
36934a38162eSPaolo Bonzini 			goto out_unlock;
36944a38162eSPaolo Bonzini 		}
369573ad1606SSean Christopherson 
3696c50d8ae3SPaolo Bonzini 		for (i = 0; i < 4; ++i) {
3697c834e5e4SSean Christopherson 			WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3698c50d8ae3SPaolo Bonzini 
36997f497775SDavid Matlack 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
37002e65e842SDavid Matlack 					      PT32_ROOT_LEVEL);
370117e368d9SSean Christopherson 			mmu->pae_root[i] = root | PT_PRESENT_MASK |
3702d2263de1SYuan Yao 					   shadow_me_value;
3703c50d8ae3SPaolo Bonzini 		}
3704b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
370573ad1606SSean Christopherson 	} else {
370673ad1606SSean Christopherson 		WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
37074a38162eSPaolo Bonzini 		r = -EIO;
37084a38162eSPaolo Bonzini 		goto out_unlock;
370973ad1606SSean Christopherson 	}
37103651c7fcSSean Christopherson 
3711b9e5603cSPaolo Bonzini 	/* root.pgd is ignored for direct MMUs. */
3712b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
37134a38162eSPaolo Bonzini out_unlock:
37144a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
37154a38162eSPaolo Bonzini 	return r;
3716c50d8ae3SPaolo Bonzini }
3717c50d8ae3SPaolo Bonzini 
37181e76a3ceSDavid Stevens static int mmu_first_shadow_root_alloc(struct kvm *kvm)
37191e76a3ceSDavid Stevens {
37201e76a3ceSDavid Stevens 	struct kvm_memslots *slots;
37211e76a3ceSDavid Stevens 	struct kvm_memory_slot *slot;
3722a54d8066SMaciej S. Szmigiero 	int r = 0, i, bkt;
37231e76a3ceSDavid Stevens 
37241e76a3ceSDavid Stevens 	/*
37251e76a3ceSDavid Stevens 	 * Check if this is the first shadow root being allocated before
37261e76a3ceSDavid Stevens 	 * taking the lock.
37271e76a3ceSDavid Stevens 	 */
37281e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
37291e76a3ceSDavid Stevens 		return 0;
37301e76a3ceSDavid Stevens 
37311e76a3ceSDavid Stevens 	mutex_lock(&kvm->slots_arch_lock);
37321e76a3ceSDavid Stevens 
37331e76a3ceSDavid Stevens 	/* Recheck, under the lock, whether this is the first shadow root. */
37341e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
37351e76a3ceSDavid Stevens 		goto out_unlock;
37361e76a3ceSDavid Stevens 
37371e76a3ceSDavid Stevens 	/*
37381e76a3ceSDavid Stevens 	 * Check if anything actually needs to be allocated, e.g. all metadata
37391e76a3ceSDavid Stevens 	 * will be allocated upfront if TDP is disabled.
37401e76a3ceSDavid Stevens 	 */
37411e76a3ceSDavid Stevens 	if (kvm_memslots_have_rmaps(kvm) &&
37421e76a3ceSDavid Stevens 	    kvm_page_track_write_tracking_enabled(kvm))
37431e76a3ceSDavid Stevens 		goto out_success;
37441e76a3ceSDavid Stevens 
37451e76a3ceSDavid Stevens 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
37461e76a3ceSDavid Stevens 		slots = __kvm_memslots(kvm, i);
3747a54d8066SMaciej S. Szmigiero 		kvm_for_each_memslot(slot, bkt, slots) {
37481e76a3ceSDavid Stevens 			/*
37491e76a3ceSDavid Stevens 			 * Both of these functions are no-ops if the target is
37501e76a3ceSDavid Stevens 			 * already allocated, so unconditionally calling both
37511e76a3ceSDavid Stevens 			 * is safe.  Intentionally do NOT free allocations on
37521e76a3ceSDavid Stevens 			 * failure to avoid having to track which allocations
37531e76a3ceSDavid Stevens 			 * were made now versus when the memslot was created.
37541e76a3ceSDavid Stevens 			 * The metadata is guaranteed to be freed when the slot
37551e76a3ceSDavid Stevens 			 * is freed, and will be kept/used if userspace retries
37561e76a3ceSDavid Stevens 			 * KVM_RUN instead of killing the VM.
37571e76a3ceSDavid Stevens 			 */
37581e76a3ceSDavid Stevens 			r = memslot_rmap_alloc(slot, slot->npages);
37591e76a3ceSDavid Stevens 			if (r)
37601e76a3ceSDavid Stevens 				goto out_unlock;
37611e76a3ceSDavid Stevens 			r = kvm_page_track_write_tracking_alloc(slot);
37621e76a3ceSDavid Stevens 			if (r)
37631e76a3ceSDavid Stevens 				goto out_unlock;
37641e76a3ceSDavid Stevens 		}
37651e76a3ceSDavid Stevens 	}
37661e76a3ceSDavid Stevens 
37671e76a3ceSDavid Stevens 	/*
37681e76a3ceSDavid Stevens 	 * Ensure that shadow_root_allocated becomes true strictly after
37691e76a3ceSDavid Stevens 	 * all the related pointers are set.
37701e76a3ceSDavid Stevens 	 */
37711e76a3ceSDavid Stevens out_success:
37721e76a3ceSDavid Stevens 	smp_store_release(&kvm->arch.shadow_root_allocated, true);
37731e76a3ceSDavid Stevens 
37741e76a3ceSDavid Stevens out_unlock:
37751e76a3ceSDavid Stevens 	mutex_unlock(&kvm->slots_arch_lock);
37761e76a3ceSDavid Stevens 	return r;
37771e76a3ceSDavid Stevens }
37781e76a3ceSDavid Stevens 
3779c50d8ae3SPaolo Bonzini static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3780c50d8ae3SPaolo Bonzini {
3781b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
37826e0918aeSSean Christopherson 	u64 pdptrs[4], pm_mask;
3783be01e8e2SSean Christopherson 	gfn_t root_gfn, root_pgd;
37847f497775SDavid Matlack 	int quadrant, i, r;
37858123f265SSean Christopherson 	hpa_t root;
3786c50d8ae3SPaolo Bonzini 
37872fdcc1b3SPaolo Bonzini 	root_pgd = kvm_mmu_get_guest_pgd(vcpu, mmu);
3788be01e8e2SSean Christopherson 	root_gfn = root_pgd >> PAGE_SHIFT;
3789c50d8ae3SPaolo Bonzini 
3790c50d8ae3SPaolo Bonzini 	if (mmu_check_root(vcpu, root_gfn))
3791c50d8ae3SPaolo Bonzini 		return 1;
3792c50d8ae3SPaolo Bonzini 
3793c50d8ae3SPaolo Bonzini 	/*
37944a38162eSPaolo Bonzini 	 * On SVM, reading PDPTRs might access guest memory, which might fault
37954a38162eSPaolo Bonzini 	 * and thus might sleep.  Grab the PDPTRs before acquiring mmu_lock.
37964a38162eSPaolo Bonzini 	 */
37974d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
37986e0918aeSSean Christopherson 		for (i = 0; i < 4; ++i) {
37996e0918aeSSean Christopherson 			pdptrs[i] = mmu->get_pdptr(vcpu, i);
38006e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK))
38016e0918aeSSean Christopherson 				continue;
38026e0918aeSSean Christopherson 
38036e0918aeSSean Christopherson 			if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
38046e0918aeSSean Christopherson 				return 1;
38056e0918aeSSean Christopherson 		}
38066e0918aeSSean Christopherson 	}
38076e0918aeSSean Christopherson 
38081e76a3ceSDavid Stevens 	r = mmu_first_shadow_root_alloc(vcpu->kvm);
3809d501f747SBen Gardon 	if (r)
3810d501f747SBen Gardon 		return r;
3811d501f747SBen Gardon 
38124a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
38134a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
38144a38162eSPaolo Bonzini 	if (r < 0)
38154a38162eSPaolo Bonzini 		goto out_unlock;
38164a38162eSPaolo Bonzini 
3817c50d8ae3SPaolo Bonzini 	/*
3818c50d8ae3SPaolo Bonzini 	 * Do we shadow a long mode page table? If so we need to
3819c50d8ae3SPaolo Bonzini 	 * write-protect the guests page table root.
3820c50d8ae3SPaolo Bonzini 	 */
38214d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
38228123f265SSean Christopherson 		root = mmu_alloc_root(vcpu, root_gfn, 0,
382386938ab6SDavid Matlack 				      mmu->root_role.level);
3824b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
3825be01e8e2SSean Christopherson 		goto set_root_pgd;
3826c50d8ae3SPaolo Bonzini 	}
3827c50d8ae3SPaolo Bonzini 
38284a38162eSPaolo Bonzini 	if (WARN_ON_ONCE(!mmu->pae_root)) {
38294a38162eSPaolo Bonzini 		r = -EIO;
38304a38162eSPaolo Bonzini 		goto out_unlock;
38314a38162eSPaolo Bonzini 	}
383273ad1606SSean Christopherson 
3833c50d8ae3SPaolo Bonzini 	/*
3834c50d8ae3SPaolo Bonzini 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3835c50d8ae3SPaolo Bonzini 	 * or a PAE 3-level page table. In either case we need to be aware that
3836c50d8ae3SPaolo Bonzini 	 * the shadow page table may be a PAE or a long mode page table.
3837c50d8ae3SPaolo Bonzini 	 */
3838e54f1ff2SKai Huang 	pm_mask = PT_PRESENT_MASK | shadow_me_value;
3839a972e29cSPaolo Bonzini 	if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3840c50d8ae3SPaolo Bonzini 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3841c50d8ae3SPaolo Bonzini 
384203ca4589SSean Christopherson 		if (WARN_ON_ONCE(!mmu->pml4_root)) {
38434a38162eSPaolo Bonzini 			r = -EIO;
38444a38162eSPaolo Bonzini 			goto out_unlock;
38454a38162eSPaolo Bonzini 		}
384603ca4589SSean Christopherson 		mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3847cb0f722aSWei Huang 
3848a972e29cSPaolo Bonzini 		if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3849cb0f722aSWei Huang 			if (WARN_ON_ONCE(!mmu->pml5_root)) {
3850cb0f722aSWei Huang 				r = -EIO;
3851cb0f722aSWei Huang 				goto out_unlock;
3852cb0f722aSWei Huang 			}
3853cb0f722aSWei Huang 			mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3854cb0f722aSWei Huang 		}
385504d45551SSean Christopherson 	}
385604d45551SSean Christopherson 
3857c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3858c834e5e4SSean Christopherson 		WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
38596e6ec584SSean Christopherson 
38604d25502aSPaolo Bonzini 		if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
38616e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3862c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3863c50d8ae3SPaolo Bonzini 				continue;
3864c50d8ae3SPaolo Bonzini 			}
38656e0918aeSSean Christopherson 			root_gfn = pdptrs[i] >> PAGE_SHIFT;
3866c50d8ae3SPaolo Bonzini 		}
3867c50d8ae3SPaolo Bonzini 
38687f497775SDavid Matlack 		/*
38697f497775SDavid Matlack 		 * If shadowing 32-bit non-PAE page tables, each PAE page
38707f497775SDavid Matlack 		 * directory maps one quarter of the guest's non-PAE page
38717f497775SDavid Matlack 		 * directory. Othwerise each PAE page direct shadows one guest
38727f497775SDavid Matlack 		 * PAE page directory so that quadrant should be 0.
38737f497775SDavid Matlack 		 */
38747f497775SDavid Matlack 		quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
38757f497775SDavid Matlack 
38767f497775SDavid Matlack 		root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3877b37233c9SSean Christopherson 		mmu->pae_root[i] = root | pm_mask;
3878c50d8ae3SPaolo Bonzini 	}
3879c50d8ae3SPaolo Bonzini 
3880a972e29cSPaolo Bonzini 	if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3881b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml5_root);
3882a972e29cSPaolo Bonzini 	else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3883b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml4_root);
3884ba0a194fSSean Christopherson 	else
3885b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
3886c50d8ae3SPaolo Bonzini 
3887be01e8e2SSean Christopherson set_root_pgd:
3888b9e5603cSPaolo Bonzini 	mmu->root.pgd = root_pgd;
38894a38162eSPaolo Bonzini out_unlock:
38904a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
3891c50d8ae3SPaolo Bonzini 
3892c6c937d6SLike Xu 	return r;
3893c50d8ae3SPaolo Bonzini }
3894c50d8ae3SPaolo Bonzini 
3895748e52b9SSean Christopherson static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3896c50d8ae3SPaolo Bonzini {
3897748e52b9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3898a972e29cSPaolo Bonzini 	bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3899cb0f722aSWei Huang 	u64 *pml5_root = NULL;
3900cb0f722aSWei Huang 	u64 *pml4_root = NULL;
3901cb0f722aSWei Huang 	u64 *pae_root;
3902748e52b9SSean Christopherson 
3903748e52b9SSean Christopherson 	/*
3904748e52b9SSean Christopherson 	 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3905748e52b9SSean Christopherson 	 * tables are allocated and initialized at root creation as there is no
3906748e52b9SSean Christopherson 	 * equivalent level in the guest's NPT to shadow.  Allocate the tables
3907748e52b9SSean Christopherson 	 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3908748e52b9SSean Christopherson 	 */
3909347a0d0dSPaolo Bonzini 	if (mmu->root_role.direct ||
3910347a0d0dSPaolo Bonzini 	    mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3911a972e29cSPaolo Bonzini 	    mmu->root_role.level < PT64_ROOT_4LEVEL)
3912748e52b9SSean Christopherson 		return 0;
3913748e52b9SSean Christopherson 
3914a717a780SSean Christopherson 	/*
3915a717a780SSean Christopherson 	 * NPT, the only paging mode that uses this horror, uses a fixed number
3916a717a780SSean Christopherson 	 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3917a717a780SSean Christopherson 	 * all MMus are 5-level.  Thus, this can safely require that pml5_root
3918a717a780SSean Christopherson 	 * is allocated if the other roots are valid and pml5 is needed, as any
3919a717a780SSean Christopherson 	 * prior MMU would also have required pml5.
3920a717a780SSean Christopherson 	 */
3921a717a780SSean Christopherson 	if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3922748e52b9SSean Christopherson 		return 0;
3923748e52b9SSean Christopherson 
3924748e52b9SSean Christopherson 	/*
3925748e52b9SSean Christopherson 	 * The special roots should always be allocated in concert.  Yell and
3926748e52b9SSean Christopherson 	 * bail if KVM ends up in a state where only one of the roots is valid.
3927748e52b9SSean Christopherson 	 */
3928cb0f722aSWei Huang 	if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3929a717a780SSean Christopherson 			 (need_pml5 && mmu->pml5_root)))
3930748e52b9SSean Christopherson 		return -EIO;
3931748e52b9SSean Christopherson 
39324a98623dSSean Christopherson 	/*
39334a98623dSSean Christopherson 	 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
39344a98623dSSean Christopherson 	 * doesn't need to be decrypted.
39354a98623dSSean Christopherson 	 */
3936748e52b9SSean Christopherson 	pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3937748e52b9SSean Christopherson 	if (!pae_root)
3938748e52b9SSean Christopherson 		return -ENOMEM;
3939748e52b9SSean Christopherson 
3940cb0f722aSWei Huang #ifdef CONFIG_X86_64
394103ca4589SSean Christopherson 	pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3942cb0f722aSWei Huang 	if (!pml4_root)
3943cb0f722aSWei Huang 		goto err_pml4;
3944cb0f722aSWei Huang 
3945a717a780SSean Christopherson 	if (need_pml5) {
3946cb0f722aSWei Huang 		pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3947cb0f722aSWei Huang 		if (!pml5_root)
3948cb0f722aSWei Huang 			goto err_pml5;
3949748e52b9SSean Christopherson 	}
3950cb0f722aSWei Huang #endif
3951748e52b9SSean Christopherson 
3952748e52b9SSean Christopherson 	mmu->pae_root = pae_root;
395303ca4589SSean Christopherson 	mmu->pml4_root = pml4_root;
3954cb0f722aSWei Huang 	mmu->pml5_root = pml5_root;
3955748e52b9SSean Christopherson 
3956748e52b9SSean Christopherson 	return 0;
3957cb0f722aSWei Huang 
3958cb0f722aSWei Huang #ifdef CONFIG_X86_64
3959cb0f722aSWei Huang err_pml5:
3960cb0f722aSWei Huang 	free_page((unsigned long)pml4_root);
3961cb0f722aSWei Huang err_pml4:
3962cb0f722aSWei Huang 	free_page((unsigned long)pae_root);
3963cb0f722aSWei Huang 	return -ENOMEM;
3964cb0f722aSWei Huang #endif
3965c50d8ae3SPaolo Bonzini }
3966c50d8ae3SPaolo Bonzini 
3967264d3dc1SLai Jiangshan static bool is_unsync_root(hpa_t root)
3968264d3dc1SLai Jiangshan {
3969264d3dc1SLai Jiangshan 	struct kvm_mmu_page *sp;
3970264d3dc1SLai Jiangshan 
397161b05a9fSLai Jiangshan 	if (!VALID_PAGE(root))
397261b05a9fSLai Jiangshan 		return false;
397361b05a9fSLai Jiangshan 
3974264d3dc1SLai Jiangshan 	/*
3975264d3dc1SLai Jiangshan 	 * The read barrier orders the CPU's read of SPTE.W during the page table
3976264d3dc1SLai Jiangshan 	 * walk before the reads of sp->unsync/sp->unsync_children here.
3977264d3dc1SLai Jiangshan 	 *
3978264d3dc1SLai Jiangshan 	 * Even if another CPU was marking the SP as unsync-ed simultaneously,
3979264d3dc1SLai Jiangshan 	 * any guest page table changes are not guaranteed to be visible anyway
3980264d3dc1SLai Jiangshan 	 * until this VCPU issues a TLB flush strictly after those changes are
3981264d3dc1SLai Jiangshan 	 * made.  We only need to ensure that the other CPU sets these flags
3982264d3dc1SLai Jiangshan 	 * before any actual changes to the page tables are made.  The comments
3983264d3dc1SLai Jiangshan 	 * in mmu_try_to_unsync_pages() describe what could go wrong if this
3984264d3dc1SLai Jiangshan 	 * requirement isn't satisfied.
3985264d3dc1SLai Jiangshan 	 */
3986264d3dc1SLai Jiangshan 	smp_rmb();
3987c5f2d564SSean Christopherson 	sp = root_to_sp(root);
39885d6a3221SSean Christopherson 
39895d6a3221SSean Christopherson 	/*
39905d6a3221SSean Christopherson 	 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
39915d6a3221SSean Christopherson 	 * PDPTEs for a given PAE root need to be synchronized individually.
39925d6a3221SSean Christopherson 	 */
39935d6a3221SSean Christopherson 	if (WARN_ON_ONCE(!sp))
39945d6a3221SSean Christopherson 		return false;
39955d6a3221SSean Christopherson 
3996264d3dc1SLai Jiangshan 	if (sp->unsync || sp->unsync_children)
3997264d3dc1SLai Jiangshan 		return true;
3998264d3dc1SLai Jiangshan 
3999264d3dc1SLai Jiangshan 	return false;
4000264d3dc1SLai Jiangshan }
4001264d3dc1SLai Jiangshan 
4002c50d8ae3SPaolo Bonzini void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
4003c50d8ae3SPaolo Bonzini {
4004c50d8ae3SPaolo Bonzini 	int i;
4005c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
4006c50d8ae3SPaolo Bonzini 
4007347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
4008c50d8ae3SPaolo Bonzini 		return;
4009c50d8ae3SPaolo Bonzini 
4010b9e5603cSPaolo Bonzini 	if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
4011c50d8ae3SPaolo Bonzini 		return;
4012c50d8ae3SPaolo Bonzini 
4013c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4014c50d8ae3SPaolo Bonzini 
40154d25502aSPaolo Bonzini 	if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
4016b9e5603cSPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->root.hpa;
4017c50d8ae3SPaolo Bonzini 
4018264d3dc1SLai Jiangshan 		if (!is_unsync_root(root))
4019c50d8ae3SPaolo Bonzini 			return;
4020c50d8ae3SPaolo Bonzini 
4021c5f2d564SSean Christopherson 		sp = root_to_sp(root);
4022c5f2d564SSean Christopherson 
4023531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
402465855ed8SLai Jiangshan 		mmu_sync_children(vcpu, sp, true);
4025531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
4026c50d8ae3SPaolo Bonzini 		return;
4027c50d8ae3SPaolo Bonzini 	}
4028c50d8ae3SPaolo Bonzini 
4029531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
4030c50d8ae3SPaolo Bonzini 
4031c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
4032c50d8ae3SPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->pae_root[i];
4033c50d8ae3SPaolo Bonzini 
4034c834e5e4SSean Christopherson 		if (IS_VALID_PAE_ROOT(root)) {
40355e3edd7eSSean Christopherson 			sp = spte_to_child_sp(root);
403665855ed8SLai Jiangshan 			mmu_sync_children(vcpu, sp, true);
4037c50d8ae3SPaolo Bonzini 		}
4038c50d8ae3SPaolo Bonzini 	}
4039c50d8ae3SPaolo Bonzini 
4040531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
4041c50d8ae3SPaolo Bonzini }
4042c50d8ae3SPaolo Bonzini 
404361b05a9fSLai Jiangshan void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
404461b05a9fSLai Jiangshan {
404561b05a9fSLai Jiangshan 	unsigned long roots_to_free = 0;
404661b05a9fSLai Jiangshan 	int i;
404761b05a9fSLai Jiangshan 
404861b05a9fSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
404961b05a9fSLai Jiangshan 		if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
405061b05a9fSLai Jiangshan 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
405161b05a9fSLai Jiangshan 
405261b05a9fSLai Jiangshan 	/* sync prev_roots by simply freeing them */
40530c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
405461b05a9fSLai Jiangshan }
405561b05a9fSLai Jiangshan 
40561f5a21eeSLai Jiangshan static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
40575b22bbe7SLai Jiangshan 				  gpa_t vaddr, u64 access,
4058c50d8ae3SPaolo Bonzini 				  struct x86_exception *exception)
4059c50d8ae3SPaolo Bonzini {
4060c50d8ae3SPaolo Bonzini 	if (exception)
4061c50d8ae3SPaolo Bonzini 		exception->error_code = 0;
4062c59a0f57SLai Jiangshan 	return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
4063c50d8ae3SPaolo Bonzini }
4064c50d8ae3SPaolo Bonzini 
4065c50d8ae3SPaolo Bonzini static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4066c50d8ae3SPaolo Bonzini {
4067c50d8ae3SPaolo Bonzini 	/*
4068c50d8ae3SPaolo Bonzini 	 * A nested guest cannot use the MMIO cache if it is using nested
4069c50d8ae3SPaolo Bonzini 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4070c50d8ae3SPaolo Bonzini 	 */
4071c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
4072c50d8ae3SPaolo Bonzini 		return false;
4073c50d8ae3SPaolo Bonzini 
4074c50d8ae3SPaolo Bonzini 	if (direct)
4075c50d8ae3SPaolo Bonzini 		return vcpu_match_mmio_gpa(vcpu, addr);
4076c50d8ae3SPaolo Bonzini 
4077c50d8ae3SPaolo Bonzini 	return vcpu_match_mmio_gva(vcpu, addr);
4078c50d8ae3SPaolo Bonzini }
4079c50d8ae3SPaolo Bonzini 
408095fb5b02SBen Gardon /*
408195fb5b02SBen Gardon  * Return the level of the lowest level SPTE added to sptes.
408295fb5b02SBen Gardon  * That SPTE may be non-present.
4083c5c8c7c5SDavid Matlack  *
4084c5c8c7c5SDavid Matlack  * Must be called between walk_shadow_page_lockless_{begin,end}.
408595fb5b02SBen Gardon  */
408639b4d43eSSean Christopherson static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4087c50d8ae3SPaolo Bonzini {
4088c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
40892aa07893SSean Christopherson 	int leaf = -1;
409095fb5b02SBen Gardon 	u64 spte;
4091c50d8ae3SPaolo Bonzini 
409239b4d43eSSean Christopherson 	for (shadow_walk_init(&iterator, vcpu, addr),
409339b4d43eSSean Christopherson 	     *root_level = iterator.level;
4094c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&iterator);
4095c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&iterator, spte)) {
409695fb5b02SBen Gardon 		leaf = iterator.level;
4097c50d8ae3SPaolo Bonzini 		spte = mmu_spte_get_lockless(iterator.sptep);
4098c50d8ae3SPaolo Bonzini 
4099dde81f94SSean Christopherson 		sptes[leaf] = spte;
410095fb5b02SBen Gardon 	}
410195fb5b02SBen Gardon 
410295fb5b02SBen Gardon 	return leaf;
410395fb5b02SBen Gardon }
410495fb5b02SBen Gardon 
41059aa41879SSean Christopherson /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
410695fb5b02SBen Gardon static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
410795fb5b02SBen Gardon {
4108dde81f94SSean Christopherson 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
410995fb5b02SBen Gardon 	struct rsvd_bits_validate *rsvd_check;
411039b4d43eSSean Christopherson 	int root, leaf, level;
411195fb5b02SBen Gardon 	bool reserved = false;
411295fb5b02SBen Gardon 
4113c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_begin(vcpu);
4114c5c8c7c5SDavid Matlack 
411578fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu))
411639b4d43eSSean Christopherson 		leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
411795fb5b02SBen Gardon 	else
411839b4d43eSSean Christopherson 		leaf = get_walk(vcpu, addr, sptes, &root);
411995fb5b02SBen Gardon 
4120c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_end(vcpu);
4121c5c8c7c5SDavid Matlack 
41222aa07893SSean Christopherson 	if (unlikely(leaf < 0)) {
41232aa07893SSean Christopherson 		*sptep = 0ull;
41242aa07893SSean Christopherson 		return reserved;
41252aa07893SSean Christopherson 	}
41262aa07893SSean Christopherson 
41279aa41879SSean Christopherson 	*sptep = sptes[leaf];
41289aa41879SSean Christopherson 
41299aa41879SSean Christopherson 	/*
41309aa41879SSean Christopherson 	 * Skip reserved bits checks on the terminal leaf if it's not a valid
41319aa41879SSean Christopherson 	 * SPTE.  Note, this also (intentionally) skips MMIO SPTEs, which, by
41329aa41879SSean Christopherson 	 * design, always have reserved bits set.  The purpose of the checks is
41339aa41879SSean Christopherson 	 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
41349aa41879SSean Christopherson 	 */
41359aa41879SSean Christopherson 	if (!is_shadow_present_pte(sptes[leaf]))
41369aa41879SSean Christopherson 		leaf++;
413795fb5b02SBen Gardon 
413895fb5b02SBen Gardon 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
413995fb5b02SBen Gardon 
41409aa41879SSean Christopherson 	for (level = root; level >= leaf; level--)
4141961f8445SSean Christopherson 		reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4142c50d8ae3SPaolo Bonzini 
4143c50d8ae3SPaolo Bonzini 	if (reserved) {
4144bb4cdf3aSSean Christopherson 		pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4145c50d8ae3SPaolo Bonzini 		       __func__, addr);
414695fb5b02SBen Gardon 		for (level = root; level >= leaf; level--)
4147bb4cdf3aSSean Christopherson 			pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4148bb4cdf3aSSean Christopherson 			       sptes[level], level,
4149961f8445SSean Christopherson 			       get_rsvd_bits(rsvd_check, sptes[level], level));
4150c50d8ae3SPaolo Bonzini 	}
4151ddce6208SSean Christopherson 
4152c50d8ae3SPaolo Bonzini 	return reserved;
4153c50d8ae3SPaolo Bonzini }
4154c50d8ae3SPaolo Bonzini 
4155c50d8ae3SPaolo Bonzini static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4156c50d8ae3SPaolo Bonzini {
4157c50d8ae3SPaolo Bonzini 	u64 spte;
4158c50d8ae3SPaolo Bonzini 	bool reserved;
4159c50d8ae3SPaolo Bonzini 
4160c50d8ae3SPaolo Bonzini 	if (mmio_info_in_cache(vcpu, addr, direct))
4161c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4162c50d8ae3SPaolo Bonzini 
416395fb5b02SBen Gardon 	reserved = get_mmio_spte(vcpu, addr, &spte);
416420ba462dSSean Christopherson 	if (WARN_ON_ONCE(reserved))
4165c50d8ae3SPaolo Bonzini 		return -EINVAL;
4166c50d8ae3SPaolo Bonzini 
4167c50d8ae3SPaolo Bonzini 	if (is_mmio_spte(spte)) {
4168c50d8ae3SPaolo Bonzini 		gfn_t gfn = get_mmio_spte_gfn(spte);
41690a2b64c5SBen Gardon 		unsigned int access = get_mmio_spte_access(spte);
4170c50d8ae3SPaolo Bonzini 
4171c50d8ae3SPaolo Bonzini 		if (!check_mmio_spte(vcpu, spte))
4172c50d8ae3SPaolo Bonzini 			return RET_PF_INVALID;
4173c50d8ae3SPaolo Bonzini 
4174c50d8ae3SPaolo Bonzini 		if (direct)
4175c50d8ae3SPaolo Bonzini 			addr = 0;
4176c50d8ae3SPaolo Bonzini 
4177c50d8ae3SPaolo Bonzini 		trace_handle_mmio_page_fault(addr, gfn, access);
4178c50d8ae3SPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4179c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4180c50d8ae3SPaolo Bonzini 	}
4181c50d8ae3SPaolo Bonzini 
4182c50d8ae3SPaolo Bonzini 	/*
4183c50d8ae3SPaolo Bonzini 	 * If the page table is zapped by other cpus, let CPU fault again on
4184c50d8ae3SPaolo Bonzini 	 * the address.
4185c50d8ae3SPaolo Bonzini 	 */
4186c50d8ae3SPaolo Bonzini 	return RET_PF_RETRY;
4187c50d8ae3SPaolo Bonzini }
4188c50d8ae3SPaolo Bonzini 
4189c50d8ae3SPaolo Bonzini static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4190b8a5d551SPaolo Bonzini 					 struct kvm_page_fault *fault)
4191c50d8ae3SPaolo Bonzini {
4192b8a5d551SPaolo Bonzini 	if (unlikely(fault->rsvd))
4193c50d8ae3SPaolo Bonzini 		return false;
4194c50d8ae3SPaolo Bonzini 
4195b8a5d551SPaolo Bonzini 	if (!fault->present || !fault->write)
4196c50d8ae3SPaolo Bonzini 		return false;
4197c50d8ae3SPaolo Bonzini 
4198c50d8ae3SPaolo Bonzini 	/*
4199c50d8ae3SPaolo Bonzini 	 * guest is writing the page which is write tracked which can
4200c50d8ae3SPaolo Bonzini 	 * not be fixed by page fault handler.
4201c50d8ae3SPaolo Bonzini 	 */
42027b574863SSean Christopherson 	if (kvm_gfn_is_write_tracked(vcpu->kvm, fault->slot, fault->gfn))
4203c50d8ae3SPaolo Bonzini 		return true;
4204c50d8ae3SPaolo Bonzini 
4205c50d8ae3SPaolo Bonzini 	return false;
4206c50d8ae3SPaolo Bonzini }
4207c50d8ae3SPaolo Bonzini 
4208c50d8ae3SPaolo Bonzini static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4209c50d8ae3SPaolo Bonzini {
4210c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
4211c50d8ae3SPaolo Bonzini 	u64 spte;
4212c50d8ae3SPaolo Bonzini 
4213c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
42143e44dce4SLai Jiangshan 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4215c50d8ae3SPaolo Bonzini 		clear_sp_write_flooding_count(iterator.sptep);
4216c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
4217c50d8ae3SPaolo Bonzini }
4218c50d8ae3SPaolo Bonzini 
42196f3c1fc5SLiang Zhang static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
42206f3c1fc5SLiang Zhang {
42216f3c1fc5SLiang Zhang 	/* make sure the token value is not 0 */
42226f3c1fc5SLiang Zhang 	u32 id = vcpu->arch.apf.id;
42236f3c1fc5SLiang Zhang 
42246f3c1fc5SLiang Zhang 	if (id << 12 == 0)
42256f3c1fc5SLiang Zhang 		vcpu->arch.apf.id = 1;
42266f3c1fc5SLiang Zhang 
42276f3c1fc5SLiang Zhang 	return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
42286f3c1fc5SLiang Zhang }
42296f3c1fc5SLiang Zhang 
4230e8c22266SVitaly Kuznetsov static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
42319f1a8526SSean Christopherson 				    gfn_t gfn)
4232c50d8ae3SPaolo Bonzini {
4233c50d8ae3SPaolo Bonzini 	struct kvm_arch_async_pf arch;
4234c50d8ae3SPaolo Bonzini 
42356f3c1fc5SLiang Zhang 	arch.token = alloc_apf_token(vcpu);
4236c50d8ae3SPaolo Bonzini 	arch.gfn = gfn;
4237347a0d0dSPaolo Bonzini 	arch.direct_map = vcpu->arch.mmu->root_role.direct;
42382fdcc1b3SPaolo Bonzini 	arch.cr3 = kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu);
4239c50d8ae3SPaolo Bonzini 
42409f1a8526SSean Christopherson 	return kvm_setup_async_pf(vcpu, cr2_or_gpa,
42419f1a8526SSean Christopherson 				  kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4242c50d8ae3SPaolo Bonzini }
4243c50d8ae3SPaolo Bonzini 
42448a009d5bSSean Christopherson void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
42458a009d5bSSean Christopherson {
42468a009d5bSSean Christopherson 	int r;
42478a009d5bSSean Christopherson 
42488a009d5bSSean Christopherson 	if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
42498a009d5bSSean Christopherson 	      work->wakeup_all)
42508a009d5bSSean Christopherson 		return;
42518a009d5bSSean Christopherson 
42528a009d5bSSean Christopherson 	r = kvm_mmu_reload(vcpu);
42538a009d5bSSean Christopherson 	if (unlikely(r))
42548a009d5bSSean Christopherson 		return;
42558a009d5bSSean Christopherson 
42568a009d5bSSean Christopherson 	if (!vcpu->arch.mmu->root_role.direct &&
42572fdcc1b3SPaolo Bonzini 	      work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
42588a009d5bSSean Christopherson 		return;
42598a009d5bSSean Christopherson 
4260258d985fSSean Christopherson 	kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true, NULL);
42618a009d5bSSean Christopherson }
42628a009d5bSSean Christopherson 
4263ba6e3fe2SDavid Matlack static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4264c50d8ae3SPaolo Bonzini {
4265e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
4266c50d8ae3SPaolo Bonzini 	bool async;
4267c50d8ae3SPaolo Bonzini 
4268e0c37868SSean Christopherson 	/*
4269e0c37868SSean Christopherson 	 * Retry the page fault if the gfn hit a memslot that is being deleted
4270e0c37868SSean Christopherson 	 * or moved.  This ensures any existing SPTEs for the old memslot will
4271e0c37868SSean Christopherson 	 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4272e0c37868SSean Christopherson 	 */
4273e0c37868SSean Christopherson 	if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
42745276c616SSean Christopherson 		return RET_PF_RETRY;
4275e0c37868SSean Christopherson 
42769cc13d60SMaxim Levitsky 	if (!kvm_is_visible_memslot(slot)) {
4277c36b7150SPaolo Bonzini 		/* Don't expose private memslots to L2. */
42789cc13d60SMaxim Levitsky 		if (is_guest_mode(vcpu)) {
4279e710c5f6SDavid Matlack 			fault->slot = NULL;
42803647cd04SPaolo Bonzini 			fault->pfn = KVM_PFN_NOSLOT;
42813647cd04SPaolo Bonzini 			fault->map_writable = false;
42825276c616SSean Christopherson 			return RET_PF_CONTINUE;
4283c50d8ae3SPaolo Bonzini 		}
42849cc13d60SMaxim Levitsky 		/*
42859cc13d60SMaxim Levitsky 		 * If the APIC access page exists but is disabled, go directly
42869cc13d60SMaxim Levitsky 		 * to emulation without caching the MMIO access or creating a
42879cc13d60SMaxim Levitsky 		 * MMIO SPTE.  That way the cache doesn't need to be purged
42889cc13d60SMaxim Levitsky 		 * when the AVIC is re-enabled.
42899cc13d60SMaxim Levitsky 		 */
42909cc13d60SMaxim Levitsky 		if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
42915276c616SSean Christopherson 		    !kvm_apicv_activated(vcpu->kvm))
42925276c616SSean Christopherson 			return RET_PF_EMULATE;
42939cc13d60SMaxim Levitsky 	}
4294c50d8ae3SPaolo Bonzini 
4295c50d8ae3SPaolo Bonzini 	async = false;
4296c8b88b33SPeter Xu 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, false, &async,
42973647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
42983647cd04SPaolo Bonzini 					  &fault->hva);
4299c50d8ae3SPaolo Bonzini 	if (!async)
43005276c616SSean Christopherson 		return RET_PF_CONTINUE; /* *pfn has correct page already */
4301c50d8ae3SPaolo Bonzini 
43022839180cSPaolo Bonzini 	if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
43033647cd04SPaolo Bonzini 		trace_kvm_try_async_get_page(fault->addr, fault->gfn);
43043647cd04SPaolo Bonzini 		if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
43051685c0f3SMingwei Zhang 			trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4306c50d8ae3SPaolo Bonzini 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
43075276c616SSean Christopherson 			return RET_PF_RETRY;
43085276c616SSean Christopherson 		} else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn)) {
43095276c616SSean Christopherson 			return RET_PF_RETRY;
43105276c616SSean Christopherson 		}
4311c50d8ae3SPaolo Bonzini 	}
4312c50d8ae3SPaolo Bonzini 
431376657687SPeter Xu 	/*
431476657687SPeter Xu 	 * Allow gup to bail on pending non-fatal signals when it's also allowed
431576657687SPeter Xu 	 * to wait for IO.  Note, gup always bails if it is unable to quickly
431676657687SPeter Xu 	 * get a page and a fatal signal, i.e. SIGKILL, is pending.
431776657687SPeter Xu 	 */
431876657687SPeter Xu 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, true, NULL,
43193647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
43203647cd04SPaolo Bonzini 					  &fault->hva);
43215276c616SSean Christopherson 	return RET_PF_CONTINUE;
4322c50d8ae3SPaolo Bonzini }
4323c50d8ae3SPaolo Bonzini 
4324354c908cSDavid Matlack static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
4325354c908cSDavid Matlack 			   unsigned int access)
4326ba6e3fe2SDavid Matlack {
432756c3a4e4SDavid Matlack 	int ret;
432856c3a4e4SDavid Matlack 
4329ba6e3fe2SDavid Matlack 	fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4330ba6e3fe2SDavid Matlack 	smp_rmb();
4331ba6e3fe2SDavid Matlack 
433256c3a4e4SDavid Matlack 	ret = __kvm_faultin_pfn(vcpu, fault);
433356c3a4e4SDavid Matlack 	if (ret != RET_PF_CONTINUE)
433456c3a4e4SDavid Matlack 		return ret;
433556c3a4e4SDavid Matlack 
433656c3a4e4SDavid Matlack 	if (unlikely(is_error_pfn(fault->pfn)))
4337cd08d178SDavid Matlack 		return kvm_handle_error_pfn(vcpu, fault);
433856c3a4e4SDavid Matlack 
4339354c908cSDavid Matlack 	if (unlikely(!fault->slot))
4340354c908cSDavid Matlack 		return kvm_handle_noslot_fault(vcpu, fault, access);
4341354c908cSDavid Matlack 
434256c3a4e4SDavid Matlack 	return RET_PF_CONTINUE;
4343ba6e3fe2SDavid Matlack }
4344ba6e3fe2SDavid Matlack 
4345a955cad8SSean Christopherson /*
4346a955cad8SSean Christopherson  * Returns true if the page fault is stale and needs to be retried, i.e. if the
4347a955cad8SSean Christopherson  * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4348a955cad8SSean Christopherson  */
4349a955cad8SSean Christopherson static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4350ba6e3fe2SDavid Matlack 				struct kvm_page_fault *fault)
4351a955cad8SSean Christopherson {
4352c5f2d564SSean Christopherson 	struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
435318c841e1SSean Christopherson 
435418c841e1SSean Christopherson 	/* Special roots, e.g. pae_root, are not backed by shadow pages. */
435518c841e1SSean Christopherson 	if (sp && is_obsolete_sp(vcpu->kvm, sp))
435618c841e1SSean Christopherson 		return true;
435718c841e1SSean Christopherson 
435818c841e1SSean Christopherson 	/*
435918c841e1SSean Christopherson 	 * Roots without an associated shadow page are considered invalid if
436018c841e1SSean Christopherson 	 * there is a pending request to free obsolete roots.  The request is
436118c841e1SSean Christopherson 	 * only a hint that the current root _may_ be obsolete and needs to be
436218c841e1SSean Christopherson 	 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
436318c841e1SSean Christopherson 	 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
436418c841e1SSean Christopherson 	 * to reload even if no vCPU is actively using the root.
436518c841e1SSean Christopherson 	 */
4366527d5cd7SSean Christopherson 	if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4367a955cad8SSean Christopherson 		return true;
4368a955cad8SSean Christopherson 
4369a955cad8SSean Christopherson 	return fault->slot &&
4370ba6e3fe2SDavid Matlack 	       mmu_invalidate_retry_hva(vcpu->kvm, fault->mmu_seq, fault->hva);
4371a955cad8SSean Christopherson }
4372a955cad8SSean Christopherson 
43734326e57eSPaolo Bonzini static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4374c50d8ae3SPaolo Bonzini {
437583f06fa7SSean Christopherson 	int r;
4376c50d8ae3SPaolo Bonzini 
4377b8a5d551SPaolo Bonzini 	if (page_fault_handle_page_track(vcpu, fault))
4378c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4379c50d8ae3SPaolo Bonzini 
43803c8ad5a6SPaolo Bonzini 	r = fast_page_fault(vcpu, fault);
4381c4371c2aSSean Christopherson 	if (r != RET_PF_INVALID)
4382c4371c2aSSean Christopherson 		return r;
438383291445SSean Christopherson 
4384378f5cd6SSean Christopherson 	r = mmu_topup_memory_caches(vcpu, false);
4385c50d8ae3SPaolo Bonzini 	if (r)
4386c50d8ae3SPaolo Bonzini 		return r;
4387c50d8ae3SPaolo Bonzini 
4388354c908cSDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
43895276c616SSean Christopherson 	if (r != RET_PF_CONTINUE)
4390367fd790SSean Christopherson 		return r;
4391367fd790SSean Christopherson 
4392367fd790SSean Christopherson 	r = RET_PF_RETRY;
4393531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
4394a2855afcSBen Gardon 
4395ba6e3fe2SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
4396367fd790SSean Christopherson 		goto out_unlock;
4397a955cad8SSean Christopherson 
43987bd7ded6SSean Christopherson 	r = make_mmu_pages_available(vcpu);
43997bd7ded6SSean Christopherson 	if (r)
4400367fd790SSean Christopherson 		goto out_unlock;
4401bb18842eSBen Gardon 
44026c882ef4SDavid Matlack 	r = direct_map(vcpu, fault);
44030f90e1c1SSean Christopherson 
4404367fd790SSean Christopherson out_unlock:
4405531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
44063647cd04SPaolo Bonzini 	kvm_release_pfn_clean(fault->pfn);
4407367fd790SSean Christopherson 	return r;
4408c50d8ae3SPaolo Bonzini }
4409c50d8ae3SPaolo Bonzini 
4410c501040aSPaolo Bonzini static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4411c501040aSPaolo Bonzini 				struct kvm_page_fault *fault)
44120f90e1c1SSean Christopherson {
44130f90e1c1SSean Christopherson 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
44144326e57eSPaolo Bonzini 	fault->max_level = PG_LEVEL_2M;
44154326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
44160f90e1c1SSean Christopherson }
44170f90e1c1SSean Christopherson 
4418c50d8ae3SPaolo Bonzini int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4419c50d8ae3SPaolo Bonzini 				u64 fault_address, char *insn, int insn_len)
4420c50d8ae3SPaolo Bonzini {
4421c50d8ae3SPaolo Bonzini 	int r = 1;
44229ce372b3SVitaly Kuznetsov 	u32 flags = vcpu->arch.apf.host_apf_flags;
4423c50d8ae3SPaolo Bonzini 
4424736c291cSSean Christopherson #ifndef CONFIG_X86_64
4425736c291cSSean Christopherson 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4426736c291cSSean Christopherson 	if (WARN_ON_ONCE(fault_address >> 32))
4427736c291cSSean Christopherson 		return -EFAULT;
4428736c291cSSean Christopherson #endif
4429736c291cSSean Christopherson 
4430c50d8ae3SPaolo Bonzini 	vcpu->arch.l1tf_flush_l1d = true;
44319ce372b3SVitaly Kuznetsov 	if (!flags) {
4432faa03b39SWonhyuk Yang 		trace_kvm_page_fault(vcpu, fault_address, error_code);
4433c50d8ae3SPaolo Bonzini 
4434c50d8ae3SPaolo Bonzini 		if (kvm_event_needs_reinjection(vcpu))
4435c50d8ae3SPaolo Bonzini 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4436c50d8ae3SPaolo Bonzini 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4437c50d8ae3SPaolo Bonzini 				insn_len);
44389ce372b3SVitaly Kuznetsov 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
443968fd66f1SVitaly Kuznetsov 		vcpu->arch.apf.host_apf_flags = 0;
4440c50d8ae3SPaolo Bonzini 		local_irq_disable();
44416bca69adSThomas Gleixner 		kvm_async_pf_task_wait_schedule(fault_address);
4442c50d8ae3SPaolo Bonzini 		local_irq_enable();
44439ce372b3SVitaly Kuznetsov 	} else {
44449ce372b3SVitaly Kuznetsov 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4445c50d8ae3SPaolo Bonzini 	}
44469ce372b3SVitaly Kuznetsov 
4447c50d8ae3SPaolo Bonzini 	return r;
4448c50d8ae3SPaolo Bonzini }
4449c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4450c50d8ae3SPaolo Bonzini 
44519aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
44529aa8ab43SDavid Matlack static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
44539aa8ab43SDavid Matlack 				  struct kvm_page_fault *fault)
44549aa8ab43SDavid Matlack {
44559aa8ab43SDavid Matlack 	int r;
44569aa8ab43SDavid Matlack 
44579aa8ab43SDavid Matlack 	if (page_fault_handle_page_track(vcpu, fault))
44589aa8ab43SDavid Matlack 		return RET_PF_EMULATE;
44599aa8ab43SDavid Matlack 
44609aa8ab43SDavid Matlack 	r = fast_page_fault(vcpu, fault);
44619aa8ab43SDavid Matlack 	if (r != RET_PF_INVALID)
44629aa8ab43SDavid Matlack 		return r;
44639aa8ab43SDavid Matlack 
44649aa8ab43SDavid Matlack 	r = mmu_topup_memory_caches(vcpu, false);
44659aa8ab43SDavid Matlack 	if (r)
44669aa8ab43SDavid Matlack 		return r;
44679aa8ab43SDavid Matlack 
44689aa8ab43SDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
44699aa8ab43SDavid Matlack 	if (r != RET_PF_CONTINUE)
44709aa8ab43SDavid Matlack 		return r;
44719aa8ab43SDavid Matlack 
44729aa8ab43SDavid Matlack 	r = RET_PF_RETRY;
44739aa8ab43SDavid Matlack 	read_lock(&vcpu->kvm->mmu_lock);
44749aa8ab43SDavid Matlack 
44759aa8ab43SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
44769aa8ab43SDavid Matlack 		goto out_unlock;
44779aa8ab43SDavid Matlack 
44789aa8ab43SDavid Matlack 	r = kvm_tdp_mmu_map(vcpu, fault);
44799aa8ab43SDavid Matlack 
44809aa8ab43SDavid Matlack out_unlock:
44819aa8ab43SDavid Matlack 	read_unlock(&vcpu->kvm->mmu_lock);
44829aa8ab43SDavid Matlack 	kvm_release_pfn_clean(fault->pfn);
44839aa8ab43SDavid Matlack 	return r;
44849aa8ab43SDavid Matlack }
44859aa8ab43SDavid Matlack #endif
44869aa8ab43SDavid Matlack 
4487c501040aSPaolo Bonzini int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4488c50d8ae3SPaolo Bonzini {
4489d5e90a69SSean Christopherson 	/*
4490d5e90a69SSean Christopherson 	 * If the guest's MTRRs may be used to compute the "real" memtype,
4491d5e90a69SSean Christopherson 	 * restrict the mapping level to ensure KVM uses a consistent memtype
4492d5e90a69SSean Christopherson 	 * across the entire mapping.  If the host MTRRs are ignored by TDP
4493d5e90a69SSean Christopherson 	 * (shadow_memtype_mask is non-zero), and the VM has non-coherent DMA
4494d5e90a69SSean Christopherson 	 * (DMA doesn't snoop CPU caches), KVM's ABI is to honor the memtype
4495d5e90a69SSean Christopherson 	 * from the guest's MTRRs so that guest accesses to memory that is
4496d5e90a69SSean Christopherson 	 * DMA'd aren't cached against the guest's wishes.
4497d5e90a69SSean Christopherson 	 *
4498d5e90a69SSean Christopherson 	 * Note, KVM may still ultimately ignore guest MTRRs for certain PFNs,
4499d5e90a69SSean Christopherson 	 * e.g. KVM will force UC memtype for host MMIO.
4500d5e90a69SSean Christopherson 	 */
4501d5e90a69SSean Christopherson 	if (shadow_memtype_mask && kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
4502d5e90a69SSean Christopherson 		for ( ; fault->max_level > PG_LEVEL_4K; --fault->max_level) {
45034326e57eSPaolo Bonzini 			int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
4504c667a3baSHou Wenlong 			gfn_t base = gfn_round_for_level(fault->gfn,
4505c667a3baSHou Wenlong 							 fault->max_level);
4506c50d8ae3SPaolo Bonzini 
4507cb9b88c6SSean Christopherson 			if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4508cb9b88c6SSean Christopherson 				break;
4509d5e90a69SSean Christopherson 		}
4510c50d8ae3SPaolo Bonzini 	}
4511c50d8ae3SPaolo Bonzini 
45129aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
45139aa8ab43SDavid Matlack 	if (tdp_mmu_enabled)
45149aa8ab43SDavid Matlack 		return kvm_tdp_mmu_page_fault(vcpu, fault);
45159aa8ab43SDavid Matlack #endif
45169aa8ab43SDavid Matlack 
45174326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
4518c50d8ae3SPaolo Bonzini }
4519c50d8ae3SPaolo Bonzini 
452084a16226SSean Christopherson static void nonpaging_init_context(struct kvm_mmu *context)
4521c50d8ae3SPaolo Bonzini {
4522c50d8ae3SPaolo Bonzini 	context->page_fault = nonpaging_page_fault;
4523c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4524c3c6c9fcSLai Jiangshan 	context->sync_spte = NULL;
4525c50d8ae3SPaolo Bonzini }
4526c50d8ae3SPaolo Bonzini 
4527be01e8e2SSean Christopherson static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
45280be44352SSean Christopherson 				  union kvm_mmu_page_role role)
45290be44352SSean Christopherson {
4530*c30e000eSSean Christopherson 	struct kvm_mmu_page *sp;
4531*c30e000eSSean Christopherson 
4532*c30e000eSSean Christopherson 	if (!VALID_PAGE(root->hpa))
4533*c30e000eSSean Christopherson 		return false;
4534*c30e000eSSean Christopherson 
4535*c30e000eSSean Christopherson 	if (!role.direct && pgd != root->pgd)
4536*c30e000eSSean Christopherson 		return false;
4537*c30e000eSSean Christopherson 
4538*c30e000eSSean Christopherson 	sp = root_to_sp(root->hpa);
4539*c30e000eSSean Christopherson 	if (WARN_ON_ONCE(!sp))
4540*c30e000eSSean Christopherson 		return false;
4541*c30e000eSSean Christopherson 
4542*c30e000eSSean Christopherson 	return role.word == sp->role.word;
45430be44352SSean Christopherson }
45440be44352SSean Christopherson 
4545c50d8ae3SPaolo Bonzini /*
45465499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available,
45475499ea73SPaolo Bonzini  * and insert the current root as the MRU in the cache.
45485499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root and
45495499ea73SPaolo Bonzini  * true is returned.
45505499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid, the LRU root is
45515499ea73SPaolo Bonzini  * evicted to make room for the current root, and false is returned.
4552c50d8ae3SPaolo Bonzini  */
45535499ea73SPaolo Bonzini static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
45545499ea73SPaolo Bonzini 					      gpa_t new_pgd,
4555c50d8ae3SPaolo Bonzini 					      union kvm_mmu_page_role new_role)
4556c50d8ae3SPaolo Bonzini {
4557c50d8ae3SPaolo Bonzini 	uint i;
4558c50d8ae3SPaolo Bonzini 
4559b9e5603cSPaolo Bonzini 	if (is_root_usable(&mmu->root, new_pgd, new_role))
45600be44352SSean Christopherson 		return true;
45610be44352SSean Christopherson 
4562c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
45635499ea73SPaolo Bonzini 		/*
45645499ea73SPaolo Bonzini 		 * The swaps end up rotating the cache like this:
45655499ea73SPaolo Bonzini 		 *   C   0 1 2 3   (on entry to the function)
45665499ea73SPaolo Bonzini 		 *   0   C 1 2 3
45675499ea73SPaolo Bonzini 		 *   1   C 0 2 3
45685499ea73SPaolo Bonzini 		 *   2   C 0 1 3
45695499ea73SPaolo Bonzini 		 *   3   C 0 1 2   (on exit from the loop)
45705499ea73SPaolo Bonzini 		 */
4571b9e5603cSPaolo Bonzini 		swap(mmu->root, mmu->prev_roots[i]);
4572b9e5603cSPaolo Bonzini 		if (is_root_usable(&mmu->root, new_pgd, new_role))
45735499ea73SPaolo Bonzini 			return true;
4574c50d8ae3SPaolo Bonzini 	}
4575c50d8ae3SPaolo Bonzini 
45765499ea73SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
45775499ea73SPaolo Bonzini 	return false;
4578c50d8ae3SPaolo Bonzini }
4579c50d8ae3SPaolo Bonzini 
4580c50d8ae3SPaolo Bonzini /*
45815499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available.
45825499ea73SPaolo Bonzini  * On entry, mmu->root is invalid.
45835499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
45845499ea73SPaolo Bonzini  * of the cache becomes invalid, and true is returned.
45855499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid and false is returned.
45865499ea73SPaolo Bonzini  */
45875499ea73SPaolo Bonzini static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
45885499ea73SPaolo Bonzini 					     gpa_t new_pgd,
45895499ea73SPaolo Bonzini 					     union kvm_mmu_page_role new_role)
45905499ea73SPaolo Bonzini {
45915499ea73SPaolo Bonzini 	uint i;
45925499ea73SPaolo Bonzini 
45935499ea73SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
45945499ea73SPaolo Bonzini 		if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
45955499ea73SPaolo Bonzini 			goto hit;
45965499ea73SPaolo Bonzini 
45975499ea73SPaolo Bonzini 	return false;
45985499ea73SPaolo Bonzini 
45995499ea73SPaolo Bonzini hit:
46005499ea73SPaolo Bonzini 	swap(mmu->root, mmu->prev_roots[i]);
46015499ea73SPaolo Bonzini 	/* Bubble up the remaining roots.  */
46025499ea73SPaolo Bonzini 	for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
46035499ea73SPaolo Bonzini 		mmu->prev_roots[i] = mmu->prev_roots[i + 1];
46045499ea73SPaolo Bonzini 	mmu->prev_roots[i].hpa = INVALID_PAGE;
46055499ea73SPaolo Bonzini 	return true;
46065499ea73SPaolo Bonzini }
46075499ea73SPaolo Bonzini 
46085499ea73SPaolo Bonzini static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
46095499ea73SPaolo Bonzini 			    gpa_t new_pgd, union kvm_mmu_page_role new_role)
46105499ea73SPaolo Bonzini {
46115499ea73SPaolo Bonzini 	/*
46125499ea73SPaolo Bonzini 	 * For now, limit the caching to 64-bit hosts+VMs in order to avoid
4613c50d8ae3SPaolo Bonzini 	 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4614c50d8ae3SPaolo Bonzini 	 * later if necessary.
4615c50d8ae3SPaolo Bonzini 	 */
4616c5f2d564SSean Christopherson 	if (VALID_PAGE(mmu->root.hpa) && !root_to_sp(mmu->root.hpa))
46175499ea73SPaolo Bonzini 		kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4618c50d8ae3SPaolo Bonzini 
46195499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa))
46205499ea73SPaolo Bonzini 		return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
46215499ea73SPaolo Bonzini 	else
46225499ea73SPaolo Bonzini 		return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4623c50d8ae3SPaolo Bonzini }
4624c50d8ae3SPaolo Bonzini 
4625d2e5f333SPaolo Bonzini void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4626c50d8ae3SPaolo Bonzini {
46270c1c92f1SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
46287a458f0eSPaolo Bonzini 	union kvm_mmu_page_role new_role = mmu->root_role;
46290c1c92f1SPaolo Bonzini 
4630a7e48ef7SWei Liu 	/*
4631a7e48ef7SWei Liu 	 * Return immediately if no usable root was found, kvm_mmu_reload()
4632a7e48ef7SWei Liu 	 * will establish a valid root prior to the next VM-Enter.
4633a7e48ef7SWei Liu 	 */
4634a7e48ef7SWei Liu 	if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role))
4635b869855bSSean Christopherson 		return;
4636c50d8ae3SPaolo Bonzini 
4637c50d8ae3SPaolo Bonzini 	/*
4638b869855bSSean Christopherson 	 * It's possible that the cached previous root page is obsolete because
4639b869855bSSean Christopherson 	 * of a change in the MMU generation number. However, changing the
4640527d5cd7SSean Christopherson 	 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4641527d5cd7SSean Christopherson 	 * which will free the root set here and allocate a new one.
4642b869855bSSean Christopherson 	 */
4643b869855bSSean Christopherson 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4644b869855bSSean Christopherson 
4645b5129100SSean Christopherson 	if (force_flush_and_sync_on_reuse) {
4646b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4647b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4648b5129100SSean Christopherson 	}
4649b869855bSSean Christopherson 
4650b869855bSSean Christopherson 	/*
4651b869855bSSean Christopherson 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4652b869855bSSean Christopherson 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
4653b869855bSSean Christopherson 	 * valid. So clear any cached MMIO info even when we don't need to sync
4654b869855bSSean Christopherson 	 * the shadow page tables.
4655c50d8ae3SPaolo Bonzini 	 */
4656c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4657c50d8ae3SPaolo Bonzini 
4658daa5b6c1SBen Gardon 	/*
4659daa5b6c1SBen Gardon 	 * If this is a direct root page, it doesn't have a write flooding
4660daa5b6c1SBen Gardon 	 * count. Otherwise, clear the write flooding count.
4661daa5b6c1SBen Gardon 	 */
4662*c30e000eSSean Christopherson 	if (!new_role.direct) {
4663*c30e000eSSean Christopherson 		struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
4664*c30e000eSSean Christopherson 
4665*c30e000eSSean Christopherson 		if (!WARN_ON_ONCE(!sp))
4666*c30e000eSSean Christopherson 			__clear_sp_write_flooding_count(sp);
4667*c30e000eSSean Christopherson 	}
4668c50d8ae3SPaolo Bonzini }
4669be01e8e2SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4670c50d8ae3SPaolo Bonzini 
4671c50d8ae3SPaolo Bonzini static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4672c3e5e415SLai Jiangshan 			   unsigned int access)
4673c50d8ae3SPaolo Bonzini {
4674c50d8ae3SPaolo Bonzini 	if (unlikely(is_mmio_spte(*sptep))) {
4675c50d8ae3SPaolo Bonzini 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4676c50d8ae3SPaolo Bonzini 			mmu_spte_clear_no_track(sptep);
4677c50d8ae3SPaolo Bonzini 			return true;
4678c50d8ae3SPaolo Bonzini 		}
4679c50d8ae3SPaolo Bonzini 
4680c50d8ae3SPaolo Bonzini 		mark_mmio_spte(vcpu, sptep, gfn, access);
4681c50d8ae3SPaolo Bonzini 		return true;
4682c50d8ae3SPaolo Bonzini 	}
4683c50d8ae3SPaolo Bonzini 
4684c50d8ae3SPaolo Bonzini 	return false;
4685c50d8ae3SPaolo Bonzini }
4686c50d8ae3SPaolo Bonzini 
4687c50d8ae3SPaolo Bonzini #define PTTYPE_EPT 18 /* arbitrary */
4688c50d8ae3SPaolo Bonzini #define PTTYPE PTTYPE_EPT
4689c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4690c50d8ae3SPaolo Bonzini #undef PTTYPE
4691c50d8ae3SPaolo Bonzini 
4692c50d8ae3SPaolo Bonzini #define PTTYPE 64
4693c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4694c50d8ae3SPaolo Bonzini #undef PTTYPE
4695c50d8ae3SPaolo Bonzini 
4696c50d8ae3SPaolo Bonzini #define PTTYPE 32
4697c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4698c50d8ae3SPaolo Bonzini #undef PTTYPE
4699c50d8ae3SPaolo Bonzini 
4700f3d90f90SSean Christopherson static void __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
4701f3d90f90SSean Christopherson 				    u64 pa_bits_rsvd, int level, bool nx,
4702f3d90f90SSean Christopherson 				    bool gbpages, bool pse, bool amd)
4703c50d8ae3SPaolo Bonzini {
4704c50d8ae3SPaolo Bonzini 	u64 gbpages_bit_rsvd = 0;
4705c50d8ae3SPaolo Bonzini 	u64 nonleaf_bit8_rsvd = 0;
47065b7f575cSSean Christopherson 	u64 high_bits_rsvd;
4707c50d8ae3SPaolo Bonzini 
4708c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = 0;
4709c50d8ae3SPaolo Bonzini 
4710c50d8ae3SPaolo Bonzini 	if (!gbpages)
4711c50d8ae3SPaolo Bonzini 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4712c50d8ae3SPaolo Bonzini 
47135b7f575cSSean Christopherson 	if (level == PT32E_ROOT_LEVEL)
47145b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
47155b7f575cSSean Christopherson 	else
47165b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
47175b7f575cSSean Christopherson 
47185b7f575cSSean Christopherson 	/* Note, NX doesn't exist in PDPTEs, this is handled below. */
47195b7f575cSSean Christopherson 	if (!nx)
47205b7f575cSSean Christopherson 		high_bits_rsvd |= rsvd_bits(63, 63);
47215b7f575cSSean Christopherson 
4722c50d8ae3SPaolo Bonzini 	/*
4723c50d8ae3SPaolo Bonzini 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4724c50d8ae3SPaolo Bonzini 	 * leaf entries) on AMD CPUs only.
4725c50d8ae3SPaolo Bonzini 	 */
4726c50d8ae3SPaolo Bonzini 	if (amd)
4727c50d8ae3SPaolo Bonzini 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4728c50d8ae3SPaolo Bonzini 
4729c50d8ae3SPaolo Bonzini 	switch (level) {
4730c50d8ae3SPaolo Bonzini 	case PT32_ROOT_LEVEL:
4731c50d8ae3SPaolo Bonzini 		/* no rsvd bits for 2 level 4K page table entries */
4732c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4733c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4734c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4735c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4736c50d8ae3SPaolo Bonzini 
4737c50d8ae3SPaolo Bonzini 		if (!pse) {
4738c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4739c50d8ae3SPaolo Bonzini 			break;
4740c50d8ae3SPaolo Bonzini 		}
4741c50d8ae3SPaolo Bonzini 
4742c50d8ae3SPaolo Bonzini 		if (is_cpuid_PSE36())
4743c50d8ae3SPaolo Bonzini 			/* 36bits PSE 4MB page */
4744c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4745c50d8ae3SPaolo Bonzini 		else
4746c50d8ae3SPaolo Bonzini 			/* 32 bits PSE 4MB page */
4747c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4748c50d8ae3SPaolo Bonzini 		break;
4749c50d8ae3SPaolo Bonzini 	case PT32E_ROOT_LEVEL:
47505b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
47515b7f575cSSean Christopherson 						   high_bits_rsvd |
47525b7f575cSSean Christopherson 						   rsvd_bits(5, 8) |
47535b7f575cSSean Christopherson 						   rsvd_bits(1, 2);	/* PDPTE */
47545b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;	/* PDE */
47555b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;	/* PTE */
47565b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4757c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20);	/* large page */
4758c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4759c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4760c50d8ae3SPaolo Bonzini 		break;
4761c50d8ae3SPaolo Bonzini 	case PT64_ROOT_5LEVEL:
47625b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
47635b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
47645b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
4765c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][4] =
4766c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][4];
4767df561f66SGustavo A. R. Silva 		fallthrough;
4768c50d8ae3SPaolo Bonzini 	case PT64_ROOT_4LEVEL:
47695b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
47705b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
47715b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
47725b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
47735b7f575cSSean Christopherson 						   gbpages_bit_rsvd;
47745b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
47755b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4776c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][3] =
4777c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][3];
47785b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
47795b7f575cSSean Christopherson 						   gbpages_bit_rsvd |
4780c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 29);
47815b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4782c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20); /* large page */
4783c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4784c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4785c50d8ae3SPaolo Bonzini 		break;
4786c50d8ae3SPaolo Bonzini 	}
4787c50d8ae3SPaolo Bonzini }
4788c50d8ae3SPaolo Bonzini 
4789c919e881SKai Huang static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4790c50d8ae3SPaolo Bonzini 					struct kvm_mmu *context)
4791c50d8ae3SPaolo Bonzini {
4792b705a277SSean Christopherson 	__reset_rsvds_bits_mask(&context->guest_rsvd_check,
47935b7f575cSSean Christopherson 				vcpu->arch.reserved_gpa_bits,
47944d25502aSPaolo Bonzini 				context->cpu_role.base.level, is_efer_nx(context),
4795ccf31d6eSSean Christopherson 				guest_can_use(vcpu, X86_FEATURE_GBPAGES),
47964e9c0d80SSean Christopherson 				is_cr4_pse(context),
479723493d0aSSean Christopherson 				guest_cpuid_is_amd_or_hygon(vcpu));
4798c50d8ae3SPaolo Bonzini }
4799c50d8ae3SPaolo Bonzini 
4800f3d90f90SSean Christopherson static void __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4801f3d90f90SSean Christopherson 					u64 pa_bits_rsvd, bool execonly,
4802f3d90f90SSean Christopherson 					int huge_page_level)
4803c50d8ae3SPaolo Bonzini {
48045b7f575cSSean Christopherson 	u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
480584ea5c09SLai Jiangshan 	u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
4806c50d8ae3SPaolo Bonzini 	u64 bad_mt_xwr;
4807c50d8ae3SPaolo Bonzini 
480884ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_1G)
480984ea5c09SLai Jiangshan 		large_1g_rsvd = rsvd_bits(7, 7);
481084ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_2M)
481184ea5c09SLai Jiangshan 		large_2m_rsvd = rsvd_bits(7, 7);
481284ea5c09SLai Jiangshan 
48135b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
48145b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
481584ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
481684ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
48175b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4818c50d8ae3SPaolo Bonzini 
4819c50d8ae3SPaolo Bonzini 	/* large page */
4820c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4821c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
482284ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
482384ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
4824c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4825c50d8ae3SPaolo Bonzini 
4826c50d8ae3SPaolo Bonzini 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
4827c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
4828c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
4829c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
4830c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
4831c50d8ae3SPaolo Bonzini 	if (!execonly) {
4832c50d8ae3SPaolo Bonzini 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
4833c50d8ae3SPaolo Bonzini 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4834c50d8ae3SPaolo Bonzini 	}
4835c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
4836c50d8ae3SPaolo Bonzini }
4837c50d8ae3SPaolo Bonzini 
4838c50d8ae3SPaolo Bonzini static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
483984ea5c09SLai Jiangshan 		struct kvm_mmu *context, bool execonly, int huge_page_level)
4840c50d8ae3SPaolo Bonzini {
4841c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
484284ea5c09SLai Jiangshan 				    vcpu->arch.reserved_gpa_bits, execonly,
484384ea5c09SLai Jiangshan 				    huge_page_level);
4844c50d8ae3SPaolo Bonzini }
4845c50d8ae3SPaolo Bonzini 
48466f8e65a6SSean Christopherson static inline u64 reserved_hpa_bits(void)
48476f8e65a6SSean Christopherson {
48486f8e65a6SSean Christopherson 	return rsvd_bits(shadow_phys_bits, 63);
48496f8e65a6SSean Christopherson }
48506f8e65a6SSean Christopherson 
4851c50d8ae3SPaolo Bonzini /*
4852c50d8ae3SPaolo Bonzini  * the page table on host is the shadow page table for the page
4853c50d8ae3SPaolo Bonzini  * table in guest or amd nested guest, its mmu features completely
4854c50d8ae3SPaolo Bonzini  * follow the features in guest.
4855c50d8ae3SPaolo Bonzini  */
485616be1d12SSean Christopherson static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
485716be1d12SSean Christopherson 					struct kvm_mmu *context)
4858c50d8ae3SPaolo Bonzini {
48598c985b2dSSean Christopherson 	/* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
48608c985b2dSSean Christopherson 	bool is_amd = true;
48618c985b2dSSean Christopherson 	/* KVM doesn't use 2-level page tables for the shadow MMU. */
48628c985b2dSSean Christopherson 	bool is_pse = false;
4863c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4864c50d8ae3SPaolo Bonzini 	int i;
4865c50d8ae3SPaolo Bonzini 
4866a972e29cSPaolo Bonzini 	WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
48678c985b2dSSean Christopherson 
4868c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4869b705a277SSean Christopherson 	__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4870a972e29cSPaolo Bonzini 				context->root_role.level,
48717a458f0eSPaolo Bonzini 				context->root_role.efer_nx,
4872ccf31d6eSSean Christopherson 				guest_can_use(vcpu, X86_FEATURE_GBPAGES),
4873ccf31d6eSSean Christopherson 				is_pse, is_amd);
4874c50d8ae3SPaolo Bonzini 
4875c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4876c50d8ae3SPaolo Bonzini 		return;
4877c50d8ae3SPaolo Bonzini 
4878a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
4879e54f1ff2SKai Huang 		/*
4880e54f1ff2SKai Huang 		 * So far shadow_me_value is a constant during KVM's life
4881e54f1ff2SKai Huang 		 * time.  Bits in shadow_me_value are allowed to be set.
4882e54f1ff2SKai Huang 		 * Bits in shadow_me_mask but not in shadow_me_value are
4883e54f1ff2SKai Huang 		 * not allowed to be set.
4884e54f1ff2SKai Huang 		 */
4885e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
4886e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
4887e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
4888e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
4889c50d8ae3SPaolo Bonzini 	}
4890c50d8ae3SPaolo Bonzini 
4891c50d8ae3SPaolo Bonzini }
4892c50d8ae3SPaolo Bonzini 
4893c50d8ae3SPaolo Bonzini static inline bool boot_cpu_is_amd(void)
4894c50d8ae3SPaolo Bonzini {
4895c50d8ae3SPaolo Bonzini 	WARN_ON_ONCE(!tdp_enabled);
4896c50d8ae3SPaolo Bonzini 	return shadow_x_mask == 0;
4897c50d8ae3SPaolo Bonzini }
4898c50d8ae3SPaolo Bonzini 
4899c50d8ae3SPaolo Bonzini /*
4900c50d8ae3SPaolo Bonzini  * the direct page table on host, use as much mmu features as
4901c50d8ae3SPaolo Bonzini  * possible, however, kvm currently does not do execution-protection.
4902c50d8ae3SPaolo Bonzini  */
4903f3d90f90SSean Christopherson static void reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
4904c50d8ae3SPaolo Bonzini {
4905c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4906c50d8ae3SPaolo Bonzini 	int i;
4907c50d8ae3SPaolo Bonzini 
4908c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4909c50d8ae3SPaolo Bonzini 
4910c50d8ae3SPaolo Bonzini 	if (boot_cpu_is_amd())
4911b705a277SSean Christopherson 		__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
49126c6ab524SSean Christopherson 					context->root_role.level, true,
4913c50d8ae3SPaolo Bonzini 					boot_cpu_has(X86_FEATURE_GBPAGES),
49148c985b2dSSean Christopherson 					false, true);
4915c50d8ae3SPaolo Bonzini 	else
4916c50d8ae3SPaolo Bonzini 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
491784ea5c09SLai Jiangshan 					    reserved_hpa_bits(), false,
491884ea5c09SLai Jiangshan 					    max_huge_page_level);
4919c50d8ae3SPaolo Bonzini 
4920c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4921c50d8ae3SPaolo Bonzini 		return;
4922c50d8ae3SPaolo Bonzini 
4923a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
4924c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4925c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4926c50d8ae3SPaolo Bonzini 	}
4927c50d8ae3SPaolo Bonzini }
4928c50d8ae3SPaolo Bonzini 
4929c50d8ae3SPaolo Bonzini /*
4930c50d8ae3SPaolo Bonzini  * as the comments in reset_shadow_zero_bits_mask() except it
4931c50d8ae3SPaolo Bonzini  * is the shadow page table for intel nested guest.
4932c50d8ae3SPaolo Bonzini  */
4933c50d8ae3SPaolo Bonzini static void
4934e8f6e738SJinrong Liang reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
4935c50d8ae3SPaolo Bonzini {
4936c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
493784ea5c09SLai Jiangshan 				    reserved_hpa_bits(), execonly,
493884ea5c09SLai Jiangshan 				    max_huge_page_level);
4939c50d8ae3SPaolo Bonzini }
4940c50d8ae3SPaolo Bonzini 
4941c50d8ae3SPaolo Bonzini #define BYTE_MASK(access) \
4942c50d8ae3SPaolo Bonzini 	((1 & (access) ? 2 : 0) | \
4943c50d8ae3SPaolo Bonzini 	 (2 & (access) ? 4 : 0) | \
4944c50d8ae3SPaolo Bonzini 	 (3 & (access) ? 8 : 0) | \
4945c50d8ae3SPaolo Bonzini 	 (4 & (access) ? 16 : 0) | \
4946c50d8ae3SPaolo Bonzini 	 (5 & (access) ? 32 : 0) | \
4947c50d8ae3SPaolo Bonzini 	 (6 & (access) ? 64 : 0) | \
4948c50d8ae3SPaolo Bonzini 	 (7 & (access) ? 128 : 0))
4949c50d8ae3SPaolo Bonzini 
4950c50d8ae3SPaolo Bonzini 
4951c596f147SSean Christopherson static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
4952c50d8ae3SPaolo Bonzini {
4953c50d8ae3SPaolo Bonzini 	unsigned byte;
4954c50d8ae3SPaolo Bonzini 
4955c50d8ae3SPaolo Bonzini 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4956c50d8ae3SPaolo Bonzini 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4957c50d8ae3SPaolo Bonzini 	const u8 u = BYTE_MASK(ACC_USER_MASK);
4958c50d8ae3SPaolo Bonzini 
4959c596f147SSean Christopherson 	bool cr4_smep = is_cr4_smep(mmu);
4960c596f147SSean Christopherson 	bool cr4_smap = is_cr4_smap(mmu);
4961c596f147SSean Christopherson 	bool cr0_wp = is_cr0_wp(mmu);
496290599c28SSean Christopherson 	bool efer_nx = is_efer_nx(mmu);
4963c50d8ae3SPaolo Bonzini 
4964c50d8ae3SPaolo Bonzini 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4965c50d8ae3SPaolo Bonzini 		unsigned pfec = byte << 1;
4966c50d8ae3SPaolo Bonzini 
4967c50d8ae3SPaolo Bonzini 		/*
4968c50d8ae3SPaolo Bonzini 		 * Each "*f" variable has a 1 bit for each UWX value
4969c50d8ae3SPaolo Bonzini 		 * that causes a fault with the given PFEC.
4970c50d8ae3SPaolo Bonzini 		 */
4971c50d8ae3SPaolo Bonzini 
4972c50d8ae3SPaolo Bonzini 		/* Faults from writes to non-writable pages */
4973c50d8ae3SPaolo Bonzini 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4974c50d8ae3SPaolo Bonzini 		/* Faults from user mode accesses to supervisor pages */
4975c50d8ae3SPaolo Bonzini 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4976c50d8ae3SPaolo Bonzini 		/* Faults from fetches of non-executable pages*/
4977c50d8ae3SPaolo Bonzini 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4978c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode fetches of user pages */
4979c50d8ae3SPaolo Bonzini 		u8 smepf = 0;
4980c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode accesses of user pages */
4981c50d8ae3SPaolo Bonzini 		u8 smapf = 0;
4982c50d8ae3SPaolo Bonzini 
4983c50d8ae3SPaolo Bonzini 		if (!ept) {
4984c50d8ae3SPaolo Bonzini 			/* Faults from kernel mode accesses to user pages */
4985c50d8ae3SPaolo Bonzini 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4986c50d8ae3SPaolo Bonzini 
4987c50d8ae3SPaolo Bonzini 			/* Not really needed: !nx will cause pte.nx to fault */
498890599c28SSean Christopherson 			if (!efer_nx)
4989c50d8ae3SPaolo Bonzini 				ff = 0;
4990c50d8ae3SPaolo Bonzini 
4991c50d8ae3SPaolo Bonzini 			/* Allow supervisor writes if !cr0.wp */
4992c50d8ae3SPaolo Bonzini 			if (!cr0_wp)
4993c50d8ae3SPaolo Bonzini 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4994c50d8ae3SPaolo Bonzini 
4995c50d8ae3SPaolo Bonzini 			/* Disallow supervisor fetches of user code if cr4.smep */
4996c50d8ae3SPaolo Bonzini 			if (cr4_smep)
4997c50d8ae3SPaolo Bonzini 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4998c50d8ae3SPaolo Bonzini 
4999c50d8ae3SPaolo Bonzini 			/*
5000c50d8ae3SPaolo Bonzini 			 * SMAP:kernel-mode data accesses from user-mode
5001c50d8ae3SPaolo Bonzini 			 * mappings should fault. A fault is considered
5002c50d8ae3SPaolo Bonzini 			 * as a SMAP violation if all of the following
5003c50d8ae3SPaolo Bonzini 			 * conditions are true:
5004c50d8ae3SPaolo Bonzini 			 *   - X86_CR4_SMAP is set in CR4
5005c50d8ae3SPaolo Bonzini 			 *   - A user page is accessed
5006c50d8ae3SPaolo Bonzini 			 *   - The access is not a fetch
50074f4aa80eSLai Jiangshan 			 *   - The access is supervisor mode
50084f4aa80eSLai Jiangshan 			 *   - If implicit supervisor access or X86_EFLAGS_AC is clear
5009c50d8ae3SPaolo Bonzini 			 *
501094b4a2f1SLai Jiangshan 			 * Here, we cover the first four conditions.
501194b4a2f1SLai Jiangshan 			 * The fifth is computed dynamically in permission_fault();
5012c50d8ae3SPaolo Bonzini 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
5013c50d8ae3SPaolo Bonzini 			 * *not* subject to SMAP restrictions.
5014c50d8ae3SPaolo Bonzini 			 */
5015c50d8ae3SPaolo Bonzini 			if (cr4_smap)
5016c50d8ae3SPaolo Bonzini 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
5017c50d8ae3SPaolo Bonzini 		}
5018c50d8ae3SPaolo Bonzini 
5019c50d8ae3SPaolo Bonzini 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
5020c50d8ae3SPaolo Bonzini 	}
5021c50d8ae3SPaolo Bonzini }
5022c50d8ae3SPaolo Bonzini 
5023c50d8ae3SPaolo Bonzini /*
5024c50d8ae3SPaolo Bonzini * PKU is an additional mechanism by which the paging controls access to
5025c50d8ae3SPaolo Bonzini * user-mode addresses based on the value in the PKRU register.  Protection
5026c50d8ae3SPaolo Bonzini * key violations are reported through a bit in the page fault error code.
5027c50d8ae3SPaolo Bonzini * Unlike other bits of the error code, the PK bit is not known at the
5028c50d8ae3SPaolo Bonzini * call site of e.g. gva_to_gpa; it must be computed directly in
5029c50d8ae3SPaolo Bonzini * permission_fault based on two bits of PKRU, on some machine state (CR4,
5030c50d8ae3SPaolo Bonzini * CR0, EFER, CPL), and on other bits of the error code and the page tables.
5031c50d8ae3SPaolo Bonzini *
5032c50d8ae3SPaolo Bonzini * In particular the following conditions come from the error code, the
5033c50d8ae3SPaolo Bonzini * page tables and the machine state:
5034c50d8ae3SPaolo Bonzini * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
5035c50d8ae3SPaolo Bonzini * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
5036c50d8ae3SPaolo Bonzini * - PK is always zero if U=0 in the page tables
5037c50d8ae3SPaolo Bonzini * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
5038c50d8ae3SPaolo Bonzini *
5039c50d8ae3SPaolo Bonzini * The PKRU bitmask caches the result of these four conditions.  The error
5040c50d8ae3SPaolo Bonzini * code (minus the P bit) and the page table's U bit form an index into the
5041c50d8ae3SPaolo Bonzini * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
5042c50d8ae3SPaolo Bonzini * with the two bits of the PKRU register corresponding to the protection key.
5043c50d8ae3SPaolo Bonzini * For the first three conditions above the bits will be 00, thus masking
5044c50d8ae3SPaolo Bonzini * away both AD and WD.  For all reads or if the last condition holds, WD
5045c50d8ae3SPaolo Bonzini * only will be masked away.
5046c50d8ae3SPaolo Bonzini */
50472e4c0661SSean Christopherson static void update_pkru_bitmask(struct kvm_mmu *mmu)
5048c50d8ae3SPaolo Bonzini {
5049c50d8ae3SPaolo Bonzini 	unsigned bit;
5050c50d8ae3SPaolo Bonzini 	bool wp;
5051c50d8ae3SPaolo Bonzini 
5052c50d8ae3SPaolo Bonzini 	mmu->pkru_mask = 0;
5053a3ca5281SChenyi Qiang 
5054a3ca5281SChenyi Qiang 	if (!is_cr4_pke(mmu))
5055c50d8ae3SPaolo Bonzini 		return;
5056c50d8ae3SPaolo Bonzini 
50572e4c0661SSean Christopherson 	wp = is_cr0_wp(mmu);
5058c50d8ae3SPaolo Bonzini 
5059c50d8ae3SPaolo Bonzini 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5060c50d8ae3SPaolo Bonzini 		unsigned pfec, pkey_bits;
5061c50d8ae3SPaolo Bonzini 		bool check_pkey, check_write, ff, uf, wf, pte_user;
5062c50d8ae3SPaolo Bonzini 
5063c50d8ae3SPaolo Bonzini 		pfec = bit << 1;
5064c50d8ae3SPaolo Bonzini 		ff = pfec & PFERR_FETCH_MASK;
5065c50d8ae3SPaolo Bonzini 		uf = pfec & PFERR_USER_MASK;
5066c50d8ae3SPaolo Bonzini 		wf = pfec & PFERR_WRITE_MASK;
5067c50d8ae3SPaolo Bonzini 
5068c50d8ae3SPaolo Bonzini 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
5069c50d8ae3SPaolo Bonzini 		pte_user = pfec & PFERR_RSVD_MASK;
5070c50d8ae3SPaolo Bonzini 
5071c50d8ae3SPaolo Bonzini 		/*
5072c50d8ae3SPaolo Bonzini 		 * Only need to check the access which is not an
5073c50d8ae3SPaolo Bonzini 		 * instruction fetch and is to a user page.
5074c50d8ae3SPaolo Bonzini 		 */
5075c50d8ae3SPaolo Bonzini 		check_pkey = (!ff && pte_user);
5076c50d8ae3SPaolo Bonzini 		/*
5077c50d8ae3SPaolo Bonzini 		 * write access is controlled by PKRU if it is a
5078c50d8ae3SPaolo Bonzini 		 * user access or CR0.WP = 1.
5079c50d8ae3SPaolo Bonzini 		 */
5080c50d8ae3SPaolo Bonzini 		check_write = check_pkey && wf && (uf || wp);
5081c50d8ae3SPaolo Bonzini 
5082c50d8ae3SPaolo Bonzini 		/* PKRU.AD stops both read and write access. */
5083c50d8ae3SPaolo Bonzini 		pkey_bits = !!check_pkey;
5084c50d8ae3SPaolo Bonzini 		/* PKRU.WD stops write access. */
5085c50d8ae3SPaolo Bonzini 		pkey_bits |= (!!check_write) << 1;
5086c50d8ae3SPaolo Bonzini 
5087c50d8ae3SPaolo Bonzini 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5088c50d8ae3SPaolo Bonzini 	}
5089c50d8ae3SPaolo Bonzini }
5090c50d8ae3SPaolo Bonzini 
5091533f9a4bSSean Christopherson static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5092533f9a4bSSean Christopherson 					struct kvm_mmu *mmu)
5093c50d8ae3SPaolo Bonzini {
5094533f9a4bSSean Christopherson 	if (!is_cr0_pg(mmu))
5095533f9a4bSSean Christopherson 		return;
5096c50d8ae3SPaolo Bonzini 
5097c919e881SKai Huang 	reset_guest_rsvds_bits_mask(vcpu, mmu);
5098533f9a4bSSean Christopherson 	update_permission_bitmask(mmu, false);
5099533f9a4bSSean Christopherson 	update_pkru_bitmask(mmu);
5100c50d8ae3SPaolo Bonzini }
5101c50d8ae3SPaolo Bonzini 
5102fe660f72SSean Christopherson static void paging64_init_context(struct kvm_mmu *context)
5103c50d8ae3SPaolo Bonzini {
5104c50d8ae3SPaolo Bonzini 	context->page_fault = paging64_page_fault;
5105c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging64_gva_to_gpa;
5106c3c6c9fcSLai Jiangshan 	context->sync_spte = paging64_sync_spte;
5107c50d8ae3SPaolo Bonzini }
5108c50d8ae3SPaolo Bonzini 
510984a16226SSean Christopherson static void paging32_init_context(struct kvm_mmu *context)
5110c50d8ae3SPaolo Bonzini {
5111c50d8ae3SPaolo Bonzini 	context->page_fault = paging32_page_fault;
5112c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging32_gva_to_gpa;
5113c3c6c9fcSLai Jiangshan 	context->sync_spte = paging32_sync_spte;
5114c50d8ae3SPaolo Bonzini }
5115c50d8ae3SPaolo Bonzini 
5116f3d90f90SSean Christopherson static union kvm_cpu_role kvm_calc_cpu_role(struct kvm_vcpu *vcpu,
5117f3d90f90SSean Christopherson 					    const struct kvm_mmu_role_regs *regs)
5118e5ed0fb0SPaolo Bonzini {
51197a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5120e5ed0fb0SPaolo Bonzini 
5121e5ed0fb0SPaolo Bonzini 	role.base.access = ACC_ALL;
5122e5ed0fb0SPaolo Bonzini 	role.base.smm = is_smm(vcpu);
5123e5ed0fb0SPaolo Bonzini 	role.base.guest_mode = is_guest_mode(vcpu);
5124e5ed0fb0SPaolo Bonzini 	role.ext.valid = 1;
5125e5ed0fb0SPaolo Bonzini 
5126e5ed0fb0SPaolo Bonzini 	if (!____is_cr0_pg(regs)) {
5127e5ed0fb0SPaolo Bonzini 		role.base.direct = 1;
5128e5ed0fb0SPaolo Bonzini 		return role;
5129e5ed0fb0SPaolo Bonzini 	}
5130e5ed0fb0SPaolo Bonzini 
5131e5ed0fb0SPaolo Bonzini 	role.base.efer_nx = ____is_efer_nx(regs);
5132e5ed0fb0SPaolo Bonzini 	role.base.cr0_wp = ____is_cr0_wp(regs);
5133e5ed0fb0SPaolo Bonzini 	role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5134e5ed0fb0SPaolo Bonzini 	role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5135e5ed0fb0SPaolo Bonzini 	role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
513660f3cb60SPaolo Bonzini 
513760f3cb60SPaolo Bonzini 	if (____is_efer_lma(regs))
513860f3cb60SPaolo Bonzini 		role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
513960f3cb60SPaolo Bonzini 							: PT64_ROOT_4LEVEL;
514060f3cb60SPaolo Bonzini 	else if (____is_cr4_pae(regs))
514160f3cb60SPaolo Bonzini 		role.base.level = PT32E_ROOT_LEVEL;
514260f3cb60SPaolo Bonzini 	else
514360f3cb60SPaolo Bonzini 		role.base.level = PT32_ROOT_LEVEL;
5144e5ed0fb0SPaolo Bonzini 
5145e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smep = ____is_cr4_smep(regs);
5146e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smap = ____is_cr4_smap(regs);
5147e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pse = ____is_cr4_pse(regs);
5148e5ed0fb0SPaolo Bonzini 
5149e5ed0fb0SPaolo Bonzini 	/* PKEY and LA57 are active iff long mode is active. */
5150e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5151e5ed0fb0SPaolo Bonzini 	role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5152e5ed0fb0SPaolo Bonzini 	role.ext.efer_lma = ____is_efer_lma(regs);
5153e5ed0fb0SPaolo Bonzini 	return role;
5154e5ed0fb0SPaolo Bonzini }
5155e5ed0fb0SPaolo Bonzini 
5156cf9f4c0eSSean Christopherson void __kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
5157cf9f4c0eSSean Christopherson 					struct kvm_mmu *mmu)
5158cf9f4c0eSSean Christopherson {
5159cf9f4c0eSSean Christopherson 	const bool cr0_wp = kvm_is_cr0_bit_set(vcpu, X86_CR0_WP);
5160cf9f4c0eSSean Christopherson 
5161cf9f4c0eSSean Christopherson 	BUILD_BUG_ON((KVM_MMU_CR0_ROLE_BITS & KVM_POSSIBLE_CR0_GUEST_BITS) != X86_CR0_WP);
5162cf9f4c0eSSean Christopherson 	BUILD_BUG_ON((KVM_MMU_CR4_ROLE_BITS & KVM_POSSIBLE_CR4_GUEST_BITS));
5163cf9f4c0eSSean Christopherson 
5164cf9f4c0eSSean Christopherson 	if (is_cr0_wp(mmu) == cr0_wp)
5165cf9f4c0eSSean Christopherson 		return;
5166cf9f4c0eSSean Christopherson 
5167cf9f4c0eSSean Christopherson 	mmu->cpu_role.base.cr0_wp = cr0_wp;
5168cf9f4c0eSSean Christopherson 	reset_guest_paging_metadata(vcpu, mmu);
5169cf9f4c0eSSean Christopherson }
5170cf9f4c0eSSean Christopherson 
5171d468d94bSSean Christopherson static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5172d468d94bSSean Christopherson {
5173746700d2SWei Huang 	/* tdp_root_level is architecture forced level, use it if nonzero */
5174746700d2SWei Huang 	if (tdp_root_level)
5175746700d2SWei Huang 		return tdp_root_level;
5176746700d2SWei Huang 
5177d468d94bSSean Christopherson 	/* Use 5-level TDP if and only if it's useful/necessary. */
517883013059SSean Christopherson 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5179d468d94bSSean Christopherson 		return 4;
5180d468d94bSSean Christopherson 
518183013059SSean Christopherson 	return max_tdp_level;
5182d468d94bSSean Christopherson }
5183d468d94bSSean Christopherson 
51847a458f0eSPaolo Bonzini static union kvm_mmu_page_role
51858626c120SSean Christopherson kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
51867a7ae829SPaolo Bonzini 				union kvm_cpu_role cpu_role)
5187c50d8ae3SPaolo Bonzini {
51887a458f0eSPaolo Bonzini 	union kvm_mmu_page_role role = {0};
5189c50d8ae3SPaolo Bonzini 
51907a458f0eSPaolo Bonzini 	role.access = ACC_ALL;
51917a458f0eSPaolo Bonzini 	role.cr0_wp = true;
51927a458f0eSPaolo Bonzini 	role.efer_nx = true;
51937a458f0eSPaolo Bonzini 	role.smm = cpu_role.base.smm;
51947a458f0eSPaolo Bonzini 	role.guest_mode = cpu_role.base.guest_mode;
519554275f74SSean Christopherson 	role.ad_disabled = !kvm_ad_enabled();
51967a458f0eSPaolo Bonzini 	role.level = kvm_mmu_get_tdp_level(vcpu);
51977a458f0eSPaolo Bonzini 	role.direct = true;
51987a458f0eSPaolo Bonzini 	role.has_4_byte_gpte = false;
5199c50d8ae3SPaolo Bonzini 
5200c50d8ae3SPaolo Bonzini 	return role;
5201c50d8ae3SPaolo Bonzini }
5202c50d8ae3SPaolo Bonzini 
520339e7e2bfSPaolo Bonzini static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5204a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5205c50d8ae3SPaolo Bonzini {
52068c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
52077a458f0eSPaolo Bonzini 	union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5208c50d8ae3SPaolo Bonzini 
5209e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
52107a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
5211c50d8ae3SPaolo Bonzini 		return;
5212c50d8ae3SPaolo Bonzini 
5213e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
52147a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
52157a02674dSSean Christopherson 	context->page_fault = kvm_tdp_page_fault;
5216c3c6c9fcSLai Jiangshan 	context->sync_spte = NULL;
52172fdcc1b3SPaolo Bonzini 	context->get_guest_pgd = get_guest_cr3;
5218c50d8ae3SPaolo Bonzini 	context->get_pdptr = kvm_pdptr_read;
5219c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5220c50d8ae3SPaolo Bonzini 
522136f26787SSean Christopherson 	if (!is_cr0_pg(context))
5222c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = nonpaging_gva_to_gpa;
522336f26787SSean Christopherson 	else if (is_cr4_pae(context))
5224c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging64_gva_to_gpa;
5225f4bd6f73SSean Christopherson 	else
5226c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging32_gva_to_gpa;
5227c50d8ae3SPaolo Bonzini 
5228533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5229e8f6e738SJinrong Liang 	reset_tdp_shadow_zero_bits_mask(context);
5230c50d8ae3SPaolo Bonzini }
5231c50d8ae3SPaolo Bonzini 
52328c008659SPaolo Bonzini static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
52337a7ae829SPaolo Bonzini 				    union kvm_cpu_role cpu_role,
52347a458f0eSPaolo Bonzini 				    union kvm_mmu_page_role root_role)
5235c50d8ae3SPaolo Bonzini {
5236e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
52377a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
523818db1b17SSean Christopherson 		return;
5239c50d8ae3SPaolo Bonzini 
5240e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
52417a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
524218db1b17SSean Christopherson 
524336f26787SSean Christopherson 	if (!is_cr0_pg(context))
524484a16226SSean Christopherson 		nonpaging_init_context(context);
524536f26787SSean Christopherson 	else if (is_cr4_pae(context))
5246fe660f72SSean Christopherson 		paging64_init_context(context);
5247c50d8ae3SPaolo Bonzini 	else
524884a16226SSean Christopherson 		paging32_init_context(context);
5249c50d8ae3SPaolo Bonzini 
5250533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5251c50d8ae3SPaolo Bonzini 	reset_shadow_zero_bits_mask(vcpu, context);
5252c50d8ae3SPaolo Bonzini }
52530f04a2acSVitaly Kuznetsov 
5254594e91a1SSean Christopherson static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5255a7f1de9bSPaolo Bonzini 				union kvm_cpu_role cpu_role)
52560f04a2acSVitaly Kuznetsov {
52578c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
525856b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
525956b321f9SPaolo Bonzini 
526056b321f9SPaolo Bonzini 	root_role = cpu_role.base;
526156b321f9SPaolo Bonzini 
526256b321f9SPaolo Bonzini 	/* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
526356b321f9SPaolo Bonzini 	root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
526456b321f9SPaolo Bonzini 
526556b321f9SPaolo Bonzini 	/*
526656b321f9SPaolo Bonzini 	 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
526756b321f9SPaolo Bonzini 	 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
526856b321f9SPaolo Bonzini 	 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
526956b321f9SPaolo Bonzini 	 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
527056b321f9SPaolo Bonzini 	 * The iTLB multi-hit workaround can be toggled at any time, so assume
527156b321f9SPaolo Bonzini 	 * NX can be used by any non-nested shadow MMU to avoid having to reset
527256b321f9SPaolo Bonzini 	 * MMU contexts.
527356b321f9SPaolo Bonzini 	 */
527456b321f9SPaolo Bonzini 	root_role.efer_nx = true;
52750f04a2acSVitaly Kuznetsov 
52767a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
52770f04a2acSVitaly Kuznetsov }
52780f04a2acSVitaly Kuznetsov 
5279dbc4739bSSean Christopherson void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5280dbc4739bSSean Christopherson 			     unsigned long cr4, u64 efer, gpa_t nested_cr3)
52810f04a2acSVitaly Kuznetsov {
52828c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5283594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
5284594e91a1SSean Christopherson 		.cr0 = cr0,
528528f091bcSPaolo Bonzini 		.cr4 = cr4 & ~X86_CR4_PKE,
5286594e91a1SSean Christopherson 		.efer = efer,
5287594e91a1SSean Christopherson 	};
52887a7ae829SPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
528956b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
529056b321f9SPaolo Bonzini 
529156b321f9SPaolo Bonzini 	/* NPT requires CR0.PG=1. */
529256b321f9SPaolo Bonzini 	WARN_ON_ONCE(cpu_role.base.direct);
529356b321f9SPaolo Bonzini 
529456b321f9SPaolo Bonzini 	root_role = cpu_role.base;
529556b321f9SPaolo Bonzini 	root_role.level = kvm_mmu_get_tdp_level(vcpu);
529684e5ffd0SLai Jiangshan 	if (root_role.level == PT64_ROOT_5LEVEL &&
529784e5ffd0SLai Jiangshan 	    cpu_role.base.level == PT64_ROOT_4LEVEL)
529884e5ffd0SLai Jiangshan 		root_role.passthrough = 1;
52990f04a2acSVitaly Kuznetsov 
53007a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5301d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, nested_cr3);
53020f04a2acSVitaly Kuznetsov }
53030f04a2acSVitaly Kuznetsov EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5304c50d8ae3SPaolo Bonzini 
53057a7ae829SPaolo Bonzini static union kvm_cpu_role
5306c50d8ae3SPaolo Bonzini kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5307bb1fcc70SSean Christopherson 				   bool execonly, u8 level)
5308c50d8ae3SPaolo Bonzini {
53097a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5310c50d8ae3SPaolo Bonzini 
5311daed87b8SPaolo Bonzini 	/*
5312daed87b8SPaolo Bonzini 	 * KVM does not support SMM transfer monitors, and consequently does not
5313daed87b8SPaolo Bonzini 	 * support the "entry to SMM" control either.  role.base.smm is always 0.
5314daed87b8SPaolo Bonzini 	 */
5315daed87b8SPaolo Bonzini 	WARN_ON_ONCE(is_smm(vcpu));
5316bb1fcc70SSean Christopherson 	role.base.level = level;
5317bb3b394dSLai Jiangshan 	role.base.has_4_byte_gpte = false;
5318c50d8ae3SPaolo Bonzini 	role.base.direct = false;
5319c50d8ae3SPaolo Bonzini 	role.base.ad_disabled = !accessed_dirty;
5320c50d8ae3SPaolo Bonzini 	role.base.guest_mode = true;
5321c50d8ae3SPaolo Bonzini 	role.base.access = ACC_ALL;
5322c50d8ae3SPaolo Bonzini 
5323cd6767c3SSean Christopherson 	role.ext.word = 0;
5324c50d8ae3SPaolo Bonzini 	role.ext.execonly = execonly;
5325cd6767c3SSean Christopherson 	role.ext.valid = 1;
5326c50d8ae3SPaolo Bonzini 
5327c50d8ae3SPaolo Bonzini 	return role;
5328c50d8ae3SPaolo Bonzini }
5329c50d8ae3SPaolo Bonzini 
5330c50d8ae3SPaolo Bonzini void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5331cc022ae1SLai Jiangshan 			     int huge_page_level, bool accessed_dirty,
5332cc022ae1SLai Jiangshan 			     gpa_t new_eptp)
5333c50d8ae3SPaolo Bonzini {
53348c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5335bb1fcc70SSean Christopherson 	u8 level = vmx_eptp_page_walk_level(new_eptp);
53367a7ae829SPaolo Bonzini 	union kvm_cpu_role new_mode =
5337c50d8ae3SPaolo Bonzini 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5338bb1fcc70SSean Christopherson 						   execonly, level);
5339c50d8ae3SPaolo Bonzini 
5340e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 != context->cpu_role.as_u64) {
5341e5ed0fb0SPaolo Bonzini 		/* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5342e5ed0fb0SPaolo Bonzini 		context->cpu_role.as_u64 = new_mode.as_u64;
53437a458f0eSPaolo Bonzini 		context->root_role.word = new_mode.base.word;
534418db1b17SSean Christopherson 
5345c50d8ae3SPaolo Bonzini 		context->page_fault = ept_page_fault;
5346c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = ept_gva_to_gpa;
5347c3c6c9fcSLai Jiangshan 		context->sync_spte = ept_sync_spte;
5348347a0d0dSPaolo Bonzini 
5349c596f147SSean Christopherson 		update_permission_bitmask(context, true);
535028f091bcSPaolo Bonzini 		context->pkru_mask = 0;
5351cc022ae1SLai Jiangshan 		reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5352e8f6e738SJinrong Liang 		reset_ept_shadow_zero_bits_mask(context, execonly);
5353c50d8ae3SPaolo Bonzini 	}
53543cffc89dSPaolo Bonzini 
5355d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, new_eptp);
53563cffc89dSPaolo Bonzini }
5357c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5358c50d8ae3SPaolo Bonzini 
535939e7e2bfSPaolo Bonzini static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5360a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5361c50d8ae3SPaolo Bonzini {
53628c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5363c50d8ae3SPaolo Bonzini 
5364a7f1de9bSPaolo Bonzini 	kvm_init_shadow_mmu(vcpu, cpu_role);
5365929d1cfaSPaolo Bonzini 
53662fdcc1b3SPaolo Bonzini 	context->get_guest_pgd     = get_guest_cr3;
5367c50d8ae3SPaolo Bonzini 	context->get_pdptr         = kvm_pdptr_read;
5368c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5369c50d8ae3SPaolo Bonzini }
5370c50d8ae3SPaolo Bonzini 
537139e7e2bfSPaolo Bonzini static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5372a7f1de9bSPaolo Bonzini 				union kvm_cpu_role new_mode)
5373c50d8ae3SPaolo Bonzini {
5374c50d8ae3SPaolo Bonzini 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5375c50d8ae3SPaolo Bonzini 
5376e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5377c50d8ae3SPaolo Bonzini 		return;
5378c50d8ae3SPaolo Bonzini 
5379e5ed0fb0SPaolo Bonzini 	g_context->cpu_role.as_u64   = new_mode.as_u64;
53802fdcc1b3SPaolo Bonzini 	g_context->get_guest_pgd     = get_guest_cr3;
5381c50d8ae3SPaolo Bonzini 	g_context->get_pdptr         = kvm_pdptr_read;
5382c50d8ae3SPaolo Bonzini 	g_context->inject_page_fault = kvm_inject_page_fault;
5383c50d8ae3SPaolo Bonzini 
5384c50d8ae3SPaolo Bonzini 	/*
53855efac074SPaolo Bonzini 	 * L2 page tables are never shadowed, so there is no need to sync
53865efac074SPaolo Bonzini 	 * SPTEs.
53875efac074SPaolo Bonzini 	 */
53889fd4a4e3SLai Jiangshan 	g_context->sync_spte         = NULL;
53895efac074SPaolo Bonzini 
53905efac074SPaolo Bonzini 	/*
5391c50d8ae3SPaolo Bonzini 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5392c50d8ae3SPaolo Bonzini 	 * L1's nested page tables (e.g. EPT12). The nested translation
5393c50d8ae3SPaolo Bonzini 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5394c50d8ae3SPaolo Bonzini 	 * L2's page tables as the first level of translation and L1's
5395c50d8ae3SPaolo Bonzini 	 * nested page tables as the second level of translation. Basically
5396c50d8ae3SPaolo Bonzini 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5397c50d8ae3SPaolo Bonzini 	 */
5398fa4b5588SSean Christopherson 	if (!is_paging(vcpu))
53991f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5400fa4b5588SSean Christopherson 	else if (is_long_mode(vcpu))
54011f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5402fa4b5588SSean Christopherson 	else if (is_pae(vcpu))
54031f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5404fa4b5588SSean Christopherson 	else
54051f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging32_gva_to_gpa;
5406fa4b5588SSean Christopherson 
5407533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, g_context);
5408c50d8ae3SPaolo Bonzini }
5409c50d8ae3SPaolo Bonzini 
5410c9060662SSean Christopherson void kvm_init_mmu(struct kvm_vcpu *vcpu)
5411c50d8ae3SPaolo Bonzini {
541239e7e2bfSPaolo Bonzini 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5413a7f1de9bSPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
541439e7e2bfSPaolo Bonzini 
5415c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
5416a7f1de9bSPaolo Bonzini 		init_kvm_nested_mmu(vcpu, cpu_role);
5417c50d8ae3SPaolo Bonzini 	else if (tdp_enabled)
5418a7f1de9bSPaolo Bonzini 		init_kvm_tdp_mmu(vcpu, cpu_role);
5419c50d8ae3SPaolo Bonzini 	else
5420a7f1de9bSPaolo Bonzini 		init_kvm_softmmu(vcpu, cpu_role);
5421c50d8ae3SPaolo Bonzini }
5422c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_mmu);
5423c50d8ae3SPaolo Bonzini 
542449c6f875SSean Christopherson void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
542549c6f875SSean Christopherson {
542649c6f875SSean Christopherson 	/*
542749c6f875SSean Christopherson 	 * Invalidate all MMU roles to force them to reinitialize as CPUID
542849c6f875SSean Christopherson 	 * information is factored into reserved bit calculations.
5429feb627e8SVitaly Kuznetsov 	 *
5430feb627e8SVitaly Kuznetsov 	 * Correctly handling multiple vCPU models with respect to paging and
5431feb627e8SVitaly Kuznetsov 	 * physical address properties) in a single VM would require tracking
5432feb627e8SVitaly Kuznetsov 	 * all relevant CPUID information in kvm_mmu_page_role. That is very
5433feb627e8SVitaly Kuznetsov 	 * undesirable as it would increase the memory requirements for
5434338068b5SSean Christopherson 	 * gfn_write_track (see struct kvm_mmu_page_role comments).  For now
5435338068b5SSean Christopherson 	 * that problem is swept under the rug; KVM's CPUID API is horrific and
5436feb627e8SVitaly Kuznetsov 	 * it's all but impossible to solve it without introducing a new API.
543749c6f875SSean Christopherson 	 */
54387a458f0eSPaolo Bonzini 	vcpu->arch.root_mmu.root_role.word = 0;
54397a458f0eSPaolo Bonzini 	vcpu->arch.guest_mmu.root_role.word = 0;
54407a458f0eSPaolo Bonzini 	vcpu->arch.nested_mmu.root_role.word = 0;
5441e5ed0fb0SPaolo Bonzini 	vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5442e5ed0fb0SPaolo Bonzini 	vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5443e5ed0fb0SPaolo Bonzini 	vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
544449c6f875SSean Christopherson 	kvm_mmu_reset_context(vcpu);
544563f5a190SSean Christopherson 
544663f5a190SSean Christopherson 	/*
5447feb627e8SVitaly Kuznetsov 	 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5448feb627e8SVitaly Kuznetsov 	 * kvm_arch_vcpu_ioctl().
544963f5a190SSean Christopherson 	 */
5450fb3146b4SSean Christopherson 	KVM_BUG_ON(kvm_vcpu_has_run(vcpu), vcpu->kvm);
545149c6f875SSean Christopherson }
545249c6f875SSean Christopherson 
5453c50d8ae3SPaolo Bonzini void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5454c50d8ae3SPaolo Bonzini {
5455c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
5456c9060662SSean Christopherson 	kvm_init_mmu(vcpu);
5457c50d8ae3SPaolo Bonzini }
5458c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5459c50d8ae3SPaolo Bonzini 
5460c50d8ae3SPaolo Bonzini int kvm_mmu_load(struct kvm_vcpu *vcpu)
5461c50d8ae3SPaolo Bonzini {
5462c50d8ae3SPaolo Bonzini 	int r;
5463c50d8ae3SPaolo Bonzini 
5464347a0d0dSPaolo Bonzini 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5465c50d8ae3SPaolo Bonzini 	if (r)
5466c50d8ae3SPaolo Bonzini 		goto out;
5467748e52b9SSean Christopherson 	r = mmu_alloc_special_roots(vcpu);
5468c50d8ae3SPaolo Bonzini 	if (r)
5469c50d8ae3SPaolo Bonzini 		goto out;
5470347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
54716e6ec584SSean Christopherson 		r = mmu_alloc_direct_roots(vcpu);
54726e6ec584SSean Christopherson 	else
54736e6ec584SSean Christopherson 		r = mmu_alloc_shadow_roots(vcpu);
5474c50d8ae3SPaolo Bonzini 	if (r)
5475c50d8ae3SPaolo Bonzini 		goto out;
5476a91f387bSSean Christopherson 
5477a91f387bSSean Christopherson 	kvm_mmu_sync_roots(vcpu);
5478a91f387bSSean Christopherson 
5479727a7e27SPaolo Bonzini 	kvm_mmu_load_pgd(vcpu);
5480db01416bSSean Christopherson 
5481db01416bSSean Christopherson 	/*
5482db01416bSSean Christopherson 	 * Flush any TLB entries for the new root, the provenance of the root
5483db01416bSSean Christopherson 	 * is unknown.  Even if KVM ensures there are no stale TLB entries
5484db01416bSSean Christopherson 	 * for a freed root, in theory another hypervisor could have left
5485db01416bSSean Christopherson 	 * stale entries.  Flushing on alloc also allows KVM to skip the TLB
5486db01416bSSean Christopherson 	 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5487db01416bSSean Christopherson 	 */
5488e27bc044SSean Christopherson 	static_call(kvm_x86_flush_tlb_current)(vcpu);
5489c50d8ae3SPaolo Bonzini out:
5490c50d8ae3SPaolo Bonzini 	return r;
5491c50d8ae3SPaolo Bonzini }
5492c50d8ae3SPaolo Bonzini 
5493c50d8ae3SPaolo Bonzini void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5494c50d8ae3SPaolo Bonzini {
54950c1c92f1SPaolo Bonzini 	struct kvm *kvm = vcpu->kvm;
54960c1c92f1SPaolo Bonzini 
54970c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
549820ba462dSSean Christopherson 	WARN_ON_ONCE(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
54990c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
550020ba462dSSean Christopherson 	WARN_ON_ONCE(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
55016d58f275SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5502c50d8ae3SPaolo Bonzini }
5503c50d8ae3SPaolo Bonzini 
5504527d5cd7SSean Christopherson static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5505527d5cd7SSean Christopherson {
5506527d5cd7SSean Christopherson 	struct kvm_mmu_page *sp;
5507527d5cd7SSean Christopherson 
5508527d5cd7SSean Christopherson 	if (!VALID_PAGE(root_hpa))
5509527d5cd7SSean Christopherson 		return false;
5510527d5cd7SSean Christopherson 
5511527d5cd7SSean Christopherson 	/*
5512527d5cd7SSean Christopherson 	 * When freeing obsolete roots, treat roots as obsolete if they don't
5513527d5cd7SSean Christopherson 	 * have an associated shadow page.  This does mean KVM will get false
5514527d5cd7SSean Christopherson 	 * positives and free roots that don't strictly need to be freed, but
5515527d5cd7SSean Christopherson 	 * such false positives are relatively rare:
5516527d5cd7SSean Christopherson 	 *
5517527d5cd7SSean Christopherson 	 *  (a) only PAE paging and nested NPT has roots without shadow pages
5518527d5cd7SSean Christopherson 	 *  (b) remote reloads due to a memslot update obsoletes _all_ roots
5519527d5cd7SSean Christopherson 	 *  (c) KVM doesn't track previous roots for PAE paging, and the guest
5520527d5cd7SSean Christopherson 	 *      is unlikely to zap an in-use PGD.
5521527d5cd7SSean Christopherson 	 */
5522c5f2d564SSean Christopherson 	sp = root_to_sp(root_hpa);
5523527d5cd7SSean Christopherson 	return !sp || is_obsolete_sp(kvm, sp);
5524527d5cd7SSean Christopherson }
5525527d5cd7SSean Christopherson 
5526527d5cd7SSean Christopherson static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5527527d5cd7SSean Christopherson {
5528527d5cd7SSean Christopherson 	unsigned long roots_to_free = 0;
5529527d5cd7SSean Christopherson 	int i;
5530527d5cd7SSean Christopherson 
5531527d5cd7SSean Christopherson 	if (is_obsolete_root(kvm, mmu->root.hpa))
5532527d5cd7SSean Christopherson 		roots_to_free |= KVM_MMU_ROOT_CURRENT;
5533527d5cd7SSean Christopherson 
5534527d5cd7SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5535cf4a8693SShaoqin Huang 		if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5536527d5cd7SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5537527d5cd7SSean Christopherson 	}
5538527d5cd7SSean Christopherson 
5539527d5cd7SSean Christopherson 	if (roots_to_free)
5540527d5cd7SSean Christopherson 		kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5541527d5cd7SSean Christopherson }
5542527d5cd7SSean Christopherson 
5543527d5cd7SSean Christopherson void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5544527d5cd7SSean Christopherson {
5545527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5546527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5547527d5cd7SSean Christopherson }
5548527d5cd7SSean Christopherson 
5549c50d8ae3SPaolo Bonzini static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5550c50d8ae3SPaolo Bonzini 				    int *bytes)
5551c50d8ae3SPaolo Bonzini {
5552c50d8ae3SPaolo Bonzini 	u64 gentry = 0;
5553c50d8ae3SPaolo Bonzini 	int r;
5554c50d8ae3SPaolo Bonzini 
5555c50d8ae3SPaolo Bonzini 	/*
5556c50d8ae3SPaolo Bonzini 	 * Assume that the pte write on a page table of the same type
5557c50d8ae3SPaolo Bonzini 	 * as the current vcpu paging mode since we update the sptes only
5558c50d8ae3SPaolo Bonzini 	 * when they have the same mode.
5559c50d8ae3SPaolo Bonzini 	 */
5560c50d8ae3SPaolo Bonzini 	if (is_pae(vcpu) && *bytes == 4) {
5561c50d8ae3SPaolo Bonzini 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5562c50d8ae3SPaolo Bonzini 		*gpa &= ~(gpa_t)7;
5563c50d8ae3SPaolo Bonzini 		*bytes = 8;
5564c50d8ae3SPaolo Bonzini 	}
5565c50d8ae3SPaolo Bonzini 
5566c50d8ae3SPaolo Bonzini 	if (*bytes == 4 || *bytes == 8) {
5567c50d8ae3SPaolo Bonzini 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5568c50d8ae3SPaolo Bonzini 		if (r)
5569c50d8ae3SPaolo Bonzini 			gentry = 0;
5570c50d8ae3SPaolo Bonzini 	}
5571c50d8ae3SPaolo Bonzini 
5572c50d8ae3SPaolo Bonzini 	return gentry;
5573c50d8ae3SPaolo Bonzini }
5574c50d8ae3SPaolo Bonzini 
5575c50d8ae3SPaolo Bonzini /*
5576c50d8ae3SPaolo Bonzini  * If we're seeing too many writes to a page, it may no longer be a page table,
5577c50d8ae3SPaolo Bonzini  * or we may be forking, in which case it is better to unmap the page.
5578c50d8ae3SPaolo Bonzini  */
5579c50d8ae3SPaolo Bonzini static bool detect_write_flooding(struct kvm_mmu_page *sp)
5580c50d8ae3SPaolo Bonzini {
5581c50d8ae3SPaolo Bonzini 	/*
5582c50d8ae3SPaolo Bonzini 	 * Skip write-flooding detected for the sp whose level is 1, because
5583c50d8ae3SPaolo Bonzini 	 * it can become unsync, then the guest page is not write-protected.
5584c50d8ae3SPaolo Bonzini 	 */
55853bae0459SSean Christopherson 	if (sp->role.level == PG_LEVEL_4K)
5586c50d8ae3SPaolo Bonzini 		return false;
5587c50d8ae3SPaolo Bonzini 
5588c50d8ae3SPaolo Bonzini 	atomic_inc(&sp->write_flooding_count);
5589c50d8ae3SPaolo Bonzini 	return atomic_read(&sp->write_flooding_count) >= 3;
5590c50d8ae3SPaolo Bonzini }
5591c50d8ae3SPaolo Bonzini 
5592c50d8ae3SPaolo Bonzini /*
5593c50d8ae3SPaolo Bonzini  * Misaligned accesses are too much trouble to fix up; also, they usually
5594c50d8ae3SPaolo Bonzini  * indicate a page is not used as a page table.
5595c50d8ae3SPaolo Bonzini  */
5596c50d8ae3SPaolo Bonzini static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5597c50d8ae3SPaolo Bonzini 				    int bytes)
5598c50d8ae3SPaolo Bonzini {
5599c50d8ae3SPaolo Bonzini 	unsigned offset, pte_size, misaligned;
5600c50d8ae3SPaolo Bonzini 
5601c50d8ae3SPaolo Bonzini 	offset = offset_in_page(gpa);
5602bb3b394dSLai Jiangshan 	pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5603c50d8ae3SPaolo Bonzini 
5604c50d8ae3SPaolo Bonzini 	/*
5605c50d8ae3SPaolo Bonzini 	 * Sometimes, the OS only writes the last one bytes to update status
5606c50d8ae3SPaolo Bonzini 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5607c50d8ae3SPaolo Bonzini 	 */
5608c50d8ae3SPaolo Bonzini 	if (!(offset & (pte_size - 1)) && bytes == 1)
5609c50d8ae3SPaolo Bonzini 		return false;
5610c50d8ae3SPaolo Bonzini 
5611c50d8ae3SPaolo Bonzini 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5612c50d8ae3SPaolo Bonzini 	misaligned |= bytes < 4;
5613c50d8ae3SPaolo Bonzini 
5614c50d8ae3SPaolo Bonzini 	return misaligned;
5615c50d8ae3SPaolo Bonzini }
5616c50d8ae3SPaolo Bonzini 
5617c50d8ae3SPaolo Bonzini static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5618c50d8ae3SPaolo Bonzini {
5619c50d8ae3SPaolo Bonzini 	unsigned page_offset, quadrant;
5620c50d8ae3SPaolo Bonzini 	u64 *spte;
5621c50d8ae3SPaolo Bonzini 	int level;
5622c50d8ae3SPaolo Bonzini 
5623c50d8ae3SPaolo Bonzini 	page_offset = offset_in_page(gpa);
5624c50d8ae3SPaolo Bonzini 	level = sp->role.level;
5625c50d8ae3SPaolo Bonzini 	*nspte = 1;
5626bb3b394dSLai Jiangshan 	if (sp->role.has_4_byte_gpte) {
5627c50d8ae3SPaolo Bonzini 		page_offset <<= 1;	/* 32->64 */
5628c50d8ae3SPaolo Bonzini 		/*
5629c50d8ae3SPaolo Bonzini 		 * A 32-bit pde maps 4MB while the shadow pdes map
5630c50d8ae3SPaolo Bonzini 		 * only 2MB.  So we need to double the offset again
5631c50d8ae3SPaolo Bonzini 		 * and zap two pdes instead of one.
5632c50d8ae3SPaolo Bonzini 		 */
5633c50d8ae3SPaolo Bonzini 		if (level == PT32_ROOT_LEVEL) {
5634c50d8ae3SPaolo Bonzini 			page_offset &= ~7; /* kill rounding error */
5635c50d8ae3SPaolo Bonzini 			page_offset <<= 1;
5636c50d8ae3SPaolo Bonzini 			*nspte = 2;
5637c50d8ae3SPaolo Bonzini 		}
5638c50d8ae3SPaolo Bonzini 		quadrant = page_offset >> PAGE_SHIFT;
5639c50d8ae3SPaolo Bonzini 		page_offset &= ~PAGE_MASK;
5640c50d8ae3SPaolo Bonzini 		if (quadrant != sp->role.quadrant)
5641c50d8ae3SPaolo Bonzini 			return NULL;
5642c50d8ae3SPaolo Bonzini 	}
5643c50d8ae3SPaolo Bonzini 
5644c50d8ae3SPaolo Bonzini 	spte = &sp->spt[page_offset / sizeof(*spte)];
5645c50d8ae3SPaolo Bonzini 	return spte;
5646c50d8ae3SPaolo Bonzini }
5647c50d8ae3SPaolo Bonzini 
564893284446SSean Christopherson void kvm_mmu_track_write(struct kvm_vcpu *vcpu, gpa_t gpa, const u8 *new,
564993284446SSean Christopherson 			 int bytes)
5650c50d8ae3SPaolo Bonzini {
5651c50d8ae3SPaolo Bonzini 	gfn_t gfn = gpa >> PAGE_SHIFT;
5652c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
5653c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
5654c50d8ae3SPaolo Bonzini 	u64 entry, gentry, *spte;
5655c50d8ae3SPaolo Bonzini 	int npte;
565606152b2dSLai Jiangshan 	bool flush = false;
5657c50d8ae3SPaolo Bonzini 
5658c50d8ae3SPaolo Bonzini 	/*
5659c50d8ae3SPaolo Bonzini 	 * If we don't have indirect shadow pages, it means no page is
5660c50d8ae3SPaolo Bonzini 	 * write-protected, so we can exit simply.
5661c50d8ae3SPaolo Bonzini 	 */
5662c50d8ae3SPaolo Bonzini 	if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5663c50d8ae3SPaolo Bonzini 		return;
5664c50d8ae3SPaolo Bonzini 
5665531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
5666c50d8ae3SPaolo Bonzini 
5667c50d8ae3SPaolo Bonzini 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5668c50d8ae3SPaolo Bonzini 
5669c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_pte_write;
5670c50d8ae3SPaolo Bonzini 
5671767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5672c50d8ae3SPaolo Bonzini 		if (detect_write_misaligned(sp, gpa, bytes) ||
5673c50d8ae3SPaolo Bonzini 		      detect_write_flooding(sp)) {
5674c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5675c50d8ae3SPaolo Bonzini 			++vcpu->kvm->stat.mmu_flooded;
5676c50d8ae3SPaolo Bonzini 			continue;
5677c50d8ae3SPaolo Bonzini 		}
5678c50d8ae3SPaolo Bonzini 
5679c50d8ae3SPaolo Bonzini 		spte = get_written_sptes(sp, gpa, &npte);
5680c50d8ae3SPaolo Bonzini 		if (!spte)
5681c50d8ae3SPaolo Bonzini 			continue;
5682c50d8ae3SPaolo Bonzini 
5683c50d8ae3SPaolo Bonzini 		while (npte--) {
5684c50d8ae3SPaolo Bonzini 			entry = *spte;
56852de4085cSBen Gardon 			mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5686c5e2184dSSean Christopherson 			if (gentry && sp->role.level != PG_LEVEL_4K)
5687c5e2184dSSean Christopherson 				++vcpu->kvm->stat.mmu_pde_zapped;
56881441ca14SJunaid Shahid 			if (is_shadow_present_pte(entry))
568906152b2dSLai Jiangshan 				flush = true;
5690c50d8ae3SPaolo Bonzini 			++spte;
5691c50d8ae3SPaolo Bonzini 		}
5692c50d8ae3SPaolo Bonzini 	}
569306152b2dSLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5694531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
5695c50d8ae3SPaolo Bonzini }
5696c50d8ae3SPaolo Bonzini 
56971075d41eSSean Christopherson int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5698c50d8ae3SPaolo Bonzini 		       void *insn, int insn_len)
5699c50d8ae3SPaolo Bonzini {
570092daa48bSSean Christopherson 	int r, emulation_type = EMULTYPE_PF;
5701347a0d0dSPaolo Bonzini 	bool direct = vcpu->arch.mmu->root_role.direct;
5702c50d8ae3SPaolo Bonzini 
5703d09f7112SSean Christopherson 	/*
5704d09f7112SSean Christopherson 	 * IMPLICIT_ACCESS is a KVM-defined flag used to correctly perform SMAP
5705d09f7112SSean Christopherson 	 * checks when emulating instructions that triggers implicit access.
5706d09f7112SSean Christopherson 	 * WARN if hardware generates a fault with an error code that collides
5707d09f7112SSean Christopherson 	 * with the KVM-defined value.  Clear the flag and continue on, i.e.
5708d09f7112SSean Christopherson 	 * don't terminate the VM, as KVM can't possibly be relying on a flag
5709d09f7112SSean Christopherson 	 * that KVM doesn't know about.
5710d09f7112SSean Christopherson 	 */
5711d09f7112SSean Christopherson 	if (WARN_ON_ONCE(error_code & PFERR_IMPLICIT_ACCESS))
5712d09f7112SSean Christopherson 		error_code &= ~PFERR_IMPLICIT_ACCESS;
5713d09f7112SSean Christopherson 
571420ba462dSSean Christopherson 	if (WARN_ON_ONCE(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5715ddce6208SSean Christopherson 		return RET_PF_RETRY;
5716ddce6208SSean Christopherson 
5717c50d8ae3SPaolo Bonzini 	r = RET_PF_INVALID;
5718c50d8ae3SPaolo Bonzini 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
5719736c291cSSean Christopherson 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5720c50d8ae3SPaolo Bonzini 		if (r == RET_PF_EMULATE)
5721c50d8ae3SPaolo Bonzini 			goto emulate;
5722c50d8ae3SPaolo Bonzini 	}
5723c50d8ae3SPaolo Bonzini 
5724c50d8ae3SPaolo Bonzini 	if (r == RET_PF_INVALID) {
57257a02674dSSean Christopherson 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
5726258d985fSSean Christopherson 					  lower_32_bits(error_code), false,
5727258d985fSSean Christopherson 					  &emulation_type);
572819025e7bSSean Christopherson 		if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
57297b367bc9SSean Christopherson 			return -EIO;
5730c50d8ae3SPaolo Bonzini 	}
5731c50d8ae3SPaolo Bonzini 
5732c50d8ae3SPaolo Bonzini 	if (r < 0)
5733c50d8ae3SPaolo Bonzini 		return r;
573483a2ba4cSSean Christopherson 	if (r != RET_PF_EMULATE)
573583a2ba4cSSean Christopherson 		return 1;
5736c50d8ae3SPaolo Bonzini 
5737c50d8ae3SPaolo Bonzini 	/*
5738c50d8ae3SPaolo Bonzini 	 * Before emulating the instruction, check if the error code
5739c50d8ae3SPaolo Bonzini 	 * was due to a RO violation while translating the guest page.
5740c50d8ae3SPaolo Bonzini 	 * This can occur when using nested virtualization with nested
5741c50d8ae3SPaolo Bonzini 	 * paging in both guests. If true, we simply unprotect the page
5742c50d8ae3SPaolo Bonzini 	 * and resume the guest.
5743c50d8ae3SPaolo Bonzini 	 */
5744347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct &&
5745c50d8ae3SPaolo Bonzini 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5746736c291cSSean Christopherson 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5747c50d8ae3SPaolo Bonzini 		return 1;
5748c50d8ae3SPaolo Bonzini 	}
5749c50d8ae3SPaolo Bonzini 
5750c50d8ae3SPaolo Bonzini 	/*
5751c50d8ae3SPaolo Bonzini 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5752c50d8ae3SPaolo Bonzini 	 * optimistically try to just unprotect the page and let the processor
5753c50d8ae3SPaolo Bonzini 	 * re-execute the instruction that caused the page fault.  Do not allow
5754c50d8ae3SPaolo Bonzini 	 * retrying MMIO emulation, as it's not only pointless but could also
5755c50d8ae3SPaolo Bonzini 	 * cause us to enter an infinite loop because the processor will keep
5756c50d8ae3SPaolo Bonzini 	 * faulting on the non-existent MMIO address.  Retrying an instruction
5757c50d8ae3SPaolo Bonzini 	 * from a nested guest is also pointless and dangerous as we are only
5758c50d8ae3SPaolo Bonzini 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
5759c50d8ae3SPaolo Bonzini 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5760c50d8ae3SPaolo Bonzini 	 */
5761736c291cSSean Christopherson 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
576292daa48bSSean Christopherson 		emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5763c50d8ae3SPaolo Bonzini emulate:
5764736c291cSSean Christopherson 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5765c50d8ae3SPaolo Bonzini 				       insn_len);
5766c50d8ae3SPaolo Bonzini }
5767c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5768c50d8ae3SPaolo Bonzini 
57699fd4a4e3SLai Jiangshan static void __kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
57709fd4a4e3SLai Jiangshan 				      u64 addr, hpa_t root_hpa)
57719fd4a4e3SLai Jiangshan {
57729fd4a4e3SLai Jiangshan 	struct kvm_shadow_walk_iterator iterator;
57739fd4a4e3SLai Jiangshan 
57749fd4a4e3SLai Jiangshan 	vcpu_clear_mmio_info(vcpu, addr);
57759fd4a4e3SLai Jiangshan 
5776762b33ebSLike Xu 	/*
5777762b33ebSLike Xu 	 * Walking and synchronizing SPTEs both assume they are operating in
5778762b33ebSLike Xu 	 * the context of the current MMU, and would need to be reworked if
5779762b33ebSLike Xu 	 * this is ever used to sync the guest_mmu, e.g. to emulate INVEPT.
5780762b33ebSLike Xu 	 */
5781762b33ebSLike Xu 	if (WARN_ON_ONCE(mmu != vcpu->arch.mmu))
5782762b33ebSLike Xu 		return;
5783762b33ebSLike Xu 
57849fd4a4e3SLai Jiangshan 	if (!VALID_PAGE(root_hpa))
57859fd4a4e3SLai Jiangshan 		return;
57869fd4a4e3SLai Jiangshan 
57879fd4a4e3SLai Jiangshan 	write_lock(&vcpu->kvm->mmu_lock);
57889fd4a4e3SLai Jiangshan 	for_each_shadow_entry_using_root(vcpu, root_hpa, addr, iterator) {
57899fd4a4e3SLai Jiangshan 		struct kvm_mmu_page *sp = sptep_to_sp(iterator.sptep);
57909fd4a4e3SLai Jiangshan 
57919fd4a4e3SLai Jiangshan 		if (sp->unsync) {
579219ace7d6SLai Jiangshan 			int ret = kvm_sync_spte(vcpu, sp, iterator.index);
57939fd4a4e3SLai Jiangshan 
57949fd4a4e3SLai Jiangshan 			if (ret < 0)
57959fd4a4e3SLai Jiangshan 				mmu_page_zap_pte(vcpu->kvm, sp, iterator.sptep, NULL);
57969fd4a4e3SLai Jiangshan 			if (ret)
57979fd4a4e3SLai Jiangshan 				kvm_flush_remote_tlbs_sptep(vcpu->kvm, iterator.sptep);
57989fd4a4e3SLai Jiangshan 		}
57999fd4a4e3SLai Jiangshan 
58009fd4a4e3SLai Jiangshan 		if (!sp->unsync_children)
58019fd4a4e3SLai Jiangshan 			break;
58029fd4a4e3SLai Jiangshan 	}
58039fd4a4e3SLai Jiangshan 	write_unlock(&vcpu->kvm->mmu_lock);
58049fd4a4e3SLai Jiangshan }
58059fd4a4e3SLai Jiangshan 
5806753b43c9SLai Jiangshan void kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5807cd42853eSLai Jiangshan 			     u64 addr, unsigned long roots)
5808c50d8ae3SPaolo Bonzini {
5809c50d8ae3SPaolo Bonzini 	int i;
5810c50d8ae3SPaolo Bonzini 
5811cd42853eSLai Jiangshan 	WARN_ON_ONCE(roots & ~KVM_MMU_ROOTS_ALL);
5812cd42853eSLai Jiangshan 
58135efac074SPaolo Bonzini 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
58145efac074SPaolo Bonzini 	if (mmu != &vcpu->arch.guest_mmu) {
58155efac074SPaolo Bonzini 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
5816753b43c9SLai Jiangshan 		if (is_noncanonical_address(addr, vcpu))
5817c50d8ae3SPaolo Bonzini 			return;
5818c50d8ae3SPaolo Bonzini 
5819753b43c9SLai Jiangshan 		static_call(kvm_x86_flush_tlb_gva)(vcpu, addr);
58205efac074SPaolo Bonzini 	}
58215efac074SPaolo Bonzini 
58229fd4a4e3SLai Jiangshan 	if (!mmu->sync_spte)
58235efac074SPaolo Bonzini 		return;
58245efac074SPaolo Bonzini 
5825cd42853eSLai Jiangshan 	if (roots & KVM_MMU_ROOT_CURRENT)
58269fd4a4e3SLai Jiangshan 		__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->root.hpa);
5827c50d8ae3SPaolo Bonzini 
5828cd42853eSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5829ed335278SLai Jiangshan 		if (roots & KVM_MMU_ROOT_PREVIOUS(i))
58309fd4a4e3SLai Jiangshan 			__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->prev_roots[i].hpa);
58315efac074SPaolo Bonzini 	}
58325efac074SPaolo Bonzini }
58332c86c444SLai Jiangshan EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_addr);
5834c50d8ae3SPaolo Bonzini 
58355efac074SPaolo Bonzini void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
58365efac074SPaolo Bonzini {
5837cd42853eSLai Jiangshan 	/*
5838cd42853eSLai Jiangshan 	 * INVLPG is required to invalidate any global mappings for the VA,
5839cd42853eSLai Jiangshan 	 * irrespective of PCID.  Blindly sync all roots as it would take
5840cd42853eSLai Jiangshan 	 * roughly the same amount of work/time to determine whether any of the
5841cd42853eSLai Jiangshan 	 * previous roots have a global mapping.
5842cd42853eSLai Jiangshan 	 *
5843cd42853eSLai Jiangshan 	 * Mappings not reachable via the current or previous cached roots will
5844cd42853eSLai Jiangshan 	 * be synced when switching to that new cr3, so nothing needs to be
5845cd42853eSLai Jiangshan 	 * done here for them.
5846cd42853eSLai Jiangshan 	 */
5847cd42853eSLai Jiangshan 	kvm_mmu_invalidate_addr(vcpu, vcpu->arch.walk_mmu, gva, KVM_MMU_ROOTS_ALL);
5848c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5849c50d8ae3SPaolo Bonzini }
5850c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5851c50d8ae3SPaolo Bonzini 
58525efac074SPaolo Bonzini 
5853c50d8ae3SPaolo Bonzini void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5854c50d8ae3SPaolo Bonzini {
5855c50d8ae3SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
58569ebc3f51SLai Jiangshan 	unsigned long roots = 0;
5857c50d8ae3SPaolo Bonzini 	uint i;
5858c50d8ae3SPaolo Bonzini 
58599ebc3f51SLai Jiangshan 	if (pcid == kvm_get_active_pcid(vcpu))
58609ebc3f51SLai Jiangshan 		roots |= KVM_MMU_ROOT_CURRENT;
5861c50d8ae3SPaolo Bonzini 
5862c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5863c50d8ae3SPaolo Bonzini 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
58649ebc3f51SLai Jiangshan 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd))
58659ebc3f51SLai Jiangshan 			roots |= KVM_MMU_ROOT_PREVIOUS(i);
5866c50d8ae3SPaolo Bonzini 	}
5867c50d8ae3SPaolo Bonzini 
58689ebc3f51SLai Jiangshan 	if (roots)
58699ebc3f51SLai Jiangshan 		kvm_mmu_invalidate_addr(vcpu, mmu, gva, roots);
5870c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5871c50d8ae3SPaolo Bonzini 
5872c50d8ae3SPaolo Bonzini 	/*
5873c50d8ae3SPaolo Bonzini 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5874c50d8ae3SPaolo Bonzini 	 * synced when switching to that cr3, so nothing needs to be done here
5875c50d8ae3SPaolo Bonzini 	 * for them.
5876c50d8ae3SPaolo Bonzini 	 */
5877c50d8ae3SPaolo Bonzini }
5878c50d8ae3SPaolo Bonzini 
5879746700d2SWei Huang void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
5880746700d2SWei Huang 		       int tdp_max_root_level, int tdp_huge_page_level)
5881c50d8ae3SPaolo Bonzini {
5882bde77235SSean Christopherson 	tdp_enabled = enable_tdp;
5883746700d2SWei Huang 	tdp_root_level = tdp_forced_root_level;
588483013059SSean Christopherson 	max_tdp_level = tdp_max_root_level;
5885703c335dSSean Christopherson 
58861f98f2bdSDavid Matlack #ifdef CONFIG_X86_64
58871f98f2bdSDavid Matlack 	tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
58881f98f2bdSDavid Matlack #endif
5889703c335dSSean Christopherson 	/*
58901d92d2e8SSean Christopherson 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5891703c335dSSean Christopherson 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5892703c335dSSean Christopherson 	 * the kernel is not.  But, KVM never creates a page size greater than
5893703c335dSSean Christopherson 	 * what is used by the kernel for any given HVA, i.e. the kernel's
5894703c335dSSean Christopherson 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5895703c335dSSean Christopherson 	 */
5896703c335dSSean Christopherson 	if (tdp_enabled)
58971d92d2e8SSean Christopherson 		max_huge_page_level = tdp_huge_page_level;
5898703c335dSSean Christopherson 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
58991d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_1G;
5900703c335dSSean Christopherson 	else
59011d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_2M;
5902c50d8ae3SPaolo Bonzini }
5903bde77235SSean Christopherson EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5904c50d8ae3SPaolo Bonzini 
5905c50d8ae3SPaolo Bonzini /* The return value indicates if tlb flush on all vcpus is needed. */
5906727ae377SSean Christopherson typedef bool (*slot_rmaps_handler) (struct kvm *kvm,
5907269e9552SHamza Mahfooz 				    struct kvm_rmap_head *rmap_head,
5908269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot);
5909c50d8ae3SPaolo Bonzini 
5910727ae377SSean Christopherson static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,
5911727ae377SSean Christopherson 					      const struct kvm_memory_slot *slot,
5912727ae377SSean Christopherson 					      slot_rmaps_handler fn,
5913727ae377SSean Christopherson 					      int start_level, int end_level,
5914727ae377SSean Christopherson 					      gfn_t start_gfn, gfn_t end_gfn,
5915727ae377SSean Christopherson 					      bool flush_on_yield, bool flush)
5916c50d8ae3SPaolo Bonzini {
5917c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
5918c50d8ae3SPaolo Bonzini 
5919eddd9e83SSean Christopherson 	lockdep_assert_held_write(&kvm->mmu_lock);
5920eddd9e83SSean Christopherson 
5921727ae377SSean Christopherson 	for_each_slot_rmap_range(slot, start_level, end_level, start_gfn,
5922c50d8ae3SPaolo Bonzini 			end_gfn, &iterator) {
5923c50d8ae3SPaolo Bonzini 		if (iterator.rmap)
5924727ae377SSean Christopherson 			flush |= fn(kvm, iterator.rmap, slot);
5925c50d8ae3SPaolo Bonzini 
5926531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
5927302695a5SSean Christopherson 			if (flush && flush_on_yield) {
59288c63e8c2SDavid Matlack 				kvm_flush_remote_tlbs_range(kvm, start_gfn,
5929c50d8ae3SPaolo Bonzini 							    iterator.gfn - start_gfn + 1);
5930c50d8ae3SPaolo Bonzini 				flush = false;
5931c50d8ae3SPaolo Bonzini 			}
5932531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
5933c50d8ae3SPaolo Bonzini 		}
5934c50d8ae3SPaolo Bonzini 	}
5935c50d8ae3SPaolo Bonzini 
5936c50d8ae3SPaolo Bonzini 	return flush;
5937c50d8ae3SPaolo Bonzini }
5938c50d8ae3SPaolo Bonzini 
5939727ae377SSean Christopherson static __always_inline bool walk_slot_rmaps(struct kvm *kvm,
5940727ae377SSean Christopherson 					    const struct kvm_memory_slot *slot,
5941727ae377SSean Christopherson 					    slot_rmaps_handler fn,
5942727ae377SSean Christopherson 					    int start_level, int end_level,
5943302695a5SSean Christopherson 					    bool flush_on_yield)
5944c50d8ae3SPaolo Bonzini {
5945727ae377SSean Christopherson 	return __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,
5946727ae377SSean Christopherson 				 slot->base_gfn, slot->base_gfn + slot->npages - 1,
59471a61b7dbSSean Christopherson 				 flush_on_yield, false);
5948c50d8ae3SPaolo Bonzini }
5949c50d8ae3SPaolo Bonzini 
5950727ae377SSean Christopherson static __always_inline bool walk_slot_rmaps_4k(struct kvm *kvm,
5951727ae377SSean Christopherson 					       const struct kvm_memory_slot *slot,
5952727ae377SSean Christopherson 					       slot_rmaps_handler fn,
5953727ae377SSean Christopherson 					       bool flush_on_yield)
5954c50d8ae3SPaolo Bonzini {
5955727ae377SSean Christopherson 	return walk_slot_rmaps(kvm, slot, fn, PG_LEVEL_4K, PG_LEVEL_4K, flush_on_yield);
5956c50d8ae3SPaolo Bonzini }
5957c50d8ae3SPaolo Bonzini 
5958c50d8ae3SPaolo Bonzini static void free_mmu_pages(struct kvm_mmu *mmu)
5959c50d8ae3SPaolo Bonzini {
59604a98623dSSean Christopherson 	if (!tdp_enabled && mmu->pae_root)
59614a98623dSSean Christopherson 		set_memory_encrypted((unsigned long)mmu->pae_root, 1);
5962c50d8ae3SPaolo Bonzini 	free_page((unsigned long)mmu->pae_root);
596303ca4589SSean Christopherson 	free_page((unsigned long)mmu->pml4_root);
5964cb0f722aSWei Huang 	free_page((unsigned long)mmu->pml5_root);
5965c50d8ae3SPaolo Bonzini }
5966c50d8ae3SPaolo Bonzini 
596704d28e37SSean Christopherson static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5968c50d8ae3SPaolo Bonzini {
5969c50d8ae3SPaolo Bonzini 	struct page *page;
5970c50d8ae3SPaolo Bonzini 	int i;
5971c50d8ae3SPaolo Bonzini 
5972b9e5603cSPaolo Bonzini 	mmu->root.hpa = INVALID_PAGE;
5973b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
597404d28e37SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
597504d28e37SSean Christopherson 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
597604d28e37SSean Christopherson 
597727f4fca2SLai Jiangshan 	/* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
597827f4fca2SLai Jiangshan 	if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
597927f4fca2SLai Jiangshan 		return 0;
598027f4fca2SLai Jiangshan 
5981c50d8ae3SPaolo Bonzini 	/*
5982c50d8ae3SPaolo Bonzini 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5983c50d8ae3SPaolo Bonzini 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
5984c50d8ae3SPaolo Bonzini 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
5985c50d8ae3SPaolo Bonzini 	 * x86_64.  Therefore we need to allocate the PDP table in the first
598604d45551SSean Christopherson 	 * 4GB of memory, which happens to fit the DMA32 zone.  TDP paging
598704d45551SSean Christopherson 	 * generally doesn't use PAE paging and can skip allocating the PDP
598804d45551SSean Christopherson 	 * table.  The main exception, handled here, is SVM's 32-bit NPT.  The
598904d45551SSean Christopherson 	 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
599084432316SLai Jiangshan 	 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
5991c50d8ae3SPaolo Bonzini 	 */
5992d468d94bSSean Christopherson 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5993c50d8ae3SPaolo Bonzini 		return 0;
5994c50d8ae3SPaolo Bonzini 
5995c50d8ae3SPaolo Bonzini 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5996c50d8ae3SPaolo Bonzini 	if (!page)
5997c50d8ae3SPaolo Bonzini 		return -ENOMEM;
5998c50d8ae3SPaolo Bonzini 
5999c50d8ae3SPaolo Bonzini 	mmu->pae_root = page_address(page);
60004a98623dSSean Christopherson 
60014a98623dSSean Christopherson 	/*
60024a98623dSSean Christopherson 	 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
60034a98623dSSean Christopherson 	 * get the CPU to treat the PDPTEs as encrypted.  Decrypt the page so
60044a98623dSSean Christopherson 	 * that KVM's writes and the CPU's reads get along.  Note, this is
60054a98623dSSean Christopherson 	 * only necessary when using shadow paging, as 64-bit NPT can get at
60064a98623dSSean Christopherson 	 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
60074a98623dSSean Christopherson 	 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
60084a98623dSSean Christopherson 	 */
60094a98623dSSean Christopherson 	if (!tdp_enabled)
60104a98623dSSean Christopherson 		set_memory_decrypted((unsigned long)mmu->pae_root, 1);
60114a98623dSSean Christopherson 	else
6012e54f1ff2SKai Huang 		WARN_ON_ONCE(shadow_me_value);
60134a98623dSSean Christopherson 
6014c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i)
6015c834e5e4SSean Christopherson 		mmu->pae_root[i] = INVALID_PAE_ROOT;
6016c50d8ae3SPaolo Bonzini 
6017c50d8ae3SPaolo Bonzini 	return 0;
6018c50d8ae3SPaolo Bonzini }
6019c50d8ae3SPaolo Bonzini 
6020c50d8ae3SPaolo Bonzini int kvm_mmu_create(struct kvm_vcpu *vcpu)
6021c50d8ae3SPaolo Bonzini {
6022c50d8ae3SPaolo Bonzini 	int ret;
6023c50d8ae3SPaolo Bonzini 
60245962bfb7SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
60255f6078f9SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
60265f6078f9SSean Christopherson 
60275962bfb7SSean Christopherson 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
60285f6078f9SSean Christopherson 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
60295962bfb7SSean Christopherson 
603096880883SSean Christopherson 	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
603196880883SSean Christopherson 
6032c50d8ae3SPaolo Bonzini 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
6033c50d8ae3SPaolo Bonzini 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6034c50d8ae3SPaolo Bonzini 
603504d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
6036c50d8ae3SPaolo Bonzini 	if (ret)
6037c50d8ae3SPaolo Bonzini 		return ret;
6038c50d8ae3SPaolo Bonzini 
603904d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
6040c50d8ae3SPaolo Bonzini 	if (ret)
6041c50d8ae3SPaolo Bonzini 		goto fail_allocate_root;
6042c50d8ae3SPaolo Bonzini 
6043c50d8ae3SPaolo Bonzini 	return ret;
6044c50d8ae3SPaolo Bonzini  fail_allocate_root:
6045c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
6046c50d8ae3SPaolo Bonzini 	return ret;
6047c50d8ae3SPaolo Bonzini }
6048c50d8ae3SPaolo Bonzini 
6049c50d8ae3SPaolo Bonzini #define BATCH_ZAP_PAGES	10
6050c50d8ae3SPaolo Bonzini static void kvm_zap_obsolete_pages(struct kvm *kvm)
6051c50d8ae3SPaolo Bonzini {
6052c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6053c50d8ae3SPaolo Bonzini 	int nr_zapped, batch = 0;
6054b28cb0cdSSean Christopherson 	bool unstable;
6055c50d8ae3SPaolo Bonzini 
6056c50d8ae3SPaolo Bonzini restart:
6057c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe_reverse(sp, node,
6058c50d8ae3SPaolo Bonzini 	      &kvm->arch.active_mmu_pages, link) {
6059c50d8ae3SPaolo Bonzini 		/*
6060c50d8ae3SPaolo Bonzini 		 * No obsolete valid page exists before a newly created page
6061c50d8ae3SPaolo Bonzini 		 * since active_mmu_pages is a FIFO list.
6062c50d8ae3SPaolo Bonzini 		 */
6063c50d8ae3SPaolo Bonzini 		if (!is_obsolete_sp(kvm, sp))
6064c50d8ae3SPaolo Bonzini 			break;
6065c50d8ae3SPaolo Bonzini 
6066c50d8ae3SPaolo Bonzini 		/*
6067f95eec9bSSean Christopherson 		 * Invalid pages should never land back on the list of active
6068f95eec9bSSean Christopherson 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
6069f95eec9bSSean Christopherson 		 * infinite loop if the page gets put back on the list (again).
6070c50d8ae3SPaolo Bonzini 		 */
607120ba462dSSean Christopherson 		if (WARN_ON_ONCE(sp->role.invalid))
6072c50d8ae3SPaolo Bonzini 			continue;
6073c50d8ae3SPaolo Bonzini 
6074c50d8ae3SPaolo Bonzini 		/*
6075c50d8ae3SPaolo Bonzini 		 * No need to flush the TLB since we're only zapping shadow
6076c50d8ae3SPaolo Bonzini 		 * pages with an obsolete generation number and all vCPUS have
6077c50d8ae3SPaolo Bonzini 		 * loaded a new root, i.e. the shadow pages being zapped cannot
6078c50d8ae3SPaolo Bonzini 		 * be in active use by the guest.
6079c50d8ae3SPaolo Bonzini 		 */
6080c50d8ae3SPaolo Bonzini 		if (batch >= BATCH_ZAP_PAGES &&
6081531810caSBen Gardon 		    cond_resched_rwlock_write(&kvm->mmu_lock)) {
6082c50d8ae3SPaolo Bonzini 			batch = 0;
6083c50d8ae3SPaolo Bonzini 			goto restart;
6084c50d8ae3SPaolo Bonzini 		}
6085c50d8ae3SPaolo Bonzini 
6086b28cb0cdSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
6087b28cb0cdSSean Christopherson 				&kvm->arch.zapped_obsolete_pages, &nr_zapped);
6088c50d8ae3SPaolo Bonzini 		batch += nr_zapped;
6089b28cb0cdSSean Christopherson 
6090b28cb0cdSSean Christopherson 		if (unstable)
6091c50d8ae3SPaolo Bonzini 			goto restart;
6092c50d8ae3SPaolo Bonzini 	}
6093c50d8ae3SPaolo Bonzini 
6094c50d8ae3SPaolo Bonzini 	/*
60957ae5840eSSean Christopherson 	 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
60967ae5840eSSean Christopherson 	 * to ensure KVM is not in the middle of a lockless shadow page table
60977ae5840eSSean Christopherson 	 * walk, which may reference the pages.  The remote TLB flush itself is
60987ae5840eSSean Christopherson 	 * not required and is simply a convenient way to kick vCPUs as needed.
60997ae5840eSSean Christopherson 	 * KVM performs a local TLB flush when allocating a new root (see
61007ae5840eSSean Christopherson 	 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
61017ae5840eSSean Christopherson 	 * running with an obsolete MMU.
6102c50d8ae3SPaolo Bonzini 	 */
6103c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
6104c50d8ae3SPaolo Bonzini }
6105c50d8ae3SPaolo Bonzini 
6106c50d8ae3SPaolo Bonzini /*
6107c50d8ae3SPaolo Bonzini  * Fast invalidate all shadow pages and use lock-break technique
6108c50d8ae3SPaolo Bonzini  * to zap obsolete pages.
6109c50d8ae3SPaolo Bonzini  *
6110c50d8ae3SPaolo Bonzini  * It's required when memslot is being deleted or VM is being
6111c50d8ae3SPaolo Bonzini  * destroyed, in these cases, we should ensure that KVM MMU does
6112c50d8ae3SPaolo Bonzini  * not use any resource of the being-deleted slot or all slots
6113c50d8ae3SPaolo Bonzini  * after calling the function.
6114c50d8ae3SPaolo Bonzini  */
6115c50d8ae3SPaolo Bonzini static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6116c50d8ae3SPaolo Bonzini {
6117c50d8ae3SPaolo Bonzini 	lockdep_assert_held(&kvm->slots_lock);
6118c50d8ae3SPaolo Bonzini 
6119531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6120c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_zap_all_fast(kvm);
6121c50d8ae3SPaolo Bonzini 
6122c50d8ae3SPaolo Bonzini 	/*
6123c50d8ae3SPaolo Bonzini 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
6124c50d8ae3SPaolo Bonzini 	 * held for the entire duration of zapping obsolete pages, it's
6125c50d8ae3SPaolo Bonzini 	 * impossible for there to be multiple invalid generations associated
6126c50d8ae3SPaolo Bonzini 	 * with *valid* shadow pages at any given time, i.e. there is exactly
6127c50d8ae3SPaolo Bonzini 	 * one valid generation and (at most) one invalid generation.
6128c50d8ae3SPaolo Bonzini 	 */
6129c50d8ae3SPaolo Bonzini 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6130c50d8ae3SPaolo Bonzini 
61312f6f66ccSSean Christopherson 	/*
61322f6f66ccSSean Christopherson 	 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
61332f6f66ccSSean Christopherson 	 * invalidating TDP MMU roots must be done while holding mmu_lock for
61342f6f66ccSSean Christopherson 	 * write and in the same critical section as making the reload request,
61352f6f66ccSSean Christopherson 	 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6136b7cccd39SBen Gardon 	 */
61371f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6138b7cccd39SBen Gardon 		kvm_tdp_mmu_invalidate_all_roots(kvm);
6139b7cccd39SBen Gardon 
6140c50d8ae3SPaolo Bonzini 	/*
6141c50d8ae3SPaolo Bonzini 	 * Notify all vcpus to reload its shadow page table and flush TLB.
6142c50d8ae3SPaolo Bonzini 	 * Then all vcpus will switch to new shadow page table with the new
6143c50d8ae3SPaolo Bonzini 	 * mmu_valid_gen.
6144c50d8ae3SPaolo Bonzini 	 *
6145c50d8ae3SPaolo Bonzini 	 * Note: we need to do this under the protection of mmu_lock,
6146c50d8ae3SPaolo Bonzini 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
6147c50d8ae3SPaolo Bonzini 	 */
6148527d5cd7SSean Christopherson 	kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6149c50d8ae3SPaolo Bonzini 
6150c50d8ae3SPaolo Bonzini 	kvm_zap_obsolete_pages(kvm);
6151faaf05b0SBen Gardon 
6152531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
61534c6654bdSBen Gardon 
6154f28e9c7fSSean Christopherson 	/*
6155f28e9c7fSSean Christopherson 	 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6156f28e9c7fSSean Christopherson 	 * returning to the caller, e.g. if the zap is in response to a memslot
6157f28e9c7fSSean Christopherson 	 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6158f28e9c7fSSean Christopherson 	 * associated with the deleted memslot once the update completes, and
6159f28e9c7fSSean Christopherson 	 * Deferring the zap until the final reference to the root is put would
6160f28e9c7fSSean Christopherson 	 * lead to use-after-free.
6161f28e9c7fSSean Christopherson 	 */
61621f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
61634c6654bdSBen Gardon 		kvm_tdp_mmu_zap_invalidated_roots(kvm);
6164c50d8ae3SPaolo Bonzini }
6165c50d8ae3SPaolo Bonzini 
6166c50d8ae3SPaolo Bonzini static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
6167c50d8ae3SPaolo Bonzini {
6168c50d8ae3SPaolo Bonzini 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
6169c50d8ae3SPaolo Bonzini }
6170c50d8ae3SPaolo Bonzini 
6171a1a39128SPaolo Bonzini int kvm_mmu_init_vm(struct kvm *kvm)
6172c50d8ae3SPaolo Bonzini {
6173a1a39128SPaolo Bonzini 	int r;
6174c50d8ae3SPaolo Bonzini 
6175a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6176a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
617755c510e2SSean Christopherson 	INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6178ce25681dSSean Christopherson 	spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6179ce25681dSSean Christopherson 
618009732d2bSDavid Matlack 	if (tdp_mmu_enabled) {
6181a1a39128SPaolo Bonzini 		r = kvm_mmu_init_tdp_mmu(kvm);
6182a1a39128SPaolo Bonzini 		if (r < 0)
6183a1a39128SPaolo Bonzini 			return r;
618409732d2bSDavid Matlack 	}
6185fe5db27dSBen Gardon 
6186ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6187ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6188ada51a9dSDavid Matlack 
6189ada51a9dSDavid Matlack 	kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6190ada51a9dSDavid Matlack 
6191ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6192ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6193ada51a9dSDavid Matlack 
6194a1a39128SPaolo Bonzini 	return 0;
6195c50d8ae3SPaolo Bonzini }
6196c50d8ae3SPaolo Bonzini 
6197ada51a9dSDavid Matlack static void mmu_free_vm_memory_caches(struct kvm *kvm)
6198ada51a9dSDavid Matlack {
6199ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6200ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6201ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6202ada51a9dSDavid Matlack }
6203ada51a9dSDavid Matlack 
6204c50d8ae3SPaolo Bonzini void kvm_mmu_uninit_vm(struct kvm *kvm)
6205c50d8ae3SPaolo Bonzini {
620609732d2bSDavid Matlack 	if (tdp_mmu_enabled)
6207fe5db27dSBen Gardon 		kvm_mmu_uninit_tdp_mmu(kvm);
6208ada51a9dSDavid Matlack 
6209ada51a9dSDavid Matlack 	mmu_free_vm_memory_caches(kvm);
6210c50d8ae3SPaolo Bonzini }
6211c50d8ae3SPaolo Bonzini 
62122833eda0SSean Christopherson static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
621321fa3246SSean Christopherson {
621421fa3246SSean Christopherson 	const struct kvm_memory_slot *memslot;
621521fa3246SSean Christopherson 	struct kvm_memslots *slots;
6216f4209439SMaciej S. Szmigiero 	struct kvm_memslot_iter iter;
621721fa3246SSean Christopherson 	bool flush = false;
621821fa3246SSean Christopherson 	gfn_t start, end;
6219f4209439SMaciej S. Szmigiero 	int i;
622021fa3246SSean Christopherson 
622121fa3246SSean Christopherson 	if (!kvm_memslots_have_rmaps(kvm))
622221fa3246SSean Christopherson 		return flush;
622321fa3246SSean Christopherson 
622421fa3246SSean Christopherson 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
622521fa3246SSean Christopherson 		slots = __kvm_memslots(kvm, i);
6226f4209439SMaciej S. Szmigiero 
6227f4209439SMaciej S. Szmigiero 		kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6228f4209439SMaciej S. Szmigiero 			memslot = iter.slot;
622921fa3246SSean Christopherson 			start = max(gfn_start, memslot->base_gfn);
623021fa3246SSean Christopherson 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
6231f4209439SMaciej S. Szmigiero 			if (WARN_ON_ONCE(start >= end))
623221fa3246SSean Christopherson 				continue;
623321fa3246SSean Christopherson 
6234727ae377SSean Christopherson 			flush = __walk_slot_rmaps(kvm, memslot, __kvm_zap_rmap,
623521fa3246SSean Christopherson 						  PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
623621fa3246SSean Christopherson 						  start, end - 1, true, flush);
623721fa3246SSean Christopherson 		}
623821fa3246SSean Christopherson 	}
623921fa3246SSean Christopherson 
624021fa3246SSean Christopherson 	return flush;
624121fa3246SSean Christopherson }
624221fa3246SSean Christopherson 
624388f58535SMaxim Levitsky /*
624488f58535SMaxim Levitsky  * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
624588f58535SMaxim Levitsky  * (not including it)
624688f58535SMaxim Levitsky  */
6247c50d8ae3SPaolo Bonzini void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6248c50d8ae3SPaolo Bonzini {
624921fa3246SSean Christopherson 	bool flush;
6250c50d8ae3SPaolo Bonzini 	int i;
6251c50d8ae3SPaolo Bonzini 
6252f4209439SMaciej S. Szmigiero 	if (WARN_ON_ONCE(gfn_end <= gfn_start))
6253f4209439SMaciej S. Szmigiero 		return;
6254f4209439SMaciej S. Szmigiero 
6255531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
62565a324c24SSean Christopherson 
62576d3085e4SSean Christopherson 	kvm_mmu_invalidate_begin(kvm, 0, -1ul);
6258edb298c6SMaxim Levitsky 
62592833eda0SSean Christopherson 	flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
62606103bc07SBen Gardon 
62611f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
62626103bc07SBen Gardon 		for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
6263f47e5bbbSSean Christopherson 			flush = kvm_tdp_mmu_zap_leafs(kvm, i, gfn_start,
6264f47e5bbbSSean Christopherson 						      gfn_end, true, flush);
62656103bc07SBen Gardon 	}
62665a324c24SSean Christopherson 
62675a324c24SSean Christopherson 	if (flush)
62688c63e8c2SDavid Matlack 		kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);
62695a324c24SSean Christopherson 
62706d3085e4SSean Christopherson 	kvm_mmu_invalidate_end(kvm, 0, -1ul);
6271edb298c6SMaxim Levitsky 
62725a324c24SSean Christopherson 	write_unlock(&kvm->mmu_lock);
6273c50d8ae3SPaolo Bonzini }
6274c50d8ae3SPaolo Bonzini 
6275c50d8ae3SPaolo Bonzini static bool slot_rmap_write_protect(struct kvm *kvm,
62760a234f5dSSean Christopherson 				    struct kvm_rmap_head *rmap_head,
6277269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot)
6278c50d8ae3SPaolo Bonzini {
62791346bbb6SDavid Matlack 	return rmap_write_protect(rmap_head, false);
6280c50d8ae3SPaolo Bonzini }
6281c50d8ae3SPaolo Bonzini 
6282c50d8ae3SPaolo Bonzini void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6283269e9552SHamza Mahfooz 				      const struct kvm_memory_slot *memslot,
62843c9bd400SJay Zhou 				      int start_level)
6285c50d8ae3SPaolo Bonzini {
6286e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6287531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6288727ae377SSean Christopherson 		walk_slot_rmaps(kvm, memslot, slot_rmap_write_protect,
6289b64d740eSJunaid Shahid 				start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6290531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6291e2209710SBen Gardon 	}
6292c50d8ae3SPaolo Bonzini 
62931f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
629424ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6295b64d740eSJunaid Shahid 		kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
629624ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
629724ae4cfaSBen Gardon 	}
6298c50d8ae3SPaolo Bonzini }
6299c50d8ae3SPaolo Bonzini 
6300ada51a9dSDavid Matlack static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6301ada51a9dSDavid Matlack {
6302ada51a9dSDavid Matlack 	return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6303ada51a9dSDavid Matlack }
6304ada51a9dSDavid Matlack 
6305ada51a9dSDavid Matlack static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6306ada51a9dSDavid Matlack {
6307ada51a9dSDavid Matlack 	if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6308ada51a9dSDavid Matlack 		return true;
6309ada51a9dSDavid Matlack 
6310ada51a9dSDavid Matlack 	/*
6311ada51a9dSDavid Matlack 	 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6312ada51a9dSDavid Matlack 	 * to split a single huge page. Calculating how many are actually needed
6313ada51a9dSDavid Matlack 	 * is possible but not worth the complexity.
6314ada51a9dSDavid Matlack 	 */
6315ada51a9dSDavid Matlack 	return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6316ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_page_header_cache, 1) ||
6317ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_shadow_page_cache, 1);
6318ada51a9dSDavid Matlack }
6319ada51a9dSDavid Matlack 
6320ada51a9dSDavid Matlack static int topup_split_caches(struct kvm *kvm)
6321ada51a9dSDavid Matlack {
6322b9b71f43SSean Christopherson 	/*
6323b9b71f43SSean Christopherson 	 * Allocating rmap list entries when splitting huge pages for nested
6324dfd4eb44SSean Christopherson 	 * MMUs is uncommon as KVM needs to use a list if and only if there is
6325b9b71f43SSean Christopherson 	 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6326dfd4eb44SSean Christopherson 	 * aliased by multiple L2 gfns and/or from multiple nested roots with
6327dfd4eb44SSean Christopherson 	 * different roles.  Aliasing gfns when using TDP is atypical for VMMs;
6328dfd4eb44SSean Christopherson 	 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6329dfd4eb44SSean Christopherson 	 * but aliasing rarely occurs post-boot or for many gfns.  If there is
6330dfd4eb44SSean Christopherson 	 * only one rmap entry, rmap->val points directly at that one entry and
6331dfd4eb44SSean Christopherson 	 * doesn't need to allocate a list.  Buffer the cache by the default
6332dfd4eb44SSean Christopherson 	 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6333b9b71f43SSean Christopherson 	 * encounters an aliased gfn or two.
6334b9b71f43SSean Christopherson 	 */
6335b9b71f43SSean Christopherson 	const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6336b9b71f43SSean Christopherson 			     KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6337ada51a9dSDavid Matlack 	int r;
6338ada51a9dSDavid Matlack 
6339ada51a9dSDavid Matlack 	lockdep_assert_held(&kvm->slots_lock);
6340ada51a9dSDavid Matlack 
6341b9b71f43SSean Christopherson 	r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6342ada51a9dSDavid Matlack 					 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6343ada51a9dSDavid Matlack 	if (r)
6344ada51a9dSDavid Matlack 		return r;
6345ada51a9dSDavid Matlack 
6346ada51a9dSDavid Matlack 	r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6347ada51a9dSDavid Matlack 	if (r)
6348ada51a9dSDavid Matlack 		return r;
6349ada51a9dSDavid Matlack 
6350ada51a9dSDavid Matlack 	return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6351ada51a9dSDavid Matlack }
6352ada51a9dSDavid Matlack 
6353ada51a9dSDavid Matlack static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6354ada51a9dSDavid Matlack {
6355ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6356ada51a9dSDavid Matlack 	struct shadow_page_caches caches = {};
6357ada51a9dSDavid Matlack 	union kvm_mmu_page_role role;
6358ada51a9dSDavid Matlack 	unsigned int access;
6359ada51a9dSDavid Matlack 	gfn_t gfn;
6360ada51a9dSDavid Matlack 
636179e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
636279e48cecSSean Christopherson 	access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6363ada51a9dSDavid Matlack 
6364ada51a9dSDavid Matlack 	/*
6365ada51a9dSDavid Matlack 	 * Note, huge page splitting always uses direct shadow pages, regardless
6366ada51a9dSDavid Matlack 	 * of whether the huge page itself is mapped by a direct or indirect
6367ada51a9dSDavid Matlack 	 * shadow page, since the huge page region itself is being directly
6368ada51a9dSDavid Matlack 	 * mapped with smaller pages.
6369ada51a9dSDavid Matlack 	 */
6370ada51a9dSDavid Matlack 	role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6371ada51a9dSDavid Matlack 
6372ada51a9dSDavid Matlack 	/* Direct SPs do not require a shadowed_info_cache. */
6373ada51a9dSDavid Matlack 	caches.page_header_cache = &kvm->arch.split_page_header_cache;
6374ada51a9dSDavid Matlack 	caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6375ada51a9dSDavid Matlack 
6376ada51a9dSDavid Matlack 	/* Safe to pass NULL for vCPU since requesting a direct SP. */
6377ada51a9dSDavid Matlack 	return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6378ada51a9dSDavid Matlack }
6379ada51a9dSDavid Matlack 
6380ada51a9dSDavid Matlack static void shadow_mmu_split_huge_page(struct kvm *kvm,
6381ada51a9dSDavid Matlack 				       const struct kvm_memory_slot *slot,
6382ada51a9dSDavid Matlack 				       u64 *huge_sptep)
6383ada51a9dSDavid Matlack 
6384ada51a9dSDavid Matlack {
6385ada51a9dSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6386ada51a9dSDavid Matlack 	u64 huge_spte = READ_ONCE(*huge_sptep);
6387ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
638803787394SPaolo Bonzini 	bool flush = false;
6389ada51a9dSDavid Matlack 	u64 *sptep, spte;
6390ada51a9dSDavid Matlack 	gfn_t gfn;
6391ada51a9dSDavid Matlack 	int index;
6392ada51a9dSDavid Matlack 
6393ada51a9dSDavid Matlack 	sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6394ada51a9dSDavid Matlack 
6395ada51a9dSDavid Matlack 	for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6396ada51a9dSDavid Matlack 		sptep = &sp->spt[index];
6397ada51a9dSDavid Matlack 		gfn = kvm_mmu_page_get_gfn(sp, index);
6398ada51a9dSDavid Matlack 
6399ada51a9dSDavid Matlack 		/*
6400ada51a9dSDavid Matlack 		 * The SP may already have populated SPTEs, e.g. if this huge
6401ada51a9dSDavid Matlack 		 * page is aliased by multiple sptes with the same access
6402ada51a9dSDavid Matlack 		 * permissions. These entries are guaranteed to map the same
6403ada51a9dSDavid Matlack 		 * gfn-to-pfn translation since the SP is direct, so no need to
6404ada51a9dSDavid Matlack 		 * modify them.
6405ada51a9dSDavid Matlack 		 *
640603787394SPaolo Bonzini 		 * However, if a given SPTE points to a lower level page table,
640703787394SPaolo Bonzini 		 * that lower level page table may only be partially populated.
640803787394SPaolo Bonzini 		 * Installing such SPTEs would effectively unmap a potion of the
640903787394SPaolo Bonzini 		 * huge page. Unmapping guest memory always requires a TLB flush
641003787394SPaolo Bonzini 		 * since a subsequent operation on the unmapped regions would
641103787394SPaolo Bonzini 		 * fail to detect the need to flush.
6412ada51a9dSDavid Matlack 		 */
641303787394SPaolo Bonzini 		if (is_shadow_present_pte(*sptep)) {
641403787394SPaolo Bonzini 			flush |= !is_last_spte(*sptep, sp->role.level);
6415ada51a9dSDavid Matlack 			continue;
641603787394SPaolo Bonzini 		}
6417ada51a9dSDavid Matlack 
6418ada51a9dSDavid Matlack 		spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
6419ada51a9dSDavid Matlack 		mmu_spte_set(sptep, spte);
6420ada51a9dSDavid Matlack 		__rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6421ada51a9dSDavid Matlack 	}
6422ada51a9dSDavid Matlack 
642303787394SPaolo Bonzini 	__link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6424ada51a9dSDavid Matlack }
6425ada51a9dSDavid Matlack 
6426ada51a9dSDavid Matlack static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6427ada51a9dSDavid Matlack 					  const struct kvm_memory_slot *slot,
6428ada51a9dSDavid Matlack 					  u64 *huge_sptep)
6429ada51a9dSDavid Matlack {
6430ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6431ada51a9dSDavid Matlack 	int level, r = 0;
6432ada51a9dSDavid Matlack 	gfn_t gfn;
6433ada51a9dSDavid Matlack 	u64 spte;
6434ada51a9dSDavid Matlack 
6435ada51a9dSDavid Matlack 	/* Grab information for the tracepoint before dropping the MMU lock. */
643679e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6437ada51a9dSDavid Matlack 	level = huge_sp->role.level;
6438ada51a9dSDavid Matlack 	spte = *huge_sptep;
6439ada51a9dSDavid Matlack 
6440ada51a9dSDavid Matlack 	if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6441ada51a9dSDavid Matlack 		r = -ENOSPC;
6442ada51a9dSDavid Matlack 		goto out;
6443ada51a9dSDavid Matlack 	}
6444ada51a9dSDavid Matlack 
6445ada51a9dSDavid Matlack 	if (need_topup_split_caches_or_resched(kvm)) {
6446ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6447ada51a9dSDavid Matlack 		cond_resched();
6448ada51a9dSDavid Matlack 		/*
6449ada51a9dSDavid Matlack 		 * If the topup succeeds, return -EAGAIN to indicate that the
6450ada51a9dSDavid Matlack 		 * rmap iterator should be restarted because the MMU lock was
6451ada51a9dSDavid Matlack 		 * dropped.
6452ada51a9dSDavid Matlack 		 */
6453ada51a9dSDavid Matlack 		r = topup_split_caches(kvm) ?: -EAGAIN;
6454ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6455ada51a9dSDavid Matlack 		goto out;
6456ada51a9dSDavid Matlack 	}
6457ada51a9dSDavid Matlack 
6458ada51a9dSDavid Matlack 	shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6459ada51a9dSDavid Matlack 
6460ada51a9dSDavid Matlack out:
6461ada51a9dSDavid Matlack 	trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6462ada51a9dSDavid Matlack 	return r;
6463ada51a9dSDavid Matlack }
6464ada51a9dSDavid Matlack 
6465ada51a9dSDavid Matlack static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6466ada51a9dSDavid Matlack 					    struct kvm_rmap_head *rmap_head,
6467ada51a9dSDavid Matlack 					    const struct kvm_memory_slot *slot)
6468ada51a9dSDavid Matlack {
6469ada51a9dSDavid Matlack 	struct rmap_iterator iter;
6470ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
6471ada51a9dSDavid Matlack 	u64 *huge_sptep;
6472ada51a9dSDavid Matlack 	int r;
6473ada51a9dSDavid Matlack 
6474ada51a9dSDavid Matlack restart:
6475ada51a9dSDavid Matlack 	for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6476ada51a9dSDavid Matlack 		sp = sptep_to_sp(huge_sptep);
6477ada51a9dSDavid Matlack 
6478ada51a9dSDavid Matlack 		/* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6479ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!sp->role.guest_mode))
6480ada51a9dSDavid Matlack 			continue;
6481ada51a9dSDavid Matlack 
6482ada51a9dSDavid Matlack 		/* The rmaps should never contain non-leaf SPTEs. */
6483ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6484ada51a9dSDavid Matlack 			continue;
6485ada51a9dSDavid Matlack 
6486ada51a9dSDavid Matlack 		/* SPs with level >PG_LEVEL_4K should never by unsync. */
6487ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(sp->unsync))
6488ada51a9dSDavid Matlack 			continue;
6489ada51a9dSDavid Matlack 
6490ada51a9dSDavid Matlack 		/* Don't bother splitting huge pages on invalid SPs. */
6491ada51a9dSDavid Matlack 		if (sp->role.invalid)
6492ada51a9dSDavid Matlack 			continue;
6493ada51a9dSDavid Matlack 
6494ada51a9dSDavid Matlack 		r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6495ada51a9dSDavid Matlack 
6496ada51a9dSDavid Matlack 		/*
6497ada51a9dSDavid Matlack 		 * The split succeeded or needs to be retried because the MMU
6498ada51a9dSDavid Matlack 		 * lock was dropped. Either way, restart the iterator to get it
6499ada51a9dSDavid Matlack 		 * back into a consistent state.
6500ada51a9dSDavid Matlack 		 */
6501ada51a9dSDavid Matlack 		if (!r || r == -EAGAIN)
6502ada51a9dSDavid Matlack 			goto restart;
6503ada51a9dSDavid Matlack 
6504ada51a9dSDavid Matlack 		/* The split failed and shouldn't be retried (e.g. -ENOMEM). */
6505ada51a9dSDavid Matlack 		break;
6506ada51a9dSDavid Matlack 	}
6507ada51a9dSDavid Matlack 
6508ada51a9dSDavid Matlack 	return false;
6509ada51a9dSDavid Matlack }
6510ada51a9dSDavid Matlack 
6511ada51a9dSDavid Matlack static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6512ada51a9dSDavid Matlack 						const struct kvm_memory_slot *slot,
6513ada51a9dSDavid Matlack 						gfn_t start, gfn_t end,
6514ada51a9dSDavid Matlack 						int target_level)
6515ada51a9dSDavid Matlack {
6516ada51a9dSDavid Matlack 	int level;
6517ada51a9dSDavid Matlack 
6518ada51a9dSDavid Matlack 	/*
6519ada51a9dSDavid Matlack 	 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
6520ada51a9dSDavid Matlack 	 * down to the target level. This ensures pages are recursively split
6521ada51a9dSDavid Matlack 	 * all the way to the target level. There's no need to split pages
6522ada51a9dSDavid Matlack 	 * already at the target level.
6523ada51a9dSDavid Matlack 	 */
6524727ae377SSean Christopherson 	for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--)
6525727ae377SSean Christopherson 		__walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,
6526ada51a9dSDavid Matlack 				  level, level, start, end - 1, true, false);
6527ada51a9dSDavid Matlack }
6528ada51a9dSDavid Matlack 
6529cb00a70bSDavid Matlack /* Must be called with the mmu_lock held in write-mode. */
6530cb00a70bSDavid Matlack void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6531cb00a70bSDavid Matlack 				   const struct kvm_memory_slot *memslot,
6532cb00a70bSDavid Matlack 				   u64 start, u64 end,
6533cb00a70bSDavid Matlack 				   int target_level)
6534cb00a70bSDavid Matlack {
65351f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6536ada51a9dSDavid Matlack 		return;
6537ada51a9dSDavid Matlack 
6538ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm))
6539ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6540ada51a9dSDavid Matlack 
6541ada51a9dSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
6542cb00a70bSDavid Matlack 
6543cb00a70bSDavid Matlack 	/*
6544cb00a70bSDavid Matlack 	 * A TLB flush is unnecessary at this point for the same resons as in
6545cb00a70bSDavid Matlack 	 * kvm_mmu_slot_try_split_huge_pages().
6546cb00a70bSDavid Matlack 	 */
6547cb00a70bSDavid Matlack }
6548cb00a70bSDavid Matlack 
6549a3fe5dbdSDavid Matlack void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6550a3fe5dbdSDavid Matlack 					const struct kvm_memory_slot *memslot,
6551a3fe5dbdSDavid Matlack 					int target_level)
6552a3fe5dbdSDavid Matlack {
6553a3fe5dbdSDavid Matlack 	u64 start = memslot->base_gfn;
6554a3fe5dbdSDavid Matlack 	u64 end = start + memslot->npages;
6555a3fe5dbdSDavid Matlack 
65561f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6557ada51a9dSDavid Matlack 		return;
6558ada51a9dSDavid Matlack 
6559ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm)) {
6560ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6561ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6562ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6563ada51a9dSDavid Matlack 	}
6564ada51a9dSDavid Matlack 
6565a3fe5dbdSDavid Matlack 	read_lock(&kvm->mmu_lock);
6566cb00a70bSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6567a3fe5dbdSDavid Matlack 	read_unlock(&kvm->mmu_lock);
6568a3fe5dbdSDavid Matlack 
6569a3fe5dbdSDavid Matlack 	/*
6570a3fe5dbdSDavid Matlack 	 * No TLB flush is necessary here. KVM will flush TLBs after
6571a3fe5dbdSDavid Matlack 	 * write-protecting and/or clearing dirty on the newly split SPTEs to
6572a3fe5dbdSDavid Matlack 	 * ensure that guest writes are reflected in the dirty log before the
6573a3fe5dbdSDavid Matlack 	 * ioctl to enable dirty logging on this memslot completes. Since the
6574a3fe5dbdSDavid Matlack 	 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6575a3fe5dbdSDavid Matlack 	 * safe for KVM to decide if a TLB flush is necessary based on the split
6576a3fe5dbdSDavid Matlack 	 * SPTEs.
6577a3fe5dbdSDavid Matlack 	 */
6578a3fe5dbdSDavid Matlack }
6579a3fe5dbdSDavid Matlack 
6580c50d8ae3SPaolo Bonzini static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
65810a234f5dSSean Christopherson 					 struct kvm_rmap_head *rmap_head,
6582269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
6583c50d8ae3SPaolo Bonzini {
6584c50d8ae3SPaolo Bonzini 	u64 *sptep;
6585c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
6586c50d8ae3SPaolo Bonzini 	int need_tlb_flush = 0;
6587c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6588c50d8ae3SPaolo Bonzini 
6589c50d8ae3SPaolo Bonzini restart:
6590c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
659157354682SSean Christopherson 		sp = sptep_to_sp(sptep);
6592c50d8ae3SPaolo Bonzini 
6593c50d8ae3SPaolo Bonzini 		/*
6594c50d8ae3SPaolo Bonzini 		 * We cannot do huge page mapping for indirect shadow pages,
6595c50d8ae3SPaolo Bonzini 		 * which are found on the last rmap (level = 1) when not using
6596c50d8ae3SPaolo Bonzini 		 * tdp; such shadow pages are synced with the page table in
6597c50d8ae3SPaolo Bonzini 		 * the guest, and the guest page table is using 4K page size
6598c50d8ae3SPaolo Bonzini 		 * mapping if the indirect sp has level = 1.
6599c50d8ae3SPaolo Bonzini 		 */
66005d49f08cSSean Christopherson 		if (sp->role.direct &&
66019eba50f8SSean Christopherson 		    sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
6602a8ac499bSSean Christopherson 							       PG_LEVEL_NUM)) {
66039202aee8SSean Christopherson 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
6604c50d8ae3SPaolo Bonzini 
66058a1300ffSSean Christopherson 			if (kvm_available_flush_remote_tlbs_range())
66061b2dc736SHou Wenlong 				kvm_flush_remote_tlbs_sptep(kvm, sptep);
6607c50d8ae3SPaolo Bonzini 			else
6608c50d8ae3SPaolo Bonzini 				need_tlb_flush = 1;
6609c50d8ae3SPaolo Bonzini 
6610c50d8ae3SPaolo Bonzini 			goto restart;
6611c50d8ae3SPaolo Bonzini 		}
6612c50d8ae3SPaolo Bonzini 	}
6613c50d8ae3SPaolo Bonzini 
6614c50d8ae3SPaolo Bonzini 	return need_tlb_flush;
6615c50d8ae3SPaolo Bonzini }
6616c50d8ae3SPaolo Bonzini 
661720d49186SDavid Matlack static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
661820d49186SDavid Matlack 					   const struct kvm_memory_slot *slot)
661920d49186SDavid Matlack {
662020d49186SDavid Matlack 	/*
662120d49186SDavid Matlack 	 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
662220d49186SDavid Matlack 	 * pages that are already mapped at the maximum hugepage level.
662320d49186SDavid Matlack 	 */
6624727ae377SSean Christopherson 	if (walk_slot_rmaps(kvm, slot, kvm_mmu_zap_collapsible_spte,
662520d49186SDavid Matlack 			    PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
6626619b5072SDavid Matlack 		kvm_flush_remote_tlbs_memslot(kvm, slot);
662720d49186SDavid Matlack }
662820d49186SDavid Matlack 
6629c50d8ae3SPaolo Bonzini void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6630269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *slot)
6631c50d8ae3SPaolo Bonzini {
6632e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6633531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
663420d49186SDavid Matlack 		kvm_rmap_zap_collapsible_sptes(kvm, slot);
6635531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6636e2209710SBen Gardon 	}
66372db6f772SBen Gardon 
66381f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
66392db6f772SBen Gardon 		read_lock(&kvm->mmu_lock);
66404b85c921SSean Christopherson 		kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
66412db6f772SBen Gardon 		read_unlock(&kvm->mmu_lock);
66422db6f772SBen Gardon 	}
6643c50d8ae3SPaolo Bonzini }
6644c50d8ae3SPaolo Bonzini 
6645c50d8ae3SPaolo Bonzini void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6646269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *memslot)
6647c50d8ae3SPaolo Bonzini {
6648e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6649531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6650610265eaSDavid Matlack 		/*
6651610265eaSDavid Matlack 		 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6652610265eaSDavid Matlack 		 * support dirty logging at a 4k granularity.
6653610265eaSDavid Matlack 		 */
6654727ae377SSean Christopherson 		walk_slot_rmaps_4k(kvm, memslot, __rmap_clear_dirty, false);
6655531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6656e2209710SBen Gardon 	}
6657c50d8ae3SPaolo Bonzini 
66581f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
665924ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6660b64d740eSJunaid Shahid 		kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
666124ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
666224ae4cfaSBen Gardon 	}
666324ae4cfaSBen Gardon 
6664c50d8ae3SPaolo Bonzini 	/*
6665b64d740eSJunaid Shahid 	 * The caller will flush the TLBs after this function returns.
6666b64d740eSJunaid Shahid 	 *
6667c50d8ae3SPaolo Bonzini 	 * It's also safe to flush TLBs out of mmu lock here as currently this
6668c50d8ae3SPaolo Bonzini 	 * function is only used for dirty logging, in which case flushing TLB
6669c50d8ae3SPaolo Bonzini 	 * out of mmu lock also guarantees no dirty pages will be lost in
6670c50d8ae3SPaolo Bonzini 	 * dirty_bitmap.
6671c50d8ae3SPaolo Bonzini 	 */
6672c50d8ae3SPaolo Bonzini }
6673c50d8ae3SPaolo Bonzini 
6674db0d70e6SSean Christopherson static void kvm_mmu_zap_all(struct kvm *kvm)
6675c50d8ae3SPaolo Bonzini {
6676c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6677c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6678c50d8ae3SPaolo Bonzini 	int ign;
6679c50d8ae3SPaolo Bonzini 
6680531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6681c50d8ae3SPaolo Bonzini restart:
6682c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
668320ba462dSSean Christopherson 		if (WARN_ON_ONCE(sp->role.invalid))
6684c50d8ae3SPaolo Bonzini 			continue;
6685c50d8ae3SPaolo Bonzini 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6686c50d8ae3SPaolo Bonzini 			goto restart;
6687531810caSBen Gardon 		if (cond_resched_rwlock_write(&kvm->mmu_lock))
6688c50d8ae3SPaolo Bonzini 			goto restart;
6689c50d8ae3SPaolo Bonzini 	}
6690c50d8ae3SPaolo Bonzini 
6691c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6692faaf05b0SBen Gardon 
66931f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6694faaf05b0SBen Gardon 		kvm_tdp_mmu_zap_all(kvm);
6695faaf05b0SBen Gardon 
6696531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
6697c50d8ae3SPaolo Bonzini }
6698c50d8ae3SPaolo Bonzini 
6699db0d70e6SSean Christopherson void kvm_arch_flush_shadow_all(struct kvm *kvm)
6700db0d70e6SSean Christopherson {
6701db0d70e6SSean Christopherson 	kvm_mmu_zap_all(kvm);
6702db0d70e6SSean Christopherson }
6703db0d70e6SSean Christopherson 
6704db0d70e6SSean Christopherson void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
6705db0d70e6SSean Christopherson 				   struct kvm_memory_slot *slot)
6706db0d70e6SSean Christopherson {
6707eeb87272SSean Christopherson 	kvm_mmu_zap_all_fast(kvm);
6708db0d70e6SSean Christopherson }
6709db0d70e6SSean Christopherson 
6710c50d8ae3SPaolo Bonzini void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6711c50d8ae3SPaolo Bonzini {
671220ba462dSSean Christopherson 	WARN_ON_ONCE(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6713c50d8ae3SPaolo Bonzini 
6714c50d8ae3SPaolo Bonzini 	gen &= MMIO_SPTE_GEN_MASK;
6715c50d8ae3SPaolo Bonzini 
6716c50d8ae3SPaolo Bonzini 	/*
6717c50d8ae3SPaolo Bonzini 	 * Generation numbers are incremented in multiples of the number of
6718c50d8ae3SPaolo Bonzini 	 * address spaces in order to provide unique generations across all
6719c50d8ae3SPaolo Bonzini 	 * address spaces.  Strip what is effectively the address space
6720c50d8ae3SPaolo Bonzini 	 * modifier prior to checking for a wrap of the MMIO generation so
6721c50d8ae3SPaolo Bonzini 	 * that a wrap in any address space is detected.
6722c50d8ae3SPaolo Bonzini 	 */
6723c50d8ae3SPaolo Bonzini 	gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6724c50d8ae3SPaolo Bonzini 
6725c50d8ae3SPaolo Bonzini 	/*
6726c50d8ae3SPaolo Bonzini 	 * The very rare case: if the MMIO generation number has wrapped,
6727c50d8ae3SPaolo Bonzini 	 * zap all shadow pages.
6728c50d8ae3SPaolo Bonzini 	 */
6729c50d8ae3SPaolo Bonzini 	if (unlikely(gen == 0)) {
67308d20bd63SSean Christopherson 		kvm_debug_ratelimited("zapping shadow pages for mmio generation wraparound\n");
6731c50d8ae3SPaolo Bonzini 		kvm_mmu_zap_all_fast(kvm);
6732c50d8ae3SPaolo Bonzini 	}
6733c50d8ae3SPaolo Bonzini }
6734c50d8ae3SPaolo Bonzini 
6735f3d90f90SSean Christopherson static unsigned long mmu_shrink_scan(struct shrinker *shrink,
6736f3d90f90SSean Christopherson 				     struct shrink_control *sc)
6737c50d8ae3SPaolo Bonzini {
6738c50d8ae3SPaolo Bonzini 	struct kvm *kvm;
6739c50d8ae3SPaolo Bonzini 	int nr_to_scan = sc->nr_to_scan;
6740c50d8ae3SPaolo Bonzini 	unsigned long freed = 0;
6741c50d8ae3SPaolo Bonzini 
6742c50d8ae3SPaolo Bonzini 	mutex_lock(&kvm_lock);
6743c50d8ae3SPaolo Bonzini 
6744c50d8ae3SPaolo Bonzini 	list_for_each_entry(kvm, &vm_list, vm_list) {
6745c50d8ae3SPaolo Bonzini 		int idx;
6746c50d8ae3SPaolo Bonzini 		LIST_HEAD(invalid_list);
6747c50d8ae3SPaolo Bonzini 
6748c50d8ae3SPaolo Bonzini 		/*
6749c50d8ae3SPaolo Bonzini 		 * Never scan more than sc->nr_to_scan VM instances.
6750c50d8ae3SPaolo Bonzini 		 * Will not hit this condition practically since we do not try
6751c50d8ae3SPaolo Bonzini 		 * to shrink more than one VM and it is very unlikely to see
6752c50d8ae3SPaolo Bonzini 		 * !n_used_mmu_pages so many times.
6753c50d8ae3SPaolo Bonzini 		 */
6754c50d8ae3SPaolo Bonzini 		if (!nr_to_scan--)
6755c50d8ae3SPaolo Bonzini 			break;
6756c50d8ae3SPaolo Bonzini 		/*
6757c50d8ae3SPaolo Bonzini 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6758c50d8ae3SPaolo Bonzini 		 * here. We may skip a VM instance errorneosly, but we do not
6759c50d8ae3SPaolo Bonzini 		 * want to shrink a VM that only started to populate its MMU
6760c50d8ae3SPaolo Bonzini 		 * anyway.
6761c50d8ae3SPaolo Bonzini 		 */
6762c50d8ae3SPaolo Bonzini 		if (!kvm->arch.n_used_mmu_pages &&
6763c50d8ae3SPaolo Bonzini 		    !kvm_has_zapped_obsolete_pages(kvm))
6764c50d8ae3SPaolo Bonzini 			continue;
6765c50d8ae3SPaolo Bonzini 
6766c50d8ae3SPaolo Bonzini 		idx = srcu_read_lock(&kvm->srcu);
6767531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6768c50d8ae3SPaolo Bonzini 
6769c50d8ae3SPaolo Bonzini 		if (kvm_has_zapped_obsolete_pages(kvm)) {
6770c50d8ae3SPaolo Bonzini 			kvm_mmu_commit_zap_page(kvm,
6771c50d8ae3SPaolo Bonzini 			      &kvm->arch.zapped_obsolete_pages);
6772c50d8ae3SPaolo Bonzini 			goto unlock;
6773c50d8ae3SPaolo Bonzini 		}
6774c50d8ae3SPaolo Bonzini 
6775ebdb292dSSean Christopherson 		freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6776c50d8ae3SPaolo Bonzini 
6777c50d8ae3SPaolo Bonzini unlock:
6778531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6779c50d8ae3SPaolo Bonzini 		srcu_read_unlock(&kvm->srcu, idx);
6780c50d8ae3SPaolo Bonzini 
6781c50d8ae3SPaolo Bonzini 		/*
6782c50d8ae3SPaolo Bonzini 		 * unfair on small ones
6783c50d8ae3SPaolo Bonzini 		 * per-vm shrinkers cry out
6784c50d8ae3SPaolo Bonzini 		 * sadness comes quickly
6785c50d8ae3SPaolo Bonzini 		 */
6786c50d8ae3SPaolo Bonzini 		list_move_tail(&kvm->vm_list, &vm_list);
6787c50d8ae3SPaolo Bonzini 		break;
6788c50d8ae3SPaolo Bonzini 	}
6789c50d8ae3SPaolo Bonzini 
6790c50d8ae3SPaolo Bonzini 	mutex_unlock(&kvm_lock);
6791c50d8ae3SPaolo Bonzini 	return freed;
6792c50d8ae3SPaolo Bonzini }
6793c50d8ae3SPaolo Bonzini 
6794f3d90f90SSean Christopherson static unsigned long mmu_shrink_count(struct shrinker *shrink,
6795f3d90f90SSean Christopherson 				      struct shrink_control *sc)
6796c50d8ae3SPaolo Bonzini {
6797c50d8ae3SPaolo Bonzini 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6798c50d8ae3SPaolo Bonzini }
6799c50d8ae3SPaolo Bonzini 
6800c50d8ae3SPaolo Bonzini static struct shrinker mmu_shrinker = {
6801c50d8ae3SPaolo Bonzini 	.count_objects = mmu_shrink_count,
6802c50d8ae3SPaolo Bonzini 	.scan_objects = mmu_shrink_scan,
6803c50d8ae3SPaolo Bonzini 	.seeks = DEFAULT_SEEKS * 10,
6804c50d8ae3SPaolo Bonzini };
6805c50d8ae3SPaolo Bonzini 
6806c50d8ae3SPaolo Bonzini static void mmu_destroy_caches(void)
6807c50d8ae3SPaolo Bonzini {
6808c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(pte_list_desc_cache);
6809c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(mmu_page_header_cache);
6810c50d8ae3SPaolo Bonzini }
6811c50d8ae3SPaolo Bonzini 
68120b210fafSSean Christopherson static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp)
68130b210fafSSean Christopherson {
68140b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
68151d6664faSLike Xu 		return sysfs_emit(buffer, "never\n");
68160b210fafSSean Christopherson 
68170b210fafSSean Christopherson 	return param_get_bool(buffer, kp);
68180b210fafSSean Christopherson }
68190b210fafSSean Christopherson 
6820c50d8ae3SPaolo Bonzini static bool get_nx_auto_mode(void)
6821c50d8ae3SPaolo Bonzini {
6822c50d8ae3SPaolo Bonzini 	/* Return true when CPU has the bug, and mitigations are ON */
6823c50d8ae3SPaolo Bonzini 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6824c50d8ae3SPaolo Bonzini }
6825c50d8ae3SPaolo Bonzini 
6826c50d8ae3SPaolo Bonzini static void __set_nx_huge_pages(bool val)
6827c50d8ae3SPaolo Bonzini {
6828c50d8ae3SPaolo Bonzini 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6829c50d8ae3SPaolo Bonzini }
6830c50d8ae3SPaolo Bonzini 
6831c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6832c50d8ae3SPaolo Bonzini {
6833c50d8ae3SPaolo Bonzini 	bool old_val = nx_huge_pages;
6834c50d8ae3SPaolo Bonzini 	bool new_val;
6835c50d8ae3SPaolo Bonzini 
68360b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
68370b210fafSSean Christopherson 		return -EPERM;
68380b210fafSSean Christopherson 
6839c50d8ae3SPaolo Bonzini 	/* In "auto" mode deploy workaround only if CPU has the bug. */
68400b210fafSSean Christopherson 	if (sysfs_streq(val, "off")) {
6841c50d8ae3SPaolo Bonzini 		new_val = 0;
68420b210fafSSean Christopherson 	} else if (sysfs_streq(val, "force")) {
6843c50d8ae3SPaolo Bonzini 		new_val = 1;
68440b210fafSSean Christopherson 	} else if (sysfs_streq(val, "auto")) {
6845c50d8ae3SPaolo Bonzini 		new_val = get_nx_auto_mode();
68460b210fafSSean Christopherson 	} else if (sysfs_streq(val, "never")) {
68470b210fafSSean Christopherson 		new_val = 0;
68480b210fafSSean Christopherson 
68490b210fafSSean Christopherson 		mutex_lock(&kvm_lock);
68500b210fafSSean Christopherson 		if (!list_empty(&vm_list)) {
68510b210fafSSean Christopherson 			mutex_unlock(&kvm_lock);
68520b210fafSSean Christopherson 			return -EBUSY;
68530b210fafSSean Christopherson 		}
68540b210fafSSean Christopherson 		nx_hugepage_mitigation_hard_disabled = true;
68550b210fafSSean Christopherson 		mutex_unlock(&kvm_lock);
68560b210fafSSean Christopherson 	} else if (kstrtobool(val, &new_val) < 0) {
6857c50d8ae3SPaolo Bonzini 		return -EINVAL;
68580b210fafSSean Christopherson 	}
6859c50d8ae3SPaolo Bonzini 
6860c50d8ae3SPaolo Bonzini 	__set_nx_huge_pages(new_val);
6861c50d8ae3SPaolo Bonzini 
6862c50d8ae3SPaolo Bonzini 	if (new_val != old_val) {
6863c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6864c50d8ae3SPaolo Bonzini 
6865c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6866c50d8ae3SPaolo Bonzini 
6867c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list) {
6868c50d8ae3SPaolo Bonzini 			mutex_lock(&kvm->slots_lock);
6869c50d8ae3SPaolo Bonzini 			kvm_mmu_zap_all_fast(kvm);
6870c50d8ae3SPaolo Bonzini 			mutex_unlock(&kvm->slots_lock);
6871c50d8ae3SPaolo Bonzini 
687255c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
6873c50d8ae3SPaolo Bonzini 		}
6874c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6875c50d8ae3SPaolo Bonzini 	}
6876c50d8ae3SPaolo Bonzini 
6877c50d8ae3SPaolo Bonzini 	return 0;
6878c50d8ae3SPaolo Bonzini }
6879c50d8ae3SPaolo Bonzini 
68801d0e8480SSean Christopherson /*
68811d0e8480SSean Christopherson  * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
68821d0e8480SSean Christopherson  * its default value of -1 is technically undefined behavior for a boolean.
6883c3e0c8c2SSean Christopherson  * Forward the module init call to SPTE code so that it too can handle module
6884c3e0c8c2SSean Christopherson  * params that need to be resolved/snapshot.
68851d0e8480SSean Christopherson  */
6886982bae43SSean Christopherson void __init kvm_mmu_x86_module_init(void)
6887c50d8ae3SPaolo Bonzini {
6888c50d8ae3SPaolo Bonzini 	if (nx_huge_pages == -1)
6889c50d8ae3SPaolo Bonzini 		__set_nx_huge_pages(get_nx_auto_mode());
6890c3e0c8c2SSean Christopherson 
68911f98f2bdSDavid Matlack 	/*
68921f98f2bdSDavid Matlack 	 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
68931f98f2bdSDavid Matlack 	 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
68941f98f2bdSDavid Matlack 	 * when the vendor module is loaded.
68951f98f2bdSDavid Matlack 	 */
68961f98f2bdSDavid Matlack 	tdp_mmu_allowed = tdp_mmu_enabled;
68971f98f2bdSDavid Matlack 
6898c3e0c8c2SSean Christopherson 	kvm_mmu_spte_module_init();
68991d0e8480SSean Christopherson }
69001d0e8480SSean Christopherson 
69011d0e8480SSean Christopherson /*
69021d0e8480SSean Christopherson  * The bulk of the MMU initialization is deferred until the vendor module is
69031d0e8480SSean Christopherson  * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
69041d0e8480SSean Christopherson  * to be reset when a potentially different vendor module is loaded.
69051d0e8480SSean Christopherson  */
69061d0e8480SSean Christopherson int kvm_mmu_vendor_module_init(void)
69071d0e8480SSean Christopherson {
69081d0e8480SSean Christopherson 	int ret = -ENOMEM;
6909c50d8ae3SPaolo Bonzini 
6910c50d8ae3SPaolo Bonzini 	/*
6911c50d8ae3SPaolo Bonzini 	 * MMU roles use union aliasing which is, generally speaking, an
6912c50d8ae3SPaolo Bonzini 	 * undefined behavior. However, we supposedly know how compilers behave
6913c50d8ae3SPaolo Bonzini 	 * and the current status quo is unlikely to change. Guardians below are
6914c50d8ae3SPaolo Bonzini 	 * supposed to let us know if the assumption becomes false.
6915c50d8ae3SPaolo Bonzini 	 */
6916c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6917c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
69187a7ae829SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
6919c50d8ae3SPaolo Bonzini 
6920c50d8ae3SPaolo Bonzini 	kvm_mmu_reset_all_pte_masks();
6921c50d8ae3SPaolo Bonzini 
6922c50d8ae3SPaolo Bonzini 	pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6923c50d8ae3SPaolo Bonzini 					    sizeof(struct pte_list_desc),
6924c50d8ae3SPaolo Bonzini 					    0, SLAB_ACCOUNT, NULL);
6925c50d8ae3SPaolo Bonzini 	if (!pte_list_desc_cache)
6926c50d8ae3SPaolo Bonzini 		goto out;
6927c50d8ae3SPaolo Bonzini 
6928c50d8ae3SPaolo Bonzini 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6929c50d8ae3SPaolo Bonzini 						  sizeof(struct kvm_mmu_page),
6930c50d8ae3SPaolo Bonzini 						  0, SLAB_ACCOUNT, NULL);
6931c50d8ae3SPaolo Bonzini 	if (!mmu_page_header_cache)
6932c50d8ae3SPaolo Bonzini 		goto out;
6933c50d8ae3SPaolo Bonzini 
6934c50d8ae3SPaolo Bonzini 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6935c50d8ae3SPaolo Bonzini 		goto out;
6936c50d8ae3SPaolo Bonzini 
6937e33c267aSRoman Gushchin 	ret = register_shrinker(&mmu_shrinker, "x86-mmu");
6938c50d8ae3SPaolo Bonzini 	if (ret)
6939d7c9bfb9SMiaohe Lin 		goto out_shrinker;
6940c50d8ae3SPaolo Bonzini 
6941c50d8ae3SPaolo Bonzini 	return 0;
6942c50d8ae3SPaolo Bonzini 
6943d7c9bfb9SMiaohe Lin out_shrinker:
6944d7c9bfb9SMiaohe Lin 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6945c50d8ae3SPaolo Bonzini out:
6946c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6947c50d8ae3SPaolo Bonzini 	return ret;
6948c50d8ae3SPaolo Bonzini }
6949c50d8ae3SPaolo Bonzini 
6950c50d8ae3SPaolo Bonzini void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6951c50d8ae3SPaolo Bonzini {
6952c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
6953c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.root_mmu);
6954c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
6955c50d8ae3SPaolo Bonzini 	mmu_free_memory_caches(vcpu);
6956c50d8ae3SPaolo Bonzini }
6957c50d8ae3SPaolo Bonzini 
69581d0e8480SSean Christopherson void kvm_mmu_vendor_module_exit(void)
6959c50d8ae3SPaolo Bonzini {
6960c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6961c50d8ae3SPaolo Bonzini 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6962c50d8ae3SPaolo Bonzini 	unregister_shrinker(&mmu_shrinker);
6963c50d8ae3SPaolo Bonzini }
6964c50d8ae3SPaolo Bonzini 
6965f47491d7SSean Christopherson /*
6966f47491d7SSean Christopherson  * Calculate the effective recovery period, accounting for '0' meaning "let KVM
6967f47491d7SSean Christopherson  * select a halving time of 1 hour".  Returns true if recovery is enabled.
6968f47491d7SSean Christopherson  */
6969f47491d7SSean Christopherson static bool calc_nx_huge_pages_recovery_period(uint *period)
6970f47491d7SSean Christopherson {
6971f47491d7SSean Christopherson 	/*
6972f47491d7SSean Christopherson 	 * Use READ_ONCE to get the params, this may be called outside of the
6973f47491d7SSean Christopherson 	 * param setters, e.g. by the kthread to compute its next timeout.
6974f47491d7SSean Christopherson 	 */
6975f47491d7SSean Christopherson 	bool enabled = READ_ONCE(nx_huge_pages);
6976f47491d7SSean Christopherson 	uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6977f47491d7SSean Christopherson 
6978f47491d7SSean Christopherson 	if (!enabled || !ratio)
6979f47491d7SSean Christopherson 		return false;
6980f47491d7SSean Christopherson 
6981f47491d7SSean Christopherson 	*period = READ_ONCE(nx_huge_pages_recovery_period_ms);
6982f47491d7SSean Christopherson 	if (!*period) {
6983f47491d7SSean Christopherson 		/* Make sure the period is not less than one second.  */
6984f47491d7SSean Christopherson 		ratio = min(ratio, 3600u);
6985f47491d7SSean Christopherson 		*period = 60 * 60 * 1000 / ratio;
6986f47491d7SSean Christopherson 	}
6987f47491d7SSean Christopherson 	return true;
6988f47491d7SSean Christopherson }
6989f47491d7SSean Christopherson 
69904dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
6991c50d8ae3SPaolo Bonzini {
69924dfe4f40SJunaid Shahid 	bool was_recovery_enabled, is_recovery_enabled;
69934dfe4f40SJunaid Shahid 	uint old_period, new_period;
6994c50d8ae3SPaolo Bonzini 	int err;
6995c50d8ae3SPaolo Bonzini 
69960b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
69970b210fafSSean Christopherson 		return -EPERM;
69980b210fafSSean Christopherson 
6999f47491d7SSean Christopherson 	was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
70004dfe4f40SJunaid Shahid 
7001c50d8ae3SPaolo Bonzini 	err = param_set_uint(val, kp);
7002c50d8ae3SPaolo Bonzini 	if (err)
7003c50d8ae3SPaolo Bonzini 		return err;
7004c50d8ae3SPaolo Bonzini 
7005f47491d7SSean Christopherson 	is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
70064dfe4f40SJunaid Shahid 
7007f47491d7SSean Christopherson 	if (is_recovery_enabled &&
70084dfe4f40SJunaid Shahid 	    (!was_recovery_enabled || old_period > new_period)) {
7009c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
7010c50d8ae3SPaolo Bonzini 
7011c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
7012c50d8ae3SPaolo Bonzini 
7013c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list)
701455c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
7015c50d8ae3SPaolo Bonzini 
7016c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
7017c50d8ae3SPaolo Bonzini 	}
7018c50d8ae3SPaolo Bonzini 
7019c50d8ae3SPaolo Bonzini 	return err;
7020c50d8ae3SPaolo Bonzini }
7021c50d8ae3SPaolo Bonzini 
702255c510e2SSean Christopherson static void kvm_recover_nx_huge_pages(struct kvm *kvm)
7023c50d8ae3SPaolo Bonzini {
7024ade74e14SSean Christopherson 	unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
7025eb298605SDavid Matlack 	struct kvm_memory_slot *slot;
7026c50d8ae3SPaolo Bonzini 	int rcu_idx;
7027c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
7028c50d8ae3SPaolo Bonzini 	unsigned int ratio;
7029c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
7030048f4980SSean Christopherson 	bool flush = false;
7031c50d8ae3SPaolo Bonzini 	ulong to_zap;
7032c50d8ae3SPaolo Bonzini 
7033c50d8ae3SPaolo Bonzini 	rcu_idx = srcu_read_lock(&kvm->srcu);
7034531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
7035c50d8ae3SPaolo Bonzini 
7036bb95dfb9SSean Christopherson 	/*
7037bb95dfb9SSean Christopherson 	 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
7038bb95dfb9SSean Christopherson 	 * be done under RCU protection, because the pages are freed via RCU
7039bb95dfb9SSean Christopherson 	 * callback.
7040bb95dfb9SSean Christopherson 	 */
7041bb95dfb9SSean Christopherson 	rcu_read_lock();
7042bb95dfb9SSean Christopherson 
7043c50d8ae3SPaolo Bonzini 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7044ade74e14SSean Christopherson 	to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
70457d919c7aSSean Christopherson 	for ( ; to_zap; --to_zap) {
704655c510e2SSean Christopherson 		if (list_empty(&kvm->arch.possible_nx_huge_pages))
70477d919c7aSSean Christopherson 			break;
70487d919c7aSSean Christopherson 
7049c50d8ae3SPaolo Bonzini 		/*
7050c50d8ae3SPaolo Bonzini 		 * We use a separate list instead of just using active_mmu_pages
705155c510e2SSean Christopherson 		 * because the number of shadow pages that be replaced with an
705255c510e2SSean Christopherson 		 * NX huge page is expected to be relatively small compared to
705355c510e2SSean Christopherson 		 * the total number of shadow pages.  And because the TDP MMU
705455c510e2SSean Christopherson 		 * doesn't use active_mmu_pages.
7055c50d8ae3SPaolo Bonzini 		 */
705655c510e2SSean Christopherson 		sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
7057c50d8ae3SPaolo Bonzini 				      struct kvm_mmu_page,
705855c510e2SSean Christopherson 				      possible_nx_huge_page_link);
705955c510e2SSean Christopherson 		WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
7060eb298605SDavid Matlack 		WARN_ON_ONCE(!sp->role.direct);
7061eb298605SDavid Matlack 
7062eb298605SDavid Matlack 		/*
7063eb298605SDavid Matlack 		 * Unaccount and do not attempt to recover any NX Huge Pages
7064eb298605SDavid Matlack 		 * that are being dirty tracked, as they would just be faulted
7065eb298605SDavid Matlack 		 * back in as 4KiB pages. The NX Huge Pages in this slot will be
7066eb298605SDavid Matlack 		 * recovered, along with all the other huge pages in the slot,
7067eb298605SDavid Matlack 		 * when dirty logging is disabled.
70686c7b2202SPaolo Bonzini 		 *
70696c7b2202SPaolo Bonzini 		 * Since gfn_to_memslot() is relatively expensive, it helps to
70706c7b2202SPaolo Bonzini 		 * skip it if it the test cannot possibly return true.  On the
70716c7b2202SPaolo Bonzini 		 * other hand, if any memslot has logging enabled, chances are
70726c7b2202SPaolo Bonzini 		 * good that all of them do, in which case unaccount_nx_huge_page()
70736c7b2202SPaolo Bonzini 		 * is much cheaper than zapping the page.
70746c7b2202SPaolo Bonzini 		 *
70756c7b2202SPaolo Bonzini 		 * If a memslot update is in progress, reading an incorrect value
70766c7b2202SPaolo Bonzini 		 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
70776c7b2202SPaolo Bonzini 		 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
70786c7b2202SPaolo Bonzini 		 * it is becoming nonzero, the page will be zapped unnecessarily.
70796c7b2202SPaolo Bonzini 		 * Either way, this only affects efficiency in racy situations,
70806c7b2202SPaolo Bonzini 		 * and not correctness.
7081eb298605SDavid Matlack 		 */
70826c7b2202SPaolo Bonzini 		slot = NULL;
70836c7b2202SPaolo Bonzini 		if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
7084817fa998SSean Christopherson 			struct kvm_memslots *slots;
7085817fa998SSean Christopherson 
7086817fa998SSean Christopherson 			slots = kvm_memslots_for_spte_role(kvm, sp->role);
7087817fa998SSean Christopherson 			slot = __gfn_to_memslot(slots, sp->gfn);
70886c7b2202SPaolo Bonzini 			WARN_ON_ONCE(!slot);
708929cf0f50SBen Gardon 		}
7090c50d8ae3SPaolo Bonzini 
7091eb298605SDavid Matlack 		if (slot && kvm_slot_dirty_track_enabled(slot))
7092eb298605SDavid Matlack 			unaccount_nx_huge_page(kvm, sp);
7093eb298605SDavid Matlack 		else if (is_tdp_mmu_page(sp))
7094c50d8ae3SPaolo Bonzini 			flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
70953a056757SSean Christopherson 		else
7096c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
709755c510e2SSean Christopherson 		WARN_ON_ONCE(sp->nx_huge_page_disallowed);
7098c50d8ae3SPaolo Bonzini 
7099531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7100048f4980SSean Christopherson 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7101bb95dfb9SSean Christopherson 			rcu_read_unlock();
7102bb95dfb9SSean Christopherson 
7103531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
7104048f4980SSean Christopherson 			flush = false;
7105bb95dfb9SSean Christopherson 
7106bb95dfb9SSean Christopherson 			rcu_read_lock();
7107c50d8ae3SPaolo Bonzini 		}
7108c50d8ae3SPaolo Bonzini 	}
7109048f4980SSean Christopherson 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7110c50d8ae3SPaolo Bonzini 
7111bb95dfb9SSean Christopherson 	rcu_read_unlock();
7112bb95dfb9SSean Christopherson 
7113531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
7114c50d8ae3SPaolo Bonzini 	srcu_read_unlock(&kvm->srcu, rcu_idx);
7115c50d8ae3SPaolo Bonzini }
7116c50d8ae3SPaolo Bonzini 
711755c510e2SSean Christopherson static long get_nx_huge_page_recovery_timeout(u64 start_time)
7118c50d8ae3SPaolo Bonzini {
7119f47491d7SSean Christopherson 	bool enabled;
7120f47491d7SSean Christopherson 	uint period;
71214dfe4f40SJunaid Shahid 
7122f47491d7SSean Christopherson 	enabled = calc_nx_huge_pages_recovery_period(&period);
71234dfe4f40SJunaid Shahid 
7124f47491d7SSean Christopherson 	return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
7125c50d8ae3SPaolo Bonzini 		       : MAX_SCHEDULE_TIMEOUT;
7126c50d8ae3SPaolo Bonzini }
7127c50d8ae3SPaolo Bonzini 
712855c510e2SSean Christopherson static int kvm_nx_huge_page_recovery_worker(struct kvm *kvm, uintptr_t data)
7129c50d8ae3SPaolo Bonzini {
7130c50d8ae3SPaolo Bonzini 	u64 start_time;
7131c50d8ae3SPaolo Bonzini 	long remaining_time;
7132c50d8ae3SPaolo Bonzini 
7133c50d8ae3SPaolo Bonzini 	while (true) {
7134c50d8ae3SPaolo Bonzini 		start_time = get_jiffies_64();
713555c510e2SSean Christopherson 		remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7136c50d8ae3SPaolo Bonzini 
7137c50d8ae3SPaolo Bonzini 		set_current_state(TASK_INTERRUPTIBLE);
7138c50d8ae3SPaolo Bonzini 		while (!kthread_should_stop() && remaining_time > 0) {
7139c50d8ae3SPaolo Bonzini 			schedule_timeout(remaining_time);
714055c510e2SSean Christopherson 			remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7141c50d8ae3SPaolo Bonzini 			set_current_state(TASK_INTERRUPTIBLE);
7142c50d8ae3SPaolo Bonzini 		}
7143c50d8ae3SPaolo Bonzini 
7144c50d8ae3SPaolo Bonzini 		set_current_state(TASK_RUNNING);
7145c50d8ae3SPaolo Bonzini 
7146c50d8ae3SPaolo Bonzini 		if (kthread_should_stop())
7147c50d8ae3SPaolo Bonzini 			return 0;
7148c50d8ae3SPaolo Bonzini 
714955c510e2SSean Christopherson 		kvm_recover_nx_huge_pages(kvm);
7150c50d8ae3SPaolo Bonzini 	}
7151c50d8ae3SPaolo Bonzini }
7152c50d8ae3SPaolo Bonzini 
7153c50d8ae3SPaolo Bonzini int kvm_mmu_post_init_vm(struct kvm *kvm)
7154c50d8ae3SPaolo Bonzini {
7155c50d8ae3SPaolo Bonzini 	int err;
7156c50d8ae3SPaolo Bonzini 
71570b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
71580b210fafSSean Christopherson 		return 0;
71590b210fafSSean Christopherson 
716055c510e2SSean Christopherson 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_huge_page_recovery_worker, 0,
7161c50d8ae3SPaolo Bonzini 					  "kvm-nx-lpage-recovery",
716255c510e2SSean Christopherson 					  &kvm->arch.nx_huge_page_recovery_thread);
7163c50d8ae3SPaolo Bonzini 	if (!err)
716455c510e2SSean Christopherson 		kthread_unpark(kvm->arch.nx_huge_page_recovery_thread);
7165c50d8ae3SPaolo Bonzini 
7166c50d8ae3SPaolo Bonzini 	return err;
7167c50d8ae3SPaolo Bonzini }
7168c50d8ae3SPaolo Bonzini 
7169c50d8ae3SPaolo Bonzini void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7170c50d8ae3SPaolo Bonzini {
717155c510e2SSean Christopherson 	if (kvm->arch.nx_huge_page_recovery_thread)
717255c510e2SSean Christopherson 		kthread_stop(kvm->arch.nx_huge_page_recovery_thread);
7173c50d8ae3SPaolo Bonzini }
7174