xref: /linux/arch/x86/kvm/mmu/mmu.c (revision 8dd2eee9d526c30fccfe75da7ec5365c6476e510)
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 
79890b4fe17SChao Peng /*
79990b4fe17SChao Peng  * The most significant bit in disallow_lpage tracks whether or not memory
80090b4fe17SChao Peng  * attributes are mixed, i.e. not identical for all gfns at the current level.
80190b4fe17SChao Peng  * The lower order bits are used to refcount other cases where a hugepage is
80290b4fe17SChao Peng  * disallowed, e.g. if KVM has shadow a page table at the gfn.
80390b4fe17SChao Peng  */
80490b4fe17SChao Peng #define KVM_LPAGE_MIXED_FLAG	BIT(31)
80590b4fe17SChao Peng 
806269e9552SHamza Mahfooz static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
807c50d8ae3SPaolo Bonzini 					    gfn_t gfn, int count)
808c50d8ae3SPaolo Bonzini {
809c50d8ae3SPaolo Bonzini 	struct kvm_lpage_info *linfo;
81090b4fe17SChao Peng 	int old, i;
811c50d8ae3SPaolo Bonzini 
8123bae0459SSean Christopherson 	for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
813c50d8ae3SPaolo Bonzini 		linfo = lpage_info_slot(gfn, slot, i);
81490b4fe17SChao Peng 
81590b4fe17SChao Peng 		old = linfo->disallow_lpage;
816c50d8ae3SPaolo Bonzini 		linfo->disallow_lpage += count;
81790b4fe17SChao Peng 		WARN_ON_ONCE((old ^ linfo->disallow_lpage) & KVM_LPAGE_MIXED_FLAG);
818c50d8ae3SPaolo Bonzini 	}
819c50d8ae3SPaolo Bonzini }
820c50d8ae3SPaolo Bonzini 
821269e9552SHamza Mahfooz void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
822c50d8ae3SPaolo Bonzini {
823c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, 1);
824c50d8ae3SPaolo Bonzini }
825c50d8ae3SPaolo Bonzini 
826269e9552SHamza Mahfooz void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
827c50d8ae3SPaolo Bonzini {
828c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, -1);
829c50d8ae3SPaolo Bonzini }
830c50d8ae3SPaolo Bonzini 
831c50d8ae3SPaolo Bonzini static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
832c50d8ae3SPaolo Bonzini {
833c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
834c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
835c50d8ae3SPaolo Bonzini 	gfn_t gfn;
836c50d8ae3SPaolo Bonzini 
837c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages++;
838c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
839c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
840c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
841c50d8ae3SPaolo Bonzini 
842c50d8ae3SPaolo Bonzini 	/* the non-leaf shadow pages are keeping readonly. */
8433bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
84496316a06SSean Christopherson 		return __kvm_write_track_add_gfn(kvm, slot, gfn);
845c50d8ae3SPaolo Bonzini 
846c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
847be911771SDavid Matlack 
848be911771SDavid Matlack 	if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
8494ad980aeSHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, PG_LEVEL_4K);
850c50d8ae3SPaolo Bonzini }
851c50d8ae3SPaolo Bonzini 
85261f94478SSean Christopherson void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
853c50d8ae3SPaolo Bonzini {
854428e9216SSean Christopherson 	/*
855428e9216SSean Christopherson 	 * If it's possible to replace the shadow page with an NX huge page,
856428e9216SSean Christopherson 	 * i.e. if the shadow page is the only thing currently preventing KVM
857428e9216SSean Christopherson 	 * from using a huge page, add the shadow page to the list of "to be
858428e9216SSean Christopherson 	 * zapped for NX recovery" pages.  Note, the shadow page can already be
859428e9216SSean Christopherson 	 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
860428e9216SSean Christopherson 	 * links a shadow page at multiple points.
861428e9216SSean Christopherson 	 */
86261f94478SSean Christopherson 	if (!list_empty(&sp->possible_nx_huge_page_link))
863c50d8ae3SPaolo Bonzini 		return;
864c50d8ae3SPaolo Bonzini 
865c50d8ae3SPaolo Bonzini 	++kvm->stat.nx_lpage_splits;
86655c510e2SSean Christopherson 	list_add_tail(&sp->possible_nx_huge_page_link,
86755c510e2SSean Christopherson 		      &kvm->arch.possible_nx_huge_pages);
868c50d8ae3SPaolo Bonzini }
869c50d8ae3SPaolo Bonzini 
87061f94478SSean Christopherson static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
87161f94478SSean Christopherson 				 bool nx_huge_page_possible)
87261f94478SSean Christopherson {
87361f94478SSean Christopherson 	sp->nx_huge_page_disallowed = true;
87461f94478SSean Christopherson 
87561f94478SSean Christopherson 	if (nx_huge_page_possible)
87661f94478SSean Christopherson 		track_possible_nx_huge_page(kvm, sp);
877c50d8ae3SPaolo Bonzini }
878c50d8ae3SPaolo Bonzini 
879c50d8ae3SPaolo Bonzini static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
880c50d8ae3SPaolo Bonzini {
881c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
882c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
883c50d8ae3SPaolo Bonzini 	gfn_t gfn;
884c50d8ae3SPaolo Bonzini 
885c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages--;
886c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
887c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
888c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
8893bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
89096316a06SSean Christopherson 		return __kvm_write_track_remove_gfn(kvm, slot, gfn);
891c50d8ae3SPaolo Bonzini 
892c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_allow_lpage(slot, gfn);
893c50d8ae3SPaolo Bonzini }
894c50d8ae3SPaolo Bonzini 
89561f94478SSean Christopherson void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
896c50d8ae3SPaolo Bonzini {
89755c510e2SSean Christopherson 	if (list_empty(&sp->possible_nx_huge_page_link))
898428e9216SSean Christopherson 		return;
899428e9216SSean Christopherson 
900c50d8ae3SPaolo Bonzini 	--kvm->stat.nx_lpage_splits;
90155c510e2SSean Christopherson 	list_del_init(&sp->possible_nx_huge_page_link);
902c50d8ae3SPaolo Bonzini }
903c50d8ae3SPaolo Bonzini 
90461f94478SSean Christopherson static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
90561f94478SSean Christopherson {
90661f94478SSean Christopherson 	sp->nx_huge_page_disallowed = false;
90761f94478SSean Christopherson 
90861f94478SSean Christopherson 	untrack_possible_nx_huge_page(kvm, sp);
909c50d8ae3SPaolo Bonzini }
910c50d8ae3SPaolo Bonzini 
911f3d90f90SSean Christopherson static struct kvm_memory_slot *gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu,
912f3d90f90SSean Christopherson 							   gfn_t gfn,
913c50d8ae3SPaolo Bonzini 							   bool no_dirty_log)
914c50d8ae3SPaolo Bonzini {
915c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
916c50d8ae3SPaolo Bonzini 
917c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
91891b0d268SPaolo Bonzini 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
91991b0d268SPaolo Bonzini 		return NULL;
920044c59c4SPeter Xu 	if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
92191b0d268SPaolo Bonzini 		return NULL;
922c50d8ae3SPaolo Bonzini 
923c50d8ae3SPaolo Bonzini 	return slot;
924c50d8ae3SPaolo Bonzini }
925c50d8ae3SPaolo Bonzini 
926c50d8ae3SPaolo Bonzini /*
927c50d8ae3SPaolo Bonzini  * About rmap_head encoding:
928c50d8ae3SPaolo Bonzini  *
929c50d8ae3SPaolo Bonzini  * If the bit zero of rmap_head->val is clear, then it points to the only spte
930c50d8ae3SPaolo Bonzini  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
931c50d8ae3SPaolo Bonzini  * pte_list_desc containing more mappings.
932c50d8ae3SPaolo Bonzini  */
933c50d8ae3SPaolo Bonzini 
934c50d8ae3SPaolo Bonzini /*
935c50d8ae3SPaolo Bonzini  * Returns the number of pointers in the rmap chain, not counting the new one.
936c50d8ae3SPaolo Bonzini  */
9372ff9039aSDavid Matlack static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
938c50d8ae3SPaolo Bonzini 			struct kvm_rmap_head *rmap_head)
939c50d8ae3SPaolo Bonzini {
940c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
94113236e25SPeter Xu 	int count = 0;
942c50d8ae3SPaolo Bonzini 
943c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
944c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)spte;
945c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
9462ff9039aSDavid Matlack 		desc = kvm_mmu_memory_cache_alloc(cache);
947c50d8ae3SPaolo Bonzini 		desc->sptes[0] = (u64 *)rmap_head->val;
948c50d8ae3SPaolo Bonzini 		desc->sptes[1] = spte;
94913236e25SPeter Xu 		desc->spte_count = 2;
950141705b7SLai Jiangshan 		desc->tail_count = 0;
951c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)desc | 1;
952c50d8ae3SPaolo Bonzini 		++count;
953c50d8ae3SPaolo Bonzini 	} else {
954c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
955141705b7SLai Jiangshan 		count = desc->tail_count + desc->spte_count;
956141705b7SLai Jiangshan 
957141705b7SLai Jiangshan 		/*
958141705b7SLai Jiangshan 		 * If the previous head is full, allocate a new head descriptor
959141705b7SLai Jiangshan 		 * as tail descriptors are always kept full.
960141705b7SLai Jiangshan 		 */
961141705b7SLai Jiangshan 		if (desc->spte_count == PTE_LIST_EXT) {
962141705b7SLai Jiangshan 			desc = kvm_mmu_memory_cache_alloc(cache);
963141705b7SLai Jiangshan 			desc->more = (struct pte_list_desc *)(rmap_head->val & ~1ul);
96413236e25SPeter Xu 			desc->spte_count = 0;
965141705b7SLai Jiangshan 			desc->tail_count = count;
966141705b7SLai Jiangshan 			rmap_head->val = (unsigned long)desc | 1;
967c6c4f961SLi RongQing 		}
96813236e25SPeter Xu 		desc->sptes[desc->spte_count++] = spte;
969c50d8ae3SPaolo Bonzini 	}
970c50d8ae3SPaolo Bonzini 	return count;
971c50d8ae3SPaolo Bonzini }
972c50d8ae3SPaolo Bonzini 
973069f30c6SMingwei Zhang static void pte_list_desc_remove_entry(struct kvm *kvm,
974069f30c6SMingwei Zhang 				       struct kvm_rmap_head *rmap_head,
975141705b7SLai Jiangshan 				       struct pte_list_desc *desc, int i)
976c50d8ae3SPaolo Bonzini {
977141705b7SLai Jiangshan 	struct pte_list_desc *head_desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
978141705b7SLai Jiangshan 	int j = head_desc->spte_count - 1;
979c50d8ae3SPaolo Bonzini 
980141705b7SLai Jiangshan 	/*
981141705b7SLai Jiangshan 	 * The head descriptor should never be empty.  A new head is added only
982141705b7SLai Jiangshan 	 * when adding an entry and the previous head is full, and heads are
983141705b7SLai Jiangshan 	 * removed (this flow) when they become empty.
984141705b7SLai Jiangshan 	 */
98552e322edSSean Christopherson 	KVM_BUG_ON_DATA_CORRUPTION(j < 0, kvm);
986141705b7SLai Jiangshan 
987141705b7SLai Jiangshan 	/*
988141705b7SLai Jiangshan 	 * Replace the to-be-freed SPTE with the last valid entry from the head
989141705b7SLai Jiangshan 	 * descriptor to ensure that tail descriptors are full at all times.
990141705b7SLai Jiangshan 	 * Note, this also means that tail_count is stable for each descriptor.
991141705b7SLai Jiangshan 	 */
992141705b7SLai Jiangshan 	desc->sptes[i] = head_desc->sptes[j];
993141705b7SLai Jiangshan 	head_desc->sptes[j] = NULL;
994141705b7SLai Jiangshan 	head_desc->spte_count--;
995141705b7SLai Jiangshan 	if (head_desc->spte_count)
996c50d8ae3SPaolo Bonzini 		return;
997141705b7SLai Jiangshan 
998141705b7SLai Jiangshan 	/*
999141705b7SLai Jiangshan 	 * The head descriptor is empty.  If there are no tail descriptors,
1000141705b7SLai Jiangshan 	 * nullify the rmap head to mark the list as emtpy, else point the rmap
1001141705b7SLai Jiangshan 	 * head at the next descriptor, i.e. the new head.
1002141705b7SLai Jiangshan 	 */
1003141705b7SLai Jiangshan 	if (!head_desc->more)
1004fe3c2b4cSMiaohe Lin 		rmap_head->val = 0;
1005c50d8ae3SPaolo Bonzini 	else
1006141705b7SLai Jiangshan 		rmap_head->val = (unsigned long)head_desc->more | 1;
1007141705b7SLai Jiangshan 	mmu_free_pte_list_desc(head_desc);
1008c50d8ae3SPaolo Bonzini }
1009c50d8ae3SPaolo Bonzini 
1010069f30c6SMingwei Zhang static void pte_list_remove(struct kvm *kvm, u64 *spte,
1011069f30c6SMingwei Zhang 			    struct kvm_rmap_head *rmap_head)
1012c50d8ae3SPaolo Bonzini {
1013c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
1014c50d8ae3SPaolo Bonzini 	int i;
1015c50d8ae3SPaolo Bonzini 
101652e322edSSean Christopherson 	if (KVM_BUG_ON_DATA_CORRUPTION(!rmap_head->val, kvm))
101752e322edSSean Christopherson 		return;
101852e322edSSean Christopherson 
101952e322edSSean Christopherson 	if (!(rmap_head->val & 1)) {
102052e322edSSean Christopherson 		if (KVM_BUG_ON_DATA_CORRUPTION((u64 *)rmap_head->val != spte, kvm))
102152e322edSSean Christopherson 			return;
102252e322edSSean Christopherson 
1023c50d8ae3SPaolo Bonzini 		rmap_head->val = 0;
1024c50d8ae3SPaolo Bonzini 	} else {
1025c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1026c50d8ae3SPaolo Bonzini 		while (desc) {
102713236e25SPeter Xu 			for (i = 0; i < desc->spte_count; ++i) {
1028c50d8ae3SPaolo Bonzini 				if (desc->sptes[i] == spte) {
1029069f30c6SMingwei Zhang 					pte_list_desc_remove_entry(kvm, rmap_head,
1030069f30c6SMingwei Zhang 								   desc, i);
1031c50d8ae3SPaolo Bonzini 					return;
1032c50d8ae3SPaolo Bonzini 				}
1033c50d8ae3SPaolo Bonzini 			}
1034c50d8ae3SPaolo Bonzini 			desc = desc->more;
1035c50d8ae3SPaolo Bonzini 		}
103652e322edSSean Christopherson 
103752e322edSSean Christopherson 		KVM_BUG_ON_DATA_CORRUPTION(true, kvm);
1038c50d8ae3SPaolo Bonzini 	}
1039c50d8ae3SPaolo Bonzini }
1040c50d8ae3SPaolo Bonzini 
10419202aee8SSean Christopherson static void kvm_zap_one_rmap_spte(struct kvm *kvm,
10429202aee8SSean Christopherson 				  struct kvm_rmap_head *rmap_head, u64 *sptep)
1043c50d8ae3SPaolo Bonzini {
104471f51d2cSMingwei Zhang 	mmu_spte_clear_track_bits(kvm, sptep);
1045069f30c6SMingwei Zhang 	pte_list_remove(kvm, sptep, rmap_head);
1046c50d8ae3SPaolo Bonzini }
1047c50d8ae3SPaolo Bonzini 
10489202aee8SSean Christopherson /* Return true if at least one SPTE was zapped, false otherwise */
10499202aee8SSean Christopherson static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
10509202aee8SSean Christopherson 				   struct kvm_rmap_head *rmap_head)
1051a75b5404SPeter Xu {
1052a75b5404SPeter Xu 	struct pte_list_desc *desc, *next;
1053a75b5404SPeter Xu 	int i;
1054a75b5404SPeter Xu 
1055a75b5404SPeter Xu 	if (!rmap_head->val)
1056a75b5404SPeter Xu 		return false;
1057a75b5404SPeter Xu 
1058a75b5404SPeter Xu 	if (!(rmap_head->val & 1)) {
105971f51d2cSMingwei Zhang 		mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
1060a75b5404SPeter Xu 		goto out;
1061a75b5404SPeter Xu 	}
1062a75b5404SPeter Xu 
1063a75b5404SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1064a75b5404SPeter Xu 
1065a75b5404SPeter Xu 	for (; desc; desc = next) {
1066a75b5404SPeter Xu 		for (i = 0; i < desc->spte_count; i++)
106771f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1068a75b5404SPeter Xu 		next = desc->more;
1069a75b5404SPeter Xu 		mmu_free_pte_list_desc(desc);
1070a75b5404SPeter Xu 	}
1071a75b5404SPeter Xu out:
1072a75b5404SPeter Xu 	/* rmap_head is meaningless now, remember to reset it */
1073a75b5404SPeter Xu 	rmap_head->val = 0;
1074a75b5404SPeter Xu 	return true;
1075a75b5404SPeter Xu }
1076a75b5404SPeter Xu 
10773bcd0662SPeter Xu unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
10783bcd0662SPeter Xu {
10793bcd0662SPeter Xu 	struct pte_list_desc *desc;
10803bcd0662SPeter Xu 
10813bcd0662SPeter Xu 	if (!rmap_head->val)
10823bcd0662SPeter Xu 		return 0;
10833bcd0662SPeter Xu 	else if (!(rmap_head->val & 1))
10843bcd0662SPeter Xu 		return 1;
10853bcd0662SPeter Xu 
10863bcd0662SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1087141705b7SLai Jiangshan 	return desc->tail_count + desc->spte_count;
10883bcd0662SPeter Xu }
10893bcd0662SPeter Xu 
109093e083d4SDavid Matlack static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1091269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
1092c50d8ae3SPaolo Bonzini {
1093c50d8ae3SPaolo Bonzini 	unsigned long idx;
1094c50d8ae3SPaolo Bonzini 
1095c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
10963bae0459SSean Christopherson 	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1097c50d8ae3SPaolo Bonzini }
1098c50d8ae3SPaolo Bonzini 
1099c50d8ae3SPaolo Bonzini static void rmap_remove(struct kvm *kvm, u64 *spte)
1100c50d8ae3SPaolo Bonzini {
1101601f8af0SDavid Matlack 	struct kvm_memslots *slots;
1102601f8af0SDavid Matlack 	struct kvm_memory_slot *slot;
1103c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1104c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1105c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1106c50d8ae3SPaolo Bonzini 
110757354682SSean Christopherson 	sp = sptep_to_sp(spte);
110879e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1109601f8af0SDavid Matlack 
1110601f8af0SDavid Matlack 	/*
111168be1306SDavid Matlack 	 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
111268be1306SDavid Matlack 	 * so we have to determine which memslots to use based on context
111368be1306SDavid Matlack 	 * information in sp->role.
1114601f8af0SDavid Matlack 	 */
1115601f8af0SDavid Matlack 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1116601f8af0SDavid Matlack 
1117601f8af0SDavid Matlack 	slot = __gfn_to_memslot(slots, gfn);
111893e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1119601f8af0SDavid Matlack 
1120069f30c6SMingwei Zhang 	pte_list_remove(kvm, spte, rmap_head);
1121c50d8ae3SPaolo Bonzini }
1122c50d8ae3SPaolo Bonzini 
1123c50d8ae3SPaolo Bonzini /*
1124c50d8ae3SPaolo Bonzini  * Used by the following functions to iterate through the sptes linked by a
1125c50d8ae3SPaolo Bonzini  * rmap.  All fields are private and not assumed to be used outside.
1126c50d8ae3SPaolo Bonzini  */
1127c50d8ae3SPaolo Bonzini struct rmap_iterator {
1128c50d8ae3SPaolo Bonzini 	/* private fields */
1129c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1130c50d8ae3SPaolo Bonzini 	int pos;			/* index of the sptep */
1131c50d8ae3SPaolo Bonzini };
1132c50d8ae3SPaolo Bonzini 
1133c50d8ae3SPaolo Bonzini /*
1134c50d8ae3SPaolo Bonzini  * Iteration must be started by this function.  This should also be used after
1135c50d8ae3SPaolo Bonzini  * removing/dropping sptes from the rmap link because in such cases the
11360a03cbdaSMiaohe Lin  * information in the iterator may not be valid.
1137c50d8ae3SPaolo Bonzini  *
1138c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1139c50d8ae3SPaolo Bonzini  */
1140c50d8ae3SPaolo Bonzini static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1141c50d8ae3SPaolo Bonzini 			   struct rmap_iterator *iter)
1142c50d8ae3SPaolo Bonzini {
1143c50d8ae3SPaolo Bonzini 	u64 *sptep;
1144c50d8ae3SPaolo Bonzini 
1145c50d8ae3SPaolo Bonzini 	if (!rmap_head->val)
1146c50d8ae3SPaolo Bonzini 		return NULL;
1147c50d8ae3SPaolo Bonzini 
1148c50d8ae3SPaolo Bonzini 	if (!(rmap_head->val & 1)) {
1149c50d8ae3SPaolo Bonzini 		iter->desc = NULL;
1150c50d8ae3SPaolo Bonzini 		sptep = (u64 *)rmap_head->val;
1151c50d8ae3SPaolo Bonzini 		goto out;
1152c50d8ae3SPaolo Bonzini 	}
1153c50d8ae3SPaolo Bonzini 
1154c50d8ae3SPaolo Bonzini 	iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1155c50d8ae3SPaolo Bonzini 	iter->pos = 0;
1156c50d8ae3SPaolo Bonzini 	sptep = iter->desc->sptes[iter->pos];
1157c50d8ae3SPaolo Bonzini out:
1158c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1159c50d8ae3SPaolo Bonzini 	return sptep;
1160c50d8ae3SPaolo Bonzini }
1161c50d8ae3SPaolo Bonzini 
1162c50d8ae3SPaolo Bonzini /*
1163c50d8ae3SPaolo Bonzini  * Must be used with a valid iterator: e.g. after rmap_get_first().
1164c50d8ae3SPaolo Bonzini  *
1165c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1166c50d8ae3SPaolo Bonzini  */
1167c50d8ae3SPaolo Bonzini static u64 *rmap_get_next(struct rmap_iterator *iter)
1168c50d8ae3SPaolo Bonzini {
1169c50d8ae3SPaolo Bonzini 	u64 *sptep;
1170c50d8ae3SPaolo Bonzini 
1171c50d8ae3SPaolo Bonzini 	if (iter->desc) {
1172c50d8ae3SPaolo Bonzini 		if (iter->pos < PTE_LIST_EXT - 1) {
1173c50d8ae3SPaolo Bonzini 			++iter->pos;
1174c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1175c50d8ae3SPaolo Bonzini 			if (sptep)
1176c50d8ae3SPaolo Bonzini 				goto out;
1177c50d8ae3SPaolo Bonzini 		}
1178c50d8ae3SPaolo Bonzini 
1179c50d8ae3SPaolo Bonzini 		iter->desc = iter->desc->more;
1180c50d8ae3SPaolo Bonzini 
1181c50d8ae3SPaolo Bonzini 		if (iter->desc) {
1182c50d8ae3SPaolo Bonzini 			iter->pos = 0;
1183c50d8ae3SPaolo Bonzini 			/* desc->sptes[0] cannot be NULL */
1184c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1185c50d8ae3SPaolo Bonzini 			goto out;
1186c50d8ae3SPaolo Bonzini 		}
1187c50d8ae3SPaolo Bonzini 	}
1188c50d8ae3SPaolo Bonzini 
1189c50d8ae3SPaolo Bonzini 	return NULL;
1190c50d8ae3SPaolo Bonzini out:
1191c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1192c50d8ae3SPaolo Bonzini 	return sptep;
1193c50d8ae3SPaolo Bonzini }
1194c50d8ae3SPaolo Bonzini 
1195c50d8ae3SPaolo Bonzini #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)			\
1196c50d8ae3SPaolo Bonzini 	for (_spte_ = rmap_get_first(_rmap_head_, _iter_);		\
1197c50d8ae3SPaolo Bonzini 	     _spte_; _spte_ = rmap_get_next(_iter_))
1198c50d8ae3SPaolo Bonzini 
1199c50d8ae3SPaolo Bonzini static void drop_spte(struct kvm *kvm, u64 *sptep)
1200c50d8ae3SPaolo Bonzini {
120171f51d2cSMingwei Zhang 	u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
12027fa2a347SSean Christopherson 
12037fa2a347SSean Christopherson 	if (is_shadow_present_pte(old_spte))
1204c50d8ae3SPaolo Bonzini 		rmap_remove(kvm, sptep);
1205c50d8ae3SPaolo Bonzini }
1206c50d8ae3SPaolo Bonzini 
120703787394SPaolo Bonzini static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1208c50d8ae3SPaolo Bonzini {
12090cd8dc73SPaolo Bonzini 	struct kvm_mmu_page *sp;
12100cd8dc73SPaolo Bonzini 
12110cd8dc73SPaolo Bonzini 	sp = sptep_to_sp(sptep);
121220ba462dSSean Christopherson 	WARN_ON_ONCE(sp->role.level == PG_LEVEL_4K);
12130cd8dc73SPaolo Bonzini 
1214c50d8ae3SPaolo Bonzini 	drop_spte(kvm, sptep);
121503787394SPaolo Bonzini 
121603787394SPaolo Bonzini 	if (flush)
12171b2dc736SHou Wenlong 		kvm_flush_remote_tlbs_sptep(kvm, sptep);
1218c50d8ae3SPaolo Bonzini }
1219c50d8ae3SPaolo Bonzini 
1220c50d8ae3SPaolo Bonzini /*
1221c50d8ae3SPaolo Bonzini  * Write-protect on the specified @sptep, @pt_protect indicates whether
1222c50d8ae3SPaolo Bonzini  * spte write-protection is caused by protecting shadow page table.
1223c50d8ae3SPaolo Bonzini  *
1224c50d8ae3SPaolo Bonzini  * Note: write protection is difference between dirty logging and spte
1225c50d8ae3SPaolo Bonzini  * protection:
1226c50d8ae3SPaolo Bonzini  * - for dirty logging, the spte can be set to writable at anytime if
1227c50d8ae3SPaolo Bonzini  *   its dirty bitmap is properly set.
1228c50d8ae3SPaolo Bonzini  * - for spte protection, the spte can be writable only after unsync-ing
1229c50d8ae3SPaolo Bonzini  *   shadow page.
1230c50d8ae3SPaolo Bonzini  *
1231c50d8ae3SPaolo Bonzini  * Return true if tlb need be flushed.
1232c50d8ae3SPaolo Bonzini  */
1233c50d8ae3SPaolo Bonzini static bool spte_write_protect(u64 *sptep, bool pt_protect)
1234c50d8ae3SPaolo Bonzini {
1235c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1236c50d8ae3SPaolo Bonzini 
1237c50d8ae3SPaolo Bonzini 	if (!is_writable_pte(spte) &&
1238706c9c55SSean Christopherson 	    !(pt_protect && is_mmu_writable_spte(spte)))
1239c50d8ae3SPaolo Bonzini 		return false;
1240c50d8ae3SPaolo Bonzini 
1241c50d8ae3SPaolo Bonzini 	if (pt_protect)
12425fc3424fSSean Christopherson 		spte &= ~shadow_mmu_writable_mask;
1243c50d8ae3SPaolo Bonzini 	spte = spte & ~PT_WRITABLE_MASK;
1244c50d8ae3SPaolo Bonzini 
1245c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1246c50d8ae3SPaolo Bonzini }
1247c50d8ae3SPaolo Bonzini 
12481346bbb6SDavid Matlack static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1249c50d8ae3SPaolo Bonzini 			       bool pt_protect)
1250c50d8ae3SPaolo Bonzini {
1251c50d8ae3SPaolo Bonzini 	u64 *sptep;
1252c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1253c50d8ae3SPaolo Bonzini 	bool flush = false;
1254c50d8ae3SPaolo Bonzini 
1255c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1256c50d8ae3SPaolo Bonzini 		flush |= spte_write_protect(sptep, pt_protect);
1257c50d8ae3SPaolo Bonzini 
1258c50d8ae3SPaolo Bonzini 	return flush;
1259c50d8ae3SPaolo Bonzini }
1260c50d8ae3SPaolo Bonzini 
1261c50d8ae3SPaolo Bonzini static bool spte_clear_dirty(u64 *sptep)
1262c50d8ae3SPaolo Bonzini {
1263c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1264c50d8ae3SPaolo Bonzini 
12650fe6370eSSean Christopherson 	KVM_MMU_WARN_ON(!spte_ad_enabled(spte));
1266c50d8ae3SPaolo Bonzini 	spte &= ~shadow_dirty_mask;
1267c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1268c50d8ae3SPaolo Bonzini }
1269c50d8ae3SPaolo Bonzini 
1270c50d8ae3SPaolo Bonzini static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1271c50d8ae3SPaolo Bonzini {
1272c50d8ae3SPaolo Bonzini 	bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1273c50d8ae3SPaolo Bonzini 					       (unsigned long *)sptep);
1274c50d8ae3SPaolo Bonzini 	if (was_writable && !spte_ad_enabled(*sptep))
1275c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1276c50d8ae3SPaolo Bonzini 
1277c50d8ae3SPaolo Bonzini 	return was_writable;
1278c50d8ae3SPaolo Bonzini }
1279c50d8ae3SPaolo Bonzini 
1280c50d8ae3SPaolo Bonzini /*
1281c50d8ae3SPaolo Bonzini  * Gets the GFN ready for another round of dirty logging by clearing the
1282c50d8ae3SPaolo Bonzini  *	- D bit on ad-enabled SPTEs, and
1283c50d8ae3SPaolo Bonzini  *	- W bit on ad-disabled SPTEs.
1284c50d8ae3SPaolo Bonzini  * Returns true iff any D or W bits were cleared.
1285c50d8ae3SPaolo Bonzini  */
12860a234f5dSSean Christopherson static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1287269e9552SHamza Mahfooz 			       const struct kvm_memory_slot *slot)
1288c50d8ae3SPaolo Bonzini {
1289c50d8ae3SPaolo Bonzini 	u64 *sptep;
1290c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1291c50d8ae3SPaolo Bonzini 	bool flush = false;
1292c50d8ae3SPaolo Bonzini 
1293c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1294c50d8ae3SPaolo Bonzini 		if (spte_ad_need_write_protect(*sptep))
1295c50d8ae3SPaolo Bonzini 			flush |= spte_wrprot_for_clear_dirty(sptep);
1296c50d8ae3SPaolo Bonzini 		else
1297c50d8ae3SPaolo Bonzini 			flush |= spte_clear_dirty(sptep);
1298c50d8ae3SPaolo Bonzini 
1299c50d8ae3SPaolo Bonzini 	return flush;
1300c50d8ae3SPaolo Bonzini }
1301c50d8ae3SPaolo Bonzini 
1302c50d8ae3SPaolo Bonzini /**
1303c50d8ae3SPaolo Bonzini  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1304c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1305c50d8ae3SPaolo Bonzini  * @slot: slot to protect
1306c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1307c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should protect
1308c50d8ae3SPaolo Bonzini  *
130989212919SKeqian Zhu  * Used when we do not need to care about huge page mappings.
1310c50d8ae3SPaolo Bonzini  */
1311c50d8ae3SPaolo Bonzini static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1312c50d8ae3SPaolo Bonzini 				     struct kvm_memory_slot *slot,
1313c50d8ae3SPaolo Bonzini 				     gfn_t gfn_offset, unsigned long mask)
1314c50d8ae3SPaolo Bonzini {
1315c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1316c50d8ae3SPaolo Bonzini 
13171f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1318a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1319a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, true);
1320e2209710SBen Gardon 
1321e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1322e2209710SBen Gardon 		return;
1323e2209710SBen Gardon 
1324c50d8ae3SPaolo Bonzini 	while (mask) {
132593e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13263bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13271346bbb6SDavid Matlack 		rmap_write_protect(rmap_head, false);
1328c50d8ae3SPaolo Bonzini 
1329c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1330c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1331c50d8ae3SPaolo Bonzini 	}
1332c50d8ae3SPaolo Bonzini }
1333c50d8ae3SPaolo Bonzini 
1334c50d8ae3SPaolo Bonzini /**
1335c50d8ae3SPaolo Bonzini  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1336c50d8ae3SPaolo Bonzini  * protect the page if the D-bit isn't supported.
1337c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1338c50d8ae3SPaolo Bonzini  * @slot: slot to clear D-bit
1339c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1340c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should clear D-bit
1341c50d8ae3SPaolo Bonzini  *
1342c50d8ae3SPaolo Bonzini  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1343c50d8ae3SPaolo Bonzini  */
1344a018eba5SSean Christopherson static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1345c50d8ae3SPaolo Bonzini 					 struct kvm_memory_slot *slot,
1346c50d8ae3SPaolo Bonzini 					 gfn_t gfn_offset, unsigned long mask)
1347c50d8ae3SPaolo Bonzini {
1348c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1349c50d8ae3SPaolo Bonzini 
13501f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1351a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1352a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, false);
1353e2209710SBen Gardon 
1354e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1355e2209710SBen Gardon 		return;
1356e2209710SBen Gardon 
1357c50d8ae3SPaolo Bonzini 	while (mask) {
135893e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13593bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13600a234f5dSSean Christopherson 		__rmap_clear_dirty(kvm, rmap_head, slot);
1361c50d8ae3SPaolo Bonzini 
1362c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1363c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1364c50d8ae3SPaolo Bonzini 	}
1365c50d8ae3SPaolo Bonzini }
1366c50d8ae3SPaolo Bonzini 
1367c50d8ae3SPaolo Bonzini /**
1368c50d8ae3SPaolo Bonzini  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1369c50d8ae3SPaolo Bonzini  * PT level pages.
1370c50d8ae3SPaolo Bonzini  *
1371c50d8ae3SPaolo Bonzini  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1372c50d8ae3SPaolo Bonzini  * enable dirty logging for them.
1373c50d8ae3SPaolo Bonzini  *
137489212919SKeqian Zhu  * We need to care about huge page mappings: e.g. during dirty logging we may
137589212919SKeqian Zhu  * have such mappings.
1376c50d8ae3SPaolo Bonzini  */
1377c50d8ae3SPaolo Bonzini void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1378c50d8ae3SPaolo Bonzini 				struct kvm_memory_slot *slot,
1379c50d8ae3SPaolo Bonzini 				gfn_t gfn_offset, unsigned long mask)
1380c50d8ae3SPaolo Bonzini {
138189212919SKeqian Zhu 	/*
138289212919SKeqian Zhu 	 * Huge pages are NOT write protected when we start dirty logging in
138389212919SKeqian Zhu 	 * initially-all-set mode; must write protect them here so that they
138489212919SKeqian Zhu 	 * are split to 4K on the first write.
138589212919SKeqian Zhu 	 *
138689212919SKeqian Zhu 	 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
138789212919SKeqian Zhu 	 * of memslot has no such restriction, so the range can cross two large
138889212919SKeqian Zhu 	 * pages.
138989212919SKeqian Zhu 	 */
139089212919SKeqian Zhu 	if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
139189212919SKeqian Zhu 		gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
139289212919SKeqian Zhu 		gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
139389212919SKeqian Zhu 
1394cb00a70bSDavid Matlack 		if (READ_ONCE(eager_page_split))
1395cb00a70bSDavid Matlack 			kvm_mmu_try_split_huge_pages(kvm, slot, start, end, PG_LEVEL_4K);
1396cb00a70bSDavid Matlack 
139789212919SKeqian Zhu 		kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
139889212919SKeqian Zhu 
139989212919SKeqian Zhu 		/* Cross two large pages? */
140089212919SKeqian Zhu 		if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
140189212919SKeqian Zhu 		    ALIGN(end << PAGE_SHIFT, PMD_SIZE))
140289212919SKeqian Zhu 			kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
140389212919SKeqian Zhu 						       PG_LEVEL_2M);
140489212919SKeqian Zhu 	}
140589212919SKeqian Zhu 
140689212919SKeqian Zhu 	/* Now handle 4K PTEs.  */
1407a018eba5SSean Christopherson 	if (kvm_x86_ops.cpu_dirty_log_size)
1408a018eba5SSean Christopherson 		kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1409c50d8ae3SPaolo Bonzini 	else
1410c50d8ae3SPaolo Bonzini 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1411c50d8ae3SPaolo Bonzini }
1412c50d8ae3SPaolo Bonzini 
1413fb04a1edSPeter Xu int kvm_cpu_dirty_log_size(void)
1414fb04a1edSPeter Xu {
14156dd03800SSean Christopherson 	return kvm_x86_ops.cpu_dirty_log_size;
1416fb04a1edSPeter Xu }
1417fb04a1edSPeter Xu 
1418c50d8ae3SPaolo Bonzini bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
14193ad93562SKeqian Zhu 				    struct kvm_memory_slot *slot, u64 gfn,
14203ad93562SKeqian Zhu 				    int min_level)
1421c50d8ae3SPaolo Bonzini {
1422c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1423c50d8ae3SPaolo Bonzini 	int i;
1424c50d8ae3SPaolo Bonzini 	bool write_protected = false;
1425c50d8ae3SPaolo Bonzini 
1426e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
14273ad93562SKeqian Zhu 		for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
142893e083d4SDavid Matlack 			rmap_head = gfn_to_rmap(gfn, i, slot);
14291346bbb6SDavid Matlack 			write_protected |= rmap_write_protect(rmap_head, true);
1430c50d8ae3SPaolo Bonzini 		}
1431e2209710SBen Gardon 	}
1432c50d8ae3SPaolo Bonzini 
14331f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
143446044f72SBen Gardon 		write_protected |=
14353ad93562SKeqian Zhu 			kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
143646044f72SBen Gardon 
1437c50d8ae3SPaolo Bonzini 	return write_protected;
1438c50d8ae3SPaolo Bonzini }
1439c50d8ae3SPaolo Bonzini 
1440cf48f9e2SDavid Matlack static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1441c50d8ae3SPaolo Bonzini {
1442c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
1443c50d8ae3SPaolo Bonzini 
1444c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
14453ad93562SKeqian Zhu 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1446c50d8ae3SPaolo Bonzini }
1447c50d8ae3SPaolo Bonzini 
1448f8480721SSean Christopherson static bool __kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1449269e9552SHamza Mahfooz 			   const struct kvm_memory_slot *slot)
1450c50d8ae3SPaolo Bonzini {
14519202aee8SSean Christopherson 	return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1452c50d8ae3SPaolo Bonzini }
1453c50d8ae3SPaolo Bonzini 
1454f8480721SSean Christopherson static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1455c50d8ae3SPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
14563039bcc7SSean Christopherson 			 pte_t unused)
1457c50d8ae3SPaolo Bonzini {
1458f8480721SSean Christopherson 	return __kvm_zap_rmap(kvm, rmap_head, slot);
1459c50d8ae3SPaolo Bonzini }
1460c50d8ae3SPaolo Bonzini 
1461aed02fe3SSean Christopherson static bool kvm_set_pte_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1462c50d8ae3SPaolo Bonzini 			     struct kvm_memory_slot *slot, gfn_t gfn, int level,
14633039bcc7SSean Christopherson 			     pte_t pte)
1464c50d8ae3SPaolo Bonzini {
1465c50d8ae3SPaolo Bonzini 	u64 *sptep;
1466c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
146798a26b69SVihas Mak 	bool need_flush = false;
1468c50d8ae3SPaolo Bonzini 	u64 new_spte;
1469c50d8ae3SPaolo Bonzini 	kvm_pfn_t new_pfn;
1470c50d8ae3SPaolo Bonzini 
147120ba462dSSean Christopherson 	WARN_ON_ONCE(pte_huge(pte));
14723039bcc7SSean Christopherson 	new_pfn = pte_pfn(pte);
1473c50d8ae3SPaolo Bonzini 
1474c50d8ae3SPaolo Bonzini restart:
1475c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
147698a26b69SVihas Mak 		need_flush = true;
1477c50d8ae3SPaolo Bonzini 
14783039bcc7SSean Christopherson 		if (pte_write(pte)) {
14799202aee8SSean Christopherson 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
1480c50d8ae3SPaolo Bonzini 			goto restart;
1481c50d8ae3SPaolo Bonzini 		} else {
1482cb3eedabSPaolo Bonzini 			new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1483cb3eedabSPaolo Bonzini 					*sptep, new_pfn);
1484c50d8ae3SPaolo Bonzini 
148571f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, sptep);
1486c50d8ae3SPaolo Bonzini 			mmu_spte_set(sptep, new_spte);
1487c50d8ae3SPaolo Bonzini 		}
1488c50d8ae3SPaolo Bonzini 	}
1489c50d8ae3SPaolo Bonzini 
14908a1300ffSSean Christopherson 	if (need_flush && kvm_available_flush_remote_tlbs_range()) {
14919ffe9265SHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, level);
149298a26b69SVihas Mak 		return false;
1493c50d8ae3SPaolo Bonzini 	}
1494c50d8ae3SPaolo Bonzini 
1495c50d8ae3SPaolo Bonzini 	return need_flush;
1496c50d8ae3SPaolo Bonzini }
1497c50d8ae3SPaolo Bonzini 
1498c50d8ae3SPaolo Bonzini struct slot_rmap_walk_iterator {
1499c50d8ae3SPaolo Bonzini 	/* input fields. */
1500269e9552SHamza Mahfooz 	const struct kvm_memory_slot *slot;
1501c50d8ae3SPaolo Bonzini 	gfn_t start_gfn;
1502c50d8ae3SPaolo Bonzini 	gfn_t end_gfn;
1503c50d8ae3SPaolo Bonzini 	int start_level;
1504c50d8ae3SPaolo Bonzini 	int end_level;
1505c50d8ae3SPaolo Bonzini 
1506c50d8ae3SPaolo Bonzini 	/* output fields. */
1507c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1508c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap;
1509c50d8ae3SPaolo Bonzini 	int level;
1510c50d8ae3SPaolo Bonzini 
1511c50d8ae3SPaolo Bonzini 	/* private field. */
1512c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *end_rmap;
1513c50d8ae3SPaolo Bonzini };
1514c50d8ae3SPaolo Bonzini 
1515f3d90f90SSean Christopherson static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,
1516f3d90f90SSean Christopherson 				 int level)
1517c50d8ae3SPaolo Bonzini {
1518c50d8ae3SPaolo Bonzini 	iterator->level = level;
1519c50d8ae3SPaolo Bonzini 	iterator->gfn = iterator->start_gfn;
152093e083d4SDavid Matlack 	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
152193e083d4SDavid Matlack 	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1522c50d8ae3SPaolo Bonzini }
1523c50d8ae3SPaolo Bonzini 
1524f3d90f90SSean Christopherson static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1525f3d90f90SSean Christopherson 				const struct kvm_memory_slot *slot,
1526f3d90f90SSean Christopherson 				int start_level, int end_level,
1527f3d90f90SSean Christopherson 				gfn_t start_gfn, gfn_t end_gfn)
1528c50d8ae3SPaolo Bonzini {
1529c50d8ae3SPaolo Bonzini 	iterator->slot = slot;
1530c50d8ae3SPaolo Bonzini 	iterator->start_level = start_level;
1531c50d8ae3SPaolo Bonzini 	iterator->end_level = end_level;
1532c50d8ae3SPaolo Bonzini 	iterator->start_gfn = start_gfn;
1533c50d8ae3SPaolo Bonzini 	iterator->end_gfn = end_gfn;
1534c50d8ae3SPaolo Bonzini 
1535c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->start_level);
1536c50d8ae3SPaolo Bonzini }
1537c50d8ae3SPaolo Bonzini 
1538c50d8ae3SPaolo Bonzini static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1539c50d8ae3SPaolo Bonzini {
1540c50d8ae3SPaolo Bonzini 	return !!iterator->rmap;
1541c50d8ae3SPaolo Bonzini }
1542c50d8ae3SPaolo Bonzini 
1543c50d8ae3SPaolo Bonzini static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1544c50d8ae3SPaolo Bonzini {
15456ba1e04fSVipin Sharma 	while (++iterator->rmap <= iterator->end_rmap) {
1546c50d8ae3SPaolo Bonzini 		iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
15476ba1e04fSVipin Sharma 
15486ba1e04fSVipin Sharma 		if (iterator->rmap->val)
1549c50d8ae3SPaolo Bonzini 			return;
1550c50d8ae3SPaolo Bonzini 	}
1551c50d8ae3SPaolo Bonzini 
1552c50d8ae3SPaolo Bonzini 	if (++iterator->level > iterator->end_level) {
1553c50d8ae3SPaolo Bonzini 		iterator->rmap = NULL;
1554c50d8ae3SPaolo Bonzini 		return;
1555c50d8ae3SPaolo Bonzini 	}
1556c50d8ae3SPaolo Bonzini 
1557c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->level);
1558c50d8ae3SPaolo Bonzini }
1559c50d8ae3SPaolo Bonzini 
1560c50d8ae3SPaolo Bonzini #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1561c50d8ae3SPaolo Bonzini 	   _start_gfn, _end_gfn, _iter_)				\
1562c50d8ae3SPaolo Bonzini 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1563c50d8ae3SPaolo Bonzini 				 _end_level_, _start_gfn, _end_gfn);	\
1564c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_okay(_iter_);				\
1565c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_next(_iter_))
1566c50d8ae3SPaolo Bonzini 
15673039bcc7SSean Christopherson typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1568c1b91493SSean Christopherson 			       struct kvm_memory_slot *slot, gfn_t gfn,
15693039bcc7SSean Christopherson 			       int level, pte_t pte);
1570c1b91493SSean Christopherson 
15713039bcc7SSean Christopherson static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
15723039bcc7SSean Christopherson 						 struct kvm_gfn_range *range,
1573c1b91493SSean Christopherson 						 rmap_handler_t handler)
1574c50d8ae3SPaolo Bonzini {
1575c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
15763039bcc7SSean Christopherson 	bool ret = false;
1577c50d8ae3SPaolo Bonzini 
15783039bcc7SSean Christopherson 	for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
15793039bcc7SSean Christopherson 				 range->start, range->end - 1, &iterator)
15803039bcc7SSean Christopherson 		ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
15813e1efe2bSSean Christopherson 			       iterator.level, range->arg.pte);
1582c50d8ae3SPaolo Bonzini 
1583c50d8ae3SPaolo Bonzini 	return ret;
1584c50d8ae3SPaolo Bonzini }
1585c50d8ae3SPaolo Bonzini 
15863039bcc7SSean Christopherson bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1587c50d8ae3SPaolo Bonzini {
1588e2209710SBen Gardon 	bool flush = false;
1589c50d8ae3SPaolo Bonzini 
1590e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1591f8480721SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
1592063afacdSBen Gardon 
15931f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1594c7785d85SHou Wenlong 		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1595063afacdSBen Gardon 
15960a3869e1SSean Christopherson 	if (kvm_x86_ops.set_apic_access_page_addr &&
15970a3869e1SSean Christopherson 	    range->slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT)
15980a8a5f2cSSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
15990a8a5f2cSSean Christopherson 
16003039bcc7SSean Christopherson 	return flush;
1601c50d8ae3SPaolo Bonzini }
1602c50d8ae3SPaolo Bonzini 
16033039bcc7SSean Christopherson bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1604c50d8ae3SPaolo Bonzini {
1605e2209710SBen Gardon 	bool flush = false;
16061d8dd6b3SBen Gardon 
1607e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1608aed02fe3SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmap);
16091d8dd6b3SBen Gardon 
16101f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16113039bcc7SSean Christopherson 		flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
16121d8dd6b3SBen Gardon 
16133039bcc7SSean Christopherson 	return flush;
1614c50d8ae3SPaolo Bonzini }
1615c50d8ae3SPaolo Bonzini 
1616aed02fe3SSean Christopherson static bool kvm_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1617c50d8ae3SPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
16183039bcc7SSean Christopherson 			 pte_t unused)
1619c50d8ae3SPaolo Bonzini {
1620c50d8ae3SPaolo Bonzini 	u64 *sptep;
16213f649ab7SKees Cook 	struct rmap_iterator iter;
1622c50d8ae3SPaolo Bonzini 	int young = 0;
1623c50d8ae3SPaolo Bonzini 
1624c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1625c50d8ae3SPaolo Bonzini 		young |= mmu_spte_age(sptep);
1626c50d8ae3SPaolo Bonzini 
1627c50d8ae3SPaolo Bonzini 	return young;
1628c50d8ae3SPaolo Bonzini }
1629c50d8ae3SPaolo Bonzini 
1630aed02fe3SSean Christopherson static bool kvm_test_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1631c50d8ae3SPaolo Bonzini 			      struct kvm_memory_slot *slot, gfn_t gfn,
16323039bcc7SSean Christopherson 			      int level, pte_t unused)
1633c50d8ae3SPaolo Bonzini {
1634c50d8ae3SPaolo Bonzini 	u64 *sptep;
1635c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1636c50d8ae3SPaolo Bonzini 
1637c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1638c50d8ae3SPaolo Bonzini 		if (is_accessed_spte(*sptep))
163998a26b69SVihas Mak 			return true;
164098a26b69SVihas Mak 	return false;
1641c50d8ae3SPaolo Bonzini }
1642c50d8ae3SPaolo Bonzini 
1643c50d8ae3SPaolo Bonzini #define RMAP_RECYCLE_THRESHOLD 1000
1644c50d8ae3SPaolo Bonzini 
16452ff9039aSDavid Matlack static void __rmap_add(struct kvm *kvm,
16462ff9039aSDavid Matlack 		       struct kvm_mmu_memory_cache *cache,
16472ff9039aSDavid Matlack 		       const struct kvm_memory_slot *slot,
164872ae5822SSean Christopherson 		       u64 *spte, gfn_t gfn, unsigned int access)
1649c50d8ae3SPaolo Bonzini {
1650c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
165168be1306SDavid Matlack 	struct kvm_rmap_head *rmap_head;
165268be1306SDavid Matlack 	int rmap_count;
1653c50d8ae3SPaolo Bonzini 
165457354682SSean Christopherson 	sp = sptep_to_sp(spte);
165579e48cecSSean Christopherson 	kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
165681cb4657SDavid Matlack 	kvm_update_page_stats(kvm, sp->role.level, 1);
165781cb4657SDavid Matlack 
165893e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
16592ff9039aSDavid Matlack 	rmap_count = pte_list_add(cache, spte, rmap_head);
1660c50d8ae3SPaolo Bonzini 
1661604f5332SMiaohe Lin 	if (rmap_count > kvm->stat.max_mmu_rmap_size)
1662604f5332SMiaohe Lin 		kvm->stat.max_mmu_rmap_size = rmap_count;
166368be1306SDavid Matlack 	if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
16649202aee8SSean Christopherson 		kvm_zap_all_rmap_sptes(kvm, rmap_head);
16651b2dc736SHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
166668be1306SDavid Matlack 	}
1667c50d8ae3SPaolo Bonzini }
1668c50d8ae3SPaolo Bonzini 
16692ff9039aSDavid Matlack static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
167072ae5822SSean Christopherson 		     u64 *spte, gfn_t gfn, unsigned int access)
16712ff9039aSDavid Matlack {
16722ff9039aSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
16732ff9039aSDavid Matlack 
16746a97575dSDavid Matlack 	__rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
16752ff9039aSDavid Matlack }
16762ff9039aSDavid Matlack 
16773039bcc7SSean Christopherson bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1678c50d8ae3SPaolo Bonzini {
1679e2209710SBen Gardon 	bool young = false;
1680f8e14497SBen Gardon 
1681e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1682aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_age_rmap);
16833039bcc7SSean Christopherson 
16841f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16853039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1686f8e14497SBen Gardon 
1687f8e14497SBen Gardon 	return young;
1688c50d8ae3SPaolo Bonzini }
1689c50d8ae3SPaolo Bonzini 
16903039bcc7SSean Christopherson bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1691c50d8ae3SPaolo Bonzini {
1692e2209710SBen Gardon 	bool young = false;
1693f8e14497SBen Gardon 
1694e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1695aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmap);
16963039bcc7SSean Christopherson 
16971f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16983039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1699f8e14497SBen Gardon 
1700f8e14497SBen Gardon 	return young;
1701c50d8ae3SPaolo Bonzini }
1702c50d8ae3SPaolo Bonzini 
170358da926cSSean Christopherson static void kvm_mmu_check_sptes_at_free(struct kvm_mmu_page *sp)
1704c50d8ae3SPaolo Bonzini {
1705870d4d4eSSean Christopherson #ifdef CONFIG_KVM_PROVE_MMU
1706242a6dd8SSean Christopherson 	int i;
1707c50d8ae3SPaolo Bonzini 
1708242a6dd8SSean Christopherson 	for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
17090fe6370eSSean Christopherson 		if (KVM_MMU_WARN_ON(is_shadow_present_pte(sp->spt[i])))
171058da926cSSean Christopherson 			pr_err_ratelimited("SPTE %llx (@ %p) for gfn %llx shadow-present at free",
171158da926cSSean Christopherson 					   sp->spt[i], &sp->spt[i],
171258da926cSSean Christopherson 					   kvm_mmu_page_get_gfn(sp, i));
1713c50d8ae3SPaolo Bonzini 	}
1714c50d8ae3SPaolo Bonzini #endif
171558da926cSSean Christopherson }
1716c50d8ae3SPaolo Bonzini 
1717c50d8ae3SPaolo Bonzini /*
1718c50d8ae3SPaolo Bonzini  * This value is the sum of all of the kvm instances's
1719c50d8ae3SPaolo Bonzini  * kvm->arch.n_used_mmu_pages values.  We need a global,
1720c50d8ae3SPaolo Bonzini  * aggregate version in order to make the slab shrinker
1721c50d8ae3SPaolo Bonzini  * faster
1722c50d8ae3SPaolo Bonzini  */
1723d5aaad6fSSean Christopherson static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1724c50d8ae3SPaolo Bonzini {
1725c50d8ae3SPaolo Bonzini 	kvm->arch.n_used_mmu_pages += nr;
1726c50d8ae3SPaolo Bonzini 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1727c50d8ae3SPaolo Bonzini }
1728c50d8ae3SPaolo Bonzini 
172943a063caSYosry Ahmed static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
173043a063caSYosry Ahmed {
173143a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, +1);
173243a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, +1);
173343a063caSYosry Ahmed }
173443a063caSYosry Ahmed 
173543a063caSYosry Ahmed static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
173643a063caSYosry Ahmed {
173743a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, -1);
173843a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, -1);
173943a063caSYosry Ahmed }
174043a063caSYosry Ahmed 
174187654643SDavid Matlack static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1742c50d8ae3SPaolo Bonzini {
174358da926cSSean Christopherson 	kvm_mmu_check_sptes_at_free(sp);
174458da926cSSean Christopherson 
1745c50d8ae3SPaolo Bonzini 	hlist_del(&sp->hash_link);
1746c50d8ae3SPaolo Bonzini 	list_del(&sp->link);
1747c50d8ae3SPaolo Bonzini 	free_page((unsigned long)sp->spt);
1748c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
17496a97575dSDavid Matlack 		free_page((unsigned long)sp->shadowed_translation);
1750c50d8ae3SPaolo Bonzini 	kmem_cache_free(mmu_page_header_cache, sp);
1751c50d8ae3SPaolo Bonzini }
1752c50d8ae3SPaolo Bonzini 
1753c50d8ae3SPaolo Bonzini static unsigned kvm_page_table_hashfn(gfn_t gfn)
1754c50d8ae3SPaolo Bonzini {
1755c50d8ae3SPaolo Bonzini 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1756c50d8ae3SPaolo Bonzini }
1757c50d8ae3SPaolo Bonzini 
17582ff9039aSDavid Matlack static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
1759c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp, u64 *parent_pte)
1760c50d8ae3SPaolo Bonzini {
1761c50d8ae3SPaolo Bonzini 	if (!parent_pte)
1762c50d8ae3SPaolo Bonzini 		return;
1763c50d8ae3SPaolo Bonzini 
17642ff9039aSDavid Matlack 	pte_list_add(cache, parent_pte, &sp->parent_ptes);
1765c50d8ae3SPaolo Bonzini }
1766c50d8ae3SPaolo Bonzini 
1767069f30c6SMingwei Zhang static void mmu_page_remove_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1768c50d8ae3SPaolo Bonzini 				       u64 *parent_pte)
1769c50d8ae3SPaolo Bonzini {
1770069f30c6SMingwei Zhang 	pte_list_remove(kvm, parent_pte, &sp->parent_ptes);
1771c50d8ae3SPaolo Bonzini }
1772c50d8ae3SPaolo Bonzini 
1773069f30c6SMingwei Zhang static void drop_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1774c50d8ae3SPaolo Bonzini 			    u64 *parent_pte)
1775c50d8ae3SPaolo Bonzini {
1776069f30c6SMingwei Zhang 	mmu_page_remove_parent_pte(kvm, sp, parent_pte);
1777c50d8ae3SPaolo Bonzini 	mmu_spte_clear_no_track(parent_pte);
1778c50d8ae3SPaolo Bonzini }
1779c50d8ae3SPaolo Bonzini 
1780c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte);
1781c50d8ae3SPaolo Bonzini static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1782c50d8ae3SPaolo Bonzini {
1783c50d8ae3SPaolo Bonzini 	u64 *sptep;
1784c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1785c50d8ae3SPaolo Bonzini 
1786c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1787c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
1788c50d8ae3SPaolo Bonzini 	}
1789c50d8ae3SPaolo Bonzini }
1790c50d8ae3SPaolo Bonzini 
1791c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte)
1792c50d8ae3SPaolo Bonzini {
1793c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1794c50d8ae3SPaolo Bonzini 
179557354682SSean Christopherson 	sp = sptep_to_sp(spte);
179679e48cecSSean Christopherson 	if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1797c50d8ae3SPaolo Bonzini 		return;
1798c50d8ae3SPaolo Bonzini 	if (sp->unsync_children++)
1799c50d8ae3SPaolo Bonzini 		return;
1800c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
1801c50d8ae3SPaolo Bonzini }
1802c50d8ae3SPaolo Bonzini 
1803c50d8ae3SPaolo Bonzini #define KVM_PAGE_ARRAY_NR 16
1804c50d8ae3SPaolo Bonzini 
1805c50d8ae3SPaolo Bonzini struct kvm_mmu_pages {
1806c50d8ae3SPaolo Bonzini 	struct mmu_page_and_offset {
1807c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
1808c50d8ae3SPaolo Bonzini 		unsigned int idx;
1809c50d8ae3SPaolo Bonzini 	} page[KVM_PAGE_ARRAY_NR];
1810c50d8ae3SPaolo Bonzini 	unsigned int nr;
1811c50d8ae3SPaolo Bonzini };
1812c50d8ae3SPaolo Bonzini 
1813c50d8ae3SPaolo Bonzini static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1814c50d8ae3SPaolo Bonzini 			 int idx)
1815c50d8ae3SPaolo Bonzini {
1816c50d8ae3SPaolo Bonzini 	int i;
1817c50d8ae3SPaolo Bonzini 
1818c50d8ae3SPaolo Bonzini 	if (sp->unsync)
1819c50d8ae3SPaolo Bonzini 		for (i=0; i < pvec->nr; i++)
1820c50d8ae3SPaolo Bonzini 			if (pvec->page[i].sp == sp)
1821c50d8ae3SPaolo Bonzini 				return 0;
1822c50d8ae3SPaolo Bonzini 
1823c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].sp = sp;
1824c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].idx = idx;
1825c50d8ae3SPaolo Bonzini 	pvec->nr++;
1826c50d8ae3SPaolo Bonzini 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
1827c50d8ae3SPaolo Bonzini }
1828c50d8ae3SPaolo Bonzini 
1829c50d8ae3SPaolo Bonzini static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1830c50d8ae3SPaolo Bonzini {
1831c50d8ae3SPaolo Bonzini 	--sp->unsync_children;
183220ba462dSSean Christopherson 	WARN_ON_ONCE((int)sp->unsync_children < 0);
1833c50d8ae3SPaolo Bonzini 	__clear_bit(idx, sp->unsync_child_bitmap);
1834c50d8ae3SPaolo Bonzini }
1835c50d8ae3SPaolo Bonzini 
1836c50d8ae3SPaolo Bonzini static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1837c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1838c50d8ae3SPaolo Bonzini {
1839c50d8ae3SPaolo Bonzini 	int i, ret, nr_unsync_leaf = 0;
1840c50d8ae3SPaolo Bonzini 
1841c50d8ae3SPaolo Bonzini 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1842c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
1843c50d8ae3SPaolo Bonzini 		u64 ent = sp->spt[i];
1844c50d8ae3SPaolo Bonzini 
1845c50d8ae3SPaolo Bonzini 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1846c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1847c50d8ae3SPaolo Bonzini 			continue;
1848c50d8ae3SPaolo Bonzini 		}
1849c50d8ae3SPaolo Bonzini 
18505e3edd7eSSean Christopherson 		child = spte_to_child_sp(ent);
1851c50d8ae3SPaolo Bonzini 
1852c50d8ae3SPaolo Bonzini 		if (child->unsync_children) {
1853c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1854c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1855c50d8ae3SPaolo Bonzini 
1856c50d8ae3SPaolo Bonzini 			ret = __mmu_unsync_walk(child, pvec);
1857c50d8ae3SPaolo Bonzini 			if (!ret) {
1858c50d8ae3SPaolo Bonzini 				clear_unsync_child_bit(sp, i);
1859c50d8ae3SPaolo Bonzini 				continue;
1860c50d8ae3SPaolo Bonzini 			} else if (ret > 0) {
1861c50d8ae3SPaolo Bonzini 				nr_unsync_leaf += ret;
1862c50d8ae3SPaolo Bonzini 			} else
1863c50d8ae3SPaolo Bonzini 				return ret;
1864c50d8ae3SPaolo Bonzini 		} else if (child->unsync) {
1865c50d8ae3SPaolo Bonzini 			nr_unsync_leaf++;
1866c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1867c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1868c50d8ae3SPaolo Bonzini 		} else
1869c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1870c50d8ae3SPaolo Bonzini 	}
1871c50d8ae3SPaolo Bonzini 
1872c50d8ae3SPaolo Bonzini 	return nr_unsync_leaf;
1873c50d8ae3SPaolo Bonzini }
1874c50d8ae3SPaolo Bonzini 
1875c50d8ae3SPaolo Bonzini #define INVALID_INDEX (-1)
1876c50d8ae3SPaolo Bonzini 
1877c50d8ae3SPaolo Bonzini static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1878c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1879c50d8ae3SPaolo Bonzini {
1880c50d8ae3SPaolo Bonzini 	pvec->nr = 0;
1881c50d8ae3SPaolo Bonzini 	if (!sp->unsync_children)
1882c50d8ae3SPaolo Bonzini 		return 0;
1883c50d8ae3SPaolo Bonzini 
1884c50d8ae3SPaolo Bonzini 	mmu_pages_add(pvec, sp, INVALID_INDEX);
1885c50d8ae3SPaolo Bonzini 	return __mmu_unsync_walk(sp, pvec);
1886c50d8ae3SPaolo Bonzini }
1887c50d8ae3SPaolo Bonzini 
1888c50d8ae3SPaolo Bonzini static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1889c50d8ae3SPaolo Bonzini {
189020ba462dSSean Christopherson 	WARN_ON_ONCE(!sp->unsync);
1891c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_sync_page(sp);
1892c50d8ae3SPaolo Bonzini 	sp->unsync = 0;
1893c50d8ae3SPaolo Bonzini 	--kvm->stat.mmu_unsync;
1894c50d8ae3SPaolo Bonzini }
1895c50d8ae3SPaolo Bonzini 
1896c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1897c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list);
1898c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1899c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list);
1900c50d8ae3SPaolo Bonzini 
1901767d8d8dSLai Jiangshan static bool sp_has_gptes(struct kvm_mmu_page *sp)
1902767d8d8dSLai Jiangshan {
1903767d8d8dSLai Jiangshan 	if (sp->role.direct)
1904767d8d8dSLai Jiangshan 		return false;
1905767d8d8dSLai Jiangshan 
190684e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
190784e5ffd0SLai Jiangshan 		return false;
190884e5ffd0SLai Jiangshan 
1909767d8d8dSLai Jiangshan 	return true;
1910767d8d8dSLai Jiangshan }
1911767d8d8dSLai Jiangshan 
1912ac101b7cSSean Christopherson #define for_each_valid_sp(_kvm, _sp, _list)				\
1913ac101b7cSSean Christopherson 	hlist_for_each_entry(_sp, _list, hash_link)			\
1914c50d8ae3SPaolo Bonzini 		if (is_obsolete_sp((_kvm), (_sp))) {			\
1915c50d8ae3SPaolo Bonzini 		} else
1916c50d8ae3SPaolo Bonzini 
1917767d8d8dSLai Jiangshan #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn)		\
1918ac101b7cSSean Christopherson 	for_each_valid_sp(_kvm, _sp,					\
1919ac101b7cSSean Christopherson 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
1920767d8d8dSLai Jiangshan 		if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1921c50d8ae3SPaolo Bonzini 
192290e44470SLai Jiangshan static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
192390e44470SLai Jiangshan {
192490e44470SLai Jiangshan 	union kvm_mmu_page_role root_role = vcpu->arch.mmu->root_role;
192590e44470SLai Jiangshan 
192690e44470SLai Jiangshan 	/*
192790e44470SLai Jiangshan 	 * Ignore various flags when verifying that it's safe to sync a shadow
192890e44470SLai Jiangshan 	 * page using the current MMU context.
192990e44470SLai Jiangshan 	 *
193090e44470SLai Jiangshan 	 *  - level: not part of the overall MMU role and will never match as the MMU's
193190e44470SLai Jiangshan 	 *           level tracks the root level
193290e44470SLai Jiangshan 	 *  - access: updated based on the new guest PTE
193390e44470SLai Jiangshan 	 *  - quadrant: not part of the overall MMU role (similar to level)
193490e44470SLai Jiangshan 	 */
193590e44470SLai Jiangshan 	const union kvm_mmu_page_role sync_role_ign = {
193690e44470SLai Jiangshan 		.level = 0xf,
193790e44470SLai Jiangshan 		.access = 0x7,
193890e44470SLai Jiangshan 		.quadrant = 0x3,
193990e44470SLai Jiangshan 		.passthrough = 0x1,
194090e44470SLai Jiangshan 	};
194190e44470SLai Jiangshan 
194290e44470SLai Jiangshan 	/*
194390e44470SLai Jiangshan 	 * Direct pages can never be unsync, and KVM should never attempt to
194490e44470SLai Jiangshan 	 * sync a shadow page for a different MMU context, e.g. if the role
194590e44470SLai Jiangshan 	 * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
194690e44470SLai Jiangshan 	 * reserved bits checks will be wrong, etc...
194790e44470SLai Jiangshan 	 */
1948c3c6c9fcSLai Jiangshan 	if (WARN_ON_ONCE(sp->role.direct || !vcpu->arch.mmu->sync_spte ||
194990e44470SLai Jiangshan 			 (sp->role.word ^ root_role.word) & ~sync_role_ign.word))
195090e44470SLai Jiangshan 		return false;
195190e44470SLai Jiangshan 
195290e44470SLai Jiangshan 	return true;
195390e44470SLai Jiangshan }
195490e44470SLai Jiangshan 
195519ace7d6SLai Jiangshan static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
195619ace7d6SLai Jiangshan {
195719ace7d6SLai Jiangshan 	if (!sp->spt[i])
195819ace7d6SLai Jiangshan 		return 0;
195919ace7d6SLai Jiangshan 
196019ace7d6SLai Jiangshan 	return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
196119ace7d6SLai Jiangshan }
196219ace7d6SLai Jiangshan 
196390e44470SLai Jiangshan static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
196490e44470SLai Jiangshan {
1965c3c6c9fcSLai Jiangshan 	int flush = 0;
1966c3c6c9fcSLai Jiangshan 	int i;
1967c3c6c9fcSLai Jiangshan 
196890e44470SLai Jiangshan 	if (!kvm_sync_page_check(vcpu, sp))
196990e44470SLai Jiangshan 		return -1;
197090e44470SLai Jiangshan 
1971c3c6c9fcSLai Jiangshan 	for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
197219ace7d6SLai Jiangshan 		int ret = kvm_sync_spte(vcpu, sp, i);
1973c3c6c9fcSLai Jiangshan 
1974c3c6c9fcSLai Jiangshan 		if (ret < -1)
1975c3c6c9fcSLai Jiangshan 			return -1;
1976c3c6c9fcSLai Jiangshan 		flush |= ret;
1977c3c6c9fcSLai Jiangshan 	}
1978c3c6c9fcSLai Jiangshan 
1979c3c6c9fcSLai Jiangshan 	/*
1980c3c6c9fcSLai Jiangshan 	 * Note, any flush is purely for KVM's correctness, e.g. when dropping
1981c3c6c9fcSLai Jiangshan 	 * an existing SPTE or clearing W/A/D bits to ensure an mmu_notifier
1982c3c6c9fcSLai Jiangshan 	 * unmap or dirty logging event doesn't fail to flush.  The guest is
1983c3c6c9fcSLai Jiangshan 	 * responsible for flushing the TLB to ensure any changes in protection
1984c3c6c9fcSLai Jiangshan 	 * bits are recognized, i.e. until the guest flushes or page faults on
1985c3c6c9fcSLai Jiangshan 	 * a relevant address, KVM is architecturally allowed to let vCPUs use
1986c3c6c9fcSLai Jiangshan 	 * cached translations with the old protection bits.
1987c3c6c9fcSLai Jiangshan 	 */
1988c3c6c9fcSLai Jiangshan 	return flush;
198990e44470SLai Jiangshan }
199090e44470SLai Jiangshan 
19918d5678a7SHou Wenlong static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1992c50d8ae3SPaolo Bonzini 			 struct list_head *invalid_list)
1993c50d8ae3SPaolo Bonzini {
199490e44470SLai Jiangshan 	int ret = __kvm_sync_page(vcpu, sp);
1995c3e5e415SLai Jiangshan 
19968d5678a7SHou Wenlong 	if (ret < 0)
1997c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
19988d5678a7SHou Wenlong 	return ret;
1999c50d8ae3SPaolo Bonzini }
2000c50d8ae3SPaolo Bonzini 
2001c50d8ae3SPaolo Bonzini static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2002c50d8ae3SPaolo Bonzini 					struct list_head *invalid_list,
2003c50d8ae3SPaolo Bonzini 					bool remote_flush)
2004c50d8ae3SPaolo Bonzini {
2005c50d8ae3SPaolo Bonzini 	if (!remote_flush && list_empty(invalid_list))
2006c50d8ae3SPaolo Bonzini 		return false;
2007c50d8ae3SPaolo Bonzini 
2008c50d8ae3SPaolo Bonzini 	if (!list_empty(invalid_list))
2009c50d8ae3SPaolo Bonzini 		kvm_mmu_commit_zap_page(kvm, invalid_list);
2010c50d8ae3SPaolo Bonzini 	else
2011c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
2012c50d8ae3SPaolo Bonzini 	return true;
2013c50d8ae3SPaolo Bonzini }
2014c50d8ae3SPaolo Bonzini 
2015c50d8ae3SPaolo Bonzini static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2016c50d8ae3SPaolo Bonzini {
2017a955cad8SSean Christopherson 	if (sp->role.invalid)
2018a955cad8SSean Christopherson 		return true;
2019a955cad8SSean Christopherson 
2020fa3e4203SMiaohe Lin 	/* TDP MMU pages do not use the MMU generation. */
2021de0322f5SSean Christopherson 	return !is_tdp_mmu_page(sp) &&
2022c50d8ae3SPaolo Bonzini 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2023c50d8ae3SPaolo Bonzini }
2024c50d8ae3SPaolo Bonzini 
2025c50d8ae3SPaolo Bonzini struct mmu_page_path {
2026c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2027c50d8ae3SPaolo Bonzini 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
2028c50d8ae3SPaolo Bonzini };
2029c50d8ae3SPaolo Bonzini 
2030c50d8ae3SPaolo Bonzini #define for_each_sp(pvec, sp, parents, i)			\
2031c50d8ae3SPaolo Bonzini 		for (i = mmu_pages_first(&pvec, &parents);	\
2032c50d8ae3SPaolo Bonzini 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
2033c50d8ae3SPaolo Bonzini 			i = mmu_pages_next(&pvec, &parents, i))
2034c50d8ae3SPaolo Bonzini 
2035c50d8ae3SPaolo Bonzini static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2036c50d8ae3SPaolo Bonzini 			  struct mmu_page_path *parents,
2037c50d8ae3SPaolo Bonzini 			  int i)
2038c50d8ae3SPaolo Bonzini {
2039c50d8ae3SPaolo Bonzini 	int n;
2040c50d8ae3SPaolo Bonzini 
2041c50d8ae3SPaolo Bonzini 	for (n = i+1; n < pvec->nr; n++) {
2042c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp = pvec->page[n].sp;
2043c50d8ae3SPaolo Bonzini 		unsigned idx = pvec->page[n].idx;
2044c50d8ae3SPaolo Bonzini 		int level = sp->role.level;
2045c50d8ae3SPaolo Bonzini 
2046c50d8ae3SPaolo Bonzini 		parents->idx[level-1] = idx;
20473bae0459SSean Christopherson 		if (level == PG_LEVEL_4K)
2048c50d8ae3SPaolo Bonzini 			break;
2049c50d8ae3SPaolo Bonzini 
2050c50d8ae3SPaolo Bonzini 		parents->parent[level-2] = sp;
2051c50d8ae3SPaolo Bonzini 	}
2052c50d8ae3SPaolo Bonzini 
2053c50d8ae3SPaolo Bonzini 	return n;
2054c50d8ae3SPaolo Bonzini }
2055c50d8ae3SPaolo Bonzini 
2056c50d8ae3SPaolo Bonzini static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2057c50d8ae3SPaolo Bonzini 			   struct mmu_page_path *parents)
2058c50d8ae3SPaolo Bonzini {
2059c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2060c50d8ae3SPaolo Bonzini 	int level;
2061c50d8ae3SPaolo Bonzini 
2062c50d8ae3SPaolo Bonzini 	if (pvec->nr == 0)
2063c50d8ae3SPaolo Bonzini 		return 0;
2064c50d8ae3SPaolo Bonzini 
206520ba462dSSean Christopherson 	WARN_ON_ONCE(pvec->page[0].idx != INVALID_INDEX);
2066c50d8ae3SPaolo Bonzini 
2067c50d8ae3SPaolo Bonzini 	sp = pvec->page[0].sp;
2068c50d8ae3SPaolo Bonzini 	level = sp->role.level;
206920ba462dSSean Christopherson 	WARN_ON_ONCE(level == PG_LEVEL_4K);
2070c50d8ae3SPaolo Bonzini 
2071c50d8ae3SPaolo Bonzini 	parents->parent[level-2] = sp;
2072c50d8ae3SPaolo Bonzini 
2073c50d8ae3SPaolo Bonzini 	/* Also set up a sentinel.  Further entries in pvec are all
2074c50d8ae3SPaolo Bonzini 	 * children of sp, so this element is never overwritten.
2075c50d8ae3SPaolo Bonzini 	 */
2076c50d8ae3SPaolo Bonzini 	parents->parent[level-1] = NULL;
2077c50d8ae3SPaolo Bonzini 	return mmu_pages_next(pvec, parents, 0);
2078c50d8ae3SPaolo Bonzini }
2079c50d8ae3SPaolo Bonzini 
2080c50d8ae3SPaolo Bonzini static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2081c50d8ae3SPaolo Bonzini {
2082c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2083c50d8ae3SPaolo Bonzini 	unsigned int level = 0;
2084c50d8ae3SPaolo Bonzini 
2085c50d8ae3SPaolo Bonzini 	do {
2086c50d8ae3SPaolo Bonzini 		unsigned int idx = parents->idx[level];
2087c50d8ae3SPaolo Bonzini 		sp = parents->parent[level];
2088c50d8ae3SPaolo Bonzini 		if (!sp)
2089c50d8ae3SPaolo Bonzini 			return;
2090c50d8ae3SPaolo Bonzini 
209120ba462dSSean Christopherson 		WARN_ON_ONCE(idx == INVALID_INDEX);
2092c50d8ae3SPaolo Bonzini 		clear_unsync_child_bit(sp, idx);
2093c50d8ae3SPaolo Bonzini 		level++;
2094c50d8ae3SPaolo Bonzini 	} while (!sp->unsync_children);
2095c50d8ae3SPaolo Bonzini }
2096c50d8ae3SPaolo Bonzini 
209765855ed8SLai Jiangshan static int mmu_sync_children(struct kvm_vcpu *vcpu,
209865855ed8SLai Jiangshan 			     struct kvm_mmu_page *parent, bool can_yield)
2099c50d8ae3SPaolo Bonzini {
2100c50d8ae3SPaolo Bonzini 	int i;
2101c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2102c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2103c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2104c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2105c50d8ae3SPaolo Bonzini 	bool flush = false;
2106c50d8ae3SPaolo Bonzini 
2107c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2108c50d8ae3SPaolo Bonzini 		bool protected = false;
2109c50d8ae3SPaolo Bonzini 
2110c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i)
2111cf48f9e2SDavid Matlack 			protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2112c50d8ae3SPaolo Bonzini 
2113c50d8ae3SPaolo Bonzini 		if (protected) {
21145591c069SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2115c50d8ae3SPaolo Bonzini 			flush = false;
2116c50d8ae3SPaolo Bonzini 		}
2117c50d8ae3SPaolo Bonzini 
2118c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2119479a1efcSSean Christopherson 			kvm_unlink_unsync_page(vcpu->kvm, sp);
21208d5678a7SHou Wenlong 			flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2121c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2122c50d8ae3SPaolo Bonzini 		}
2123531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2124c3e5e415SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
212565855ed8SLai Jiangshan 			if (!can_yield) {
212665855ed8SLai Jiangshan 				kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
212765855ed8SLai Jiangshan 				return -EINTR;
212865855ed8SLai Jiangshan 			}
212965855ed8SLai Jiangshan 
2130531810caSBen Gardon 			cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2131c50d8ae3SPaolo Bonzini 			flush = false;
2132c50d8ae3SPaolo Bonzini 		}
2133c50d8ae3SPaolo Bonzini 	}
2134c50d8ae3SPaolo Bonzini 
2135c3e5e415SLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
213665855ed8SLai Jiangshan 	return 0;
2137c50d8ae3SPaolo Bonzini }
2138c50d8ae3SPaolo Bonzini 
2139c50d8ae3SPaolo Bonzini static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2140c50d8ae3SPaolo Bonzini {
2141c50d8ae3SPaolo Bonzini 	atomic_set(&sp->write_flooding_count,  0);
2142c50d8ae3SPaolo Bonzini }
2143c50d8ae3SPaolo Bonzini 
2144c50d8ae3SPaolo Bonzini static void clear_sp_write_flooding_count(u64 *spte)
2145c50d8ae3SPaolo Bonzini {
214657354682SSean Christopherson 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
2147c50d8ae3SPaolo Bonzini }
2148c50d8ae3SPaolo Bonzini 
2149cbd858b1SDavid Matlack /*
2150cbd858b1SDavid Matlack  * The vCPU is required when finding indirect shadow pages; the shadow
2151cbd858b1SDavid Matlack  * page may already exist and syncing it needs the vCPU pointer in
2152cbd858b1SDavid Matlack  * order to read guest page tables.  Direct shadow pages are never
2153cbd858b1SDavid Matlack  * unsync, thus @vcpu can be NULL if @role.direct is true.
2154cbd858b1SDavid Matlack  */
21553cc736b3SDavid Matlack static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
21563cc736b3SDavid Matlack 						     struct kvm_vcpu *vcpu,
215794c81364SDavid Matlack 						     gfn_t gfn,
215894c81364SDavid Matlack 						     struct hlist_head *sp_list,
21592e65e842SDavid Matlack 						     union kvm_mmu_page_role role)
2160c50d8ae3SPaolo Bonzini {
2161c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
21628d5678a7SHou Wenlong 	int ret;
2163c50d8ae3SPaolo Bonzini 	int collisions = 0;
2164c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2165c50d8ae3SPaolo Bonzini 
21663cc736b3SDavid Matlack 	for_each_valid_sp(kvm, sp, sp_list) {
2167c50d8ae3SPaolo Bonzini 		if (sp->gfn != gfn) {
2168c50d8ae3SPaolo Bonzini 			collisions++;
2169c50d8ae3SPaolo Bonzini 			continue;
2170c50d8ae3SPaolo Bonzini 		}
2171c50d8ae3SPaolo Bonzini 
2172ddc16abbSSean Christopherson 		if (sp->role.word != role.word) {
2173ddc16abbSSean Christopherson 			/*
2174ddc16abbSSean Christopherson 			 * If the guest is creating an upper-level page, zap
2175ddc16abbSSean Christopherson 			 * unsync pages for the same gfn.  While it's possible
2176ddc16abbSSean Christopherson 			 * the guest is using recursive page tables, in all
2177ddc16abbSSean Christopherson 			 * likelihood the guest has stopped using the unsync
2178ddc16abbSSean Christopherson 			 * page and is installing a completely unrelated page.
2179ddc16abbSSean Christopherson 			 * Unsync pages must not be left as is, because the new
2180ddc16abbSSean Christopherson 			 * upper-level page will be write-protected.
2181ddc16abbSSean Christopherson 			 */
21822e65e842SDavid Matlack 			if (role.level > PG_LEVEL_4K && sp->unsync)
21833cc736b3SDavid Matlack 				kvm_mmu_prepare_zap_page(kvm, sp,
2184ddc16abbSSean Christopherson 							 &invalid_list);
2185c50d8ae3SPaolo Bonzini 			continue;
2186ddc16abbSSean Christopherson 		}
2187c50d8ae3SPaolo Bonzini 
2188bb924ca6SDavid Matlack 		/* unsync and write-flooding only apply to indirect SPs. */
2189bb924ca6SDavid Matlack 		if (sp->role.direct)
219094c81364SDavid Matlack 			goto out;
2191fb58a9c3SSean Christopherson 
2192c50d8ae3SPaolo Bonzini 		if (sp->unsync) {
2193cbd858b1SDavid Matlack 			if (KVM_BUG_ON(!vcpu, kvm))
2194cbd858b1SDavid Matlack 				break;
2195cbd858b1SDavid Matlack 
219607dc4f35SSean Christopherson 			/*
2197479a1efcSSean Christopherson 			 * The page is good, but is stale.  kvm_sync_page does
219807dc4f35SSean Christopherson 			 * get the latest guest state, but (unlike mmu_unsync_children)
219907dc4f35SSean Christopherson 			 * it doesn't write-protect the page or mark it synchronized!
220007dc4f35SSean Christopherson 			 * This way the validity of the mapping is ensured, but the
220107dc4f35SSean Christopherson 			 * overhead of write protection is not incurred until the
220207dc4f35SSean Christopherson 			 * guest invalidates the TLB mapping.  This allows multiple
220307dc4f35SSean Christopherson 			 * SPs for a single gfn to be unsync.
220407dc4f35SSean Christopherson 			 *
220507dc4f35SSean Christopherson 			 * If the sync fails, the page is zapped.  If so, break
220607dc4f35SSean Christopherson 			 * in order to rebuild it.
2207c50d8ae3SPaolo Bonzini 			 */
22088d5678a7SHou Wenlong 			ret = kvm_sync_page(vcpu, sp, &invalid_list);
22098d5678a7SHou Wenlong 			if (ret < 0)
2210c50d8ae3SPaolo Bonzini 				break;
2211c50d8ae3SPaolo Bonzini 
221220ba462dSSean Christopherson 			WARN_ON_ONCE(!list_empty(&invalid_list));
22138d5678a7SHou Wenlong 			if (ret > 0)
22143cc736b3SDavid Matlack 				kvm_flush_remote_tlbs(kvm);
2215c50d8ae3SPaolo Bonzini 		}
2216c50d8ae3SPaolo Bonzini 
2217c50d8ae3SPaolo Bonzini 		__clear_sp_write_flooding_count(sp);
2218fb58a9c3SSean Christopherson 
2219c50d8ae3SPaolo Bonzini 		goto out;
2220c50d8ae3SPaolo Bonzini 	}
2221c50d8ae3SPaolo Bonzini 
222294c81364SDavid Matlack 	sp = NULL;
22233cc736b3SDavid Matlack 	++kvm->stat.mmu_cache_miss;
2224c50d8ae3SPaolo Bonzini 
222594c81364SDavid Matlack out:
22263cc736b3SDavid Matlack 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
222794c81364SDavid Matlack 
22283cc736b3SDavid Matlack 	if (collisions > kvm->stat.max_mmu_page_hash_collisions)
22293cc736b3SDavid Matlack 		kvm->stat.max_mmu_page_hash_collisions = collisions;
223094c81364SDavid Matlack 	return sp;
223194c81364SDavid Matlack }
223294c81364SDavid Matlack 
22332f8b1b53SDavid Matlack /* Caches used when allocating a new shadow page. */
22342f8b1b53SDavid Matlack struct shadow_page_caches {
22352f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *page_header_cache;
22362f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *shadow_page_cache;
22376a97575dSDavid Matlack 	struct kvm_mmu_memory_cache *shadowed_info_cache;
22382f8b1b53SDavid Matlack };
22392f8b1b53SDavid Matlack 
2240336081fbSDavid Matlack static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
22412f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
224294c81364SDavid Matlack 						      gfn_t gfn,
224394c81364SDavid Matlack 						      struct hlist_head *sp_list,
224494c81364SDavid Matlack 						      union kvm_mmu_page_role role)
224594c81364SDavid Matlack {
2246c306aec8SDavid Matlack 	struct kvm_mmu_page *sp;
2247c306aec8SDavid Matlack 
22482f8b1b53SDavid Matlack 	sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
22492f8b1b53SDavid Matlack 	sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
2250c306aec8SDavid Matlack 	if (!role.direct)
22516a97575dSDavid Matlack 		sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2252c306aec8SDavid Matlack 
2253c306aec8SDavid Matlack 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2254c306aec8SDavid Matlack 
225555c510e2SSean Christopherson 	INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2256428e9216SSean Christopherson 
2257c306aec8SDavid Matlack 	/*
2258c306aec8SDavid Matlack 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2259c306aec8SDavid Matlack 	 * depends on valid pages being added to the head of the list.  See
2260c306aec8SDavid Matlack 	 * comments in kvm_zap_obsolete_pages().
2261c306aec8SDavid Matlack 	 */
2262336081fbSDavid Matlack 	sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2263336081fbSDavid Matlack 	list_add(&sp->link, &kvm->arch.active_mmu_pages);
226443a063caSYosry Ahmed 	kvm_account_mmu_page(kvm, sp);
2265c50d8ae3SPaolo Bonzini 
2266c50d8ae3SPaolo Bonzini 	sp->gfn = gfn;
2267c50d8ae3SPaolo Bonzini 	sp->role = role;
2268ac101b7cSSean Christopherson 	hlist_add_head(&sp->hash_link, sp_list);
2269be911771SDavid Matlack 	if (sp_has_gptes(sp))
2270336081fbSDavid Matlack 		account_shadowed(kvm, sp);
2271ddc16abbSSean Christopherson 
227294c81364SDavid Matlack 	return sp;
227394c81364SDavid Matlack }
227494c81364SDavid Matlack 
2275cbd858b1SDavid Matlack /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
22763cc736b3SDavid Matlack static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
22773cc736b3SDavid Matlack 						      struct kvm_vcpu *vcpu,
22782f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
227987654643SDavid Matlack 						      gfn_t gfn,
228094c81364SDavid Matlack 						      union kvm_mmu_page_role role)
228194c81364SDavid Matlack {
228294c81364SDavid Matlack 	struct hlist_head *sp_list;
228394c81364SDavid Matlack 	struct kvm_mmu_page *sp;
228494c81364SDavid Matlack 	bool created = false;
228594c81364SDavid Matlack 
22863cc736b3SDavid Matlack 	sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
228794c81364SDavid Matlack 
22883cc736b3SDavid Matlack 	sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
228994c81364SDavid Matlack 	if (!sp) {
229094c81364SDavid Matlack 		created = true;
22913cc736b3SDavid Matlack 		sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
229294c81364SDavid Matlack 	}
229394c81364SDavid Matlack 
229494c81364SDavid Matlack 	trace_kvm_mmu_get_page(sp, created);
2295c50d8ae3SPaolo Bonzini 	return sp;
2296c50d8ae3SPaolo Bonzini }
2297c50d8ae3SPaolo Bonzini 
22982f8b1b53SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
22992f8b1b53SDavid Matlack 						    gfn_t gfn,
23002f8b1b53SDavid Matlack 						    union kvm_mmu_page_role role)
23012f8b1b53SDavid Matlack {
23022f8b1b53SDavid Matlack 	struct shadow_page_caches caches = {
23032f8b1b53SDavid Matlack 		.page_header_cache = &vcpu->arch.mmu_page_header_cache,
23042f8b1b53SDavid Matlack 		.shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
23056a97575dSDavid Matlack 		.shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
23062f8b1b53SDavid Matlack 	};
23072f8b1b53SDavid Matlack 
23083cc736b3SDavid Matlack 	return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
23092f8b1b53SDavid Matlack }
23102f8b1b53SDavid Matlack 
231139944ab9SSean Christopherson static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
231239944ab9SSean Christopherson 						  unsigned int access)
23132e65e842SDavid Matlack {
23142e65e842SDavid Matlack 	struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
23152e65e842SDavid Matlack 	union kvm_mmu_page_role role;
23162e65e842SDavid Matlack 
23172e65e842SDavid Matlack 	role = parent_sp->role;
23182e65e842SDavid Matlack 	role.level--;
23192e65e842SDavid Matlack 	role.access = access;
23202e65e842SDavid Matlack 	role.direct = direct;
23212e65e842SDavid Matlack 	role.passthrough = 0;
23222e65e842SDavid Matlack 
23232e65e842SDavid Matlack 	/*
23242e65e842SDavid Matlack 	 * If the guest has 4-byte PTEs then that means it's using 32-bit,
23252e65e842SDavid Matlack 	 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
23262e65e842SDavid Matlack 	 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
23272e65e842SDavid Matlack 	 * shadow each guest page table with multiple shadow page tables, which
23282e65e842SDavid Matlack 	 * requires extra bookkeeping in the role.
23292e65e842SDavid Matlack 	 *
23302e65e842SDavid Matlack 	 * Specifically, to shadow the guest's page directory (which covers a
23312e65e842SDavid Matlack 	 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
23322e65e842SDavid Matlack 	 * 1GiB of the address space. @role.quadrant encodes which quarter of
23332e65e842SDavid Matlack 	 * the address space each maps.
23342e65e842SDavid Matlack 	 *
23352e65e842SDavid Matlack 	 * To shadow the guest's page tables (which each map a 4MiB region), KVM
23362e65e842SDavid Matlack 	 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
23372e65e842SDavid Matlack 	 * @role.quadrant encodes which half of the region they map.
23382e65e842SDavid Matlack 	 *
233939944ab9SSean Christopherson 	 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
234039944ab9SSean Christopherson 	 * consumes bits 29:21.  To consume bits 31:30, KVM's uses 4 shadow
234139944ab9SSean Christopherson 	 * PDPTEs; those 4 PAE page directories are pre-allocated and their
234239944ab9SSean Christopherson 	 * quadrant is assigned in mmu_alloc_root().   A 4-byte PTE consumes
234339944ab9SSean Christopherson 	 * bits 21:12, while an 8-byte PTE consumes bits 20:12.  To consume
234439944ab9SSean Christopherson 	 * bit 21 in the PTE (the child here), KVM propagates that bit to the
234539944ab9SSean Christopherson 	 * quadrant, i.e. sets quadrant to '0' or '1'.  The parent 8-byte PDE
234639944ab9SSean Christopherson 	 * covers bit 21 (see above), thus the quadrant is calculated from the
234739944ab9SSean Christopherson 	 * _least_ significant bit of the PDE index.
23482e65e842SDavid Matlack 	 */
23492e65e842SDavid Matlack 	if (role.has_4_byte_gpte) {
23502e65e842SDavid Matlack 		WARN_ON_ONCE(role.level != PG_LEVEL_4K);
235179e48cecSSean Christopherson 		role.quadrant = spte_index(sptep) & 1;
23522e65e842SDavid Matlack 	}
23532e65e842SDavid Matlack 
23542e65e842SDavid Matlack 	return role;
23552e65e842SDavid Matlack }
23562e65e842SDavid Matlack 
23572e65e842SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
23582e65e842SDavid Matlack 						 u64 *sptep, gfn_t gfn,
23592e65e842SDavid Matlack 						 bool direct, unsigned int access)
23602e65e842SDavid Matlack {
23612e65e842SDavid Matlack 	union kvm_mmu_page_role role;
23622e65e842SDavid Matlack 
23630cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
23640cd8dc73SPaolo Bonzini 		return ERR_PTR(-EEXIST);
23650cd8dc73SPaolo Bonzini 
23662e65e842SDavid Matlack 	role = kvm_mmu_child_role(sptep, direct, access);
236787654643SDavid Matlack 	return kvm_mmu_get_shadow_page(vcpu, gfn, role);
23682e65e842SDavid Matlack }
23692e65e842SDavid Matlack 
2370c50d8ae3SPaolo Bonzini static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2371c50d8ae3SPaolo Bonzini 					struct kvm_vcpu *vcpu, hpa_t root,
2372c50d8ae3SPaolo Bonzini 					u64 addr)
2373c50d8ae3SPaolo Bonzini {
2374c50d8ae3SPaolo Bonzini 	iterator->addr = addr;
2375c50d8ae3SPaolo Bonzini 	iterator->shadow_addr = root;
2376a972e29cSPaolo Bonzini 	iterator->level = vcpu->arch.mmu->root_role.level;
2377c50d8ae3SPaolo Bonzini 
237812ec33a7SLai Jiangshan 	if (iterator->level >= PT64_ROOT_4LEVEL &&
23794d25502aSPaolo Bonzini 	    vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2380347a0d0dSPaolo Bonzini 	    !vcpu->arch.mmu->root_role.direct)
238112ec33a7SLai Jiangshan 		iterator->level = PT32E_ROOT_LEVEL;
2382c50d8ae3SPaolo Bonzini 
2383c50d8ae3SPaolo Bonzini 	if (iterator->level == PT32E_ROOT_LEVEL) {
2384c50d8ae3SPaolo Bonzini 		/*
2385c50d8ae3SPaolo Bonzini 		 * prev_root is currently only used for 64-bit hosts. So only
2386c50d8ae3SPaolo Bonzini 		 * the active root_hpa is valid here.
2387c50d8ae3SPaolo Bonzini 		 */
2388b9e5603cSPaolo Bonzini 		BUG_ON(root != vcpu->arch.mmu->root.hpa);
2389c50d8ae3SPaolo Bonzini 
2390c50d8ae3SPaolo Bonzini 		iterator->shadow_addr
2391c50d8ae3SPaolo Bonzini 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
23922ca3129eSSean Christopherson 		iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2393c50d8ae3SPaolo Bonzini 		--iterator->level;
2394c50d8ae3SPaolo Bonzini 		if (!iterator->shadow_addr)
2395c50d8ae3SPaolo Bonzini 			iterator->level = 0;
2396c50d8ae3SPaolo Bonzini 	}
2397c50d8ae3SPaolo Bonzini }
2398c50d8ae3SPaolo Bonzini 
2399c50d8ae3SPaolo Bonzini static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2400c50d8ae3SPaolo Bonzini 			     struct kvm_vcpu *vcpu, u64 addr)
2401c50d8ae3SPaolo Bonzini {
2402b9e5603cSPaolo Bonzini 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2403c50d8ae3SPaolo Bonzini 				    addr);
2404c50d8ae3SPaolo Bonzini }
2405c50d8ae3SPaolo Bonzini 
2406c50d8ae3SPaolo Bonzini static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2407c50d8ae3SPaolo Bonzini {
24083bae0459SSean Christopherson 	if (iterator->level < PG_LEVEL_4K)
2409c50d8ae3SPaolo Bonzini 		return false;
2410c50d8ae3SPaolo Bonzini 
24112ca3129eSSean Christopherson 	iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2412c50d8ae3SPaolo Bonzini 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2413c50d8ae3SPaolo Bonzini 	return true;
2414c50d8ae3SPaolo Bonzini }
2415c50d8ae3SPaolo Bonzini 
2416c50d8ae3SPaolo Bonzini static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2417c50d8ae3SPaolo Bonzini 			       u64 spte)
2418c50d8ae3SPaolo Bonzini {
24193e44dce4SLai Jiangshan 	if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2420c50d8ae3SPaolo Bonzini 		iterator->level = 0;
2421c50d8ae3SPaolo Bonzini 		return;
2422c50d8ae3SPaolo Bonzini 	}
2423c50d8ae3SPaolo Bonzini 
24242ca3129eSSean Christopherson 	iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2425c50d8ae3SPaolo Bonzini 	--iterator->level;
2426c50d8ae3SPaolo Bonzini }
2427c50d8ae3SPaolo Bonzini 
2428c50d8ae3SPaolo Bonzini static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2429c50d8ae3SPaolo Bonzini {
2430c50d8ae3SPaolo Bonzini 	__shadow_walk_next(iterator, *iterator->sptep);
2431c50d8ae3SPaolo Bonzini }
2432c50d8ae3SPaolo Bonzini 
24330cd8dc73SPaolo Bonzini static void __link_shadow_page(struct kvm *kvm,
24340cd8dc73SPaolo Bonzini 			       struct kvm_mmu_memory_cache *cache, u64 *sptep,
243503787394SPaolo Bonzini 			       struct kvm_mmu_page *sp, bool flush)
2436c50d8ae3SPaolo Bonzini {
2437c50d8ae3SPaolo Bonzini 	u64 spte;
2438c50d8ae3SPaolo Bonzini 
2439c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2440c50d8ae3SPaolo Bonzini 
24410cd8dc73SPaolo Bonzini 	/*
24420cd8dc73SPaolo Bonzini 	 * If an SPTE is present already, it must be a leaf and therefore
244303787394SPaolo Bonzini 	 * a large one.  Drop it, and flush the TLB if needed, before
244403787394SPaolo Bonzini 	 * installing sp.
24450cd8dc73SPaolo Bonzini 	 */
24460cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep))
244703787394SPaolo Bonzini 		drop_large_spte(kvm, sptep, flush);
24480cd8dc73SPaolo Bonzini 
2449cc4674d0SBen Gardon 	spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2450c50d8ae3SPaolo Bonzini 
2451c50d8ae3SPaolo Bonzini 	mmu_spte_set(sptep, spte);
2452c50d8ae3SPaolo Bonzini 
24532ff9039aSDavid Matlack 	mmu_page_add_parent_pte(cache, sp, sptep);
2454c50d8ae3SPaolo Bonzini 
2455c4a48868SLai Jiangshan 	/*
2456c4a48868SLai Jiangshan 	 * The non-direct sub-pagetable must be updated before linking.  For
2457c4a48868SLai Jiangshan 	 * L1 sp, the pagetable is updated via kvm_sync_page() in
2458c4a48868SLai Jiangshan 	 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2459c4a48868SLai Jiangshan 	 * so sp->unsync can be true or false.  For higher level non-direct
2460c4a48868SLai Jiangshan 	 * sp, the pagetable is updated/synced via mmu_sync_children() in
2461c4a48868SLai Jiangshan 	 * FNAME(fetch)(), so sp->unsync_children can only be false.
2462c4a48868SLai Jiangshan 	 * WARN_ON_ONCE() if anything happens unexpectedly.
2463c4a48868SLai Jiangshan 	 */
2464c4a48868SLai Jiangshan 	if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2465c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
2466c50d8ae3SPaolo Bonzini }
2467c50d8ae3SPaolo Bonzini 
24682ff9039aSDavid Matlack static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
24692ff9039aSDavid Matlack 			     struct kvm_mmu_page *sp)
24702ff9039aSDavid Matlack {
247103787394SPaolo Bonzini 	__link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
24722ff9039aSDavid Matlack }
24732ff9039aSDavid Matlack 
2474c50d8ae3SPaolo Bonzini static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2475c50d8ae3SPaolo Bonzini 				   unsigned direct_access)
2476c50d8ae3SPaolo Bonzini {
2477c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2478c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
2479c50d8ae3SPaolo Bonzini 
2480c50d8ae3SPaolo Bonzini 		/*
2481c50d8ae3SPaolo Bonzini 		 * For the direct sp, if the guest pte's dirty bit
2482c50d8ae3SPaolo Bonzini 		 * changed form clean to dirty, it will corrupt the
2483c50d8ae3SPaolo Bonzini 		 * sp's access: allow writable in the read-only sp,
2484c50d8ae3SPaolo Bonzini 		 * so we should update the spte at this point to get
2485c50d8ae3SPaolo Bonzini 		 * a new sp with the correct access.
2486c50d8ae3SPaolo Bonzini 		 */
24875e3edd7eSSean Christopherson 		child = spte_to_child_sp(*sptep);
2488c50d8ae3SPaolo Bonzini 		if (child->role.access == direct_access)
2489c50d8ae3SPaolo Bonzini 			return;
2490c50d8ae3SPaolo Bonzini 
2491069f30c6SMingwei Zhang 		drop_parent_pte(vcpu->kvm, child, sptep);
24923cdf9374SHou Wenlong 		kvm_flush_remote_tlbs_sptep(vcpu->kvm, sptep);
2493c50d8ae3SPaolo Bonzini 	}
2494c50d8ae3SPaolo Bonzini }
2495c50d8ae3SPaolo Bonzini 
24962de4085cSBen Gardon /* Returns the number of zapped non-leaf child shadow pages. */
24972de4085cSBen Gardon static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
24982de4085cSBen Gardon 			    u64 *spte, struct list_head *invalid_list)
2499c50d8ae3SPaolo Bonzini {
2500c50d8ae3SPaolo Bonzini 	u64 pte;
2501c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *child;
2502c50d8ae3SPaolo Bonzini 
2503c50d8ae3SPaolo Bonzini 	pte = *spte;
2504c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(pte)) {
2505c50d8ae3SPaolo Bonzini 		if (is_last_spte(pte, sp->role.level)) {
2506c50d8ae3SPaolo Bonzini 			drop_spte(kvm, spte);
2507c50d8ae3SPaolo Bonzini 		} else {
25085e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2509069f30c6SMingwei Zhang 			drop_parent_pte(kvm, child, spte);
25102de4085cSBen Gardon 
25112de4085cSBen Gardon 			/*
25122de4085cSBen Gardon 			 * Recursively zap nested TDP SPs, parentless SPs are
25132de4085cSBen Gardon 			 * unlikely to be used again in the near future.  This
25142de4085cSBen Gardon 			 * avoids retaining a large number of stale nested SPs.
25152de4085cSBen Gardon 			 */
25162de4085cSBen Gardon 			if (tdp_enabled && invalid_list &&
25172de4085cSBen Gardon 			    child->role.guest_mode && !child->parent_ptes.val)
25182de4085cSBen Gardon 				return kvm_mmu_prepare_zap_page(kvm, child,
25192de4085cSBen Gardon 								invalid_list);
2520c50d8ae3SPaolo Bonzini 		}
2521ace569e0SSean Christopherson 	} else if (is_mmio_spte(pte)) {
2522c50d8ae3SPaolo Bonzini 		mmu_spte_clear_no_track(spte);
2523ace569e0SSean Christopherson 	}
25242de4085cSBen Gardon 	return 0;
2525c50d8ae3SPaolo Bonzini }
2526c50d8ae3SPaolo Bonzini 
25272de4085cSBen Gardon static int kvm_mmu_page_unlink_children(struct kvm *kvm,
25282de4085cSBen Gardon 					struct kvm_mmu_page *sp,
25292de4085cSBen Gardon 					struct list_head *invalid_list)
2530c50d8ae3SPaolo Bonzini {
25312de4085cSBen Gardon 	int zapped = 0;
2532c50d8ae3SPaolo Bonzini 	unsigned i;
2533c50d8ae3SPaolo Bonzini 
25342ca3129eSSean Christopherson 	for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
25352de4085cSBen Gardon 		zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
25362de4085cSBen Gardon 
25372de4085cSBen Gardon 	return zapped;
2538c50d8ae3SPaolo Bonzini }
2539c50d8ae3SPaolo Bonzini 
2540069f30c6SMingwei Zhang static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2541c50d8ae3SPaolo Bonzini {
2542c50d8ae3SPaolo Bonzini 	u64 *sptep;
2543c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
2544c50d8ae3SPaolo Bonzini 
2545c50d8ae3SPaolo Bonzini 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2546069f30c6SMingwei Zhang 		drop_parent_pte(kvm, sp, sptep);
2547c50d8ae3SPaolo Bonzini }
2548c50d8ae3SPaolo Bonzini 
2549c50d8ae3SPaolo Bonzini static int mmu_zap_unsync_children(struct kvm *kvm,
2550c50d8ae3SPaolo Bonzini 				   struct kvm_mmu_page *parent,
2551c50d8ae3SPaolo Bonzini 				   struct list_head *invalid_list)
2552c50d8ae3SPaolo Bonzini {
2553c50d8ae3SPaolo Bonzini 	int i, zapped = 0;
2554c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2555c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2556c50d8ae3SPaolo Bonzini 
25573bae0459SSean Christopherson 	if (parent->role.level == PG_LEVEL_4K)
2558c50d8ae3SPaolo Bonzini 		return 0;
2559c50d8ae3SPaolo Bonzini 
2560c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2561c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
2562c50d8ae3SPaolo Bonzini 
2563c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2564c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2565c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2566c50d8ae3SPaolo Bonzini 			zapped++;
2567c50d8ae3SPaolo Bonzini 		}
2568c50d8ae3SPaolo Bonzini 	}
2569c50d8ae3SPaolo Bonzini 
2570c50d8ae3SPaolo Bonzini 	return zapped;
2571c50d8ae3SPaolo Bonzini }
2572c50d8ae3SPaolo Bonzini 
2573c50d8ae3SPaolo Bonzini static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2574c50d8ae3SPaolo Bonzini 				       struct kvm_mmu_page *sp,
2575c50d8ae3SPaolo Bonzini 				       struct list_head *invalid_list,
2576c50d8ae3SPaolo Bonzini 				       int *nr_zapped)
2577c50d8ae3SPaolo Bonzini {
2578527d5cd7SSean Christopherson 	bool list_unstable, zapped_root = false;
2579c50d8ae3SPaolo Bonzini 
258047b0c2e4SKazuki Takiguchi 	lockdep_assert_held_write(&kvm->mmu_lock);
2581c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_prepare_zap_page(sp);
2582c50d8ae3SPaolo Bonzini 	++kvm->stat.mmu_shadow_zapped;
2583c50d8ae3SPaolo Bonzini 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
25842de4085cSBen Gardon 	*nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2585069f30c6SMingwei Zhang 	kvm_mmu_unlink_parents(kvm, sp);
2586c50d8ae3SPaolo Bonzini 
2587c50d8ae3SPaolo Bonzini 	/* Zapping children means active_mmu_pages has become unstable. */
2588c50d8ae3SPaolo Bonzini 	list_unstable = *nr_zapped;
2589c50d8ae3SPaolo Bonzini 
2590767d8d8dSLai Jiangshan 	if (!sp->role.invalid && sp_has_gptes(sp))
2591c50d8ae3SPaolo Bonzini 		unaccount_shadowed(kvm, sp);
2592c50d8ae3SPaolo Bonzini 
2593c50d8ae3SPaolo Bonzini 	if (sp->unsync)
2594c50d8ae3SPaolo Bonzini 		kvm_unlink_unsync_page(kvm, sp);
2595c50d8ae3SPaolo Bonzini 	if (!sp->root_count) {
2596c50d8ae3SPaolo Bonzini 		/* Count self */
2597c50d8ae3SPaolo Bonzini 		(*nr_zapped)++;
2598f95eec9bSSean Christopherson 
2599f95eec9bSSean Christopherson 		/*
2600f95eec9bSSean Christopherson 		 * Already invalid pages (previously active roots) are not on
2601f95eec9bSSean Christopherson 		 * the active page list.  See list_del() in the "else" case of
2602f95eec9bSSean Christopherson 		 * !sp->root_count.
2603f95eec9bSSean Christopherson 		 */
2604f95eec9bSSean Christopherson 		if (sp->role.invalid)
2605f95eec9bSSean Christopherson 			list_add(&sp->link, invalid_list);
2606f95eec9bSSean Christopherson 		else
2607c50d8ae3SPaolo Bonzini 			list_move(&sp->link, invalid_list);
260843a063caSYosry Ahmed 		kvm_unaccount_mmu_page(kvm, sp);
2609c50d8ae3SPaolo Bonzini 	} else {
2610f95eec9bSSean Christopherson 		/*
2611f95eec9bSSean Christopherson 		 * Remove the active root from the active page list, the root
2612f95eec9bSSean Christopherson 		 * will be explicitly freed when the root_count hits zero.
2613f95eec9bSSean Christopherson 		 */
2614f95eec9bSSean Christopherson 		list_del(&sp->link);
2615c50d8ae3SPaolo Bonzini 
2616c50d8ae3SPaolo Bonzini 		/*
2617c50d8ae3SPaolo Bonzini 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2618c50d8ae3SPaolo Bonzini 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2619c50d8ae3SPaolo Bonzini 		 * treats invalid shadow pages as being obsolete.
2620c50d8ae3SPaolo Bonzini 		 */
2621527d5cd7SSean Christopherson 		zapped_root = !is_obsolete_sp(kvm, sp);
2622c50d8ae3SPaolo Bonzini 	}
2623c50d8ae3SPaolo Bonzini 
262455c510e2SSean Christopherson 	if (sp->nx_huge_page_disallowed)
262555c510e2SSean Christopherson 		unaccount_nx_huge_page(kvm, sp);
2626c50d8ae3SPaolo Bonzini 
2627c50d8ae3SPaolo Bonzini 	sp->role.invalid = 1;
2628527d5cd7SSean Christopherson 
2629527d5cd7SSean Christopherson 	/*
2630527d5cd7SSean Christopherson 	 * Make the request to free obsolete roots after marking the root
2631527d5cd7SSean Christopherson 	 * invalid, otherwise other vCPUs may not see it as invalid.
2632527d5cd7SSean Christopherson 	 */
2633527d5cd7SSean Christopherson 	if (zapped_root)
2634527d5cd7SSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2635c50d8ae3SPaolo Bonzini 	return list_unstable;
2636c50d8ae3SPaolo Bonzini }
2637c50d8ae3SPaolo Bonzini 
2638c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2639c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list)
2640c50d8ae3SPaolo Bonzini {
2641c50d8ae3SPaolo Bonzini 	int nr_zapped;
2642c50d8ae3SPaolo Bonzini 
2643c50d8ae3SPaolo Bonzini 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2644c50d8ae3SPaolo Bonzini 	return nr_zapped;
2645c50d8ae3SPaolo Bonzini }
2646c50d8ae3SPaolo Bonzini 
2647c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2648c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list)
2649c50d8ae3SPaolo Bonzini {
2650c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *nsp;
2651c50d8ae3SPaolo Bonzini 
2652c50d8ae3SPaolo Bonzini 	if (list_empty(invalid_list))
2653c50d8ae3SPaolo Bonzini 		return;
2654c50d8ae3SPaolo Bonzini 
2655c50d8ae3SPaolo Bonzini 	/*
2656c50d8ae3SPaolo Bonzini 	 * We need to make sure everyone sees our modifications to
2657c50d8ae3SPaolo Bonzini 	 * the page tables and see changes to vcpu->mode here. The barrier
2658c50d8ae3SPaolo Bonzini 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2659c50d8ae3SPaolo Bonzini 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2660c50d8ae3SPaolo Bonzini 	 *
2661c50d8ae3SPaolo Bonzini 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2662c50d8ae3SPaolo Bonzini 	 * guest mode and/or lockless shadow page table walks.
2663c50d8ae3SPaolo Bonzini 	 */
2664c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs(kvm);
2665c50d8ae3SPaolo Bonzini 
2666c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
266720ba462dSSean Christopherson 		WARN_ON_ONCE(!sp->role.invalid || sp->root_count);
266887654643SDavid Matlack 		kvm_mmu_free_shadow_page(sp);
2669c50d8ae3SPaolo Bonzini 	}
2670c50d8ae3SPaolo Bonzini }
2671c50d8ae3SPaolo Bonzini 
26726b82ef2cSSean Christopherson static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
26736b82ef2cSSean Christopherson 						  unsigned long nr_to_zap)
2674c50d8ae3SPaolo Bonzini {
26756b82ef2cSSean Christopherson 	unsigned long total_zapped = 0;
26766b82ef2cSSean Christopherson 	struct kvm_mmu_page *sp, *tmp;
2677ba7888ddSSean Christopherson 	LIST_HEAD(invalid_list);
26786b82ef2cSSean Christopherson 	bool unstable;
26796b82ef2cSSean Christopherson 	int nr_zapped;
2680c50d8ae3SPaolo Bonzini 
2681c50d8ae3SPaolo Bonzini 	if (list_empty(&kvm->arch.active_mmu_pages))
2682ba7888ddSSean Christopherson 		return 0;
2683c50d8ae3SPaolo Bonzini 
26846b82ef2cSSean Christopherson restart:
26858fc51726SSean Christopherson 	list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
26866b82ef2cSSean Christopherson 		/*
26876b82ef2cSSean Christopherson 		 * Don't zap active root pages, the page itself can't be freed
26886b82ef2cSSean Christopherson 		 * and zapping it will just force vCPUs to realloc and reload.
26896b82ef2cSSean Christopherson 		 */
26906b82ef2cSSean Christopherson 		if (sp->root_count)
26916b82ef2cSSean Christopherson 			continue;
26926b82ef2cSSean Christopherson 
26936b82ef2cSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
26946b82ef2cSSean Christopherson 						      &nr_zapped);
26956b82ef2cSSean Christopherson 		total_zapped += nr_zapped;
26966b82ef2cSSean Christopherson 		if (total_zapped >= nr_to_zap)
2697ba7888ddSSean Christopherson 			break;
2698ba7888ddSSean Christopherson 
26996b82ef2cSSean Christopherson 		if (unstable)
27006b82ef2cSSean Christopherson 			goto restart;
2701ba7888ddSSean Christopherson 	}
27026b82ef2cSSean Christopherson 
27036b82ef2cSSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
27046b82ef2cSSean Christopherson 
27056b82ef2cSSean Christopherson 	kvm->stat.mmu_recycled += total_zapped;
27066b82ef2cSSean Christopherson 	return total_zapped;
27076b82ef2cSSean Christopherson }
27086b82ef2cSSean Christopherson 
2709afe8d7e6SSean Christopherson static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2710afe8d7e6SSean Christopherson {
2711afe8d7e6SSean Christopherson 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2712afe8d7e6SSean Christopherson 		return kvm->arch.n_max_mmu_pages -
2713afe8d7e6SSean Christopherson 			kvm->arch.n_used_mmu_pages;
2714afe8d7e6SSean Christopherson 
2715afe8d7e6SSean Christopherson 	return 0;
2716c50d8ae3SPaolo Bonzini }
2717c50d8ae3SPaolo Bonzini 
2718ba7888ddSSean Christopherson static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2719ba7888ddSSean Christopherson {
27206b82ef2cSSean Christopherson 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2721ba7888ddSSean Christopherson 
27226b82ef2cSSean Christopherson 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2723ba7888ddSSean Christopherson 		return 0;
2724ba7888ddSSean Christopherson 
27256b82ef2cSSean Christopherson 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2726ba7888ddSSean Christopherson 
27276e6ec584SSean Christopherson 	/*
27286e6ec584SSean Christopherson 	 * Note, this check is intentionally soft, it only guarantees that one
27296e6ec584SSean Christopherson 	 * page is available, while the caller may end up allocating as many as
27306e6ec584SSean Christopherson 	 * four pages, e.g. for PAE roots or for 5-level paging.  Temporarily
27316e6ec584SSean Christopherson 	 * exceeding the (arbitrary by default) limit will not harm the host,
2732c4342633SIngo Molnar 	 * being too aggressive may unnecessarily kill the guest, and getting an
27336e6ec584SSean Christopherson 	 * exact count is far more trouble than it's worth, especially in the
27346e6ec584SSean Christopherson 	 * page fault paths.
27356e6ec584SSean Christopherson 	 */
2736ba7888ddSSean Christopherson 	if (!kvm_mmu_available_pages(vcpu->kvm))
2737ba7888ddSSean Christopherson 		return -ENOSPC;
2738ba7888ddSSean Christopherson 	return 0;
2739ba7888ddSSean Christopherson }
2740ba7888ddSSean Christopherson 
2741c50d8ae3SPaolo Bonzini /*
2742c50d8ae3SPaolo Bonzini  * Changing the number of mmu pages allocated to the vm
2743c50d8ae3SPaolo Bonzini  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2744c50d8ae3SPaolo Bonzini  */
2745c50d8ae3SPaolo Bonzini void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2746c50d8ae3SPaolo Bonzini {
2747531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2748c50d8ae3SPaolo Bonzini 
2749c50d8ae3SPaolo Bonzini 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
27506b82ef2cSSean Christopherson 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
27516b82ef2cSSean Christopherson 						  goal_nr_mmu_pages);
2752c50d8ae3SPaolo Bonzini 
2753c50d8ae3SPaolo Bonzini 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2754c50d8ae3SPaolo Bonzini 	}
2755c50d8ae3SPaolo Bonzini 
2756c50d8ae3SPaolo Bonzini 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2757c50d8ae3SPaolo Bonzini 
2758531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2759c50d8ae3SPaolo Bonzini }
2760c50d8ae3SPaolo Bonzini 
2761c50d8ae3SPaolo Bonzini int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2762c50d8ae3SPaolo Bonzini {
2763c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2764c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2765c50d8ae3SPaolo Bonzini 	int r;
2766c50d8ae3SPaolo Bonzini 
2767c50d8ae3SPaolo Bonzini 	r = 0;
2768531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2769767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2770c50d8ae3SPaolo Bonzini 		r = 1;
2771c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2772c50d8ae3SPaolo Bonzini 	}
2773c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2774531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2775c50d8ae3SPaolo Bonzini 
2776c50d8ae3SPaolo Bonzini 	return r;
2777c50d8ae3SPaolo Bonzini }
277896ad91aeSSean Christopherson 
277996ad91aeSSean Christopherson static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
278096ad91aeSSean Christopherson {
278196ad91aeSSean Christopherson 	gpa_t gpa;
278296ad91aeSSean Christopherson 	int r;
278396ad91aeSSean Christopherson 
2784347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
278596ad91aeSSean Christopherson 		return 0;
278696ad91aeSSean Christopherson 
278796ad91aeSSean Christopherson 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
278896ad91aeSSean Christopherson 
278996ad91aeSSean Christopherson 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
279096ad91aeSSean Christopherson 
279196ad91aeSSean Christopherson 	return r;
279296ad91aeSSean Christopherson }
2793c50d8ae3SPaolo Bonzini 
27944d78d0b3SBen Gardon static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2795c50d8ae3SPaolo Bonzini {
2796c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_unsync_page(sp);
27974d78d0b3SBen Gardon 	++kvm->stat.mmu_unsync;
2798c50d8ae3SPaolo Bonzini 	sp->unsync = 1;
2799c50d8ae3SPaolo Bonzini 
2800c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
2801c50d8ae3SPaolo Bonzini }
2802c50d8ae3SPaolo Bonzini 
28030337f585SSean Christopherson /*
28040337f585SSean Christopherson  * Attempt to unsync any shadow pages that can be reached by the specified gfn,
28050337f585SSean Christopherson  * KVM is creating a writable mapping for said gfn.  Returns 0 if all pages
28060337f585SSean Christopherson  * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
28070337f585SSean Christopherson  * be write-protected.
28080337f585SSean Christopherson  */
28098283e36aSBen Gardon int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
28102839180cSPaolo Bonzini 			    gfn_t gfn, bool can_unsync, bool prefetch)
2811c50d8ae3SPaolo Bonzini {
2812c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2813ce25681dSSean Christopherson 	bool locked = false;
2814c50d8ae3SPaolo Bonzini 
28150337f585SSean Christopherson 	/*
28160337f585SSean Christopherson 	 * Force write-protection if the page is being tracked.  Note, the page
28170337f585SSean Christopherson 	 * track machinery is used to write-protect upper-level shadow pages,
28180337f585SSean Christopherson 	 * i.e. this guards the role.level == 4K assertion below!
28190337f585SSean Christopherson 	 */
28207b574863SSean Christopherson 	if (kvm_gfn_is_write_tracked(kvm, slot, gfn))
28210337f585SSean Christopherson 		return -EPERM;
2822c50d8ae3SPaolo Bonzini 
28230337f585SSean Christopherson 	/*
28240337f585SSean Christopherson 	 * The page is not write-tracked, mark existing shadow pages unsync
28250337f585SSean Christopherson 	 * unless KVM is synchronizing an unsync SP (can_unsync = false).  In
28260337f585SSean Christopherson 	 * that case, KVM must complete emulation of the guest TLB flush before
28270337f585SSean Christopherson 	 * allowing shadow pages to become unsync (writable by the guest).
28280337f585SSean Christopherson 	 */
2829767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2830c50d8ae3SPaolo Bonzini 		if (!can_unsync)
28310337f585SSean Christopherson 			return -EPERM;
2832c50d8ae3SPaolo Bonzini 
2833c50d8ae3SPaolo Bonzini 		if (sp->unsync)
2834c50d8ae3SPaolo Bonzini 			continue;
2835c50d8ae3SPaolo Bonzini 
28362839180cSPaolo Bonzini 		if (prefetch)
2837f1c4a88cSLai Jiangshan 			return -EEXIST;
2838f1c4a88cSLai Jiangshan 
2839ce25681dSSean Christopherson 		/*
2840ce25681dSSean Christopherson 		 * TDP MMU page faults require an additional spinlock as they
2841ce25681dSSean Christopherson 		 * run with mmu_lock held for read, not write, and the unsync
2842ce25681dSSean Christopherson 		 * logic is not thread safe.  Take the spinklock regardless of
2843ce25681dSSean Christopherson 		 * the MMU type to avoid extra conditionals/parameters, there's
2844ce25681dSSean Christopherson 		 * no meaningful penalty if mmu_lock is held for write.
2845ce25681dSSean Christopherson 		 */
2846ce25681dSSean Christopherson 		if (!locked) {
2847ce25681dSSean Christopherson 			locked = true;
28484d78d0b3SBen Gardon 			spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2849ce25681dSSean Christopherson 
2850ce25681dSSean Christopherson 			/*
2851ce25681dSSean Christopherson 			 * Recheck after taking the spinlock, a different vCPU
2852ce25681dSSean Christopherson 			 * may have since marked the page unsync.  A false
2853ce25681dSSean Christopherson 			 * positive on the unprotected check above is not
2854ce25681dSSean Christopherson 			 * possible as clearing sp->unsync _must_ hold mmu_lock
2855ce25681dSSean Christopherson 			 * for write, i.e. unsync cannot transition from 0->1
2856ce25681dSSean Christopherson 			 * while this CPU holds mmu_lock for read (or write).
2857ce25681dSSean Christopherson 			 */
2858ce25681dSSean Christopherson 			if (READ_ONCE(sp->unsync))
2859ce25681dSSean Christopherson 				continue;
2860ce25681dSSean Christopherson 		}
2861ce25681dSSean Christopherson 
286220ba462dSSean Christopherson 		WARN_ON_ONCE(sp->role.level != PG_LEVEL_4K);
28634d78d0b3SBen Gardon 		kvm_unsync_page(kvm, sp);
2864c50d8ae3SPaolo Bonzini 	}
2865ce25681dSSean Christopherson 	if (locked)
28664d78d0b3SBen Gardon 		spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2867c50d8ae3SPaolo Bonzini 
2868c50d8ae3SPaolo Bonzini 	/*
2869c50d8ae3SPaolo Bonzini 	 * We need to ensure that the marking of unsync pages is visible
2870c50d8ae3SPaolo Bonzini 	 * before the SPTE is updated to allow writes because
2871c50d8ae3SPaolo Bonzini 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2872c50d8ae3SPaolo Bonzini 	 * the MMU lock and so can race with this. If the SPTE was updated
2873c50d8ae3SPaolo Bonzini 	 * before the page had been marked as unsync-ed, something like the
2874c50d8ae3SPaolo Bonzini 	 * following could happen:
2875c50d8ae3SPaolo Bonzini 	 *
2876c50d8ae3SPaolo Bonzini 	 * CPU 1                    CPU 2
2877c50d8ae3SPaolo Bonzini 	 * ---------------------------------------------------------------------
2878c50d8ae3SPaolo Bonzini 	 * 1.2 Host updates SPTE
2879c50d8ae3SPaolo Bonzini 	 *     to be writable
2880c50d8ae3SPaolo Bonzini 	 *                      2.1 Guest writes a GPTE for GVA X.
2881c50d8ae3SPaolo Bonzini 	 *                          (GPTE being in the guest page table shadowed
2882c50d8ae3SPaolo Bonzini 	 *                           by the SP from CPU 1.)
2883c50d8ae3SPaolo Bonzini 	 *                          This reads SPTE during the page table walk.
2884c50d8ae3SPaolo Bonzini 	 *                          Since SPTE.W is read as 1, there is no
2885c50d8ae3SPaolo Bonzini 	 *                          fault.
2886c50d8ae3SPaolo Bonzini 	 *
2887c50d8ae3SPaolo Bonzini 	 *                      2.2 Guest issues TLB flush.
2888c50d8ae3SPaolo Bonzini 	 *                          That causes a VM Exit.
2889c50d8ae3SPaolo Bonzini 	 *
28900337f585SSean Christopherson 	 *                      2.3 Walking of unsync pages sees sp->unsync is
28910337f585SSean Christopherson 	 *                          false and skips the page.
2892c50d8ae3SPaolo Bonzini 	 *
2893c50d8ae3SPaolo Bonzini 	 *                      2.4 Guest accesses GVA X.
2894c50d8ae3SPaolo Bonzini 	 *                          Since the mapping in the SP was not updated,
2895c50d8ae3SPaolo Bonzini 	 *                          so the old mapping for GVA X incorrectly
2896c50d8ae3SPaolo Bonzini 	 *                          gets used.
2897c50d8ae3SPaolo Bonzini 	 * 1.1 Host marks SP
2898c50d8ae3SPaolo Bonzini 	 *     as unsync
2899c50d8ae3SPaolo Bonzini 	 *     (sp->unsync = true)
2900c50d8ae3SPaolo Bonzini 	 *
2901c50d8ae3SPaolo Bonzini 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2902264d3dc1SLai Jiangshan 	 * the situation in 2.4 does not arise.  It pairs with the read barrier
2903264d3dc1SLai Jiangshan 	 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2904c50d8ae3SPaolo Bonzini 	 */
2905c50d8ae3SPaolo Bonzini 	smp_wmb();
2906c50d8ae3SPaolo Bonzini 
29070337f585SSean Christopherson 	return 0;
2908c50d8ae3SPaolo Bonzini }
2909c50d8ae3SPaolo Bonzini 
29108a9f566aSDavid Matlack static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
29118a9f566aSDavid Matlack 			u64 *sptep, unsigned int pte_access, gfn_t gfn,
2912a12f4381SPaolo Bonzini 			kvm_pfn_t pfn, struct kvm_page_fault *fault)
2913799a4190SBen Gardon {
2914d786c778SPaolo Bonzini 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2915eb5cd7ffSPaolo Bonzini 	int level = sp->role.level;
2916c50d8ae3SPaolo Bonzini 	int was_rmapped = 0;
2917c4371c2aSSean Christopherson 	int ret = RET_PF_FIXED;
2918c50d8ae3SPaolo Bonzini 	bool flush = false;
2919ad67e480SPaolo Bonzini 	bool wrprot;
2920d786c778SPaolo Bonzini 	u64 spte;
2921c50d8ae3SPaolo Bonzini 
2922a12f4381SPaolo Bonzini 	/* Prefetching always gets a writable pfn.  */
2923a12f4381SPaolo Bonzini 	bool host_writable = !fault || fault->map_writable;
29242839180cSPaolo Bonzini 	bool prefetch = !fault || fault->prefetch;
2925a12f4381SPaolo Bonzini 	bool write_fault = fault && fault->write;
2926c50d8ae3SPaolo Bonzini 
2927a54aa15cSSean Christopherson 	if (unlikely(is_noslot_pfn(pfn))) {
29281075d41eSSean Christopherson 		vcpu->stat.pf_mmio_spte_created++;
2929a54aa15cSSean Christopherson 		mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2930a54aa15cSSean Christopherson 		return RET_PF_EMULATE;
2931a54aa15cSSean Christopherson 	}
2932a54aa15cSSean Christopherson 
2933c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep)) {
2934c50d8ae3SPaolo Bonzini 		/*
2935c50d8ae3SPaolo Bonzini 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2936c50d8ae3SPaolo Bonzini 		 * the parent of the now unreachable PTE.
2937c50d8ae3SPaolo Bonzini 		 */
29383bae0459SSean Christopherson 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2939c50d8ae3SPaolo Bonzini 			struct kvm_mmu_page *child;
2940c50d8ae3SPaolo Bonzini 			u64 pte = *sptep;
2941c50d8ae3SPaolo Bonzini 
29425e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2943069f30c6SMingwei Zhang 			drop_parent_pte(vcpu->kvm, child, sptep);
2944c50d8ae3SPaolo Bonzini 			flush = true;
2945c50d8ae3SPaolo Bonzini 		} else if (pfn != spte_to_pfn(*sptep)) {
2946c50d8ae3SPaolo Bonzini 			drop_spte(vcpu->kvm, sptep);
2947c50d8ae3SPaolo Bonzini 			flush = true;
2948c50d8ae3SPaolo Bonzini 		} else
2949c50d8ae3SPaolo Bonzini 			was_rmapped = 1;
2950c50d8ae3SPaolo Bonzini 	}
2951c50d8ae3SPaolo Bonzini 
29522839180cSPaolo Bonzini 	wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
29537158bee4SPaolo Bonzini 			   true, host_writable, &spte);
2954d786c778SPaolo Bonzini 
2955d786c778SPaolo Bonzini 	if (*sptep == spte) {
2956d786c778SPaolo Bonzini 		ret = RET_PF_SPURIOUS;
2957d786c778SPaolo Bonzini 	} else {
2958d786c778SPaolo Bonzini 		flush |= mmu_spte_update(sptep, spte);
29595959ff4aSMaxim Levitsky 		trace_kvm_mmu_set_spte(level, gfn, sptep);
2960c50d8ae3SPaolo Bonzini 	}
2961c50d8ae3SPaolo Bonzini 
2962ad67e480SPaolo Bonzini 	if (wrprot) {
2963c50d8ae3SPaolo Bonzini 		if (write_fault)
2964c50d8ae3SPaolo Bonzini 			ret = RET_PF_EMULATE;
2965c50d8ae3SPaolo Bonzini 	}
2966c50d8ae3SPaolo Bonzini 
2967d786c778SPaolo Bonzini 	if (flush)
29684ad980aeSHou Wenlong 		kvm_flush_remote_tlbs_gfn(vcpu->kvm, gfn, level);
2969c50d8ae3SPaolo Bonzini 
2970c50d8ae3SPaolo Bonzini 	if (!was_rmapped) {
2971d786c778SPaolo Bonzini 		WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
29726a97575dSDavid Matlack 		rmap_add(vcpu, slot, sptep, gfn, pte_access);
29736a97575dSDavid Matlack 	} else {
29746a97575dSDavid Matlack 		/* Already rmapped but the pte_access bits may have changed. */
297579e48cecSSean Christopherson 		kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
2976c50d8ae3SPaolo Bonzini 	}
2977c50d8ae3SPaolo Bonzini 
2978c50d8ae3SPaolo Bonzini 	return ret;
2979c50d8ae3SPaolo Bonzini }
2980c50d8ae3SPaolo Bonzini 
2981c50d8ae3SPaolo Bonzini static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2982c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp,
2983c50d8ae3SPaolo Bonzini 				    u64 *start, u64 *end)
2984c50d8ae3SPaolo Bonzini {
2985c50d8ae3SPaolo Bonzini 	struct page *pages[PTE_PREFETCH_NUM];
2986c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
29870a2b64c5SBen Gardon 	unsigned int access = sp->role.access;
2988c50d8ae3SPaolo Bonzini 	int i, ret;
2989c50d8ae3SPaolo Bonzini 	gfn_t gfn;
2990c50d8ae3SPaolo Bonzini 
299179e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
2992c50d8ae3SPaolo Bonzini 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2993c50d8ae3SPaolo Bonzini 	if (!slot)
2994c50d8ae3SPaolo Bonzini 		return -1;
2995c50d8ae3SPaolo Bonzini 
2996c50d8ae3SPaolo Bonzini 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2997c50d8ae3SPaolo Bonzini 	if (ret <= 0)
2998c50d8ae3SPaolo Bonzini 		return -1;
2999c50d8ae3SPaolo Bonzini 
3000c50d8ae3SPaolo Bonzini 	for (i = 0; i < ret; i++, gfn++, start++) {
30018a9f566aSDavid Matlack 		mmu_set_spte(vcpu, slot, start, access, gfn,
3002a12f4381SPaolo Bonzini 			     page_to_pfn(pages[i]), NULL);
3003c50d8ae3SPaolo Bonzini 		put_page(pages[i]);
3004c50d8ae3SPaolo Bonzini 	}
3005c50d8ae3SPaolo Bonzini 
3006c50d8ae3SPaolo Bonzini 	return 0;
3007c50d8ae3SPaolo Bonzini }
3008c50d8ae3SPaolo Bonzini 
3009c50d8ae3SPaolo Bonzini static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3010c50d8ae3SPaolo Bonzini 				  struct kvm_mmu_page *sp, u64 *sptep)
3011c50d8ae3SPaolo Bonzini {
3012c50d8ae3SPaolo Bonzini 	u64 *spte, *start = NULL;
3013c50d8ae3SPaolo Bonzini 	int i;
3014c50d8ae3SPaolo Bonzini 
301520ba462dSSean Christopherson 	WARN_ON_ONCE(!sp->role.direct);
3016c50d8ae3SPaolo Bonzini 
301779e48cecSSean Christopherson 	i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
3018c50d8ae3SPaolo Bonzini 	spte = sp->spt + i;
3019c50d8ae3SPaolo Bonzini 
3020c50d8ae3SPaolo Bonzini 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3021c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*spte) || spte == sptep) {
3022c50d8ae3SPaolo Bonzini 			if (!start)
3023c50d8ae3SPaolo Bonzini 				continue;
3024c50d8ae3SPaolo Bonzini 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3025c6cecc4bSSean Christopherson 				return;
3026c50d8ae3SPaolo Bonzini 			start = NULL;
3027c50d8ae3SPaolo Bonzini 		} else if (!start)
3028c50d8ae3SPaolo Bonzini 			start = spte;
3029c50d8ae3SPaolo Bonzini 	}
3030c6cecc4bSSean Christopherson 	if (start)
3031c6cecc4bSSean Christopherson 		direct_pte_prefetch_many(vcpu, sp, start, spte);
3032c50d8ae3SPaolo Bonzini }
3033c50d8ae3SPaolo Bonzini 
3034c50d8ae3SPaolo Bonzini static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3035c50d8ae3SPaolo Bonzini {
3036c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3037c50d8ae3SPaolo Bonzini 
303857354682SSean Christopherson 	sp = sptep_to_sp(sptep);
3039c50d8ae3SPaolo Bonzini 
3040c50d8ae3SPaolo Bonzini 	/*
3041c50d8ae3SPaolo Bonzini 	 * Without accessed bits, there's no way to distinguish between
3042c50d8ae3SPaolo Bonzini 	 * actually accessed translations and prefetched, so disable pte
3043c50d8ae3SPaolo Bonzini 	 * prefetch if accessed bits aren't available.
3044c50d8ae3SPaolo Bonzini 	 */
3045c50d8ae3SPaolo Bonzini 	if (sp_ad_disabled(sp))
3046c50d8ae3SPaolo Bonzini 		return;
3047c50d8ae3SPaolo Bonzini 
30483bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
3049c50d8ae3SPaolo Bonzini 		return;
3050c50d8ae3SPaolo Bonzini 
30514a42d848SDavid Stevens 	/*
30524a42d848SDavid Stevens 	 * If addresses are being invalidated, skip prefetching to avoid
30534a42d848SDavid Stevens 	 * accidentally prefetching those addresses.
30544a42d848SDavid Stevens 	 */
305520ec3ebdSChao Peng 	if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
30564a42d848SDavid Stevens 		return;
30574a42d848SDavid Stevens 
3058c50d8ae3SPaolo Bonzini 	__direct_pte_prefetch(vcpu, sp, sptep);
3059c50d8ae3SPaolo Bonzini }
3060c50d8ae3SPaolo Bonzini 
306165e3b446SSean Christopherson /*
306265e3b446SSean Christopherson  * Lookup the mapping level for @gfn in the current mm.
306365e3b446SSean Christopherson  *
306465e3b446SSean Christopherson  * WARNING!  Use of host_pfn_mapping_level() requires the caller and the end
306565e3b446SSean Christopherson  * consumer to be tied into KVM's handlers for MMU notifier events!
306665e3b446SSean Christopherson  *
306765e3b446SSean Christopherson  * There are several ways to safely use this helper:
306865e3b446SSean Christopherson  *
30698569992dSChao Peng  * - Check mmu_invalidate_retry_gfn() after grabbing the mapping level, before
307065e3b446SSean Christopherson  *   consuming it.  In this case, mmu_lock doesn't need to be held during the
307165e3b446SSean Christopherson  *   lookup, but it does need to be held while checking the MMU notifier.
307265e3b446SSean Christopherson  *
307365e3b446SSean Christopherson  * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
307465e3b446SSean Christopherson  *   event for the hva.  This can be done by explicit checking the MMU notifier
307565e3b446SSean Christopherson  *   or by ensuring that KVM already has a valid mapping that covers the hva.
307665e3b446SSean Christopherson  *
307765e3b446SSean Christopherson  * - Do not use the result to install new mappings, e.g. use the host mapping
307865e3b446SSean Christopherson  *   level only to decide whether or not to zap an entry.  In this case, it's
307965e3b446SSean Christopherson  *   not required to hold mmu_lock (though it's highly likely the caller will
308065e3b446SSean Christopherson  *   want to hold mmu_lock anyways, e.g. to modify SPTEs).
308165e3b446SSean Christopherson  *
308265e3b446SSean Christopherson  * Note!  The lookup can still race with modifications to host page tables, but
308365e3b446SSean Christopherson  * the above "rules" ensure KVM will not _consume_ the result of the walk if a
308465e3b446SSean Christopherson  * race with the primary MMU occurs.
308565e3b446SSean Christopherson  */
3086a8ac499bSSean Christopherson static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
30878ca6f063SBen Gardon 				  const struct kvm_memory_slot *slot)
3088db543216SSean Christopherson {
3089284dc493SSean Christopherson 	int level = PG_LEVEL_4K;
3090db543216SSean Christopherson 	unsigned long hva;
309144187235SMingwei Zhang 	unsigned long flags;
309244187235SMingwei Zhang 	pgd_t pgd;
309344187235SMingwei Zhang 	p4d_t p4d;
309444187235SMingwei Zhang 	pud_t pud;
309544187235SMingwei Zhang 	pmd_t pmd;
3096db543216SSean Christopherson 
30975d49f08cSSean Christopherson 	/*
3098293e306eSSean Christopherson 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3099293e306eSSean Christopherson 	 * is not solely for performance, it's also necessary to avoid the
3100293e306eSSean Christopherson 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
3101293e306eSSean Christopherson 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
3102293e306eSSean Christopherson 	 * page fault steps have already verified the guest isn't writing a
3103293e306eSSean Christopherson 	 * read-only memslot.
3104293e306eSSean Christopherson 	 */
3105db543216SSean Christopherson 	hva = __gfn_to_hva_memslot(slot, gfn);
3106db543216SSean Christopherson 
310744187235SMingwei Zhang 	/*
310865e3b446SSean Christopherson 	 * Disable IRQs to prevent concurrent tear down of host page tables,
310965e3b446SSean Christopherson 	 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
311065e3b446SSean Christopherson 	 * the original page table.
311144187235SMingwei Zhang 	 */
311244187235SMingwei Zhang 	local_irq_save(flags);
3113db543216SSean Christopherson 
311465e3b446SSean Christopherson 	/*
311565e3b446SSean Christopherson 	 * Read each entry once.  As above, a non-leaf entry can be promoted to
311665e3b446SSean Christopherson 	 * a huge page _during_ this walk.  Re-reading the entry could send the
311765e3b446SSean Christopherson 	 * walk into the weeks, e.g. p*d_large() returns false (sees the old
311865e3b446SSean Christopherson 	 * value) and then p*d_offset() walks into the target huge page instead
311965e3b446SSean Christopherson 	 * of the old page table (sees the new value).
312065e3b446SSean Christopherson 	 */
312144187235SMingwei Zhang 	pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
312244187235SMingwei Zhang 	if (pgd_none(pgd))
312344187235SMingwei Zhang 		goto out;
312444187235SMingwei Zhang 
312544187235SMingwei Zhang 	p4d = READ_ONCE(*p4d_offset(&pgd, hva));
312644187235SMingwei Zhang 	if (p4d_none(p4d) || !p4d_present(p4d))
312744187235SMingwei Zhang 		goto out;
312844187235SMingwei Zhang 
312944187235SMingwei Zhang 	pud = READ_ONCE(*pud_offset(&p4d, hva));
313044187235SMingwei Zhang 	if (pud_none(pud) || !pud_present(pud))
313144187235SMingwei Zhang 		goto out;
313244187235SMingwei Zhang 
313344187235SMingwei Zhang 	if (pud_large(pud)) {
313444187235SMingwei Zhang 		level = PG_LEVEL_1G;
313544187235SMingwei Zhang 		goto out;
313644187235SMingwei Zhang 	}
313744187235SMingwei Zhang 
313844187235SMingwei Zhang 	pmd = READ_ONCE(*pmd_offset(&pud, hva));
313944187235SMingwei Zhang 	if (pmd_none(pmd) || !pmd_present(pmd))
314044187235SMingwei Zhang 		goto out;
314144187235SMingwei Zhang 
314244187235SMingwei Zhang 	if (pmd_large(pmd))
314344187235SMingwei Zhang 		level = PG_LEVEL_2M;
314444187235SMingwei Zhang 
314544187235SMingwei Zhang out:
314644187235SMingwei Zhang 	local_irq_restore(flags);
3147db543216SSean Christopherson 	return level;
3148db543216SSean Christopherson }
3149db543216SSean Christopherson 
3150*8dd2eee9SChao Peng static int __kvm_mmu_max_mapping_level(struct kvm *kvm,
3151*8dd2eee9SChao Peng 				       const struct kvm_memory_slot *slot,
3152*8dd2eee9SChao Peng 				       gfn_t gfn, int max_level, bool is_private)
31531b6d9d9eSSean Christopherson {
31541b6d9d9eSSean Christopherson 	struct kvm_lpage_info *linfo;
3155ec607a56SPaolo Bonzini 	int host_level;
31561b6d9d9eSSean Christopherson 
31571b6d9d9eSSean Christopherson 	max_level = min(max_level, max_huge_page_level);
31581b6d9d9eSSean Christopherson 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
31591b6d9d9eSSean Christopherson 		linfo = lpage_info_slot(gfn, slot, max_level);
31601b6d9d9eSSean Christopherson 		if (!linfo->disallow_lpage)
31611b6d9d9eSSean Christopherson 			break;
31621b6d9d9eSSean Christopherson 	}
31631b6d9d9eSSean Christopherson 
3164*8dd2eee9SChao Peng 	if (is_private)
3165*8dd2eee9SChao Peng 		return max_level;
3166*8dd2eee9SChao Peng 
31671b6d9d9eSSean Christopherson 	if (max_level == PG_LEVEL_4K)
31681b6d9d9eSSean Christopherson 		return PG_LEVEL_4K;
31691b6d9d9eSSean Christopherson 
3170a8ac499bSSean Christopherson 	host_level = host_pfn_mapping_level(kvm, gfn, slot);
3171ec607a56SPaolo Bonzini 	return min(host_level, max_level);
31721b6d9d9eSSean Christopherson }
31731b6d9d9eSSean Christopherson 
3174*8dd2eee9SChao Peng int kvm_mmu_max_mapping_level(struct kvm *kvm,
3175*8dd2eee9SChao Peng 			      const struct kvm_memory_slot *slot, gfn_t gfn,
3176*8dd2eee9SChao Peng 			      int max_level)
3177*8dd2eee9SChao Peng {
3178*8dd2eee9SChao Peng 	bool is_private = kvm_slot_can_be_private(slot) &&
3179*8dd2eee9SChao Peng 			  kvm_mem_is_private(kvm, gfn);
3180*8dd2eee9SChao Peng 
3181*8dd2eee9SChao Peng 	return __kvm_mmu_max_mapping_level(kvm, slot, gfn, max_level, is_private);
3182*8dd2eee9SChao Peng }
3183*8dd2eee9SChao Peng 
318473a3c659SPaolo Bonzini void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
31850885904dSSean Christopherson {
3186e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
318717eff019SSean Christopherson 	kvm_pfn_t mask;
31880885904dSSean Christopherson 
318973a3c659SPaolo Bonzini 	fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
31903cf06612SSean Christopherson 
319173a3c659SPaolo Bonzini 	if (unlikely(fault->max_level == PG_LEVEL_4K))
319273a3c659SPaolo Bonzini 		return;
319317eff019SSean Christopherson 
31945d49f08cSSean Christopherson 	if (is_error_noslot_pfn(fault->pfn))
319573a3c659SPaolo Bonzini 		return;
319617eff019SSean Christopherson 
3197e710c5f6SDavid Matlack 	if (kvm_slot_dirty_track_enabled(slot))
319873a3c659SPaolo Bonzini 		return;
3199293e306eSSean Christopherson 
32003cf06612SSean Christopherson 	/*
32013cf06612SSean Christopherson 	 * Enforce the iTLB multihit workaround after capturing the requested
32023cf06612SSean Christopherson 	 * level, which will be used to do precise, accurate accounting.
32033cf06612SSean Christopherson 	 */
3204*8dd2eee9SChao Peng 	fault->req_level = __kvm_mmu_max_mapping_level(vcpu->kvm, slot,
3205*8dd2eee9SChao Peng 						       fault->gfn, fault->max_level,
3206*8dd2eee9SChao Peng 						       fault->is_private);
320773a3c659SPaolo Bonzini 	if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
320873a3c659SPaolo Bonzini 		return;
32094cd071d1SSean Christopherson 
32100885904dSSean Christopherson 	/*
321120ec3ebdSChao Peng 	 * mmu_invalidate_retry() was successful and mmu_lock is held, so
32124cd071d1SSean Christopherson 	 * the pmd can't be split from under us.
32130885904dSSean Christopherson 	 */
321473a3c659SPaolo Bonzini 	fault->goal_level = fault->req_level;
321573a3c659SPaolo Bonzini 	mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
321673a3c659SPaolo Bonzini 	VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
321773a3c659SPaolo Bonzini 	fault->pfn &= ~mask;
32180885904dSSean Christopherson }
32190885904dSSean Christopherson 
3220536f0e6aSPaolo Bonzini void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3221c50d8ae3SPaolo Bonzini {
3222536f0e6aSPaolo Bonzini 	if (cur_level > PG_LEVEL_4K &&
3223536f0e6aSPaolo Bonzini 	    cur_level == fault->goal_level &&
3224c50d8ae3SPaolo Bonzini 	    is_shadow_present_pte(spte) &&
322576901e56SMingwei Zhang 	    !is_large_pte(spte) &&
322676901e56SMingwei Zhang 	    spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3227c50d8ae3SPaolo Bonzini 		/*
32286c882ef4SDavid Matlack 		 * A small SPTE exists for this pfn, but FNAME(fetch),
32296c882ef4SDavid Matlack 		 * direct_map(), or kvm_tdp_mmu_map() would like to create a
32306c882ef4SDavid Matlack 		 * large PTE instead: just force them to go down another level,
32316c882ef4SDavid Matlack 		 * patching back for them into pfn the next 9 bits of the
32326c882ef4SDavid Matlack 		 * address.
3233c50d8ae3SPaolo Bonzini 		 */
3234536f0e6aSPaolo Bonzini 		u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3235536f0e6aSPaolo Bonzini 				KVM_PAGES_PER_HPAGE(cur_level - 1);
3236536f0e6aSPaolo Bonzini 		fault->pfn |= fault->gfn & page_mask;
3237536f0e6aSPaolo Bonzini 		fault->goal_level--;
3238c50d8ae3SPaolo Bonzini 	}
3239c50d8ae3SPaolo Bonzini }
3240c50d8ae3SPaolo Bonzini 
32416c882ef4SDavid Matlack static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3242c50d8ae3SPaolo Bonzini {
3243c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator it;
3244c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
324573a3c659SPaolo Bonzini 	int ret;
324643b74355SPaolo Bonzini 	gfn_t base_gfn = fault->gfn;
3247c50d8ae3SPaolo Bonzini 
324873a3c659SPaolo Bonzini 	kvm_mmu_hugepage_adjust(vcpu, fault);
32494cd071d1SSean Christopherson 
3250f0066d94SPaolo Bonzini 	trace_kvm_mmu_spte_requested(fault);
325143b74355SPaolo Bonzini 	for_each_shadow_entry(vcpu, fault->addr, it) {
3252c50d8ae3SPaolo Bonzini 		/*
3253c50d8ae3SPaolo Bonzini 		 * We cannot overwrite existing page tables with an NX
3254c50d8ae3SPaolo Bonzini 		 * large page, as the leaf could be executable.
3255c50d8ae3SPaolo Bonzini 		 */
325673a3c659SPaolo Bonzini 		if (fault->nx_huge_page_workaround_enabled)
3257536f0e6aSPaolo Bonzini 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3258c50d8ae3SPaolo Bonzini 
3259c667a3baSHou Wenlong 		base_gfn = gfn_round_for_level(fault->gfn, it.level);
326073a3c659SPaolo Bonzini 		if (it.level == fault->goal_level)
3261c50d8ae3SPaolo Bonzini 			break;
3262c50d8ae3SPaolo Bonzini 
32632e65e842SDavid Matlack 		sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
32640cd8dc73SPaolo Bonzini 		if (sp == ERR_PTR(-EEXIST))
32650cd8dc73SPaolo Bonzini 			continue;
3266c50d8ae3SPaolo Bonzini 
3267c50d8ae3SPaolo Bonzini 		link_shadow_page(vcpu, it.sptep, sp);
3268b5b0977fSSean Christopherson 		if (fault->huge_page_disallowed)
326955c510e2SSean Christopherson 			account_nx_huge_page(vcpu->kvm, sp,
3270428e9216SSean Christopherson 					     fault->req_level >= it.level);
3271c50d8ae3SPaolo Bonzini 	}
3272c50d8ae3SPaolo Bonzini 
3273b1a429fbSSean Christopherson 	if (WARN_ON_ONCE(it.level != fault->goal_level))
3274b1a429fbSSean Christopherson 		return -EFAULT;
3275b1a429fbSSean Christopherson 
32768a9f566aSDavid Matlack 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3277a12f4381SPaolo Bonzini 			   base_gfn, fault->pfn, fault);
327812703759SSean Christopherson 	if (ret == RET_PF_SPURIOUS)
327912703759SSean Christopherson 		return ret;
328012703759SSean Christopherson 
3281c50d8ae3SPaolo Bonzini 	direct_pte_prefetch(vcpu, it.sptep);
3282c50d8ae3SPaolo Bonzini 	return ret;
3283c50d8ae3SPaolo Bonzini }
3284c50d8ae3SPaolo Bonzini 
3285cd08d178SDavid Matlack static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3286c50d8ae3SPaolo Bonzini {
3287cd08d178SDavid Matlack 	unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3288cd08d178SDavid Matlack 
3289cd08d178SDavid Matlack 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3290c50d8ae3SPaolo Bonzini }
3291c50d8ae3SPaolo Bonzini 
3292cd08d178SDavid Matlack static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3293c50d8ae3SPaolo Bonzini {
3294cd08d178SDavid Matlack 	if (is_sigpending_pfn(fault->pfn)) {
329576657687SPeter Xu 		kvm_handle_signal_exit(vcpu);
329676657687SPeter Xu 		return -EINTR;
329776657687SPeter Xu 	}
329876657687SPeter Xu 
3299c50d8ae3SPaolo Bonzini 	/*
3300c50d8ae3SPaolo Bonzini 	 * Do not cache the mmio info caused by writing the readonly gfn
3301c50d8ae3SPaolo Bonzini 	 * into the spte otherwise read access on readonly gfn also can
3302c50d8ae3SPaolo Bonzini 	 * caused mmio page fault and treat it as mmio access.
3303c50d8ae3SPaolo Bonzini 	 */
3304cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3305c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3306c50d8ae3SPaolo Bonzini 
3307cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3308cd08d178SDavid Matlack 		kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3309c50d8ae3SPaolo Bonzini 		return RET_PF_RETRY;
3310c50d8ae3SPaolo Bonzini 	}
3311c50d8ae3SPaolo Bonzini 
3312c50d8ae3SPaolo Bonzini 	return -EFAULT;
3313c50d8ae3SPaolo Bonzini }
3314c50d8ae3SPaolo Bonzini 
3315354c908cSDavid Matlack static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3316354c908cSDavid Matlack 				   struct kvm_page_fault *fault,
33175276c616SSean Christopherson 				   unsigned int access)
3318c50d8ae3SPaolo Bonzini {
33193a13f4feSPaolo Bonzini 	gva_t gva = fault->is_tdp ? 0 : fault->addr;
33203a13f4feSPaolo Bonzini 
33213a13f4feSPaolo Bonzini 	vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3322c50d8ae3SPaolo Bonzini 			     access & shadow_mmio_access_mask);
3323354c908cSDavid Matlack 
332430ab5901SSean Christopherson 	/*
332530ab5901SSean Christopherson 	 * If MMIO caching is disabled, emulate immediately without
332630ab5901SSean Christopherson 	 * touching the shadow page tables as attempting to install an
3327354c908cSDavid Matlack 	 * MMIO SPTE will just be an expensive nop.
332830ab5901SSean Christopherson 	 */
3329354c908cSDavid Matlack 	if (unlikely(!enable_mmio_caching))
33305276c616SSean Christopherson 		return RET_PF_EMULATE;
3331354c908cSDavid Matlack 
3332354c908cSDavid Matlack 	/*
3333354c908cSDavid Matlack 	 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3334354c908cSDavid Matlack 	 * any guest that generates such gfns is running nested and is being
3335354c908cSDavid Matlack 	 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3336354c908cSDavid Matlack 	 * only if L1's MAXPHYADDR is inaccurate with respect to the
3337354c908cSDavid Matlack 	 * hardware's).
3338354c908cSDavid Matlack 	 */
3339354c908cSDavid Matlack 	if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3340354c908cSDavid Matlack 		return RET_PF_EMULATE;
3341c50d8ae3SPaolo Bonzini 
33425276c616SSean Christopherson 	return RET_PF_CONTINUE;
3343c50d8ae3SPaolo Bonzini }
3344c50d8ae3SPaolo Bonzini 
33453c8ad5a6SPaolo Bonzini static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
3346c50d8ae3SPaolo Bonzini {
3347c50d8ae3SPaolo Bonzini 	/*
33485c64aba5SSean Christopherson 	 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
33495c64aba5SSean Christopherson 	 * reach the common page fault handler if the SPTE has an invalid MMIO
33505c64aba5SSean Christopherson 	 * generation number.  Refreshing the MMIO generation needs to go down
33515c64aba5SSean Christopherson 	 * the slow path.  Note, EPT Misconfigs do NOT set the PRESENT flag!
3352c50d8ae3SPaolo Bonzini 	 */
33533c8ad5a6SPaolo Bonzini 	if (fault->rsvd)
3354c50d8ae3SPaolo Bonzini 		return false;
3355c50d8ae3SPaolo Bonzini 
3356c50d8ae3SPaolo Bonzini 	/*
3357c50d8ae3SPaolo Bonzini 	 * #PF can be fast if:
3358c50d8ae3SPaolo Bonzini 	 *
335954275f74SSean Christopherson 	 * 1. The shadow page table entry is not present and A/D bits are
336054275f74SSean Christopherson 	 *    disabled _by KVM_, which could mean that the fault is potentially
336154275f74SSean Christopherson 	 *    caused by access tracking (if enabled).  If A/D bits are enabled
336254275f74SSean Christopherson 	 *    by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
336354275f74SSean Christopherson 	 *    bits for L2 and employ access tracking, but the fast page fault
336454275f74SSean Christopherson 	 *    mechanism only supports direct MMUs.
336554275f74SSean Christopherson 	 * 2. The shadow page table entry is present, the access is a write,
336654275f74SSean Christopherson 	 *    and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
336754275f74SSean Christopherson 	 *    the fault was caused by a write-protection violation.  If the
336854275f74SSean Christopherson 	 *    SPTE is MMU-writable (determined later), the fault can be fixed
336954275f74SSean Christopherson 	 *    by setting the Writable bit, which can be done out of mmu_lock.
3370c50d8ae3SPaolo Bonzini 	 */
33715c64aba5SSean Christopherson 	if (!fault->present)
33725c64aba5SSean Christopherson 		return !kvm_ad_enabled();
33735c64aba5SSean Christopherson 
33745c64aba5SSean Christopherson 	/*
33755c64aba5SSean Christopherson 	 * Note, instruction fetches and writes are mutually exclusive, ignore
33765c64aba5SSean Christopherson 	 * the "exec" flag.
33775c64aba5SSean Christopherson 	 */
33785c64aba5SSean Christopherson 	return fault->write;
3379c50d8ae3SPaolo Bonzini }
3380c50d8ae3SPaolo Bonzini 
3381c50d8ae3SPaolo Bonzini /*
3382c50d8ae3SPaolo Bonzini  * Returns true if the SPTE was fixed successfully. Otherwise,
3383c50d8ae3SPaolo Bonzini  * someone else modified the SPTE from its original value.
3384c50d8ae3SPaolo Bonzini  */
3385f3d90f90SSean Christopherson static bool fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu,
3386f3d90f90SSean Christopherson 				    struct kvm_page_fault *fault,
3387c50d8ae3SPaolo Bonzini 				    u64 *sptep, u64 old_spte, u64 new_spte)
3388c50d8ae3SPaolo Bonzini {
3389c50d8ae3SPaolo Bonzini 	/*
3390c50d8ae3SPaolo Bonzini 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3391c50d8ae3SPaolo Bonzini 	 * order to eliminate unnecessary PML logging. See comments in
3392c50d8ae3SPaolo Bonzini 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3393c50d8ae3SPaolo Bonzini 	 * enabled, so we do not do this. This might result in the same GPA
3394c50d8ae3SPaolo Bonzini 	 * to be logged in PML buffer again when the write really happens, and
3395c50d8ae3SPaolo Bonzini 	 * eventually to be called by mark_page_dirty twice. But it's also no
3396c50d8ae3SPaolo Bonzini 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3397c50d8ae3SPaolo Bonzini 	 * so non-PML cases won't be impacted.
3398c50d8ae3SPaolo Bonzini 	 *
3399c50d8ae3SPaolo Bonzini 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3400c50d8ae3SPaolo Bonzini 	 */
34012db2f46fSUros Bizjak 	if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3402c50d8ae3SPaolo Bonzini 		return false;
3403c50d8ae3SPaolo Bonzini 
3404e710c5f6SDavid Matlack 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3405e710c5f6SDavid Matlack 		mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3406c50d8ae3SPaolo Bonzini 
3407c50d8ae3SPaolo Bonzini 	return true;
3408c50d8ae3SPaolo Bonzini }
3409c50d8ae3SPaolo Bonzini 
34103c8ad5a6SPaolo Bonzini static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3411c50d8ae3SPaolo Bonzini {
34123c8ad5a6SPaolo Bonzini 	if (fault->exec)
3413c50d8ae3SPaolo Bonzini 		return is_executable_pte(spte);
3414c50d8ae3SPaolo Bonzini 
34153c8ad5a6SPaolo Bonzini 	if (fault->write)
3416c50d8ae3SPaolo Bonzini 		return is_writable_pte(spte);
3417c50d8ae3SPaolo Bonzini 
3418c50d8ae3SPaolo Bonzini 	/* Fault was on Read access */
3419c50d8ae3SPaolo Bonzini 	return spte & PT_PRESENT_MASK;
3420c50d8ae3SPaolo Bonzini }
3421c50d8ae3SPaolo Bonzini 
3422c50d8ae3SPaolo Bonzini /*
34236e8eb206SDavid Matlack  * Returns the last level spte pointer of the shadow page walk for the given
34246e8eb206SDavid Matlack  * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
34256e8eb206SDavid Matlack  * walk could be performed, returns NULL and *spte does not contain valid data.
34266e8eb206SDavid Matlack  *
34276e8eb206SDavid Matlack  * Contract:
34286e8eb206SDavid Matlack  *  - Must be called between walk_shadow_page_lockless_{begin,end}.
34296e8eb206SDavid Matlack  *  - The returned sptep must not be used after walk_shadow_page_lockless_end.
34306e8eb206SDavid Matlack  */
34316e8eb206SDavid Matlack static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
34326e8eb206SDavid Matlack {
34336e8eb206SDavid Matlack 	struct kvm_shadow_walk_iterator iterator;
34346e8eb206SDavid Matlack 	u64 old_spte;
34356e8eb206SDavid Matlack 	u64 *sptep = NULL;
34366e8eb206SDavid Matlack 
34376e8eb206SDavid Matlack 	for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
34386e8eb206SDavid Matlack 		sptep = iterator.sptep;
34396e8eb206SDavid Matlack 		*spte = old_spte;
34406e8eb206SDavid Matlack 	}
34416e8eb206SDavid Matlack 
34426e8eb206SDavid Matlack 	return sptep;
34436e8eb206SDavid Matlack }
34446e8eb206SDavid Matlack 
34456e8eb206SDavid Matlack /*
3446c4371c2aSSean Christopherson  * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3447c50d8ae3SPaolo Bonzini  */
34483c8ad5a6SPaolo Bonzini static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3449c50d8ae3SPaolo Bonzini {
3450c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3451c4371c2aSSean Christopherson 	int ret = RET_PF_INVALID;
34521de9992fSLi zeming 	u64 spte;
34531de9992fSLi zeming 	u64 *sptep;
3454c50d8ae3SPaolo Bonzini 	uint retry_count = 0;
3455c50d8ae3SPaolo Bonzini 
34563c8ad5a6SPaolo Bonzini 	if (!page_fault_can_be_fast(fault))
3457c4371c2aSSean Christopherson 		return ret;
3458c50d8ae3SPaolo Bonzini 
3459c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
3460c50d8ae3SPaolo Bonzini 
3461c50d8ae3SPaolo Bonzini 	do {
3462c50d8ae3SPaolo Bonzini 		u64 new_spte;
3463c50d8ae3SPaolo Bonzini 
3464dfe0ecc6SSean Christopherson 		if (tdp_mmu_enabled)
34653c8ad5a6SPaolo Bonzini 			sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
34666e8eb206SDavid Matlack 		else
34673c8ad5a6SPaolo Bonzini 			sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3468c50d8ae3SPaolo Bonzini 
34691de9992fSLi zeming 		/*
34701de9992fSLi zeming 		 * It's entirely possible for the mapping to have been zapped
34711de9992fSLi zeming 		 * by a different task, but the root page should always be
34721de9992fSLi zeming 		 * available as the vCPU holds a reference to its root(s).
34731de9992fSLi zeming 		 */
34741de9992fSLi zeming 		if (WARN_ON_ONCE(!sptep))
34751de9992fSLi zeming 			spte = REMOVED_SPTE;
34761de9992fSLi zeming 
3477ec89e643SSean Christopherson 		if (!is_shadow_present_pte(spte))
3478ec89e643SSean Christopherson 			break;
3479ec89e643SSean Christopherson 
34806e8eb206SDavid Matlack 		sp = sptep_to_sp(sptep);
3481c50d8ae3SPaolo Bonzini 		if (!is_last_spte(spte, sp->role.level))
3482c50d8ae3SPaolo Bonzini 			break;
3483c50d8ae3SPaolo Bonzini 
3484c50d8ae3SPaolo Bonzini 		/*
3485c50d8ae3SPaolo Bonzini 		 * Check whether the memory access that caused the fault would
3486c50d8ae3SPaolo Bonzini 		 * still cause it if it were to be performed right now. If not,
3487c50d8ae3SPaolo Bonzini 		 * then this is a spurious fault caused by TLB lazily flushed,
3488c50d8ae3SPaolo Bonzini 		 * or some other CPU has already fixed the PTE after the
3489c50d8ae3SPaolo Bonzini 		 * current CPU took the fault.
3490c50d8ae3SPaolo Bonzini 		 *
3491c50d8ae3SPaolo Bonzini 		 * Need not check the access of upper level table entries since
3492c50d8ae3SPaolo Bonzini 		 * they are always ACC_ALL.
3493c50d8ae3SPaolo Bonzini 		 */
34943c8ad5a6SPaolo Bonzini 		if (is_access_allowed(fault, spte)) {
3495c4371c2aSSean Christopherson 			ret = RET_PF_SPURIOUS;
3496c50d8ae3SPaolo Bonzini 			break;
3497c50d8ae3SPaolo Bonzini 		}
3498c50d8ae3SPaolo Bonzini 
3499c50d8ae3SPaolo Bonzini 		new_spte = spte;
3500c50d8ae3SPaolo Bonzini 
350154275f74SSean Christopherson 		/*
350254275f74SSean Christopherson 		 * KVM only supports fixing page faults outside of MMU lock for
350354275f74SSean Christopherson 		 * direct MMUs, nested MMUs are always indirect, and KVM always
350454275f74SSean Christopherson 		 * uses A/D bits for non-nested MMUs.  Thus, if A/D bits are
350554275f74SSean Christopherson 		 * enabled, the SPTE can't be an access-tracked SPTE.
350654275f74SSean Christopherson 		 */
350754275f74SSean Christopherson 		if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3508c50d8ae3SPaolo Bonzini 			new_spte = restore_acc_track_spte(new_spte);
3509c50d8ae3SPaolo Bonzini 
3510c50d8ae3SPaolo Bonzini 		/*
351154275f74SSean Christopherson 		 * To keep things simple, only SPTEs that are MMU-writable can
351254275f74SSean Christopherson 		 * be made fully writable outside of mmu_lock, e.g. only SPTEs
351354275f74SSean Christopherson 		 * that were write-protected for dirty-logging or access
351454275f74SSean Christopherson 		 * tracking are handled here.  Don't bother checking if the
351554275f74SSean Christopherson 		 * SPTE is writable to prioritize running with A/D bits enabled.
351654275f74SSean Christopherson 		 * The is_access_allowed() check above handles the common case
351754275f74SSean Christopherson 		 * of the fault being spurious, and the SPTE is known to be
351854275f74SSean Christopherson 		 * shadow-present, i.e. except for access tracking restoration
351954275f74SSean Christopherson 		 * making the new SPTE writable, the check is wasteful.
3520c50d8ae3SPaolo Bonzini 		 */
3521706c9c55SSean Christopherson 		if (fault->write && is_mmu_writable_spte(spte)) {
3522c50d8ae3SPaolo Bonzini 			new_spte |= PT_WRITABLE_MASK;
3523c50d8ae3SPaolo Bonzini 
3524c50d8ae3SPaolo Bonzini 			/*
352510c30de0SJunaid Shahid 			 * Do not fix write-permission on the large spte when
352610c30de0SJunaid Shahid 			 * dirty logging is enabled. Since we only dirty the
352710c30de0SJunaid Shahid 			 * first page into the dirty-bitmap in
3528c50d8ae3SPaolo Bonzini 			 * fast_pf_fix_direct_spte(), other pages are missed
3529c50d8ae3SPaolo Bonzini 			 * if its slot has dirty logging enabled.
3530c50d8ae3SPaolo Bonzini 			 *
3531c50d8ae3SPaolo Bonzini 			 * Instead, we let the slow page fault path create a
3532c50d8ae3SPaolo Bonzini 			 * normal spte to fix the access.
3533c50d8ae3SPaolo Bonzini 			 */
353410c30de0SJunaid Shahid 			if (sp->role.level > PG_LEVEL_4K &&
353510c30de0SJunaid Shahid 			    kvm_slot_dirty_track_enabled(fault->slot))
3536c50d8ae3SPaolo Bonzini 				break;
3537c50d8ae3SPaolo Bonzini 		}
3538c50d8ae3SPaolo Bonzini 
3539c50d8ae3SPaolo Bonzini 		/* Verify that the fault can be handled in the fast path */
3540c50d8ae3SPaolo Bonzini 		if (new_spte == spte ||
35413c8ad5a6SPaolo Bonzini 		    !is_access_allowed(fault, new_spte))
3542c50d8ae3SPaolo Bonzini 			break;
3543c50d8ae3SPaolo Bonzini 
3544c50d8ae3SPaolo Bonzini 		/*
3545c50d8ae3SPaolo Bonzini 		 * Currently, fast page fault only works for direct mapping
3546c50d8ae3SPaolo Bonzini 		 * since the gfn is not stable for indirect shadow page. See
35473ecad8c2SMauro Carvalho Chehab 		 * Documentation/virt/kvm/locking.rst to get more detail.
3548c50d8ae3SPaolo Bonzini 		 */
3549e710c5f6SDavid Matlack 		if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3550c4371c2aSSean Christopherson 			ret = RET_PF_FIXED;
3551c50d8ae3SPaolo Bonzini 			break;
3552c4371c2aSSean Christopherson 		}
3553c50d8ae3SPaolo Bonzini 
3554c50d8ae3SPaolo Bonzini 		if (++retry_count > 4) {
35558d20bd63SSean Christopherson 			pr_warn_once("Fast #PF retrying more than 4 times.\n");
3556c50d8ae3SPaolo Bonzini 			break;
3557c50d8ae3SPaolo Bonzini 		}
3558c50d8ae3SPaolo Bonzini 
3559c50d8ae3SPaolo Bonzini 	} while (true);
3560c50d8ae3SPaolo Bonzini 
3561f0066d94SPaolo Bonzini 	trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3562c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3563c50d8ae3SPaolo Bonzini 
35641075d41eSSean Christopherson 	if (ret != RET_PF_INVALID)
35651075d41eSSean Christopherson 		vcpu->stat.pf_fast++;
35661075d41eSSean Christopherson 
3567c4371c2aSSean Christopherson 	return ret;
3568c50d8ae3SPaolo Bonzini }
3569c50d8ae3SPaolo Bonzini 
3570c50d8ae3SPaolo Bonzini static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3571c50d8ae3SPaolo Bonzini 			       struct list_head *invalid_list)
3572c50d8ae3SPaolo Bonzini {
3573c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3574c50d8ae3SPaolo Bonzini 
3575c50d8ae3SPaolo Bonzini 	if (!VALID_PAGE(*root_hpa))
3576c50d8ae3SPaolo Bonzini 		return;
3577c50d8ae3SPaolo Bonzini 
3578c5f2d564SSean Christopherson 	sp = root_to_sp(*root_hpa);
357920ba462dSSean Christopherson 	if (WARN_ON_ONCE(!sp))
35809191b8f0SPaolo Bonzini 		return;
358102c00b3aSBen Gardon 
3582897218ffSPaolo Bonzini 	if (is_tdp_mmu_page(sp))
35836103bc07SBen Gardon 		kvm_tdp_mmu_put_root(kvm, sp, false);
358476eb54e7SBen Gardon 	else if (!--sp->root_count && sp->role.invalid)
3585c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3586c50d8ae3SPaolo Bonzini 
3587c50d8ae3SPaolo Bonzini 	*root_hpa = INVALID_PAGE;
3588c50d8ae3SPaolo Bonzini }
3589c50d8ae3SPaolo Bonzini 
3590c50d8ae3SPaolo Bonzini /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
35910c1c92f1SPaolo Bonzini void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3592c50d8ae3SPaolo Bonzini 			ulong roots_to_free)
3593c50d8ae3SPaolo Bonzini {
3594c50d8ae3SPaolo Bonzini 	int i;
3595c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
3596594bef79SPaolo Bonzini 	bool free_active_root;
3597c50d8ae3SPaolo Bonzini 
3598f94db0c8SSean Christopherson 	WARN_ON_ONCE(roots_to_free & ~KVM_MMU_ROOTS_ALL);
3599f94db0c8SSean Christopherson 
3600c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3601c50d8ae3SPaolo Bonzini 
3602c50d8ae3SPaolo Bonzini 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3603594bef79SPaolo Bonzini 	free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3604594bef79SPaolo Bonzini 		&& VALID_PAGE(mmu->root.hpa);
3605594bef79SPaolo Bonzini 
3606594bef79SPaolo Bonzini 	if (!free_active_root) {
3607c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3608c50d8ae3SPaolo Bonzini 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3609c50d8ae3SPaolo Bonzini 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3610c50d8ae3SPaolo Bonzini 				break;
3611c50d8ae3SPaolo Bonzini 
3612c50d8ae3SPaolo Bonzini 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3613c50d8ae3SPaolo Bonzini 			return;
3614c50d8ae3SPaolo Bonzini 	}
3615c50d8ae3SPaolo Bonzini 
3616531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
3617c50d8ae3SPaolo Bonzini 
3618c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3619c50d8ae3SPaolo Bonzini 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
36204d710de9SSean Christopherson 			mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3621c50d8ae3SPaolo Bonzini 					   &invalid_list);
3622c50d8ae3SPaolo Bonzini 
3623c50d8ae3SPaolo Bonzini 	if (free_active_root) {
36240e3223d8SSean Christopherson 		if (kvm_mmu_is_dummy_root(mmu->root.hpa)) {
36250e3223d8SSean Christopherson 			/* Nothing to cleanup for dummy roots. */
36260e3223d8SSean Christopherson 		} else if (root_to_sp(mmu->root.hpa)) {
3627b9e5603cSPaolo Bonzini 			mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
362804d45551SSean Christopherson 		} else if (mmu->pae_root) {
3629c834e5e4SSean Christopherson 			for (i = 0; i < 4; ++i) {
3630c834e5e4SSean Christopherson 				if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3631c834e5e4SSean Christopherson 					continue;
3632c834e5e4SSean Christopherson 
3633c834e5e4SSean Christopherson 				mmu_free_root_page(kvm, &mmu->pae_root[i],
3634c50d8ae3SPaolo Bonzini 						   &invalid_list);
3635c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3636c50d8ae3SPaolo Bonzini 			}
3637c50d8ae3SPaolo Bonzini 		}
3638b9e5603cSPaolo Bonzini 		mmu->root.hpa = INVALID_PAGE;
3639b9e5603cSPaolo Bonzini 		mmu->root.pgd = 0;
3640c50d8ae3SPaolo Bonzini 	}
3641c50d8ae3SPaolo Bonzini 
36424d710de9SSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
3643531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
3644c50d8ae3SPaolo Bonzini }
3645c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3646c50d8ae3SPaolo Bonzini 
36470c1c92f1SPaolo Bonzini void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
364825b62c62SSean Christopherson {
364925b62c62SSean Christopherson 	unsigned long roots_to_free = 0;
3650c5f2d564SSean Christopherson 	struct kvm_mmu_page *sp;
365125b62c62SSean Christopherson 	hpa_t root_hpa;
365225b62c62SSean Christopherson 	int i;
365325b62c62SSean Christopherson 
365425b62c62SSean Christopherson 	/*
365525b62c62SSean Christopherson 	 * This should not be called while L2 is active, L2 can't invalidate
365625b62c62SSean Christopherson 	 * _only_ its own roots, e.g. INVVPID unconditionally exits.
365725b62c62SSean Christopherson 	 */
36587a458f0eSPaolo Bonzini 	WARN_ON_ONCE(mmu->root_role.guest_mode);
365925b62c62SSean Christopherson 
366025b62c62SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
366125b62c62SSean Christopherson 		root_hpa = mmu->prev_roots[i].hpa;
366225b62c62SSean Christopherson 		if (!VALID_PAGE(root_hpa))
366325b62c62SSean Christopherson 			continue;
366425b62c62SSean Christopherson 
3665c5f2d564SSean Christopherson 		sp = root_to_sp(root_hpa);
3666c5f2d564SSean Christopherson 		if (!sp || sp->role.guest_mode)
366725b62c62SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
366825b62c62SSean Christopherson 	}
366925b62c62SSean Christopherson 
36700c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, roots_to_free);
367125b62c62SSean Christopherson }
367225b62c62SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
367325b62c62SSean Christopherson 
36742e65e842SDavid Matlack static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
367586938ab6SDavid Matlack 			    u8 level)
3676c50d8ae3SPaolo Bonzini {
36772e65e842SDavid Matlack 	union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3678c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
36798123f265SSean Christopherson 
36802e65e842SDavid Matlack 	role.level = level;
36812e65e842SDavid Matlack 	role.quadrant = quadrant;
36822e65e842SDavid Matlack 
36837f497775SDavid Matlack 	WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
36847f497775SDavid Matlack 	WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
36857f497775SDavid Matlack 
368687654643SDavid Matlack 	sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
36878123f265SSean Christopherson 	++sp->root_count;
36888123f265SSean Christopherson 
36898123f265SSean Christopherson 	return __pa(sp->spt);
36908123f265SSean Christopherson }
36918123f265SSean Christopherson 
36928123f265SSean Christopherson static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
36938123f265SSean Christopherson {
3694b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3695a972e29cSPaolo Bonzini 	u8 shadow_root_level = mmu->root_role.level;
36968123f265SSean Christopherson 	hpa_t root;
3697c50d8ae3SPaolo Bonzini 	unsigned i;
36984a38162eSPaolo Bonzini 	int r;
36994a38162eSPaolo Bonzini 
37004a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
37014a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
37024a38162eSPaolo Bonzini 	if (r < 0)
37034a38162eSPaolo Bonzini 		goto out_unlock;
3704c50d8ae3SPaolo Bonzini 
37051f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
370602c00b3aSBen Gardon 		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
3707b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
370802c00b3aSBen Gardon 	} else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
370986938ab6SDavid Matlack 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3710b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
37118123f265SSean Christopherson 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
37124a38162eSPaolo Bonzini 		if (WARN_ON_ONCE(!mmu->pae_root)) {
37134a38162eSPaolo Bonzini 			r = -EIO;
37144a38162eSPaolo Bonzini 			goto out_unlock;
37154a38162eSPaolo Bonzini 		}
371673ad1606SSean Christopherson 
3717c50d8ae3SPaolo Bonzini 		for (i = 0; i < 4; ++i) {
3718c834e5e4SSean Christopherson 			WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3719c50d8ae3SPaolo Bonzini 
37207f497775SDavid Matlack 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
37212e65e842SDavid Matlack 					      PT32_ROOT_LEVEL);
372217e368d9SSean Christopherson 			mmu->pae_root[i] = root | PT_PRESENT_MASK |
3723d2263de1SYuan Yao 					   shadow_me_value;
3724c50d8ae3SPaolo Bonzini 		}
3725b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
372673ad1606SSean Christopherson 	} else {
372773ad1606SSean Christopherson 		WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
37284a38162eSPaolo Bonzini 		r = -EIO;
37294a38162eSPaolo Bonzini 		goto out_unlock;
373073ad1606SSean Christopherson 	}
37313651c7fcSSean Christopherson 
3732b9e5603cSPaolo Bonzini 	/* root.pgd is ignored for direct MMUs. */
3733b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
37344a38162eSPaolo Bonzini out_unlock:
37354a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
37364a38162eSPaolo Bonzini 	return r;
3737c50d8ae3SPaolo Bonzini }
3738c50d8ae3SPaolo Bonzini 
37391e76a3ceSDavid Stevens static int mmu_first_shadow_root_alloc(struct kvm *kvm)
37401e76a3ceSDavid Stevens {
37411e76a3ceSDavid Stevens 	struct kvm_memslots *slots;
37421e76a3ceSDavid Stevens 	struct kvm_memory_slot *slot;
3743a54d8066SMaciej S. Szmigiero 	int r = 0, i, bkt;
37441e76a3ceSDavid Stevens 
37451e76a3ceSDavid Stevens 	/*
37461e76a3ceSDavid Stevens 	 * Check if this is the first shadow root being allocated before
37471e76a3ceSDavid Stevens 	 * taking the lock.
37481e76a3ceSDavid Stevens 	 */
37491e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
37501e76a3ceSDavid Stevens 		return 0;
37511e76a3ceSDavid Stevens 
37521e76a3ceSDavid Stevens 	mutex_lock(&kvm->slots_arch_lock);
37531e76a3ceSDavid Stevens 
37541e76a3ceSDavid Stevens 	/* Recheck, under the lock, whether this is the first shadow root. */
37551e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
37561e76a3ceSDavid Stevens 		goto out_unlock;
37571e76a3ceSDavid Stevens 
37581e76a3ceSDavid Stevens 	/*
37591e76a3ceSDavid Stevens 	 * Check if anything actually needs to be allocated, e.g. all metadata
37601e76a3ceSDavid Stevens 	 * will be allocated upfront if TDP is disabled.
37611e76a3ceSDavid Stevens 	 */
37621e76a3ceSDavid Stevens 	if (kvm_memslots_have_rmaps(kvm) &&
37631e76a3ceSDavid Stevens 	    kvm_page_track_write_tracking_enabled(kvm))
37641e76a3ceSDavid Stevens 		goto out_success;
37651e76a3ceSDavid Stevens 
37661e76a3ceSDavid Stevens 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
37671e76a3ceSDavid Stevens 		slots = __kvm_memslots(kvm, i);
3768a54d8066SMaciej S. Szmigiero 		kvm_for_each_memslot(slot, bkt, slots) {
37691e76a3ceSDavid Stevens 			/*
37701e76a3ceSDavid Stevens 			 * Both of these functions are no-ops if the target is
37711e76a3ceSDavid Stevens 			 * already allocated, so unconditionally calling both
37721e76a3ceSDavid Stevens 			 * is safe.  Intentionally do NOT free allocations on
37731e76a3ceSDavid Stevens 			 * failure to avoid having to track which allocations
37741e76a3ceSDavid Stevens 			 * were made now versus when the memslot was created.
37751e76a3ceSDavid Stevens 			 * The metadata is guaranteed to be freed when the slot
37761e76a3ceSDavid Stevens 			 * is freed, and will be kept/used if userspace retries
37771e76a3ceSDavid Stevens 			 * KVM_RUN instead of killing the VM.
37781e76a3ceSDavid Stevens 			 */
37791e76a3ceSDavid Stevens 			r = memslot_rmap_alloc(slot, slot->npages);
37801e76a3ceSDavid Stevens 			if (r)
37811e76a3ceSDavid Stevens 				goto out_unlock;
37821e76a3ceSDavid Stevens 			r = kvm_page_track_write_tracking_alloc(slot);
37831e76a3ceSDavid Stevens 			if (r)
37841e76a3ceSDavid Stevens 				goto out_unlock;
37851e76a3ceSDavid Stevens 		}
37861e76a3ceSDavid Stevens 	}
37871e76a3ceSDavid Stevens 
37881e76a3ceSDavid Stevens 	/*
37891e76a3ceSDavid Stevens 	 * Ensure that shadow_root_allocated becomes true strictly after
37901e76a3ceSDavid Stevens 	 * all the related pointers are set.
37911e76a3ceSDavid Stevens 	 */
37921e76a3ceSDavid Stevens out_success:
37931e76a3ceSDavid Stevens 	smp_store_release(&kvm->arch.shadow_root_allocated, true);
37941e76a3ceSDavid Stevens 
37951e76a3ceSDavid Stevens out_unlock:
37961e76a3ceSDavid Stevens 	mutex_unlock(&kvm->slots_arch_lock);
37971e76a3ceSDavid Stevens 	return r;
37981e76a3ceSDavid Stevens }
37991e76a3ceSDavid Stevens 
3800c50d8ae3SPaolo Bonzini static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3801c50d8ae3SPaolo Bonzini {
3802b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
38036e0918aeSSean Christopherson 	u64 pdptrs[4], pm_mask;
3804be01e8e2SSean Christopherson 	gfn_t root_gfn, root_pgd;
38057f497775SDavid Matlack 	int quadrant, i, r;
38068123f265SSean Christopherson 	hpa_t root;
3807c50d8ae3SPaolo Bonzini 
38082fdcc1b3SPaolo Bonzini 	root_pgd = kvm_mmu_get_guest_pgd(vcpu, mmu);
3809be01e8e2SSean Christopherson 	root_gfn = root_pgd >> PAGE_SHIFT;
3810c50d8ae3SPaolo Bonzini 
38110e3223d8SSean Christopherson 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
38120e3223d8SSean Christopherson 		mmu->root.hpa = kvm_mmu_get_dummy_root();
38130e3223d8SSean Christopherson 		return 0;
38140e3223d8SSean Christopherson 	}
3815c50d8ae3SPaolo Bonzini 
3816c50d8ae3SPaolo Bonzini 	/*
38174a38162eSPaolo Bonzini 	 * On SVM, reading PDPTRs might access guest memory, which might fault
38184a38162eSPaolo Bonzini 	 * and thus might sleep.  Grab the PDPTRs before acquiring mmu_lock.
38194a38162eSPaolo Bonzini 	 */
38204d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
38216e0918aeSSean Christopherson 		for (i = 0; i < 4; ++i) {
38226e0918aeSSean Christopherson 			pdptrs[i] = mmu->get_pdptr(vcpu, i);
38236e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK))
38246e0918aeSSean Christopherson 				continue;
38256e0918aeSSean Christopherson 
38260e3223d8SSean Christopherson 			if (!kvm_vcpu_is_visible_gfn(vcpu, pdptrs[i] >> PAGE_SHIFT))
38270e3223d8SSean Christopherson 				pdptrs[i] = 0;
38286e0918aeSSean Christopherson 		}
38296e0918aeSSean Christopherson 	}
38306e0918aeSSean Christopherson 
38311e76a3ceSDavid Stevens 	r = mmu_first_shadow_root_alloc(vcpu->kvm);
3832d501f747SBen Gardon 	if (r)
3833d501f747SBen Gardon 		return r;
3834d501f747SBen Gardon 
38354a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
38364a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
38374a38162eSPaolo Bonzini 	if (r < 0)
38384a38162eSPaolo Bonzini 		goto out_unlock;
38394a38162eSPaolo Bonzini 
3840c50d8ae3SPaolo Bonzini 	/*
3841c50d8ae3SPaolo Bonzini 	 * Do we shadow a long mode page table? If so we need to
3842c50d8ae3SPaolo Bonzini 	 * write-protect the guests page table root.
3843c50d8ae3SPaolo Bonzini 	 */
38444d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
38458123f265SSean Christopherson 		root = mmu_alloc_root(vcpu, root_gfn, 0,
384686938ab6SDavid Matlack 				      mmu->root_role.level);
3847b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
3848be01e8e2SSean Christopherson 		goto set_root_pgd;
3849c50d8ae3SPaolo Bonzini 	}
3850c50d8ae3SPaolo Bonzini 
38514a38162eSPaolo Bonzini 	if (WARN_ON_ONCE(!mmu->pae_root)) {
38524a38162eSPaolo Bonzini 		r = -EIO;
38534a38162eSPaolo Bonzini 		goto out_unlock;
38544a38162eSPaolo Bonzini 	}
385573ad1606SSean Christopherson 
3856c50d8ae3SPaolo Bonzini 	/*
3857c50d8ae3SPaolo Bonzini 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3858c50d8ae3SPaolo Bonzini 	 * or a PAE 3-level page table. In either case we need to be aware that
3859c50d8ae3SPaolo Bonzini 	 * the shadow page table may be a PAE or a long mode page table.
3860c50d8ae3SPaolo Bonzini 	 */
3861e54f1ff2SKai Huang 	pm_mask = PT_PRESENT_MASK | shadow_me_value;
3862a972e29cSPaolo Bonzini 	if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3863c50d8ae3SPaolo Bonzini 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3864c50d8ae3SPaolo Bonzini 
386503ca4589SSean Christopherson 		if (WARN_ON_ONCE(!mmu->pml4_root)) {
38664a38162eSPaolo Bonzini 			r = -EIO;
38674a38162eSPaolo Bonzini 			goto out_unlock;
38684a38162eSPaolo Bonzini 		}
386903ca4589SSean Christopherson 		mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3870cb0f722aSWei Huang 
3871a972e29cSPaolo Bonzini 		if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3872cb0f722aSWei Huang 			if (WARN_ON_ONCE(!mmu->pml5_root)) {
3873cb0f722aSWei Huang 				r = -EIO;
3874cb0f722aSWei Huang 				goto out_unlock;
3875cb0f722aSWei Huang 			}
3876cb0f722aSWei Huang 			mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3877cb0f722aSWei Huang 		}
387804d45551SSean Christopherson 	}
387904d45551SSean Christopherson 
3880c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3881c834e5e4SSean Christopherson 		WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
38826e6ec584SSean Christopherson 
38834d25502aSPaolo Bonzini 		if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
38846e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3885c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3886c50d8ae3SPaolo Bonzini 				continue;
3887c50d8ae3SPaolo Bonzini 			}
38886e0918aeSSean Christopherson 			root_gfn = pdptrs[i] >> PAGE_SHIFT;
3889c50d8ae3SPaolo Bonzini 		}
3890c50d8ae3SPaolo Bonzini 
38917f497775SDavid Matlack 		/*
38927f497775SDavid Matlack 		 * If shadowing 32-bit non-PAE page tables, each PAE page
38937f497775SDavid Matlack 		 * directory maps one quarter of the guest's non-PAE page
38947f497775SDavid Matlack 		 * directory. Othwerise each PAE page direct shadows one guest
38957f497775SDavid Matlack 		 * PAE page directory so that quadrant should be 0.
38967f497775SDavid Matlack 		 */
38977f497775SDavid Matlack 		quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
38987f497775SDavid Matlack 
38997f497775SDavid Matlack 		root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3900b37233c9SSean Christopherson 		mmu->pae_root[i] = root | pm_mask;
3901c50d8ae3SPaolo Bonzini 	}
3902c50d8ae3SPaolo Bonzini 
3903a972e29cSPaolo Bonzini 	if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3904b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml5_root);
3905a972e29cSPaolo Bonzini 	else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3906b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml4_root);
3907ba0a194fSSean Christopherson 	else
3908b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
3909c50d8ae3SPaolo Bonzini 
3910be01e8e2SSean Christopherson set_root_pgd:
3911b9e5603cSPaolo Bonzini 	mmu->root.pgd = root_pgd;
39124a38162eSPaolo Bonzini out_unlock:
39134a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
3914c50d8ae3SPaolo Bonzini 
3915c6c937d6SLike Xu 	return r;
3916c50d8ae3SPaolo Bonzini }
3917c50d8ae3SPaolo Bonzini 
3918748e52b9SSean Christopherson static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3919c50d8ae3SPaolo Bonzini {
3920748e52b9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3921a972e29cSPaolo Bonzini 	bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3922cb0f722aSWei Huang 	u64 *pml5_root = NULL;
3923cb0f722aSWei Huang 	u64 *pml4_root = NULL;
3924cb0f722aSWei Huang 	u64 *pae_root;
3925748e52b9SSean Christopherson 
3926748e52b9SSean Christopherson 	/*
3927748e52b9SSean Christopherson 	 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3928748e52b9SSean Christopherson 	 * tables are allocated and initialized at root creation as there is no
3929748e52b9SSean Christopherson 	 * equivalent level in the guest's NPT to shadow.  Allocate the tables
3930748e52b9SSean Christopherson 	 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3931748e52b9SSean Christopherson 	 */
3932347a0d0dSPaolo Bonzini 	if (mmu->root_role.direct ||
3933347a0d0dSPaolo Bonzini 	    mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3934a972e29cSPaolo Bonzini 	    mmu->root_role.level < PT64_ROOT_4LEVEL)
3935748e52b9SSean Christopherson 		return 0;
3936748e52b9SSean Christopherson 
3937a717a780SSean Christopherson 	/*
3938a717a780SSean Christopherson 	 * NPT, the only paging mode that uses this horror, uses a fixed number
3939a717a780SSean Christopherson 	 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3940a717a780SSean Christopherson 	 * all MMus are 5-level.  Thus, this can safely require that pml5_root
3941a717a780SSean Christopherson 	 * is allocated if the other roots are valid and pml5 is needed, as any
3942a717a780SSean Christopherson 	 * prior MMU would also have required pml5.
3943a717a780SSean Christopherson 	 */
3944a717a780SSean Christopherson 	if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3945748e52b9SSean Christopherson 		return 0;
3946748e52b9SSean Christopherson 
3947748e52b9SSean Christopherson 	/*
3948748e52b9SSean Christopherson 	 * The special roots should always be allocated in concert.  Yell and
3949748e52b9SSean Christopherson 	 * bail if KVM ends up in a state where only one of the roots is valid.
3950748e52b9SSean Christopherson 	 */
3951cb0f722aSWei Huang 	if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3952a717a780SSean Christopherson 			 (need_pml5 && mmu->pml5_root)))
3953748e52b9SSean Christopherson 		return -EIO;
3954748e52b9SSean Christopherson 
39554a98623dSSean Christopherson 	/*
39564a98623dSSean Christopherson 	 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
39574a98623dSSean Christopherson 	 * doesn't need to be decrypted.
39584a98623dSSean Christopherson 	 */
3959748e52b9SSean Christopherson 	pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3960748e52b9SSean Christopherson 	if (!pae_root)
3961748e52b9SSean Christopherson 		return -ENOMEM;
3962748e52b9SSean Christopherson 
3963cb0f722aSWei Huang #ifdef CONFIG_X86_64
396403ca4589SSean Christopherson 	pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3965cb0f722aSWei Huang 	if (!pml4_root)
3966cb0f722aSWei Huang 		goto err_pml4;
3967cb0f722aSWei Huang 
3968a717a780SSean Christopherson 	if (need_pml5) {
3969cb0f722aSWei Huang 		pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3970cb0f722aSWei Huang 		if (!pml5_root)
3971cb0f722aSWei Huang 			goto err_pml5;
3972748e52b9SSean Christopherson 	}
3973cb0f722aSWei Huang #endif
3974748e52b9SSean Christopherson 
3975748e52b9SSean Christopherson 	mmu->pae_root = pae_root;
397603ca4589SSean Christopherson 	mmu->pml4_root = pml4_root;
3977cb0f722aSWei Huang 	mmu->pml5_root = pml5_root;
3978748e52b9SSean Christopherson 
3979748e52b9SSean Christopherson 	return 0;
3980cb0f722aSWei Huang 
3981cb0f722aSWei Huang #ifdef CONFIG_X86_64
3982cb0f722aSWei Huang err_pml5:
3983cb0f722aSWei Huang 	free_page((unsigned long)pml4_root);
3984cb0f722aSWei Huang err_pml4:
3985cb0f722aSWei Huang 	free_page((unsigned long)pae_root);
3986cb0f722aSWei Huang 	return -ENOMEM;
3987cb0f722aSWei Huang #endif
3988c50d8ae3SPaolo Bonzini }
3989c50d8ae3SPaolo Bonzini 
3990264d3dc1SLai Jiangshan static bool is_unsync_root(hpa_t root)
3991264d3dc1SLai Jiangshan {
3992264d3dc1SLai Jiangshan 	struct kvm_mmu_page *sp;
3993264d3dc1SLai Jiangshan 
39940e3223d8SSean Christopherson 	if (!VALID_PAGE(root) || kvm_mmu_is_dummy_root(root))
399561b05a9fSLai Jiangshan 		return false;
399661b05a9fSLai Jiangshan 
3997264d3dc1SLai Jiangshan 	/*
3998264d3dc1SLai Jiangshan 	 * The read barrier orders the CPU's read of SPTE.W during the page table
3999264d3dc1SLai Jiangshan 	 * walk before the reads of sp->unsync/sp->unsync_children here.
4000264d3dc1SLai Jiangshan 	 *
4001264d3dc1SLai Jiangshan 	 * Even if another CPU was marking the SP as unsync-ed simultaneously,
4002264d3dc1SLai Jiangshan 	 * any guest page table changes are not guaranteed to be visible anyway
4003264d3dc1SLai Jiangshan 	 * until this VCPU issues a TLB flush strictly after those changes are
4004264d3dc1SLai Jiangshan 	 * made.  We only need to ensure that the other CPU sets these flags
4005264d3dc1SLai Jiangshan 	 * before any actual changes to the page tables are made.  The comments
4006264d3dc1SLai Jiangshan 	 * in mmu_try_to_unsync_pages() describe what could go wrong if this
4007264d3dc1SLai Jiangshan 	 * requirement isn't satisfied.
4008264d3dc1SLai Jiangshan 	 */
4009264d3dc1SLai Jiangshan 	smp_rmb();
4010c5f2d564SSean Christopherson 	sp = root_to_sp(root);
40115d6a3221SSean Christopherson 
40125d6a3221SSean Christopherson 	/*
40135d6a3221SSean Christopherson 	 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
40145d6a3221SSean Christopherson 	 * PDPTEs for a given PAE root need to be synchronized individually.
40155d6a3221SSean Christopherson 	 */
40165d6a3221SSean Christopherson 	if (WARN_ON_ONCE(!sp))
40175d6a3221SSean Christopherson 		return false;
40185d6a3221SSean Christopherson 
4019264d3dc1SLai Jiangshan 	if (sp->unsync || sp->unsync_children)
4020264d3dc1SLai Jiangshan 		return true;
4021264d3dc1SLai Jiangshan 
4022264d3dc1SLai Jiangshan 	return false;
4023264d3dc1SLai Jiangshan }
4024264d3dc1SLai Jiangshan 
4025c50d8ae3SPaolo Bonzini void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
4026c50d8ae3SPaolo Bonzini {
4027c50d8ae3SPaolo Bonzini 	int i;
4028c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
4029c50d8ae3SPaolo Bonzini 
4030347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
4031c50d8ae3SPaolo Bonzini 		return;
4032c50d8ae3SPaolo Bonzini 
4033b9e5603cSPaolo Bonzini 	if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
4034c50d8ae3SPaolo Bonzini 		return;
4035c50d8ae3SPaolo Bonzini 
4036c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4037c50d8ae3SPaolo Bonzini 
40384d25502aSPaolo Bonzini 	if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
4039b9e5603cSPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->root.hpa;
4040c50d8ae3SPaolo Bonzini 
4041264d3dc1SLai Jiangshan 		if (!is_unsync_root(root))
4042c50d8ae3SPaolo Bonzini 			return;
4043c50d8ae3SPaolo Bonzini 
4044c5f2d564SSean Christopherson 		sp = root_to_sp(root);
4045c5f2d564SSean Christopherson 
4046531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
404765855ed8SLai Jiangshan 		mmu_sync_children(vcpu, sp, true);
4048531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
4049c50d8ae3SPaolo Bonzini 		return;
4050c50d8ae3SPaolo Bonzini 	}
4051c50d8ae3SPaolo Bonzini 
4052531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
4053c50d8ae3SPaolo Bonzini 
4054c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
4055c50d8ae3SPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->pae_root[i];
4056c50d8ae3SPaolo Bonzini 
4057c834e5e4SSean Christopherson 		if (IS_VALID_PAE_ROOT(root)) {
40585e3edd7eSSean Christopherson 			sp = spte_to_child_sp(root);
405965855ed8SLai Jiangshan 			mmu_sync_children(vcpu, sp, true);
4060c50d8ae3SPaolo Bonzini 		}
4061c50d8ae3SPaolo Bonzini 	}
4062c50d8ae3SPaolo Bonzini 
4063531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
4064c50d8ae3SPaolo Bonzini }
4065c50d8ae3SPaolo Bonzini 
406661b05a9fSLai Jiangshan void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
406761b05a9fSLai Jiangshan {
406861b05a9fSLai Jiangshan 	unsigned long roots_to_free = 0;
406961b05a9fSLai Jiangshan 	int i;
407061b05a9fSLai Jiangshan 
407161b05a9fSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
407261b05a9fSLai Jiangshan 		if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
407361b05a9fSLai Jiangshan 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
407461b05a9fSLai Jiangshan 
407561b05a9fSLai Jiangshan 	/* sync prev_roots by simply freeing them */
40760c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
407761b05a9fSLai Jiangshan }
407861b05a9fSLai Jiangshan 
40791f5a21eeSLai Jiangshan static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
40805b22bbe7SLai Jiangshan 				  gpa_t vaddr, u64 access,
4081c50d8ae3SPaolo Bonzini 				  struct x86_exception *exception)
4082c50d8ae3SPaolo Bonzini {
4083c50d8ae3SPaolo Bonzini 	if (exception)
4084c50d8ae3SPaolo Bonzini 		exception->error_code = 0;
4085c59a0f57SLai Jiangshan 	return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
4086c50d8ae3SPaolo Bonzini }
4087c50d8ae3SPaolo Bonzini 
4088c50d8ae3SPaolo Bonzini static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4089c50d8ae3SPaolo Bonzini {
4090c50d8ae3SPaolo Bonzini 	/*
4091c50d8ae3SPaolo Bonzini 	 * A nested guest cannot use the MMIO cache if it is using nested
4092c50d8ae3SPaolo Bonzini 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4093c50d8ae3SPaolo Bonzini 	 */
4094c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
4095c50d8ae3SPaolo Bonzini 		return false;
4096c50d8ae3SPaolo Bonzini 
4097c50d8ae3SPaolo Bonzini 	if (direct)
4098c50d8ae3SPaolo Bonzini 		return vcpu_match_mmio_gpa(vcpu, addr);
4099c50d8ae3SPaolo Bonzini 
4100c50d8ae3SPaolo Bonzini 	return vcpu_match_mmio_gva(vcpu, addr);
4101c50d8ae3SPaolo Bonzini }
4102c50d8ae3SPaolo Bonzini 
410395fb5b02SBen Gardon /*
410495fb5b02SBen Gardon  * Return the level of the lowest level SPTE added to sptes.
410595fb5b02SBen Gardon  * That SPTE may be non-present.
4106c5c8c7c5SDavid Matlack  *
4107c5c8c7c5SDavid Matlack  * Must be called between walk_shadow_page_lockless_{begin,end}.
410895fb5b02SBen Gardon  */
410939b4d43eSSean Christopherson static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4110c50d8ae3SPaolo Bonzini {
4111c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
41122aa07893SSean Christopherson 	int leaf = -1;
411395fb5b02SBen Gardon 	u64 spte;
4114c50d8ae3SPaolo Bonzini 
411539b4d43eSSean Christopherson 	for (shadow_walk_init(&iterator, vcpu, addr),
411639b4d43eSSean Christopherson 	     *root_level = iterator.level;
4117c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&iterator);
4118c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&iterator, spte)) {
411995fb5b02SBen Gardon 		leaf = iterator.level;
4120c50d8ae3SPaolo Bonzini 		spte = mmu_spte_get_lockless(iterator.sptep);
4121c50d8ae3SPaolo Bonzini 
4122dde81f94SSean Christopherson 		sptes[leaf] = spte;
412395fb5b02SBen Gardon 	}
412495fb5b02SBen Gardon 
412595fb5b02SBen Gardon 	return leaf;
412695fb5b02SBen Gardon }
412795fb5b02SBen Gardon 
41289aa41879SSean Christopherson /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
412995fb5b02SBen Gardon static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
413095fb5b02SBen Gardon {
4131dde81f94SSean Christopherson 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
413295fb5b02SBen Gardon 	struct rsvd_bits_validate *rsvd_check;
413339b4d43eSSean Christopherson 	int root, leaf, level;
413495fb5b02SBen Gardon 	bool reserved = false;
413595fb5b02SBen Gardon 
4136c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_begin(vcpu);
4137c5c8c7c5SDavid Matlack 
413878fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu))
413939b4d43eSSean Christopherson 		leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
414095fb5b02SBen Gardon 	else
414139b4d43eSSean Christopherson 		leaf = get_walk(vcpu, addr, sptes, &root);
414295fb5b02SBen Gardon 
4143c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_end(vcpu);
4144c5c8c7c5SDavid Matlack 
41452aa07893SSean Christopherson 	if (unlikely(leaf < 0)) {
41462aa07893SSean Christopherson 		*sptep = 0ull;
41472aa07893SSean Christopherson 		return reserved;
41482aa07893SSean Christopherson 	}
41492aa07893SSean Christopherson 
41509aa41879SSean Christopherson 	*sptep = sptes[leaf];
41519aa41879SSean Christopherson 
41529aa41879SSean Christopherson 	/*
41539aa41879SSean Christopherson 	 * Skip reserved bits checks on the terminal leaf if it's not a valid
41549aa41879SSean Christopherson 	 * SPTE.  Note, this also (intentionally) skips MMIO SPTEs, which, by
41559aa41879SSean Christopherson 	 * design, always have reserved bits set.  The purpose of the checks is
41569aa41879SSean Christopherson 	 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
41579aa41879SSean Christopherson 	 */
41589aa41879SSean Christopherson 	if (!is_shadow_present_pte(sptes[leaf]))
41599aa41879SSean Christopherson 		leaf++;
416095fb5b02SBen Gardon 
416195fb5b02SBen Gardon 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
416295fb5b02SBen Gardon 
41639aa41879SSean Christopherson 	for (level = root; level >= leaf; level--)
4164961f8445SSean Christopherson 		reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4165c50d8ae3SPaolo Bonzini 
4166c50d8ae3SPaolo Bonzini 	if (reserved) {
4167bb4cdf3aSSean Christopherson 		pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4168c50d8ae3SPaolo Bonzini 		       __func__, addr);
416995fb5b02SBen Gardon 		for (level = root; level >= leaf; level--)
4170bb4cdf3aSSean Christopherson 			pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4171bb4cdf3aSSean Christopherson 			       sptes[level], level,
4172961f8445SSean Christopherson 			       get_rsvd_bits(rsvd_check, sptes[level], level));
4173c50d8ae3SPaolo Bonzini 	}
4174ddce6208SSean Christopherson 
4175c50d8ae3SPaolo Bonzini 	return reserved;
4176c50d8ae3SPaolo Bonzini }
4177c50d8ae3SPaolo Bonzini 
4178c50d8ae3SPaolo Bonzini static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4179c50d8ae3SPaolo Bonzini {
4180c50d8ae3SPaolo Bonzini 	u64 spte;
4181c50d8ae3SPaolo Bonzini 	bool reserved;
4182c50d8ae3SPaolo Bonzini 
4183c50d8ae3SPaolo Bonzini 	if (mmio_info_in_cache(vcpu, addr, direct))
4184c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4185c50d8ae3SPaolo Bonzini 
418695fb5b02SBen Gardon 	reserved = get_mmio_spte(vcpu, addr, &spte);
418720ba462dSSean Christopherson 	if (WARN_ON_ONCE(reserved))
4188c50d8ae3SPaolo Bonzini 		return -EINVAL;
4189c50d8ae3SPaolo Bonzini 
4190c50d8ae3SPaolo Bonzini 	if (is_mmio_spte(spte)) {
4191c50d8ae3SPaolo Bonzini 		gfn_t gfn = get_mmio_spte_gfn(spte);
41920a2b64c5SBen Gardon 		unsigned int access = get_mmio_spte_access(spte);
4193c50d8ae3SPaolo Bonzini 
4194c50d8ae3SPaolo Bonzini 		if (!check_mmio_spte(vcpu, spte))
4195c50d8ae3SPaolo Bonzini 			return RET_PF_INVALID;
4196c50d8ae3SPaolo Bonzini 
4197c50d8ae3SPaolo Bonzini 		if (direct)
4198c50d8ae3SPaolo Bonzini 			addr = 0;
4199c50d8ae3SPaolo Bonzini 
4200c50d8ae3SPaolo Bonzini 		trace_handle_mmio_page_fault(addr, gfn, access);
4201c50d8ae3SPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4202c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4203c50d8ae3SPaolo Bonzini 	}
4204c50d8ae3SPaolo Bonzini 
4205c50d8ae3SPaolo Bonzini 	/*
4206c50d8ae3SPaolo Bonzini 	 * If the page table is zapped by other cpus, let CPU fault again on
4207c50d8ae3SPaolo Bonzini 	 * the address.
4208c50d8ae3SPaolo Bonzini 	 */
4209c50d8ae3SPaolo Bonzini 	return RET_PF_RETRY;
4210c50d8ae3SPaolo Bonzini }
4211c50d8ae3SPaolo Bonzini 
4212c50d8ae3SPaolo Bonzini static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4213b8a5d551SPaolo Bonzini 					 struct kvm_page_fault *fault)
4214c50d8ae3SPaolo Bonzini {
4215b8a5d551SPaolo Bonzini 	if (unlikely(fault->rsvd))
4216c50d8ae3SPaolo Bonzini 		return false;
4217c50d8ae3SPaolo Bonzini 
4218b8a5d551SPaolo Bonzini 	if (!fault->present || !fault->write)
4219c50d8ae3SPaolo Bonzini 		return false;
4220c50d8ae3SPaolo Bonzini 
4221c50d8ae3SPaolo Bonzini 	/*
4222c50d8ae3SPaolo Bonzini 	 * guest is writing the page which is write tracked which can
4223c50d8ae3SPaolo Bonzini 	 * not be fixed by page fault handler.
4224c50d8ae3SPaolo Bonzini 	 */
42257b574863SSean Christopherson 	if (kvm_gfn_is_write_tracked(vcpu->kvm, fault->slot, fault->gfn))
4226c50d8ae3SPaolo Bonzini 		return true;
4227c50d8ae3SPaolo Bonzini 
4228c50d8ae3SPaolo Bonzini 	return false;
4229c50d8ae3SPaolo Bonzini }
4230c50d8ae3SPaolo Bonzini 
4231c50d8ae3SPaolo Bonzini static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4232c50d8ae3SPaolo Bonzini {
4233c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
4234c50d8ae3SPaolo Bonzini 	u64 spte;
4235c50d8ae3SPaolo Bonzini 
4236c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
42373e44dce4SLai Jiangshan 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4238c50d8ae3SPaolo Bonzini 		clear_sp_write_flooding_count(iterator.sptep);
4239c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
4240c50d8ae3SPaolo Bonzini }
4241c50d8ae3SPaolo Bonzini 
42426f3c1fc5SLiang Zhang static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
42436f3c1fc5SLiang Zhang {
42446f3c1fc5SLiang Zhang 	/* make sure the token value is not 0 */
42456f3c1fc5SLiang Zhang 	u32 id = vcpu->arch.apf.id;
42466f3c1fc5SLiang Zhang 
42476f3c1fc5SLiang Zhang 	if (id << 12 == 0)
42486f3c1fc5SLiang Zhang 		vcpu->arch.apf.id = 1;
42496f3c1fc5SLiang Zhang 
42506f3c1fc5SLiang Zhang 	return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
42516f3c1fc5SLiang Zhang }
42526f3c1fc5SLiang Zhang 
4253e8c22266SVitaly Kuznetsov static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
42549f1a8526SSean Christopherson 				    gfn_t gfn)
4255c50d8ae3SPaolo Bonzini {
4256c50d8ae3SPaolo Bonzini 	struct kvm_arch_async_pf arch;
4257c50d8ae3SPaolo Bonzini 
42586f3c1fc5SLiang Zhang 	arch.token = alloc_apf_token(vcpu);
4259c50d8ae3SPaolo Bonzini 	arch.gfn = gfn;
4260347a0d0dSPaolo Bonzini 	arch.direct_map = vcpu->arch.mmu->root_role.direct;
42612fdcc1b3SPaolo Bonzini 	arch.cr3 = kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu);
4262c50d8ae3SPaolo Bonzini 
42639f1a8526SSean Christopherson 	return kvm_setup_async_pf(vcpu, cr2_or_gpa,
42649f1a8526SSean Christopherson 				  kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4265c50d8ae3SPaolo Bonzini }
4266c50d8ae3SPaolo Bonzini 
42678a009d5bSSean Christopherson void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
42688a009d5bSSean Christopherson {
42698a009d5bSSean Christopherson 	int r;
42708a009d5bSSean Christopherson 
42718a009d5bSSean Christopherson 	if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
42728a009d5bSSean Christopherson 	      work->wakeup_all)
42738a009d5bSSean Christopherson 		return;
42748a009d5bSSean Christopherson 
42758a009d5bSSean Christopherson 	r = kvm_mmu_reload(vcpu);
42768a009d5bSSean Christopherson 	if (unlikely(r))
42778a009d5bSSean Christopherson 		return;
42788a009d5bSSean Christopherson 
42798a009d5bSSean Christopherson 	if (!vcpu->arch.mmu->root_role.direct &&
42802fdcc1b3SPaolo Bonzini 	      work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
42818a009d5bSSean Christopherson 		return;
42828a009d5bSSean Christopherson 
4283258d985fSSean Christopherson 	kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true, NULL);
42848a009d5bSSean Christopherson }
42858a009d5bSSean Christopherson 
4286*8dd2eee9SChao Peng static inline u8 kvm_max_level_for_order(int order)
4287*8dd2eee9SChao Peng {
4288*8dd2eee9SChao Peng 	BUILD_BUG_ON(KVM_MAX_HUGEPAGE_LEVEL > PG_LEVEL_1G);
4289*8dd2eee9SChao Peng 
4290*8dd2eee9SChao Peng 	KVM_MMU_WARN_ON(order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G) &&
4291*8dd2eee9SChao Peng 			order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M) &&
4292*8dd2eee9SChao Peng 			order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_4K));
4293*8dd2eee9SChao Peng 
4294*8dd2eee9SChao Peng 	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G))
4295*8dd2eee9SChao Peng 		return PG_LEVEL_1G;
4296*8dd2eee9SChao Peng 
4297*8dd2eee9SChao Peng 	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M))
4298*8dd2eee9SChao Peng 		return PG_LEVEL_2M;
4299*8dd2eee9SChao Peng 
4300*8dd2eee9SChao Peng 	return PG_LEVEL_4K;
4301*8dd2eee9SChao Peng }
4302*8dd2eee9SChao Peng 
4303*8dd2eee9SChao Peng static void kvm_mmu_prepare_memory_fault_exit(struct kvm_vcpu *vcpu,
4304*8dd2eee9SChao Peng 					      struct kvm_page_fault *fault)
4305*8dd2eee9SChao Peng {
4306*8dd2eee9SChao Peng 	kvm_prepare_memory_fault_exit(vcpu, fault->gfn << PAGE_SHIFT,
4307*8dd2eee9SChao Peng 				      PAGE_SIZE, fault->write, fault->exec,
4308*8dd2eee9SChao Peng 				      fault->is_private);
4309*8dd2eee9SChao Peng }
4310*8dd2eee9SChao Peng 
4311*8dd2eee9SChao Peng static int kvm_faultin_pfn_private(struct kvm_vcpu *vcpu,
4312*8dd2eee9SChao Peng 				   struct kvm_page_fault *fault)
4313*8dd2eee9SChao Peng {
4314*8dd2eee9SChao Peng 	int max_order, r;
4315*8dd2eee9SChao Peng 
4316*8dd2eee9SChao Peng 	if (!kvm_slot_can_be_private(fault->slot)) {
4317*8dd2eee9SChao Peng 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
4318*8dd2eee9SChao Peng 		return -EFAULT;
4319*8dd2eee9SChao Peng 	}
4320*8dd2eee9SChao Peng 
4321*8dd2eee9SChao Peng 	r = kvm_gmem_get_pfn(vcpu->kvm, fault->slot, fault->gfn, &fault->pfn,
4322*8dd2eee9SChao Peng 			     &max_order);
4323*8dd2eee9SChao Peng 	if (r) {
4324*8dd2eee9SChao Peng 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
4325*8dd2eee9SChao Peng 		return r;
4326*8dd2eee9SChao Peng 	}
4327*8dd2eee9SChao Peng 
4328*8dd2eee9SChao Peng 	fault->max_level = min(kvm_max_level_for_order(max_order),
4329*8dd2eee9SChao Peng 			       fault->max_level);
4330*8dd2eee9SChao Peng 	fault->map_writable = !(fault->slot->flags & KVM_MEM_READONLY);
4331*8dd2eee9SChao Peng 
4332*8dd2eee9SChao Peng 	return RET_PF_CONTINUE;
4333*8dd2eee9SChao Peng }
4334*8dd2eee9SChao Peng 
4335ba6e3fe2SDavid Matlack static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4336c50d8ae3SPaolo Bonzini {
4337e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
4338c50d8ae3SPaolo Bonzini 	bool async;
4339c50d8ae3SPaolo Bonzini 
4340e0c37868SSean Christopherson 	/*
4341e0c37868SSean Christopherson 	 * Retry the page fault if the gfn hit a memslot that is being deleted
4342e0c37868SSean Christopherson 	 * or moved.  This ensures any existing SPTEs for the old memslot will
4343e0c37868SSean Christopherson 	 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4344e0c37868SSean Christopherson 	 */
4345e0c37868SSean Christopherson 	if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
43465276c616SSean Christopherson 		return RET_PF_RETRY;
4347e0c37868SSean Christopherson 
43489cc13d60SMaxim Levitsky 	if (!kvm_is_visible_memslot(slot)) {
4349c36b7150SPaolo Bonzini 		/* Don't expose private memslots to L2. */
43509cc13d60SMaxim Levitsky 		if (is_guest_mode(vcpu)) {
4351e710c5f6SDavid Matlack 			fault->slot = NULL;
43523647cd04SPaolo Bonzini 			fault->pfn = KVM_PFN_NOSLOT;
43533647cd04SPaolo Bonzini 			fault->map_writable = false;
43545276c616SSean Christopherson 			return RET_PF_CONTINUE;
4355c50d8ae3SPaolo Bonzini 		}
43569cc13d60SMaxim Levitsky 		/*
43579cc13d60SMaxim Levitsky 		 * If the APIC access page exists but is disabled, go directly
43589cc13d60SMaxim Levitsky 		 * to emulation without caching the MMIO access or creating a
43599cc13d60SMaxim Levitsky 		 * MMIO SPTE.  That way the cache doesn't need to be purged
43609cc13d60SMaxim Levitsky 		 * when the AVIC is re-enabled.
43619cc13d60SMaxim Levitsky 		 */
43629cc13d60SMaxim Levitsky 		if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
43635276c616SSean Christopherson 		    !kvm_apicv_activated(vcpu->kvm))
43645276c616SSean Christopherson 			return RET_PF_EMULATE;
43659cc13d60SMaxim Levitsky 	}
4366c50d8ae3SPaolo Bonzini 
4367*8dd2eee9SChao Peng 	if (fault->is_private != kvm_mem_is_private(vcpu->kvm, fault->gfn)) {
4368*8dd2eee9SChao Peng 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
4369*8dd2eee9SChao Peng 		return -EFAULT;
4370*8dd2eee9SChao Peng 	}
4371*8dd2eee9SChao Peng 
4372*8dd2eee9SChao Peng 	if (fault->is_private)
4373*8dd2eee9SChao Peng 		return kvm_faultin_pfn_private(vcpu, fault);
4374*8dd2eee9SChao Peng 
4375c50d8ae3SPaolo Bonzini 	async = false;
4376c8b88b33SPeter Xu 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, false, &async,
43773647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
43783647cd04SPaolo Bonzini 					  &fault->hva);
4379c50d8ae3SPaolo Bonzini 	if (!async)
43805276c616SSean Christopherson 		return RET_PF_CONTINUE; /* *pfn has correct page already */
4381c50d8ae3SPaolo Bonzini 
43822839180cSPaolo Bonzini 	if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
43833647cd04SPaolo Bonzini 		trace_kvm_try_async_get_page(fault->addr, fault->gfn);
43843647cd04SPaolo Bonzini 		if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
43851685c0f3SMingwei Zhang 			trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4386c50d8ae3SPaolo Bonzini 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
43875276c616SSean Christopherson 			return RET_PF_RETRY;
43885276c616SSean Christopherson 		} else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn)) {
43895276c616SSean Christopherson 			return RET_PF_RETRY;
43905276c616SSean Christopherson 		}
4391c50d8ae3SPaolo Bonzini 	}
4392c50d8ae3SPaolo Bonzini 
439376657687SPeter Xu 	/*
439476657687SPeter Xu 	 * Allow gup to bail on pending non-fatal signals when it's also allowed
439576657687SPeter Xu 	 * to wait for IO.  Note, gup always bails if it is unable to quickly
439676657687SPeter Xu 	 * get a page and a fatal signal, i.e. SIGKILL, is pending.
439776657687SPeter Xu 	 */
439876657687SPeter Xu 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, true, NULL,
43993647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
44003647cd04SPaolo Bonzini 					  &fault->hva);
44015276c616SSean Christopherson 	return RET_PF_CONTINUE;
4402c50d8ae3SPaolo Bonzini }
4403c50d8ae3SPaolo Bonzini 
4404354c908cSDavid Matlack static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
4405354c908cSDavid Matlack 			   unsigned int access)
4406ba6e3fe2SDavid Matlack {
440756c3a4e4SDavid Matlack 	int ret;
440856c3a4e4SDavid Matlack 
4409ba6e3fe2SDavid Matlack 	fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4410ba6e3fe2SDavid Matlack 	smp_rmb();
4411ba6e3fe2SDavid Matlack 
441256c3a4e4SDavid Matlack 	ret = __kvm_faultin_pfn(vcpu, fault);
441356c3a4e4SDavid Matlack 	if (ret != RET_PF_CONTINUE)
441456c3a4e4SDavid Matlack 		return ret;
441556c3a4e4SDavid Matlack 
441656c3a4e4SDavid Matlack 	if (unlikely(is_error_pfn(fault->pfn)))
4417cd08d178SDavid Matlack 		return kvm_handle_error_pfn(vcpu, fault);
441856c3a4e4SDavid Matlack 
4419354c908cSDavid Matlack 	if (unlikely(!fault->slot))
4420354c908cSDavid Matlack 		return kvm_handle_noslot_fault(vcpu, fault, access);
4421354c908cSDavid Matlack 
442256c3a4e4SDavid Matlack 	return RET_PF_CONTINUE;
4423ba6e3fe2SDavid Matlack }
4424ba6e3fe2SDavid Matlack 
4425a955cad8SSean Christopherson /*
4426a955cad8SSean Christopherson  * Returns true if the page fault is stale and needs to be retried, i.e. if the
4427a955cad8SSean Christopherson  * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4428a955cad8SSean Christopherson  */
4429a955cad8SSean Christopherson static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4430ba6e3fe2SDavid Matlack 				struct kvm_page_fault *fault)
4431a955cad8SSean Christopherson {
4432c5f2d564SSean Christopherson 	struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
443318c841e1SSean Christopherson 
443418c841e1SSean Christopherson 	/* Special roots, e.g. pae_root, are not backed by shadow pages. */
443518c841e1SSean Christopherson 	if (sp && is_obsolete_sp(vcpu->kvm, sp))
443618c841e1SSean Christopherson 		return true;
443718c841e1SSean Christopherson 
443818c841e1SSean Christopherson 	/*
443918c841e1SSean Christopherson 	 * Roots without an associated shadow page are considered invalid if
444018c841e1SSean Christopherson 	 * there is a pending request to free obsolete roots.  The request is
444118c841e1SSean Christopherson 	 * only a hint that the current root _may_ be obsolete and needs to be
444218c841e1SSean Christopherson 	 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
444318c841e1SSean Christopherson 	 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
444418c841e1SSean Christopherson 	 * to reload even if no vCPU is actively using the root.
444518c841e1SSean Christopherson 	 */
4446527d5cd7SSean Christopherson 	if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4447a955cad8SSean Christopherson 		return true;
4448a955cad8SSean Christopherson 
4449a955cad8SSean Christopherson 	return fault->slot &&
44508569992dSChao Peng 	       mmu_invalidate_retry_gfn(vcpu->kvm, fault->mmu_seq, fault->gfn);
4451a955cad8SSean Christopherson }
4452a955cad8SSean Christopherson 
44534326e57eSPaolo Bonzini static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4454c50d8ae3SPaolo Bonzini {
445583f06fa7SSean Christopherson 	int r;
4456c50d8ae3SPaolo Bonzini 
44570e3223d8SSean Christopherson 	/* Dummy roots are used only for shadowing bad guest roots. */
44580e3223d8SSean Christopherson 	if (WARN_ON_ONCE(kvm_mmu_is_dummy_root(vcpu->arch.mmu->root.hpa)))
44590e3223d8SSean Christopherson 		return RET_PF_RETRY;
44600e3223d8SSean Christopherson 
4461b8a5d551SPaolo Bonzini 	if (page_fault_handle_page_track(vcpu, fault))
4462c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4463c50d8ae3SPaolo Bonzini 
44643c8ad5a6SPaolo Bonzini 	r = fast_page_fault(vcpu, fault);
4465c4371c2aSSean Christopherson 	if (r != RET_PF_INVALID)
4466c4371c2aSSean Christopherson 		return r;
446783291445SSean Christopherson 
4468378f5cd6SSean Christopherson 	r = mmu_topup_memory_caches(vcpu, false);
4469c50d8ae3SPaolo Bonzini 	if (r)
4470c50d8ae3SPaolo Bonzini 		return r;
4471c50d8ae3SPaolo Bonzini 
4472354c908cSDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
44735276c616SSean Christopherson 	if (r != RET_PF_CONTINUE)
4474367fd790SSean Christopherson 		return r;
4475367fd790SSean Christopherson 
4476367fd790SSean Christopherson 	r = RET_PF_RETRY;
4477531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
4478a2855afcSBen Gardon 
4479ba6e3fe2SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
4480367fd790SSean Christopherson 		goto out_unlock;
4481a955cad8SSean Christopherson 
44827bd7ded6SSean Christopherson 	r = make_mmu_pages_available(vcpu);
44837bd7ded6SSean Christopherson 	if (r)
4484367fd790SSean Christopherson 		goto out_unlock;
4485bb18842eSBen Gardon 
44866c882ef4SDavid Matlack 	r = direct_map(vcpu, fault);
44870f90e1c1SSean Christopherson 
4488367fd790SSean Christopherson out_unlock:
4489531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
44903647cd04SPaolo Bonzini 	kvm_release_pfn_clean(fault->pfn);
4491367fd790SSean Christopherson 	return r;
4492c50d8ae3SPaolo Bonzini }
4493c50d8ae3SPaolo Bonzini 
4494c501040aSPaolo Bonzini static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4495c501040aSPaolo Bonzini 				struct kvm_page_fault *fault)
44960f90e1c1SSean Christopherson {
44970f90e1c1SSean Christopherson 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
44984326e57eSPaolo Bonzini 	fault->max_level = PG_LEVEL_2M;
44994326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
45000f90e1c1SSean Christopherson }
45010f90e1c1SSean Christopherson 
4502c50d8ae3SPaolo Bonzini int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4503c50d8ae3SPaolo Bonzini 				u64 fault_address, char *insn, int insn_len)
4504c50d8ae3SPaolo Bonzini {
4505c50d8ae3SPaolo Bonzini 	int r = 1;
45069ce372b3SVitaly Kuznetsov 	u32 flags = vcpu->arch.apf.host_apf_flags;
4507c50d8ae3SPaolo Bonzini 
4508736c291cSSean Christopherson #ifndef CONFIG_X86_64
4509736c291cSSean Christopherson 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4510736c291cSSean Christopherson 	if (WARN_ON_ONCE(fault_address >> 32))
4511736c291cSSean Christopherson 		return -EFAULT;
4512736c291cSSean Christopherson #endif
4513736c291cSSean Christopherson 
4514c50d8ae3SPaolo Bonzini 	vcpu->arch.l1tf_flush_l1d = true;
45159ce372b3SVitaly Kuznetsov 	if (!flags) {
4516faa03b39SWonhyuk Yang 		trace_kvm_page_fault(vcpu, fault_address, error_code);
4517c50d8ae3SPaolo Bonzini 
4518c50d8ae3SPaolo Bonzini 		if (kvm_event_needs_reinjection(vcpu))
4519c50d8ae3SPaolo Bonzini 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4520c50d8ae3SPaolo Bonzini 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4521c50d8ae3SPaolo Bonzini 				insn_len);
45229ce372b3SVitaly Kuznetsov 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
452368fd66f1SVitaly Kuznetsov 		vcpu->arch.apf.host_apf_flags = 0;
4524c50d8ae3SPaolo Bonzini 		local_irq_disable();
45256bca69adSThomas Gleixner 		kvm_async_pf_task_wait_schedule(fault_address);
4526c50d8ae3SPaolo Bonzini 		local_irq_enable();
45279ce372b3SVitaly Kuznetsov 	} else {
45289ce372b3SVitaly Kuznetsov 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4529c50d8ae3SPaolo Bonzini 	}
45309ce372b3SVitaly Kuznetsov 
4531c50d8ae3SPaolo Bonzini 	return r;
4532c50d8ae3SPaolo Bonzini }
4533c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4534c50d8ae3SPaolo Bonzini 
45359aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
45369aa8ab43SDavid Matlack static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
45379aa8ab43SDavid Matlack 				  struct kvm_page_fault *fault)
45389aa8ab43SDavid Matlack {
45399aa8ab43SDavid Matlack 	int r;
45409aa8ab43SDavid Matlack 
45419aa8ab43SDavid Matlack 	if (page_fault_handle_page_track(vcpu, fault))
45429aa8ab43SDavid Matlack 		return RET_PF_EMULATE;
45439aa8ab43SDavid Matlack 
45449aa8ab43SDavid Matlack 	r = fast_page_fault(vcpu, fault);
45459aa8ab43SDavid Matlack 	if (r != RET_PF_INVALID)
45469aa8ab43SDavid Matlack 		return r;
45479aa8ab43SDavid Matlack 
45489aa8ab43SDavid Matlack 	r = mmu_topup_memory_caches(vcpu, false);
45499aa8ab43SDavid Matlack 	if (r)
45509aa8ab43SDavid Matlack 		return r;
45519aa8ab43SDavid Matlack 
45529aa8ab43SDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
45539aa8ab43SDavid Matlack 	if (r != RET_PF_CONTINUE)
45549aa8ab43SDavid Matlack 		return r;
45559aa8ab43SDavid Matlack 
45569aa8ab43SDavid Matlack 	r = RET_PF_RETRY;
45579aa8ab43SDavid Matlack 	read_lock(&vcpu->kvm->mmu_lock);
45589aa8ab43SDavid Matlack 
45599aa8ab43SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
45609aa8ab43SDavid Matlack 		goto out_unlock;
45619aa8ab43SDavid Matlack 
45629aa8ab43SDavid Matlack 	r = kvm_tdp_mmu_map(vcpu, fault);
45639aa8ab43SDavid Matlack 
45649aa8ab43SDavid Matlack out_unlock:
45659aa8ab43SDavid Matlack 	read_unlock(&vcpu->kvm->mmu_lock);
45669aa8ab43SDavid Matlack 	kvm_release_pfn_clean(fault->pfn);
45679aa8ab43SDavid Matlack 	return r;
45689aa8ab43SDavid Matlack }
45699aa8ab43SDavid Matlack #endif
45709aa8ab43SDavid Matlack 
45711affe455SYan Zhao bool __kvm_mmu_honors_guest_mtrrs(bool vm_has_noncoherent_dma)
45721affe455SYan Zhao {
45731affe455SYan Zhao 	/*
45741affe455SYan Zhao 	 * If host MTRRs are ignored (shadow_memtype_mask is non-zero), and the
45751affe455SYan Zhao 	 * VM has non-coherent DMA (DMA doesn't snoop CPU caches), KVM's ABI is
45761affe455SYan Zhao 	 * to honor the memtype from the guest's MTRRs so that guest accesses
45771affe455SYan Zhao 	 * to memory that is DMA'd aren't cached against the guest's wishes.
45781affe455SYan Zhao 	 *
45791affe455SYan Zhao 	 * Note, KVM may still ultimately ignore guest MTRRs for certain PFNs,
45801affe455SYan Zhao 	 * e.g. KVM will force UC memtype for host MMIO.
45811affe455SYan Zhao 	 */
45821affe455SYan Zhao 	return vm_has_noncoherent_dma && shadow_memtype_mask;
45831affe455SYan Zhao }
45841affe455SYan Zhao 
4585c501040aSPaolo Bonzini int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4586c50d8ae3SPaolo Bonzini {
4587d5e90a69SSean Christopherson 	/*
4588d5e90a69SSean Christopherson 	 * If the guest's MTRRs may be used to compute the "real" memtype,
4589d5e90a69SSean Christopherson 	 * restrict the mapping level to ensure KVM uses a consistent memtype
45901affe455SYan Zhao 	 * across the entire mapping.
4591d5e90a69SSean Christopherson 	 */
45921affe455SYan Zhao 	if (kvm_mmu_honors_guest_mtrrs(vcpu->kvm)) {
4593d5e90a69SSean Christopherson 		for ( ; fault->max_level > PG_LEVEL_4K; --fault->max_level) {
45944326e57eSPaolo Bonzini 			int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
4595c667a3baSHou Wenlong 			gfn_t base = gfn_round_for_level(fault->gfn,
4596c667a3baSHou Wenlong 							 fault->max_level);
4597c50d8ae3SPaolo Bonzini 
4598cb9b88c6SSean Christopherson 			if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4599cb9b88c6SSean Christopherson 				break;
4600d5e90a69SSean Christopherson 		}
4601c50d8ae3SPaolo Bonzini 	}
4602c50d8ae3SPaolo Bonzini 
46039aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
46049aa8ab43SDavid Matlack 	if (tdp_mmu_enabled)
46059aa8ab43SDavid Matlack 		return kvm_tdp_mmu_page_fault(vcpu, fault);
46069aa8ab43SDavid Matlack #endif
46079aa8ab43SDavid Matlack 
46084326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
4609c50d8ae3SPaolo Bonzini }
4610c50d8ae3SPaolo Bonzini 
461184a16226SSean Christopherson static void nonpaging_init_context(struct kvm_mmu *context)
4612c50d8ae3SPaolo Bonzini {
4613c50d8ae3SPaolo Bonzini 	context->page_fault = nonpaging_page_fault;
4614c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4615c3c6c9fcSLai Jiangshan 	context->sync_spte = NULL;
4616c50d8ae3SPaolo Bonzini }
4617c50d8ae3SPaolo Bonzini 
4618be01e8e2SSean Christopherson static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
46190be44352SSean Christopherson 				  union kvm_mmu_page_role role)
46200be44352SSean Christopherson {
4621c30e000eSSean Christopherson 	struct kvm_mmu_page *sp;
4622c30e000eSSean Christopherson 
4623c30e000eSSean Christopherson 	if (!VALID_PAGE(root->hpa))
4624c30e000eSSean Christopherson 		return false;
4625c30e000eSSean Christopherson 
4626c30e000eSSean Christopherson 	if (!role.direct && pgd != root->pgd)
4627c30e000eSSean Christopherson 		return false;
4628c30e000eSSean Christopherson 
4629c30e000eSSean Christopherson 	sp = root_to_sp(root->hpa);
4630c30e000eSSean Christopherson 	if (WARN_ON_ONCE(!sp))
4631c30e000eSSean Christopherson 		return false;
4632c30e000eSSean Christopherson 
4633c30e000eSSean Christopherson 	return role.word == sp->role.word;
46340be44352SSean Christopherson }
46350be44352SSean Christopherson 
4636c50d8ae3SPaolo Bonzini /*
46375499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available,
46385499ea73SPaolo Bonzini  * and insert the current root as the MRU in the cache.
46395499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root and
46405499ea73SPaolo Bonzini  * true is returned.
46415499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid, the LRU root is
46425499ea73SPaolo Bonzini  * evicted to make room for the current root, and false is returned.
4643c50d8ae3SPaolo Bonzini  */
46445499ea73SPaolo Bonzini static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
46455499ea73SPaolo Bonzini 					      gpa_t new_pgd,
4646c50d8ae3SPaolo Bonzini 					      union kvm_mmu_page_role new_role)
4647c50d8ae3SPaolo Bonzini {
4648c50d8ae3SPaolo Bonzini 	uint i;
4649c50d8ae3SPaolo Bonzini 
4650b9e5603cSPaolo Bonzini 	if (is_root_usable(&mmu->root, new_pgd, new_role))
46510be44352SSean Christopherson 		return true;
46520be44352SSean Christopherson 
4653c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
46545499ea73SPaolo Bonzini 		/*
46555499ea73SPaolo Bonzini 		 * The swaps end up rotating the cache like this:
46565499ea73SPaolo Bonzini 		 *   C   0 1 2 3   (on entry to the function)
46575499ea73SPaolo Bonzini 		 *   0   C 1 2 3
46585499ea73SPaolo Bonzini 		 *   1   C 0 2 3
46595499ea73SPaolo Bonzini 		 *   2   C 0 1 3
46605499ea73SPaolo Bonzini 		 *   3   C 0 1 2   (on exit from the loop)
46615499ea73SPaolo Bonzini 		 */
4662b9e5603cSPaolo Bonzini 		swap(mmu->root, mmu->prev_roots[i]);
4663b9e5603cSPaolo Bonzini 		if (is_root_usable(&mmu->root, new_pgd, new_role))
46645499ea73SPaolo Bonzini 			return true;
4665c50d8ae3SPaolo Bonzini 	}
4666c50d8ae3SPaolo Bonzini 
46675499ea73SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
46685499ea73SPaolo Bonzini 	return false;
4669c50d8ae3SPaolo Bonzini }
4670c50d8ae3SPaolo Bonzini 
4671c50d8ae3SPaolo Bonzini /*
46725499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available.
46735499ea73SPaolo Bonzini  * On entry, mmu->root is invalid.
46745499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
46755499ea73SPaolo Bonzini  * of the cache becomes invalid, and true is returned.
46765499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid and false is returned.
46775499ea73SPaolo Bonzini  */
46785499ea73SPaolo Bonzini static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
46795499ea73SPaolo Bonzini 					     gpa_t new_pgd,
46805499ea73SPaolo Bonzini 					     union kvm_mmu_page_role new_role)
46815499ea73SPaolo Bonzini {
46825499ea73SPaolo Bonzini 	uint i;
46835499ea73SPaolo Bonzini 
46845499ea73SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
46855499ea73SPaolo Bonzini 		if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
46865499ea73SPaolo Bonzini 			goto hit;
46875499ea73SPaolo Bonzini 
46885499ea73SPaolo Bonzini 	return false;
46895499ea73SPaolo Bonzini 
46905499ea73SPaolo Bonzini hit:
46915499ea73SPaolo Bonzini 	swap(mmu->root, mmu->prev_roots[i]);
46925499ea73SPaolo Bonzini 	/* Bubble up the remaining roots.  */
46935499ea73SPaolo Bonzini 	for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
46945499ea73SPaolo Bonzini 		mmu->prev_roots[i] = mmu->prev_roots[i + 1];
46955499ea73SPaolo Bonzini 	mmu->prev_roots[i].hpa = INVALID_PAGE;
46965499ea73SPaolo Bonzini 	return true;
46975499ea73SPaolo Bonzini }
46985499ea73SPaolo Bonzini 
46995499ea73SPaolo Bonzini static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
47005499ea73SPaolo Bonzini 			    gpa_t new_pgd, union kvm_mmu_page_role new_role)
47015499ea73SPaolo Bonzini {
47025499ea73SPaolo Bonzini 	/*
47030e3223d8SSean Christopherson 	 * Limit reuse to 64-bit hosts+VMs without "special" roots in order to
47040e3223d8SSean Christopherson 	 * avoid having to deal with PDPTEs and other complexities.
4705c50d8ae3SPaolo Bonzini 	 */
4706c5f2d564SSean Christopherson 	if (VALID_PAGE(mmu->root.hpa) && !root_to_sp(mmu->root.hpa))
47075499ea73SPaolo Bonzini 		kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4708c50d8ae3SPaolo Bonzini 
47095499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa))
47105499ea73SPaolo Bonzini 		return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
47115499ea73SPaolo Bonzini 	else
47125499ea73SPaolo Bonzini 		return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4713c50d8ae3SPaolo Bonzini }
4714c50d8ae3SPaolo Bonzini 
4715d2e5f333SPaolo Bonzini void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4716c50d8ae3SPaolo Bonzini {
47170c1c92f1SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
47187a458f0eSPaolo Bonzini 	union kvm_mmu_page_role new_role = mmu->root_role;
47190c1c92f1SPaolo Bonzini 
4720a7e48ef7SWei Liu 	/*
4721a7e48ef7SWei Liu 	 * Return immediately if no usable root was found, kvm_mmu_reload()
4722a7e48ef7SWei Liu 	 * will establish a valid root prior to the next VM-Enter.
4723a7e48ef7SWei Liu 	 */
4724a7e48ef7SWei Liu 	if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role))
4725b869855bSSean Christopherson 		return;
4726c50d8ae3SPaolo Bonzini 
4727c50d8ae3SPaolo Bonzini 	/*
4728b869855bSSean Christopherson 	 * It's possible that the cached previous root page is obsolete because
4729b869855bSSean Christopherson 	 * of a change in the MMU generation number. However, changing the
4730527d5cd7SSean Christopherson 	 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4731527d5cd7SSean Christopherson 	 * which will free the root set here and allocate a new one.
4732b869855bSSean Christopherson 	 */
4733b869855bSSean Christopherson 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4734b869855bSSean Christopherson 
4735b5129100SSean Christopherson 	if (force_flush_and_sync_on_reuse) {
4736b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4737b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4738b5129100SSean Christopherson 	}
4739b869855bSSean Christopherson 
4740b869855bSSean Christopherson 	/*
4741b869855bSSean Christopherson 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4742b869855bSSean Christopherson 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
4743b869855bSSean Christopherson 	 * valid. So clear any cached MMIO info even when we don't need to sync
4744b869855bSSean Christopherson 	 * the shadow page tables.
4745c50d8ae3SPaolo Bonzini 	 */
4746c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4747c50d8ae3SPaolo Bonzini 
4748daa5b6c1SBen Gardon 	/*
4749daa5b6c1SBen Gardon 	 * If this is a direct root page, it doesn't have a write flooding
4750daa5b6c1SBen Gardon 	 * count. Otherwise, clear the write flooding count.
4751daa5b6c1SBen Gardon 	 */
4752c30e000eSSean Christopherson 	if (!new_role.direct) {
4753c30e000eSSean Christopherson 		struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
4754c30e000eSSean Christopherson 
4755c30e000eSSean Christopherson 		if (!WARN_ON_ONCE(!sp))
4756c30e000eSSean Christopherson 			__clear_sp_write_flooding_count(sp);
4757c30e000eSSean Christopherson 	}
4758c50d8ae3SPaolo Bonzini }
4759be01e8e2SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4760c50d8ae3SPaolo Bonzini 
4761c50d8ae3SPaolo Bonzini static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4762c3e5e415SLai Jiangshan 			   unsigned int access)
4763c50d8ae3SPaolo Bonzini {
4764c50d8ae3SPaolo Bonzini 	if (unlikely(is_mmio_spte(*sptep))) {
4765c50d8ae3SPaolo Bonzini 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4766c50d8ae3SPaolo Bonzini 			mmu_spte_clear_no_track(sptep);
4767c50d8ae3SPaolo Bonzini 			return true;
4768c50d8ae3SPaolo Bonzini 		}
4769c50d8ae3SPaolo Bonzini 
4770c50d8ae3SPaolo Bonzini 		mark_mmio_spte(vcpu, sptep, gfn, access);
4771c50d8ae3SPaolo Bonzini 		return true;
4772c50d8ae3SPaolo Bonzini 	}
4773c50d8ae3SPaolo Bonzini 
4774c50d8ae3SPaolo Bonzini 	return false;
4775c50d8ae3SPaolo Bonzini }
4776c50d8ae3SPaolo Bonzini 
4777c50d8ae3SPaolo Bonzini #define PTTYPE_EPT 18 /* arbitrary */
4778c50d8ae3SPaolo Bonzini #define PTTYPE PTTYPE_EPT
4779c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4780c50d8ae3SPaolo Bonzini #undef PTTYPE
4781c50d8ae3SPaolo Bonzini 
4782c50d8ae3SPaolo Bonzini #define PTTYPE 64
4783c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4784c50d8ae3SPaolo Bonzini #undef PTTYPE
4785c50d8ae3SPaolo Bonzini 
4786c50d8ae3SPaolo Bonzini #define PTTYPE 32
4787c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4788c50d8ae3SPaolo Bonzini #undef PTTYPE
4789c50d8ae3SPaolo Bonzini 
4790f3d90f90SSean Christopherson static void __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
4791f3d90f90SSean Christopherson 				    u64 pa_bits_rsvd, int level, bool nx,
4792f3d90f90SSean Christopherson 				    bool gbpages, bool pse, bool amd)
4793c50d8ae3SPaolo Bonzini {
4794c50d8ae3SPaolo Bonzini 	u64 gbpages_bit_rsvd = 0;
4795c50d8ae3SPaolo Bonzini 	u64 nonleaf_bit8_rsvd = 0;
47965b7f575cSSean Christopherson 	u64 high_bits_rsvd;
4797c50d8ae3SPaolo Bonzini 
4798c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = 0;
4799c50d8ae3SPaolo Bonzini 
4800c50d8ae3SPaolo Bonzini 	if (!gbpages)
4801c50d8ae3SPaolo Bonzini 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4802c50d8ae3SPaolo Bonzini 
48035b7f575cSSean Christopherson 	if (level == PT32E_ROOT_LEVEL)
48045b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
48055b7f575cSSean Christopherson 	else
48065b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
48075b7f575cSSean Christopherson 
48085b7f575cSSean Christopherson 	/* Note, NX doesn't exist in PDPTEs, this is handled below. */
48095b7f575cSSean Christopherson 	if (!nx)
48105b7f575cSSean Christopherson 		high_bits_rsvd |= rsvd_bits(63, 63);
48115b7f575cSSean Christopherson 
4812c50d8ae3SPaolo Bonzini 	/*
4813c50d8ae3SPaolo Bonzini 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4814c50d8ae3SPaolo Bonzini 	 * leaf entries) on AMD CPUs only.
4815c50d8ae3SPaolo Bonzini 	 */
4816c50d8ae3SPaolo Bonzini 	if (amd)
4817c50d8ae3SPaolo Bonzini 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4818c50d8ae3SPaolo Bonzini 
4819c50d8ae3SPaolo Bonzini 	switch (level) {
4820c50d8ae3SPaolo Bonzini 	case PT32_ROOT_LEVEL:
4821c50d8ae3SPaolo Bonzini 		/* no rsvd bits for 2 level 4K page table entries */
4822c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4823c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4824c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4825c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4826c50d8ae3SPaolo Bonzini 
4827c50d8ae3SPaolo Bonzini 		if (!pse) {
4828c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4829c50d8ae3SPaolo Bonzini 			break;
4830c50d8ae3SPaolo Bonzini 		}
4831c50d8ae3SPaolo Bonzini 
4832c50d8ae3SPaolo Bonzini 		if (is_cpuid_PSE36())
4833c50d8ae3SPaolo Bonzini 			/* 36bits PSE 4MB page */
4834c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4835c50d8ae3SPaolo Bonzini 		else
4836c50d8ae3SPaolo Bonzini 			/* 32 bits PSE 4MB page */
4837c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4838c50d8ae3SPaolo Bonzini 		break;
4839c50d8ae3SPaolo Bonzini 	case PT32E_ROOT_LEVEL:
48405b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
48415b7f575cSSean Christopherson 						   high_bits_rsvd |
48425b7f575cSSean Christopherson 						   rsvd_bits(5, 8) |
48435b7f575cSSean Christopherson 						   rsvd_bits(1, 2);	/* PDPTE */
48445b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;	/* PDE */
48455b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;	/* PTE */
48465b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4847c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20);	/* large page */
4848c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4849c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4850c50d8ae3SPaolo Bonzini 		break;
4851c50d8ae3SPaolo Bonzini 	case PT64_ROOT_5LEVEL:
48525b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
48535b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
48545b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
4855c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][4] =
4856c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][4];
4857df561f66SGustavo A. R. Silva 		fallthrough;
4858c50d8ae3SPaolo Bonzini 	case PT64_ROOT_4LEVEL:
48595b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
48605b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
48615b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
48625b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
48635b7f575cSSean Christopherson 						   gbpages_bit_rsvd;
48645b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
48655b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4866c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][3] =
4867c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][3];
48685b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
48695b7f575cSSean Christopherson 						   gbpages_bit_rsvd |
4870c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 29);
48715b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4872c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20); /* large page */
4873c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4874c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4875c50d8ae3SPaolo Bonzini 		break;
4876c50d8ae3SPaolo Bonzini 	}
4877c50d8ae3SPaolo Bonzini }
4878c50d8ae3SPaolo Bonzini 
4879c919e881SKai Huang static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4880c50d8ae3SPaolo Bonzini 					struct kvm_mmu *context)
4881c50d8ae3SPaolo Bonzini {
4882b705a277SSean Christopherson 	__reset_rsvds_bits_mask(&context->guest_rsvd_check,
48835b7f575cSSean Christopherson 				vcpu->arch.reserved_gpa_bits,
48844d25502aSPaolo Bonzini 				context->cpu_role.base.level, is_efer_nx(context),
4885ccf31d6eSSean Christopherson 				guest_can_use(vcpu, X86_FEATURE_GBPAGES),
48864e9c0d80SSean Christopherson 				is_cr4_pse(context),
488723493d0aSSean Christopherson 				guest_cpuid_is_amd_or_hygon(vcpu));
4888c50d8ae3SPaolo Bonzini }
4889c50d8ae3SPaolo Bonzini 
4890f3d90f90SSean Christopherson static void __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4891f3d90f90SSean Christopherson 					u64 pa_bits_rsvd, bool execonly,
4892f3d90f90SSean Christopherson 					int huge_page_level)
4893c50d8ae3SPaolo Bonzini {
48945b7f575cSSean Christopherson 	u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
489584ea5c09SLai Jiangshan 	u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
4896c50d8ae3SPaolo Bonzini 	u64 bad_mt_xwr;
4897c50d8ae3SPaolo Bonzini 
489884ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_1G)
489984ea5c09SLai Jiangshan 		large_1g_rsvd = rsvd_bits(7, 7);
490084ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_2M)
490184ea5c09SLai Jiangshan 		large_2m_rsvd = rsvd_bits(7, 7);
490284ea5c09SLai Jiangshan 
49035b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
49045b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
490584ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
490684ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
49075b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4908c50d8ae3SPaolo Bonzini 
4909c50d8ae3SPaolo Bonzini 	/* large page */
4910c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4911c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
491284ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
491384ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
4914c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4915c50d8ae3SPaolo Bonzini 
4916c50d8ae3SPaolo Bonzini 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
4917c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
4918c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
4919c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
4920c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
4921c50d8ae3SPaolo Bonzini 	if (!execonly) {
4922c50d8ae3SPaolo Bonzini 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
4923c50d8ae3SPaolo Bonzini 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4924c50d8ae3SPaolo Bonzini 	}
4925c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
4926c50d8ae3SPaolo Bonzini }
4927c50d8ae3SPaolo Bonzini 
4928c50d8ae3SPaolo Bonzini static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
492984ea5c09SLai Jiangshan 		struct kvm_mmu *context, bool execonly, int huge_page_level)
4930c50d8ae3SPaolo Bonzini {
4931c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
493284ea5c09SLai Jiangshan 				    vcpu->arch.reserved_gpa_bits, execonly,
493384ea5c09SLai Jiangshan 				    huge_page_level);
4934c50d8ae3SPaolo Bonzini }
4935c50d8ae3SPaolo Bonzini 
49366f8e65a6SSean Christopherson static inline u64 reserved_hpa_bits(void)
49376f8e65a6SSean Christopherson {
49386f8e65a6SSean Christopherson 	return rsvd_bits(shadow_phys_bits, 63);
49396f8e65a6SSean Christopherson }
49406f8e65a6SSean Christopherson 
4941c50d8ae3SPaolo Bonzini /*
4942c50d8ae3SPaolo Bonzini  * the page table on host is the shadow page table for the page
4943c50d8ae3SPaolo Bonzini  * table in guest or amd nested guest, its mmu features completely
4944c50d8ae3SPaolo Bonzini  * follow the features in guest.
4945c50d8ae3SPaolo Bonzini  */
494616be1d12SSean Christopherson static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
494716be1d12SSean Christopherson 					struct kvm_mmu *context)
4948c50d8ae3SPaolo Bonzini {
49498c985b2dSSean Christopherson 	/* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
49508c985b2dSSean Christopherson 	bool is_amd = true;
49518c985b2dSSean Christopherson 	/* KVM doesn't use 2-level page tables for the shadow MMU. */
49528c985b2dSSean Christopherson 	bool is_pse = false;
4953c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4954c50d8ae3SPaolo Bonzini 	int i;
4955c50d8ae3SPaolo Bonzini 
4956a972e29cSPaolo Bonzini 	WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
49578c985b2dSSean Christopherson 
4958c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4959b705a277SSean Christopherson 	__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4960a972e29cSPaolo Bonzini 				context->root_role.level,
49617a458f0eSPaolo Bonzini 				context->root_role.efer_nx,
4962ccf31d6eSSean Christopherson 				guest_can_use(vcpu, X86_FEATURE_GBPAGES),
4963ccf31d6eSSean Christopherson 				is_pse, is_amd);
4964c50d8ae3SPaolo Bonzini 
4965c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4966c50d8ae3SPaolo Bonzini 		return;
4967c50d8ae3SPaolo Bonzini 
4968a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
4969e54f1ff2SKai Huang 		/*
4970e54f1ff2SKai Huang 		 * So far shadow_me_value is a constant during KVM's life
4971e54f1ff2SKai Huang 		 * time.  Bits in shadow_me_value are allowed to be set.
4972e54f1ff2SKai Huang 		 * Bits in shadow_me_mask but not in shadow_me_value are
4973e54f1ff2SKai Huang 		 * not allowed to be set.
4974e54f1ff2SKai Huang 		 */
4975e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
4976e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
4977e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
4978e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
4979c50d8ae3SPaolo Bonzini 	}
4980c50d8ae3SPaolo Bonzini 
4981c50d8ae3SPaolo Bonzini }
4982c50d8ae3SPaolo Bonzini 
4983c50d8ae3SPaolo Bonzini static inline bool boot_cpu_is_amd(void)
4984c50d8ae3SPaolo Bonzini {
4985c50d8ae3SPaolo Bonzini 	WARN_ON_ONCE(!tdp_enabled);
4986c50d8ae3SPaolo Bonzini 	return shadow_x_mask == 0;
4987c50d8ae3SPaolo Bonzini }
4988c50d8ae3SPaolo Bonzini 
4989c50d8ae3SPaolo Bonzini /*
4990c50d8ae3SPaolo Bonzini  * the direct page table on host, use as much mmu features as
4991c50d8ae3SPaolo Bonzini  * possible, however, kvm currently does not do execution-protection.
4992c50d8ae3SPaolo Bonzini  */
4993f3d90f90SSean Christopherson static void reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
4994c50d8ae3SPaolo Bonzini {
4995c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4996c50d8ae3SPaolo Bonzini 	int i;
4997c50d8ae3SPaolo Bonzini 
4998c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4999c50d8ae3SPaolo Bonzini 
5000c50d8ae3SPaolo Bonzini 	if (boot_cpu_is_amd())
5001b705a277SSean Christopherson 		__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
50026c6ab524SSean Christopherson 					context->root_role.level, true,
5003c50d8ae3SPaolo Bonzini 					boot_cpu_has(X86_FEATURE_GBPAGES),
50048c985b2dSSean Christopherson 					false, true);
5005c50d8ae3SPaolo Bonzini 	else
5006c50d8ae3SPaolo Bonzini 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
500784ea5c09SLai Jiangshan 					    reserved_hpa_bits(), false,
500884ea5c09SLai Jiangshan 					    max_huge_page_level);
5009c50d8ae3SPaolo Bonzini 
5010c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
5011c50d8ae3SPaolo Bonzini 		return;
5012c50d8ae3SPaolo Bonzini 
5013a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
5014c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
5015c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
5016c50d8ae3SPaolo Bonzini 	}
5017c50d8ae3SPaolo Bonzini }
5018c50d8ae3SPaolo Bonzini 
5019c50d8ae3SPaolo Bonzini /*
5020c50d8ae3SPaolo Bonzini  * as the comments in reset_shadow_zero_bits_mask() except it
5021c50d8ae3SPaolo Bonzini  * is the shadow page table for intel nested guest.
5022c50d8ae3SPaolo Bonzini  */
5023c50d8ae3SPaolo Bonzini static void
5024e8f6e738SJinrong Liang reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
5025c50d8ae3SPaolo Bonzini {
5026c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
502784ea5c09SLai Jiangshan 				    reserved_hpa_bits(), execonly,
502884ea5c09SLai Jiangshan 				    max_huge_page_level);
5029c50d8ae3SPaolo Bonzini }
5030c50d8ae3SPaolo Bonzini 
5031c50d8ae3SPaolo Bonzini #define BYTE_MASK(access) \
5032c50d8ae3SPaolo Bonzini 	((1 & (access) ? 2 : 0) | \
5033c50d8ae3SPaolo Bonzini 	 (2 & (access) ? 4 : 0) | \
5034c50d8ae3SPaolo Bonzini 	 (3 & (access) ? 8 : 0) | \
5035c50d8ae3SPaolo Bonzini 	 (4 & (access) ? 16 : 0) | \
5036c50d8ae3SPaolo Bonzini 	 (5 & (access) ? 32 : 0) | \
5037c50d8ae3SPaolo Bonzini 	 (6 & (access) ? 64 : 0) | \
5038c50d8ae3SPaolo Bonzini 	 (7 & (access) ? 128 : 0))
5039c50d8ae3SPaolo Bonzini 
5040c50d8ae3SPaolo Bonzini 
5041c596f147SSean Christopherson static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
5042c50d8ae3SPaolo Bonzini {
5043c50d8ae3SPaolo Bonzini 	unsigned byte;
5044c50d8ae3SPaolo Bonzini 
5045c50d8ae3SPaolo Bonzini 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
5046c50d8ae3SPaolo Bonzini 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
5047c50d8ae3SPaolo Bonzini 	const u8 u = BYTE_MASK(ACC_USER_MASK);
5048c50d8ae3SPaolo Bonzini 
5049c596f147SSean Christopherson 	bool cr4_smep = is_cr4_smep(mmu);
5050c596f147SSean Christopherson 	bool cr4_smap = is_cr4_smap(mmu);
5051c596f147SSean Christopherson 	bool cr0_wp = is_cr0_wp(mmu);
505290599c28SSean Christopherson 	bool efer_nx = is_efer_nx(mmu);
5053c50d8ae3SPaolo Bonzini 
5054c50d8ae3SPaolo Bonzini 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
5055c50d8ae3SPaolo Bonzini 		unsigned pfec = byte << 1;
5056c50d8ae3SPaolo Bonzini 
5057c50d8ae3SPaolo Bonzini 		/*
5058c50d8ae3SPaolo Bonzini 		 * Each "*f" variable has a 1 bit for each UWX value
5059c50d8ae3SPaolo Bonzini 		 * that causes a fault with the given PFEC.
5060c50d8ae3SPaolo Bonzini 		 */
5061c50d8ae3SPaolo Bonzini 
5062c50d8ae3SPaolo Bonzini 		/* Faults from writes to non-writable pages */
5063c50d8ae3SPaolo Bonzini 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
5064c50d8ae3SPaolo Bonzini 		/* Faults from user mode accesses to supervisor pages */
5065c50d8ae3SPaolo Bonzini 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
5066c50d8ae3SPaolo Bonzini 		/* Faults from fetches of non-executable pages*/
5067c50d8ae3SPaolo Bonzini 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
5068c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode fetches of user pages */
5069c50d8ae3SPaolo Bonzini 		u8 smepf = 0;
5070c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode accesses of user pages */
5071c50d8ae3SPaolo Bonzini 		u8 smapf = 0;
5072c50d8ae3SPaolo Bonzini 
5073c50d8ae3SPaolo Bonzini 		if (!ept) {
5074c50d8ae3SPaolo Bonzini 			/* Faults from kernel mode accesses to user pages */
5075c50d8ae3SPaolo Bonzini 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
5076c50d8ae3SPaolo Bonzini 
5077c50d8ae3SPaolo Bonzini 			/* Not really needed: !nx will cause pte.nx to fault */
507890599c28SSean Christopherson 			if (!efer_nx)
5079c50d8ae3SPaolo Bonzini 				ff = 0;
5080c50d8ae3SPaolo Bonzini 
5081c50d8ae3SPaolo Bonzini 			/* Allow supervisor writes if !cr0.wp */
5082c50d8ae3SPaolo Bonzini 			if (!cr0_wp)
5083c50d8ae3SPaolo Bonzini 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
5084c50d8ae3SPaolo Bonzini 
5085c50d8ae3SPaolo Bonzini 			/* Disallow supervisor fetches of user code if cr4.smep */
5086c50d8ae3SPaolo Bonzini 			if (cr4_smep)
5087c50d8ae3SPaolo Bonzini 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
5088c50d8ae3SPaolo Bonzini 
5089c50d8ae3SPaolo Bonzini 			/*
5090c50d8ae3SPaolo Bonzini 			 * SMAP:kernel-mode data accesses from user-mode
5091c50d8ae3SPaolo Bonzini 			 * mappings should fault. A fault is considered
5092c50d8ae3SPaolo Bonzini 			 * as a SMAP violation if all of the following
5093c50d8ae3SPaolo Bonzini 			 * conditions are true:
5094c50d8ae3SPaolo Bonzini 			 *   - X86_CR4_SMAP is set in CR4
5095c50d8ae3SPaolo Bonzini 			 *   - A user page is accessed
5096c50d8ae3SPaolo Bonzini 			 *   - The access is not a fetch
50974f4aa80eSLai Jiangshan 			 *   - The access is supervisor mode
50984f4aa80eSLai Jiangshan 			 *   - If implicit supervisor access or X86_EFLAGS_AC is clear
5099c50d8ae3SPaolo Bonzini 			 *
510094b4a2f1SLai Jiangshan 			 * Here, we cover the first four conditions.
510194b4a2f1SLai Jiangshan 			 * The fifth is computed dynamically in permission_fault();
5102c50d8ae3SPaolo Bonzini 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
5103c50d8ae3SPaolo Bonzini 			 * *not* subject to SMAP restrictions.
5104c50d8ae3SPaolo Bonzini 			 */
5105c50d8ae3SPaolo Bonzini 			if (cr4_smap)
5106c50d8ae3SPaolo Bonzini 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
5107c50d8ae3SPaolo Bonzini 		}
5108c50d8ae3SPaolo Bonzini 
5109c50d8ae3SPaolo Bonzini 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
5110c50d8ae3SPaolo Bonzini 	}
5111c50d8ae3SPaolo Bonzini }
5112c50d8ae3SPaolo Bonzini 
5113c50d8ae3SPaolo Bonzini /*
5114c50d8ae3SPaolo Bonzini * PKU is an additional mechanism by which the paging controls access to
5115c50d8ae3SPaolo Bonzini * user-mode addresses based on the value in the PKRU register.  Protection
5116c50d8ae3SPaolo Bonzini * key violations are reported through a bit in the page fault error code.
5117c50d8ae3SPaolo Bonzini * Unlike other bits of the error code, the PK bit is not known at the
5118c50d8ae3SPaolo Bonzini * call site of e.g. gva_to_gpa; it must be computed directly in
5119c50d8ae3SPaolo Bonzini * permission_fault based on two bits of PKRU, on some machine state (CR4,
5120c50d8ae3SPaolo Bonzini * CR0, EFER, CPL), and on other bits of the error code and the page tables.
5121c50d8ae3SPaolo Bonzini *
5122c50d8ae3SPaolo Bonzini * In particular the following conditions come from the error code, the
5123c50d8ae3SPaolo Bonzini * page tables and the machine state:
5124c50d8ae3SPaolo Bonzini * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
5125c50d8ae3SPaolo Bonzini * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
5126c50d8ae3SPaolo Bonzini * - PK is always zero if U=0 in the page tables
5127c50d8ae3SPaolo Bonzini * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
5128c50d8ae3SPaolo Bonzini *
5129c50d8ae3SPaolo Bonzini * The PKRU bitmask caches the result of these four conditions.  The error
5130c50d8ae3SPaolo Bonzini * code (minus the P bit) and the page table's U bit form an index into the
5131c50d8ae3SPaolo Bonzini * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
5132c50d8ae3SPaolo Bonzini * with the two bits of the PKRU register corresponding to the protection key.
5133c50d8ae3SPaolo Bonzini * For the first three conditions above the bits will be 00, thus masking
5134c50d8ae3SPaolo Bonzini * away both AD and WD.  For all reads or if the last condition holds, WD
5135c50d8ae3SPaolo Bonzini * only will be masked away.
5136c50d8ae3SPaolo Bonzini */
51372e4c0661SSean Christopherson static void update_pkru_bitmask(struct kvm_mmu *mmu)
5138c50d8ae3SPaolo Bonzini {
5139c50d8ae3SPaolo Bonzini 	unsigned bit;
5140c50d8ae3SPaolo Bonzini 	bool wp;
5141c50d8ae3SPaolo Bonzini 
5142c50d8ae3SPaolo Bonzini 	mmu->pkru_mask = 0;
5143a3ca5281SChenyi Qiang 
5144a3ca5281SChenyi Qiang 	if (!is_cr4_pke(mmu))
5145c50d8ae3SPaolo Bonzini 		return;
5146c50d8ae3SPaolo Bonzini 
51472e4c0661SSean Christopherson 	wp = is_cr0_wp(mmu);
5148c50d8ae3SPaolo Bonzini 
5149c50d8ae3SPaolo Bonzini 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5150c50d8ae3SPaolo Bonzini 		unsigned pfec, pkey_bits;
5151c50d8ae3SPaolo Bonzini 		bool check_pkey, check_write, ff, uf, wf, pte_user;
5152c50d8ae3SPaolo Bonzini 
5153c50d8ae3SPaolo Bonzini 		pfec = bit << 1;
5154c50d8ae3SPaolo Bonzini 		ff = pfec & PFERR_FETCH_MASK;
5155c50d8ae3SPaolo Bonzini 		uf = pfec & PFERR_USER_MASK;
5156c50d8ae3SPaolo Bonzini 		wf = pfec & PFERR_WRITE_MASK;
5157c50d8ae3SPaolo Bonzini 
5158c50d8ae3SPaolo Bonzini 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
5159c50d8ae3SPaolo Bonzini 		pte_user = pfec & PFERR_RSVD_MASK;
5160c50d8ae3SPaolo Bonzini 
5161c50d8ae3SPaolo Bonzini 		/*
5162c50d8ae3SPaolo Bonzini 		 * Only need to check the access which is not an
5163c50d8ae3SPaolo Bonzini 		 * instruction fetch and is to a user page.
5164c50d8ae3SPaolo Bonzini 		 */
5165c50d8ae3SPaolo Bonzini 		check_pkey = (!ff && pte_user);
5166c50d8ae3SPaolo Bonzini 		/*
5167c50d8ae3SPaolo Bonzini 		 * write access is controlled by PKRU if it is a
5168c50d8ae3SPaolo Bonzini 		 * user access or CR0.WP = 1.
5169c50d8ae3SPaolo Bonzini 		 */
5170c50d8ae3SPaolo Bonzini 		check_write = check_pkey && wf && (uf || wp);
5171c50d8ae3SPaolo Bonzini 
5172c50d8ae3SPaolo Bonzini 		/* PKRU.AD stops both read and write access. */
5173c50d8ae3SPaolo Bonzini 		pkey_bits = !!check_pkey;
5174c50d8ae3SPaolo Bonzini 		/* PKRU.WD stops write access. */
5175c50d8ae3SPaolo Bonzini 		pkey_bits |= (!!check_write) << 1;
5176c50d8ae3SPaolo Bonzini 
5177c50d8ae3SPaolo Bonzini 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5178c50d8ae3SPaolo Bonzini 	}
5179c50d8ae3SPaolo Bonzini }
5180c50d8ae3SPaolo Bonzini 
5181533f9a4bSSean Christopherson static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5182533f9a4bSSean Christopherson 					struct kvm_mmu *mmu)
5183c50d8ae3SPaolo Bonzini {
5184533f9a4bSSean Christopherson 	if (!is_cr0_pg(mmu))
5185533f9a4bSSean Christopherson 		return;
5186c50d8ae3SPaolo Bonzini 
5187c919e881SKai Huang 	reset_guest_rsvds_bits_mask(vcpu, mmu);
5188533f9a4bSSean Christopherson 	update_permission_bitmask(mmu, false);
5189533f9a4bSSean Christopherson 	update_pkru_bitmask(mmu);
5190c50d8ae3SPaolo Bonzini }
5191c50d8ae3SPaolo Bonzini 
5192fe660f72SSean Christopherson static void paging64_init_context(struct kvm_mmu *context)
5193c50d8ae3SPaolo Bonzini {
5194c50d8ae3SPaolo Bonzini 	context->page_fault = paging64_page_fault;
5195c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging64_gva_to_gpa;
5196c3c6c9fcSLai Jiangshan 	context->sync_spte = paging64_sync_spte;
5197c50d8ae3SPaolo Bonzini }
5198c50d8ae3SPaolo Bonzini 
519984a16226SSean Christopherson static void paging32_init_context(struct kvm_mmu *context)
5200c50d8ae3SPaolo Bonzini {
5201c50d8ae3SPaolo Bonzini 	context->page_fault = paging32_page_fault;
5202c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging32_gva_to_gpa;
5203c3c6c9fcSLai Jiangshan 	context->sync_spte = paging32_sync_spte;
5204c50d8ae3SPaolo Bonzini }
5205c50d8ae3SPaolo Bonzini 
5206f3d90f90SSean Christopherson static union kvm_cpu_role kvm_calc_cpu_role(struct kvm_vcpu *vcpu,
5207f3d90f90SSean Christopherson 					    const struct kvm_mmu_role_regs *regs)
5208e5ed0fb0SPaolo Bonzini {
52097a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5210e5ed0fb0SPaolo Bonzini 
5211e5ed0fb0SPaolo Bonzini 	role.base.access = ACC_ALL;
5212e5ed0fb0SPaolo Bonzini 	role.base.smm = is_smm(vcpu);
5213e5ed0fb0SPaolo Bonzini 	role.base.guest_mode = is_guest_mode(vcpu);
5214e5ed0fb0SPaolo Bonzini 	role.ext.valid = 1;
5215e5ed0fb0SPaolo Bonzini 
5216e5ed0fb0SPaolo Bonzini 	if (!____is_cr0_pg(regs)) {
5217e5ed0fb0SPaolo Bonzini 		role.base.direct = 1;
5218e5ed0fb0SPaolo Bonzini 		return role;
5219e5ed0fb0SPaolo Bonzini 	}
5220e5ed0fb0SPaolo Bonzini 
5221e5ed0fb0SPaolo Bonzini 	role.base.efer_nx = ____is_efer_nx(regs);
5222e5ed0fb0SPaolo Bonzini 	role.base.cr0_wp = ____is_cr0_wp(regs);
5223e5ed0fb0SPaolo Bonzini 	role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5224e5ed0fb0SPaolo Bonzini 	role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5225e5ed0fb0SPaolo Bonzini 	role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
522660f3cb60SPaolo Bonzini 
522760f3cb60SPaolo Bonzini 	if (____is_efer_lma(regs))
522860f3cb60SPaolo Bonzini 		role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
522960f3cb60SPaolo Bonzini 							: PT64_ROOT_4LEVEL;
523060f3cb60SPaolo Bonzini 	else if (____is_cr4_pae(regs))
523160f3cb60SPaolo Bonzini 		role.base.level = PT32E_ROOT_LEVEL;
523260f3cb60SPaolo Bonzini 	else
523360f3cb60SPaolo Bonzini 		role.base.level = PT32_ROOT_LEVEL;
5234e5ed0fb0SPaolo Bonzini 
5235e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smep = ____is_cr4_smep(regs);
5236e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smap = ____is_cr4_smap(regs);
5237e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pse = ____is_cr4_pse(regs);
5238e5ed0fb0SPaolo Bonzini 
5239e5ed0fb0SPaolo Bonzini 	/* PKEY and LA57 are active iff long mode is active. */
5240e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5241e5ed0fb0SPaolo Bonzini 	role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5242e5ed0fb0SPaolo Bonzini 	role.ext.efer_lma = ____is_efer_lma(regs);
5243e5ed0fb0SPaolo Bonzini 	return role;
5244e5ed0fb0SPaolo Bonzini }
5245e5ed0fb0SPaolo Bonzini 
5246cf9f4c0eSSean Christopherson void __kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
5247cf9f4c0eSSean Christopherson 					struct kvm_mmu *mmu)
5248cf9f4c0eSSean Christopherson {
5249cf9f4c0eSSean Christopherson 	const bool cr0_wp = kvm_is_cr0_bit_set(vcpu, X86_CR0_WP);
5250cf9f4c0eSSean Christopherson 
5251cf9f4c0eSSean Christopherson 	BUILD_BUG_ON((KVM_MMU_CR0_ROLE_BITS & KVM_POSSIBLE_CR0_GUEST_BITS) != X86_CR0_WP);
5252cf9f4c0eSSean Christopherson 	BUILD_BUG_ON((KVM_MMU_CR4_ROLE_BITS & KVM_POSSIBLE_CR4_GUEST_BITS));
5253cf9f4c0eSSean Christopherson 
5254cf9f4c0eSSean Christopherson 	if (is_cr0_wp(mmu) == cr0_wp)
5255cf9f4c0eSSean Christopherson 		return;
5256cf9f4c0eSSean Christopherson 
5257cf9f4c0eSSean Christopherson 	mmu->cpu_role.base.cr0_wp = cr0_wp;
5258cf9f4c0eSSean Christopherson 	reset_guest_paging_metadata(vcpu, mmu);
5259cf9f4c0eSSean Christopherson }
5260cf9f4c0eSSean Christopherson 
5261d468d94bSSean Christopherson static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5262d468d94bSSean Christopherson {
5263746700d2SWei Huang 	/* tdp_root_level is architecture forced level, use it if nonzero */
5264746700d2SWei Huang 	if (tdp_root_level)
5265746700d2SWei Huang 		return tdp_root_level;
5266746700d2SWei Huang 
5267d468d94bSSean Christopherson 	/* Use 5-level TDP if and only if it's useful/necessary. */
526883013059SSean Christopherson 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5269d468d94bSSean Christopherson 		return 4;
5270d468d94bSSean Christopherson 
527183013059SSean Christopherson 	return max_tdp_level;
5272d468d94bSSean Christopherson }
5273d468d94bSSean Christopherson 
52747a458f0eSPaolo Bonzini static union kvm_mmu_page_role
52758626c120SSean Christopherson kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
52767a7ae829SPaolo Bonzini 				union kvm_cpu_role cpu_role)
5277c50d8ae3SPaolo Bonzini {
52787a458f0eSPaolo Bonzini 	union kvm_mmu_page_role role = {0};
5279c50d8ae3SPaolo Bonzini 
52807a458f0eSPaolo Bonzini 	role.access = ACC_ALL;
52817a458f0eSPaolo Bonzini 	role.cr0_wp = true;
52827a458f0eSPaolo Bonzini 	role.efer_nx = true;
52837a458f0eSPaolo Bonzini 	role.smm = cpu_role.base.smm;
52847a458f0eSPaolo Bonzini 	role.guest_mode = cpu_role.base.guest_mode;
528554275f74SSean Christopherson 	role.ad_disabled = !kvm_ad_enabled();
52867a458f0eSPaolo Bonzini 	role.level = kvm_mmu_get_tdp_level(vcpu);
52877a458f0eSPaolo Bonzini 	role.direct = true;
52887a458f0eSPaolo Bonzini 	role.has_4_byte_gpte = false;
5289c50d8ae3SPaolo Bonzini 
5290c50d8ae3SPaolo Bonzini 	return role;
5291c50d8ae3SPaolo Bonzini }
5292c50d8ae3SPaolo Bonzini 
529339e7e2bfSPaolo Bonzini static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5294a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5295c50d8ae3SPaolo Bonzini {
52968c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
52977a458f0eSPaolo Bonzini 	union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5298c50d8ae3SPaolo Bonzini 
5299e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
53007a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
5301c50d8ae3SPaolo Bonzini 		return;
5302c50d8ae3SPaolo Bonzini 
5303e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
53047a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
53057a02674dSSean Christopherson 	context->page_fault = kvm_tdp_page_fault;
5306c3c6c9fcSLai Jiangshan 	context->sync_spte = NULL;
53072fdcc1b3SPaolo Bonzini 	context->get_guest_pgd = get_guest_cr3;
5308c50d8ae3SPaolo Bonzini 	context->get_pdptr = kvm_pdptr_read;
5309c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5310c50d8ae3SPaolo Bonzini 
531136f26787SSean Christopherson 	if (!is_cr0_pg(context))
5312c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = nonpaging_gva_to_gpa;
531336f26787SSean Christopherson 	else if (is_cr4_pae(context))
5314c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging64_gva_to_gpa;
5315f4bd6f73SSean Christopherson 	else
5316c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging32_gva_to_gpa;
5317c50d8ae3SPaolo Bonzini 
5318533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5319e8f6e738SJinrong Liang 	reset_tdp_shadow_zero_bits_mask(context);
5320c50d8ae3SPaolo Bonzini }
5321c50d8ae3SPaolo Bonzini 
53228c008659SPaolo Bonzini static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
53237a7ae829SPaolo Bonzini 				    union kvm_cpu_role cpu_role,
53247a458f0eSPaolo Bonzini 				    union kvm_mmu_page_role root_role)
5325c50d8ae3SPaolo Bonzini {
5326e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
53277a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
532818db1b17SSean Christopherson 		return;
5329c50d8ae3SPaolo Bonzini 
5330e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
53317a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
533218db1b17SSean Christopherson 
533336f26787SSean Christopherson 	if (!is_cr0_pg(context))
533484a16226SSean Christopherson 		nonpaging_init_context(context);
533536f26787SSean Christopherson 	else if (is_cr4_pae(context))
5336fe660f72SSean Christopherson 		paging64_init_context(context);
5337c50d8ae3SPaolo Bonzini 	else
533884a16226SSean Christopherson 		paging32_init_context(context);
5339c50d8ae3SPaolo Bonzini 
5340533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5341c50d8ae3SPaolo Bonzini 	reset_shadow_zero_bits_mask(vcpu, context);
5342c50d8ae3SPaolo Bonzini }
53430f04a2acSVitaly Kuznetsov 
5344594e91a1SSean Christopherson static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5345a7f1de9bSPaolo Bonzini 				union kvm_cpu_role cpu_role)
53460f04a2acSVitaly Kuznetsov {
53478c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
534856b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
534956b321f9SPaolo Bonzini 
535056b321f9SPaolo Bonzini 	root_role = cpu_role.base;
535156b321f9SPaolo Bonzini 
535256b321f9SPaolo Bonzini 	/* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
535356b321f9SPaolo Bonzini 	root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
535456b321f9SPaolo Bonzini 
535556b321f9SPaolo Bonzini 	/*
535656b321f9SPaolo Bonzini 	 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
535756b321f9SPaolo Bonzini 	 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
535856b321f9SPaolo Bonzini 	 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
535956b321f9SPaolo Bonzini 	 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
536056b321f9SPaolo Bonzini 	 * The iTLB multi-hit workaround can be toggled at any time, so assume
536156b321f9SPaolo Bonzini 	 * NX can be used by any non-nested shadow MMU to avoid having to reset
536256b321f9SPaolo Bonzini 	 * MMU contexts.
536356b321f9SPaolo Bonzini 	 */
536456b321f9SPaolo Bonzini 	root_role.efer_nx = true;
53650f04a2acSVitaly Kuznetsov 
53667a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
53670f04a2acSVitaly Kuznetsov }
53680f04a2acSVitaly Kuznetsov 
5369dbc4739bSSean Christopherson void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5370dbc4739bSSean Christopherson 			     unsigned long cr4, u64 efer, gpa_t nested_cr3)
53710f04a2acSVitaly Kuznetsov {
53728c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5373594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
5374594e91a1SSean Christopherson 		.cr0 = cr0,
537528f091bcSPaolo Bonzini 		.cr4 = cr4 & ~X86_CR4_PKE,
5376594e91a1SSean Christopherson 		.efer = efer,
5377594e91a1SSean Christopherson 	};
53787a7ae829SPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
537956b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
538056b321f9SPaolo Bonzini 
538156b321f9SPaolo Bonzini 	/* NPT requires CR0.PG=1. */
538256b321f9SPaolo Bonzini 	WARN_ON_ONCE(cpu_role.base.direct);
538356b321f9SPaolo Bonzini 
538456b321f9SPaolo Bonzini 	root_role = cpu_role.base;
538556b321f9SPaolo Bonzini 	root_role.level = kvm_mmu_get_tdp_level(vcpu);
538684e5ffd0SLai Jiangshan 	if (root_role.level == PT64_ROOT_5LEVEL &&
538784e5ffd0SLai Jiangshan 	    cpu_role.base.level == PT64_ROOT_4LEVEL)
538884e5ffd0SLai Jiangshan 		root_role.passthrough = 1;
53890f04a2acSVitaly Kuznetsov 
53907a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5391d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, nested_cr3);
53920f04a2acSVitaly Kuznetsov }
53930f04a2acSVitaly Kuznetsov EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5394c50d8ae3SPaolo Bonzini 
53957a7ae829SPaolo Bonzini static union kvm_cpu_role
5396c50d8ae3SPaolo Bonzini kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5397bb1fcc70SSean Christopherson 				   bool execonly, u8 level)
5398c50d8ae3SPaolo Bonzini {
53997a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5400c50d8ae3SPaolo Bonzini 
5401daed87b8SPaolo Bonzini 	/*
5402daed87b8SPaolo Bonzini 	 * KVM does not support SMM transfer monitors, and consequently does not
5403daed87b8SPaolo Bonzini 	 * support the "entry to SMM" control either.  role.base.smm is always 0.
5404daed87b8SPaolo Bonzini 	 */
5405daed87b8SPaolo Bonzini 	WARN_ON_ONCE(is_smm(vcpu));
5406bb1fcc70SSean Christopherson 	role.base.level = level;
5407bb3b394dSLai Jiangshan 	role.base.has_4_byte_gpte = false;
5408c50d8ae3SPaolo Bonzini 	role.base.direct = false;
5409c50d8ae3SPaolo Bonzini 	role.base.ad_disabled = !accessed_dirty;
5410c50d8ae3SPaolo Bonzini 	role.base.guest_mode = true;
5411c50d8ae3SPaolo Bonzini 	role.base.access = ACC_ALL;
5412c50d8ae3SPaolo Bonzini 
5413cd6767c3SSean Christopherson 	role.ext.word = 0;
5414c50d8ae3SPaolo Bonzini 	role.ext.execonly = execonly;
5415cd6767c3SSean Christopherson 	role.ext.valid = 1;
5416c50d8ae3SPaolo Bonzini 
5417c50d8ae3SPaolo Bonzini 	return role;
5418c50d8ae3SPaolo Bonzini }
5419c50d8ae3SPaolo Bonzini 
5420c50d8ae3SPaolo Bonzini void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5421cc022ae1SLai Jiangshan 			     int huge_page_level, bool accessed_dirty,
5422cc022ae1SLai Jiangshan 			     gpa_t new_eptp)
5423c50d8ae3SPaolo Bonzini {
54248c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5425bb1fcc70SSean Christopherson 	u8 level = vmx_eptp_page_walk_level(new_eptp);
54267a7ae829SPaolo Bonzini 	union kvm_cpu_role new_mode =
5427c50d8ae3SPaolo Bonzini 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5428bb1fcc70SSean Christopherson 						   execonly, level);
5429c50d8ae3SPaolo Bonzini 
5430e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 != context->cpu_role.as_u64) {
5431e5ed0fb0SPaolo Bonzini 		/* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5432e5ed0fb0SPaolo Bonzini 		context->cpu_role.as_u64 = new_mode.as_u64;
54337a458f0eSPaolo Bonzini 		context->root_role.word = new_mode.base.word;
543418db1b17SSean Christopherson 
5435c50d8ae3SPaolo Bonzini 		context->page_fault = ept_page_fault;
5436c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = ept_gva_to_gpa;
5437c3c6c9fcSLai Jiangshan 		context->sync_spte = ept_sync_spte;
5438347a0d0dSPaolo Bonzini 
5439c596f147SSean Christopherson 		update_permission_bitmask(context, true);
544028f091bcSPaolo Bonzini 		context->pkru_mask = 0;
5441cc022ae1SLai Jiangshan 		reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5442e8f6e738SJinrong Liang 		reset_ept_shadow_zero_bits_mask(context, execonly);
5443c50d8ae3SPaolo Bonzini 	}
54443cffc89dSPaolo Bonzini 
5445d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, new_eptp);
54463cffc89dSPaolo Bonzini }
5447c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5448c50d8ae3SPaolo Bonzini 
544939e7e2bfSPaolo Bonzini static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5450a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5451c50d8ae3SPaolo Bonzini {
54528c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5453c50d8ae3SPaolo Bonzini 
5454a7f1de9bSPaolo Bonzini 	kvm_init_shadow_mmu(vcpu, cpu_role);
5455929d1cfaSPaolo Bonzini 
54562fdcc1b3SPaolo Bonzini 	context->get_guest_pgd     = get_guest_cr3;
5457c50d8ae3SPaolo Bonzini 	context->get_pdptr         = kvm_pdptr_read;
5458c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5459c50d8ae3SPaolo Bonzini }
5460c50d8ae3SPaolo Bonzini 
546139e7e2bfSPaolo Bonzini static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5462a7f1de9bSPaolo Bonzini 				union kvm_cpu_role new_mode)
5463c50d8ae3SPaolo Bonzini {
5464c50d8ae3SPaolo Bonzini 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5465c50d8ae3SPaolo Bonzini 
5466e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5467c50d8ae3SPaolo Bonzini 		return;
5468c50d8ae3SPaolo Bonzini 
5469e5ed0fb0SPaolo Bonzini 	g_context->cpu_role.as_u64   = new_mode.as_u64;
54702fdcc1b3SPaolo Bonzini 	g_context->get_guest_pgd     = get_guest_cr3;
5471c50d8ae3SPaolo Bonzini 	g_context->get_pdptr         = kvm_pdptr_read;
5472c50d8ae3SPaolo Bonzini 	g_context->inject_page_fault = kvm_inject_page_fault;
5473c50d8ae3SPaolo Bonzini 
5474c50d8ae3SPaolo Bonzini 	/*
54755efac074SPaolo Bonzini 	 * L2 page tables are never shadowed, so there is no need to sync
54765efac074SPaolo Bonzini 	 * SPTEs.
54775efac074SPaolo Bonzini 	 */
54789fd4a4e3SLai Jiangshan 	g_context->sync_spte         = NULL;
54795efac074SPaolo Bonzini 
54805efac074SPaolo Bonzini 	/*
5481c50d8ae3SPaolo Bonzini 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5482c50d8ae3SPaolo Bonzini 	 * L1's nested page tables (e.g. EPT12). The nested translation
5483c50d8ae3SPaolo Bonzini 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5484c50d8ae3SPaolo Bonzini 	 * L2's page tables as the first level of translation and L1's
5485c50d8ae3SPaolo Bonzini 	 * nested page tables as the second level of translation. Basically
5486c50d8ae3SPaolo Bonzini 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5487c50d8ae3SPaolo Bonzini 	 */
5488fa4b5588SSean Christopherson 	if (!is_paging(vcpu))
54891f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5490fa4b5588SSean Christopherson 	else if (is_long_mode(vcpu))
54911f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5492fa4b5588SSean Christopherson 	else if (is_pae(vcpu))
54931f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5494fa4b5588SSean Christopherson 	else
54951f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging32_gva_to_gpa;
5496fa4b5588SSean Christopherson 
5497533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, g_context);
5498c50d8ae3SPaolo Bonzini }
5499c50d8ae3SPaolo Bonzini 
5500c9060662SSean Christopherson void kvm_init_mmu(struct kvm_vcpu *vcpu)
5501c50d8ae3SPaolo Bonzini {
550239e7e2bfSPaolo Bonzini 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5503a7f1de9bSPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
550439e7e2bfSPaolo Bonzini 
5505c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
5506a7f1de9bSPaolo Bonzini 		init_kvm_nested_mmu(vcpu, cpu_role);
5507c50d8ae3SPaolo Bonzini 	else if (tdp_enabled)
5508a7f1de9bSPaolo Bonzini 		init_kvm_tdp_mmu(vcpu, cpu_role);
5509c50d8ae3SPaolo Bonzini 	else
5510a7f1de9bSPaolo Bonzini 		init_kvm_softmmu(vcpu, cpu_role);
5511c50d8ae3SPaolo Bonzini }
5512c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_mmu);
5513c50d8ae3SPaolo Bonzini 
551449c6f875SSean Christopherson void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
551549c6f875SSean Christopherson {
551649c6f875SSean Christopherson 	/*
551749c6f875SSean Christopherson 	 * Invalidate all MMU roles to force them to reinitialize as CPUID
551849c6f875SSean Christopherson 	 * information is factored into reserved bit calculations.
5519feb627e8SVitaly Kuznetsov 	 *
5520feb627e8SVitaly Kuznetsov 	 * Correctly handling multiple vCPU models with respect to paging and
5521feb627e8SVitaly Kuznetsov 	 * physical address properties) in a single VM would require tracking
5522feb627e8SVitaly Kuznetsov 	 * all relevant CPUID information in kvm_mmu_page_role. That is very
5523feb627e8SVitaly Kuznetsov 	 * undesirable as it would increase the memory requirements for
5524338068b5SSean Christopherson 	 * gfn_write_track (see struct kvm_mmu_page_role comments).  For now
5525338068b5SSean Christopherson 	 * that problem is swept under the rug; KVM's CPUID API is horrific and
5526feb627e8SVitaly Kuznetsov 	 * it's all but impossible to solve it without introducing a new API.
552749c6f875SSean Christopherson 	 */
55287a458f0eSPaolo Bonzini 	vcpu->arch.root_mmu.root_role.word = 0;
55297a458f0eSPaolo Bonzini 	vcpu->arch.guest_mmu.root_role.word = 0;
55307a458f0eSPaolo Bonzini 	vcpu->arch.nested_mmu.root_role.word = 0;
5531e5ed0fb0SPaolo Bonzini 	vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5532e5ed0fb0SPaolo Bonzini 	vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5533e5ed0fb0SPaolo Bonzini 	vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
553449c6f875SSean Christopherson 	kvm_mmu_reset_context(vcpu);
553563f5a190SSean Christopherson 
553663f5a190SSean Christopherson 	/*
5537feb627e8SVitaly Kuznetsov 	 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5538feb627e8SVitaly Kuznetsov 	 * kvm_arch_vcpu_ioctl().
553963f5a190SSean Christopherson 	 */
5540fb3146b4SSean Christopherson 	KVM_BUG_ON(kvm_vcpu_has_run(vcpu), vcpu->kvm);
554149c6f875SSean Christopherson }
554249c6f875SSean Christopherson 
5543c50d8ae3SPaolo Bonzini void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5544c50d8ae3SPaolo Bonzini {
5545c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
5546c9060662SSean Christopherson 	kvm_init_mmu(vcpu);
5547c50d8ae3SPaolo Bonzini }
5548c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5549c50d8ae3SPaolo Bonzini 
5550c50d8ae3SPaolo Bonzini int kvm_mmu_load(struct kvm_vcpu *vcpu)
5551c50d8ae3SPaolo Bonzini {
5552c50d8ae3SPaolo Bonzini 	int r;
5553c50d8ae3SPaolo Bonzini 
5554347a0d0dSPaolo Bonzini 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5555c50d8ae3SPaolo Bonzini 	if (r)
5556c50d8ae3SPaolo Bonzini 		goto out;
5557748e52b9SSean Christopherson 	r = mmu_alloc_special_roots(vcpu);
5558c50d8ae3SPaolo Bonzini 	if (r)
5559c50d8ae3SPaolo Bonzini 		goto out;
5560347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
55616e6ec584SSean Christopherson 		r = mmu_alloc_direct_roots(vcpu);
55626e6ec584SSean Christopherson 	else
55636e6ec584SSean Christopherson 		r = mmu_alloc_shadow_roots(vcpu);
5564c50d8ae3SPaolo Bonzini 	if (r)
5565c50d8ae3SPaolo Bonzini 		goto out;
5566a91f387bSSean Christopherson 
5567a91f387bSSean Christopherson 	kvm_mmu_sync_roots(vcpu);
5568a91f387bSSean Christopherson 
5569727a7e27SPaolo Bonzini 	kvm_mmu_load_pgd(vcpu);
5570db01416bSSean Christopherson 
5571db01416bSSean Christopherson 	/*
5572db01416bSSean Christopherson 	 * Flush any TLB entries for the new root, the provenance of the root
5573db01416bSSean Christopherson 	 * is unknown.  Even if KVM ensures there are no stale TLB entries
5574db01416bSSean Christopherson 	 * for a freed root, in theory another hypervisor could have left
5575db01416bSSean Christopherson 	 * stale entries.  Flushing on alloc also allows KVM to skip the TLB
5576db01416bSSean Christopherson 	 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5577db01416bSSean Christopherson 	 */
5578e27bc044SSean Christopherson 	static_call(kvm_x86_flush_tlb_current)(vcpu);
5579c50d8ae3SPaolo Bonzini out:
5580c50d8ae3SPaolo Bonzini 	return r;
5581c50d8ae3SPaolo Bonzini }
5582c50d8ae3SPaolo Bonzini 
5583c50d8ae3SPaolo Bonzini void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5584c50d8ae3SPaolo Bonzini {
55850c1c92f1SPaolo Bonzini 	struct kvm *kvm = vcpu->kvm;
55860c1c92f1SPaolo Bonzini 
55870c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
558820ba462dSSean Christopherson 	WARN_ON_ONCE(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
55890c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
559020ba462dSSean Christopherson 	WARN_ON_ONCE(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
55916d58f275SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5592c50d8ae3SPaolo Bonzini }
5593c50d8ae3SPaolo Bonzini 
5594527d5cd7SSean Christopherson static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5595527d5cd7SSean Christopherson {
5596527d5cd7SSean Christopherson 	struct kvm_mmu_page *sp;
5597527d5cd7SSean Christopherson 
5598527d5cd7SSean Christopherson 	if (!VALID_PAGE(root_hpa))
5599527d5cd7SSean Christopherson 		return false;
5600527d5cd7SSean Christopherson 
5601527d5cd7SSean Christopherson 	/*
5602527d5cd7SSean Christopherson 	 * When freeing obsolete roots, treat roots as obsolete if they don't
56030e3223d8SSean Christopherson 	 * have an associated shadow page, as it's impossible to determine if
56040e3223d8SSean Christopherson 	 * such roots are fresh or stale.  This does mean KVM will get false
5605527d5cd7SSean Christopherson 	 * positives and free roots that don't strictly need to be freed, but
5606527d5cd7SSean Christopherson 	 * such false positives are relatively rare:
5607527d5cd7SSean Christopherson 	 *
56080e3223d8SSean Christopherson 	 *  (a) only PAE paging and nested NPT have roots without shadow pages
56090e3223d8SSean Christopherson 	 *      (or any shadow paging flavor with a dummy root, see note below)
5610527d5cd7SSean Christopherson 	 *  (b) remote reloads due to a memslot update obsoletes _all_ roots
5611527d5cd7SSean Christopherson 	 *  (c) KVM doesn't track previous roots for PAE paging, and the guest
5612527d5cd7SSean Christopherson 	 *      is unlikely to zap an in-use PGD.
56130e3223d8SSean Christopherson 	 *
56140e3223d8SSean Christopherson 	 * Note!  Dummy roots are unique in that they are obsoleted by memslot
56150e3223d8SSean Christopherson 	 * _creation_!  See also FNAME(fetch).
5616527d5cd7SSean Christopherson 	 */
5617c5f2d564SSean Christopherson 	sp = root_to_sp(root_hpa);
5618527d5cd7SSean Christopherson 	return !sp || is_obsolete_sp(kvm, sp);
5619527d5cd7SSean Christopherson }
5620527d5cd7SSean Christopherson 
5621527d5cd7SSean Christopherson static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5622527d5cd7SSean Christopherson {
5623527d5cd7SSean Christopherson 	unsigned long roots_to_free = 0;
5624527d5cd7SSean Christopherson 	int i;
5625527d5cd7SSean Christopherson 
5626527d5cd7SSean Christopherson 	if (is_obsolete_root(kvm, mmu->root.hpa))
5627527d5cd7SSean Christopherson 		roots_to_free |= KVM_MMU_ROOT_CURRENT;
5628527d5cd7SSean Christopherson 
5629527d5cd7SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5630cf4a8693SShaoqin Huang 		if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5631527d5cd7SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5632527d5cd7SSean Christopherson 	}
5633527d5cd7SSean Christopherson 
5634527d5cd7SSean Christopherson 	if (roots_to_free)
5635527d5cd7SSean Christopherson 		kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5636527d5cd7SSean Christopherson }
5637527d5cd7SSean Christopherson 
5638527d5cd7SSean Christopherson void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5639527d5cd7SSean Christopherson {
5640527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5641527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5642527d5cd7SSean Christopherson }
5643527d5cd7SSean Christopherson 
5644c50d8ae3SPaolo Bonzini static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5645c50d8ae3SPaolo Bonzini 				    int *bytes)
5646c50d8ae3SPaolo Bonzini {
5647c50d8ae3SPaolo Bonzini 	u64 gentry = 0;
5648c50d8ae3SPaolo Bonzini 	int r;
5649c50d8ae3SPaolo Bonzini 
5650c50d8ae3SPaolo Bonzini 	/*
5651c50d8ae3SPaolo Bonzini 	 * Assume that the pte write on a page table of the same type
5652c50d8ae3SPaolo Bonzini 	 * as the current vcpu paging mode since we update the sptes only
5653c50d8ae3SPaolo Bonzini 	 * when they have the same mode.
5654c50d8ae3SPaolo Bonzini 	 */
5655c50d8ae3SPaolo Bonzini 	if (is_pae(vcpu) && *bytes == 4) {
5656c50d8ae3SPaolo Bonzini 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5657c50d8ae3SPaolo Bonzini 		*gpa &= ~(gpa_t)7;
5658c50d8ae3SPaolo Bonzini 		*bytes = 8;
5659c50d8ae3SPaolo Bonzini 	}
5660c50d8ae3SPaolo Bonzini 
5661c50d8ae3SPaolo Bonzini 	if (*bytes == 4 || *bytes == 8) {
5662c50d8ae3SPaolo Bonzini 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5663c50d8ae3SPaolo Bonzini 		if (r)
5664c50d8ae3SPaolo Bonzini 			gentry = 0;
5665c50d8ae3SPaolo Bonzini 	}
5666c50d8ae3SPaolo Bonzini 
5667c50d8ae3SPaolo Bonzini 	return gentry;
5668c50d8ae3SPaolo Bonzini }
5669c50d8ae3SPaolo Bonzini 
5670c50d8ae3SPaolo Bonzini /*
5671c50d8ae3SPaolo Bonzini  * If we're seeing too many writes to a page, it may no longer be a page table,
5672c50d8ae3SPaolo Bonzini  * or we may be forking, in which case it is better to unmap the page.
5673c50d8ae3SPaolo Bonzini  */
5674c50d8ae3SPaolo Bonzini static bool detect_write_flooding(struct kvm_mmu_page *sp)
5675c50d8ae3SPaolo Bonzini {
5676c50d8ae3SPaolo Bonzini 	/*
5677c50d8ae3SPaolo Bonzini 	 * Skip write-flooding detected for the sp whose level is 1, because
5678c50d8ae3SPaolo Bonzini 	 * it can become unsync, then the guest page is not write-protected.
5679c50d8ae3SPaolo Bonzini 	 */
56803bae0459SSean Christopherson 	if (sp->role.level == PG_LEVEL_4K)
5681c50d8ae3SPaolo Bonzini 		return false;
5682c50d8ae3SPaolo Bonzini 
5683c50d8ae3SPaolo Bonzini 	atomic_inc(&sp->write_flooding_count);
5684c50d8ae3SPaolo Bonzini 	return atomic_read(&sp->write_flooding_count) >= 3;
5685c50d8ae3SPaolo Bonzini }
5686c50d8ae3SPaolo Bonzini 
5687c50d8ae3SPaolo Bonzini /*
5688c50d8ae3SPaolo Bonzini  * Misaligned accesses are too much trouble to fix up; also, they usually
5689c50d8ae3SPaolo Bonzini  * indicate a page is not used as a page table.
5690c50d8ae3SPaolo Bonzini  */
5691c50d8ae3SPaolo Bonzini static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5692c50d8ae3SPaolo Bonzini 				    int bytes)
5693c50d8ae3SPaolo Bonzini {
5694c50d8ae3SPaolo Bonzini 	unsigned offset, pte_size, misaligned;
5695c50d8ae3SPaolo Bonzini 
5696c50d8ae3SPaolo Bonzini 	offset = offset_in_page(gpa);
5697bb3b394dSLai Jiangshan 	pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5698c50d8ae3SPaolo Bonzini 
5699c50d8ae3SPaolo Bonzini 	/*
5700c50d8ae3SPaolo Bonzini 	 * Sometimes, the OS only writes the last one bytes to update status
5701c50d8ae3SPaolo Bonzini 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5702c50d8ae3SPaolo Bonzini 	 */
5703c50d8ae3SPaolo Bonzini 	if (!(offset & (pte_size - 1)) && bytes == 1)
5704c50d8ae3SPaolo Bonzini 		return false;
5705c50d8ae3SPaolo Bonzini 
5706c50d8ae3SPaolo Bonzini 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5707c50d8ae3SPaolo Bonzini 	misaligned |= bytes < 4;
5708c50d8ae3SPaolo Bonzini 
5709c50d8ae3SPaolo Bonzini 	return misaligned;
5710c50d8ae3SPaolo Bonzini }
5711c50d8ae3SPaolo Bonzini 
5712c50d8ae3SPaolo Bonzini static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5713c50d8ae3SPaolo Bonzini {
5714c50d8ae3SPaolo Bonzini 	unsigned page_offset, quadrant;
5715c50d8ae3SPaolo Bonzini 	u64 *spte;
5716c50d8ae3SPaolo Bonzini 	int level;
5717c50d8ae3SPaolo Bonzini 
5718c50d8ae3SPaolo Bonzini 	page_offset = offset_in_page(gpa);
5719c50d8ae3SPaolo Bonzini 	level = sp->role.level;
5720c50d8ae3SPaolo Bonzini 	*nspte = 1;
5721bb3b394dSLai Jiangshan 	if (sp->role.has_4_byte_gpte) {
5722c50d8ae3SPaolo Bonzini 		page_offset <<= 1;	/* 32->64 */
5723c50d8ae3SPaolo Bonzini 		/*
5724c50d8ae3SPaolo Bonzini 		 * A 32-bit pde maps 4MB while the shadow pdes map
5725c50d8ae3SPaolo Bonzini 		 * only 2MB.  So we need to double the offset again
5726c50d8ae3SPaolo Bonzini 		 * and zap two pdes instead of one.
5727c50d8ae3SPaolo Bonzini 		 */
5728c50d8ae3SPaolo Bonzini 		if (level == PT32_ROOT_LEVEL) {
5729c50d8ae3SPaolo Bonzini 			page_offset &= ~7; /* kill rounding error */
5730c50d8ae3SPaolo Bonzini 			page_offset <<= 1;
5731c50d8ae3SPaolo Bonzini 			*nspte = 2;
5732c50d8ae3SPaolo Bonzini 		}
5733c50d8ae3SPaolo Bonzini 		quadrant = page_offset >> PAGE_SHIFT;
5734c50d8ae3SPaolo Bonzini 		page_offset &= ~PAGE_MASK;
5735c50d8ae3SPaolo Bonzini 		if (quadrant != sp->role.quadrant)
5736c50d8ae3SPaolo Bonzini 			return NULL;
5737c50d8ae3SPaolo Bonzini 	}
5738c50d8ae3SPaolo Bonzini 
5739c50d8ae3SPaolo Bonzini 	spte = &sp->spt[page_offset / sizeof(*spte)];
5740c50d8ae3SPaolo Bonzini 	return spte;
5741c50d8ae3SPaolo Bonzini }
5742c50d8ae3SPaolo Bonzini 
574393284446SSean Christopherson void kvm_mmu_track_write(struct kvm_vcpu *vcpu, gpa_t gpa, const u8 *new,
574493284446SSean Christopherson 			 int bytes)
5745c50d8ae3SPaolo Bonzini {
5746c50d8ae3SPaolo Bonzini 	gfn_t gfn = gpa >> PAGE_SHIFT;
5747c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
5748c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
5749c50d8ae3SPaolo Bonzini 	u64 entry, gentry, *spte;
5750c50d8ae3SPaolo Bonzini 	int npte;
575106152b2dSLai Jiangshan 	bool flush = false;
5752c50d8ae3SPaolo Bonzini 
5753c50d8ae3SPaolo Bonzini 	/*
5754c50d8ae3SPaolo Bonzini 	 * If we don't have indirect shadow pages, it means no page is
5755c50d8ae3SPaolo Bonzini 	 * write-protected, so we can exit simply.
5756c50d8ae3SPaolo Bonzini 	 */
5757c50d8ae3SPaolo Bonzini 	if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5758c50d8ae3SPaolo Bonzini 		return;
5759c50d8ae3SPaolo Bonzini 
5760531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
5761c50d8ae3SPaolo Bonzini 
5762c50d8ae3SPaolo Bonzini 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5763c50d8ae3SPaolo Bonzini 
5764c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_pte_write;
5765c50d8ae3SPaolo Bonzini 
5766767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5767c50d8ae3SPaolo Bonzini 		if (detect_write_misaligned(sp, gpa, bytes) ||
5768c50d8ae3SPaolo Bonzini 		      detect_write_flooding(sp)) {
5769c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5770c50d8ae3SPaolo Bonzini 			++vcpu->kvm->stat.mmu_flooded;
5771c50d8ae3SPaolo Bonzini 			continue;
5772c50d8ae3SPaolo Bonzini 		}
5773c50d8ae3SPaolo Bonzini 
5774c50d8ae3SPaolo Bonzini 		spte = get_written_sptes(sp, gpa, &npte);
5775c50d8ae3SPaolo Bonzini 		if (!spte)
5776c50d8ae3SPaolo Bonzini 			continue;
5777c50d8ae3SPaolo Bonzini 
5778c50d8ae3SPaolo Bonzini 		while (npte--) {
5779c50d8ae3SPaolo Bonzini 			entry = *spte;
57802de4085cSBen Gardon 			mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5781c5e2184dSSean Christopherson 			if (gentry && sp->role.level != PG_LEVEL_4K)
5782c5e2184dSSean Christopherson 				++vcpu->kvm->stat.mmu_pde_zapped;
57831441ca14SJunaid Shahid 			if (is_shadow_present_pte(entry))
578406152b2dSLai Jiangshan 				flush = true;
5785c50d8ae3SPaolo Bonzini 			++spte;
5786c50d8ae3SPaolo Bonzini 		}
5787c50d8ae3SPaolo Bonzini 	}
578806152b2dSLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5789531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
5790c50d8ae3SPaolo Bonzini }
5791c50d8ae3SPaolo Bonzini 
57921075d41eSSean Christopherson int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5793c50d8ae3SPaolo Bonzini 		       void *insn, int insn_len)
5794c50d8ae3SPaolo Bonzini {
579592daa48bSSean Christopherson 	int r, emulation_type = EMULTYPE_PF;
5796347a0d0dSPaolo Bonzini 	bool direct = vcpu->arch.mmu->root_role.direct;
5797c50d8ae3SPaolo Bonzini 
5798d09f7112SSean Christopherson 	/*
5799d09f7112SSean Christopherson 	 * IMPLICIT_ACCESS is a KVM-defined flag used to correctly perform SMAP
5800d09f7112SSean Christopherson 	 * checks when emulating instructions that triggers implicit access.
5801d09f7112SSean Christopherson 	 * WARN if hardware generates a fault with an error code that collides
5802d09f7112SSean Christopherson 	 * with the KVM-defined value.  Clear the flag and continue on, i.e.
5803d09f7112SSean Christopherson 	 * don't terminate the VM, as KVM can't possibly be relying on a flag
5804d09f7112SSean Christopherson 	 * that KVM doesn't know about.
5805d09f7112SSean Christopherson 	 */
5806d09f7112SSean Christopherson 	if (WARN_ON_ONCE(error_code & PFERR_IMPLICIT_ACCESS))
5807d09f7112SSean Christopherson 		error_code &= ~PFERR_IMPLICIT_ACCESS;
5808d09f7112SSean Christopherson 
580920ba462dSSean Christopherson 	if (WARN_ON_ONCE(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5810ddce6208SSean Christopherson 		return RET_PF_RETRY;
5811ddce6208SSean Christopherson 
5812c50d8ae3SPaolo Bonzini 	r = RET_PF_INVALID;
5813c50d8ae3SPaolo Bonzini 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
5814736c291cSSean Christopherson 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5815c50d8ae3SPaolo Bonzini 		if (r == RET_PF_EMULATE)
5816c50d8ae3SPaolo Bonzini 			goto emulate;
5817c50d8ae3SPaolo Bonzini 	}
5818c50d8ae3SPaolo Bonzini 
5819c50d8ae3SPaolo Bonzini 	if (r == RET_PF_INVALID) {
58207a02674dSSean Christopherson 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
5821258d985fSSean Christopherson 					  lower_32_bits(error_code), false,
5822258d985fSSean Christopherson 					  &emulation_type);
582319025e7bSSean Christopherson 		if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
58247b367bc9SSean Christopherson 			return -EIO;
5825c50d8ae3SPaolo Bonzini 	}
5826c50d8ae3SPaolo Bonzini 
5827c50d8ae3SPaolo Bonzini 	if (r < 0)
5828c50d8ae3SPaolo Bonzini 		return r;
582983a2ba4cSSean Christopherson 	if (r != RET_PF_EMULATE)
583083a2ba4cSSean Christopherson 		return 1;
5831c50d8ae3SPaolo Bonzini 
5832c50d8ae3SPaolo Bonzini 	/*
5833c50d8ae3SPaolo Bonzini 	 * Before emulating the instruction, check if the error code
5834c50d8ae3SPaolo Bonzini 	 * was due to a RO violation while translating the guest page.
5835c50d8ae3SPaolo Bonzini 	 * This can occur when using nested virtualization with nested
5836c50d8ae3SPaolo Bonzini 	 * paging in both guests. If true, we simply unprotect the page
5837c50d8ae3SPaolo Bonzini 	 * and resume the guest.
5838c50d8ae3SPaolo Bonzini 	 */
5839347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct &&
5840c50d8ae3SPaolo Bonzini 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5841736c291cSSean Christopherson 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5842c50d8ae3SPaolo Bonzini 		return 1;
5843c50d8ae3SPaolo Bonzini 	}
5844c50d8ae3SPaolo Bonzini 
5845c50d8ae3SPaolo Bonzini 	/*
5846c50d8ae3SPaolo Bonzini 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5847c50d8ae3SPaolo Bonzini 	 * optimistically try to just unprotect the page and let the processor
5848c50d8ae3SPaolo Bonzini 	 * re-execute the instruction that caused the page fault.  Do not allow
5849c50d8ae3SPaolo Bonzini 	 * retrying MMIO emulation, as it's not only pointless but could also
5850c50d8ae3SPaolo Bonzini 	 * cause us to enter an infinite loop because the processor will keep
5851c50d8ae3SPaolo Bonzini 	 * faulting on the non-existent MMIO address.  Retrying an instruction
5852c50d8ae3SPaolo Bonzini 	 * from a nested guest is also pointless and dangerous as we are only
5853c50d8ae3SPaolo Bonzini 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
5854c50d8ae3SPaolo Bonzini 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5855c50d8ae3SPaolo Bonzini 	 */
5856736c291cSSean Christopherson 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
585792daa48bSSean Christopherson 		emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5858c50d8ae3SPaolo Bonzini emulate:
5859736c291cSSean Christopherson 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5860c50d8ae3SPaolo Bonzini 				       insn_len);
5861c50d8ae3SPaolo Bonzini }
5862c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5863c50d8ae3SPaolo Bonzini 
58649fd4a4e3SLai Jiangshan static void __kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
58659fd4a4e3SLai Jiangshan 				      u64 addr, hpa_t root_hpa)
58669fd4a4e3SLai Jiangshan {
58679fd4a4e3SLai Jiangshan 	struct kvm_shadow_walk_iterator iterator;
58689fd4a4e3SLai Jiangshan 
58699fd4a4e3SLai Jiangshan 	vcpu_clear_mmio_info(vcpu, addr);
58709fd4a4e3SLai Jiangshan 
5871762b33ebSLike Xu 	/*
5872762b33ebSLike Xu 	 * Walking and synchronizing SPTEs both assume they are operating in
5873762b33ebSLike Xu 	 * the context of the current MMU, and would need to be reworked if
5874762b33ebSLike Xu 	 * this is ever used to sync the guest_mmu, e.g. to emulate INVEPT.
5875762b33ebSLike Xu 	 */
5876762b33ebSLike Xu 	if (WARN_ON_ONCE(mmu != vcpu->arch.mmu))
5877762b33ebSLike Xu 		return;
5878762b33ebSLike Xu 
58799fd4a4e3SLai Jiangshan 	if (!VALID_PAGE(root_hpa))
58809fd4a4e3SLai Jiangshan 		return;
58819fd4a4e3SLai Jiangshan 
58829fd4a4e3SLai Jiangshan 	write_lock(&vcpu->kvm->mmu_lock);
58839fd4a4e3SLai Jiangshan 	for_each_shadow_entry_using_root(vcpu, root_hpa, addr, iterator) {
58849fd4a4e3SLai Jiangshan 		struct kvm_mmu_page *sp = sptep_to_sp(iterator.sptep);
58859fd4a4e3SLai Jiangshan 
58869fd4a4e3SLai Jiangshan 		if (sp->unsync) {
588719ace7d6SLai Jiangshan 			int ret = kvm_sync_spte(vcpu, sp, iterator.index);
58889fd4a4e3SLai Jiangshan 
58899fd4a4e3SLai Jiangshan 			if (ret < 0)
58909fd4a4e3SLai Jiangshan 				mmu_page_zap_pte(vcpu->kvm, sp, iterator.sptep, NULL);
58919fd4a4e3SLai Jiangshan 			if (ret)
58929fd4a4e3SLai Jiangshan 				kvm_flush_remote_tlbs_sptep(vcpu->kvm, iterator.sptep);
58939fd4a4e3SLai Jiangshan 		}
58949fd4a4e3SLai Jiangshan 
58959fd4a4e3SLai Jiangshan 		if (!sp->unsync_children)
58969fd4a4e3SLai Jiangshan 			break;
58979fd4a4e3SLai Jiangshan 	}
58989fd4a4e3SLai Jiangshan 	write_unlock(&vcpu->kvm->mmu_lock);
58999fd4a4e3SLai Jiangshan }
59009fd4a4e3SLai Jiangshan 
5901753b43c9SLai Jiangshan void kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5902cd42853eSLai Jiangshan 			     u64 addr, unsigned long roots)
5903c50d8ae3SPaolo Bonzini {
5904c50d8ae3SPaolo Bonzini 	int i;
5905c50d8ae3SPaolo Bonzini 
5906cd42853eSLai Jiangshan 	WARN_ON_ONCE(roots & ~KVM_MMU_ROOTS_ALL);
5907cd42853eSLai Jiangshan 
59085efac074SPaolo Bonzini 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
59095efac074SPaolo Bonzini 	if (mmu != &vcpu->arch.guest_mmu) {
59105efac074SPaolo Bonzini 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
5911753b43c9SLai Jiangshan 		if (is_noncanonical_address(addr, vcpu))
5912c50d8ae3SPaolo Bonzini 			return;
5913c50d8ae3SPaolo Bonzini 
5914753b43c9SLai Jiangshan 		static_call(kvm_x86_flush_tlb_gva)(vcpu, addr);
59155efac074SPaolo Bonzini 	}
59165efac074SPaolo Bonzini 
59179fd4a4e3SLai Jiangshan 	if (!mmu->sync_spte)
59185efac074SPaolo Bonzini 		return;
59195efac074SPaolo Bonzini 
5920cd42853eSLai Jiangshan 	if (roots & KVM_MMU_ROOT_CURRENT)
59219fd4a4e3SLai Jiangshan 		__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->root.hpa);
5922c50d8ae3SPaolo Bonzini 
5923cd42853eSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5924ed335278SLai Jiangshan 		if (roots & KVM_MMU_ROOT_PREVIOUS(i))
59259fd4a4e3SLai Jiangshan 			__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->prev_roots[i].hpa);
59265efac074SPaolo Bonzini 	}
59275efac074SPaolo Bonzini }
59282c86c444SLai Jiangshan EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_addr);
5929c50d8ae3SPaolo Bonzini 
59305efac074SPaolo Bonzini void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
59315efac074SPaolo Bonzini {
5932cd42853eSLai Jiangshan 	/*
5933cd42853eSLai Jiangshan 	 * INVLPG is required to invalidate any global mappings for the VA,
5934cd42853eSLai Jiangshan 	 * irrespective of PCID.  Blindly sync all roots as it would take
5935cd42853eSLai Jiangshan 	 * roughly the same amount of work/time to determine whether any of the
5936cd42853eSLai Jiangshan 	 * previous roots have a global mapping.
5937cd42853eSLai Jiangshan 	 *
5938cd42853eSLai Jiangshan 	 * Mappings not reachable via the current or previous cached roots will
5939cd42853eSLai Jiangshan 	 * be synced when switching to that new cr3, so nothing needs to be
5940cd42853eSLai Jiangshan 	 * done here for them.
5941cd42853eSLai Jiangshan 	 */
5942cd42853eSLai Jiangshan 	kvm_mmu_invalidate_addr(vcpu, vcpu->arch.walk_mmu, gva, KVM_MMU_ROOTS_ALL);
5943c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5944c50d8ae3SPaolo Bonzini }
5945c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5946c50d8ae3SPaolo Bonzini 
59475efac074SPaolo Bonzini 
5948c50d8ae3SPaolo Bonzini void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5949c50d8ae3SPaolo Bonzini {
5950c50d8ae3SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
59519ebc3f51SLai Jiangshan 	unsigned long roots = 0;
5952c50d8ae3SPaolo Bonzini 	uint i;
5953c50d8ae3SPaolo Bonzini 
59549ebc3f51SLai Jiangshan 	if (pcid == kvm_get_active_pcid(vcpu))
59559ebc3f51SLai Jiangshan 		roots |= KVM_MMU_ROOT_CURRENT;
5956c50d8ae3SPaolo Bonzini 
5957c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5958c50d8ae3SPaolo Bonzini 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
59599ebc3f51SLai Jiangshan 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd))
59609ebc3f51SLai Jiangshan 			roots |= KVM_MMU_ROOT_PREVIOUS(i);
5961c50d8ae3SPaolo Bonzini 	}
5962c50d8ae3SPaolo Bonzini 
59639ebc3f51SLai Jiangshan 	if (roots)
59649ebc3f51SLai Jiangshan 		kvm_mmu_invalidate_addr(vcpu, mmu, gva, roots);
5965c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5966c50d8ae3SPaolo Bonzini 
5967c50d8ae3SPaolo Bonzini 	/*
5968c50d8ae3SPaolo Bonzini 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5969c50d8ae3SPaolo Bonzini 	 * synced when switching to that cr3, so nothing needs to be done here
5970c50d8ae3SPaolo Bonzini 	 * for them.
5971c50d8ae3SPaolo Bonzini 	 */
5972c50d8ae3SPaolo Bonzini }
5973c50d8ae3SPaolo Bonzini 
5974746700d2SWei Huang void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
5975746700d2SWei Huang 		       int tdp_max_root_level, int tdp_huge_page_level)
5976c50d8ae3SPaolo Bonzini {
5977bde77235SSean Christopherson 	tdp_enabled = enable_tdp;
5978746700d2SWei Huang 	tdp_root_level = tdp_forced_root_level;
597983013059SSean Christopherson 	max_tdp_level = tdp_max_root_level;
5980703c335dSSean Christopherson 
59811f98f2bdSDavid Matlack #ifdef CONFIG_X86_64
59821f98f2bdSDavid Matlack 	tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
59831f98f2bdSDavid Matlack #endif
5984703c335dSSean Christopherson 	/*
59851d92d2e8SSean Christopherson 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5986703c335dSSean Christopherson 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5987703c335dSSean Christopherson 	 * the kernel is not.  But, KVM never creates a page size greater than
5988703c335dSSean Christopherson 	 * what is used by the kernel for any given HVA, i.e. the kernel's
5989703c335dSSean Christopherson 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5990703c335dSSean Christopherson 	 */
5991703c335dSSean Christopherson 	if (tdp_enabled)
59921d92d2e8SSean Christopherson 		max_huge_page_level = tdp_huge_page_level;
5993703c335dSSean Christopherson 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
59941d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_1G;
5995703c335dSSean Christopherson 	else
59961d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_2M;
5997c50d8ae3SPaolo Bonzini }
5998bde77235SSean Christopherson EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5999c50d8ae3SPaolo Bonzini 
6000c50d8ae3SPaolo Bonzini /* The return value indicates if tlb flush on all vcpus is needed. */
6001727ae377SSean Christopherson typedef bool (*slot_rmaps_handler) (struct kvm *kvm,
6002269e9552SHamza Mahfooz 				    struct kvm_rmap_head *rmap_head,
6003269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot);
6004c50d8ae3SPaolo Bonzini 
6005727ae377SSean Christopherson static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,
6006727ae377SSean Christopherson 					      const struct kvm_memory_slot *slot,
6007727ae377SSean Christopherson 					      slot_rmaps_handler fn,
6008727ae377SSean Christopherson 					      int start_level, int end_level,
6009727ae377SSean Christopherson 					      gfn_t start_gfn, gfn_t end_gfn,
6010727ae377SSean Christopherson 					      bool flush_on_yield, bool flush)
6011c50d8ae3SPaolo Bonzini {
6012c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
6013c50d8ae3SPaolo Bonzini 
6014eddd9e83SSean Christopherson 	lockdep_assert_held_write(&kvm->mmu_lock);
6015eddd9e83SSean Christopherson 
6016727ae377SSean Christopherson 	for_each_slot_rmap_range(slot, start_level, end_level, start_gfn,
6017c50d8ae3SPaolo Bonzini 			end_gfn, &iterator) {
6018c50d8ae3SPaolo Bonzini 		if (iterator.rmap)
6019727ae377SSean Christopherson 			flush |= fn(kvm, iterator.rmap, slot);
6020c50d8ae3SPaolo Bonzini 
6021531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
6022302695a5SSean Christopherson 			if (flush && flush_on_yield) {
60238c63e8c2SDavid Matlack 				kvm_flush_remote_tlbs_range(kvm, start_gfn,
6024c50d8ae3SPaolo Bonzini 							    iterator.gfn - start_gfn + 1);
6025c50d8ae3SPaolo Bonzini 				flush = false;
6026c50d8ae3SPaolo Bonzini 			}
6027531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
6028c50d8ae3SPaolo Bonzini 		}
6029c50d8ae3SPaolo Bonzini 	}
6030c50d8ae3SPaolo Bonzini 
6031c50d8ae3SPaolo Bonzini 	return flush;
6032c50d8ae3SPaolo Bonzini }
6033c50d8ae3SPaolo Bonzini 
6034727ae377SSean Christopherson static __always_inline bool walk_slot_rmaps(struct kvm *kvm,
6035727ae377SSean Christopherson 					    const struct kvm_memory_slot *slot,
6036727ae377SSean Christopherson 					    slot_rmaps_handler fn,
6037727ae377SSean Christopherson 					    int start_level, int end_level,
6038302695a5SSean Christopherson 					    bool flush_on_yield)
6039c50d8ae3SPaolo Bonzini {
6040727ae377SSean Christopherson 	return __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,
6041727ae377SSean Christopherson 				 slot->base_gfn, slot->base_gfn + slot->npages - 1,
60421a61b7dbSSean Christopherson 				 flush_on_yield, false);
6043c50d8ae3SPaolo Bonzini }
6044c50d8ae3SPaolo Bonzini 
6045727ae377SSean Christopherson static __always_inline bool walk_slot_rmaps_4k(struct kvm *kvm,
6046727ae377SSean Christopherson 					       const struct kvm_memory_slot *slot,
6047727ae377SSean Christopherson 					       slot_rmaps_handler fn,
6048727ae377SSean Christopherson 					       bool flush_on_yield)
6049c50d8ae3SPaolo Bonzini {
6050727ae377SSean Christopherson 	return walk_slot_rmaps(kvm, slot, fn, PG_LEVEL_4K, PG_LEVEL_4K, flush_on_yield);
6051c50d8ae3SPaolo Bonzini }
6052c50d8ae3SPaolo Bonzini 
6053c50d8ae3SPaolo Bonzini static void free_mmu_pages(struct kvm_mmu *mmu)
6054c50d8ae3SPaolo Bonzini {
60554a98623dSSean Christopherson 	if (!tdp_enabled && mmu->pae_root)
60564a98623dSSean Christopherson 		set_memory_encrypted((unsigned long)mmu->pae_root, 1);
6057c50d8ae3SPaolo Bonzini 	free_page((unsigned long)mmu->pae_root);
605803ca4589SSean Christopherson 	free_page((unsigned long)mmu->pml4_root);
6059cb0f722aSWei Huang 	free_page((unsigned long)mmu->pml5_root);
6060c50d8ae3SPaolo Bonzini }
6061c50d8ae3SPaolo Bonzini 
606204d28e37SSean Christopherson static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
6063c50d8ae3SPaolo Bonzini {
6064c50d8ae3SPaolo Bonzini 	struct page *page;
6065c50d8ae3SPaolo Bonzini 	int i;
6066c50d8ae3SPaolo Bonzini 
6067b9e5603cSPaolo Bonzini 	mmu->root.hpa = INVALID_PAGE;
6068b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
606904d28e37SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
607004d28e37SSean Christopherson 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
607104d28e37SSean Christopherson 
607227f4fca2SLai Jiangshan 	/* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
607327f4fca2SLai Jiangshan 	if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
607427f4fca2SLai Jiangshan 		return 0;
607527f4fca2SLai Jiangshan 
6076c50d8ae3SPaolo Bonzini 	/*
6077c50d8ae3SPaolo Bonzini 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
6078c50d8ae3SPaolo Bonzini 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
6079c50d8ae3SPaolo Bonzini 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
6080c50d8ae3SPaolo Bonzini 	 * x86_64.  Therefore we need to allocate the PDP table in the first
608104d45551SSean Christopherson 	 * 4GB of memory, which happens to fit the DMA32 zone.  TDP paging
608204d45551SSean Christopherson 	 * generally doesn't use PAE paging and can skip allocating the PDP
608304d45551SSean Christopherson 	 * table.  The main exception, handled here, is SVM's 32-bit NPT.  The
608404d45551SSean Christopherson 	 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
608584432316SLai Jiangshan 	 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
6086c50d8ae3SPaolo Bonzini 	 */
6087d468d94bSSean Christopherson 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
6088c50d8ae3SPaolo Bonzini 		return 0;
6089c50d8ae3SPaolo Bonzini 
6090c50d8ae3SPaolo Bonzini 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
6091c50d8ae3SPaolo Bonzini 	if (!page)
6092c50d8ae3SPaolo Bonzini 		return -ENOMEM;
6093c50d8ae3SPaolo Bonzini 
6094c50d8ae3SPaolo Bonzini 	mmu->pae_root = page_address(page);
60954a98623dSSean Christopherson 
60964a98623dSSean Christopherson 	/*
60974a98623dSSean Christopherson 	 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
60984a98623dSSean Christopherson 	 * get the CPU to treat the PDPTEs as encrypted.  Decrypt the page so
60994a98623dSSean Christopherson 	 * that KVM's writes and the CPU's reads get along.  Note, this is
61004a98623dSSean Christopherson 	 * only necessary when using shadow paging, as 64-bit NPT can get at
61014a98623dSSean Christopherson 	 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
61024a98623dSSean Christopherson 	 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
61034a98623dSSean Christopherson 	 */
61044a98623dSSean Christopherson 	if (!tdp_enabled)
61054a98623dSSean Christopherson 		set_memory_decrypted((unsigned long)mmu->pae_root, 1);
61064a98623dSSean Christopherson 	else
6107e54f1ff2SKai Huang 		WARN_ON_ONCE(shadow_me_value);
61084a98623dSSean Christopherson 
6109c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i)
6110c834e5e4SSean Christopherson 		mmu->pae_root[i] = INVALID_PAE_ROOT;
6111c50d8ae3SPaolo Bonzini 
6112c50d8ae3SPaolo Bonzini 	return 0;
6113c50d8ae3SPaolo Bonzini }
6114c50d8ae3SPaolo Bonzini 
6115c50d8ae3SPaolo Bonzini int kvm_mmu_create(struct kvm_vcpu *vcpu)
6116c50d8ae3SPaolo Bonzini {
6117c50d8ae3SPaolo Bonzini 	int ret;
6118c50d8ae3SPaolo Bonzini 
61195962bfb7SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
61205f6078f9SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
61215f6078f9SSean Christopherson 
61225962bfb7SSean Christopherson 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
61235f6078f9SSean Christopherson 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
61245962bfb7SSean Christopherson 
612596880883SSean Christopherson 	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
612696880883SSean Christopherson 
6127c50d8ae3SPaolo Bonzini 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
6128c50d8ae3SPaolo Bonzini 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6129c50d8ae3SPaolo Bonzini 
613004d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
6131c50d8ae3SPaolo Bonzini 	if (ret)
6132c50d8ae3SPaolo Bonzini 		return ret;
6133c50d8ae3SPaolo Bonzini 
613404d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
6135c50d8ae3SPaolo Bonzini 	if (ret)
6136c50d8ae3SPaolo Bonzini 		goto fail_allocate_root;
6137c50d8ae3SPaolo Bonzini 
6138c50d8ae3SPaolo Bonzini 	return ret;
6139c50d8ae3SPaolo Bonzini  fail_allocate_root:
6140c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
6141c50d8ae3SPaolo Bonzini 	return ret;
6142c50d8ae3SPaolo Bonzini }
6143c50d8ae3SPaolo Bonzini 
6144c50d8ae3SPaolo Bonzini #define BATCH_ZAP_PAGES	10
6145c50d8ae3SPaolo Bonzini static void kvm_zap_obsolete_pages(struct kvm *kvm)
6146c50d8ae3SPaolo Bonzini {
6147c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6148c50d8ae3SPaolo Bonzini 	int nr_zapped, batch = 0;
6149b28cb0cdSSean Christopherson 	bool unstable;
6150c50d8ae3SPaolo Bonzini 
6151c50d8ae3SPaolo Bonzini restart:
6152c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe_reverse(sp, node,
6153c50d8ae3SPaolo Bonzini 	      &kvm->arch.active_mmu_pages, link) {
6154c50d8ae3SPaolo Bonzini 		/*
6155c50d8ae3SPaolo Bonzini 		 * No obsolete valid page exists before a newly created page
6156c50d8ae3SPaolo Bonzini 		 * since active_mmu_pages is a FIFO list.
6157c50d8ae3SPaolo Bonzini 		 */
6158c50d8ae3SPaolo Bonzini 		if (!is_obsolete_sp(kvm, sp))
6159c50d8ae3SPaolo Bonzini 			break;
6160c50d8ae3SPaolo Bonzini 
6161c50d8ae3SPaolo Bonzini 		/*
6162f95eec9bSSean Christopherson 		 * Invalid pages should never land back on the list of active
6163f95eec9bSSean Christopherson 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
6164f95eec9bSSean Christopherson 		 * infinite loop if the page gets put back on the list (again).
6165c50d8ae3SPaolo Bonzini 		 */
616620ba462dSSean Christopherson 		if (WARN_ON_ONCE(sp->role.invalid))
6167c50d8ae3SPaolo Bonzini 			continue;
6168c50d8ae3SPaolo Bonzini 
6169c50d8ae3SPaolo Bonzini 		/*
6170c50d8ae3SPaolo Bonzini 		 * No need to flush the TLB since we're only zapping shadow
6171c50d8ae3SPaolo Bonzini 		 * pages with an obsolete generation number and all vCPUS have
6172c50d8ae3SPaolo Bonzini 		 * loaded a new root, i.e. the shadow pages being zapped cannot
6173c50d8ae3SPaolo Bonzini 		 * be in active use by the guest.
6174c50d8ae3SPaolo Bonzini 		 */
6175c50d8ae3SPaolo Bonzini 		if (batch >= BATCH_ZAP_PAGES &&
6176531810caSBen Gardon 		    cond_resched_rwlock_write(&kvm->mmu_lock)) {
6177c50d8ae3SPaolo Bonzini 			batch = 0;
6178c50d8ae3SPaolo Bonzini 			goto restart;
6179c50d8ae3SPaolo Bonzini 		}
6180c50d8ae3SPaolo Bonzini 
6181b28cb0cdSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
6182b28cb0cdSSean Christopherson 				&kvm->arch.zapped_obsolete_pages, &nr_zapped);
6183c50d8ae3SPaolo Bonzini 		batch += nr_zapped;
6184b28cb0cdSSean Christopherson 
6185b28cb0cdSSean Christopherson 		if (unstable)
6186c50d8ae3SPaolo Bonzini 			goto restart;
6187c50d8ae3SPaolo Bonzini 	}
6188c50d8ae3SPaolo Bonzini 
6189c50d8ae3SPaolo Bonzini 	/*
61907ae5840eSSean Christopherson 	 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
61917ae5840eSSean Christopherson 	 * to ensure KVM is not in the middle of a lockless shadow page table
61927ae5840eSSean Christopherson 	 * walk, which may reference the pages.  The remote TLB flush itself is
61937ae5840eSSean Christopherson 	 * not required and is simply a convenient way to kick vCPUs as needed.
61947ae5840eSSean Christopherson 	 * KVM performs a local TLB flush when allocating a new root (see
61957ae5840eSSean Christopherson 	 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
61967ae5840eSSean Christopherson 	 * running with an obsolete MMU.
6197c50d8ae3SPaolo Bonzini 	 */
6198c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
6199c50d8ae3SPaolo Bonzini }
6200c50d8ae3SPaolo Bonzini 
6201c50d8ae3SPaolo Bonzini /*
6202c50d8ae3SPaolo Bonzini  * Fast invalidate all shadow pages and use lock-break technique
6203c50d8ae3SPaolo Bonzini  * to zap obsolete pages.
6204c50d8ae3SPaolo Bonzini  *
6205c50d8ae3SPaolo Bonzini  * It's required when memslot is being deleted or VM is being
6206c50d8ae3SPaolo Bonzini  * destroyed, in these cases, we should ensure that KVM MMU does
6207c50d8ae3SPaolo Bonzini  * not use any resource of the being-deleted slot or all slots
6208c50d8ae3SPaolo Bonzini  * after calling the function.
6209c50d8ae3SPaolo Bonzini  */
6210c50d8ae3SPaolo Bonzini static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6211c50d8ae3SPaolo Bonzini {
6212c50d8ae3SPaolo Bonzini 	lockdep_assert_held(&kvm->slots_lock);
6213c50d8ae3SPaolo Bonzini 
6214531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6215c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_zap_all_fast(kvm);
6216c50d8ae3SPaolo Bonzini 
6217c50d8ae3SPaolo Bonzini 	/*
6218c50d8ae3SPaolo Bonzini 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
6219c50d8ae3SPaolo Bonzini 	 * held for the entire duration of zapping obsolete pages, it's
6220c50d8ae3SPaolo Bonzini 	 * impossible for there to be multiple invalid generations associated
6221c50d8ae3SPaolo Bonzini 	 * with *valid* shadow pages at any given time, i.e. there is exactly
6222c50d8ae3SPaolo Bonzini 	 * one valid generation and (at most) one invalid generation.
6223c50d8ae3SPaolo Bonzini 	 */
6224c50d8ae3SPaolo Bonzini 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6225c50d8ae3SPaolo Bonzini 
62262f6f66ccSSean Christopherson 	/*
62272f6f66ccSSean Christopherson 	 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
62282f6f66ccSSean Christopherson 	 * invalidating TDP MMU roots must be done while holding mmu_lock for
62292f6f66ccSSean Christopherson 	 * write and in the same critical section as making the reload request,
62302f6f66ccSSean Christopherson 	 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6231b7cccd39SBen Gardon 	 */
62321f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6233b7cccd39SBen Gardon 		kvm_tdp_mmu_invalidate_all_roots(kvm);
6234b7cccd39SBen Gardon 
6235c50d8ae3SPaolo Bonzini 	/*
6236c50d8ae3SPaolo Bonzini 	 * Notify all vcpus to reload its shadow page table and flush TLB.
6237c50d8ae3SPaolo Bonzini 	 * Then all vcpus will switch to new shadow page table with the new
6238c50d8ae3SPaolo Bonzini 	 * mmu_valid_gen.
6239c50d8ae3SPaolo Bonzini 	 *
6240c50d8ae3SPaolo Bonzini 	 * Note: we need to do this under the protection of mmu_lock,
6241c50d8ae3SPaolo Bonzini 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
6242c50d8ae3SPaolo Bonzini 	 */
6243527d5cd7SSean Christopherson 	kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6244c50d8ae3SPaolo Bonzini 
6245c50d8ae3SPaolo Bonzini 	kvm_zap_obsolete_pages(kvm);
6246faaf05b0SBen Gardon 
6247531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
62484c6654bdSBen Gardon 
6249f28e9c7fSSean Christopherson 	/*
6250f28e9c7fSSean Christopherson 	 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6251f28e9c7fSSean Christopherson 	 * returning to the caller, e.g. if the zap is in response to a memslot
6252f28e9c7fSSean Christopherson 	 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6253f28e9c7fSSean Christopherson 	 * associated with the deleted memslot once the update completes, and
6254f28e9c7fSSean Christopherson 	 * Deferring the zap until the final reference to the root is put would
6255f28e9c7fSSean Christopherson 	 * lead to use-after-free.
6256f28e9c7fSSean Christopherson 	 */
62571f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
62584c6654bdSBen Gardon 		kvm_tdp_mmu_zap_invalidated_roots(kvm);
6259c50d8ae3SPaolo Bonzini }
6260c50d8ae3SPaolo Bonzini 
6261c50d8ae3SPaolo Bonzini static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
6262c50d8ae3SPaolo Bonzini {
6263c50d8ae3SPaolo Bonzini 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
6264c50d8ae3SPaolo Bonzini }
6265c50d8ae3SPaolo Bonzini 
62660df9dab8SSean Christopherson void kvm_mmu_init_vm(struct kvm *kvm)
6267c50d8ae3SPaolo Bonzini {
6268a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6269a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
627055c510e2SSean Christopherson 	INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6271ce25681dSSean Christopherson 	spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6272ce25681dSSean Christopherson 
62730df9dab8SSean Christopherson 	if (tdp_mmu_enabled)
62740df9dab8SSean Christopherson 		kvm_mmu_init_tdp_mmu(kvm);
6275fe5db27dSBen Gardon 
6276ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6277ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6278ada51a9dSDavid Matlack 
6279ada51a9dSDavid Matlack 	kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6280ada51a9dSDavid Matlack 
6281ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6282ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6283c50d8ae3SPaolo Bonzini }
6284c50d8ae3SPaolo Bonzini 
6285ada51a9dSDavid Matlack static void mmu_free_vm_memory_caches(struct kvm *kvm)
6286ada51a9dSDavid Matlack {
6287ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6288ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6289ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6290ada51a9dSDavid Matlack }
6291ada51a9dSDavid Matlack 
6292c50d8ae3SPaolo Bonzini void kvm_mmu_uninit_vm(struct kvm *kvm)
6293c50d8ae3SPaolo Bonzini {
629409732d2bSDavid Matlack 	if (tdp_mmu_enabled)
6295fe5db27dSBen Gardon 		kvm_mmu_uninit_tdp_mmu(kvm);
6296ada51a9dSDavid Matlack 
6297ada51a9dSDavid Matlack 	mmu_free_vm_memory_caches(kvm);
6298c50d8ae3SPaolo Bonzini }
6299c50d8ae3SPaolo Bonzini 
63002833eda0SSean Christopherson static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
630121fa3246SSean Christopherson {
630221fa3246SSean Christopherson 	const struct kvm_memory_slot *memslot;
630321fa3246SSean Christopherson 	struct kvm_memslots *slots;
6304f4209439SMaciej S. Szmigiero 	struct kvm_memslot_iter iter;
630521fa3246SSean Christopherson 	bool flush = false;
630621fa3246SSean Christopherson 	gfn_t start, end;
6307f4209439SMaciej S. Szmigiero 	int i;
630821fa3246SSean Christopherson 
630921fa3246SSean Christopherson 	if (!kvm_memslots_have_rmaps(kvm))
631021fa3246SSean Christopherson 		return flush;
631121fa3246SSean Christopherson 
631221fa3246SSean Christopherson 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
631321fa3246SSean Christopherson 		slots = __kvm_memslots(kvm, i);
6314f4209439SMaciej S. Szmigiero 
6315f4209439SMaciej S. Szmigiero 		kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6316f4209439SMaciej S. Szmigiero 			memslot = iter.slot;
631721fa3246SSean Christopherson 			start = max(gfn_start, memslot->base_gfn);
631821fa3246SSean Christopherson 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
6319f4209439SMaciej S. Szmigiero 			if (WARN_ON_ONCE(start >= end))
632021fa3246SSean Christopherson 				continue;
632121fa3246SSean Christopherson 
6322727ae377SSean Christopherson 			flush = __walk_slot_rmaps(kvm, memslot, __kvm_zap_rmap,
632321fa3246SSean Christopherson 						  PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
632421fa3246SSean Christopherson 						  start, end - 1, true, flush);
632521fa3246SSean Christopherson 		}
632621fa3246SSean Christopherson 	}
632721fa3246SSean Christopherson 
632821fa3246SSean Christopherson 	return flush;
632921fa3246SSean Christopherson }
633021fa3246SSean Christopherson 
633188f58535SMaxim Levitsky /*
633288f58535SMaxim Levitsky  * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
633388f58535SMaxim Levitsky  * (not including it)
633488f58535SMaxim Levitsky  */
6335c50d8ae3SPaolo Bonzini void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6336c50d8ae3SPaolo Bonzini {
633721fa3246SSean Christopherson 	bool flush;
6338c50d8ae3SPaolo Bonzini 
6339f4209439SMaciej S. Szmigiero 	if (WARN_ON_ONCE(gfn_end <= gfn_start))
6340f4209439SMaciej S. Szmigiero 		return;
6341f4209439SMaciej S. Szmigiero 
6342531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
63435a324c24SSean Christopherson 
63448569992dSChao Peng 	kvm_mmu_invalidate_begin(kvm);
63458569992dSChao Peng 
63468569992dSChao Peng 	kvm_mmu_invalidate_range_add(kvm, gfn_start, gfn_end);
6347edb298c6SMaxim Levitsky 
63482833eda0SSean Christopherson 	flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
63496103bc07SBen Gardon 
6350441a5dfcSPaolo Bonzini 	if (tdp_mmu_enabled)
6351441a5dfcSPaolo Bonzini 		flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush);
63525a324c24SSean Christopherson 
63535a324c24SSean Christopherson 	if (flush)
63548c63e8c2SDavid Matlack 		kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);
63555a324c24SSean Christopherson 
63568569992dSChao Peng 	kvm_mmu_invalidate_end(kvm);
6357edb298c6SMaxim Levitsky 
63585a324c24SSean Christopherson 	write_unlock(&kvm->mmu_lock);
6359c50d8ae3SPaolo Bonzini }
6360c50d8ae3SPaolo Bonzini 
6361c50d8ae3SPaolo Bonzini static bool slot_rmap_write_protect(struct kvm *kvm,
63620a234f5dSSean Christopherson 				    struct kvm_rmap_head *rmap_head,
6363269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot)
6364c50d8ae3SPaolo Bonzini {
63651346bbb6SDavid Matlack 	return rmap_write_protect(rmap_head, false);
6366c50d8ae3SPaolo Bonzini }
6367c50d8ae3SPaolo Bonzini 
6368c50d8ae3SPaolo Bonzini void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6369269e9552SHamza Mahfooz 				      const struct kvm_memory_slot *memslot,
63703c9bd400SJay Zhou 				      int start_level)
6371c50d8ae3SPaolo Bonzini {
6372e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6373531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6374727ae377SSean Christopherson 		walk_slot_rmaps(kvm, memslot, slot_rmap_write_protect,
6375b64d740eSJunaid Shahid 				start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6376531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6377e2209710SBen Gardon 	}
6378c50d8ae3SPaolo Bonzini 
63791f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
638024ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6381b64d740eSJunaid Shahid 		kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
638224ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
638324ae4cfaSBen Gardon 	}
6384c50d8ae3SPaolo Bonzini }
6385c50d8ae3SPaolo Bonzini 
6386ada51a9dSDavid Matlack static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6387ada51a9dSDavid Matlack {
6388ada51a9dSDavid Matlack 	return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6389ada51a9dSDavid Matlack }
6390ada51a9dSDavid Matlack 
6391ada51a9dSDavid Matlack static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6392ada51a9dSDavid Matlack {
6393ada51a9dSDavid Matlack 	if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6394ada51a9dSDavid Matlack 		return true;
6395ada51a9dSDavid Matlack 
6396ada51a9dSDavid Matlack 	/*
6397ada51a9dSDavid Matlack 	 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6398ada51a9dSDavid Matlack 	 * to split a single huge page. Calculating how many are actually needed
6399ada51a9dSDavid Matlack 	 * is possible but not worth the complexity.
6400ada51a9dSDavid Matlack 	 */
6401ada51a9dSDavid Matlack 	return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6402ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_page_header_cache, 1) ||
6403ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_shadow_page_cache, 1);
6404ada51a9dSDavid Matlack }
6405ada51a9dSDavid Matlack 
6406ada51a9dSDavid Matlack static int topup_split_caches(struct kvm *kvm)
6407ada51a9dSDavid Matlack {
6408b9b71f43SSean Christopherson 	/*
6409b9b71f43SSean Christopherson 	 * Allocating rmap list entries when splitting huge pages for nested
6410dfd4eb44SSean Christopherson 	 * MMUs is uncommon as KVM needs to use a list if and only if there is
6411b9b71f43SSean Christopherson 	 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6412dfd4eb44SSean Christopherson 	 * aliased by multiple L2 gfns and/or from multiple nested roots with
6413dfd4eb44SSean Christopherson 	 * different roles.  Aliasing gfns when using TDP is atypical for VMMs;
6414dfd4eb44SSean Christopherson 	 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6415dfd4eb44SSean Christopherson 	 * but aliasing rarely occurs post-boot or for many gfns.  If there is
6416dfd4eb44SSean Christopherson 	 * only one rmap entry, rmap->val points directly at that one entry and
6417dfd4eb44SSean Christopherson 	 * doesn't need to allocate a list.  Buffer the cache by the default
6418dfd4eb44SSean Christopherson 	 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6419b9b71f43SSean Christopherson 	 * encounters an aliased gfn or two.
6420b9b71f43SSean Christopherson 	 */
6421b9b71f43SSean Christopherson 	const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6422b9b71f43SSean Christopherson 			     KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6423ada51a9dSDavid Matlack 	int r;
6424ada51a9dSDavid Matlack 
6425ada51a9dSDavid Matlack 	lockdep_assert_held(&kvm->slots_lock);
6426ada51a9dSDavid Matlack 
6427b9b71f43SSean Christopherson 	r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6428ada51a9dSDavid Matlack 					 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6429ada51a9dSDavid Matlack 	if (r)
6430ada51a9dSDavid Matlack 		return r;
6431ada51a9dSDavid Matlack 
6432ada51a9dSDavid Matlack 	r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6433ada51a9dSDavid Matlack 	if (r)
6434ada51a9dSDavid Matlack 		return r;
6435ada51a9dSDavid Matlack 
6436ada51a9dSDavid Matlack 	return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6437ada51a9dSDavid Matlack }
6438ada51a9dSDavid Matlack 
6439ada51a9dSDavid Matlack static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6440ada51a9dSDavid Matlack {
6441ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6442ada51a9dSDavid Matlack 	struct shadow_page_caches caches = {};
6443ada51a9dSDavid Matlack 	union kvm_mmu_page_role role;
6444ada51a9dSDavid Matlack 	unsigned int access;
6445ada51a9dSDavid Matlack 	gfn_t gfn;
6446ada51a9dSDavid Matlack 
644779e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
644879e48cecSSean Christopherson 	access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6449ada51a9dSDavid Matlack 
6450ada51a9dSDavid Matlack 	/*
6451ada51a9dSDavid Matlack 	 * Note, huge page splitting always uses direct shadow pages, regardless
6452ada51a9dSDavid Matlack 	 * of whether the huge page itself is mapped by a direct or indirect
6453ada51a9dSDavid Matlack 	 * shadow page, since the huge page region itself is being directly
6454ada51a9dSDavid Matlack 	 * mapped with smaller pages.
6455ada51a9dSDavid Matlack 	 */
6456ada51a9dSDavid Matlack 	role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6457ada51a9dSDavid Matlack 
6458ada51a9dSDavid Matlack 	/* Direct SPs do not require a shadowed_info_cache. */
6459ada51a9dSDavid Matlack 	caches.page_header_cache = &kvm->arch.split_page_header_cache;
6460ada51a9dSDavid Matlack 	caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6461ada51a9dSDavid Matlack 
6462ada51a9dSDavid Matlack 	/* Safe to pass NULL for vCPU since requesting a direct SP. */
6463ada51a9dSDavid Matlack 	return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6464ada51a9dSDavid Matlack }
6465ada51a9dSDavid Matlack 
6466ada51a9dSDavid Matlack static void shadow_mmu_split_huge_page(struct kvm *kvm,
6467ada51a9dSDavid Matlack 				       const struct kvm_memory_slot *slot,
6468ada51a9dSDavid Matlack 				       u64 *huge_sptep)
6469ada51a9dSDavid Matlack 
6470ada51a9dSDavid Matlack {
6471ada51a9dSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6472ada51a9dSDavid Matlack 	u64 huge_spte = READ_ONCE(*huge_sptep);
6473ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
647403787394SPaolo Bonzini 	bool flush = false;
6475ada51a9dSDavid Matlack 	u64 *sptep, spte;
6476ada51a9dSDavid Matlack 	gfn_t gfn;
6477ada51a9dSDavid Matlack 	int index;
6478ada51a9dSDavid Matlack 
6479ada51a9dSDavid Matlack 	sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6480ada51a9dSDavid Matlack 
6481ada51a9dSDavid Matlack 	for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6482ada51a9dSDavid Matlack 		sptep = &sp->spt[index];
6483ada51a9dSDavid Matlack 		gfn = kvm_mmu_page_get_gfn(sp, index);
6484ada51a9dSDavid Matlack 
6485ada51a9dSDavid Matlack 		/*
6486ada51a9dSDavid Matlack 		 * The SP may already have populated SPTEs, e.g. if this huge
6487ada51a9dSDavid Matlack 		 * page is aliased by multiple sptes with the same access
6488ada51a9dSDavid Matlack 		 * permissions. These entries are guaranteed to map the same
6489ada51a9dSDavid Matlack 		 * gfn-to-pfn translation since the SP is direct, so no need to
6490ada51a9dSDavid Matlack 		 * modify them.
6491ada51a9dSDavid Matlack 		 *
649203787394SPaolo Bonzini 		 * However, if a given SPTE points to a lower level page table,
649303787394SPaolo Bonzini 		 * that lower level page table may only be partially populated.
649403787394SPaolo Bonzini 		 * Installing such SPTEs would effectively unmap a potion of the
649503787394SPaolo Bonzini 		 * huge page. Unmapping guest memory always requires a TLB flush
649603787394SPaolo Bonzini 		 * since a subsequent operation on the unmapped regions would
649703787394SPaolo Bonzini 		 * fail to detect the need to flush.
6498ada51a9dSDavid Matlack 		 */
649903787394SPaolo Bonzini 		if (is_shadow_present_pte(*sptep)) {
650003787394SPaolo Bonzini 			flush |= !is_last_spte(*sptep, sp->role.level);
6501ada51a9dSDavid Matlack 			continue;
650203787394SPaolo Bonzini 		}
6503ada51a9dSDavid Matlack 
6504ada51a9dSDavid Matlack 		spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
6505ada51a9dSDavid Matlack 		mmu_spte_set(sptep, spte);
6506ada51a9dSDavid Matlack 		__rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6507ada51a9dSDavid Matlack 	}
6508ada51a9dSDavid Matlack 
650903787394SPaolo Bonzini 	__link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6510ada51a9dSDavid Matlack }
6511ada51a9dSDavid Matlack 
6512ada51a9dSDavid Matlack static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6513ada51a9dSDavid Matlack 					  const struct kvm_memory_slot *slot,
6514ada51a9dSDavid Matlack 					  u64 *huge_sptep)
6515ada51a9dSDavid Matlack {
6516ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6517ada51a9dSDavid Matlack 	int level, r = 0;
6518ada51a9dSDavid Matlack 	gfn_t gfn;
6519ada51a9dSDavid Matlack 	u64 spte;
6520ada51a9dSDavid Matlack 
6521ada51a9dSDavid Matlack 	/* Grab information for the tracepoint before dropping the MMU lock. */
652279e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6523ada51a9dSDavid Matlack 	level = huge_sp->role.level;
6524ada51a9dSDavid Matlack 	spte = *huge_sptep;
6525ada51a9dSDavid Matlack 
6526ada51a9dSDavid Matlack 	if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6527ada51a9dSDavid Matlack 		r = -ENOSPC;
6528ada51a9dSDavid Matlack 		goto out;
6529ada51a9dSDavid Matlack 	}
6530ada51a9dSDavid Matlack 
6531ada51a9dSDavid Matlack 	if (need_topup_split_caches_or_resched(kvm)) {
6532ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6533ada51a9dSDavid Matlack 		cond_resched();
6534ada51a9dSDavid Matlack 		/*
6535ada51a9dSDavid Matlack 		 * If the topup succeeds, return -EAGAIN to indicate that the
6536ada51a9dSDavid Matlack 		 * rmap iterator should be restarted because the MMU lock was
6537ada51a9dSDavid Matlack 		 * dropped.
6538ada51a9dSDavid Matlack 		 */
6539ada51a9dSDavid Matlack 		r = topup_split_caches(kvm) ?: -EAGAIN;
6540ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6541ada51a9dSDavid Matlack 		goto out;
6542ada51a9dSDavid Matlack 	}
6543ada51a9dSDavid Matlack 
6544ada51a9dSDavid Matlack 	shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6545ada51a9dSDavid Matlack 
6546ada51a9dSDavid Matlack out:
6547ada51a9dSDavid Matlack 	trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6548ada51a9dSDavid Matlack 	return r;
6549ada51a9dSDavid Matlack }
6550ada51a9dSDavid Matlack 
6551ada51a9dSDavid Matlack static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6552ada51a9dSDavid Matlack 					    struct kvm_rmap_head *rmap_head,
6553ada51a9dSDavid Matlack 					    const struct kvm_memory_slot *slot)
6554ada51a9dSDavid Matlack {
6555ada51a9dSDavid Matlack 	struct rmap_iterator iter;
6556ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
6557ada51a9dSDavid Matlack 	u64 *huge_sptep;
6558ada51a9dSDavid Matlack 	int r;
6559ada51a9dSDavid Matlack 
6560ada51a9dSDavid Matlack restart:
6561ada51a9dSDavid Matlack 	for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6562ada51a9dSDavid Matlack 		sp = sptep_to_sp(huge_sptep);
6563ada51a9dSDavid Matlack 
6564ada51a9dSDavid Matlack 		/* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6565ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!sp->role.guest_mode))
6566ada51a9dSDavid Matlack 			continue;
6567ada51a9dSDavid Matlack 
6568ada51a9dSDavid Matlack 		/* The rmaps should never contain non-leaf SPTEs. */
6569ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6570ada51a9dSDavid Matlack 			continue;
6571ada51a9dSDavid Matlack 
6572ada51a9dSDavid Matlack 		/* SPs with level >PG_LEVEL_4K should never by unsync. */
6573ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(sp->unsync))
6574ada51a9dSDavid Matlack 			continue;
6575ada51a9dSDavid Matlack 
6576ada51a9dSDavid Matlack 		/* Don't bother splitting huge pages on invalid SPs. */
6577ada51a9dSDavid Matlack 		if (sp->role.invalid)
6578ada51a9dSDavid Matlack 			continue;
6579ada51a9dSDavid Matlack 
6580ada51a9dSDavid Matlack 		r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6581ada51a9dSDavid Matlack 
6582ada51a9dSDavid Matlack 		/*
6583ada51a9dSDavid Matlack 		 * The split succeeded or needs to be retried because the MMU
6584ada51a9dSDavid Matlack 		 * lock was dropped. Either way, restart the iterator to get it
6585ada51a9dSDavid Matlack 		 * back into a consistent state.
6586ada51a9dSDavid Matlack 		 */
6587ada51a9dSDavid Matlack 		if (!r || r == -EAGAIN)
6588ada51a9dSDavid Matlack 			goto restart;
6589ada51a9dSDavid Matlack 
6590ada51a9dSDavid Matlack 		/* The split failed and shouldn't be retried (e.g. -ENOMEM). */
6591ada51a9dSDavid Matlack 		break;
6592ada51a9dSDavid Matlack 	}
6593ada51a9dSDavid Matlack 
6594ada51a9dSDavid Matlack 	return false;
6595ada51a9dSDavid Matlack }
6596ada51a9dSDavid Matlack 
6597ada51a9dSDavid Matlack static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6598ada51a9dSDavid Matlack 						const struct kvm_memory_slot *slot,
6599ada51a9dSDavid Matlack 						gfn_t start, gfn_t end,
6600ada51a9dSDavid Matlack 						int target_level)
6601ada51a9dSDavid Matlack {
6602ada51a9dSDavid Matlack 	int level;
6603ada51a9dSDavid Matlack 
6604ada51a9dSDavid Matlack 	/*
6605ada51a9dSDavid Matlack 	 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
6606ada51a9dSDavid Matlack 	 * down to the target level. This ensures pages are recursively split
6607ada51a9dSDavid Matlack 	 * all the way to the target level. There's no need to split pages
6608ada51a9dSDavid Matlack 	 * already at the target level.
6609ada51a9dSDavid Matlack 	 */
6610727ae377SSean Christopherson 	for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--)
6611727ae377SSean Christopherson 		__walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,
6612ada51a9dSDavid Matlack 				  level, level, start, end - 1, true, false);
6613ada51a9dSDavid Matlack }
6614ada51a9dSDavid Matlack 
6615cb00a70bSDavid Matlack /* Must be called with the mmu_lock held in write-mode. */
6616cb00a70bSDavid Matlack void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6617cb00a70bSDavid Matlack 				   const struct kvm_memory_slot *memslot,
6618cb00a70bSDavid Matlack 				   u64 start, u64 end,
6619cb00a70bSDavid Matlack 				   int target_level)
6620cb00a70bSDavid Matlack {
66211f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6622ada51a9dSDavid Matlack 		return;
6623ada51a9dSDavid Matlack 
6624ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm))
6625ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6626ada51a9dSDavid Matlack 
6627ada51a9dSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
6628cb00a70bSDavid Matlack 
6629cb00a70bSDavid Matlack 	/*
6630cb00a70bSDavid Matlack 	 * A TLB flush is unnecessary at this point for the same resons as in
6631cb00a70bSDavid Matlack 	 * kvm_mmu_slot_try_split_huge_pages().
6632cb00a70bSDavid Matlack 	 */
6633cb00a70bSDavid Matlack }
6634cb00a70bSDavid Matlack 
6635a3fe5dbdSDavid Matlack void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6636a3fe5dbdSDavid Matlack 					const struct kvm_memory_slot *memslot,
6637a3fe5dbdSDavid Matlack 					int target_level)
6638a3fe5dbdSDavid Matlack {
6639a3fe5dbdSDavid Matlack 	u64 start = memslot->base_gfn;
6640a3fe5dbdSDavid Matlack 	u64 end = start + memslot->npages;
6641a3fe5dbdSDavid Matlack 
66421f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6643ada51a9dSDavid Matlack 		return;
6644ada51a9dSDavid Matlack 
6645ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm)) {
6646ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6647ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6648ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6649ada51a9dSDavid Matlack 	}
6650ada51a9dSDavid Matlack 
6651a3fe5dbdSDavid Matlack 	read_lock(&kvm->mmu_lock);
6652cb00a70bSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6653a3fe5dbdSDavid Matlack 	read_unlock(&kvm->mmu_lock);
6654a3fe5dbdSDavid Matlack 
6655a3fe5dbdSDavid Matlack 	/*
6656a3fe5dbdSDavid Matlack 	 * No TLB flush is necessary here. KVM will flush TLBs after
6657a3fe5dbdSDavid Matlack 	 * write-protecting and/or clearing dirty on the newly split SPTEs to
6658a3fe5dbdSDavid Matlack 	 * ensure that guest writes are reflected in the dirty log before the
6659a3fe5dbdSDavid Matlack 	 * ioctl to enable dirty logging on this memslot completes. Since the
6660a3fe5dbdSDavid Matlack 	 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6661a3fe5dbdSDavid Matlack 	 * safe for KVM to decide if a TLB flush is necessary based on the split
6662a3fe5dbdSDavid Matlack 	 * SPTEs.
6663a3fe5dbdSDavid Matlack 	 */
6664a3fe5dbdSDavid Matlack }
6665a3fe5dbdSDavid Matlack 
6666c50d8ae3SPaolo Bonzini static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
66670a234f5dSSean Christopherson 					 struct kvm_rmap_head *rmap_head,
6668269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
6669c50d8ae3SPaolo Bonzini {
6670c50d8ae3SPaolo Bonzini 	u64 *sptep;
6671c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
6672c50d8ae3SPaolo Bonzini 	int need_tlb_flush = 0;
6673c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6674c50d8ae3SPaolo Bonzini 
6675c50d8ae3SPaolo Bonzini restart:
6676c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
667757354682SSean Christopherson 		sp = sptep_to_sp(sptep);
6678c50d8ae3SPaolo Bonzini 
6679c50d8ae3SPaolo Bonzini 		/*
6680c50d8ae3SPaolo Bonzini 		 * We cannot do huge page mapping for indirect shadow pages,
6681c50d8ae3SPaolo Bonzini 		 * which are found on the last rmap (level = 1) when not using
6682c50d8ae3SPaolo Bonzini 		 * tdp; such shadow pages are synced with the page table in
6683c50d8ae3SPaolo Bonzini 		 * the guest, and the guest page table is using 4K page size
6684c50d8ae3SPaolo Bonzini 		 * mapping if the indirect sp has level = 1.
6685c50d8ae3SPaolo Bonzini 		 */
66865d49f08cSSean Christopherson 		if (sp->role.direct &&
66879eba50f8SSean Christopherson 		    sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
6688a8ac499bSSean Christopherson 							       PG_LEVEL_NUM)) {
66899202aee8SSean Christopherson 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
6690c50d8ae3SPaolo Bonzini 
66918a1300ffSSean Christopherson 			if (kvm_available_flush_remote_tlbs_range())
66921b2dc736SHou Wenlong 				kvm_flush_remote_tlbs_sptep(kvm, sptep);
6693c50d8ae3SPaolo Bonzini 			else
6694c50d8ae3SPaolo Bonzini 				need_tlb_flush = 1;
6695c50d8ae3SPaolo Bonzini 
6696c50d8ae3SPaolo Bonzini 			goto restart;
6697c50d8ae3SPaolo Bonzini 		}
6698c50d8ae3SPaolo Bonzini 	}
6699c50d8ae3SPaolo Bonzini 
6700c50d8ae3SPaolo Bonzini 	return need_tlb_flush;
6701c50d8ae3SPaolo Bonzini }
6702c50d8ae3SPaolo Bonzini 
670320d49186SDavid Matlack static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
670420d49186SDavid Matlack 					   const struct kvm_memory_slot *slot)
670520d49186SDavid Matlack {
670620d49186SDavid Matlack 	/*
670720d49186SDavid Matlack 	 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
670820d49186SDavid Matlack 	 * pages that are already mapped at the maximum hugepage level.
670920d49186SDavid Matlack 	 */
6710727ae377SSean Christopherson 	if (walk_slot_rmaps(kvm, slot, kvm_mmu_zap_collapsible_spte,
671120d49186SDavid Matlack 			    PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
6712619b5072SDavid Matlack 		kvm_flush_remote_tlbs_memslot(kvm, slot);
671320d49186SDavid Matlack }
671420d49186SDavid Matlack 
6715c50d8ae3SPaolo Bonzini void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6716269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *slot)
6717c50d8ae3SPaolo Bonzini {
6718e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6719531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
672020d49186SDavid Matlack 		kvm_rmap_zap_collapsible_sptes(kvm, slot);
6721531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6722e2209710SBen Gardon 	}
67232db6f772SBen Gardon 
67241f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
67252db6f772SBen Gardon 		read_lock(&kvm->mmu_lock);
67264b85c921SSean Christopherson 		kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
67272db6f772SBen Gardon 		read_unlock(&kvm->mmu_lock);
67282db6f772SBen Gardon 	}
6729c50d8ae3SPaolo Bonzini }
6730c50d8ae3SPaolo Bonzini 
6731c50d8ae3SPaolo Bonzini void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6732269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *memslot)
6733c50d8ae3SPaolo Bonzini {
6734e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6735531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6736610265eaSDavid Matlack 		/*
6737610265eaSDavid Matlack 		 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6738610265eaSDavid Matlack 		 * support dirty logging at a 4k granularity.
6739610265eaSDavid Matlack 		 */
6740727ae377SSean Christopherson 		walk_slot_rmaps_4k(kvm, memslot, __rmap_clear_dirty, false);
6741531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6742e2209710SBen Gardon 	}
6743c50d8ae3SPaolo Bonzini 
67441f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
674524ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6746b64d740eSJunaid Shahid 		kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
674724ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
674824ae4cfaSBen Gardon 	}
674924ae4cfaSBen Gardon 
6750c50d8ae3SPaolo Bonzini 	/*
6751b64d740eSJunaid Shahid 	 * The caller will flush the TLBs after this function returns.
6752b64d740eSJunaid Shahid 	 *
6753c50d8ae3SPaolo Bonzini 	 * It's also safe to flush TLBs out of mmu lock here as currently this
6754c50d8ae3SPaolo Bonzini 	 * function is only used for dirty logging, in which case flushing TLB
6755c50d8ae3SPaolo Bonzini 	 * out of mmu lock also guarantees no dirty pages will be lost in
6756c50d8ae3SPaolo Bonzini 	 * dirty_bitmap.
6757c50d8ae3SPaolo Bonzini 	 */
6758c50d8ae3SPaolo Bonzini }
6759c50d8ae3SPaolo Bonzini 
6760db0d70e6SSean Christopherson static void kvm_mmu_zap_all(struct kvm *kvm)
6761c50d8ae3SPaolo Bonzini {
6762c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6763c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6764c50d8ae3SPaolo Bonzini 	int ign;
6765c50d8ae3SPaolo Bonzini 
6766531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6767c50d8ae3SPaolo Bonzini restart:
6768c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
676920ba462dSSean Christopherson 		if (WARN_ON_ONCE(sp->role.invalid))
6770c50d8ae3SPaolo Bonzini 			continue;
6771c50d8ae3SPaolo Bonzini 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6772c50d8ae3SPaolo Bonzini 			goto restart;
6773531810caSBen Gardon 		if (cond_resched_rwlock_write(&kvm->mmu_lock))
6774c50d8ae3SPaolo Bonzini 			goto restart;
6775c50d8ae3SPaolo Bonzini 	}
6776c50d8ae3SPaolo Bonzini 
6777c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6778faaf05b0SBen Gardon 
67791f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6780faaf05b0SBen Gardon 		kvm_tdp_mmu_zap_all(kvm);
6781faaf05b0SBen Gardon 
6782531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
6783c50d8ae3SPaolo Bonzini }
6784c50d8ae3SPaolo Bonzini 
6785db0d70e6SSean Christopherson void kvm_arch_flush_shadow_all(struct kvm *kvm)
6786db0d70e6SSean Christopherson {
6787db0d70e6SSean Christopherson 	kvm_mmu_zap_all(kvm);
6788db0d70e6SSean Christopherson }
6789db0d70e6SSean Christopherson 
6790db0d70e6SSean Christopherson void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
6791db0d70e6SSean Christopherson 				   struct kvm_memory_slot *slot)
6792db0d70e6SSean Christopherson {
6793eeb87272SSean Christopherson 	kvm_mmu_zap_all_fast(kvm);
6794db0d70e6SSean Christopherson }
6795db0d70e6SSean Christopherson 
6796c50d8ae3SPaolo Bonzini void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6797c50d8ae3SPaolo Bonzini {
679820ba462dSSean Christopherson 	WARN_ON_ONCE(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6799c50d8ae3SPaolo Bonzini 
6800c50d8ae3SPaolo Bonzini 	gen &= MMIO_SPTE_GEN_MASK;
6801c50d8ae3SPaolo Bonzini 
6802c50d8ae3SPaolo Bonzini 	/*
6803c50d8ae3SPaolo Bonzini 	 * Generation numbers are incremented in multiples of the number of
6804c50d8ae3SPaolo Bonzini 	 * address spaces in order to provide unique generations across all
6805c50d8ae3SPaolo Bonzini 	 * address spaces.  Strip what is effectively the address space
6806c50d8ae3SPaolo Bonzini 	 * modifier prior to checking for a wrap of the MMIO generation so
6807c50d8ae3SPaolo Bonzini 	 * that a wrap in any address space is detected.
6808c50d8ae3SPaolo Bonzini 	 */
6809c50d8ae3SPaolo Bonzini 	gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6810c50d8ae3SPaolo Bonzini 
6811c50d8ae3SPaolo Bonzini 	/*
6812c50d8ae3SPaolo Bonzini 	 * The very rare case: if the MMIO generation number has wrapped,
6813c50d8ae3SPaolo Bonzini 	 * zap all shadow pages.
6814c50d8ae3SPaolo Bonzini 	 */
6815c50d8ae3SPaolo Bonzini 	if (unlikely(gen == 0)) {
68168d20bd63SSean Christopherson 		kvm_debug_ratelimited("zapping shadow pages for mmio generation wraparound\n");
6817c50d8ae3SPaolo Bonzini 		kvm_mmu_zap_all_fast(kvm);
6818c50d8ae3SPaolo Bonzini 	}
6819c50d8ae3SPaolo Bonzini }
6820c50d8ae3SPaolo Bonzini 
6821f3d90f90SSean Christopherson static unsigned long mmu_shrink_scan(struct shrinker *shrink,
6822f3d90f90SSean Christopherson 				     struct shrink_control *sc)
6823c50d8ae3SPaolo Bonzini {
6824c50d8ae3SPaolo Bonzini 	struct kvm *kvm;
6825c50d8ae3SPaolo Bonzini 	int nr_to_scan = sc->nr_to_scan;
6826c50d8ae3SPaolo Bonzini 	unsigned long freed = 0;
6827c50d8ae3SPaolo Bonzini 
6828c50d8ae3SPaolo Bonzini 	mutex_lock(&kvm_lock);
6829c50d8ae3SPaolo Bonzini 
6830c50d8ae3SPaolo Bonzini 	list_for_each_entry(kvm, &vm_list, vm_list) {
6831c50d8ae3SPaolo Bonzini 		int idx;
6832c50d8ae3SPaolo Bonzini 		LIST_HEAD(invalid_list);
6833c50d8ae3SPaolo Bonzini 
6834c50d8ae3SPaolo Bonzini 		/*
6835c50d8ae3SPaolo Bonzini 		 * Never scan more than sc->nr_to_scan VM instances.
6836c50d8ae3SPaolo Bonzini 		 * Will not hit this condition practically since we do not try
6837c50d8ae3SPaolo Bonzini 		 * to shrink more than one VM and it is very unlikely to see
6838c50d8ae3SPaolo Bonzini 		 * !n_used_mmu_pages so many times.
6839c50d8ae3SPaolo Bonzini 		 */
6840c50d8ae3SPaolo Bonzini 		if (!nr_to_scan--)
6841c50d8ae3SPaolo Bonzini 			break;
6842c50d8ae3SPaolo Bonzini 		/*
6843c50d8ae3SPaolo Bonzini 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6844c50d8ae3SPaolo Bonzini 		 * here. We may skip a VM instance errorneosly, but we do not
6845c50d8ae3SPaolo Bonzini 		 * want to shrink a VM that only started to populate its MMU
6846c50d8ae3SPaolo Bonzini 		 * anyway.
6847c50d8ae3SPaolo Bonzini 		 */
6848c50d8ae3SPaolo Bonzini 		if (!kvm->arch.n_used_mmu_pages &&
6849c50d8ae3SPaolo Bonzini 		    !kvm_has_zapped_obsolete_pages(kvm))
6850c50d8ae3SPaolo Bonzini 			continue;
6851c50d8ae3SPaolo Bonzini 
6852c50d8ae3SPaolo Bonzini 		idx = srcu_read_lock(&kvm->srcu);
6853531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6854c50d8ae3SPaolo Bonzini 
6855c50d8ae3SPaolo Bonzini 		if (kvm_has_zapped_obsolete_pages(kvm)) {
6856c50d8ae3SPaolo Bonzini 			kvm_mmu_commit_zap_page(kvm,
6857c50d8ae3SPaolo Bonzini 			      &kvm->arch.zapped_obsolete_pages);
6858c50d8ae3SPaolo Bonzini 			goto unlock;
6859c50d8ae3SPaolo Bonzini 		}
6860c50d8ae3SPaolo Bonzini 
6861ebdb292dSSean Christopherson 		freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6862c50d8ae3SPaolo Bonzini 
6863c50d8ae3SPaolo Bonzini unlock:
6864531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6865c50d8ae3SPaolo Bonzini 		srcu_read_unlock(&kvm->srcu, idx);
6866c50d8ae3SPaolo Bonzini 
6867c50d8ae3SPaolo Bonzini 		/*
6868c50d8ae3SPaolo Bonzini 		 * unfair on small ones
6869c50d8ae3SPaolo Bonzini 		 * per-vm shrinkers cry out
6870c50d8ae3SPaolo Bonzini 		 * sadness comes quickly
6871c50d8ae3SPaolo Bonzini 		 */
6872c50d8ae3SPaolo Bonzini 		list_move_tail(&kvm->vm_list, &vm_list);
6873c50d8ae3SPaolo Bonzini 		break;
6874c50d8ae3SPaolo Bonzini 	}
6875c50d8ae3SPaolo Bonzini 
6876c50d8ae3SPaolo Bonzini 	mutex_unlock(&kvm_lock);
6877c50d8ae3SPaolo Bonzini 	return freed;
6878c50d8ae3SPaolo Bonzini }
6879c50d8ae3SPaolo Bonzini 
6880f3d90f90SSean Christopherson static unsigned long mmu_shrink_count(struct shrinker *shrink,
6881f3d90f90SSean Christopherson 				      struct shrink_control *sc)
6882c50d8ae3SPaolo Bonzini {
6883c50d8ae3SPaolo Bonzini 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6884c50d8ae3SPaolo Bonzini }
6885c50d8ae3SPaolo Bonzini 
6886c50d8ae3SPaolo Bonzini static struct shrinker mmu_shrinker = {
6887c50d8ae3SPaolo Bonzini 	.count_objects = mmu_shrink_count,
6888c50d8ae3SPaolo Bonzini 	.scan_objects = mmu_shrink_scan,
6889c50d8ae3SPaolo Bonzini 	.seeks = DEFAULT_SEEKS * 10,
6890c50d8ae3SPaolo Bonzini };
6891c50d8ae3SPaolo Bonzini 
6892c50d8ae3SPaolo Bonzini static void mmu_destroy_caches(void)
6893c50d8ae3SPaolo Bonzini {
6894c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(pte_list_desc_cache);
6895c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(mmu_page_header_cache);
6896c50d8ae3SPaolo Bonzini }
6897c50d8ae3SPaolo Bonzini 
68980b210fafSSean Christopherson static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp)
68990b210fafSSean Christopherson {
69000b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
69011d6664faSLike Xu 		return sysfs_emit(buffer, "never\n");
69020b210fafSSean Christopherson 
69030b210fafSSean Christopherson 	return param_get_bool(buffer, kp);
69040b210fafSSean Christopherson }
69050b210fafSSean Christopherson 
6906c50d8ae3SPaolo Bonzini static bool get_nx_auto_mode(void)
6907c50d8ae3SPaolo Bonzini {
6908c50d8ae3SPaolo Bonzini 	/* Return true when CPU has the bug, and mitigations are ON */
6909c50d8ae3SPaolo Bonzini 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6910c50d8ae3SPaolo Bonzini }
6911c50d8ae3SPaolo Bonzini 
6912c50d8ae3SPaolo Bonzini static void __set_nx_huge_pages(bool val)
6913c50d8ae3SPaolo Bonzini {
6914c50d8ae3SPaolo Bonzini 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6915c50d8ae3SPaolo Bonzini }
6916c50d8ae3SPaolo Bonzini 
6917c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6918c50d8ae3SPaolo Bonzini {
6919c50d8ae3SPaolo Bonzini 	bool old_val = nx_huge_pages;
6920c50d8ae3SPaolo Bonzini 	bool new_val;
6921c50d8ae3SPaolo Bonzini 
69220b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
69230b210fafSSean Christopherson 		return -EPERM;
69240b210fafSSean Christopherson 
6925c50d8ae3SPaolo Bonzini 	/* In "auto" mode deploy workaround only if CPU has the bug. */
69260b210fafSSean Christopherson 	if (sysfs_streq(val, "off")) {
6927c50d8ae3SPaolo Bonzini 		new_val = 0;
69280b210fafSSean Christopherson 	} else if (sysfs_streq(val, "force")) {
6929c50d8ae3SPaolo Bonzini 		new_val = 1;
69300b210fafSSean Christopherson 	} else if (sysfs_streq(val, "auto")) {
6931c50d8ae3SPaolo Bonzini 		new_val = get_nx_auto_mode();
69320b210fafSSean Christopherson 	} else if (sysfs_streq(val, "never")) {
69330b210fafSSean Christopherson 		new_val = 0;
69340b210fafSSean Christopherson 
69350b210fafSSean Christopherson 		mutex_lock(&kvm_lock);
69360b210fafSSean Christopherson 		if (!list_empty(&vm_list)) {
69370b210fafSSean Christopherson 			mutex_unlock(&kvm_lock);
69380b210fafSSean Christopherson 			return -EBUSY;
69390b210fafSSean Christopherson 		}
69400b210fafSSean Christopherson 		nx_hugepage_mitigation_hard_disabled = true;
69410b210fafSSean Christopherson 		mutex_unlock(&kvm_lock);
69420b210fafSSean Christopherson 	} else if (kstrtobool(val, &new_val) < 0) {
6943c50d8ae3SPaolo Bonzini 		return -EINVAL;
69440b210fafSSean Christopherson 	}
6945c50d8ae3SPaolo Bonzini 
6946c50d8ae3SPaolo Bonzini 	__set_nx_huge_pages(new_val);
6947c50d8ae3SPaolo Bonzini 
6948c50d8ae3SPaolo Bonzini 	if (new_val != old_val) {
6949c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6950c50d8ae3SPaolo Bonzini 
6951c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6952c50d8ae3SPaolo Bonzini 
6953c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list) {
6954c50d8ae3SPaolo Bonzini 			mutex_lock(&kvm->slots_lock);
6955c50d8ae3SPaolo Bonzini 			kvm_mmu_zap_all_fast(kvm);
6956c50d8ae3SPaolo Bonzini 			mutex_unlock(&kvm->slots_lock);
6957c50d8ae3SPaolo Bonzini 
695855c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
6959c50d8ae3SPaolo Bonzini 		}
6960c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6961c50d8ae3SPaolo Bonzini 	}
6962c50d8ae3SPaolo Bonzini 
6963c50d8ae3SPaolo Bonzini 	return 0;
6964c50d8ae3SPaolo Bonzini }
6965c50d8ae3SPaolo Bonzini 
69661d0e8480SSean Christopherson /*
69671d0e8480SSean Christopherson  * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
69681d0e8480SSean Christopherson  * its default value of -1 is technically undefined behavior for a boolean.
6969c3e0c8c2SSean Christopherson  * Forward the module init call to SPTE code so that it too can handle module
6970c3e0c8c2SSean Christopherson  * params that need to be resolved/snapshot.
69711d0e8480SSean Christopherson  */
6972982bae43SSean Christopherson void __init kvm_mmu_x86_module_init(void)
6973c50d8ae3SPaolo Bonzini {
6974c50d8ae3SPaolo Bonzini 	if (nx_huge_pages == -1)
6975c50d8ae3SPaolo Bonzini 		__set_nx_huge_pages(get_nx_auto_mode());
6976c3e0c8c2SSean Christopherson 
69771f98f2bdSDavid Matlack 	/*
69781f98f2bdSDavid Matlack 	 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
69791f98f2bdSDavid Matlack 	 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
69801f98f2bdSDavid Matlack 	 * when the vendor module is loaded.
69811f98f2bdSDavid Matlack 	 */
69821f98f2bdSDavid Matlack 	tdp_mmu_allowed = tdp_mmu_enabled;
69831f98f2bdSDavid Matlack 
6984c3e0c8c2SSean Christopherson 	kvm_mmu_spte_module_init();
69851d0e8480SSean Christopherson }
69861d0e8480SSean Christopherson 
69871d0e8480SSean Christopherson /*
69881d0e8480SSean Christopherson  * The bulk of the MMU initialization is deferred until the vendor module is
69891d0e8480SSean Christopherson  * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
69901d0e8480SSean Christopherson  * to be reset when a potentially different vendor module is loaded.
69911d0e8480SSean Christopherson  */
69921d0e8480SSean Christopherson int kvm_mmu_vendor_module_init(void)
69931d0e8480SSean Christopherson {
69941d0e8480SSean Christopherson 	int ret = -ENOMEM;
6995c50d8ae3SPaolo Bonzini 
6996c50d8ae3SPaolo Bonzini 	/*
6997c50d8ae3SPaolo Bonzini 	 * MMU roles use union aliasing which is, generally speaking, an
6998c50d8ae3SPaolo Bonzini 	 * undefined behavior. However, we supposedly know how compilers behave
6999c50d8ae3SPaolo Bonzini 	 * and the current status quo is unlikely to change. Guardians below are
7000c50d8ae3SPaolo Bonzini 	 * supposed to let us know if the assumption becomes false.
7001c50d8ae3SPaolo Bonzini 	 */
7002c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
7003c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
70047a7ae829SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
7005c50d8ae3SPaolo Bonzini 
7006c50d8ae3SPaolo Bonzini 	kvm_mmu_reset_all_pte_masks();
7007c50d8ae3SPaolo Bonzini 
7008c50d8ae3SPaolo Bonzini 	pte_list_desc_cache = kmem_cache_create("pte_list_desc",
7009c50d8ae3SPaolo Bonzini 					    sizeof(struct pte_list_desc),
7010c50d8ae3SPaolo Bonzini 					    0, SLAB_ACCOUNT, NULL);
7011c50d8ae3SPaolo Bonzini 	if (!pte_list_desc_cache)
7012c50d8ae3SPaolo Bonzini 		goto out;
7013c50d8ae3SPaolo Bonzini 
7014c50d8ae3SPaolo Bonzini 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
7015c50d8ae3SPaolo Bonzini 						  sizeof(struct kvm_mmu_page),
7016c50d8ae3SPaolo Bonzini 						  0, SLAB_ACCOUNT, NULL);
7017c50d8ae3SPaolo Bonzini 	if (!mmu_page_header_cache)
7018c50d8ae3SPaolo Bonzini 		goto out;
7019c50d8ae3SPaolo Bonzini 
7020c50d8ae3SPaolo Bonzini 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
7021c50d8ae3SPaolo Bonzini 		goto out;
7022c50d8ae3SPaolo Bonzini 
7023e33c267aSRoman Gushchin 	ret = register_shrinker(&mmu_shrinker, "x86-mmu");
7024c50d8ae3SPaolo Bonzini 	if (ret)
7025d7c9bfb9SMiaohe Lin 		goto out_shrinker;
7026c50d8ae3SPaolo Bonzini 
7027c50d8ae3SPaolo Bonzini 	return 0;
7028c50d8ae3SPaolo Bonzini 
7029d7c9bfb9SMiaohe Lin out_shrinker:
7030d7c9bfb9SMiaohe Lin 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
7031c50d8ae3SPaolo Bonzini out:
7032c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
7033c50d8ae3SPaolo Bonzini 	return ret;
7034c50d8ae3SPaolo Bonzini }
7035c50d8ae3SPaolo Bonzini 
7036c50d8ae3SPaolo Bonzini void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
7037c50d8ae3SPaolo Bonzini {
7038c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
7039c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.root_mmu);
7040c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
7041c50d8ae3SPaolo Bonzini 	mmu_free_memory_caches(vcpu);
7042c50d8ae3SPaolo Bonzini }
7043c50d8ae3SPaolo Bonzini 
70441d0e8480SSean Christopherson void kvm_mmu_vendor_module_exit(void)
7045c50d8ae3SPaolo Bonzini {
7046c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
7047c50d8ae3SPaolo Bonzini 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
7048c50d8ae3SPaolo Bonzini 	unregister_shrinker(&mmu_shrinker);
7049c50d8ae3SPaolo Bonzini }
7050c50d8ae3SPaolo Bonzini 
7051f47491d7SSean Christopherson /*
7052f47491d7SSean Christopherson  * Calculate the effective recovery period, accounting for '0' meaning "let KVM
7053f47491d7SSean Christopherson  * select a halving time of 1 hour".  Returns true if recovery is enabled.
7054f47491d7SSean Christopherson  */
7055f47491d7SSean Christopherson static bool calc_nx_huge_pages_recovery_period(uint *period)
7056f47491d7SSean Christopherson {
7057f47491d7SSean Christopherson 	/*
7058f47491d7SSean Christopherson 	 * Use READ_ONCE to get the params, this may be called outside of the
7059f47491d7SSean Christopherson 	 * param setters, e.g. by the kthread to compute its next timeout.
7060f47491d7SSean Christopherson 	 */
7061f47491d7SSean Christopherson 	bool enabled = READ_ONCE(nx_huge_pages);
7062f47491d7SSean Christopherson 	uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7063f47491d7SSean Christopherson 
7064f47491d7SSean Christopherson 	if (!enabled || !ratio)
7065f47491d7SSean Christopherson 		return false;
7066f47491d7SSean Christopherson 
7067f47491d7SSean Christopherson 	*period = READ_ONCE(nx_huge_pages_recovery_period_ms);
7068f47491d7SSean Christopherson 	if (!*period) {
7069f47491d7SSean Christopherson 		/* Make sure the period is not less than one second.  */
7070f47491d7SSean Christopherson 		ratio = min(ratio, 3600u);
7071f47491d7SSean Christopherson 		*period = 60 * 60 * 1000 / ratio;
7072f47491d7SSean Christopherson 	}
7073f47491d7SSean Christopherson 	return true;
7074f47491d7SSean Christopherson }
7075f47491d7SSean Christopherson 
70764dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
7077c50d8ae3SPaolo Bonzini {
70784dfe4f40SJunaid Shahid 	bool was_recovery_enabled, is_recovery_enabled;
70794dfe4f40SJunaid Shahid 	uint old_period, new_period;
7080c50d8ae3SPaolo Bonzini 	int err;
7081c50d8ae3SPaolo Bonzini 
70820b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
70830b210fafSSean Christopherson 		return -EPERM;
70840b210fafSSean Christopherson 
7085f47491d7SSean Christopherson 	was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
70864dfe4f40SJunaid Shahid 
7087c50d8ae3SPaolo Bonzini 	err = param_set_uint(val, kp);
7088c50d8ae3SPaolo Bonzini 	if (err)
7089c50d8ae3SPaolo Bonzini 		return err;
7090c50d8ae3SPaolo Bonzini 
7091f47491d7SSean Christopherson 	is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
70924dfe4f40SJunaid Shahid 
7093f47491d7SSean Christopherson 	if (is_recovery_enabled &&
70944dfe4f40SJunaid Shahid 	    (!was_recovery_enabled || old_period > new_period)) {
7095c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
7096c50d8ae3SPaolo Bonzini 
7097c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
7098c50d8ae3SPaolo Bonzini 
7099c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list)
710055c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
7101c50d8ae3SPaolo Bonzini 
7102c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
7103c50d8ae3SPaolo Bonzini 	}
7104c50d8ae3SPaolo Bonzini 
7105c50d8ae3SPaolo Bonzini 	return err;
7106c50d8ae3SPaolo Bonzini }
7107c50d8ae3SPaolo Bonzini 
710855c510e2SSean Christopherson static void kvm_recover_nx_huge_pages(struct kvm *kvm)
7109c50d8ae3SPaolo Bonzini {
7110ade74e14SSean Christopherson 	unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
7111eb298605SDavid Matlack 	struct kvm_memory_slot *slot;
7112c50d8ae3SPaolo Bonzini 	int rcu_idx;
7113c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
7114c50d8ae3SPaolo Bonzini 	unsigned int ratio;
7115c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
7116048f4980SSean Christopherson 	bool flush = false;
7117c50d8ae3SPaolo Bonzini 	ulong to_zap;
7118c50d8ae3SPaolo Bonzini 
7119c50d8ae3SPaolo Bonzini 	rcu_idx = srcu_read_lock(&kvm->srcu);
7120531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
7121c50d8ae3SPaolo Bonzini 
7122bb95dfb9SSean Christopherson 	/*
7123bb95dfb9SSean Christopherson 	 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
7124bb95dfb9SSean Christopherson 	 * be done under RCU protection, because the pages are freed via RCU
7125bb95dfb9SSean Christopherson 	 * callback.
7126bb95dfb9SSean Christopherson 	 */
7127bb95dfb9SSean Christopherson 	rcu_read_lock();
7128bb95dfb9SSean Christopherson 
7129c50d8ae3SPaolo Bonzini 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7130ade74e14SSean Christopherson 	to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
71317d919c7aSSean Christopherson 	for ( ; to_zap; --to_zap) {
713255c510e2SSean Christopherson 		if (list_empty(&kvm->arch.possible_nx_huge_pages))
71337d919c7aSSean Christopherson 			break;
71347d919c7aSSean Christopherson 
7135c50d8ae3SPaolo Bonzini 		/*
7136c50d8ae3SPaolo Bonzini 		 * We use a separate list instead of just using active_mmu_pages
713755c510e2SSean Christopherson 		 * because the number of shadow pages that be replaced with an
713855c510e2SSean Christopherson 		 * NX huge page is expected to be relatively small compared to
713955c510e2SSean Christopherson 		 * the total number of shadow pages.  And because the TDP MMU
714055c510e2SSean Christopherson 		 * doesn't use active_mmu_pages.
7141c50d8ae3SPaolo Bonzini 		 */
714255c510e2SSean Christopherson 		sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
7143c50d8ae3SPaolo Bonzini 				      struct kvm_mmu_page,
714455c510e2SSean Christopherson 				      possible_nx_huge_page_link);
714555c510e2SSean Christopherson 		WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
7146eb298605SDavid Matlack 		WARN_ON_ONCE(!sp->role.direct);
7147eb298605SDavid Matlack 
7148eb298605SDavid Matlack 		/*
7149eb298605SDavid Matlack 		 * Unaccount and do not attempt to recover any NX Huge Pages
7150eb298605SDavid Matlack 		 * that are being dirty tracked, as they would just be faulted
7151eb298605SDavid Matlack 		 * back in as 4KiB pages. The NX Huge Pages in this slot will be
7152eb298605SDavid Matlack 		 * recovered, along with all the other huge pages in the slot,
7153eb298605SDavid Matlack 		 * when dirty logging is disabled.
71546c7b2202SPaolo Bonzini 		 *
71556c7b2202SPaolo Bonzini 		 * Since gfn_to_memslot() is relatively expensive, it helps to
71566c7b2202SPaolo Bonzini 		 * skip it if it the test cannot possibly return true.  On the
71576c7b2202SPaolo Bonzini 		 * other hand, if any memslot has logging enabled, chances are
71586c7b2202SPaolo Bonzini 		 * good that all of them do, in which case unaccount_nx_huge_page()
71596c7b2202SPaolo Bonzini 		 * is much cheaper than zapping the page.
71606c7b2202SPaolo Bonzini 		 *
71616c7b2202SPaolo Bonzini 		 * If a memslot update is in progress, reading an incorrect value
71626c7b2202SPaolo Bonzini 		 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
71636c7b2202SPaolo Bonzini 		 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
71646c7b2202SPaolo Bonzini 		 * it is becoming nonzero, the page will be zapped unnecessarily.
71656c7b2202SPaolo Bonzini 		 * Either way, this only affects efficiency in racy situations,
71666c7b2202SPaolo Bonzini 		 * and not correctness.
7167eb298605SDavid Matlack 		 */
71686c7b2202SPaolo Bonzini 		slot = NULL;
71696c7b2202SPaolo Bonzini 		if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
7170817fa998SSean Christopherson 			struct kvm_memslots *slots;
7171817fa998SSean Christopherson 
7172817fa998SSean Christopherson 			slots = kvm_memslots_for_spte_role(kvm, sp->role);
7173817fa998SSean Christopherson 			slot = __gfn_to_memslot(slots, sp->gfn);
71746c7b2202SPaolo Bonzini 			WARN_ON_ONCE(!slot);
717529cf0f50SBen Gardon 		}
7176c50d8ae3SPaolo Bonzini 
7177eb298605SDavid Matlack 		if (slot && kvm_slot_dirty_track_enabled(slot))
7178eb298605SDavid Matlack 			unaccount_nx_huge_page(kvm, sp);
7179eb298605SDavid Matlack 		else if (is_tdp_mmu_page(sp))
7180c50d8ae3SPaolo Bonzini 			flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
71813a056757SSean Christopherson 		else
7182c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
718355c510e2SSean Christopherson 		WARN_ON_ONCE(sp->nx_huge_page_disallowed);
7184c50d8ae3SPaolo Bonzini 
7185531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7186048f4980SSean Christopherson 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7187bb95dfb9SSean Christopherson 			rcu_read_unlock();
7188bb95dfb9SSean Christopherson 
7189531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
7190048f4980SSean Christopherson 			flush = false;
7191bb95dfb9SSean Christopherson 
7192bb95dfb9SSean Christopherson 			rcu_read_lock();
7193c50d8ae3SPaolo Bonzini 		}
7194c50d8ae3SPaolo Bonzini 	}
7195048f4980SSean Christopherson 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7196c50d8ae3SPaolo Bonzini 
7197bb95dfb9SSean Christopherson 	rcu_read_unlock();
7198bb95dfb9SSean Christopherson 
7199531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
7200c50d8ae3SPaolo Bonzini 	srcu_read_unlock(&kvm->srcu, rcu_idx);
7201c50d8ae3SPaolo Bonzini }
7202c50d8ae3SPaolo Bonzini 
720355c510e2SSean Christopherson static long get_nx_huge_page_recovery_timeout(u64 start_time)
7204c50d8ae3SPaolo Bonzini {
7205f47491d7SSean Christopherson 	bool enabled;
7206f47491d7SSean Christopherson 	uint period;
72074dfe4f40SJunaid Shahid 
7208f47491d7SSean Christopherson 	enabled = calc_nx_huge_pages_recovery_period(&period);
72094dfe4f40SJunaid Shahid 
7210f47491d7SSean Christopherson 	return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
7211c50d8ae3SPaolo Bonzini 		       : MAX_SCHEDULE_TIMEOUT;
7212c50d8ae3SPaolo Bonzini }
7213c50d8ae3SPaolo Bonzini 
721455c510e2SSean Christopherson static int kvm_nx_huge_page_recovery_worker(struct kvm *kvm, uintptr_t data)
7215c50d8ae3SPaolo Bonzini {
7216c50d8ae3SPaolo Bonzini 	u64 start_time;
7217c50d8ae3SPaolo Bonzini 	long remaining_time;
7218c50d8ae3SPaolo Bonzini 
7219c50d8ae3SPaolo Bonzini 	while (true) {
7220c50d8ae3SPaolo Bonzini 		start_time = get_jiffies_64();
722155c510e2SSean Christopherson 		remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7222c50d8ae3SPaolo Bonzini 
7223c50d8ae3SPaolo Bonzini 		set_current_state(TASK_INTERRUPTIBLE);
7224c50d8ae3SPaolo Bonzini 		while (!kthread_should_stop() && remaining_time > 0) {
7225c50d8ae3SPaolo Bonzini 			schedule_timeout(remaining_time);
722655c510e2SSean Christopherson 			remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7227c50d8ae3SPaolo Bonzini 			set_current_state(TASK_INTERRUPTIBLE);
7228c50d8ae3SPaolo Bonzini 		}
7229c50d8ae3SPaolo Bonzini 
7230c50d8ae3SPaolo Bonzini 		set_current_state(TASK_RUNNING);
7231c50d8ae3SPaolo Bonzini 
7232c50d8ae3SPaolo Bonzini 		if (kthread_should_stop())
7233c50d8ae3SPaolo Bonzini 			return 0;
7234c50d8ae3SPaolo Bonzini 
723555c510e2SSean Christopherson 		kvm_recover_nx_huge_pages(kvm);
7236c50d8ae3SPaolo Bonzini 	}
7237c50d8ae3SPaolo Bonzini }
7238c50d8ae3SPaolo Bonzini 
7239c50d8ae3SPaolo Bonzini int kvm_mmu_post_init_vm(struct kvm *kvm)
7240c50d8ae3SPaolo Bonzini {
7241c50d8ae3SPaolo Bonzini 	int err;
7242c50d8ae3SPaolo Bonzini 
72430b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
72440b210fafSSean Christopherson 		return 0;
72450b210fafSSean Christopherson 
724655c510e2SSean Christopherson 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_huge_page_recovery_worker, 0,
7247c50d8ae3SPaolo Bonzini 					  "kvm-nx-lpage-recovery",
724855c510e2SSean Christopherson 					  &kvm->arch.nx_huge_page_recovery_thread);
7249c50d8ae3SPaolo Bonzini 	if (!err)
725055c510e2SSean Christopherson 		kthread_unpark(kvm->arch.nx_huge_page_recovery_thread);
7251c50d8ae3SPaolo Bonzini 
7252c50d8ae3SPaolo Bonzini 	return err;
7253c50d8ae3SPaolo Bonzini }
7254c50d8ae3SPaolo Bonzini 
7255c50d8ae3SPaolo Bonzini void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7256c50d8ae3SPaolo Bonzini {
725755c510e2SSean Christopherson 	if (kvm->arch.nx_huge_page_recovery_thread)
725855c510e2SSean Christopherson 		kthread_stop(kvm->arch.nx_huge_page_recovery_thread);
7259c50d8ae3SPaolo Bonzini }
726090b4fe17SChao Peng 
726190b4fe17SChao Peng #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
7262*8dd2eee9SChao Peng bool kvm_arch_pre_set_memory_attributes(struct kvm *kvm,
7263*8dd2eee9SChao Peng 					struct kvm_gfn_range *range)
7264*8dd2eee9SChao Peng {
7265*8dd2eee9SChao Peng 	/*
7266*8dd2eee9SChao Peng 	 * Zap SPTEs even if the slot can't be mapped PRIVATE.  KVM x86 only
7267*8dd2eee9SChao Peng 	 * supports KVM_MEMORY_ATTRIBUTE_PRIVATE, and so it *seems* like KVM
7268*8dd2eee9SChao Peng 	 * can simply ignore such slots.  But if userspace is making memory
7269*8dd2eee9SChao Peng 	 * PRIVATE, then KVM must prevent the guest from accessing the memory
7270*8dd2eee9SChao Peng 	 * as shared.  And if userspace is making memory SHARED and this point
7271*8dd2eee9SChao Peng 	 * is reached, then at least one page within the range was previously
7272*8dd2eee9SChao Peng 	 * PRIVATE, i.e. the slot's possible hugepage ranges are changing.
7273*8dd2eee9SChao Peng 	 * Zapping SPTEs in this case ensures KVM will reassess whether or not
7274*8dd2eee9SChao Peng 	 * a hugepage can be used for affected ranges.
7275*8dd2eee9SChao Peng 	 */
7276*8dd2eee9SChao Peng 	if (WARN_ON_ONCE(!kvm_arch_has_private_mem(kvm)))
7277*8dd2eee9SChao Peng 		return false;
7278*8dd2eee9SChao Peng 
7279*8dd2eee9SChao Peng 	return kvm_unmap_gfn_range(kvm, range);
7280*8dd2eee9SChao Peng }
7281*8dd2eee9SChao Peng 
728290b4fe17SChao Peng static bool hugepage_test_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
728390b4fe17SChao Peng 				int level)
728490b4fe17SChao Peng {
728590b4fe17SChao Peng 	return lpage_info_slot(gfn, slot, level)->disallow_lpage & KVM_LPAGE_MIXED_FLAG;
728690b4fe17SChao Peng }
728790b4fe17SChao Peng 
728890b4fe17SChao Peng static void hugepage_clear_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
728990b4fe17SChao Peng 				 int level)
729090b4fe17SChao Peng {
729190b4fe17SChao Peng 	lpage_info_slot(gfn, slot, level)->disallow_lpage &= ~KVM_LPAGE_MIXED_FLAG;
729290b4fe17SChao Peng }
729390b4fe17SChao Peng 
729490b4fe17SChao Peng static void hugepage_set_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
729590b4fe17SChao Peng 			       int level)
729690b4fe17SChao Peng {
729790b4fe17SChao Peng 	lpage_info_slot(gfn, slot, level)->disallow_lpage |= KVM_LPAGE_MIXED_FLAG;
729890b4fe17SChao Peng }
729990b4fe17SChao Peng 
730090b4fe17SChao Peng static bool hugepage_has_attrs(struct kvm *kvm, struct kvm_memory_slot *slot,
730190b4fe17SChao Peng 			       gfn_t gfn, int level, unsigned long attrs)
730290b4fe17SChao Peng {
730390b4fe17SChao Peng 	const unsigned long start = gfn;
730490b4fe17SChao Peng 	const unsigned long end = start + KVM_PAGES_PER_HPAGE(level);
730590b4fe17SChao Peng 
730690b4fe17SChao Peng 	if (level == PG_LEVEL_2M)
730790b4fe17SChao Peng 		return kvm_range_has_memory_attributes(kvm, start, end, attrs);
730890b4fe17SChao Peng 
730990b4fe17SChao Peng 	for (gfn = start; gfn < end; gfn += KVM_PAGES_PER_HPAGE(level - 1)) {
731090b4fe17SChao Peng 		if (hugepage_test_mixed(slot, gfn, level - 1) ||
731190b4fe17SChao Peng 		    attrs != kvm_get_memory_attributes(kvm, gfn))
731290b4fe17SChao Peng 			return false;
731390b4fe17SChao Peng 	}
731490b4fe17SChao Peng 	return true;
731590b4fe17SChao Peng }
731690b4fe17SChao Peng 
731790b4fe17SChao Peng bool kvm_arch_post_set_memory_attributes(struct kvm *kvm,
731890b4fe17SChao Peng 					 struct kvm_gfn_range *range)
731990b4fe17SChao Peng {
732090b4fe17SChao Peng 	unsigned long attrs = range->arg.attributes;
732190b4fe17SChao Peng 	struct kvm_memory_slot *slot = range->slot;
732290b4fe17SChao Peng 	int level;
732390b4fe17SChao Peng 
732490b4fe17SChao Peng 	lockdep_assert_held_write(&kvm->mmu_lock);
732590b4fe17SChao Peng 	lockdep_assert_held(&kvm->slots_lock);
732690b4fe17SChao Peng 
732790b4fe17SChao Peng 	/*
732890b4fe17SChao Peng 	 * Calculate which ranges can be mapped with hugepages even if the slot
732990b4fe17SChao Peng 	 * can't map memory PRIVATE.  KVM mustn't create a SHARED hugepage over
733090b4fe17SChao Peng 	 * a range that has PRIVATE GFNs, and conversely converting a range to
733190b4fe17SChao Peng 	 * SHARED may now allow hugepages.
733290b4fe17SChao Peng 	 */
733390b4fe17SChao Peng 	if (WARN_ON_ONCE(!kvm_arch_has_private_mem(kvm)))
733490b4fe17SChao Peng 		return false;
733590b4fe17SChao Peng 
733690b4fe17SChao Peng 	/*
733790b4fe17SChao Peng 	 * The sequence matters here: upper levels consume the result of lower
733890b4fe17SChao Peng 	 * level's scanning.
733990b4fe17SChao Peng 	 */
734090b4fe17SChao Peng 	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
734190b4fe17SChao Peng 		gfn_t nr_pages = KVM_PAGES_PER_HPAGE(level);
734290b4fe17SChao Peng 		gfn_t gfn = gfn_round_for_level(range->start, level);
734390b4fe17SChao Peng 
734490b4fe17SChao Peng 		/* Process the head page if it straddles the range. */
734590b4fe17SChao Peng 		if (gfn != range->start || gfn + nr_pages > range->end) {
734690b4fe17SChao Peng 			/*
734790b4fe17SChao Peng 			 * Skip mixed tracking if the aligned gfn isn't covered
734890b4fe17SChao Peng 			 * by the memslot, KVM can't use a hugepage due to the
734990b4fe17SChao Peng 			 * misaligned address regardless of memory attributes.
735090b4fe17SChao Peng 			 */
735190b4fe17SChao Peng 			if (gfn >= slot->base_gfn) {
735290b4fe17SChao Peng 				if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
735390b4fe17SChao Peng 					hugepage_clear_mixed(slot, gfn, level);
735490b4fe17SChao Peng 				else
735590b4fe17SChao Peng 					hugepage_set_mixed(slot, gfn, level);
735690b4fe17SChao Peng 			}
735790b4fe17SChao Peng 			gfn += nr_pages;
735890b4fe17SChao Peng 		}
735990b4fe17SChao Peng 
736090b4fe17SChao Peng 		/*
736190b4fe17SChao Peng 		 * Pages entirely covered by the range are guaranteed to have
736290b4fe17SChao Peng 		 * only the attributes which were just set.
736390b4fe17SChao Peng 		 */
736490b4fe17SChao Peng 		for ( ; gfn + nr_pages <= range->end; gfn += nr_pages)
736590b4fe17SChao Peng 			hugepage_clear_mixed(slot, gfn, level);
736690b4fe17SChao Peng 
736790b4fe17SChao Peng 		/*
736890b4fe17SChao Peng 		 * Process the last tail page if it straddles the range and is
736990b4fe17SChao Peng 		 * contained by the memslot.  Like the head page, KVM can't
737090b4fe17SChao Peng 		 * create a hugepage if the slot size is misaligned.
737190b4fe17SChao Peng 		 */
737290b4fe17SChao Peng 		if (gfn < range->end &&
737390b4fe17SChao Peng 		    (gfn + nr_pages) <= (slot->base_gfn + slot->npages)) {
737490b4fe17SChao Peng 			if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
737590b4fe17SChao Peng 				hugepage_clear_mixed(slot, gfn, level);
737690b4fe17SChao Peng 			else
737790b4fe17SChao Peng 				hugepage_set_mixed(slot, gfn, level);
737890b4fe17SChao Peng 		}
737990b4fe17SChao Peng 	}
738090b4fe17SChao Peng 	return false;
738190b4fe17SChao Peng }
738290b4fe17SChao Peng 
738390b4fe17SChao Peng void kvm_mmu_init_memslot_memory_attributes(struct kvm *kvm,
738490b4fe17SChao Peng 					    struct kvm_memory_slot *slot)
738590b4fe17SChao Peng {
738690b4fe17SChao Peng 	int level;
738790b4fe17SChao Peng 
738890b4fe17SChao Peng 	if (!kvm_arch_has_private_mem(kvm))
738990b4fe17SChao Peng 		return;
739090b4fe17SChao Peng 
739190b4fe17SChao Peng 	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
739290b4fe17SChao Peng 		/*
739390b4fe17SChao Peng 		 * Don't bother tracking mixed attributes for pages that can't
739490b4fe17SChao Peng 		 * be huge due to alignment, i.e. process only pages that are
739590b4fe17SChao Peng 		 * entirely contained by the memslot.
739690b4fe17SChao Peng 		 */
739790b4fe17SChao Peng 		gfn_t end = gfn_round_for_level(slot->base_gfn + slot->npages, level);
739890b4fe17SChao Peng 		gfn_t start = gfn_round_for_level(slot->base_gfn, level);
739990b4fe17SChao Peng 		gfn_t nr_pages = KVM_PAGES_PER_HPAGE(level);
740090b4fe17SChao Peng 		gfn_t gfn;
740190b4fe17SChao Peng 
740290b4fe17SChao Peng 		if (start < slot->base_gfn)
740390b4fe17SChao Peng 			start += nr_pages;
740490b4fe17SChao Peng 
740590b4fe17SChao Peng 		/*
740690b4fe17SChao Peng 		 * Unlike setting attributes, every potential hugepage needs to
740790b4fe17SChao Peng 		 * be manually checked as the attributes may already be mixed.
740890b4fe17SChao Peng 		 */
740990b4fe17SChao Peng 		for (gfn = start; gfn < end; gfn += nr_pages) {
741090b4fe17SChao Peng 			unsigned long attrs = kvm_get_memory_attributes(kvm, gfn);
741190b4fe17SChao Peng 
741290b4fe17SChao Peng 			if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
741390b4fe17SChao Peng 				hugepage_clear_mixed(slot, gfn, level);
741490b4fe17SChao Peng 			else
741590b4fe17SChao Peng 				hugepage_set_mixed(slot, gfn, level);
741690b4fe17SChao Peng 		}
741790b4fe17SChao Peng 	}
741890b4fe17SChao Peng }
741990b4fe17SChao Peng #endif
7420