xref: /linux/arch/x86/kvm/mmu/mmu.c (revision 9d70f3fec14421e793ffbc0ec2f739b24e534900)
1c50d8ae3SPaolo Bonzini // SPDX-License-Identifier: GPL-2.0-only
2c50d8ae3SPaolo Bonzini /*
3c50d8ae3SPaolo Bonzini  * Kernel-based Virtual Machine driver for Linux
4c50d8ae3SPaolo Bonzini  *
5c50d8ae3SPaolo Bonzini  * This module enables machines with Intel VT-x extensions to run virtual
6c50d8ae3SPaolo Bonzini  * machines without emulation or binary translation.
7c50d8ae3SPaolo Bonzini  *
8c50d8ae3SPaolo Bonzini  * MMU support
9c50d8ae3SPaolo Bonzini  *
10c50d8ae3SPaolo Bonzini  * Copyright (C) 2006 Qumranet, Inc.
11c50d8ae3SPaolo Bonzini  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12c50d8ae3SPaolo Bonzini  *
13c50d8ae3SPaolo Bonzini  * Authors:
14c50d8ae3SPaolo Bonzini  *   Yaniv Kamay  <yaniv@qumranet.com>
15c50d8ae3SPaolo Bonzini  *   Avi Kivity   <avi@qumranet.com>
16c50d8ae3SPaolo Bonzini  */
178d20bd63SSean Christopherson #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18c50d8ae3SPaolo Bonzini 
19c50d8ae3SPaolo Bonzini #include "irq.h"
2088197e6aS彭浩(Richard) #include "ioapic.h"
21c50d8ae3SPaolo Bonzini #include "mmu.h"
226ca9a6f3SSean Christopherson #include "mmu_internal.h"
23fe5db27dSBen Gardon #include "tdp_mmu.h"
24c50d8ae3SPaolo Bonzini #include "x86.h"
25c50d8ae3SPaolo Bonzini #include "kvm_cache_regs.h"
26b0b42197SPaolo Bonzini #include "smm.h"
272f728d66SSean Christopherson #include "kvm_emulate.h"
2858ea7cf7SSean Christopherson #include "page_track.h"
29c50d8ae3SPaolo Bonzini #include "cpuid.h"
305a9624afSPaolo Bonzini #include "spte.h"
31c50d8ae3SPaolo Bonzini 
32c50d8ae3SPaolo Bonzini #include <linux/kvm_host.h>
33c50d8ae3SPaolo Bonzini #include <linux/types.h>
34c50d8ae3SPaolo Bonzini #include <linux/string.h>
35c50d8ae3SPaolo Bonzini #include <linux/mm.h>
36c50d8ae3SPaolo Bonzini #include <linux/highmem.h>
37c50d8ae3SPaolo Bonzini #include <linux/moduleparam.h>
38c50d8ae3SPaolo Bonzini #include <linux/export.h>
39c50d8ae3SPaolo Bonzini #include <linux/swap.h>
40c50d8ae3SPaolo Bonzini #include <linux/hugetlb.h>
41c50d8ae3SPaolo Bonzini #include <linux/compiler.h>
42c50d8ae3SPaolo Bonzini #include <linux/srcu.h>
43c50d8ae3SPaolo Bonzini #include <linux/slab.h>
44c50d8ae3SPaolo Bonzini #include <linux/sched/signal.h>
45c50d8ae3SPaolo Bonzini #include <linux/uaccess.h>
46c50d8ae3SPaolo Bonzini #include <linux/hash.h>
47c50d8ae3SPaolo Bonzini #include <linux/kern_levels.h>
4811b36fe7SChristophe JAILLET #include <linux/kstrtox.h>
49c50d8ae3SPaolo Bonzini #include <linux/kthread.h>
5066a5c40fSTanzir Hasan #include <linux/wordpart.h>
51c50d8ae3SPaolo Bonzini 
52c50d8ae3SPaolo Bonzini #include <asm/page.h>
53eb243d1dSIngo Molnar #include <asm/memtype.h>
54c50d8ae3SPaolo Bonzini #include <asm/cmpxchg.h>
55c50d8ae3SPaolo Bonzini #include <asm/io.h>
564a98623dSSean Christopherson #include <asm/set_memory.h>
5765efc4dcSThomas Gleixner #include <asm/spec-ctrl.h>
58c50d8ae3SPaolo Bonzini #include <asm/vmx.h>
5958ea7cf7SSean Christopherson 
60c50d8ae3SPaolo Bonzini #include "trace.h"
61c50d8ae3SPaolo Bonzini 
620b210fafSSean Christopherson static bool nx_hugepage_mitigation_hard_disabled;
630b210fafSSean Christopherson 
64a9d6496dSShaokun Zhang int __read_mostly nx_huge_pages = -1;
654dfe4f40SJunaid Shahid static uint __read_mostly nx_huge_pages_recovery_period_ms;
66c50d8ae3SPaolo Bonzini #ifdef CONFIG_PREEMPT_RT
67c50d8ae3SPaolo Bonzini /* Recovery can cause latency spikes, disable it for PREEMPT_RT.  */
68c50d8ae3SPaolo Bonzini static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
69c50d8ae3SPaolo Bonzini #else
70c50d8ae3SPaolo Bonzini static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
71c50d8ae3SPaolo Bonzini #endif
72c50d8ae3SPaolo Bonzini 
730b210fafSSean Christopherson static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp);
74c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
754dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp);
76c50d8ae3SPaolo Bonzini 
77d5d6c18dSJoe Perches static const struct kernel_param_ops nx_huge_pages_ops = {
78c50d8ae3SPaolo Bonzini 	.set = set_nx_huge_pages,
790b210fafSSean Christopherson 	.get = get_nx_huge_pages,
80c50d8ae3SPaolo Bonzini };
81c50d8ae3SPaolo Bonzini 
824dfe4f40SJunaid Shahid static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
834dfe4f40SJunaid Shahid 	.set = set_nx_huge_pages_recovery_param,
84c50d8ae3SPaolo Bonzini 	.get = param_get_uint,
85c50d8ae3SPaolo Bonzini };
86c50d8ae3SPaolo Bonzini 
87c50d8ae3SPaolo Bonzini module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
88c50d8ae3SPaolo Bonzini __MODULE_PARM_TYPE(nx_huge_pages, "bool");
894dfe4f40SJunaid Shahid module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_param_ops,
90c50d8ae3SPaolo Bonzini 		&nx_huge_pages_recovery_ratio, 0644);
91c50d8ae3SPaolo Bonzini __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
924dfe4f40SJunaid Shahid module_param_cb(nx_huge_pages_recovery_period_ms, &nx_huge_pages_recovery_param_ops,
934dfe4f40SJunaid Shahid 		&nx_huge_pages_recovery_period_ms, 0644);
944dfe4f40SJunaid Shahid __MODULE_PARM_TYPE(nx_huge_pages_recovery_period_ms, "uint");
95c50d8ae3SPaolo Bonzini 
9671fe7013SSean Christopherson static bool __read_mostly force_flush_and_sync_on_reuse;
9771fe7013SSean Christopherson module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
9871fe7013SSean Christopherson 
99c50d8ae3SPaolo Bonzini /*
100c50d8ae3SPaolo Bonzini  * When setting this variable to true it enables Two-Dimensional-Paging
101c50d8ae3SPaolo Bonzini  * where the hardware walks 2 page tables:
102c50d8ae3SPaolo Bonzini  * 1. the guest-virtual to guest-physical
103c50d8ae3SPaolo Bonzini  * 2. while doing 1. it walks guest-physical to host-physical
104c50d8ae3SPaolo Bonzini  * If the hardware supports that we don't need to do shadow paging.
105c50d8ae3SPaolo Bonzini  */
106c50d8ae3SPaolo Bonzini bool tdp_enabled = false;
107c50d8ae3SPaolo Bonzini 
1087f604e92SDavid Matlack static bool __ro_after_init tdp_mmu_allowed;
1091f98f2bdSDavid Matlack 
1101f98f2bdSDavid Matlack #ifdef CONFIG_X86_64
1111f98f2bdSDavid Matlack bool __read_mostly tdp_mmu_enabled = true;
1121f98f2bdSDavid Matlack module_param_named(tdp_mmu, tdp_mmu_enabled, bool, 0444);
1131f98f2bdSDavid Matlack #endif
1141f98f2bdSDavid Matlack 
1151d92d2e8SSean Christopherson static int max_huge_page_level __read_mostly;
116746700d2SWei Huang static int tdp_root_level __read_mostly;
11783013059SSean Christopherson static int max_tdp_level __read_mostly;
118703c335dSSean Christopherson 
119c50d8ae3SPaolo Bonzini #define PTE_PREFETCH_NUM		8
120c50d8ae3SPaolo Bonzini 
121c50d8ae3SPaolo Bonzini #include <trace/events/kvm.h>
122c50d8ae3SPaolo Bonzini 
123dc1cff96SPeter Xu /* make pte_list_desc fit well in cache lines */
12413236e25SPeter Xu #define PTE_LIST_EXT 14
125c50d8ae3SPaolo Bonzini 
12613236e25SPeter Xu /*
127141705b7SLai Jiangshan  * struct pte_list_desc is the core data structure used to implement a custom
128141705b7SLai Jiangshan  * list for tracking a set of related SPTEs, e.g. all the SPTEs that map a
129141705b7SLai Jiangshan  * given GFN when used in the context of rmaps.  Using a custom list allows KVM
130141705b7SLai Jiangshan  * to optimize for the common case where many GFNs will have at most a handful
131141705b7SLai Jiangshan  * of SPTEs pointing at them, i.e. allows packing multiple SPTEs into a small
132141705b7SLai Jiangshan  * memory footprint, which in turn improves runtime performance by exploiting
133141705b7SLai Jiangshan  * cache locality.
134141705b7SLai Jiangshan  *
135141705b7SLai Jiangshan  * A list is comprised of one or more pte_list_desc objects (descriptors).
136141705b7SLai Jiangshan  * Each individual descriptor stores up to PTE_LIST_EXT SPTEs.  If a descriptor
137141705b7SLai Jiangshan  * is full and a new SPTEs needs to be added, a new descriptor is allocated and
138141705b7SLai Jiangshan  * becomes the head of the list.  This means that by definitions, all tail
139141705b7SLai Jiangshan  * descriptors are full.
140141705b7SLai Jiangshan  *
141141705b7SLai Jiangshan  * Note, the meta data fields are deliberately placed at the start of the
142141705b7SLai Jiangshan  * structure to optimize the cacheline layout; accessing the descriptor will
143141705b7SLai Jiangshan  * touch only a single cacheline so long as @spte_count<=6 (or if only the
144141705b7SLai Jiangshan  * descriptors metadata is accessed).
14513236e25SPeter Xu  */
146c50d8ae3SPaolo Bonzini struct pte_list_desc {
147c50d8ae3SPaolo Bonzini 	struct pte_list_desc *more;
148141705b7SLai Jiangshan 	/* The number of PTEs stored in _this_ descriptor. */
149141705b7SLai Jiangshan 	u32 spte_count;
150141705b7SLai Jiangshan 	/* The number of PTEs stored in all tails of this descriptor. */
151141705b7SLai Jiangshan 	u32 tail_count;
15213236e25SPeter Xu 	u64 *sptes[PTE_LIST_EXT];
153c50d8ae3SPaolo Bonzini };
154c50d8ae3SPaolo Bonzini 
155c50d8ae3SPaolo Bonzini struct kvm_shadow_walk_iterator {
156c50d8ae3SPaolo Bonzini 	u64 addr;
157c50d8ae3SPaolo Bonzini 	hpa_t shadow_addr;
158c50d8ae3SPaolo Bonzini 	u64 *sptep;
159c50d8ae3SPaolo Bonzini 	int level;
160c50d8ae3SPaolo Bonzini 	unsigned index;
161c50d8ae3SPaolo Bonzini };
162c50d8ae3SPaolo Bonzini 
163c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
164c50d8ae3SPaolo Bonzini 	for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
165c50d8ae3SPaolo Bonzini 					 (_root), (_addr));                \
166c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			           \
167c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
168c50d8ae3SPaolo Bonzini 
169c50d8ae3SPaolo Bonzini #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
170c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);	\
171c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			\
172c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
173c50d8ae3SPaolo Bonzini 
174c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)	\
175c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);		\
176c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker)) &&				\
177c50d8ae3SPaolo Bonzini 		({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });	\
178c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&(_walker), spte))
179c50d8ae3SPaolo Bonzini 
180c50d8ae3SPaolo Bonzini static struct kmem_cache *pte_list_desc_cache;
18102c00b3aSBen Gardon struct kmem_cache *mmu_page_header_cache;
182c50d8ae3SPaolo Bonzini static struct percpu_counter kvm_total_used_mmu_pages;
183c50d8ae3SPaolo Bonzini 
184c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 spte);
185c50d8ae3SPaolo Bonzini 
186594e91a1SSean Christopherson struct kvm_mmu_role_regs {
187594e91a1SSean Christopherson 	const unsigned long cr0;
188594e91a1SSean Christopherson 	const unsigned long cr4;
189594e91a1SSean Christopherson 	const u64 efer;
190594e91a1SSean Christopherson };
191594e91a1SSean Christopherson 
192c50d8ae3SPaolo Bonzini #define CREATE_TRACE_POINTS
193c50d8ae3SPaolo Bonzini #include "mmutrace.h"
194c50d8ae3SPaolo Bonzini 
195594e91a1SSean Christopherson /*
196594e91a1SSean Christopherson  * Yes, lot's of underscores.  They're a hint that you probably shouldn't be
1977a458f0eSPaolo Bonzini  * reading from the role_regs.  Once the root_role is constructed, it becomes
198594e91a1SSean Christopherson  * the single source of truth for the MMU's state.
199594e91a1SSean Christopherson  */
200594e91a1SSean Christopherson #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag)			\
20182ffa13fSPaolo Bonzini static inline bool __maybe_unused					\
20282ffa13fSPaolo Bonzini ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs)		\
203594e91a1SSean Christopherson {									\
204594e91a1SSean Christopherson 	return !!(regs->reg & flag);					\
205594e91a1SSean Christopherson }
206594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
207594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
208594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
209594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
210594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
211594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
212594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
213594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
214594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
215594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
216594e91a1SSean Christopherson 
21760667724SSean Christopherson /*
21860667724SSean Christopherson  * The MMU itself (with a valid role) is the single source of truth for the
21960667724SSean Christopherson  * MMU.  Do not use the regs used to build the MMU/role, nor the vCPU.  The
22060667724SSean Christopherson  * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
22160667724SSean Christopherson  * and the vCPU may be incorrect/irrelevant.
22260667724SSean Christopherson  */
22360667724SSean Christopherson #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name)		\
2244ac21457SPaolo Bonzini static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu)	\
22560667724SSean Christopherson {								\
226e5ed0fb0SPaolo Bonzini 	return !!(mmu->cpu_role. base_or_ext . reg##_##name);	\
22760667724SSean Christopherson }
22860667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
22960667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pse);
23060667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smep);
23160667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smap);
23260667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pke);
23360667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, la57);
23460667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
23556b321f9SPaolo Bonzini BUILD_MMU_ROLE_ACCESSOR(ext,  efer, lma);
23660667724SSean Christopherson 
237faf72962SPaolo Bonzini static inline bool is_cr0_pg(struct kvm_mmu *mmu)
238faf72962SPaolo Bonzini {
239faf72962SPaolo Bonzini         return mmu->cpu_role.base.level > 0;
240faf72962SPaolo Bonzini }
241faf72962SPaolo Bonzini 
242faf72962SPaolo Bonzini static inline bool is_cr4_pae(struct kvm_mmu *mmu)
243faf72962SPaolo Bonzini {
244faf72962SPaolo Bonzini         return !mmu->cpu_role.base.has_4_byte_gpte;
245faf72962SPaolo Bonzini }
246faf72962SPaolo Bonzini 
247594e91a1SSean Christopherson static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
248594e91a1SSean Christopherson {
249594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
250594e91a1SSean Christopherson 		.cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
251594e91a1SSean Christopherson 		.cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
252594e91a1SSean Christopherson 		.efer = vcpu->arch.efer,
253594e91a1SSean Christopherson 	};
254594e91a1SSean Christopherson 
255594e91a1SSean Christopherson 	return regs;
256594e91a1SSean Christopherson }
257c50d8ae3SPaolo Bonzini 
2582fdcc1b3SPaolo Bonzini static unsigned long get_guest_cr3(struct kvm_vcpu *vcpu)
259c50d8ae3SPaolo Bonzini {
2602fdcc1b3SPaolo Bonzini 	return kvm_read_cr3(vcpu);
261c50d8ae3SPaolo Bonzini }
262c50d8ae3SPaolo Bonzini 
2632fdcc1b3SPaolo Bonzini static inline unsigned long kvm_mmu_get_guest_pgd(struct kvm_vcpu *vcpu,
2642fdcc1b3SPaolo Bonzini 						  struct kvm_mmu *mmu)
265c50d8ae3SPaolo Bonzini {
266aefb2f2eSBreno Leitao 	if (IS_ENABLED(CONFIG_MITIGATION_RETPOLINE) && mmu->get_guest_pgd == get_guest_cr3)
2672fdcc1b3SPaolo Bonzini 		return kvm_read_cr3(vcpu);
268c50d8ae3SPaolo Bonzini 
2692fdcc1b3SPaolo Bonzini 	return mmu->get_guest_pgd(vcpu);
2702fdcc1b3SPaolo Bonzini }
271c50d8ae3SPaolo Bonzini 
2728a1300ffSSean Christopherson static inline bool kvm_available_flush_remote_tlbs_range(void)
273c50d8ae3SPaolo Bonzini {
2740277022aSSean Christopherson #if IS_ENABLED(CONFIG_HYPERV)
2758a1300ffSSean Christopherson 	return kvm_x86_ops.flush_remote_tlbs_range;
2760277022aSSean Christopherson #else
2770277022aSSean Christopherson 	return false;
2780277022aSSean Christopherson #endif
279c50d8ae3SPaolo Bonzini }
280c50d8ae3SPaolo Bonzini 
2811b2dc736SHou Wenlong static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index);
2821b2dc736SHou Wenlong 
2831b2dc736SHou Wenlong /* Flush the range of guest memory mapped by the given SPTE. */
2841b2dc736SHou Wenlong static void kvm_flush_remote_tlbs_sptep(struct kvm *kvm, u64 *sptep)
2851b2dc736SHou Wenlong {
2861b2dc736SHou Wenlong 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2871b2dc736SHou Wenlong 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, spte_index(sptep));
2881b2dc736SHou Wenlong 
2891b2dc736SHou Wenlong 	kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
2901b2dc736SHou Wenlong }
2911b2dc736SHou Wenlong 
2928f79b064SBen Gardon static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
2938f79b064SBen Gardon 			   unsigned int access)
2948f79b064SBen Gardon {
295c236d962SSean Christopherson 	u64 spte = make_mmio_spte(vcpu, gfn, access);
2968f79b064SBen Gardon 
297c236d962SSean Christopherson 	trace_mark_mmio_spte(sptep, gfn, spte);
298c236d962SSean Christopherson 	mmu_spte_set(sptep, spte);
299c50d8ae3SPaolo Bonzini }
300c50d8ae3SPaolo Bonzini 
301c50d8ae3SPaolo Bonzini static gfn_t get_mmio_spte_gfn(u64 spte)
302c50d8ae3SPaolo Bonzini {
303c50d8ae3SPaolo Bonzini 	u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
304c50d8ae3SPaolo Bonzini 
3058a967d65SPaolo Bonzini 	gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
306c50d8ae3SPaolo Bonzini 	       & shadow_nonpresent_or_rsvd_mask;
307c50d8ae3SPaolo Bonzini 
308c50d8ae3SPaolo Bonzini 	return gpa >> PAGE_SHIFT;
309c50d8ae3SPaolo Bonzini }
310c50d8ae3SPaolo Bonzini 
311c50d8ae3SPaolo Bonzini static unsigned get_mmio_spte_access(u64 spte)
312c50d8ae3SPaolo Bonzini {
313c50d8ae3SPaolo Bonzini 	return spte & shadow_mmio_access_mask;
314c50d8ae3SPaolo Bonzini }
315c50d8ae3SPaolo Bonzini 
316c50d8ae3SPaolo Bonzini static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
317c50d8ae3SPaolo Bonzini {
318c50d8ae3SPaolo Bonzini 	u64 kvm_gen, spte_gen, gen;
319c50d8ae3SPaolo Bonzini 
320c50d8ae3SPaolo Bonzini 	gen = kvm_vcpu_memslots(vcpu)->generation;
321c50d8ae3SPaolo Bonzini 	if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
322c50d8ae3SPaolo Bonzini 		return false;
323c50d8ae3SPaolo Bonzini 
324c50d8ae3SPaolo Bonzini 	kvm_gen = gen & MMIO_SPTE_GEN_MASK;
325c50d8ae3SPaolo Bonzini 	spte_gen = get_mmio_spte_generation(spte);
326c50d8ae3SPaolo Bonzini 
327c50d8ae3SPaolo Bonzini 	trace_check_mmio_spte(spte, kvm_gen, spte_gen);
328c50d8ae3SPaolo Bonzini 	return likely(kvm_gen == spte_gen);
329c50d8ae3SPaolo Bonzini }
330c50d8ae3SPaolo Bonzini 
331c50d8ae3SPaolo Bonzini static int is_cpuid_PSE36(void)
332c50d8ae3SPaolo Bonzini {
333c50d8ae3SPaolo Bonzini 	return 1;
334c50d8ae3SPaolo Bonzini }
335c50d8ae3SPaolo Bonzini 
336c50d8ae3SPaolo Bonzini #ifdef CONFIG_X86_64
337c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
338c50d8ae3SPaolo Bonzini {
339837d557aSSean Christopherson 	KVM_MMU_WARN_ON(is_ept_ve_possible(spte));
340c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
341c50d8ae3SPaolo Bonzini }
342c50d8ae3SPaolo Bonzini 
343c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
344c50d8ae3SPaolo Bonzini {
345837d557aSSean Christopherson 	KVM_MMU_WARN_ON(is_ept_ve_possible(spte));
346c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
347c50d8ae3SPaolo Bonzini }
348c50d8ae3SPaolo Bonzini 
349c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
350c50d8ae3SPaolo Bonzini {
351837d557aSSean Christopherson 	KVM_MMU_WARN_ON(is_ept_ve_possible(spte));
352c50d8ae3SPaolo Bonzini 	return xchg(sptep, spte);
353c50d8ae3SPaolo Bonzini }
354c50d8ae3SPaolo Bonzini 
355c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
356c50d8ae3SPaolo Bonzini {
357c50d8ae3SPaolo Bonzini 	return READ_ONCE(*sptep);
358c50d8ae3SPaolo Bonzini }
359c50d8ae3SPaolo Bonzini #else
360c50d8ae3SPaolo Bonzini union split_spte {
361c50d8ae3SPaolo Bonzini 	struct {
362c50d8ae3SPaolo Bonzini 		u32 spte_low;
363c50d8ae3SPaolo Bonzini 		u32 spte_high;
364c50d8ae3SPaolo Bonzini 	};
365c50d8ae3SPaolo Bonzini 	u64 spte;
366c50d8ae3SPaolo Bonzini };
367c50d8ae3SPaolo Bonzini 
368c50d8ae3SPaolo Bonzini static void count_spte_clear(u64 *sptep, u64 spte)
369c50d8ae3SPaolo Bonzini {
37057354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
371c50d8ae3SPaolo Bonzini 
372c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(spte))
373c50d8ae3SPaolo Bonzini 		return;
374c50d8ae3SPaolo Bonzini 
375c50d8ae3SPaolo Bonzini 	/* Ensure the spte is completely set before we increase the count */
376c50d8ae3SPaolo Bonzini 	smp_wmb();
377c50d8ae3SPaolo Bonzini 	sp->clear_spte_count++;
378c50d8ae3SPaolo Bonzini }
379c50d8ae3SPaolo Bonzini 
380c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
381c50d8ae3SPaolo Bonzini {
382c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
383c50d8ae3SPaolo Bonzini 
384c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
385c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
386c50d8ae3SPaolo Bonzini 
387c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
388c50d8ae3SPaolo Bonzini 
389c50d8ae3SPaolo Bonzini 	/*
390c50d8ae3SPaolo Bonzini 	 * If we map the spte from nonpresent to present, We should store
391c50d8ae3SPaolo Bonzini 	 * the high bits firstly, then set present bit, so cpu can not
392c50d8ae3SPaolo Bonzini 	 * fetch this spte while we are setting the spte.
393c50d8ae3SPaolo Bonzini 	 */
394c50d8ae3SPaolo Bonzini 	smp_wmb();
395c50d8ae3SPaolo Bonzini 
396c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
397c50d8ae3SPaolo Bonzini }
398c50d8ae3SPaolo Bonzini 
399c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
400c50d8ae3SPaolo Bonzini {
401c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
402c50d8ae3SPaolo Bonzini 
403c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
404c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
405c50d8ae3SPaolo Bonzini 
406c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
407c50d8ae3SPaolo Bonzini 
408c50d8ae3SPaolo Bonzini 	/*
409c50d8ae3SPaolo Bonzini 	 * If we map the spte from present to nonpresent, we should clear
410c50d8ae3SPaolo Bonzini 	 * present bit firstly to avoid vcpu fetch the old high bits.
411c50d8ae3SPaolo Bonzini 	 */
412c50d8ae3SPaolo Bonzini 	smp_wmb();
413c50d8ae3SPaolo Bonzini 
414c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
415c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
416c50d8ae3SPaolo Bonzini }
417c50d8ae3SPaolo Bonzini 
418c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
419c50d8ae3SPaolo Bonzini {
420c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte, orig;
421c50d8ae3SPaolo Bonzini 
422c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
423c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
424c50d8ae3SPaolo Bonzini 
425c50d8ae3SPaolo Bonzini 	/* xchg acts as a barrier before the setting of the high bits */
426c50d8ae3SPaolo Bonzini 	orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
427c50d8ae3SPaolo Bonzini 	orig.spte_high = ssptep->spte_high;
428c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
429c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
430c50d8ae3SPaolo Bonzini 
431c50d8ae3SPaolo Bonzini 	return orig.spte;
432c50d8ae3SPaolo Bonzini }
433c50d8ae3SPaolo Bonzini 
434c50d8ae3SPaolo Bonzini /*
435c50d8ae3SPaolo Bonzini  * The idea using the light way get the spte on x86_32 guest is from
436c50d8ae3SPaolo Bonzini  * gup_get_pte (mm/gup.c).
437c50d8ae3SPaolo Bonzini  *
438f3b65bbaSPaolo Bonzini  * An spte tlb flush may be pending, because they are coalesced and
439f3b65bbaSPaolo Bonzini  * we are running out of the MMU lock.  Therefore
440c50d8ae3SPaolo Bonzini  * we need to protect against in-progress updates of the spte.
441c50d8ae3SPaolo Bonzini  *
442c50d8ae3SPaolo Bonzini  * Reading the spte while an update is in progress may get the old value
443c50d8ae3SPaolo Bonzini  * for the high part of the spte.  The race is fine for a present->non-present
444c50d8ae3SPaolo Bonzini  * change (because the high part of the spte is ignored for non-present spte),
445c50d8ae3SPaolo Bonzini  * but for a present->present change we must reread the spte.
446c50d8ae3SPaolo Bonzini  *
447c50d8ae3SPaolo Bonzini  * All such changes are done in two steps (present->non-present and
448c50d8ae3SPaolo Bonzini  * non-present->present), hence it is enough to count the number of
449c50d8ae3SPaolo Bonzini  * present->non-present updates: if it changed while reading the spte,
450c50d8ae3SPaolo Bonzini  * we might have hit the race.  This is done using clear_spte_count.
451c50d8ae3SPaolo Bonzini  */
452c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
453c50d8ae3SPaolo Bonzini {
45457354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
455c50d8ae3SPaolo Bonzini 	union split_spte spte, *orig = (union split_spte *)sptep;
456c50d8ae3SPaolo Bonzini 	int count;
457c50d8ae3SPaolo Bonzini 
458c50d8ae3SPaolo Bonzini retry:
459c50d8ae3SPaolo Bonzini 	count = sp->clear_spte_count;
460c50d8ae3SPaolo Bonzini 	smp_rmb();
461c50d8ae3SPaolo Bonzini 
462c50d8ae3SPaolo Bonzini 	spte.spte_low = orig->spte_low;
463c50d8ae3SPaolo Bonzini 	smp_rmb();
464c50d8ae3SPaolo Bonzini 
465c50d8ae3SPaolo Bonzini 	spte.spte_high = orig->spte_high;
466c50d8ae3SPaolo Bonzini 	smp_rmb();
467c50d8ae3SPaolo Bonzini 
468c50d8ae3SPaolo Bonzini 	if (unlikely(spte.spte_low != orig->spte_low ||
469c50d8ae3SPaolo Bonzini 	      count != sp->clear_spte_count))
470c50d8ae3SPaolo Bonzini 		goto retry;
471c50d8ae3SPaolo Bonzini 
472c50d8ae3SPaolo Bonzini 	return spte.spte;
473c50d8ae3SPaolo Bonzini }
474c50d8ae3SPaolo Bonzini #endif
475c50d8ae3SPaolo Bonzini 
476c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_set:
477c50d8ae3SPaolo Bonzini  * Set the sptep from nonpresent to present.
478c50d8ae3SPaolo Bonzini  * Note: the sptep being assigned *must* be either not present
479c50d8ae3SPaolo Bonzini  * or in a state where the hardware will not attempt to update
480c50d8ae3SPaolo Bonzini  * the spte.
481c50d8ae3SPaolo Bonzini  */
482c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 new_spte)
483c50d8ae3SPaolo Bonzini {
48420ba462dSSean Christopherson 	WARN_ON_ONCE(is_shadow_present_pte(*sptep));
485c50d8ae3SPaolo Bonzini 	__set_spte(sptep, new_spte);
486c50d8ae3SPaolo Bonzini }
487c50d8ae3SPaolo Bonzini 
488c50d8ae3SPaolo Bonzini /*
489c50d8ae3SPaolo Bonzini  * Update the SPTE (excluding the PFN), but do not track changes in its
490c50d8ae3SPaolo Bonzini  * accessed/dirty status.
491c50d8ae3SPaolo Bonzini  */
492c50d8ae3SPaolo Bonzini static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
493c50d8ae3SPaolo Bonzini {
494c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
495c50d8ae3SPaolo Bonzini 
49620ba462dSSean Christopherson 	WARN_ON_ONCE(!is_shadow_present_pte(new_spte));
497115111efSDavid Matlack 	check_spte_writable_invariants(new_spte);
498c50d8ae3SPaolo Bonzini 
499c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte)) {
500c50d8ae3SPaolo Bonzini 		mmu_spte_set(sptep, new_spte);
501c50d8ae3SPaolo Bonzini 		return old_spte;
502c50d8ae3SPaolo Bonzini 	}
503c50d8ae3SPaolo Bonzini 
504c50d8ae3SPaolo Bonzini 	if (!spte_has_volatile_bits(old_spte))
505c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, new_spte);
506c50d8ae3SPaolo Bonzini 	else
507c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, new_spte);
508c50d8ae3SPaolo Bonzini 
50920ba462dSSean Christopherson 	WARN_ON_ONCE(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
510c50d8ae3SPaolo Bonzini 
511c50d8ae3SPaolo Bonzini 	return old_spte;
512c50d8ae3SPaolo Bonzini }
513c50d8ae3SPaolo Bonzini 
514c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_update:
515c50d8ae3SPaolo Bonzini  * Update the state bits, it means the mapped pfn is not changed.
516c50d8ae3SPaolo Bonzini  *
51702844ac1SDavid Matlack  * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
51802844ac1SDavid Matlack  * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
51902844ac1SDavid Matlack  * spte, even though the writable spte might be cached on a CPU's TLB.
520c50d8ae3SPaolo Bonzini  *
521c50d8ae3SPaolo Bonzini  * Returns true if the TLB needs to be flushed
522c50d8ae3SPaolo Bonzini  */
523c50d8ae3SPaolo Bonzini static bool mmu_spte_update(u64 *sptep, u64 new_spte)
524c50d8ae3SPaolo Bonzini {
525c50d8ae3SPaolo Bonzini 	bool flush = false;
526c50d8ae3SPaolo Bonzini 	u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
527c50d8ae3SPaolo Bonzini 
528c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
529c50d8ae3SPaolo Bonzini 		return false;
530c50d8ae3SPaolo Bonzini 
531c50d8ae3SPaolo Bonzini 	/*
532c50d8ae3SPaolo Bonzini 	 * For the spte updated out of mmu-lock is safe, since
533c50d8ae3SPaolo Bonzini 	 * we always atomically update it, see the comments in
534c50d8ae3SPaolo Bonzini 	 * spte_has_volatile_bits().
535c50d8ae3SPaolo Bonzini 	 */
536706c9c55SSean Christopherson 	if (is_mmu_writable_spte(old_spte) &&
537c50d8ae3SPaolo Bonzini 	      !is_writable_pte(new_spte))
538c50d8ae3SPaolo Bonzini 		flush = true;
539c50d8ae3SPaolo Bonzini 
540c50d8ae3SPaolo Bonzini 	/*
541c50d8ae3SPaolo Bonzini 	 * Flush TLB when accessed/dirty states are changed in the page tables,
542c50d8ae3SPaolo Bonzini 	 * to guarantee consistency between TLB and page tables.
543c50d8ae3SPaolo Bonzini 	 */
544c50d8ae3SPaolo Bonzini 
545c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
546c50d8ae3SPaolo Bonzini 		flush = true;
547c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(spte_to_pfn(old_spte));
548c50d8ae3SPaolo Bonzini 	}
549c50d8ae3SPaolo Bonzini 
550c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
551c50d8ae3SPaolo Bonzini 		flush = true;
552c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(old_spte));
553c50d8ae3SPaolo Bonzini 	}
554c50d8ae3SPaolo Bonzini 
555c50d8ae3SPaolo Bonzini 	return flush;
556c50d8ae3SPaolo Bonzini }
557c50d8ae3SPaolo Bonzini 
558c50d8ae3SPaolo Bonzini /*
559c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_track_bits:
560c50d8ae3SPaolo Bonzini  * It sets the sptep from present to nonpresent, and track the
561c50d8ae3SPaolo Bonzini  * state bits, it is used to clear the last level sptep.
5627fa2a347SSean Christopherson  * Returns the old PTE.
563c50d8ae3SPaolo Bonzini  */
56435d539c3SSean Christopherson static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
565c50d8ae3SPaolo Bonzini {
566c50d8ae3SPaolo Bonzini 	kvm_pfn_t pfn;
567c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
56871f51d2cSMingwei Zhang 	int level = sptep_to_sp(sptep)->role.level;
569b14b2690SSean Christopherson 	struct page *page;
570c50d8ae3SPaolo Bonzini 
57154eb3ef5SSean Christopherson 	if (!is_shadow_present_pte(old_spte) ||
57254eb3ef5SSean Christopherson 	    !spte_has_volatile_bits(old_spte))
573d8fa2031SSean Christopherson 		__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
574c50d8ae3SPaolo Bonzini 	else
575d8fa2031SSean Christopherson 		old_spte = __update_clear_spte_slow(sptep, SHADOW_NONPRESENT_VALUE);
576c50d8ae3SPaolo Bonzini 
577c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
5787fa2a347SSean Christopherson 		return old_spte;
579c50d8ae3SPaolo Bonzini 
58071f51d2cSMingwei Zhang 	kvm_update_page_stats(kvm, level, -1);
58171f51d2cSMingwei Zhang 
582c50d8ae3SPaolo Bonzini 	pfn = spte_to_pfn(old_spte);
583c50d8ae3SPaolo Bonzini 
584c50d8ae3SPaolo Bonzini 	/*
585b14b2690SSean Christopherson 	 * KVM doesn't hold a reference to any pages mapped into the guest, and
586b14b2690SSean Christopherson 	 * instead uses the mmu_notifier to ensure that KVM unmaps any pages
587b14b2690SSean Christopherson 	 * before they are reclaimed.  Sanity check that, if the pfn is backed
588b14b2690SSean Christopherson 	 * by a refcounted page, the refcount is elevated.
589c50d8ae3SPaolo Bonzini 	 */
590b14b2690SSean Christopherson 	page = kvm_pfn_to_refcounted_page(pfn);
59120ba462dSSean Christopherson 	WARN_ON_ONCE(page && !page_count(page));
592c50d8ae3SPaolo Bonzini 
593c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte))
594c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(pfn);
595c50d8ae3SPaolo Bonzini 
596c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte))
597c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(pfn);
598c50d8ae3SPaolo Bonzini 
5997fa2a347SSean Christopherson 	return old_spte;
600c50d8ae3SPaolo Bonzini }
601c50d8ae3SPaolo Bonzini 
602c50d8ae3SPaolo Bonzini /*
603c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_no_track:
604c50d8ae3SPaolo Bonzini  * Directly clear spte without caring the state bits of sptep,
605c50d8ae3SPaolo Bonzini  * it is used to set the upper level spte.
606c50d8ae3SPaolo Bonzini  */
607c50d8ae3SPaolo Bonzini static void mmu_spte_clear_no_track(u64 *sptep)
608c50d8ae3SPaolo Bonzini {
609d8fa2031SSean Christopherson 	__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
610c50d8ae3SPaolo Bonzini }
611c50d8ae3SPaolo Bonzini 
612c50d8ae3SPaolo Bonzini static u64 mmu_spte_get_lockless(u64 *sptep)
613c50d8ae3SPaolo Bonzini {
614c50d8ae3SPaolo Bonzini 	return __get_spte_lockless(sptep);
615c50d8ae3SPaolo Bonzini }
616c50d8ae3SPaolo Bonzini 
617c50d8ae3SPaolo Bonzini /* Returns the Accessed status of the PTE and resets it at the same time. */
618c50d8ae3SPaolo Bonzini static bool mmu_spte_age(u64 *sptep)
619c50d8ae3SPaolo Bonzini {
620c50d8ae3SPaolo Bonzini 	u64 spte = mmu_spte_get_lockless(sptep);
621c50d8ae3SPaolo Bonzini 
622c50d8ae3SPaolo Bonzini 	if (!is_accessed_spte(spte))
623c50d8ae3SPaolo Bonzini 		return false;
624c50d8ae3SPaolo Bonzini 
625c50d8ae3SPaolo Bonzini 	if (spte_ad_enabled(spte)) {
626c50d8ae3SPaolo Bonzini 		clear_bit((ffs(shadow_accessed_mask) - 1),
627c50d8ae3SPaolo Bonzini 			  (unsigned long *)sptep);
628c50d8ae3SPaolo Bonzini 	} else {
629c50d8ae3SPaolo Bonzini 		/*
630c50d8ae3SPaolo Bonzini 		 * Capture the dirty status of the page, so that it doesn't get
631c50d8ae3SPaolo Bonzini 		 * lost when the SPTE is marked for access tracking.
632c50d8ae3SPaolo Bonzini 		 */
633c50d8ae3SPaolo Bonzini 		if (is_writable_pte(spte))
634c50d8ae3SPaolo Bonzini 			kvm_set_pfn_dirty(spte_to_pfn(spte));
635c50d8ae3SPaolo Bonzini 
636c50d8ae3SPaolo Bonzini 		spte = mark_spte_for_access_track(spte);
637c50d8ae3SPaolo Bonzini 		mmu_spte_update_no_track(sptep, spte);
638c50d8ae3SPaolo Bonzini 	}
639c50d8ae3SPaolo Bonzini 
640c50d8ae3SPaolo Bonzini 	return true;
641c50d8ae3SPaolo Bonzini }
642c50d8ae3SPaolo Bonzini 
64378fdd2f0SSean Christopherson static inline bool is_tdp_mmu_active(struct kvm_vcpu *vcpu)
64478fdd2f0SSean Christopherson {
64578fdd2f0SSean Christopherson 	return tdp_mmu_enabled && vcpu->arch.mmu->root_role.direct;
64678fdd2f0SSean Christopherson }
64778fdd2f0SSean Christopherson 
648c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
649c50d8ae3SPaolo Bonzini {
65078fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu)) {
651c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_begin();
652c5c8c7c5SDavid Matlack 	} else {
653c50d8ae3SPaolo Bonzini 		/*
654c50d8ae3SPaolo Bonzini 		 * Prevent page table teardown by making any free-er wait during
655c50d8ae3SPaolo Bonzini 		 * kvm_flush_remote_tlbs() IPI to all active vcpus.
656c50d8ae3SPaolo Bonzini 		 */
657c50d8ae3SPaolo Bonzini 		local_irq_disable();
658c50d8ae3SPaolo Bonzini 
659c50d8ae3SPaolo Bonzini 		/*
660c50d8ae3SPaolo Bonzini 		 * Make sure a following spte read is not reordered ahead of the write
661c50d8ae3SPaolo Bonzini 		 * to vcpu->mode.
662c50d8ae3SPaolo Bonzini 		 */
663c50d8ae3SPaolo Bonzini 		smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
664c50d8ae3SPaolo Bonzini 	}
665c5c8c7c5SDavid Matlack }
666c50d8ae3SPaolo Bonzini 
667c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
668c50d8ae3SPaolo Bonzini {
66978fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu)) {
670c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_end();
671c5c8c7c5SDavid Matlack 	} else {
672c50d8ae3SPaolo Bonzini 		/*
673c50d8ae3SPaolo Bonzini 		 * Make sure the write to vcpu->mode is not reordered in front of
674c50d8ae3SPaolo Bonzini 		 * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
675c50d8ae3SPaolo Bonzini 		 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
676c50d8ae3SPaolo Bonzini 		 */
677c50d8ae3SPaolo Bonzini 		smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
678c50d8ae3SPaolo Bonzini 		local_irq_enable();
679c50d8ae3SPaolo Bonzini 	}
680c5c8c7c5SDavid Matlack }
681c50d8ae3SPaolo Bonzini 
682378f5cd6SSean Christopherson static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
683c50d8ae3SPaolo Bonzini {
684c50d8ae3SPaolo Bonzini 	int r;
685c50d8ae3SPaolo Bonzini 
686531281adSSean Christopherson 	/* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
68794ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
688531281adSSean Christopherson 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
689c50d8ae3SPaolo Bonzini 	if (r)
690c50d8ae3SPaolo Bonzini 		return r;
69194ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
692171a90d7SSean Christopherson 				       PT64_ROOT_MAX_LEVEL);
693171a90d7SSean Christopherson 	if (r)
694171a90d7SSean Christopherson 		return r;
695378f5cd6SSean Christopherson 	if (maybe_indirect) {
6966a97575dSDavid Matlack 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
697171a90d7SSean Christopherson 					       PT64_ROOT_MAX_LEVEL);
698c50d8ae3SPaolo Bonzini 		if (r)
699c50d8ae3SPaolo Bonzini 			return r;
700378f5cd6SSean Christopherson 	}
70194ce87efSSean Christopherson 	return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
702531281adSSean Christopherson 					  PT64_ROOT_MAX_LEVEL);
703c50d8ae3SPaolo Bonzini }
704c50d8ae3SPaolo Bonzini 
705c50d8ae3SPaolo Bonzini static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
706c50d8ae3SPaolo Bonzini {
70794ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
70894ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
7096a97575dSDavid Matlack 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
71094ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
711c50d8ae3SPaolo Bonzini }
712c50d8ae3SPaolo Bonzini 
713c50d8ae3SPaolo Bonzini static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
714c50d8ae3SPaolo Bonzini {
715c50d8ae3SPaolo Bonzini 	kmem_cache_free(pte_list_desc_cache, pte_list_desc);
716c50d8ae3SPaolo Bonzini }
717c50d8ae3SPaolo Bonzini 
7186a97575dSDavid Matlack static bool sp_has_gptes(struct kvm_mmu_page *sp);
7196a97575dSDavid Matlack 
720c50d8ae3SPaolo Bonzini static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
721c50d8ae3SPaolo Bonzini {
72284e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
72384e5ffd0SLai Jiangshan 		return sp->gfn;
72484e5ffd0SLai Jiangshan 
7259ecc1c11SHou Wenlong 	if (sp->shadowed_translation)
7266a97575dSDavid Matlack 		return sp->shadowed_translation[index] >> PAGE_SHIFT;
727c50d8ae3SPaolo Bonzini 
7282ca3129eSSean Christopherson 	return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
729c50d8ae3SPaolo Bonzini }
730c50d8ae3SPaolo Bonzini 
7316a97575dSDavid Matlack /*
7326a97575dSDavid Matlack  * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
7336a97575dSDavid Matlack  * that the SPTE itself may have a more constrained access permissions that
7346a97575dSDavid Matlack  * what the guest enforces. For example, a guest may create an executable
7356a97575dSDavid Matlack  * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
7366a97575dSDavid Matlack  */
7376a97575dSDavid Matlack static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
738c50d8ae3SPaolo Bonzini {
7399ecc1c11SHou Wenlong 	if (sp->shadowed_translation)
7406a97575dSDavid Matlack 		return sp->shadowed_translation[index] & ACC_ALL;
7416a97575dSDavid Matlack 
7426a97575dSDavid Matlack 	/*
7436a97575dSDavid Matlack 	 * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
7446a97575dSDavid Matlack 	 * KVM is not shadowing any guest page tables, so the "guest access
7456a97575dSDavid Matlack 	 * permissions" are just ACC_ALL.
7466a97575dSDavid Matlack 	 *
7476a97575dSDavid Matlack 	 * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
7486a97575dSDavid Matlack 	 * is shadowing a guest huge page with small pages, the guest access
7496a97575dSDavid Matlack 	 * permissions being shadowed are the access permissions of the huge
7506a97575dSDavid Matlack 	 * page.
7516a97575dSDavid Matlack 	 *
7526a97575dSDavid Matlack 	 * In both cases, sp->role.access contains the correct access bits.
7536a97575dSDavid Matlack 	 */
7546a97575dSDavid Matlack 	return sp->role.access;
7556a97575dSDavid Matlack }
7566a97575dSDavid Matlack 
75772ae5822SSean Christopherson static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
75872ae5822SSean Christopherson 					 gfn_t gfn, unsigned int access)
7596a97575dSDavid Matlack {
7609ecc1c11SHou Wenlong 	if (sp->shadowed_translation) {
7616a97575dSDavid Matlack 		sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
76284e5ffd0SLai Jiangshan 		return;
76384e5ffd0SLai Jiangshan 	}
76484e5ffd0SLai Jiangshan 
7656a97575dSDavid Matlack 	WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
7666a97575dSDavid Matlack 	          "access mismatch under %s page %llx (expected %u, got %u)\n",
7676a97575dSDavid Matlack 	          sp->role.passthrough ? "passthrough" : "direct",
7686a97575dSDavid Matlack 	          sp->gfn, kvm_mmu_page_get_access(sp, index), access);
7696a97575dSDavid Matlack 
7706a97575dSDavid Matlack 	WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
7716a97575dSDavid Matlack 	          "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
7726a97575dSDavid Matlack 	          sp->role.passthrough ? "passthrough" : "direct",
7736a97575dSDavid Matlack 	          sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
774c50d8ae3SPaolo Bonzini }
775c50d8ae3SPaolo Bonzini 
77672ae5822SSean Christopherson static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
77772ae5822SSean Christopherson 				    unsigned int access)
7786a97575dSDavid Matlack {
7796a97575dSDavid Matlack 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
7806a97575dSDavid Matlack 
7816a97575dSDavid Matlack 	kvm_mmu_page_set_translation(sp, index, gfn, access);
782c50d8ae3SPaolo Bonzini }
783c50d8ae3SPaolo Bonzini 
784c50d8ae3SPaolo Bonzini /*
785c50d8ae3SPaolo Bonzini  * Return the pointer to the large page information for a given gfn,
786c50d8ae3SPaolo Bonzini  * handling slots that are not large page aligned.
787c50d8ae3SPaolo Bonzini  */
788c50d8ae3SPaolo Bonzini static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
7898ca6f063SBen Gardon 		const struct kvm_memory_slot *slot, int level)
790c50d8ae3SPaolo Bonzini {
791c50d8ae3SPaolo Bonzini 	unsigned long idx;
792c50d8ae3SPaolo Bonzini 
793c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
794c50d8ae3SPaolo Bonzini 	return &slot->arch.lpage_info[level - 2][idx];
795c50d8ae3SPaolo Bonzini }
796c50d8ae3SPaolo Bonzini 
79790b4fe17SChao Peng /*
79890b4fe17SChao Peng  * The most significant bit in disallow_lpage tracks whether or not memory
79990b4fe17SChao Peng  * attributes are mixed, i.e. not identical for all gfns at the current level.
80090b4fe17SChao Peng  * The lower order bits are used to refcount other cases where a hugepage is
80190b4fe17SChao Peng  * disallowed, e.g. if KVM has shadow a page table at the gfn.
80290b4fe17SChao Peng  */
80390b4fe17SChao Peng #define KVM_LPAGE_MIXED_FLAG	BIT(31)
80490b4fe17SChao Peng 
805269e9552SHamza Mahfooz static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
806c50d8ae3SPaolo Bonzini 					    gfn_t gfn, int count)
807c50d8ae3SPaolo Bonzini {
808c50d8ae3SPaolo Bonzini 	struct kvm_lpage_info *linfo;
80990b4fe17SChao Peng 	int old, i;
810c50d8ae3SPaolo Bonzini 
8113bae0459SSean Christopherson 	for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
812c50d8ae3SPaolo Bonzini 		linfo = lpage_info_slot(gfn, slot, i);
81390b4fe17SChao Peng 
81490b4fe17SChao Peng 		old = linfo->disallow_lpage;
815c50d8ae3SPaolo Bonzini 		linfo->disallow_lpage += count;
81690b4fe17SChao Peng 		WARN_ON_ONCE((old ^ linfo->disallow_lpage) & KVM_LPAGE_MIXED_FLAG);
817c50d8ae3SPaolo Bonzini 	}
818c50d8ae3SPaolo Bonzini }
819c50d8ae3SPaolo Bonzini 
820269e9552SHamza Mahfooz void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
821c50d8ae3SPaolo Bonzini {
822c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, 1);
823c50d8ae3SPaolo Bonzini }
824c50d8ae3SPaolo Bonzini 
825269e9552SHamza Mahfooz void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
826c50d8ae3SPaolo Bonzini {
827c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, -1);
828c50d8ae3SPaolo Bonzini }
829c50d8ae3SPaolo Bonzini 
830c50d8ae3SPaolo Bonzini static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
831c50d8ae3SPaolo Bonzini {
832c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
833c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
834c50d8ae3SPaolo Bonzini 	gfn_t gfn;
835c50d8ae3SPaolo Bonzini 
836c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages++;
837226d9b8fSSean Christopherson 	/*
838226d9b8fSSean Christopherson 	 * Ensure indirect_shadow_pages is elevated prior to re-reading guest
839226d9b8fSSean Christopherson 	 * child PTEs in FNAME(gpte_changed), i.e. guarantee either in-flight
840226d9b8fSSean Christopherson 	 * emulated writes are visible before re-reading guest PTEs, or that
841226d9b8fSSean Christopherson 	 * an emulated write will see the elevated count and acquire mmu_lock
842226d9b8fSSean Christopherson 	 * to update SPTEs.  Pairs with the smp_mb() in kvm_mmu_track_write().
843226d9b8fSSean Christopherson 	 */
844226d9b8fSSean Christopherson 	smp_mb();
845226d9b8fSSean Christopherson 
846c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
847c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
848c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
849c50d8ae3SPaolo Bonzini 
850c50d8ae3SPaolo Bonzini 	/* the non-leaf shadow pages are keeping readonly. */
8513bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
85296316a06SSean Christopherson 		return __kvm_write_track_add_gfn(kvm, slot, gfn);
853c50d8ae3SPaolo Bonzini 
854c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
855be911771SDavid Matlack 
856be911771SDavid Matlack 	if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
8574ad980aeSHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, PG_LEVEL_4K);
858c50d8ae3SPaolo Bonzini }
859c50d8ae3SPaolo Bonzini 
86061f94478SSean Christopherson void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
861c50d8ae3SPaolo Bonzini {
862428e9216SSean Christopherson 	/*
863428e9216SSean Christopherson 	 * If it's possible to replace the shadow page with an NX huge page,
864428e9216SSean Christopherson 	 * i.e. if the shadow page is the only thing currently preventing KVM
865428e9216SSean Christopherson 	 * from using a huge page, add the shadow page to the list of "to be
866428e9216SSean Christopherson 	 * zapped for NX recovery" pages.  Note, the shadow page can already be
867428e9216SSean Christopherson 	 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
868428e9216SSean Christopherson 	 * links a shadow page at multiple points.
869428e9216SSean Christopherson 	 */
87061f94478SSean Christopherson 	if (!list_empty(&sp->possible_nx_huge_page_link))
871c50d8ae3SPaolo Bonzini 		return;
872c50d8ae3SPaolo Bonzini 
873c50d8ae3SPaolo Bonzini 	++kvm->stat.nx_lpage_splits;
87455c510e2SSean Christopherson 	list_add_tail(&sp->possible_nx_huge_page_link,
87555c510e2SSean Christopherson 		      &kvm->arch.possible_nx_huge_pages);
876c50d8ae3SPaolo Bonzini }
877c50d8ae3SPaolo Bonzini 
87861f94478SSean Christopherson static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
87961f94478SSean Christopherson 				 bool nx_huge_page_possible)
88061f94478SSean Christopherson {
88161f94478SSean Christopherson 	sp->nx_huge_page_disallowed = true;
88261f94478SSean Christopherson 
88361f94478SSean Christopherson 	if (nx_huge_page_possible)
88461f94478SSean Christopherson 		track_possible_nx_huge_page(kvm, sp);
885c50d8ae3SPaolo Bonzini }
886c50d8ae3SPaolo Bonzini 
887c50d8ae3SPaolo Bonzini static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
888c50d8ae3SPaolo Bonzini {
889c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
890c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
891c50d8ae3SPaolo Bonzini 	gfn_t gfn;
892c50d8ae3SPaolo Bonzini 
893c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages--;
894c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
895c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
896c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
8973bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
89896316a06SSean Christopherson 		return __kvm_write_track_remove_gfn(kvm, slot, gfn);
899c50d8ae3SPaolo Bonzini 
900c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_allow_lpage(slot, gfn);
901c50d8ae3SPaolo Bonzini }
902c50d8ae3SPaolo Bonzini 
90361f94478SSean Christopherson void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
904c50d8ae3SPaolo Bonzini {
90555c510e2SSean Christopherson 	if (list_empty(&sp->possible_nx_huge_page_link))
906428e9216SSean Christopherson 		return;
907428e9216SSean Christopherson 
908c50d8ae3SPaolo Bonzini 	--kvm->stat.nx_lpage_splits;
90955c510e2SSean Christopherson 	list_del_init(&sp->possible_nx_huge_page_link);
910c50d8ae3SPaolo Bonzini }
911c50d8ae3SPaolo Bonzini 
91261f94478SSean Christopherson static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
91361f94478SSean Christopherson {
91461f94478SSean Christopherson 	sp->nx_huge_page_disallowed = false;
91561f94478SSean Christopherson 
91661f94478SSean Christopherson 	untrack_possible_nx_huge_page(kvm, sp);
917c50d8ae3SPaolo Bonzini }
918c50d8ae3SPaolo Bonzini 
919f3d90f90SSean Christopherson static struct kvm_memory_slot *gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu,
920f3d90f90SSean Christopherson 							   gfn_t gfn,
921c50d8ae3SPaolo Bonzini 							   bool no_dirty_log)
922c50d8ae3SPaolo Bonzini {
923c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
924c50d8ae3SPaolo Bonzini 
925c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
92691b0d268SPaolo Bonzini 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
92791b0d268SPaolo Bonzini 		return NULL;
928044c59c4SPeter Xu 	if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
92991b0d268SPaolo Bonzini 		return NULL;
930c50d8ae3SPaolo Bonzini 
931c50d8ae3SPaolo Bonzini 	return slot;
932c50d8ae3SPaolo Bonzini }
933c50d8ae3SPaolo Bonzini 
934c50d8ae3SPaolo Bonzini /*
935c50d8ae3SPaolo Bonzini  * About rmap_head encoding:
936c50d8ae3SPaolo Bonzini  *
937c50d8ae3SPaolo Bonzini  * If the bit zero of rmap_head->val is clear, then it points to the only spte
938c50d8ae3SPaolo Bonzini  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
939c50d8ae3SPaolo Bonzini  * pte_list_desc containing more mappings.
940c50d8ae3SPaolo Bonzini  */
941c50d8ae3SPaolo Bonzini 
942c50d8ae3SPaolo Bonzini /*
943c50d8ae3SPaolo Bonzini  * Returns the number of pointers in the rmap chain, not counting the new one.
944c50d8ae3SPaolo Bonzini  */
9452ff9039aSDavid Matlack static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
946c50d8ae3SPaolo Bonzini 			struct kvm_rmap_head *rmap_head)
947c50d8ae3SPaolo Bonzini {
948c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
94913236e25SPeter Xu 	int count = 0;
950c50d8ae3SPaolo Bonzini 
951c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
952c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)spte;
953c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
9542ff9039aSDavid Matlack 		desc = kvm_mmu_memory_cache_alloc(cache);
955c50d8ae3SPaolo Bonzini 		desc->sptes[0] = (u64 *)rmap_head->val;
956c50d8ae3SPaolo Bonzini 		desc->sptes[1] = spte;
95713236e25SPeter Xu 		desc->spte_count = 2;
958141705b7SLai Jiangshan 		desc->tail_count = 0;
959c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)desc | 1;
960c50d8ae3SPaolo Bonzini 		++count;
961c50d8ae3SPaolo Bonzini 	} else {
962c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
963141705b7SLai Jiangshan 		count = desc->tail_count + desc->spte_count;
964141705b7SLai Jiangshan 
965141705b7SLai Jiangshan 		/*
966141705b7SLai Jiangshan 		 * If the previous head is full, allocate a new head descriptor
967141705b7SLai Jiangshan 		 * as tail descriptors are always kept full.
968141705b7SLai Jiangshan 		 */
969141705b7SLai Jiangshan 		if (desc->spte_count == PTE_LIST_EXT) {
970141705b7SLai Jiangshan 			desc = kvm_mmu_memory_cache_alloc(cache);
971141705b7SLai Jiangshan 			desc->more = (struct pte_list_desc *)(rmap_head->val & ~1ul);
97213236e25SPeter Xu 			desc->spte_count = 0;
973141705b7SLai Jiangshan 			desc->tail_count = count;
974141705b7SLai Jiangshan 			rmap_head->val = (unsigned long)desc | 1;
975c6c4f961SLi RongQing 		}
97613236e25SPeter Xu 		desc->sptes[desc->spte_count++] = spte;
977c50d8ae3SPaolo Bonzini 	}
978c50d8ae3SPaolo Bonzini 	return count;
979c50d8ae3SPaolo Bonzini }
980c50d8ae3SPaolo Bonzini 
981069f30c6SMingwei Zhang static void pte_list_desc_remove_entry(struct kvm *kvm,
982069f30c6SMingwei Zhang 				       struct kvm_rmap_head *rmap_head,
983141705b7SLai Jiangshan 				       struct pte_list_desc *desc, int i)
984c50d8ae3SPaolo Bonzini {
985141705b7SLai Jiangshan 	struct pte_list_desc *head_desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
986141705b7SLai Jiangshan 	int j = head_desc->spte_count - 1;
987c50d8ae3SPaolo Bonzini 
988141705b7SLai Jiangshan 	/*
989141705b7SLai Jiangshan 	 * The head descriptor should never be empty.  A new head is added only
990141705b7SLai Jiangshan 	 * when adding an entry and the previous head is full, and heads are
991141705b7SLai Jiangshan 	 * removed (this flow) when they become empty.
992141705b7SLai Jiangshan 	 */
99352e322edSSean Christopherson 	KVM_BUG_ON_DATA_CORRUPTION(j < 0, kvm);
994141705b7SLai Jiangshan 
995141705b7SLai Jiangshan 	/*
996141705b7SLai Jiangshan 	 * Replace the to-be-freed SPTE with the last valid entry from the head
997141705b7SLai Jiangshan 	 * descriptor to ensure that tail descriptors are full at all times.
998141705b7SLai Jiangshan 	 * Note, this also means that tail_count is stable for each descriptor.
999141705b7SLai Jiangshan 	 */
1000141705b7SLai Jiangshan 	desc->sptes[i] = head_desc->sptes[j];
1001141705b7SLai Jiangshan 	head_desc->sptes[j] = NULL;
1002141705b7SLai Jiangshan 	head_desc->spte_count--;
1003141705b7SLai Jiangshan 	if (head_desc->spte_count)
1004c50d8ae3SPaolo Bonzini 		return;
1005141705b7SLai Jiangshan 
1006141705b7SLai Jiangshan 	/*
1007141705b7SLai Jiangshan 	 * The head descriptor is empty.  If there are no tail descriptors,
100854aa699eSBjorn Helgaas 	 * nullify the rmap head to mark the list as empty, else point the rmap
1009141705b7SLai Jiangshan 	 * head at the next descriptor, i.e. the new head.
1010141705b7SLai Jiangshan 	 */
1011141705b7SLai Jiangshan 	if (!head_desc->more)
1012fe3c2b4cSMiaohe Lin 		rmap_head->val = 0;
1013c50d8ae3SPaolo Bonzini 	else
1014141705b7SLai Jiangshan 		rmap_head->val = (unsigned long)head_desc->more | 1;
1015141705b7SLai Jiangshan 	mmu_free_pte_list_desc(head_desc);
1016c50d8ae3SPaolo Bonzini }
1017c50d8ae3SPaolo Bonzini 
1018069f30c6SMingwei Zhang static void pte_list_remove(struct kvm *kvm, u64 *spte,
1019069f30c6SMingwei Zhang 			    struct kvm_rmap_head *rmap_head)
1020c50d8ae3SPaolo Bonzini {
1021c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
1022c50d8ae3SPaolo Bonzini 	int i;
1023c50d8ae3SPaolo Bonzini 
102452e322edSSean Christopherson 	if (KVM_BUG_ON_DATA_CORRUPTION(!rmap_head->val, kvm))
102552e322edSSean Christopherson 		return;
102652e322edSSean Christopherson 
102752e322edSSean Christopherson 	if (!(rmap_head->val & 1)) {
102852e322edSSean Christopherson 		if (KVM_BUG_ON_DATA_CORRUPTION((u64 *)rmap_head->val != spte, kvm))
102952e322edSSean Christopherson 			return;
103052e322edSSean Christopherson 
1031c50d8ae3SPaolo Bonzini 		rmap_head->val = 0;
1032c50d8ae3SPaolo Bonzini 	} else {
1033c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1034c50d8ae3SPaolo Bonzini 		while (desc) {
103513236e25SPeter Xu 			for (i = 0; i < desc->spte_count; ++i) {
1036c50d8ae3SPaolo Bonzini 				if (desc->sptes[i] == spte) {
1037069f30c6SMingwei Zhang 					pte_list_desc_remove_entry(kvm, rmap_head,
1038069f30c6SMingwei Zhang 								   desc, i);
1039c50d8ae3SPaolo Bonzini 					return;
1040c50d8ae3SPaolo Bonzini 				}
1041c50d8ae3SPaolo Bonzini 			}
1042c50d8ae3SPaolo Bonzini 			desc = desc->more;
1043c50d8ae3SPaolo Bonzini 		}
104452e322edSSean Christopherson 
104552e322edSSean Christopherson 		KVM_BUG_ON_DATA_CORRUPTION(true, kvm);
1046c50d8ae3SPaolo Bonzini 	}
1047c50d8ae3SPaolo Bonzini }
1048c50d8ae3SPaolo Bonzini 
10499202aee8SSean Christopherson static void kvm_zap_one_rmap_spte(struct kvm *kvm,
10509202aee8SSean Christopherson 				  struct kvm_rmap_head *rmap_head, u64 *sptep)
1051c50d8ae3SPaolo Bonzini {
105271f51d2cSMingwei Zhang 	mmu_spte_clear_track_bits(kvm, sptep);
1053069f30c6SMingwei Zhang 	pte_list_remove(kvm, sptep, rmap_head);
1054c50d8ae3SPaolo Bonzini }
1055c50d8ae3SPaolo Bonzini 
10569202aee8SSean Christopherson /* Return true if at least one SPTE was zapped, false otherwise */
10579202aee8SSean Christopherson static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
10589202aee8SSean Christopherson 				   struct kvm_rmap_head *rmap_head)
1059a75b5404SPeter Xu {
1060a75b5404SPeter Xu 	struct pte_list_desc *desc, *next;
1061a75b5404SPeter Xu 	int i;
1062a75b5404SPeter Xu 
1063a75b5404SPeter Xu 	if (!rmap_head->val)
1064a75b5404SPeter Xu 		return false;
1065a75b5404SPeter Xu 
1066a75b5404SPeter Xu 	if (!(rmap_head->val & 1)) {
106771f51d2cSMingwei Zhang 		mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
1068a75b5404SPeter Xu 		goto out;
1069a75b5404SPeter Xu 	}
1070a75b5404SPeter Xu 
1071a75b5404SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1072a75b5404SPeter Xu 
1073a75b5404SPeter Xu 	for (; desc; desc = next) {
1074a75b5404SPeter Xu 		for (i = 0; i < desc->spte_count; i++)
107571f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1076a75b5404SPeter Xu 		next = desc->more;
1077a75b5404SPeter Xu 		mmu_free_pte_list_desc(desc);
1078a75b5404SPeter Xu 	}
1079a75b5404SPeter Xu out:
1080a75b5404SPeter Xu 	/* rmap_head is meaningless now, remember to reset it */
1081a75b5404SPeter Xu 	rmap_head->val = 0;
1082a75b5404SPeter Xu 	return true;
1083a75b5404SPeter Xu }
1084a75b5404SPeter Xu 
10853bcd0662SPeter Xu unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
10863bcd0662SPeter Xu {
10873bcd0662SPeter Xu 	struct pte_list_desc *desc;
10883bcd0662SPeter Xu 
10893bcd0662SPeter Xu 	if (!rmap_head->val)
10903bcd0662SPeter Xu 		return 0;
10913bcd0662SPeter Xu 	else if (!(rmap_head->val & 1))
10923bcd0662SPeter Xu 		return 1;
10933bcd0662SPeter Xu 
10943bcd0662SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1095141705b7SLai Jiangshan 	return desc->tail_count + desc->spte_count;
10963bcd0662SPeter Xu }
10973bcd0662SPeter Xu 
109893e083d4SDavid Matlack static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1099269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
1100c50d8ae3SPaolo Bonzini {
1101c50d8ae3SPaolo Bonzini 	unsigned long idx;
1102c50d8ae3SPaolo Bonzini 
1103c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
11043bae0459SSean Christopherson 	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1105c50d8ae3SPaolo Bonzini }
1106c50d8ae3SPaolo Bonzini 
1107c50d8ae3SPaolo Bonzini static void rmap_remove(struct kvm *kvm, u64 *spte)
1108c50d8ae3SPaolo Bonzini {
1109601f8af0SDavid Matlack 	struct kvm_memslots *slots;
1110601f8af0SDavid Matlack 	struct kvm_memory_slot *slot;
1111c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1112c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1113c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1114c50d8ae3SPaolo Bonzini 
111557354682SSean Christopherson 	sp = sptep_to_sp(spte);
111679e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1117601f8af0SDavid Matlack 
1118601f8af0SDavid Matlack 	/*
111968be1306SDavid Matlack 	 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
112068be1306SDavid Matlack 	 * so we have to determine which memslots to use based on context
112168be1306SDavid Matlack 	 * information in sp->role.
1122601f8af0SDavid Matlack 	 */
1123601f8af0SDavid Matlack 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1124601f8af0SDavid Matlack 
1125601f8af0SDavid Matlack 	slot = __gfn_to_memslot(slots, gfn);
112693e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1127601f8af0SDavid Matlack 
1128069f30c6SMingwei Zhang 	pte_list_remove(kvm, spte, rmap_head);
1129c50d8ae3SPaolo Bonzini }
1130c50d8ae3SPaolo Bonzini 
1131c50d8ae3SPaolo Bonzini /*
1132c50d8ae3SPaolo Bonzini  * Used by the following functions to iterate through the sptes linked by a
1133c50d8ae3SPaolo Bonzini  * rmap.  All fields are private and not assumed to be used outside.
1134c50d8ae3SPaolo Bonzini  */
1135c50d8ae3SPaolo Bonzini struct rmap_iterator {
1136c50d8ae3SPaolo Bonzini 	/* private fields */
1137c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1138c50d8ae3SPaolo Bonzini 	int pos;			/* index of the sptep */
1139c50d8ae3SPaolo Bonzini };
1140c50d8ae3SPaolo Bonzini 
1141c50d8ae3SPaolo Bonzini /*
1142c50d8ae3SPaolo Bonzini  * Iteration must be started by this function.  This should also be used after
1143c50d8ae3SPaolo Bonzini  * removing/dropping sptes from the rmap link because in such cases the
11440a03cbdaSMiaohe Lin  * information in the iterator may not be valid.
1145c50d8ae3SPaolo Bonzini  *
1146c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1147c50d8ae3SPaolo Bonzini  */
1148c50d8ae3SPaolo Bonzini static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1149c50d8ae3SPaolo Bonzini 			   struct rmap_iterator *iter)
1150c50d8ae3SPaolo Bonzini {
1151c50d8ae3SPaolo Bonzini 	u64 *sptep;
1152c50d8ae3SPaolo Bonzini 
1153c50d8ae3SPaolo Bonzini 	if (!rmap_head->val)
1154c50d8ae3SPaolo Bonzini 		return NULL;
1155c50d8ae3SPaolo Bonzini 
1156c50d8ae3SPaolo Bonzini 	if (!(rmap_head->val & 1)) {
1157c50d8ae3SPaolo Bonzini 		iter->desc = NULL;
1158c50d8ae3SPaolo Bonzini 		sptep = (u64 *)rmap_head->val;
1159c50d8ae3SPaolo Bonzini 		goto out;
1160c50d8ae3SPaolo Bonzini 	}
1161c50d8ae3SPaolo Bonzini 
1162c50d8ae3SPaolo Bonzini 	iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1163c50d8ae3SPaolo Bonzini 	iter->pos = 0;
1164c50d8ae3SPaolo Bonzini 	sptep = iter->desc->sptes[iter->pos];
1165c50d8ae3SPaolo Bonzini out:
1166c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1167c50d8ae3SPaolo Bonzini 	return sptep;
1168c50d8ae3SPaolo Bonzini }
1169c50d8ae3SPaolo Bonzini 
1170c50d8ae3SPaolo Bonzini /*
1171c50d8ae3SPaolo Bonzini  * Must be used with a valid iterator: e.g. after rmap_get_first().
1172c50d8ae3SPaolo Bonzini  *
1173c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1174c50d8ae3SPaolo Bonzini  */
1175c50d8ae3SPaolo Bonzini static u64 *rmap_get_next(struct rmap_iterator *iter)
1176c50d8ae3SPaolo Bonzini {
1177c50d8ae3SPaolo Bonzini 	u64 *sptep;
1178c50d8ae3SPaolo Bonzini 
1179c50d8ae3SPaolo Bonzini 	if (iter->desc) {
1180c50d8ae3SPaolo Bonzini 		if (iter->pos < PTE_LIST_EXT - 1) {
1181c50d8ae3SPaolo Bonzini 			++iter->pos;
1182c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1183c50d8ae3SPaolo Bonzini 			if (sptep)
1184c50d8ae3SPaolo Bonzini 				goto out;
1185c50d8ae3SPaolo Bonzini 		}
1186c50d8ae3SPaolo Bonzini 
1187c50d8ae3SPaolo Bonzini 		iter->desc = iter->desc->more;
1188c50d8ae3SPaolo Bonzini 
1189c50d8ae3SPaolo Bonzini 		if (iter->desc) {
1190c50d8ae3SPaolo Bonzini 			iter->pos = 0;
1191c50d8ae3SPaolo Bonzini 			/* desc->sptes[0] cannot be NULL */
1192c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1193c50d8ae3SPaolo Bonzini 			goto out;
1194c50d8ae3SPaolo Bonzini 		}
1195c50d8ae3SPaolo Bonzini 	}
1196c50d8ae3SPaolo Bonzini 
1197c50d8ae3SPaolo Bonzini 	return NULL;
1198c50d8ae3SPaolo Bonzini out:
1199c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1200c50d8ae3SPaolo Bonzini 	return sptep;
1201c50d8ae3SPaolo Bonzini }
1202c50d8ae3SPaolo Bonzini 
1203c50d8ae3SPaolo Bonzini #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)			\
1204c50d8ae3SPaolo Bonzini 	for (_spte_ = rmap_get_first(_rmap_head_, _iter_);		\
1205c50d8ae3SPaolo Bonzini 	     _spte_; _spte_ = rmap_get_next(_iter_))
1206c50d8ae3SPaolo Bonzini 
1207c50d8ae3SPaolo Bonzini static void drop_spte(struct kvm *kvm, u64 *sptep)
1208c50d8ae3SPaolo Bonzini {
120971f51d2cSMingwei Zhang 	u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
12107fa2a347SSean Christopherson 
12117fa2a347SSean Christopherson 	if (is_shadow_present_pte(old_spte))
1212c50d8ae3SPaolo Bonzini 		rmap_remove(kvm, sptep);
1213c50d8ae3SPaolo Bonzini }
1214c50d8ae3SPaolo Bonzini 
121503787394SPaolo Bonzini static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1216c50d8ae3SPaolo Bonzini {
12170cd8dc73SPaolo Bonzini 	struct kvm_mmu_page *sp;
12180cd8dc73SPaolo Bonzini 
12190cd8dc73SPaolo Bonzini 	sp = sptep_to_sp(sptep);
122020ba462dSSean Christopherson 	WARN_ON_ONCE(sp->role.level == PG_LEVEL_4K);
12210cd8dc73SPaolo Bonzini 
1222c50d8ae3SPaolo Bonzini 	drop_spte(kvm, sptep);
122303787394SPaolo Bonzini 
122403787394SPaolo Bonzini 	if (flush)
12251b2dc736SHou Wenlong 		kvm_flush_remote_tlbs_sptep(kvm, sptep);
1226c50d8ae3SPaolo Bonzini }
1227c50d8ae3SPaolo Bonzini 
1228c50d8ae3SPaolo Bonzini /*
1229c50d8ae3SPaolo Bonzini  * Write-protect on the specified @sptep, @pt_protect indicates whether
1230c50d8ae3SPaolo Bonzini  * spte write-protection is caused by protecting shadow page table.
1231c50d8ae3SPaolo Bonzini  *
1232c50d8ae3SPaolo Bonzini  * Note: write protection is difference between dirty logging and spte
1233c50d8ae3SPaolo Bonzini  * protection:
1234c50d8ae3SPaolo Bonzini  * - for dirty logging, the spte can be set to writable at anytime if
1235c50d8ae3SPaolo Bonzini  *   its dirty bitmap is properly set.
1236c50d8ae3SPaolo Bonzini  * - for spte protection, the spte can be writable only after unsync-ing
1237c50d8ae3SPaolo Bonzini  *   shadow page.
1238c50d8ae3SPaolo Bonzini  *
1239c50d8ae3SPaolo Bonzini  * Return true if tlb need be flushed.
1240c50d8ae3SPaolo Bonzini  */
1241c50d8ae3SPaolo Bonzini static bool spte_write_protect(u64 *sptep, bool pt_protect)
1242c50d8ae3SPaolo Bonzini {
1243c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1244c50d8ae3SPaolo Bonzini 
1245c50d8ae3SPaolo Bonzini 	if (!is_writable_pte(spte) &&
1246706c9c55SSean Christopherson 	    !(pt_protect && is_mmu_writable_spte(spte)))
1247c50d8ae3SPaolo Bonzini 		return false;
1248c50d8ae3SPaolo Bonzini 
1249c50d8ae3SPaolo Bonzini 	if (pt_protect)
12505fc3424fSSean Christopherson 		spte &= ~shadow_mmu_writable_mask;
1251c50d8ae3SPaolo Bonzini 	spte = spte & ~PT_WRITABLE_MASK;
1252c50d8ae3SPaolo Bonzini 
1253c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1254c50d8ae3SPaolo Bonzini }
1255c50d8ae3SPaolo Bonzini 
12561346bbb6SDavid Matlack static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1257c50d8ae3SPaolo Bonzini 			       bool pt_protect)
1258c50d8ae3SPaolo Bonzini {
1259c50d8ae3SPaolo Bonzini 	u64 *sptep;
1260c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1261c50d8ae3SPaolo Bonzini 	bool flush = false;
1262c50d8ae3SPaolo Bonzini 
1263c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1264c50d8ae3SPaolo Bonzini 		flush |= spte_write_protect(sptep, pt_protect);
1265c50d8ae3SPaolo Bonzini 
1266c50d8ae3SPaolo Bonzini 	return flush;
1267c50d8ae3SPaolo Bonzini }
1268c50d8ae3SPaolo Bonzini 
1269c50d8ae3SPaolo Bonzini static bool spte_clear_dirty(u64 *sptep)
1270c50d8ae3SPaolo Bonzini {
1271c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1272c50d8ae3SPaolo Bonzini 
12730fe6370eSSean Christopherson 	KVM_MMU_WARN_ON(!spte_ad_enabled(spte));
1274c50d8ae3SPaolo Bonzini 	spte &= ~shadow_dirty_mask;
1275c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1276c50d8ae3SPaolo Bonzini }
1277c50d8ae3SPaolo Bonzini 
1278c50d8ae3SPaolo Bonzini static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1279c50d8ae3SPaolo Bonzini {
1280c50d8ae3SPaolo Bonzini 	bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1281c50d8ae3SPaolo Bonzini 					       (unsigned long *)sptep);
1282c50d8ae3SPaolo Bonzini 	if (was_writable && !spte_ad_enabled(*sptep))
1283c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1284c50d8ae3SPaolo Bonzini 
1285c50d8ae3SPaolo Bonzini 	return was_writable;
1286c50d8ae3SPaolo Bonzini }
1287c50d8ae3SPaolo Bonzini 
1288c50d8ae3SPaolo Bonzini /*
1289c50d8ae3SPaolo Bonzini  * Gets the GFN ready for another round of dirty logging by clearing the
1290c50d8ae3SPaolo Bonzini  *	- D bit on ad-enabled SPTEs, and
1291c50d8ae3SPaolo Bonzini  *	- W bit on ad-disabled SPTEs.
1292c50d8ae3SPaolo Bonzini  * Returns true iff any D or W bits were cleared.
1293c50d8ae3SPaolo Bonzini  */
12940a234f5dSSean Christopherson static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1295269e9552SHamza Mahfooz 			       const struct kvm_memory_slot *slot)
1296c50d8ae3SPaolo Bonzini {
1297c50d8ae3SPaolo Bonzini 	u64 *sptep;
1298c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1299c50d8ae3SPaolo Bonzini 	bool flush = false;
1300c50d8ae3SPaolo Bonzini 
1301c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1302c50d8ae3SPaolo Bonzini 		if (spte_ad_need_write_protect(*sptep))
1303c50d8ae3SPaolo Bonzini 			flush |= spte_wrprot_for_clear_dirty(sptep);
1304c50d8ae3SPaolo Bonzini 		else
1305c50d8ae3SPaolo Bonzini 			flush |= spte_clear_dirty(sptep);
1306c50d8ae3SPaolo Bonzini 
1307c50d8ae3SPaolo Bonzini 	return flush;
1308c50d8ae3SPaolo Bonzini }
1309c50d8ae3SPaolo Bonzini 
1310c50d8ae3SPaolo Bonzini /**
1311c50d8ae3SPaolo Bonzini  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1312c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1313c50d8ae3SPaolo Bonzini  * @slot: slot to protect
1314c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1315c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should protect
1316c50d8ae3SPaolo Bonzini  *
131789212919SKeqian Zhu  * Used when we do not need to care about huge page mappings.
1318c50d8ae3SPaolo Bonzini  */
1319c50d8ae3SPaolo Bonzini static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1320c50d8ae3SPaolo Bonzini 				     struct kvm_memory_slot *slot,
1321c50d8ae3SPaolo Bonzini 				     gfn_t gfn_offset, unsigned long mask)
1322c50d8ae3SPaolo Bonzini {
1323c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1324c50d8ae3SPaolo Bonzini 
13251f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1326a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1327a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, true);
1328e2209710SBen Gardon 
1329e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1330e2209710SBen Gardon 		return;
1331e2209710SBen Gardon 
1332c50d8ae3SPaolo Bonzini 	while (mask) {
133393e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13343bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13351346bbb6SDavid Matlack 		rmap_write_protect(rmap_head, false);
1336c50d8ae3SPaolo Bonzini 
1337c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1338c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1339c50d8ae3SPaolo Bonzini 	}
1340c50d8ae3SPaolo Bonzini }
1341c50d8ae3SPaolo Bonzini 
1342c50d8ae3SPaolo Bonzini /**
1343c50d8ae3SPaolo Bonzini  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1344c50d8ae3SPaolo Bonzini  * protect the page if the D-bit isn't supported.
1345c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1346c50d8ae3SPaolo Bonzini  * @slot: slot to clear D-bit
1347c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1348c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should clear D-bit
1349c50d8ae3SPaolo Bonzini  *
1350c50d8ae3SPaolo Bonzini  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1351c50d8ae3SPaolo Bonzini  */
1352a018eba5SSean Christopherson static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1353c50d8ae3SPaolo Bonzini 					 struct kvm_memory_slot *slot,
1354c50d8ae3SPaolo Bonzini 					 gfn_t gfn_offset, unsigned long mask)
1355c50d8ae3SPaolo Bonzini {
1356c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1357c50d8ae3SPaolo Bonzini 
13581f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1359a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1360a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, false);
1361e2209710SBen Gardon 
1362e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1363e2209710SBen Gardon 		return;
1364e2209710SBen Gardon 
1365c50d8ae3SPaolo Bonzini 	while (mask) {
136693e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13673bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13680a234f5dSSean Christopherson 		__rmap_clear_dirty(kvm, rmap_head, slot);
1369c50d8ae3SPaolo Bonzini 
1370c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1371c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1372c50d8ae3SPaolo Bonzini 	}
1373c50d8ae3SPaolo Bonzini }
1374c50d8ae3SPaolo Bonzini 
1375c50d8ae3SPaolo Bonzini /**
1376c50d8ae3SPaolo Bonzini  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1377c50d8ae3SPaolo Bonzini  * PT level pages.
1378c50d8ae3SPaolo Bonzini  *
1379c50d8ae3SPaolo Bonzini  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1380c50d8ae3SPaolo Bonzini  * enable dirty logging for them.
1381c50d8ae3SPaolo Bonzini  *
138289212919SKeqian Zhu  * We need to care about huge page mappings: e.g. during dirty logging we may
138389212919SKeqian Zhu  * have such mappings.
1384c50d8ae3SPaolo Bonzini  */
1385c50d8ae3SPaolo Bonzini void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1386c50d8ae3SPaolo Bonzini 				struct kvm_memory_slot *slot,
1387c50d8ae3SPaolo Bonzini 				gfn_t gfn_offset, unsigned long mask)
1388c50d8ae3SPaolo Bonzini {
138989212919SKeqian Zhu 	/*
139089212919SKeqian Zhu 	 * Huge pages are NOT write protected when we start dirty logging in
139189212919SKeqian Zhu 	 * initially-all-set mode; must write protect them here so that they
139289212919SKeqian Zhu 	 * are split to 4K on the first write.
139389212919SKeqian Zhu 	 *
139489212919SKeqian Zhu 	 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
139589212919SKeqian Zhu 	 * of memslot has no such restriction, so the range can cross two large
139689212919SKeqian Zhu 	 * pages.
139789212919SKeqian Zhu 	 */
139889212919SKeqian Zhu 	if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
139989212919SKeqian Zhu 		gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
140089212919SKeqian Zhu 		gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
140189212919SKeqian Zhu 
1402cb00a70bSDavid Matlack 		if (READ_ONCE(eager_page_split))
14031aa4bb91SDavid Matlack 			kvm_mmu_try_split_huge_pages(kvm, slot, start, end + 1, PG_LEVEL_4K);
1404cb00a70bSDavid Matlack 
140589212919SKeqian Zhu 		kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
140689212919SKeqian Zhu 
140789212919SKeqian Zhu 		/* Cross two large pages? */
140889212919SKeqian Zhu 		if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
140989212919SKeqian Zhu 		    ALIGN(end << PAGE_SHIFT, PMD_SIZE))
141089212919SKeqian Zhu 			kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
141189212919SKeqian Zhu 						       PG_LEVEL_2M);
141289212919SKeqian Zhu 	}
141389212919SKeqian Zhu 
141489212919SKeqian Zhu 	/* Now handle 4K PTEs.  */
1415a018eba5SSean Christopherson 	if (kvm_x86_ops.cpu_dirty_log_size)
1416a018eba5SSean Christopherson 		kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1417c50d8ae3SPaolo Bonzini 	else
1418c50d8ae3SPaolo Bonzini 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1419c50d8ae3SPaolo Bonzini }
1420c50d8ae3SPaolo Bonzini 
1421fb04a1edSPeter Xu int kvm_cpu_dirty_log_size(void)
1422fb04a1edSPeter Xu {
14236dd03800SSean Christopherson 	return kvm_x86_ops.cpu_dirty_log_size;
1424fb04a1edSPeter Xu }
1425fb04a1edSPeter Xu 
1426c50d8ae3SPaolo Bonzini bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
14273ad93562SKeqian Zhu 				    struct kvm_memory_slot *slot, u64 gfn,
14283ad93562SKeqian Zhu 				    int min_level)
1429c50d8ae3SPaolo Bonzini {
1430c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1431c50d8ae3SPaolo Bonzini 	int i;
1432c50d8ae3SPaolo Bonzini 	bool write_protected = false;
1433c50d8ae3SPaolo Bonzini 
1434e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
14353ad93562SKeqian Zhu 		for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
143693e083d4SDavid Matlack 			rmap_head = gfn_to_rmap(gfn, i, slot);
14371346bbb6SDavid Matlack 			write_protected |= rmap_write_protect(rmap_head, true);
1438c50d8ae3SPaolo Bonzini 		}
1439e2209710SBen Gardon 	}
1440c50d8ae3SPaolo Bonzini 
14411f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
144246044f72SBen Gardon 		write_protected |=
14433ad93562SKeqian Zhu 			kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
144446044f72SBen Gardon 
1445c50d8ae3SPaolo Bonzini 	return write_protected;
1446c50d8ae3SPaolo Bonzini }
1447c50d8ae3SPaolo Bonzini 
1448cf48f9e2SDavid Matlack static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1449c50d8ae3SPaolo Bonzini {
1450c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
1451c50d8ae3SPaolo Bonzini 
1452c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
14533ad93562SKeqian Zhu 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1454c50d8ae3SPaolo Bonzini }
1455c50d8ae3SPaolo Bonzini 
1456f8480721SSean Christopherson static bool __kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1457269e9552SHamza Mahfooz 			   const struct kvm_memory_slot *slot)
1458c50d8ae3SPaolo Bonzini {
14599202aee8SSean Christopherson 	return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1460c50d8ae3SPaolo Bonzini }
1461c50d8ae3SPaolo Bonzini 
1462f8480721SSean Christopherson static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1463f3b65bbaSPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level)
1464c50d8ae3SPaolo Bonzini {
1465f8480721SSean Christopherson 	return __kvm_zap_rmap(kvm, rmap_head, slot);
1466c50d8ae3SPaolo Bonzini }
1467c50d8ae3SPaolo Bonzini 
1468c50d8ae3SPaolo Bonzini struct slot_rmap_walk_iterator {
1469c50d8ae3SPaolo Bonzini 	/* input fields. */
1470269e9552SHamza Mahfooz 	const struct kvm_memory_slot *slot;
1471c50d8ae3SPaolo Bonzini 	gfn_t start_gfn;
1472c50d8ae3SPaolo Bonzini 	gfn_t end_gfn;
1473c50d8ae3SPaolo Bonzini 	int start_level;
1474c50d8ae3SPaolo Bonzini 	int end_level;
1475c50d8ae3SPaolo Bonzini 
1476c50d8ae3SPaolo Bonzini 	/* output fields. */
1477c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1478c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap;
1479c50d8ae3SPaolo Bonzini 	int level;
1480c50d8ae3SPaolo Bonzini 
1481c50d8ae3SPaolo Bonzini 	/* private field. */
1482c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *end_rmap;
1483c50d8ae3SPaolo Bonzini };
1484c50d8ae3SPaolo Bonzini 
1485f3d90f90SSean Christopherson static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,
1486f3d90f90SSean Christopherson 				 int level)
1487c50d8ae3SPaolo Bonzini {
1488c50d8ae3SPaolo Bonzini 	iterator->level = level;
1489c50d8ae3SPaolo Bonzini 	iterator->gfn = iterator->start_gfn;
149093e083d4SDavid Matlack 	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
149193e083d4SDavid Matlack 	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1492c50d8ae3SPaolo Bonzini }
1493c50d8ae3SPaolo Bonzini 
1494f3d90f90SSean Christopherson static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1495f3d90f90SSean Christopherson 				const struct kvm_memory_slot *slot,
1496f3d90f90SSean Christopherson 				int start_level, int end_level,
1497f3d90f90SSean Christopherson 				gfn_t start_gfn, gfn_t end_gfn)
1498c50d8ae3SPaolo Bonzini {
1499c50d8ae3SPaolo Bonzini 	iterator->slot = slot;
1500c50d8ae3SPaolo Bonzini 	iterator->start_level = start_level;
1501c50d8ae3SPaolo Bonzini 	iterator->end_level = end_level;
1502c50d8ae3SPaolo Bonzini 	iterator->start_gfn = start_gfn;
1503c50d8ae3SPaolo Bonzini 	iterator->end_gfn = end_gfn;
1504c50d8ae3SPaolo Bonzini 
1505c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->start_level);
1506c50d8ae3SPaolo Bonzini }
1507c50d8ae3SPaolo Bonzini 
1508c50d8ae3SPaolo Bonzini static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1509c50d8ae3SPaolo Bonzini {
1510c50d8ae3SPaolo Bonzini 	return !!iterator->rmap;
1511c50d8ae3SPaolo Bonzini }
1512c50d8ae3SPaolo Bonzini 
1513c50d8ae3SPaolo Bonzini static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1514c50d8ae3SPaolo Bonzini {
15156ba1e04fSVipin Sharma 	while (++iterator->rmap <= iterator->end_rmap) {
1516c50d8ae3SPaolo Bonzini 		iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
15176ba1e04fSVipin Sharma 
15186ba1e04fSVipin Sharma 		if (iterator->rmap->val)
1519c50d8ae3SPaolo Bonzini 			return;
1520c50d8ae3SPaolo Bonzini 	}
1521c50d8ae3SPaolo Bonzini 
1522c50d8ae3SPaolo Bonzini 	if (++iterator->level > iterator->end_level) {
1523c50d8ae3SPaolo Bonzini 		iterator->rmap = NULL;
1524c50d8ae3SPaolo Bonzini 		return;
1525c50d8ae3SPaolo Bonzini 	}
1526c50d8ae3SPaolo Bonzini 
1527c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->level);
1528c50d8ae3SPaolo Bonzini }
1529c50d8ae3SPaolo Bonzini 
1530c50d8ae3SPaolo Bonzini #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1531c50d8ae3SPaolo Bonzini 	   _start_gfn, _end_gfn, _iter_)				\
1532c50d8ae3SPaolo Bonzini 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1533c50d8ae3SPaolo Bonzini 				 _end_level_, _start_gfn, _end_gfn);	\
1534c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_okay(_iter_);				\
1535c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_next(_iter_))
1536c50d8ae3SPaolo Bonzini 
15373039bcc7SSean Christopherson typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1538c1b91493SSean Christopherson 			       struct kvm_memory_slot *slot, gfn_t gfn,
1539f3b65bbaSPaolo Bonzini 			       int level);
1540c1b91493SSean Christopherson 
15413039bcc7SSean Christopherson static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
15423039bcc7SSean Christopherson 						 struct kvm_gfn_range *range,
1543c1b91493SSean Christopherson 						 rmap_handler_t handler)
1544c50d8ae3SPaolo Bonzini {
1545c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
15463039bcc7SSean Christopherson 	bool ret = false;
1547c50d8ae3SPaolo Bonzini 
15483039bcc7SSean Christopherson 	for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
15493039bcc7SSean Christopherson 				 range->start, range->end - 1, &iterator)
15503039bcc7SSean Christopherson 		ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
1551f3b65bbaSPaolo Bonzini 			       iterator.level);
1552c50d8ae3SPaolo Bonzini 
1553c50d8ae3SPaolo Bonzini 	return ret;
1554c50d8ae3SPaolo Bonzini }
1555c50d8ae3SPaolo Bonzini 
15563039bcc7SSean Christopherson bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1557c50d8ae3SPaolo Bonzini {
1558e2209710SBen Gardon 	bool flush = false;
1559c50d8ae3SPaolo Bonzini 
1560e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1561f8480721SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
1562063afacdSBen Gardon 
15631f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1564c7785d85SHou Wenlong 		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1565063afacdSBen Gardon 
15660a3869e1SSean Christopherson 	if (kvm_x86_ops.set_apic_access_page_addr &&
15670a3869e1SSean Christopherson 	    range->slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT)
15680a8a5f2cSSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
15690a8a5f2cSSean Christopherson 
15703039bcc7SSean Christopherson 	return flush;
1571c50d8ae3SPaolo Bonzini }
1572c50d8ae3SPaolo Bonzini 
1573aed02fe3SSean Christopherson static bool kvm_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1574f3b65bbaSPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level)
1575c50d8ae3SPaolo Bonzini {
1576c50d8ae3SPaolo Bonzini 	u64 *sptep;
15773f649ab7SKees Cook 	struct rmap_iterator iter;
1578c50d8ae3SPaolo Bonzini 	int young = 0;
1579c50d8ae3SPaolo Bonzini 
1580c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1581c50d8ae3SPaolo Bonzini 		young |= mmu_spte_age(sptep);
1582c50d8ae3SPaolo Bonzini 
1583c50d8ae3SPaolo Bonzini 	return young;
1584c50d8ae3SPaolo Bonzini }
1585c50d8ae3SPaolo Bonzini 
1586aed02fe3SSean Christopherson static bool kvm_test_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1587f3b65bbaSPaolo Bonzini 			      struct kvm_memory_slot *slot, gfn_t gfn, int level)
1588c50d8ae3SPaolo Bonzini {
1589c50d8ae3SPaolo Bonzini 	u64 *sptep;
1590c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1591c50d8ae3SPaolo Bonzini 
1592c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1593c50d8ae3SPaolo Bonzini 		if (is_accessed_spte(*sptep))
159498a26b69SVihas Mak 			return true;
159598a26b69SVihas Mak 	return false;
1596c50d8ae3SPaolo Bonzini }
1597c50d8ae3SPaolo Bonzini 
1598c50d8ae3SPaolo Bonzini #define RMAP_RECYCLE_THRESHOLD 1000
1599c50d8ae3SPaolo Bonzini 
16002ff9039aSDavid Matlack static void __rmap_add(struct kvm *kvm,
16012ff9039aSDavid Matlack 		       struct kvm_mmu_memory_cache *cache,
16022ff9039aSDavid Matlack 		       const struct kvm_memory_slot *slot,
160372ae5822SSean Christopherson 		       u64 *spte, gfn_t gfn, unsigned int access)
1604c50d8ae3SPaolo Bonzini {
1605c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
160668be1306SDavid Matlack 	struct kvm_rmap_head *rmap_head;
160768be1306SDavid Matlack 	int rmap_count;
1608c50d8ae3SPaolo Bonzini 
160957354682SSean Christopherson 	sp = sptep_to_sp(spte);
161079e48cecSSean Christopherson 	kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
161181cb4657SDavid Matlack 	kvm_update_page_stats(kvm, sp->role.level, 1);
161281cb4657SDavid Matlack 
161393e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
16142ff9039aSDavid Matlack 	rmap_count = pte_list_add(cache, spte, rmap_head);
1615c50d8ae3SPaolo Bonzini 
1616604f5332SMiaohe Lin 	if (rmap_count > kvm->stat.max_mmu_rmap_size)
1617604f5332SMiaohe Lin 		kvm->stat.max_mmu_rmap_size = rmap_count;
161868be1306SDavid Matlack 	if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
16199202aee8SSean Christopherson 		kvm_zap_all_rmap_sptes(kvm, rmap_head);
16201b2dc736SHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
162168be1306SDavid Matlack 	}
1622c50d8ae3SPaolo Bonzini }
1623c50d8ae3SPaolo Bonzini 
16242ff9039aSDavid Matlack static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
162572ae5822SSean Christopherson 		     u64 *spte, gfn_t gfn, unsigned int access)
16262ff9039aSDavid Matlack {
16272ff9039aSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
16282ff9039aSDavid Matlack 
16296a97575dSDavid Matlack 	__rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
16302ff9039aSDavid Matlack }
16312ff9039aSDavid Matlack 
16323039bcc7SSean Christopherson bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1633c50d8ae3SPaolo Bonzini {
1634e2209710SBen Gardon 	bool young = false;
1635f8e14497SBen Gardon 
1636e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1637aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_age_rmap);
16383039bcc7SSean Christopherson 
16391f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16403039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1641f8e14497SBen Gardon 
1642f8e14497SBen Gardon 	return young;
1643c50d8ae3SPaolo Bonzini }
1644c50d8ae3SPaolo Bonzini 
16453039bcc7SSean Christopherson bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1646c50d8ae3SPaolo Bonzini {
1647e2209710SBen Gardon 	bool young = false;
1648f8e14497SBen Gardon 
1649e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1650aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmap);
16513039bcc7SSean Christopherson 
16521f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16533039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1654f8e14497SBen Gardon 
1655f8e14497SBen Gardon 	return young;
1656c50d8ae3SPaolo Bonzini }
1657c50d8ae3SPaolo Bonzini 
165858da926cSSean Christopherson static void kvm_mmu_check_sptes_at_free(struct kvm_mmu_page *sp)
1659c50d8ae3SPaolo Bonzini {
1660870d4d4eSSean Christopherson #ifdef CONFIG_KVM_PROVE_MMU
1661242a6dd8SSean Christopherson 	int i;
1662c50d8ae3SPaolo Bonzini 
1663242a6dd8SSean Christopherson 	for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
16640fe6370eSSean Christopherson 		if (KVM_MMU_WARN_ON(is_shadow_present_pte(sp->spt[i])))
166558da926cSSean Christopherson 			pr_err_ratelimited("SPTE %llx (@ %p) for gfn %llx shadow-present at free",
166658da926cSSean Christopherson 					   sp->spt[i], &sp->spt[i],
166758da926cSSean Christopherson 					   kvm_mmu_page_get_gfn(sp, i));
1668c50d8ae3SPaolo Bonzini 	}
1669c50d8ae3SPaolo Bonzini #endif
167058da926cSSean Christopherson }
1671c50d8ae3SPaolo Bonzini 
1672c50d8ae3SPaolo Bonzini /*
1673c50d8ae3SPaolo Bonzini  * This value is the sum of all of the kvm instances's
1674c50d8ae3SPaolo Bonzini  * kvm->arch.n_used_mmu_pages values.  We need a global,
1675c50d8ae3SPaolo Bonzini  * aggregate version in order to make the slab shrinker
1676c50d8ae3SPaolo Bonzini  * faster
1677c50d8ae3SPaolo Bonzini  */
1678d5aaad6fSSean Christopherson static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1679c50d8ae3SPaolo Bonzini {
1680c50d8ae3SPaolo Bonzini 	kvm->arch.n_used_mmu_pages += nr;
1681c50d8ae3SPaolo Bonzini 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1682c50d8ae3SPaolo Bonzini }
1683c50d8ae3SPaolo Bonzini 
168443a063caSYosry Ahmed static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
168543a063caSYosry Ahmed {
168643a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, +1);
168743a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, +1);
168843a063caSYosry Ahmed }
168943a063caSYosry Ahmed 
169043a063caSYosry Ahmed static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
169143a063caSYosry Ahmed {
169243a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, -1);
169343a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, -1);
169443a063caSYosry Ahmed }
169543a063caSYosry Ahmed 
169687654643SDavid Matlack static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1697c50d8ae3SPaolo Bonzini {
169858da926cSSean Christopherson 	kvm_mmu_check_sptes_at_free(sp);
169958da926cSSean Christopherson 
1700c50d8ae3SPaolo Bonzini 	hlist_del(&sp->hash_link);
1701c50d8ae3SPaolo Bonzini 	list_del(&sp->link);
1702c50d8ae3SPaolo Bonzini 	free_page((unsigned long)sp->spt);
17036a97575dSDavid Matlack 	free_page((unsigned long)sp->shadowed_translation);
1704c50d8ae3SPaolo Bonzini 	kmem_cache_free(mmu_page_header_cache, sp);
1705c50d8ae3SPaolo Bonzini }
1706c50d8ae3SPaolo Bonzini 
1707c50d8ae3SPaolo Bonzini static unsigned kvm_page_table_hashfn(gfn_t gfn)
1708c50d8ae3SPaolo Bonzini {
1709c50d8ae3SPaolo Bonzini 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1710c50d8ae3SPaolo Bonzini }
1711c50d8ae3SPaolo Bonzini 
17122ff9039aSDavid Matlack static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
1713c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp, u64 *parent_pte)
1714c50d8ae3SPaolo Bonzini {
1715c50d8ae3SPaolo Bonzini 	if (!parent_pte)
1716c50d8ae3SPaolo Bonzini 		return;
1717c50d8ae3SPaolo Bonzini 
17182ff9039aSDavid Matlack 	pte_list_add(cache, parent_pte, &sp->parent_ptes);
1719c50d8ae3SPaolo Bonzini }
1720c50d8ae3SPaolo Bonzini 
1721069f30c6SMingwei Zhang static void mmu_page_remove_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1722c50d8ae3SPaolo Bonzini 				       u64 *parent_pte)
1723c50d8ae3SPaolo Bonzini {
1724069f30c6SMingwei Zhang 	pte_list_remove(kvm, parent_pte, &sp->parent_ptes);
1725c50d8ae3SPaolo Bonzini }
1726c50d8ae3SPaolo Bonzini 
1727069f30c6SMingwei Zhang static void drop_parent_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
1728c50d8ae3SPaolo Bonzini 			    u64 *parent_pte)
1729c50d8ae3SPaolo Bonzini {
1730069f30c6SMingwei Zhang 	mmu_page_remove_parent_pte(kvm, sp, parent_pte);
1731c50d8ae3SPaolo Bonzini 	mmu_spte_clear_no_track(parent_pte);
1732c50d8ae3SPaolo Bonzini }
1733c50d8ae3SPaolo Bonzini 
1734c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte);
1735c50d8ae3SPaolo Bonzini static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1736c50d8ae3SPaolo Bonzini {
1737c50d8ae3SPaolo Bonzini 	u64 *sptep;
1738c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1739c50d8ae3SPaolo Bonzini 
1740c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1741c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
1742c50d8ae3SPaolo Bonzini 	}
1743c50d8ae3SPaolo Bonzini }
1744c50d8ae3SPaolo Bonzini 
1745c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte)
1746c50d8ae3SPaolo Bonzini {
1747c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1748c50d8ae3SPaolo Bonzini 
174957354682SSean Christopherson 	sp = sptep_to_sp(spte);
175079e48cecSSean Christopherson 	if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1751c50d8ae3SPaolo Bonzini 		return;
1752c50d8ae3SPaolo Bonzini 	if (sp->unsync_children++)
1753c50d8ae3SPaolo Bonzini 		return;
1754c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
1755c50d8ae3SPaolo Bonzini }
1756c50d8ae3SPaolo Bonzini 
1757c50d8ae3SPaolo Bonzini #define KVM_PAGE_ARRAY_NR 16
1758c50d8ae3SPaolo Bonzini 
1759c50d8ae3SPaolo Bonzini struct kvm_mmu_pages {
1760c50d8ae3SPaolo Bonzini 	struct mmu_page_and_offset {
1761c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
1762c50d8ae3SPaolo Bonzini 		unsigned int idx;
1763c50d8ae3SPaolo Bonzini 	} page[KVM_PAGE_ARRAY_NR];
1764c50d8ae3SPaolo Bonzini 	unsigned int nr;
1765c50d8ae3SPaolo Bonzini };
1766c50d8ae3SPaolo Bonzini 
1767c50d8ae3SPaolo Bonzini static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1768c50d8ae3SPaolo Bonzini 			 int idx)
1769c50d8ae3SPaolo Bonzini {
1770c50d8ae3SPaolo Bonzini 	int i;
1771c50d8ae3SPaolo Bonzini 
1772c50d8ae3SPaolo Bonzini 	if (sp->unsync)
1773c50d8ae3SPaolo Bonzini 		for (i=0; i < pvec->nr; i++)
1774c50d8ae3SPaolo Bonzini 			if (pvec->page[i].sp == sp)
1775c50d8ae3SPaolo Bonzini 				return 0;
1776c50d8ae3SPaolo Bonzini 
1777c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].sp = sp;
1778c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].idx = idx;
1779c50d8ae3SPaolo Bonzini 	pvec->nr++;
1780c50d8ae3SPaolo Bonzini 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
1781c50d8ae3SPaolo Bonzini }
1782c50d8ae3SPaolo Bonzini 
1783c50d8ae3SPaolo Bonzini static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1784c50d8ae3SPaolo Bonzini {
1785c50d8ae3SPaolo Bonzini 	--sp->unsync_children;
178620ba462dSSean Christopherson 	WARN_ON_ONCE((int)sp->unsync_children < 0);
1787c50d8ae3SPaolo Bonzini 	__clear_bit(idx, sp->unsync_child_bitmap);
1788c50d8ae3SPaolo Bonzini }
1789c50d8ae3SPaolo Bonzini 
1790c50d8ae3SPaolo Bonzini static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1791c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1792c50d8ae3SPaolo Bonzini {
1793c50d8ae3SPaolo Bonzini 	int i, ret, nr_unsync_leaf = 0;
1794c50d8ae3SPaolo Bonzini 
1795c50d8ae3SPaolo Bonzini 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1796c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
1797c50d8ae3SPaolo Bonzini 		u64 ent = sp->spt[i];
1798c50d8ae3SPaolo Bonzini 
1799c50d8ae3SPaolo Bonzini 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1800c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1801c50d8ae3SPaolo Bonzini 			continue;
1802c50d8ae3SPaolo Bonzini 		}
1803c50d8ae3SPaolo Bonzini 
18045e3edd7eSSean Christopherson 		child = spte_to_child_sp(ent);
1805c50d8ae3SPaolo Bonzini 
1806c50d8ae3SPaolo Bonzini 		if (child->unsync_children) {
1807c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1808c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1809c50d8ae3SPaolo Bonzini 
1810c50d8ae3SPaolo Bonzini 			ret = __mmu_unsync_walk(child, pvec);
1811c50d8ae3SPaolo Bonzini 			if (!ret) {
1812c50d8ae3SPaolo Bonzini 				clear_unsync_child_bit(sp, i);
1813c50d8ae3SPaolo Bonzini 				continue;
1814c50d8ae3SPaolo Bonzini 			} else if (ret > 0) {
1815c50d8ae3SPaolo Bonzini 				nr_unsync_leaf += ret;
1816c50d8ae3SPaolo Bonzini 			} else
1817c50d8ae3SPaolo Bonzini 				return ret;
1818c50d8ae3SPaolo Bonzini 		} else if (child->unsync) {
1819c50d8ae3SPaolo Bonzini 			nr_unsync_leaf++;
1820c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1821c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1822c50d8ae3SPaolo Bonzini 		} else
1823c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1824c50d8ae3SPaolo Bonzini 	}
1825c50d8ae3SPaolo Bonzini 
1826c50d8ae3SPaolo Bonzini 	return nr_unsync_leaf;
1827c50d8ae3SPaolo Bonzini }
1828c50d8ae3SPaolo Bonzini 
1829c50d8ae3SPaolo Bonzini #define INVALID_INDEX (-1)
1830c50d8ae3SPaolo Bonzini 
1831c50d8ae3SPaolo Bonzini static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1832c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1833c50d8ae3SPaolo Bonzini {
1834c50d8ae3SPaolo Bonzini 	pvec->nr = 0;
1835c50d8ae3SPaolo Bonzini 	if (!sp->unsync_children)
1836c50d8ae3SPaolo Bonzini 		return 0;
1837c50d8ae3SPaolo Bonzini 
1838c50d8ae3SPaolo Bonzini 	mmu_pages_add(pvec, sp, INVALID_INDEX);
1839c50d8ae3SPaolo Bonzini 	return __mmu_unsync_walk(sp, pvec);
1840c50d8ae3SPaolo Bonzini }
1841c50d8ae3SPaolo Bonzini 
1842c50d8ae3SPaolo Bonzini static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1843c50d8ae3SPaolo Bonzini {
184420ba462dSSean Christopherson 	WARN_ON_ONCE(!sp->unsync);
1845c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_sync_page(sp);
1846c50d8ae3SPaolo Bonzini 	sp->unsync = 0;
1847c50d8ae3SPaolo Bonzini 	--kvm->stat.mmu_unsync;
1848c50d8ae3SPaolo Bonzini }
1849c50d8ae3SPaolo Bonzini 
1850c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1851c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list);
1852c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1853c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list);
1854c50d8ae3SPaolo Bonzini 
1855767d8d8dSLai Jiangshan static bool sp_has_gptes(struct kvm_mmu_page *sp)
1856767d8d8dSLai Jiangshan {
1857767d8d8dSLai Jiangshan 	if (sp->role.direct)
1858767d8d8dSLai Jiangshan 		return false;
1859767d8d8dSLai Jiangshan 
186084e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
186184e5ffd0SLai Jiangshan 		return false;
186284e5ffd0SLai Jiangshan 
1863767d8d8dSLai Jiangshan 	return true;
1864767d8d8dSLai Jiangshan }
1865767d8d8dSLai Jiangshan 
1866ac101b7cSSean Christopherson #define for_each_valid_sp(_kvm, _sp, _list)				\
1867ac101b7cSSean Christopherson 	hlist_for_each_entry(_sp, _list, hash_link)			\
1868c50d8ae3SPaolo Bonzini 		if (is_obsolete_sp((_kvm), (_sp))) {			\
1869c50d8ae3SPaolo Bonzini 		} else
1870c50d8ae3SPaolo Bonzini 
1871767d8d8dSLai Jiangshan #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn)		\
1872ac101b7cSSean Christopherson 	for_each_valid_sp(_kvm, _sp,					\
1873ac101b7cSSean Christopherson 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
1874767d8d8dSLai Jiangshan 		if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1875c50d8ae3SPaolo Bonzini 
187690e44470SLai Jiangshan static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
187790e44470SLai Jiangshan {
187890e44470SLai Jiangshan 	union kvm_mmu_page_role root_role = vcpu->arch.mmu->root_role;
187990e44470SLai Jiangshan 
188090e44470SLai Jiangshan 	/*
188190e44470SLai Jiangshan 	 * Ignore various flags when verifying that it's safe to sync a shadow
188290e44470SLai Jiangshan 	 * page using the current MMU context.
188390e44470SLai Jiangshan 	 *
188490e44470SLai Jiangshan 	 *  - level: not part of the overall MMU role and will never match as the MMU's
188590e44470SLai Jiangshan 	 *           level tracks the root level
188690e44470SLai Jiangshan 	 *  - access: updated based on the new guest PTE
188790e44470SLai Jiangshan 	 *  - quadrant: not part of the overall MMU role (similar to level)
188890e44470SLai Jiangshan 	 */
188990e44470SLai Jiangshan 	const union kvm_mmu_page_role sync_role_ign = {
189090e44470SLai Jiangshan 		.level = 0xf,
189190e44470SLai Jiangshan 		.access = 0x7,
189290e44470SLai Jiangshan 		.quadrant = 0x3,
189390e44470SLai Jiangshan 		.passthrough = 0x1,
189490e44470SLai Jiangshan 	};
189590e44470SLai Jiangshan 
189690e44470SLai Jiangshan 	/*
189790e44470SLai Jiangshan 	 * Direct pages can never be unsync, and KVM should never attempt to
189890e44470SLai Jiangshan 	 * sync a shadow page for a different MMU context, e.g. if the role
189990e44470SLai Jiangshan 	 * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
190090e44470SLai Jiangshan 	 * reserved bits checks will be wrong, etc...
190190e44470SLai Jiangshan 	 */
1902c3c6c9fcSLai Jiangshan 	if (WARN_ON_ONCE(sp->role.direct || !vcpu->arch.mmu->sync_spte ||
190390e44470SLai Jiangshan 			 (sp->role.word ^ root_role.word) & ~sync_role_ign.word))
190490e44470SLai Jiangshan 		return false;
190590e44470SLai Jiangshan 
190690e44470SLai Jiangshan 	return true;
190790e44470SLai Jiangshan }
190890e44470SLai Jiangshan 
190919ace7d6SLai Jiangshan static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
191019ace7d6SLai Jiangshan {
1911d8fa2031SSean Christopherson 	/* sp->spt[i] has initial value of shadow page table allocation */
1912d8fa2031SSean Christopherson 	if (sp->spt[i] == SHADOW_NONPRESENT_VALUE)
191319ace7d6SLai Jiangshan 		return 0;
191419ace7d6SLai Jiangshan 
191519ace7d6SLai Jiangshan 	return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
191619ace7d6SLai Jiangshan }
191719ace7d6SLai Jiangshan 
191890e44470SLai Jiangshan static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
191990e44470SLai Jiangshan {
1920c3c6c9fcSLai Jiangshan 	int flush = 0;
1921c3c6c9fcSLai Jiangshan 	int i;
1922c3c6c9fcSLai Jiangshan 
192390e44470SLai Jiangshan 	if (!kvm_sync_page_check(vcpu, sp))
192490e44470SLai Jiangshan 		return -1;
192590e44470SLai Jiangshan 
1926c3c6c9fcSLai Jiangshan 	for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
192719ace7d6SLai Jiangshan 		int ret = kvm_sync_spte(vcpu, sp, i);
1928c3c6c9fcSLai Jiangshan 
1929c3c6c9fcSLai Jiangshan 		if (ret < -1)
1930c3c6c9fcSLai Jiangshan 			return -1;
1931c3c6c9fcSLai Jiangshan 		flush |= ret;
1932c3c6c9fcSLai Jiangshan 	}
1933c3c6c9fcSLai Jiangshan 
1934c3c6c9fcSLai Jiangshan 	/*
1935c3c6c9fcSLai Jiangshan 	 * Note, any flush is purely for KVM's correctness, e.g. when dropping
1936c3c6c9fcSLai Jiangshan 	 * an existing SPTE or clearing W/A/D bits to ensure an mmu_notifier
1937c3c6c9fcSLai Jiangshan 	 * unmap or dirty logging event doesn't fail to flush.  The guest is
1938c3c6c9fcSLai Jiangshan 	 * responsible for flushing the TLB to ensure any changes in protection
1939c3c6c9fcSLai Jiangshan 	 * bits are recognized, i.e. until the guest flushes or page faults on
1940c3c6c9fcSLai Jiangshan 	 * a relevant address, KVM is architecturally allowed to let vCPUs use
1941c3c6c9fcSLai Jiangshan 	 * cached translations with the old protection bits.
1942c3c6c9fcSLai Jiangshan 	 */
1943c3c6c9fcSLai Jiangshan 	return flush;
194490e44470SLai Jiangshan }
194590e44470SLai Jiangshan 
19468d5678a7SHou Wenlong static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1947c50d8ae3SPaolo Bonzini 			 struct list_head *invalid_list)
1948c50d8ae3SPaolo Bonzini {
194990e44470SLai Jiangshan 	int ret = __kvm_sync_page(vcpu, sp);
1950c3e5e415SLai Jiangshan 
19518d5678a7SHou Wenlong 	if (ret < 0)
1952c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
19538d5678a7SHou Wenlong 	return ret;
1954c50d8ae3SPaolo Bonzini }
1955c50d8ae3SPaolo Bonzini 
1956c50d8ae3SPaolo Bonzini static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1957c50d8ae3SPaolo Bonzini 					struct list_head *invalid_list,
1958c50d8ae3SPaolo Bonzini 					bool remote_flush)
1959c50d8ae3SPaolo Bonzini {
1960c50d8ae3SPaolo Bonzini 	if (!remote_flush && list_empty(invalid_list))
1961c50d8ae3SPaolo Bonzini 		return false;
1962c50d8ae3SPaolo Bonzini 
1963c50d8ae3SPaolo Bonzini 	if (!list_empty(invalid_list))
1964c50d8ae3SPaolo Bonzini 		kvm_mmu_commit_zap_page(kvm, invalid_list);
1965c50d8ae3SPaolo Bonzini 	else
1966c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
1967c50d8ae3SPaolo Bonzini 	return true;
1968c50d8ae3SPaolo Bonzini }
1969c50d8ae3SPaolo Bonzini 
1970c50d8ae3SPaolo Bonzini static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
1971c50d8ae3SPaolo Bonzini {
1972a955cad8SSean Christopherson 	if (sp->role.invalid)
1973a955cad8SSean Christopherson 		return true;
1974a955cad8SSean Christopherson 
1975fa3e4203SMiaohe Lin 	/* TDP MMU pages do not use the MMU generation. */
1976de0322f5SSean Christopherson 	return !is_tdp_mmu_page(sp) &&
1977c50d8ae3SPaolo Bonzini 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
1978c50d8ae3SPaolo Bonzini }
1979c50d8ae3SPaolo Bonzini 
1980c50d8ae3SPaolo Bonzini struct mmu_page_path {
1981c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
1982c50d8ae3SPaolo Bonzini 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
1983c50d8ae3SPaolo Bonzini };
1984c50d8ae3SPaolo Bonzini 
1985c50d8ae3SPaolo Bonzini #define for_each_sp(pvec, sp, parents, i)			\
1986c50d8ae3SPaolo Bonzini 		for (i = mmu_pages_first(&pvec, &parents);	\
1987c50d8ae3SPaolo Bonzini 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
1988c50d8ae3SPaolo Bonzini 			i = mmu_pages_next(&pvec, &parents, i))
1989c50d8ae3SPaolo Bonzini 
1990c50d8ae3SPaolo Bonzini static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1991c50d8ae3SPaolo Bonzini 			  struct mmu_page_path *parents,
1992c50d8ae3SPaolo Bonzini 			  int i)
1993c50d8ae3SPaolo Bonzini {
1994c50d8ae3SPaolo Bonzini 	int n;
1995c50d8ae3SPaolo Bonzini 
1996c50d8ae3SPaolo Bonzini 	for (n = i+1; n < pvec->nr; n++) {
1997c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp = pvec->page[n].sp;
1998c50d8ae3SPaolo Bonzini 		unsigned idx = pvec->page[n].idx;
1999c50d8ae3SPaolo Bonzini 		int level = sp->role.level;
2000c50d8ae3SPaolo Bonzini 
2001c50d8ae3SPaolo Bonzini 		parents->idx[level-1] = idx;
20023bae0459SSean Christopherson 		if (level == PG_LEVEL_4K)
2003c50d8ae3SPaolo Bonzini 			break;
2004c50d8ae3SPaolo Bonzini 
2005c50d8ae3SPaolo Bonzini 		parents->parent[level-2] = sp;
2006c50d8ae3SPaolo Bonzini 	}
2007c50d8ae3SPaolo Bonzini 
2008c50d8ae3SPaolo Bonzini 	return n;
2009c50d8ae3SPaolo Bonzini }
2010c50d8ae3SPaolo Bonzini 
2011c50d8ae3SPaolo Bonzini static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2012c50d8ae3SPaolo Bonzini 			   struct mmu_page_path *parents)
2013c50d8ae3SPaolo Bonzini {
2014c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2015c50d8ae3SPaolo Bonzini 	int level;
2016c50d8ae3SPaolo Bonzini 
2017c50d8ae3SPaolo Bonzini 	if (pvec->nr == 0)
2018c50d8ae3SPaolo Bonzini 		return 0;
2019c50d8ae3SPaolo Bonzini 
202020ba462dSSean Christopherson 	WARN_ON_ONCE(pvec->page[0].idx != INVALID_INDEX);
2021c50d8ae3SPaolo Bonzini 
2022c50d8ae3SPaolo Bonzini 	sp = pvec->page[0].sp;
2023c50d8ae3SPaolo Bonzini 	level = sp->role.level;
202420ba462dSSean Christopherson 	WARN_ON_ONCE(level == PG_LEVEL_4K);
2025c50d8ae3SPaolo Bonzini 
2026c50d8ae3SPaolo Bonzini 	parents->parent[level-2] = sp;
2027c50d8ae3SPaolo Bonzini 
2028c50d8ae3SPaolo Bonzini 	/* Also set up a sentinel.  Further entries in pvec are all
2029c50d8ae3SPaolo Bonzini 	 * children of sp, so this element is never overwritten.
2030c50d8ae3SPaolo Bonzini 	 */
2031c50d8ae3SPaolo Bonzini 	parents->parent[level-1] = NULL;
2032c50d8ae3SPaolo Bonzini 	return mmu_pages_next(pvec, parents, 0);
2033c50d8ae3SPaolo Bonzini }
2034c50d8ae3SPaolo Bonzini 
2035c50d8ae3SPaolo Bonzini static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2036c50d8ae3SPaolo Bonzini {
2037c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2038c50d8ae3SPaolo Bonzini 	unsigned int level = 0;
2039c50d8ae3SPaolo Bonzini 
2040c50d8ae3SPaolo Bonzini 	do {
2041c50d8ae3SPaolo Bonzini 		unsigned int idx = parents->idx[level];
2042c50d8ae3SPaolo Bonzini 		sp = parents->parent[level];
2043c50d8ae3SPaolo Bonzini 		if (!sp)
2044c50d8ae3SPaolo Bonzini 			return;
2045c50d8ae3SPaolo Bonzini 
204620ba462dSSean Christopherson 		WARN_ON_ONCE(idx == INVALID_INDEX);
2047c50d8ae3SPaolo Bonzini 		clear_unsync_child_bit(sp, idx);
2048c50d8ae3SPaolo Bonzini 		level++;
2049c50d8ae3SPaolo Bonzini 	} while (!sp->unsync_children);
2050c50d8ae3SPaolo Bonzini }
2051c50d8ae3SPaolo Bonzini 
205265855ed8SLai Jiangshan static int mmu_sync_children(struct kvm_vcpu *vcpu,
205365855ed8SLai Jiangshan 			     struct kvm_mmu_page *parent, bool can_yield)
2054c50d8ae3SPaolo Bonzini {
2055c50d8ae3SPaolo Bonzini 	int i;
2056c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2057c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2058c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2059c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2060c50d8ae3SPaolo Bonzini 	bool flush = false;
2061c50d8ae3SPaolo Bonzini 
2062c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2063c50d8ae3SPaolo Bonzini 		bool protected = false;
2064c50d8ae3SPaolo Bonzini 
2065c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i)
2066cf48f9e2SDavid Matlack 			protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2067c50d8ae3SPaolo Bonzini 
2068c50d8ae3SPaolo Bonzini 		if (protected) {
20695591c069SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2070c50d8ae3SPaolo Bonzini 			flush = false;
2071c50d8ae3SPaolo Bonzini 		}
2072c50d8ae3SPaolo Bonzini 
2073c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2074479a1efcSSean Christopherson 			kvm_unlink_unsync_page(vcpu->kvm, sp);
20758d5678a7SHou Wenlong 			flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2076c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2077c50d8ae3SPaolo Bonzini 		}
2078531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2079c3e5e415SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
208065855ed8SLai Jiangshan 			if (!can_yield) {
208165855ed8SLai Jiangshan 				kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
208265855ed8SLai Jiangshan 				return -EINTR;
208365855ed8SLai Jiangshan 			}
208465855ed8SLai Jiangshan 
2085531810caSBen Gardon 			cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2086c50d8ae3SPaolo Bonzini 			flush = false;
2087c50d8ae3SPaolo Bonzini 		}
2088c50d8ae3SPaolo Bonzini 	}
2089c50d8ae3SPaolo Bonzini 
2090c3e5e415SLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
209165855ed8SLai Jiangshan 	return 0;
2092c50d8ae3SPaolo Bonzini }
2093c50d8ae3SPaolo Bonzini 
2094c50d8ae3SPaolo Bonzini static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2095c50d8ae3SPaolo Bonzini {
2096c50d8ae3SPaolo Bonzini 	atomic_set(&sp->write_flooding_count,  0);
2097c50d8ae3SPaolo Bonzini }
2098c50d8ae3SPaolo Bonzini 
2099c50d8ae3SPaolo Bonzini static void clear_sp_write_flooding_count(u64 *spte)
2100c50d8ae3SPaolo Bonzini {
210157354682SSean Christopherson 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
2102c50d8ae3SPaolo Bonzini }
2103c50d8ae3SPaolo Bonzini 
2104cbd858b1SDavid Matlack /*
2105cbd858b1SDavid Matlack  * The vCPU is required when finding indirect shadow pages; the shadow
2106cbd858b1SDavid Matlack  * page may already exist and syncing it needs the vCPU pointer in
2107cbd858b1SDavid Matlack  * order to read guest page tables.  Direct shadow pages are never
2108cbd858b1SDavid Matlack  * unsync, thus @vcpu can be NULL if @role.direct is true.
2109cbd858b1SDavid Matlack  */
21103cc736b3SDavid Matlack static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
21113cc736b3SDavid Matlack 						     struct kvm_vcpu *vcpu,
211294c81364SDavid Matlack 						     gfn_t gfn,
211394c81364SDavid Matlack 						     struct hlist_head *sp_list,
21142e65e842SDavid Matlack 						     union kvm_mmu_page_role role)
2115c50d8ae3SPaolo Bonzini {
2116c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
21178d5678a7SHou Wenlong 	int ret;
2118c50d8ae3SPaolo Bonzini 	int collisions = 0;
2119c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2120c50d8ae3SPaolo Bonzini 
21213cc736b3SDavid Matlack 	for_each_valid_sp(kvm, sp, sp_list) {
2122c50d8ae3SPaolo Bonzini 		if (sp->gfn != gfn) {
2123c50d8ae3SPaolo Bonzini 			collisions++;
2124c50d8ae3SPaolo Bonzini 			continue;
2125c50d8ae3SPaolo Bonzini 		}
2126c50d8ae3SPaolo Bonzini 
2127ddc16abbSSean Christopherson 		if (sp->role.word != role.word) {
2128ddc16abbSSean Christopherson 			/*
2129ddc16abbSSean Christopherson 			 * If the guest is creating an upper-level page, zap
2130ddc16abbSSean Christopherson 			 * unsync pages for the same gfn.  While it's possible
2131ddc16abbSSean Christopherson 			 * the guest is using recursive page tables, in all
2132ddc16abbSSean Christopherson 			 * likelihood the guest has stopped using the unsync
2133ddc16abbSSean Christopherson 			 * page and is installing a completely unrelated page.
2134ddc16abbSSean Christopherson 			 * Unsync pages must not be left as is, because the new
2135ddc16abbSSean Christopherson 			 * upper-level page will be write-protected.
2136ddc16abbSSean Christopherson 			 */
21372e65e842SDavid Matlack 			if (role.level > PG_LEVEL_4K && sp->unsync)
21383cc736b3SDavid Matlack 				kvm_mmu_prepare_zap_page(kvm, sp,
2139ddc16abbSSean Christopherson 							 &invalid_list);
2140c50d8ae3SPaolo Bonzini 			continue;
2141ddc16abbSSean Christopherson 		}
2142c50d8ae3SPaolo Bonzini 
2143bb924ca6SDavid Matlack 		/* unsync and write-flooding only apply to indirect SPs. */
2144bb924ca6SDavid Matlack 		if (sp->role.direct)
214594c81364SDavid Matlack 			goto out;
2146fb58a9c3SSean Christopherson 
2147c50d8ae3SPaolo Bonzini 		if (sp->unsync) {
2148cbd858b1SDavid Matlack 			if (KVM_BUG_ON(!vcpu, kvm))
2149cbd858b1SDavid Matlack 				break;
2150cbd858b1SDavid Matlack 
215107dc4f35SSean Christopherson 			/*
2152479a1efcSSean Christopherson 			 * The page is good, but is stale.  kvm_sync_page does
215307dc4f35SSean Christopherson 			 * get the latest guest state, but (unlike mmu_unsync_children)
215407dc4f35SSean Christopherson 			 * it doesn't write-protect the page or mark it synchronized!
215507dc4f35SSean Christopherson 			 * This way the validity of the mapping is ensured, but the
215607dc4f35SSean Christopherson 			 * overhead of write protection is not incurred until the
215707dc4f35SSean Christopherson 			 * guest invalidates the TLB mapping.  This allows multiple
215807dc4f35SSean Christopherson 			 * SPs for a single gfn to be unsync.
215907dc4f35SSean Christopherson 			 *
216007dc4f35SSean Christopherson 			 * If the sync fails, the page is zapped.  If so, break
216107dc4f35SSean Christopherson 			 * in order to rebuild it.
2162c50d8ae3SPaolo Bonzini 			 */
21638d5678a7SHou Wenlong 			ret = kvm_sync_page(vcpu, sp, &invalid_list);
21648d5678a7SHou Wenlong 			if (ret < 0)
2165c50d8ae3SPaolo Bonzini 				break;
2166c50d8ae3SPaolo Bonzini 
216720ba462dSSean Christopherson 			WARN_ON_ONCE(!list_empty(&invalid_list));
21688d5678a7SHou Wenlong 			if (ret > 0)
21693cc736b3SDavid Matlack 				kvm_flush_remote_tlbs(kvm);
2170c50d8ae3SPaolo Bonzini 		}
2171c50d8ae3SPaolo Bonzini 
2172c50d8ae3SPaolo Bonzini 		__clear_sp_write_flooding_count(sp);
2173fb58a9c3SSean Christopherson 
2174c50d8ae3SPaolo Bonzini 		goto out;
2175c50d8ae3SPaolo Bonzini 	}
2176c50d8ae3SPaolo Bonzini 
217794c81364SDavid Matlack 	sp = NULL;
21783cc736b3SDavid Matlack 	++kvm->stat.mmu_cache_miss;
2179c50d8ae3SPaolo Bonzini 
218094c81364SDavid Matlack out:
21813cc736b3SDavid Matlack 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
218294c81364SDavid Matlack 
21833cc736b3SDavid Matlack 	if (collisions > kvm->stat.max_mmu_page_hash_collisions)
21843cc736b3SDavid Matlack 		kvm->stat.max_mmu_page_hash_collisions = collisions;
218594c81364SDavid Matlack 	return sp;
218694c81364SDavid Matlack }
218794c81364SDavid Matlack 
21882f8b1b53SDavid Matlack /* Caches used when allocating a new shadow page. */
21892f8b1b53SDavid Matlack struct shadow_page_caches {
21902f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *page_header_cache;
21912f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *shadow_page_cache;
21926a97575dSDavid Matlack 	struct kvm_mmu_memory_cache *shadowed_info_cache;
21932f8b1b53SDavid Matlack };
21942f8b1b53SDavid Matlack 
2195336081fbSDavid Matlack static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
21962f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
219794c81364SDavid Matlack 						      gfn_t gfn,
219894c81364SDavid Matlack 						      struct hlist_head *sp_list,
219994c81364SDavid Matlack 						      union kvm_mmu_page_role role)
220094c81364SDavid Matlack {
2201c306aec8SDavid Matlack 	struct kvm_mmu_page *sp;
2202c306aec8SDavid Matlack 
22032f8b1b53SDavid Matlack 	sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
22042f8b1b53SDavid Matlack 	sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
22059ecc1c11SHou Wenlong 	if (!role.direct && role.level <= KVM_MAX_HUGEPAGE_LEVEL)
22066a97575dSDavid Matlack 		sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2207c306aec8SDavid Matlack 
2208c306aec8SDavid Matlack 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2209c306aec8SDavid Matlack 
221055c510e2SSean Christopherson 	INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2211428e9216SSean Christopherson 
2212c306aec8SDavid Matlack 	/*
2213c306aec8SDavid Matlack 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2214c306aec8SDavid Matlack 	 * depends on valid pages being added to the head of the list.  See
2215c306aec8SDavid Matlack 	 * comments in kvm_zap_obsolete_pages().
2216c306aec8SDavid Matlack 	 */
2217336081fbSDavid Matlack 	sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2218336081fbSDavid Matlack 	list_add(&sp->link, &kvm->arch.active_mmu_pages);
221943a063caSYosry Ahmed 	kvm_account_mmu_page(kvm, sp);
2220c50d8ae3SPaolo Bonzini 
2221c50d8ae3SPaolo Bonzini 	sp->gfn = gfn;
2222c50d8ae3SPaolo Bonzini 	sp->role = role;
2223ac101b7cSSean Christopherson 	hlist_add_head(&sp->hash_link, sp_list);
2224be911771SDavid Matlack 	if (sp_has_gptes(sp))
2225336081fbSDavid Matlack 		account_shadowed(kvm, sp);
2226ddc16abbSSean Christopherson 
222794c81364SDavid Matlack 	return sp;
222894c81364SDavid Matlack }
222994c81364SDavid Matlack 
2230cbd858b1SDavid Matlack /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
22313cc736b3SDavid Matlack static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
22323cc736b3SDavid Matlack 						      struct kvm_vcpu *vcpu,
22332f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
223487654643SDavid Matlack 						      gfn_t gfn,
223594c81364SDavid Matlack 						      union kvm_mmu_page_role role)
223694c81364SDavid Matlack {
223794c81364SDavid Matlack 	struct hlist_head *sp_list;
223894c81364SDavid Matlack 	struct kvm_mmu_page *sp;
223994c81364SDavid Matlack 	bool created = false;
224094c81364SDavid Matlack 
22413cc736b3SDavid Matlack 	sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
224294c81364SDavid Matlack 
22433cc736b3SDavid Matlack 	sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
224494c81364SDavid Matlack 	if (!sp) {
224594c81364SDavid Matlack 		created = true;
22463cc736b3SDavid Matlack 		sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
224794c81364SDavid Matlack 	}
224894c81364SDavid Matlack 
224994c81364SDavid Matlack 	trace_kvm_mmu_get_page(sp, created);
2250c50d8ae3SPaolo Bonzini 	return sp;
2251c50d8ae3SPaolo Bonzini }
2252c50d8ae3SPaolo Bonzini 
22532f8b1b53SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
22542f8b1b53SDavid Matlack 						    gfn_t gfn,
22552f8b1b53SDavid Matlack 						    union kvm_mmu_page_role role)
22562f8b1b53SDavid Matlack {
22572f8b1b53SDavid Matlack 	struct shadow_page_caches caches = {
22582f8b1b53SDavid Matlack 		.page_header_cache = &vcpu->arch.mmu_page_header_cache,
22592f8b1b53SDavid Matlack 		.shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
22606a97575dSDavid Matlack 		.shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
22612f8b1b53SDavid Matlack 	};
22622f8b1b53SDavid Matlack 
22633cc736b3SDavid Matlack 	return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
22642f8b1b53SDavid Matlack }
22652f8b1b53SDavid Matlack 
226639944ab9SSean Christopherson static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
226739944ab9SSean Christopherson 						  unsigned int access)
22682e65e842SDavid Matlack {
22692e65e842SDavid Matlack 	struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
22702e65e842SDavid Matlack 	union kvm_mmu_page_role role;
22712e65e842SDavid Matlack 
22722e65e842SDavid Matlack 	role = parent_sp->role;
22732e65e842SDavid Matlack 	role.level--;
22742e65e842SDavid Matlack 	role.access = access;
22752e65e842SDavid Matlack 	role.direct = direct;
22762e65e842SDavid Matlack 	role.passthrough = 0;
22772e65e842SDavid Matlack 
22782e65e842SDavid Matlack 	/*
22792e65e842SDavid Matlack 	 * If the guest has 4-byte PTEs then that means it's using 32-bit,
22802e65e842SDavid Matlack 	 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
22812e65e842SDavid Matlack 	 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
22822e65e842SDavid Matlack 	 * shadow each guest page table with multiple shadow page tables, which
22832e65e842SDavid Matlack 	 * requires extra bookkeeping in the role.
22842e65e842SDavid Matlack 	 *
22852e65e842SDavid Matlack 	 * Specifically, to shadow the guest's page directory (which covers a
22862e65e842SDavid Matlack 	 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
22872e65e842SDavid Matlack 	 * 1GiB of the address space. @role.quadrant encodes which quarter of
22882e65e842SDavid Matlack 	 * the address space each maps.
22892e65e842SDavid Matlack 	 *
22902e65e842SDavid Matlack 	 * To shadow the guest's page tables (which each map a 4MiB region), KVM
22912e65e842SDavid Matlack 	 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
22922e65e842SDavid Matlack 	 * @role.quadrant encodes which half of the region they map.
22932e65e842SDavid Matlack 	 *
229439944ab9SSean Christopherson 	 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
229539944ab9SSean Christopherson 	 * consumes bits 29:21.  To consume bits 31:30, KVM's uses 4 shadow
229639944ab9SSean Christopherson 	 * PDPTEs; those 4 PAE page directories are pre-allocated and their
229739944ab9SSean Christopherson 	 * quadrant is assigned in mmu_alloc_root().   A 4-byte PTE consumes
229839944ab9SSean Christopherson 	 * bits 21:12, while an 8-byte PTE consumes bits 20:12.  To consume
229939944ab9SSean Christopherson 	 * bit 21 in the PTE (the child here), KVM propagates that bit to the
230039944ab9SSean Christopherson 	 * quadrant, i.e. sets quadrant to '0' or '1'.  The parent 8-byte PDE
230139944ab9SSean Christopherson 	 * covers bit 21 (see above), thus the quadrant is calculated from the
230239944ab9SSean Christopherson 	 * _least_ significant bit of the PDE index.
23032e65e842SDavid Matlack 	 */
23042e65e842SDavid Matlack 	if (role.has_4_byte_gpte) {
23052e65e842SDavid Matlack 		WARN_ON_ONCE(role.level != PG_LEVEL_4K);
230679e48cecSSean Christopherson 		role.quadrant = spte_index(sptep) & 1;
23072e65e842SDavid Matlack 	}
23082e65e842SDavid Matlack 
23092e65e842SDavid Matlack 	return role;
23102e65e842SDavid Matlack }
23112e65e842SDavid Matlack 
23122e65e842SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
23132e65e842SDavid Matlack 						 u64 *sptep, gfn_t gfn,
23142e65e842SDavid Matlack 						 bool direct, unsigned int access)
23152e65e842SDavid Matlack {
23162e65e842SDavid Matlack 	union kvm_mmu_page_role role;
23172e65e842SDavid Matlack 
23180cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
23190cd8dc73SPaolo Bonzini 		return ERR_PTR(-EEXIST);
23200cd8dc73SPaolo Bonzini 
23212e65e842SDavid Matlack 	role = kvm_mmu_child_role(sptep, direct, access);
232287654643SDavid Matlack 	return kvm_mmu_get_shadow_page(vcpu, gfn, role);
23232e65e842SDavid Matlack }
23242e65e842SDavid Matlack 
2325c50d8ae3SPaolo Bonzini static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2326c50d8ae3SPaolo Bonzini 					struct kvm_vcpu *vcpu, hpa_t root,
2327c50d8ae3SPaolo Bonzini 					u64 addr)
2328c50d8ae3SPaolo Bonzini {
2329c50d8ae3SPaolo Bonzini 	iterator->addr = addr;
2330c50d8ae3SPaolo Bonzini 	iterator->shadow_addr = root;
2331a972e29cSPaolo Bonzini 	iterator->level = vcpu->arch.mmu->root_role.level;
2332c50d8ae3SPaolo Bonzini 
233312ec33a7SLai Jiangshan 	if (iterator->level >= PT64_ROOT_4LEVEL &&
23344d25502aSPaolo Bonzini 	    vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2335347a0d0dSPaolo Bonzini 	    !vcpu->arch.mmu->root_role.direct)
233612ec33a7SLai Jiangshan 		iterator->level = PT32E_ROOT_LEVEL;
2337c50d8ae3SPaolo Bonzini 
2338c50d8ae3SPaolo Bonzini 	if (iterator->level == PT32E_ROOT_LEVEL) {
2339c50d8ae3SPaolo Bonzini 		/*
2340c50d8ae3SPaolo Bonzini 		 * prev_root is currently only used for 64-bit hosts. So only
2341c50d8ae3SPaolo Bonzini 		 * the active root_hpa is valid here.
2342c50d8ae3SPaolo Bonzini 		 */
2343b9e5603cSPaolo Bonzini 		BUG_ON(root != vcpu->arch.mmu->root.hpa);
2344c50d8ae3SPaolo Bonzini 
2345c50d8ae3SPaolo Bonzini 		iterator->shadow_addr
2346c50d8ae3SPaolo Bonzini 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
23472ca3129eSSean Christopherson 		iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2348c50d8ae3SPaolo Bonzini 		--iterator->level;
2349c50d8ae3SPaolo Bonzini 		if (!iterator->shadow_addr)
2350c50d8ae3SPaolo Bonzini 			iterator->level = 0;
2351c50d8ae3SPaolo Bonzini 	}
2352c50d8ae3SPaolo Bonzini }
2353c50d8ae3SPaolo Bonzini 
2354c50d8ae3SPaolo Bonzini static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2355c50d8ae3SPaolo Bonzini 			     struct kvm_vcpu *vcpu, u64 addr)
2356c50d8ae3SPaolo Bonzini {
2357b9e5603cSPaolo Bonzini 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2358c50d8ae3SPaolo Bonzini 				    addr);
2359c50d8ae3SPaolo Bonzini }
2360c50d8ae3SPaolo Bonzini 
2361c50d8ae3SPaolo Bonzini static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2362c50d8ae3SPaolo Bonzini {
23633bae0459SSean Christopherson 	if (iterator->level < PG_LEVEL_4K)
2364c50d8ae3SPaolo Bonzini 		return false;
2365c50d8ae3SPaolo Bonzini 
23662ca3129eSSean Christopherson 	iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2367c50d8ae3SPaolo Bonzini 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2368c50d8ae3SPaolo Bonzini 	return true;
2369c50d8ae3SPaolo Bonzini }
2370c50d8ae3SPaolo Bonzini 
2371c50d8ae3SPaolo Bonzini static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2372c50d8ae3SPaolo Bonzini 			       u64 spte)
2373c50d8ae3SPaolo Bonzini {
23743e44dce4SLai Jiangshan 	if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2375c50d8ae3SPaolo Bonzini 		iterator->level = 0;
2376c50d8ae3SPaolo Bonzini 		return;
2377c50d8ae3SPaolo Bonzini 	}
2378c50d8ae3SPaolo Bonzini 
23792ca3129eSSean Christopherson 	iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2380c50d8ae3SPaolo Bonzini 	--iterator->level;
2381c50d8ae3SPaolo Bonzini }
2382c50d8ae3SPaolo Bonzini 
2383c50d8ae3SPaolo Bonzini static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2384c50d8ae3SPaolo Bonzini {
2385c50d8ae3SPaolo Bonzini 	__shadow_walk_next(iterator, *iterator->sptep);
2386c50d8ae3SPaolo Bonzini }
2387c50d8ae3SPaolo Bonzini 
23880cd8dc73SPaolo Bonzini static void __link_shadow_page(struct kvm *kvm,
23890cd8dc73SPaolo Bonzini 			       struct kvm_mmu_memory_cache *cache, u64 *sptep,
239003787394SPaolo Bonzini 			       struct kvm_mmu_page *sp, bool flush)
2391c50d8ae3SPaolo Bonzini {
2392c50d8ae3SPaolo Bonzini 	u64 spte;
2393c50d8ae3SPaolo Bonzini 
2394c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2395c50d8ae3SPaolo Bonzini 
23960cd8dc73SPaolo Bonzini 	/*
23970cd8dc73SPaolo Bonzini 	 * If an SPTE is present already, it must be a leaf and therefore
239803787394SPaolo Bonzini 	 * a large one.  Drop it, and flush the TLB if needed, before
239903787394SPaolo Bonzini 	 * installing sp.
24000cd8dc73SPaolo Bonzini 	 */
24010cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep))
240203787394SPaolo Bonzini 		drop_large_spte(kvm, sptep, flush);
24030cd8dc73SPaolo Bonzini 
2404cc4674d0SBen Gardon 	spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2405c50d8ae3SPaolo Bonzini 
2406c50d8ae3SPaolo Bonzini 	mmu_spte_set(sptep, spte);
2407c50d8ae3SPaolo Bonzini 
24082ff9039aSDavid Matlack 	mmu_page_add_parent_pte(cache, sp, sptep);
2409c50d8ae3SPaolo Bonzini 
2410c4a48868SLai Jiangshan 	/*
2411c4a48868SLai Jiangshan 	 * The non-direct sub-pagetable must be updated before linking.  For
2412c4a48868SLai Jiangshan 	 * L1 sp, the pagetable is updated via kvm_sync_page() in
2413c4a48868SLai Jiangshan 	 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2414c4a48868SLai Jiangshan 	 * so sp->unsync can be true or false.  For higher level non-direct
2415c4a48868SLai Jiangshan 	 * sp, the pagetable is updated/synced via mmu_sync_children() in
2416c4a48868SLai Jiangshan 	 * FNAME(fetch)(), so sp->unsync_children can only be false.
2417c4a48868SLai Jiangshan 	 * WARN_ON_ONCE() if anything happens unexpectedly.
2418c4a48868SLai Jiangshan 	 */
2419c4a48868SLai Jiangshan 	if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2420c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
2421c50d8ae3SPaolo Bonzini }
2422c50d8ae3SPaolo Bonzini 
24232ff9039aSDavid Matlack static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
24242ff9039aSDavid Matlack 			     struct kvm_mmu_page *sp)
24252ff9039aSDavid Matlack {
242603787394SPaolo Bonzini 	__link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
24272ff9039aSDavid Matlack }
24282ff9039aSDavid Matlack 
2429c50d8ae3SPaolo Bonzini static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2430c50d8ae3SPaolo Bonzini 				   unsigned direct_access)
2431c50d8ae3SPaolo Bonzini {
2432c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2433c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
2434c50d8ae3SPaolo Bonzini 
2435c50d8ae3SPaolo Bonzini 		/*
2436c50d8ae3SPaolo Bonzini 		 * For the direct sp, if the guest pte's dirty bit
2437c50d8ae3SPaolo Bonzini 		 * changed form clean to dirty, it will corrupt the
2438c50d8ae3SPaolo Bonzini 		 * sp's access: allow writable in the read-only sp,
2439c50d8ae3SPaolo Bonzini 		 * so we should update the spte at this point to get
2440c50d8ae3SPaolo Bonzini 		 * a new sp with the correct access.
2441c50d8ae3SPaolo Bonzini 		 */
24425e3edd7eSSean Christopherson 		child = spte_to_child_sp(*sptep);
2443c50d8ae3SPaolo Bonzini 		if (child->role.access == direct_access)
2444c50d8ae3SPaolo Bonzini 			return;
2445c50d8ae3SPaolo Bonzini 
2446069f30c6SMingwei Zhang 		drop_parent_pte(vcpu->kvm, child, sptep);
24473cdf9374SHou Wenlong 		kvm_flush_remote_tlbs_sptep(vcpu->kvm, sptep);
2448c50d8ae3SPaolo Bonzini 	}
2449c50d8ae3SPaolo Bonzini }
2450c50d8ae3SPaolo Bonzini 
24512de4085cSBen Gardon /* Returns the number of zapped non-leaf child shadow pages. */
24522de4085cSBen Gardon static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
24532de4085cSBen Gardon 			    u64 *spte, struct list_head *invalid_list)
2454c50d8ae3SPaolo Bonzini {
2455c50d8ae3SPaolo Bonzini 	u64 pte;
2456c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *child;
2457c50d8ae3SPaolo Bonzini 
2458c50d8ae3SPaolo Bonzini 	pte = *spte;
2459c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(pte)) {
2460c50d8ae3SPaolo Bonzini 		if (is_last_spte(pte, sp->role.level)) {
2461c50d8ae3SPaolo Bonzini 			drop_spte(kvm, spte);
2462c50d8ae3SPaolo Bonzini 		} else {
24635e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2464069f30c6SMingwei Zhang 			drop_parent_pte(kvm, child, spte);
24652de4085cSBen Gardon 
24662de4085cSBen Gardon 			/*
24672de4085cSBen Gardon 			 * Recursively zap nested TDP SPs, parentless SPs are
24682de4085cSBen Gardon 			 * unlikely to be used again in the near future.  This
24692de4085cSBen Gardon 			 * avoids retaining a large number of stale nested SPs.
24702de4085cSBen Gardon 			 */
24712de4085cSBen Gardon 			if (tdp_enabled && invalid_list &&
24722de4085cSBen Gardon 			    child->role.guest_mode && !child->parent_ptes.val)
24732de4085cSBen Gardon 				return kvm_mmu_prepare_zap_page(kvm, child,
24742de4085cSBen Gardon 								invalid_list);
2475c50d8ae3SPaolo Bonzini 		}
2476949019b9SSean Christopherson 	} else if (is_mmio_spte(kvm, pte)) {
2477c50d8ae3SPaolo Bonzini 		mmu_spte_clear_no_track(spte);
2478ace569e0SSean Christopherson 	}
24792de4085cSBen Gardon 	return 0;
2480c50d8ae3SPaolo Bonzini }
2481c50d8ae3SPaolo Bonzini 
24822de4085cSBen Gardon static int kvm_mmu_page_unlink_children(struct kvm *kvm,
24832de4085cSBen Gardon 					struct kvm_mmu_page *sp,
24842de4085cSBen Gardon 					struct list_head *invalid_list)
2485c50d8ae3SPaolo Bonzini {
24862de4085cSBen Gardon 	int zapped = 0;
2487c50d8ae3SPaolo Bonzini 	unsigned i;
2488c50d8ae3SPaolo Bonzini 
24892ca3129eSSean Christopherson 	for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
24902de4085cSBen Gardon 		zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
24912de4085cSBen Gardon 
24922de4085cSBen Gardon 	return zapped;
2493c50d8ae3SPaolo Bonzini }
2494c50d8ae3SPaolo Bonzini 
2495069f30c6SMingwei Zhang static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2496c50d8ae3SPaolo Bonzini {
2497c50d8ae3SPaolo Bonzini 	u64 *sptep;
2498c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
2499c50d8ae3SPaolo Bonzini 
2500c50d8ae3SPaolo Bonzini 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2501069f30c6SMingwei Zhang 		drop_parent_pte(kvm, sp, sptep);
2502c50d8ae3SPaolo Bonzini }
2503c50d8ae3SPaolo Bonzini 
2504c50d8ae3SPaolo Bonzini static int mmu_zap_unsync_children(struct kvm *kvm,
2505c50d8ae3SPaolo Bonzini 				   struct kvm_mmu_page *parent,
2506c50d8ae3SPaolo Bonzini 				   struct list_head *invalid_list)
2507c50d8ae3SPaolo Bonzini {
2508c50d8ae3SPaolo Bonzini 	int i, zapped = 0;
2509c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2510c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2511c50d8ae3SPaolo Bonzini 
25123bae0459SSean Christopherson 	if (parent->role.level == PG_LEVEL_4K)
2513c50d8ae3SPaolo Bonzini 		return 0;
2514c50d8ae3SPaolo Bonzini 
2515c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2516c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
2517c50d8ae3SPaolo Bonzini 
2518c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2519c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2520c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2521c50d8ae3SPaolo Bonzini 			zapped++;
2522c50d8ae3SPaolo Bonzini 		}
2523c50d8ae3SPaolo Bonzini 	}
2524c50d8ae3SPaolo Bonzini 
2525c50d8ae3SPaolo Bonzini 	return zapped;
2526c50d8ae3SPaolo Bonzini }
2527c50d8ae3SPaolo Bonzini 
2528c50d8ae3SPaolo Bonzini static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2529c50d8ae3SPaolo Bonzini 				       struct kvm_mmu_page *sp,
2530c50d8ae3SPaolo Bonzini 				       struct list_head *invalid_list,
2531c50d8ae3SPaolo Bonzini 				       int *nr_zapped)
2532c50d8ae3SPaolo Bonzini {
2533527d5cd7SSean Christopherson 	bool list_unstable, zapped_root = false;
2534c50d8ae3SPaolo Bonzini 
253547b0c2e4SKazuki Takiguchi 	lockdep_assert_held_write(&kvm->mmu_lock);
2536c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_prepare_zap_page(sp);
2537c50d8ae3SPaolo Bonzini 	++kvm->stat.mmu_shadow_zapped;
2538c50d8ae3SPaolo Bonzini 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
25392de4085cSBen Gardon 	*nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2540069f30c6SMingwei Zhang 	kvm_mmu_unlink_parents(kvm, sp);
2541c50d8ae3SPaolo Bonzini 
2542c50d8ae3SPaolo Bonzini 	/* Zapping children means active_mmu_pages has become unstable. */
2543c50d8ae3SPaolo Bonzini 	list_unstable = *nr_zapped;
2544c50d8ae3SPaolo Bonzini 
2545767d8d8dSLai Jiangshan 	if (!sp->role.invalid && sp_has_gptes(sp))
2546c50d8ae3SPaolo Bonzini 		unaccount_shadowed(kvm, sp);
2547c50d8ae3SPaolo Bonzini 
2548c50d8ae3SPaolo Bonzini 	if (sp->unsync)
2549c50d8ae3SPaolo Bonzini 		kvm_unlink_unsync_page(kvm, sp);
2550c50d8ae3SPaolo Bonzini 	if (!sp->root_count) {
2551c50d8ae3SPaolo Bonzini 		/* Count self */
2552c50d8ae3SPaolo Bonzini 		(*nr_zapped)++;
2553f95eec9bSSean Christopherson 
2554f95eec9bSSean Christopherson 		/*
2555f95eec9bSSean Christopherson 		 * Already invalid pages (previously active roots) are not on
2556f95eec9bSSean Christopherson 		 * the active page list.  See list_del() in the "else" case of
2557f95eec9bSSean Christopherson 		 * !sp->root_count.
2558f95eec9bSSean Christopherson 		 */
2559f95eec9bSSean Christopherson 		if (sp->role.invalid)
2560f95eec9bSSean Christopherson 			list_add(&sp->link, invalid_list);
2561f95eec9bSSean Christopherson 		else
2562c50d8ae3SPaolo Bonzini 			list_move(&sp->link, invalid_list);
256343a063caSYosry Ahmed 		kvm_unaccount_mmu_page(kvm, sp);
2564c50d8ae3SPaolo Bonzini 	} else {
2565f95eec9bSSean Christopherson 		/*
2566f95eec9bSSean Christopherson 		 * Remove the active root from the active page list, the root
2567f95eec9bSSean Christopherson 		 * will be explicitly freed when the root_count hits zero.
2568f95eec9bSSean Christopherson 		 */
2569f95eec9bSSean Christopherson 		list_del(&sp->link);
2570c50d8ae3SPaolo Bonzini 
2571c50d8ae3SPaolo Bonzini 		/*
2572c50d8ae3SPaolo Bonzini 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2573c50d8ae3SPaolo Bonzini 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2574c50d8ae3SPaolo Bonzini 		 * treats invalid shadow pages as being obsolete.
2575c50d8ae3SPaolo Bonzini 		 */
2576527d5cd7SSean Christopherson 		zapped_root = !is_obsolete_sp(kvm, sp);
2577c50d8ae3SPaolo Bonzini 	}
2578c50d8ae3SPaolo Bonzini 
257955c510e2SSean Christopherson 	if (sp->nx_huge_page_disallowed)
258055c510e2SSean Christopherson 		unaccount_nx_huge_page(kvm, sp);
2581c50d8ae3SPaolo Bonzini 
2582c50d8ae3SPaolo Bonzini 	sp->role.invalid = 1;
2583527d5cd7SSean Christopherson 
2584527d5cd7SSean Christopherson 	/*
2585527d5cd7SSean Christopherson 	 * Make the request to free obsolete roots after marking the root
2586527d5cd7SSean Christopherson 	 * invalid, otherwise other vCPUs may not see it as invalid.
2587527d5cd7SSean Christopherson 	 */
2588527d5cd7SSean Christopherson 	if (zapped_root)
2589527d5cd7SSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2590c50d8ae3SPaolo Bonzini 	return list_unstable;
2591c50d8ae3SPaolo Bonzini }
2592c50d8ae3SPaolo Bonzini 
2593c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2594c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list)
2595c50d8ae3SPaolo Bonzini {
2596c50d8ae3SPaolo Bonzini 	int nr_zapped;
2597c50d8ae3SPaolo Bonzini 
2598c50d8ae3SPaolo Bonzini 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2599c50d8ae3SPaolo Bonzini 	return nr_zapped;
2600c50d8ae3SPaolo Bonzini }
2601c50d8ae3SPaolo Bonzini 
2602c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2603c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list)
2604c50d8ae3SPaolo Bonzini {
2605c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *nsp;
2606c50d8ae3SPaolo Bonzini 
2607c50d8ae3SPaolo Bonzini 	if (list_empty(invalid_list))
2608c50d8ae3SPaolo Bonzini 		return;
2609c50d8ae3SPaolo Bonzini 
2610c50d8ae3SPaolo Bonzini 	/*
2611c50d8ae3SPaolo Bonzini 	 * We need to make sure everyone sees our modifications to
2612c50d8ae3SPaolo Bonzini 	 * the page tables and see changes to vcpu->mode here. The barrier
2613c50d8ae3SPaolo Bonzini 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2614c50d8ae3SPaolo Bonzini 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2615c50d8ae3SPaolo Bonzini 	 *
2616c50d8ae3SPaolo Bonzini 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2617c50d8ae3SPaolo Bonzini 	 * guest mode and/or lockless shadow page table walks.
2618c50d8ae3SPaolo Bonzini 	 */
2619c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs(kvm);
2620c50d8ae3SPaolo Bonzini 
2621c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
262220ba462dSSean Christopherson 		WARN_ON_ONCE(!sp->role.invalid || sp->root_count);
262387654643SDavid Matlack 		kvm_mmu_free_shadow_page(sp);
2624c50d8ae3SPaolo Bonzini 	}
2625c50d8ae3SPaolo Bonzini }
2626c50d8ae3SPaolo Bonzini 
26276b82ef2cSSean Christopherson static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
26286b82ef2cSSean Christopherson 						  unsigned long nr_to_zap)
2629c50d8ae3SPaolo Bonzini {
26306b82ef2cSSean Christopherson 	unsigned long total_zapped = 0;
26316b82ef2cSSean Christopherson 	struct kvm_mmu_page *sp, *tmp;
2632ba7888ddSSean Christopherson 	LIST_HEAD(invalid_list);
26336b82ef2cSSean Christopherson 	bool unstable;
26346b82ef2cSSean Christopherson 	int nr_zapped;
2635c50d8ae3SPaolo Bonzini 
2636c50d8ae3SPaolo Bonzini 	if (list_empty(&kvm->arch.active_mmu_pages))
2637ba7888ddSSean Christopherson 		return 0;
2638c50d8ae3SPaolo Bonzini 
26396b82ef2cSSean Christopherson restart:
26408fc51726SSean Christopherson 	list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
26416b82ef2cSSean Christopherson 		/*
26426b82ef2cSSean Christopherson 		 * Don't zap active root pages, the page itself can't be freed
26436b82ef2cSSean Christopherson 		 * and zapping it will just force vCPUs to realloc and reload.
26446b82ef2cSSean Christopherson 		 */
26456b82ef2cSSean Christopherson 		if (sp->root_count)
26466b82ef2cSSean Christopherson 			continue;
26476b82ef2cSSean Christopherson 
26486b82ef2cSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
26496b82ef2cSSean Christopherson 						      &nr_zapped);
26506b82ef2cSSean Christopherson 		total_zapped += nr_zapped;
26516b82ef2cSSean Christopherson 		if (total_zapped >= nr_to_zap)
2652ba7888ddSSean Christopherson 			break;
2653ba7888ddSSean Christopherson 
26546b82ef2cSSean Christopherson 		if (unstable)
26556b82ef2cSSean Christopherson 			goto restart;
2656ba7888ddSSean Christopherson 	}
26576b82ef2cSSean Christopherson 
26586b82ef2cSSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
26596b82ef2cSSean Christopherson 
26606b82ef2cSSean Christopherson 	kvm->stat.mmu_recycled += total_zapped;
26616b82ef2cSSean Christopherson 	return total_zapped;
26626b82ef2cSSean Christopherson }
26636b82ef2cSSean Christopherson 
2664afe8d7e6SSean Christopherson static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2665afe8d7e6SSean Christopherson {
2666afe8d7e6SSean Christopherson 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2667afe8d7e6SSean Christopherson 		return kvm->arch.n_max_mmu_pages -
2668afe8d7e6SSean Christopherson 			kvm->arch.n_used_mmu_pages;
2669afe8d7e6SSean Christopherson 
2670afe8d7e6SSean Christopherson 	return 0;
2671c50d8ae3SPaolo Bonzini }
2672c50d8ae3SPaolo Bonzini 
2673ba7888ddSSean Christopherson static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2674ba7888ddSSean Christopherson {
26756b82ef2cSSean Christopherson 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2676ba7888ddSSean Christopherson 
26776b82ef2cSSean Christopherson 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2678ba7888ddSSean Christopherson 		return 0;
2679ba7888ddSSean Christopherson 
26806b82ef2cSSean Christopherson 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2681ba7888ddSSean Christopherson 
26826e6ec584SSean Christopherson 	/*
26836e6ec584SSean Christopherson 	 * Note, this check is intentionally soft, it only guarantees that one
26846e6ec584SSean Christopherson 	 * page is available, while the caller may end up allocating as many as
26856e6ec584SSean Christopherson 	 * four pages, e.g. for PAE roots or for 5-level paging.  Temporarily
26866e6ec584SSean Christopherson 	 * exceeding the (arbitrary by default) limit will not harm the host,
2687c4342633SIngo Molnar 	 * being too aggressive may unnecessarily kill the guest, and getting an
26886e6ec584SSean Christopherson 	 * exact count is far more trouble than it's worth, especially in the
26896e6ec584SSean Christopherson 	 * page fault paths.
26906e6ec584SSean Christopherson 	 */
2691ba7888ddSSean Christopherson 	if (!kvm_mmu_available_pages(vcpu->kvm))
2692ba7888ddSSean Christopherson 		return -ENOSPC;
2693ba7888ddSSean Christopherson 	return 0;
2694ba7888ddSSean Christopherson }
2695ba7888ddSSean Christopherson 
2696c50d8ae3SPaolo Bonzini /*
2697c50d8ae3SPaolo Bonzini  * Changing the number of mmu pages allocated to the vm
2698c50d8ae3SPaolo Bonzini  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2699c50d8ae3SPaolo Bonzini  */
2700c50d8ae3SPaolo Bonzini void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2701c50d8ae3SPaolo Bonzini {
2702531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2703c50d8ae3SPaolo Bonzini 
2704c50d8ae3SPaolo Bonzini 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
27056b82ef2cSSean Christopherson 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
27066b82ef2cSSean Christopherson 						  goal_nr_mmu_pages);
2707c50d8ae3SPaolo Bonzini 
2708c50d8ae3SPaolo Bonzini 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2709c50d8ae3SPaolo Bonzini 	}
2710c50d8ae3SPaolo Bonzini 
2711c50d8ae3SPaolo Bonzini 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2712c50d8ae3SPaolo Bonzini 
2713531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2714c50d8ae3SPaolo Bonzini }
2715c50d8ae3SPaolo Bonzini 
2716c50d8ae3SPaolo Bonzini int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2717c50d8ae3SPaolo Bonzini {
2718c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2719c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2720c50d8ae3SPaolo Bonzini 	int r;
2721c50d8ae3SPaolo Bonzini 
2722c50d8ae3SPaolo Bonzini 	r = 0;
2723531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2724767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2725c50d8ae3SPaolo Bonzini 		r = 1;
2726c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2727c50d8ae3SPaolo Bonzini 	}
2728c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2729531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2730c50d8ae3SPaolo Bonzini 
2731c50d8ae3SPaolo Bonzini 	return r;
2732c50d8ae3SPaolo Bonzini }
273396ad91aeSSean Christopherson 
273496ad91aeSSean Christopherson static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
273596ad91aeSSean Christopherson {
273696ad91aeSSean Christopherson 	gpa_t gpa;
273796ad91aeSSean Christopherson 	int r;
273896ad91aeSSean Christopherson 
2739347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
274096ad91aeSSean Christopherson 		return 0;
274196ad91aeSSean Christopherson 
274296ad91aeSSean Christopherson 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
274396ad91aeSSean Christopherson 
274496ad91aeSSean Christopherson 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
274596ad91aeSSean Christopherson 
274696ad91aeSSean Christopherson 	return r;
274796ad91aeSSean Christopherson }
2748c50d8ae3SPaolo Bonzini 
27494d78d0b3SBen Gardon static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2750c50d8ae3SPaolo Bonzini {
2751c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_unsync_page(sp);
27524d78d0b3SBen Gardon 	++kvm->stat.mmu_unsync;
2753c50d8ae3SPaolo Bonzini 	sp->unsync = 1;
2754c50d8ae3SPaolo Bonzini 
2755c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
2756c50d8ae3SPaolo Bonzini }
2757c50d8ae3SPaolo Bonzini 
27580337f585SSean Christopherson /*
27590337f585SSean Christopherson  * Attempt to unsync any shadow pages that can be reached by the specified gfn,
27600337f585SSean Christopherson  * KVM is creating a writable mapping for said gfn.  Returns 0 if all pages
27610337f585SSean Christopherson  * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
27620337f585SSean Christopherson  * be write-protected.
27630337f585SSean Christopherson  */
27648283e36aSBen Gardon int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
27652839180cSPaolo Bonzini 			    gfn_t gfn, bool can_unsync, bool prefetch)
2766c50d8ae3SPaolo Bonzini {
2767c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2768ce25681dSSean Christopherson 	bool locked = false;
2769c50d8ae3SPaolo Bonzini 
27700337f585SSean Christopherson 	/*
27710337f585SSean Christopherson 	 * Force write-protection if the page is being tracked.  Note, the page
27720337f585SSean Christopherson 	 * track machinery is used to write-protect upper-level shadow pages,
27730337f585SSean Christopherson 	 * i.e. this guards the role.level == 4K assertion below!
27740337f585SSean Christopherson 	 */
27757b574863SSean Christopherson 	if (kvm_gfn_is_write_tracked(kvm, slot, gfn))
27760337f585SSean Christopherson 		return -EPERM;
2777c50d8ae3SPaolo Bonzini 
27780337f585SSean Christopherson 	/*
27790337f585SSean Christopherson 	 * The page is not write-tracked, mark existing shadow pages unsync
27800337f585SSean Christopherson 	 * unless KVM is synchronizing an unsync SP (can_unsync = false).  In
27810337f585SSean Christopherson 	 * that case, KVM must complete emulation of the guest TLB flush before
27820337f585SSean Christopherson 	 * allowing shadow pages to become unsync (writable by the guest).
27830337f585SSean Christopherson 	 */
2784767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2785c50d8ae3SPaolo Bonzini 		if (!can_unsync)
27860337f585SSean Christopherson 			return -EPERM;
2787c50d8ae3SPaolo Bonzini 
2788c50d8ae3SPaolo Bonzini 		if (sp->unsync)
2789c50d8ae3SPaolo Bonzini 			continue;
2790c50d8ae3SPaolo Bonzini 
27912839180cSPaolo Bonzini 		if (prefetch)
2792f1c4a88cSLai Jiangshan 			return -EEXIST;
2793f1c4a88cSLai Jiangshan 
2794ce25681dSSean Christopherson 		/*
2795ce25681dSSean Christopherson 		 * TDP MMU page faults require an additional spinlock as they
2796ce25681dSSean Christopherson 		 * run with mmu_lock held for read, not write, and the unsync
2797ce25681dSSean Christopherson 		 * logic is not thread safe.  Take the spinklock regardless of
2798ce25681dSSean Christopherson 		 * the MMU type to avoid extra conditionals/parameters, there's
2799ce25681dSSean Christopherson 		 * no meaningful penalty if mmu_lock is held for write.
2800ce25681dSSean Christopherson 		 */
2801ce25681dSSean Christopherson 		if (!locked) {
2802ce25681dSSean Christopherson 			locked = true;
28034d78d0b3SBen Gardon 			spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2804ce25681dSSean Christopherson 
2805ce25681dSSean Christopherson 			/*
2806ce25681dSSean Christopherson 			 * Recheck after taking the spinlock, a different vCPU
2807ce25681dSSean Christopherson 			 * may have since marked the page unsync.  A false
2808e59f75deSPaolo Bonzini 			 * negative on the unprotected check above is not
2809ce25681dSSean Christopherson 			 * possible as clearing sp->unsync _must_ hold mmu_lock
2810e59f75deSPaolo Bonzini 			 * for write, i.e. unsync cannot transition from 1->0
2811ce25681dSSean Christopherson 			 * while this CPU holds mmu_lock for read (or write).
2812ce25681dSSean Christopherson 			 */
2813ce25681dSSean Christopherson 			if (READ_ONCE(sp->unsync))
2814ce25681dSSean Christopherson 				continue;
2815ce25681dSSean Christopherson 		}
2816ce25681dSSean Christopherson 
281720ba462dSSean Christopherson 		WARN_ON_ONCE(sp->role.level != PG_LEVEL_4K);
28184d78d0b3SBen Gardon 		kvm_unsync_page(kvm, sp);
2819c50d8ae3SPaolo Bonzini 	}
2820ce25681dSSean Christopherson 	if (locked)
28214d78d0b3SBen Gardon 		spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2822c50d8ae3SPaolo Bonzini 
2823c50d8ae3SPaolo Bonzini 	/*
2824c50d8ae3SPaolo Bonzini 	 * We need to ensure that the marking of unsync pages is visible
2825c50d8ae3SPaolo Bonzini 	 * before the SPTE is updated to allow writes because
2826c50d8ae3SPaolo Bonzini 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2827c50d8ae3SPaolo Bonzini 	 * the MMU lock and so can race with this. If the SPTE was updated
2828c50d8ae3SPaolo Bonzini 	 * before the page had been marked as unsync-ed, something like the
2829c50d8ae3SPaolo Bonzini 	 * following could happen:
2830c50d8ae3SPaolo Bonzini 	 *
2831c50d8ae3SPaolo Bonzini 	 * CPU 1                    CPU 2
2832c50d8ae3SPaolo Bonzini 	 * ---------------------------------------------------------------------
2833c50d8ae3SPaolo Bonzini 	 * 1.2 Host updates SPTE
2834c50d8ae3SPaolo Bonzini 	 *     to be writable
2835c50d8ae3SPaolo Bonzini 	 *                      2.1 Guest writes a GPTE for GVA X.
2836c50d8ae3SPaolo Bonzini 	 *                          (GPTE being in the guest page table shadowed
2837c50d8ae3SPaolo Bonzini 	 *                           by the SP from CPU 1.)
2838c50d8ae3SPaolo Bonzini 	 *                          This reads SPTE during the page table walk.
2839c50d8ae3SPaolo Bonzini 	 *                          Since SPTE.W is read as 1, there is no
2840c50d8ae3SPaolo Bonzini 	 *                          fault.
2841c50d8ae3SPaolo Bonzini 	 *
2842c50d8ae3SPaolo Bonzini 	 *                      2.2 Guest issues TLB flush.
2843c50d8ae3SPaolo Bonzini 	 *                          That causes a VM Exit.
2844c50d8ae3SPaolo Bonzini 	 *
28450337f585SSean Christopherson 	 *                      2.3 Walking of unsync pages sees sp->unsync is
28460337f585SSean Christopherson 	 *                          false and skips the page.
2847c50d8ae3SPaolo Bonzini 	 *
2848c50d8ae3SPaolo Bonzini 	 *                      2.4 Guest accesses GVA X.
2849c50d8ae3SPaolo Bonzini 	 *                          Since the mapping in the SP was not updated,
2850c50d8ae3SPaolo Bonzini 	 *                          so the old mapping for GVA X incorrectly
2851c50d8ae3SPaolo Bonzini 	 *                          gets used.
2852c50d8ae3SPaolo Bonzini 	 * 1.1 Host marks SP
2853c50d8ae3SPaolo Bonzini 	 *     as unsync
2854c50d8ae3SPaolo Bonzini 	 *     (sp->unsync = true)
2855c50d8ae3SPaolo Bonzini 	 *
2856c50d8ae3SPaolo Bonzini 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2857264d3dc1SLai Jiangshan 	 * the situation in 2.4 does not arise.  It pairs with the read barrier
2858264d3dc1SLai Jiangshan 	 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2859c50d8ae3SPaolo Bonzini 	 */
2860c50d8ae3SPaolo Bonzini 	smp_wmb();
2861c50d8ae3SPaolo Bonzini 
28620337f585SSean Christopherson 	return 0;
2863c50d8ae3SPaolo Bonzini }
2864c50d8ae3SPaolo Bonzini 
28658a9f566aSDavid Matlack static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
28668a9f566aSDavid Matlack 			u64 *sptep, unsigned int pte_access, gfn_t gfn,
2867a12f4381SPaolo Bonzini 			kvm_pfn_t pfn, struct kvm_page_fault *fault)
2868799a4190SBen Gardon {
2869d786c778SPaolo Bonzini 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2870eb5cd7ffSPaolo Bonzini 	int level = sp->role.level;
2871c50d8ae3SPaolo Bonzini 	int was_rmapped = 0;
2872c4371c2aSSean Christopherson 	int ret = RET_PF_FIXED;
2873c50d8ae3SPaolo Bonzini 	bool flush = false;
2874ad67e480SPaolo Bonzini 	bool wrprot;
2875d786c778SPaolo Bonzini 	u64 spte;
2876c50d8ae3SPaolo Bonzini 
2877a12f4381SPaolo Bonzini 	/* Prefetching always gets a writable pfn.  */
2878a12f4381SPaolo Bonzini 	bool host_writable = !fault || fault->map_writable;
28792839180cSPaolo Bonzini 	bool prefetch = !fault || fault->prefetch;
2880a12f4381SPaolo Bonzini 	bool write_fault = fault && fault->write;
2881c50d8ae3SPaolo Bonzini 
2882a54aa15cSSean Christopherson 	if (unlikely(is_noslot_pfn(pfn))) {
28831075d41eSSean Christopherson 		vcpu->stat.pf_mmio_spte_created++;
2884a54aa15cSSean Christopherson 		mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2885a54aa15cSSean Christopherson 		return RET_PF_EMULATE;
2886a54aa15cSSean Christopherson 	}
2887a54aa15cSSean Christopherson 
2888c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep)) {
2889c50d8ae3SPaolo Bonzini 		/*
2890c50d8ae3SPaolo Bonzini 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2891c50d8ae3SPaolo Bonzini 		 * the parent of the now unreachable PTE.
2892c50d8ae3SPaolo Bonzini 		 */
28933bae0459SSean Christopherson 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2894c50d8ae3SPaolo Bonzini 			struct kvm_mmu_page *child;
2895c50d8ae3SPaolo Bonzini 			u64 pte = *sptep;
2896c50d8ae3SPaolo Bonzini 
28975e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2898069f30c6SMingwei Zhang 			drop_parent_pte(vcpu->kvm, child, sptep);
2899c50d8ae3SPaolo Bonzini 			flush = true;
2900c50d8ae3SPaolo Bonzini 		} else if (pfn != spte_to_pfn(*sptep)) {
2901c50d8ae3SPaolo Bonzini 			drop_spte(vcpu->kvm, sptep);
2902c50d8ae3SPaolo Bonzini 			flush = true;
2903c50d8ae3SPaolo Bonzini 		} else
2904c50d8ae3SPaolo Bonzini 			was_rmapped = 1;
2905c50d8ae3SPaolo Bonzini 	}
2906c50d8ae3SPaolo Bonzini 
29072839180cSPaolo Bonzini 	wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
29087158bee4SPaolo Bonzini 			   true, host_writable, &spte);
2909d786c778SPaolo Bonzini 
2910d786c778SPaolo Bonzini 	if (*sptep == spte) {
2911d786c778SPaolo Bonzini 		ret = RET_PF_SPURIOUS;
2912d786c778SPaolo Bonzini 	} else {
2913d786c778SPaolo Bonzini 		flush |= mmu_spte_update(sptep, spte);
29145959ff4aSMaxim Levitsky 		trace_kvm_mmu_set_spte(level, gfn, sptep);
2915c50d8ae3SPaolo Bonzini 	}
2916c50d8ae3SPaolo Bonzini 
2917ad67e480SPaolo Bonzini 	if (wrprot) {
2918c50d8ae3SPaolo Bonzini 		if (write_fault)
2919c50d8ae3SPaolo Bonzini 			ret = RET_PF_EMULATE;
2920c50d8ae3SPaolo Bonzini 	}
2921c50d8ae3SPaolo Bonzini 
2922d786c778SPaolo Bonzini 	if (flush)
29234ad980aeSHou Wenlong 		kvm_flush_remote_tlbs_gfn(vcpu->kvm, gfn, level);
2924c50d8ae3SPaolo Bonzini 
2925c50d8ae3SPaolo Bonzini 	if (!was_rmapped) {
2926d786c778SPaolo Bonzini 		WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
29276a97575dSDavid Matlack 		rmap_add(vcpu, slot, sptep, gfn, pte_access);
29286a97575dSDavid Matlack 	} else {
29296a97575dSDavid Matlack 		/* Already rmapped but the pte_access bits may have changed. */
293079e48cecSSean Christopherson 		kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
2931c50d8ae3SPaolo Bonzini 	}
2932c50d8ae3SPaolo Bonzini 
2933c50d8ae3SPaolo Bonzini 	return ret;
2934c50d8ae3SPaolo Bonzini }
2935c50d8ae3SPaolo Bonzini 
2936c50d8ae3SPaolo Bonzini static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2937c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp,
2938c50d8ae3SPaolo Bonzini 				    u64 *start, u64 *end)
2939c50d8ae3SPaolo Bonzini {
2940c50d8ae3SPaolo Bonzini 	struct page *pages[PTE_PREFETCH_NUM];
2941c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
29420a2b64c5SBen Gardon 	unsigned int access = sp->role.access;
2943c50d8ae3SPaolo Bonzini 	int i, ret;
2944c50d8ae3SPaolo Bonzini 	gfn_t gfn;
2945c50d8ae3SPaolo Bonzini 
294679e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
2947c50d8ae3SPaolo Bonzini 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2948c50d8ae3SPaolo Bonzini 	if (!slot)
2949c50d8ae3SPaolo Bonzini 		return -1;
2950c50d8ae3SPaolo Bonzini 
2951c50d8ae3SPaolo Bonzini 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2952c50d8ae3SPaolo Bonzini 	if (ret <= 0)
2953c50d8ae3SPaolo Bonzini 		return -1;
2954c50d8ae3SPaolo Bonzini 
2955c50d8ae3SPaolo Bonzini 	for (i = 0; i < ret; i++, gfn++, start++) {
29568a9f566aSDavid Matlack 		mmu_set_spte(vcpu, slot, start, access, gfn,
2957a12f4381SPaolo Bonzini 			     page_to_pfn(pages[i]), NULL);
2958c50d8ae3SPaolo Bonzini 		put_page(pages[i]);
2959c50d8ae3SPaolo Bonzini 	}
2960c50d8ae3SPaolo Bonzini 
2961c50d8ae3SPaolo Bonzini 	return 0;
2962c50d8ae3SPaolo Bonzini }
2963c50d8ae3SPaolo Bonzini 
2964c50d8ae3SPaolo Bonzini static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2965c50d8ae3SPaolo Bonzini 				  struct kvm_mmu_page *sp, u64 *sptep)
2966c50d8ae3SPaolo Bonzini {
2967c50d8ae3SPaolo Bonzini 	u64 *spte, *start = NULL;
2968c50d8ae3SPaolo Bonzini 	int i;
2969c50d8ae3SPaolo Bonzini 
297020ba462dSSean Christopherson 	WARN_ON_ONCE(!sp->role.direct);
2971c50d8ae3SPaolo Bonzini 
297279e48cecSSean Christopherson 	i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
2973c50d8ae3SPaolo Bonzini 	spte = sp->spt + i;
2974c50d8ae3SPaolo Bonzini 
2975c50d8ae3SPaolo Bonzini 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
2976c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*spte) || spte == sptep) {
2977c50d8ae3SPaolo Bonzini 			if (!start)
2978c50d8ae3SPaolo Bonzini 				continue;
2979c50d8ae3SPaolo Bonzini 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2980c6cecc4bSSean Christopherson 				return;
2981c50d8ae3SPaolo Bonzini 			start = NULL;
2982c50d8ae3SPaolo Bonzini 		} else if (!start)
2983c50d8ae3SPaolo Bonzini 			start = spte;
2984c50d8ae3SPaolo Bonzini 	}
2985c6cecc4bSSean Christopherson 	if (start)
2986c6cecc4bSSean Christopherson 		direct_pte_prefetch_many(vcpu, sp, start, spte);
2987c50d8ae3SPaolo Bonzini }
2988c50d8ae3SPaolo Bonzini 
2989c50d8ae3SPaolo Bonzini static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2990c50d8ae3SPaolo Bonzini {
2991c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2992c50d8ae3SPaolo Bonzini 
299357354682SSean Christopherson 	sp = sptep_to_sp(sptep);
2994c50d8ae3SPaolo Bonzini 
2995c50d8ae3SPaolo Bonzini 	/*
2996c50d8ae3SPaolo Bonzini 	 * Without accessed bits, there's no way to distinguish between
2997c50d8ae3SPaolo Bonzini 	 * actually accessed translations and prefetched, so disable pte
2998c50d8ae3SPaolo Bonzini 	 * prefetch if accessed bits aren't available.
2999c50d8ae3SPaolo Bonzini 	 */
3000c50d8ae3SPaolo Bonzini 	if (sp_ad_disabled(sp))
3001c50d8ae3SPaolo Bonzini 		return;
3002c50d8ae3SPaolo Bonzini 
30033bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
3004c50d8ae3SPaolo Bonzini 		return;
3005c50d8ae3SPaolo Bonzini 
30064a42d848SDavid Stevens 	/*
30074a42d848SDavid Stevens 	 * If addresses are being invalidated, skip prefetching to avoid
30084a42d848SDavid Stevens 	 * accidentally prefetching those addresses.
30094a42d848SDavid Stevens 	 */
301020ec3ebdSChao Peng 	if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
30114a42d848SDavid Stevens 		return;
30124a42d848SDavid Stevens 
3013c50d8ae3SPaolo Bonzini 	__direct_pte_prefetch(vcpu, sp, sptep);
3014c50d8ae3SPaolo Bonzini }
3015c50d8ae3SPaolo Bonzini 
301665e3b446SSean Christopherson /*
301765e3b446SSean Christopherson  * Lookup the mapping level for @gfn in the current mm.
301865e3b446SSean Christopherson  *
301965e3b446SSean Christopherson  * WARNING!  Use of host_pfn_mapping_level() requires the caller and the end
302065e3b446SSean Christopherson  * consumer to be tied into KVM's handlers for MMU notifier events!
302165e3b446SSean Christopherson  *
302265e3b446SSean Christopherson  * There are several ways to safely use this helper:
302365e3b446SSean Christopherson  *
30248569992dSChao Peng  * - Check mmu_invalidate_retry_gfn() after grabbing the mapping level, before
302565e3b446SSean Christopherson  *   consuming it.  In this case, mmu_lock doesn't need to be held during the
302665e3b446SSean Christopherson  *   lookup, but it does need to be held while checking the MMU notifier.
302765e3b446SSean Christopherson  *
302865e3b446SSean Christopherson  * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
302965e3b446SSean Christopherson  *   event for the hva.  This can be done by explicit checking the MMU notifier
303065e3b446SSean Christopherson  *   or by ensuring that KVM already has a valid mapping that covers the hva.
303165e3b446SSean Christopherson  *
303265e3b446SSean Christopherson  * - Do not use the result to install new mappings, e.g. use the host mapping
303365e3b446SSean Christopherson  *   level only to decide whether or not to zap an entry.  In this case, it's
303465e3b446SSean Christopherson  *   not required to hold mmu_lock (though it's highly likely the caller will
303565e3b446SSean Christopherson  *   want to hold mmu_lock anyways, e.g. to modify SPTEs).
303665e3b446SSean Christopherson  *
303765e3b446SSean Christopherson  * Note!  The lookup can still race with modifications to host page tables, but
303865e3b446SSean Christopherson  * the above "rules" ensure KVM will not _consume_ the result of the walk if a
303965e3b446SSean Christopherson  * race with the primary MMU occurs.
304065e3b446SSean Christopherson  */
3041a8ac499bSSean Christopherson static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
30428ca6f063SBen Gardon 				  const struct kvm_memory_slot *slot)
3043db543216SSean Christopherson {
3044284dc493SSean Christopherson 	int level = PG_LEVEL_4K;
3045db543216SSean Christopherson 	unsigned long hva;
304644187235SMingwei Zhang 	unsigned long flags;
304744187235SMingwei Zhang 	pgd_t pgd;
304844187235SMingwei Zhang 	p4d_t p4d;
304944187235SMingwei Zhang 	pud_t pud;
305044187235SMingwei Zhang 	pmd_t pmd;
3051db543216SSean Christopherson 
30525d49f08cSSean Christopherson 	/*
3053293e306eSSean Christopherson 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3054293e306eSSean Christopherson 	 * is not solely for performance, it's also necessary to avoid the
3055293e306eSSean Christopherson 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
3056293e306eSSean Christopherson 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
3057293e306eSSean Christopherson 	 * page fault steps have already verified the guest isn't writing a
3058293e306eSSean Christopherson 	 * read-only memslot.
3059293e306eSSean Christopherson 	 */
3060db543216SSean Christopherson 	hva = __gfn_to_hva_memslot(slot, gfn);
3061db543216SSean Christopherson 
306244187235SMingwei Zhang 	/*
306365e3b446SSean Christopherson 	 * Disable IRQs to prevent concurrent tear down of host page tables,
306465e3b446SSean Christopherson 	 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
306565e3b446SSean Christopherson 	 * the original page table.
306644187235SMingwei Zhang 	 */
306744187235SMingwei Zhang 	local_irq_save(flags);
3068db543216SSean Christopherson 
306965e3b446SSean Christopherson 	/*
307065e3b446SSean Christopherson 	 * Read each entry once.  As above, a non-leaf entry can be promoted to
307165e3b446SSean Christopherson 	 * a huge page _during_ this walk.  Re-reading the entry could send the
3072e72c7c2bSPeter Xu 	 * walk into the weeks, e.g. p*d_leaf() returns false (sees the old
307365e3b446SSean Christopherson 	 * value) and then p*d_offset() walks into the target huge page instead
307465e3b446SSean Christopherson 	 * of the old page table (sees the new value).
307565e3b446SSean Christopherson 	 */
307644187235SMingwei Zhang 	pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
307744187235SMingwei Zhang 	if (pgd_none(pgd))
307844187235SMingwei Zhang 		goto out;
307944187235SMingwei Zhang 
308044187235SMingwei Zhang 	p4d = READ_ONCE(*p4d_offset(&pgd, hva));
308144187235SMingwei Zhang 	if (p4d_none(p4d) || !p4d_present(p4d))
308244187235SMingwei Zhang 		goto out;
308344187235SMingwei Zhang 
308444187235SMingwei Zhang 	pud = READ_ONCE(*pud_offset(&p4d, hva));
308544187235SMingwei Zhang 	if (pud_none(pud) || !pud_present(pud))
308644187235SMingwei Zhang 		goto out;
308744187235SMingwei Zhang 
30880a845e0fSPeter Xu 	if (pud_leaf(pud)) {
308944187235SMingwei Zhang 		level = PG_LEVEL_1G;
309044187235SMingwei Zhang 		goto out;
309144187235SMingwei Zhang 	}
309244187235SMingwei Zhang 
309344187235SMingwei Zhang 	pmd = READ_ONCE(*pmd_offset(&pud, hva));
309444187235SMingwei Zhang 	if (pmd_none(pmd) || !pmd_present(pmd))
309544187235SMingwei Zhang 		goto out;
309644187235SMingwei Zhang 
30972f709f7bSPeter Xu 	if (pmd_leaf(pmd))
309844187235SMingwei Zhang 		level = PG_LEVEL_2M;
309944187235SMingwei Zhang 
310044187235SMingwei Zhang out:
310144187235SMingwei Zhang 	local_irq_restore(flags);
3102db543216SSean Christopherson 	return level;
3103db543216SSean Christopherson }
3104db543216SSean Christopherson 
31058dd2eee9SChao Peng static int __kvm_mmu_max_mapping_level(struct kvm *kvm,
31068dd2eee9SChao Peng 				       const struct kvm_memory_slot *slot,
31078dd2eee9SChao Peng 				       gfn_t gfn, int max_level, bool is_private)
31081b6d9d9eSSean Christopherson {
31091b6d9d9eSSean Christopherson 	struct kvm_lpage_info *linfo;
3110ec607a56SPaolo Bonzini 	int host_level;
31111b6d9d9eSSean Christopherson 
31121b6d9d9eSSean Christopherson 	max_level = min(max_level, max_huge_page_level);
31131b6d9d9eSSean Christopherson 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
31141b6d9d9eSSean Christopherson 		linfo = lpage_info_slot(gfn, slot, max_level);
31151b6d9d9eSSean Christopherson 		if (!linfo->disallow_lpage)
31161b6d9d9eSSean Christopherson 			break;
31171b6d9d9eSSean Christopherson 	}
31181b6d9d9eSSean Christopherson 
31198dd2eee9SChao Peng 	if (is_private)
31208dd2eee9SChao Peng 		return max_level;
31218dd2eee9SChao Peng 
31221b6d9d9eSSean Christopherson 	if (max_level == PG_LEVEL_4K)
31231b6d9d9eSSean Christopherson 		return PG_LEVEL_4K;
31241b6d9d9eSSean Christopherson 
3125a8ac499bSSean Christopherson 	host_level = host_pfn_mapping_level(kvm, gfn, slot);
3126ec607a56SPaolo Bonzini 	return min(host_level, max_level);
31271b6d9d9eSSean Christopherson }
31281b6d9d9eSSean Christopherson 
31298dd2eee9SChao Peng int kvm_mmu_max_mapping_level(struct kvm *kvm,
31308dd2eee9SChao Peng 			      const struct kvm_memory_slot *slot, gfn_t gfn,
31318dd2eee9SChao Peng 			      int max_level)
31328dd2eee9SChao Peng {
31338dd2eee9SChao Peng 	bool is_private = kvm_slot_can_be_private(slot) &&
31348dd2eee9SChao Peng 			  kvm_mem_is_private(kvm, gfn);
31358dd2eee9SChao Peng 
31368dd2eee9SChao Peng 	return __kvm_mmu_max_mapping_level(kvm, slot, gfn, max_level, is_private);
31378dd2eee9SChao Peng }
31388dd2eee9SChao Peng 
313973a3c659SPaolo Bonzini void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
31400885904dSSean Christopherson {
3141e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
314217eff019SSean Christopherson 	kvm_pfn_t mask;
31430885904dSSean Christopherson 
314473a3c659SPaolo Bonzini 	fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
31453cf06612SSean Christopherson 
314673a3c659SPaolo Bonzini 	if (unlikely(fault->max_level == PG_LEVEL_4K))
314773a3c659SPaolo Bonzini 		return;
314817eff019SSean Christopherson 
31495d49f08cSSean Christopherson 	if (is_error_noslot_pfn(fault->pfn))
315073a3c659SPaolo Bonzini 		return;
315117eff019SSean Christopherson 
3152e710c5f6SDavid Matlack 	if (kvm_slot_dirty_track_enabled(slot))
315373a3c659SPaolo Bonzini 		return;
3154293e306eSSean Christopherson 
31553cf06612SSean Christopherson 	/*
31563cf06612SSean Christopherson 	 * Enforce the iTLB multihit workaround after capturing the requested
31573cf06612SSean Christopherson 	 * level, which will be used to do precise, accurate accounting.
31583cf06612SSean Christopherson 	 */
31598dd2eee9SChao Peng 	fault->req_level = __kvm_mmu_max_mapping_level(vcpu->kvm, slot,
31608dd2eee9SChao Peng 						       fault->gfn, fault->max_level,
31618dd2eee9SChao Peng 						       fault->is_private);
316273a3c659SPaolo Bonzini 	if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
316373a3c659SPaolo Bonzini 		return;
31644cd071d1SSean Christopherson 
31650885904dSSean Christopherson 	/*
316620ec3ebdSChao Peng 	 * mmu_invalidate_retry() was successful and mmu_lock is held, so
31674cd071d1SSean Christopherson 	 * the pmd can't be split from under us.
31680885904dSSean Christopherson 	 */
316973a3c659SPaolo Bonzini 	fault->goal_level = fault->req_level;
317073a3c659SPaolo Bonzini 	mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
317173a3c659SPaolo Bonzini 	VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
317273a3c659SPaolo Bonzini 	fault->pfn &= ~mask;
31730885904dSSean Christopherson }
31740885904dSSean Christopherson 
3175536f0e6aSPaolo Bonzini void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3176c50d8ae3SPaolo Bonzini {
3177536f0e6aSPaolo Bonzini 	if (cur_level > PG_LEVEL_4K &&
3178536f0e6aSPaolo Bonzini 	    cur_level == fault->goal_level &&
3179c50d8ae3SPaolo Bonzini 	    is_shadow_present_pte(spte) &&
318076901e56SMingwei Zhang 	    !is_large_pte(spte) &&
318176901e56SMingwei Zhang 	    spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3182c50d8ae3SPaolo Bonzini 		/*
31836c882ef4SDavid Matlack 		 * A small SPTE exists for this pfn, but FNAME(fetch),
31846c882ef4SDavid Matlack 		 * direct_map(), or kvm_tdp_mmu_map() would like to create a
31856c882ef4SDavid Matlack 		 * large PTE instead: just force them to go down another level,
31866c882ef4SDavid Matlack 		 * patching back for them into pfn the next 9 bits of the
31876c882ef4SDavid Matlack 		 * address.
3188c50d8ae3SPaolo Bonzini 		 */
3189536f0e6aSPaolo Bonzini 		u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3190536f0e6aSPaolo Bonzini 				KVM_PAGES_PER_HPAGE(cur_level - 1);
3191536f0e6aSPaolo Bonzini 		fault->pfn |= fault->gfn & page_mask;
3192536f0e6aSPaolo Bonzini 		fault->goal_level--;
3193c50d8ae3SPaolo Bonzini 	}
3194c50d8ae3SPaolo Bonzini }
3195c50d8ae3SPaolo Bonzini 
31966c882ef4SDavid Matlack static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3197c50d8ae3SPaolo Bonzini {
3198c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator it;
3199c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
320073a3c659SPaolo Bonzini 	int ret;
320143b74355SPaolo Bonzini 	gfn_t base_gfn = fault->gfn;
3202c50d8ae3SPaolo Bonzini 
320373a3c659SPaolo Bonzini 	kvm_mmu_hugepage_adjust(vcpu, fault);
32044cd071d1SSean Christopherson 
3205f0066d94SPaolo Bonzini 	trace_kvm_mmu_spte_requested(fault);
320643b74355SPaolo Bonzini 	for_each_shadow_entry(vcpu, fault->addr, it) {
3207c50d8ae3SPaolo Bonzini 		/*
3208c50d8ae3SPaolo Bonzini 		 * We cannot overwrite existing page tables with an NX
3209c50d8ae3SPaolo Bonzini 		 * large page, as the leaf could be executable.
3210c50d8ae3SPaolo Bonzini 		 */
321173a3c659SPaolo Bonzini 		if (fault->nx_huge_page_workaround_enabled)
3212536f0e6aSPaolo Bonzini 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3213c50d8ae3SPaolo Bonzini 
3214c667a3baSHou Wenlong 		base_gfn = gfn_round_for_level(fault->gfn, it.level);
321573a3c659SPaolo Bonzini 		if (it.level == fault->goal_level)
3216c50d8ae3SPaolo Bonzini 			break;
3217c50d8ae3SPaolo Bonzini 
32182e65e842SDavid Matlack 		sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
32190cd8dc73SPaolo Bonzini 		if (sp == ERR_PTR(-EEXIST))
32200cd8dc73SPaolo Bonzini 			continue;
3221c50d8ae3SPaolo Bonzini 
3222c50d8ae3SPaolo Bonzini 		link_shadow_page(vcpu, it.sptep, sp);
3223b5b0977fSSean Christopherson 		if (fault->huge_page_disallowed)
322455c510e2SSean Christopherson 			account_nx_huge_page(vcpu->kvm, sp,
3225428e9216SSean Christopherson 					     fault->req_level >= it.level);
3226c50d8ae3SPaolo Bonzini 	}
3227c50d8ae3SPaolo Bonzini 
3228b1a429fbSSean Christopherson 	if (WARN_ON_ONCE(it.level != fault->goal_level))
3229b1a429fbSSean Christopherson 		return -EFAULT;
3230b1a429fbSSean Christopherson 
32318a9f566aSDavid Matlack 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3232a12f4381SPaolo Bonzini 			   base_gfn, fault->pfn, fault);
323312703759SSean Christopherson 	if (ret == RET_PF_SPURIOUS)
323412703759SSean Christopherson 		return ret;
323512703759SSean Christopherson 
3236c50d8ae3SPaolo Bonzini 	direct_pte_prefetch(vcpu, it.sptep);
3237c50d8ae3SPaolo Bonzini 	return ret;
3238c50d8ae3SPaolo Bonzini }
3239c50d8ae3SPaolo Bonzini 
3240cd08d178SDavid Matlack static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3241c50d8ae3SPaolo Bonzini {
3242cd08d178SDavid Matlack 	unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3243cd08d178SDavid Matlack 
3244cd08d178SDavid Matlack 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3245c50d8ae3SPaolo Bonzini }
3246c50d8ae3SPaolo Bonzini 
3247cd08d178SDavid Matlack static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3248c50d8ae3SPaolo Bonzini {
3249cd08d178SDavid Matlack 	if (is_sigpending_pfn(fault->pfn)) {
325076657687SPeter Xu 		kvm_handle_signal_exit(vcpu);
325176657687SPeter Xu 		return -EINTR;
325276657687SPeter Xu 	}
325376657687SPeter Xu 
3254c50d8ae3SPaolo Bonzini 	/*
3255c50d8ae3SPaolo Bonzini 	 * Do not cache the mmio info caused by writing the readonly gfn
3256c50d8ae3SPaolo Bonzini 	 * into the spte otherwise read access on readonly gfn also can
3257c50d8ae3SPaolo Bonzini 	 * caused mmio page fault and treat it as mmio access.
3258c50d8ae3SPaolo Bonzini 	 */
3259cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3260c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3261c50d8ae3SPaolo Bonzini 
3262cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3263cd08d178SDavid Matlack 		kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3264c50d8ae3SPaolo Bonzini 		return RET_PF_RETRY;
3265c50d8ae3SPaolo Bonzini 	}
3266c50d8ae3SPaolo Bonzini 
3267c50d8ae3SPaolo Bonzini 	return -EFAULT;
3268c50d8ae3SPaolo Bonzini }
3269c50d8ae3SPaolo Bonzini 
3270354c908cSDavid Matlack static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3271354c908cSDavid Matlack 				   struct kvm_page_fault *fault,
32725276c616SSean Christopherson 				   unsigned int access)
3273c50d8ae3SPaolo Bonzini {
32743a13f4feSPaolo Bonzini 	gva_t gva = fault->is_tdp ? 0 : fault->addr;
32753a13f4feSPaolo Bonzini 
3276bde9f9d2SSean Christopherson 	if (fault->is_private) {
3277bde9f9d2SSean Christopherson 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
3278bde9f9d2SSean Christopherson 		return -EFAULT;
3279bde9f9d2SSean Christopherson 	}
3280bde9f9d2SSean Christopherson 
32813a13f4feSPaolo Bonzini 	vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3282c50d8ae3SPaolo Bonzini 			     access & shadow_mmio_access_mask);
3283354c908cSDavid Matlack 
3284f6adeae8SSean Christopherson 	fault->slot = NULL;
3285f6adeae8SSean Christopherson 	fault->pfn = KVM_PFN_NOSLOT;
3286f6adeae8SSean Christopherson 	fault->map_writable = false;
328736d44927SSean Christopherson 	fault->hva = KVM_HVA_ERR_BAD;
3288f6adeae8SSean Christopherson 
328930ab5901SSean Christopherson 	/*
329030ab5901SSean Christopherson 	 * If MMIO caching is disabled, emulate immediately without
329130ab5901SSean Christopherson 	 * touching the shadow page tables as attempting to install an
3292354c908cSDavid Matlack 	 * MMIO SPTE will just be an expensive nop.
329330ab5901SSean Christopherson 	 */
3294354c908cSDavid Matlack 	if (unlikely(!enable_mmio_caching))
32955276c616SSean Christopherson 		return RET_PF_EMULATE;
3296354c908cSDavid Matlack 
3297354c908cSDavid Matlack 	/*
3298354c908cSDavid Matlack 	 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3299354c908cSDavid Matlack 	 * any guest that generates such gfns is running nested and is being
3300354c908cSDavid Matlack 	 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3301354c908cSDavid Matlack 	 * only if L1's MAXPHYADDR is inaccurate with respect to the
3302354c908cSDavid Matlack 	 * hardware's).
3303354c908cSDavid Matlack 	 */
3304354c908cSDavid Matlack 	if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3305354c908cSDavid Matlack 		return RET_PF_EMULATE;
3306c50d8ae3SPaolo Bonzini 
33075276c616SSean Christopherson 	return RET_PF_CONTINUE;
3308c50d8ae3SPaolo Bonzini }
3309c50d8ae3SPaolo Bonzini 
3310b74d002dSMichael Roth static bool page_fault_can_be_fast(struct kvm *kvm, struct kvm_page_fault *fault)
3311c50d8ae3SPaolo Bonzini {
3312c50d8ae3SPaolo Bonzini 	/*
33135c64aba5SSean Christopherson 	 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
33145c64aba5SSean Christopherson 	 * reach the common page fault handler if the SPTE has an invalid MMIO
33155c64aba5SSean Christopherson 	 * generation number.  Refreshing the MMIO generation needs to go down
33165c64aba5SSean Christopherson 	 * the slow path.  Note, EPT Misconfigs do NOT set the PRESENT flag!
3317c50d8ae3SPaolo Bonzini 	 */
33183c8ad5a6SPaolo Bonzini 	if (fault->rsvd)
3319c50d8ae3SPaolo Bonzini 		return false;
3320c50d8ae3SPaolo Bonzini 
3321c50d8ae3SPaolo Bonzini 	/*
3322b74d002dSMichael Roth 	 * For hardware-protected VMs, certain conditions like attempting to
3323b74d002dSMichael Roth 	 * perform a write to a page which is not in the state that the guest
3324b74d002dSMichael Roth 	 * expects it to be in can result in a nested/extended #PF. In this
3325b74d002dSMichael Roth 	 * case, the below code might misconstrue this situation as being the
3326b74d002dSMichael Roth 	 * result of a write-protected access, and treat it as a spurious case
3327b74d002dSMichael Roth 	 * rather than taking any action to satisfy the real source of the #PF
3328b74d002dSMichael Roth 	 * such as generating a KVM_EXIT_MEMORY_FAULT. This can lead to the
3329b74d002dSMichael Roth 	 * guest spinning on a #PF indefinitely, so don't attempt the fast path
3330b74d002dSMichael Roth 	 * in this case.
3331b74d002dSMichael Roth 	 *
3332b74d002dSMichael Roth 	 * Note that the kvm_mem_is_private() check might race with an
3333b74d002dSMichael Roth 	 * attribute update, but this will either result in the guest spinning
3334b74d002dSMichael Roth 	 * on RET_PF_SPURIOUS until the update completes, or an actual spurious
3335b74d002dSMichael Roth 	 * case might go down the slow path. Either case will resolve itself.
3336b74d002dSMichael Roth 	 */
3337b74d002dSMichael Roth 	if (kvm->arch.has_private_mem &&
3338b74d002dSMichael Roth 	    fault->is_private != kvm_mem_is_private(kvm, fault->gfn))
3339b74d002dSMichael Roth 		return false;
3340b74d002dSMichael Roth 
3341b74d002dSMichael Roth 	/*
3342c50d8ae3SPaolo Bonzini 	 * #PF can be fast if:
3343c50d8ae3SPaolo Bonzini 	 *
334454275f74SSean Christopherson 	 * 1. The shadow page table entry is not present and A/D bits are
334554275f74SSean Christopherson 	 *    disabled _by KVM_, which could mean that the fault is potentially
334654275f74SSean Christopherson 	 *    caused by access tracking (if enabled).  If A/D bits are enabled
334754275f74SSean Christopherson 	 *    by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
334854275f74SSean Christopherson 	 *    bits for L2 and employ access tracking, but the fast page fault
334954275f74SSean Christopherson 	 *    mechanism only supports direct MMUs.
335054275f74SSean Christopherson 	 * 2. The shadow page table entry is present, the access is a write,
335154275f74SSean Christopherson 	 *    and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
335254275f74SSean Christopherson 	 *    the fault was caused by a write-protection violation.  If the
335354275f74SSean Christopherson 	 *    SPTE is MMU-writable (determined later), the fault can be fixed
335454275f74SSean Christopherson 	 *    by setting the Writable bit, which can be done out of mmu_lock.
3355c50d8ae3SPaolo Bonzini 	 */
33565c64aba5SSean Christopherson 	if (!fault->present)
33575c64aba5SSean Christopherson 		return !kvm_ad_enabled();
33585c64aba5SSean Christopherson 
33595c64aba5SSean Christopherson 	/*
33605c64aba5SSean Christopherson 	 * Note, instruction fetches and writes are mutually exclusive, ignore
33615c64aba5SSean Christopherson 	 * the "exec" flag.
33625c64aba5SSean Christopherson 	 */
33635c64aba5SSean Christopherson 	return fault->write;
3364c50d8ae3SPaolo Bonzini }
3365c50d8ae3SPaolo Bonzini 
3366c50d8ae3SPaolo Bonzini /*
3367c50d8ae3SPaolo Bonzini  * Returns true if the SPTE was fixed successfully. Otherwise,
3368c50d8ae3SPaolo Bonzini  * someone else modified the SPTE from its original value.
3369c50d8ae3SPaolo Bonzini  */
3370f3d90f90SSean Christopherson static bool fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu,
3371f3d90f90SSean Christopherson 				    struct kvm_page_fault *fault,
3372c50d8ae3SPaolo Bonzini 				    u64 *sptep, u64 old_spte, u64 new_spte)
3373c50d8ae3SPaolo Bonzini {
3374c50d8ae3SPaolo Bonzini 	/*
3375c50d8ae3SPaolo Bonzini 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3376c50d8ae3SPaolo Bonzini 	 * order to eliminate unnecessary PML logging. See comments in
3377c50d8ae3SPaolo Bonzini 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3378c50d8ae3SPaolo Bonzini 	 * enabled, so we do not do this. This might result in the same GPA
3379c50d8ae3SPaolo Bonzini 	 * to be logged in PML buffer again when the write really happens, and
3380c50d8ae3SPaolo Bonzini 	 * eventually to be called by mark_page_dirty twice. But it's also no
3381c50d8ae3SPaolo Bonzini 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3382c50d8ae3SPaolo Bonzini 	 * so non-PML cases won't be impacted.
3383c50d8ae3SPaolo Bonzini 	 *
3384c50d8ae3SPaolo Bonzini 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3385c50d8ae3SPaolo Bonzini 	 */
33862db2f46fSUros Bizjak 	if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3387c50d8ae3SPaolo Bonzini 		return false;
3388c50d8ae3SPaolo Bonzini 
3389e710c5f6SDavid Matlack 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3390e710c5f6SDavid Matlack 		mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3391c50d8ae3SPaolo Bonzini 
3392c50d8ae3SPaolo Bonzini 	return true;
3393c50d8ae3SPaolo Bonzini }
3394c50d8ae3SPaolo Bonzini 
33953c8ad5a6SPaolo Bonzini static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3396c50d8ae3SPaolo Bonzini {
33973c8ad5a6SPaolo Bonzini 	if (fault->exec)
3398c50d8ae3SPaolo Bonzini 		return is_executable_pte(spte);
3399c50d8ae3SPaolo Bonzini 
34003c8ad5a6SPaolo Bonzini 	if (fault->write)
3401c50d8ae3SPaolo Bonzini 		return is_writable_pte(spte);
3402c50d8ae3SPaolo Bonzini 
3403c50d8ae3SPaolo Bonzini 	/* Fault was on Read access */
3404c50d8ae3SPaolo Bonzini 	return spte & PT_PRESENT_MASK;
3405c50d8ae3SPaolo Bonzini }
3406c50d8ae3SPaolo Bonzini 
3407c50d8ae3SPaolo Bonzini /*
34086e8eb206SDavid Matlack  * Returns the last level spte pointer of the shadow page walk for the given
34096e8eb206SDavid Matlack  * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
34106e8eb206SDavid Matlack  * walk could be performed, returns NULL and *spte does not contain valid data.
34116e8eb206SDavid Matlack  *
34126e8eb206SDavid Matlack  * Contract:
34136e8eb206SDavid Matlack  *  - Must be called between walk_shadow_page_lockless_{begin,end}.
34146e8eb206SDavid Matlack  *  - The returned sptep must not be used after walk_shadow_page_lockless_end.
34156e8eb206SDavid Matlack  */
34166e8eb206SDavid Matlack static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
34176e8eb206SDavid Matlack {
34186e8eb206SDavid Matlack 	struct kvm_shadow_walk_iterator iterator;
34196e8eb206SDavid Matlack 	u64 old_spte;
34206e8eb206SDavid Matlack 	u64 *sptep = NULL;
34216e8eb206SDavid Matlack 
34226e8eb206SDavid Matlack 	for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
34236e8eb206SDavid Matlack 		sptep = iterator.sptep;
34246e8eb206SDavid Matlack 		*spte = old_spte;
34256e8eb206SDavid Matlack 	}
34266e8eb206SDavid Matlack 
34276e8eb206SDavid Matlack 	return sptep;
34286e8eb206SDavid Matlack }
34296e8eb206SDavid Matlack 
34306e8eb206SDavid Matlack /*
3431c4371c2aSSean Christopherson  * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3432c50d8ae3SPaolo Bonzini  */
34333c8ad5a6SPaolo Bonzini static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3434c50d8ae3SPaolo Bonzini {
3435c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3436c4371c2aSSean Christopherson 	int ret = RET_PF_INVALID;
34371de9992fSLi zeming 	u64 spte;
34381de9992fSLi zeming 	u64 *sptep;
3439c50d8ae3SPaolo Bonzini 	uint retry_count = 0;
3440c50d8ae3SPaolo Bonzini 
3441b74d002dSMichael Roth 	if (!page_fault_can_be_fast(vcpu->kvm, fault))
3442c4371c2aSSean Christopherson 		return ret;
3443c50d8ae3SPaolo Bonzini 
3444c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
3445c50d8ae3SPaolo Bonzini 
3446c50d8ae3SPaolo Bonzini 	do {
3447c50d8ae3SPaolo Bonzini 		u64 new_spte;
3448c50d8ae3SPaolo Bonzini 
3449dfe0ecc6SSean Christopherson 		if (tdp_mmu_enabled)
3450c2f38f75SRick Edgecombe 			sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->gfn, &spte);
34516e8eb206SDavid Matlack 		else
34523c8ad5a6SPaolo Bonzini 			sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3453c50d8ae3SPaolo Bonzini 
34541de9992fSLi zeming 		/*
34551de9992fSLi zeming 		 * It's entirely possible for the mapping to have been zapped
34561de9992fSLi zeming 		 * by a different task, but the root page should always be
34571de9992fSLi zeming 		 * available as the vCPU holds a reference to its root(s).
34581de9992fSLi zeming 		 */
34591de9992fSLi zeming 		if (WARN_ON_ONCE(!sptep))
3460964cea81SRick Edgecombe 			spte = FROZEN_SPTE;
34611de9992fSLi zeming 
3462ec89e643SSean Christopherson 		if (!is_shadow_present_pte(spte))
3463ec89e643SSean Christopherson 			break;
3464ec89e643SSean Christopherson 
34656e8eb206SDavid Matlack 		sp = sptep_to_sp(sptep);
3466c50d8ae3SPaolo Bonzini 		if (!is_last_spte(spte, sp->role.level))
3467c50d8ae3SPaolo Bonzini 			break;
3468c50d8ae3SPaolo Bonzini 
3469c50d8ae3SPaolo Bonzini 		/*
3470c50d8ae3SPaolo Bonzini 		 * Check whether the memory access that caused the fault would
3471c50d8ae3SPaolo Bonzini 		 * still cause it if it were to be performed right now. If not,
3472c50d8ae3SPaolo Bonzini 		 * then this is a spurious fault caused by TLB lazily flushed,
3473c50d8ae3SPaolo Bonzini 		 * or some other CPU has already fixed the PTE after the
3474c50d8ae3SPaolo Bonzini 		 * current CPU took the fault.
3475c50d8ae3SPaolo Bonzini 		 *
3476c50d8ae3SPaolo Bonzini 		 * Need not check the access of upper level table entries since
3477c50d8ae3SPaolo Bonzini 		 * they are always ACC_ALL.
3478c50d8ae3SPaolo Bonzini 		 */
34793c8ad5a6SPaolo Bonzini 		if (is_access_allowed(fault, spte)) {
3480c4371c2aSSean Christopherson 			ret = RET_PF_SPURIOUS;
3481c50d8ae3SPaolo Bonzini 			break;
3482c50d8ae3SPaolo Bonzini 		}
3483c50d8ae3SPaolo Bonzini 
3484c50d8ae3SPaolo Bonzini 		new_spte = spte;
3485c50d8ae3SPaolo Bonzini 
348654275f74SSean Christopherson 		/*
348754275f74SSean Christopherson 		 * KVM only supports fixing page faults outside of MMU lock for
348854275f74SSean Christopherson 		 * direct MMUs, nested MMUs are always indirect, and KVM always
348954275f74SSean Christopherson 		 * uses A/D bits for non-nested MMUs.  Thus, if A/D bits are
349054275f74SSean Christopherson 		 * enabled, the SPTE can't be an access-tracked SPTE.
349154275f74SSean Christopherson 		 */
349254275f74SSean Christopherson 		if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3493c50d8ae3SPaolo Bonzini 			new_spte = restore_acc_track_spte(new_spte);
3494c50d8ae3SPaolo Bonzini 
3495c50d8ae3SPaolo Bonzini 		/*
349654275f74SSean Christopherson 		 * To keep things simple, only SPTEs that are MMU-writable can
349754275f74SSean Christopherson 		 * be made fully writable outside of mmu_lock, e.g. only SPTEs
349854275f74SSean Christopherson 		 * that were write-protected for dirty-logging or access
349954275f74SSean Christopherson 		 * tracking are handled here.  Don't bother checking if the
350054275f74SSean Christopherson 		 * SPTE is writable to prioritize running with A/D bits enabled.
350154275f74SSean Christopherson 		 * The is_access_allowed() check above handles the common case
350254275f74SSean Christopherson 		 * of the fault being spurious, and the SPTE is known to be
350354275f74SSean Christopherson 		 * shadow-present, i.e. except for access tracking restoration
350454275f74SSean Christopherson 		 * making the new SPTE writable, the check is wasteful.
3505c50d8ae3SPaolo Bonzini 		 */
3506706c9c55SSean Christopherson 		if (fault->write && is_mmu_writable_spte(spte)) {
3507c50d8ae3SPaolo Bonzini 			new_spte |= PT_WRITABLE_MASK;
3508c50d8ae3SPaolo Bonzini 
3509c50d8ae3SPaolo Bonzini 			/*
351010c30de0SJunaid Shahid 			 * Do not fix write-permission on the large spte when
351110c30de0SJunaid Shahid 			 * dirty logging is enabled. Since we only dirty the
351210c30de0SJunaid Shahid 			 * first page into the dirty-bitmap in
3513c50d8ae3SPaolo Bonzini 			 * fast_pf_fix_direct_spte(), other pages are missed
3514c50d8ae3SPaolo Bonzini 			 * if its slot has dirty logging enabled.
3515c50d8ae3SPaolo Bonzini 			 *
3516c50d8ae3SPaolo Bonzini 			 * Instead, we let the slow page fault path create a
3517c50d8ae3SPaolo Bonzini 			 * normal spte to fix the access.
3518c50d8ae3SPaolo Bonzini 			 */
351910c30de0SJunaid Shahid 			if (sp->role.level > PG_LEVEL_4K &&
352010c30de0SJunaid Shahid 			    kvm_slot_dirty_track_enabled(fault->slot))
3521c50d8ae3SPaolo Bonzini 				break;
3522c50d8ae3SPaolo Bonzini 		}
3523c50d8ae3SPaolo Bonzini 
3524c50d8ae3SPaolo Bonzini 		/* Verify that the fault can be handled in the fast path */
3525c50d8ae3SPaolo Bonzini 		if (new_spte == spte ||
35263c8ad5a6SPaolo Bonzini 		    !is_access_allowed(fault, new_spte))
3527c50d8ae3SPaolo Bonzini 			break;
3528c50d8ae3SPaolo Bonzini 
3529c50d8ae3SPaolo Bonzini 		/*
3530c50d8ae3SPaolo Bonzini 		 * Currently, fast page fault only works for direct mapping
3531c50d8ae3SPaolo Bonzini 		 * since the gfn is not stable for indirect shadow page. See
35323ecad8c2SMauro Carvalho Chehab 		 * Documentation/virt/kvm/locking.rst to get more detail.
3533c50d8ae3SPaolo Bonzini 		 */
3534e710c5f6SDavid Matlack 		if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3535c4371c2aSSean Christopherson 			ret = RET_PF_FIXED;
3536c50d8ae3SPaolo Bonzini 			break;
3537c4371c2aSSean Christopherson 		}
3538c50d8ae3SPaolo Bonzini 
3539c50d8ae3SPaolo Bonzini 		if (++retry_count > 4) {
35408d20bd63SSean Christopherson 			pr_warn_once("Fast #PF retrying more than 4 times.\n");
3541c50d8ae3SPaolo Bonzini 			break;
3542c50d8ae3SPaolo Bonzini 		}
3543c50d8ae3SPaolo Bonzini 
3544c50d8ae3SPaolo Bonzini 	} while (true);
3545c50d8ae3SPaolo Bonzini 
3546f0066d94SPaolo Bonzini 	trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3547c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3548c50d8ae3SPaolo Bonzini 
35491075d41eSSean Christopherson 	if (ret != RET_PF_INVALID)
35501075d41eSSean Christopherson 		vcpu->stat.pf_fast++;
35511075d41eSSean Christopherson 
3552c4371c2aSSean Christopherson 	return ret;
3553c50d8ae3SPaolo Bonzini }
3554c50d8ae3SPaolo Bonzini 
3555c50d8ae3SPaolo Bonzini static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3556c50d8ae3SPaolo Bonzini 			       struct list_head *invalid_list)
3557c50d8ae3SPaolo Bonzini {
3558c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3559c50d8ae3SPaolo Bonzini 
3560c50d8ae3SPaolo Bonzini 	if (!VALID_PAGE(*root_hpa))
3561c50d8ae3SPaolo Bonzini 		return;
3562c50d8ae3SPaolo Bonzini 
3563c5f2d564SSean Christopherson 	sp = root_to_sp(*root_hpa);
356420ba462dSSean Christopherson 	if (WARN_ON_ONCE(!sp))
35659191b8f0SPaolo Bonzini 		return;
356602c00b3aSBen Gardon 
3567576a15deSSean Christopherson 	if (is_tdp_mmu_page(sp)) {
3568576a15deSSean Christopherson 		lockdep_assert_held_read(&kvm->mmu_lock);
35695f3c8c91SPaolo Bonzini 		kvm_tdp_mmu_put_root(kvm, sp);
3570576a15deSSean Christopherson 	} else {
3571576a15deSSean Christopherson 		lockdep_assert_held_write(&kvm->mmu_lock);
3572576a15deSSean Christopherson 		if (!--sp->root_count && sp->role.invalid)
3573c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3574576a15deSSean Christopherson 	}
3575c50d8ae3SPaolo Bonzini 
3576c50d8ae3SPaolo Bonzini 	*root_hpa = INVALID_PAGE;
3577c50d8ae3SPaolo Bonzini }
3578c50d8ae3SPaolo Bonzini 
3579c50d8ae3SPaolo Bonzini /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
35800c1c92f1SPaolo Bonzini void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3581c50d8ae3SPaolo Bonzini 			ulong roots_to_free)
3582c50d8ae3SPaolo Bonzini {
3583576a15deSSean Christopherson 	bool is_tdp_mmu = tdp_mmu_enabled && mmu->root_role.direct;
3584c50d8ae3SPaolo Bonzini 	int i;
3585c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
3586594bef79SPaolo Bonzini 	bool free_active_root;
3587c50d8ae3SPaolo Bonzini 
3588f94db0c8SSean Christopherson 	WARN_ON_ONCE(roots_to_free & ~KVM_MMU_ROOTS_ALL);
3589f94db0c8SSean Christopherson 
3590c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3591c50d8ae3SPaolo Bonzini 
3592c50d8ae3SPaolo Bonzini 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3593594bef79SPaolo Bonzini 	free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3594594bef79SPaolo Bonzini 		&& VALID_PAGE(mmu->root.hpa);
3595594bef79SPaolo Bonzini 
3596594bef79SPaolo Bonzini 	if (!free_active_root) {
3597c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3598c50d8ae3SPaolo Bonzini 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3599c50d8ae3SPaolo Bonzini 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3600c50d8ae3SPaolo Bonzini 				break;
3601c50d8ae3SPaolo Bonzini 
3602c50d8ae3SPaolo Bonzini 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3603c50d8ae3SPaolo Bonzini 			return;
3604c50d8ae3SPaolo Bonzini 	}
3605c50d8ae3SPaolo Bonzini 
3606576a15deSSean Christopherson 	if (is_tdp_mmu)
3607576a15deSSean Christopherson 		read_lock(&kvm->mmu_lock);
3608576a15deSSean Christopherson 	else
3609531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
3610c50d8ae3SPaolo Bonzini 
3611c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3612c50d8ae3SPaolo Bonzini 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
36134d710de9SSean Christopherson 			mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3614c50d8ae3SPaolo Bonzini 					   &invalid_list);
3615c50d8ae3SPaolo Bonzini 
3616c50d8ae3SPaolo Bonzini 	if (free_active_root) {
36170e3223d8SSean Christopherson 		if (kvm_mmu_is_dummy_root(mmu->root.hpa)) {
36180e3223d8SSean Christopherson 			/* Nothing to cleanup for dummy roots. */
36190e3223d8SSean Christopherson 		} else if (root_to_sp(mmu->root.hpa)) {
3620b9e5603cSPaolo Bonzini 			mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
362104d45551SSean Christopherson 		} else if (mmu->pae_root) {
3622c834e5e4SSean Christopherson 			for (i = 0; i < 4; ++i) {
3623c834e5e4SSean Christopherson 				if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3624c834e5e4SSean Christopherson 					continue;
3625c834e5e4SSean Christopherson 
3626c834e5e4SSean Christopherson 				mmu_free_root_page(kvm, &mmu->pae_root[i],
3627c50d8ae3SPaolo Bonzini 						   &invalid_list);
3628c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3629c50d8ae3SPaolo Bonzini 			}
3630c50d8ae3SPaolo Bonzini 		}
3631b9e5603cSPaolo Bonzini 		mmu->root.hpa = INVALID_PAGE;
3632b9e5603cSPaolo Bonzini 		mmu->root.pgd = 0;
3633c50d8ae3SPaolo Bonzini 	}
3634c50d8ae3SPaolo Bonzini 
3635576a15deSSean Christopherson 	if (is_tdp_mmu) {
3636576a15deSSean Christopherson 		read_unlock(&kvm->mmu_lock);
3637576a15deSSean Christopherson 		WARN_ON_ONCE(!list_empty(&invalid_list));
3638576a15deSSean Christopherson 	} else {
36394d710de9SSean Christopherson 		kvm_mmu_commit_zap_page(kvm, &invalid_list);
3640531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
3641c50d8ae3SPaolo Bonzini 	}
3642576a15deSSean Christopherson }
3643c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3644c50d8ae3SPaolo Bonzini 
36450c1c92f1SPaolo Bonzini void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
364625b62c62SSean Christopherson {
364725b62c62SSean Christopherson 	unsigned long roots_to_free = 0;
3648c5f2d564SSean Christopherson 	struct kvm_mmu_page *sp;
364925b62c62SSean Christopherson 	hpa_t root_hpa;
365025b62c62SSean Christopherson 	int i;
365125b62c62SSean Christopherson 
365225b62c62SSean Christopherson 	/*
365325b62c62SSean Christopherson 	 * This should not be called while L2 is active, L2 can't invalidate
365425b62c62SSean Christopherson 	 * _only_ its own roots, e.g. INVVPID unconditionally exits.
365525b62c62SSean Christopherson 	 */
36567a458f0eSPaolo Bonzini 	WARN_ON_ONCE(mmu->root_role.guest_mode);
365725b62c62SSean Christopherson 
365825b62c62SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
365925b62c62SSean Christopherson 		root_hpa = mmu->prev_roots[i].hpa;
366025b62c62SSean Christopherson 		if (!VALID_PAGE(root_hpa))
366125b62c62SSean Christopherson 			continue;
366225b62c62SSean Christopherson 
3663c5f2d564SSean Christopherson 		sp = root_to_sp(root_hpa);
3664c5f2d564SSean Christopherson 		if (!sp || sp->role.guest_mode)
366525b62c62SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
366625b62c62SSean Christopherson 	}
366725b62c62SSean Christopherson 
36680c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, roots_to_free);
366925b62c62SSean Christopherson }
367025b62c62SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
367125b62c62SSean Christopherson 
36722e65e842SDavid Matlack static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
367386938ab6SDavid Matlack 			    u8 level)
3674c50d8ae3SPaolo Bonzini {
36752e65e842SDavid Matlack 	union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3676c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
36778123f265SSean Christopherson 
36782e65e842SDavid Matlack 	role.level = level;
36792e65e842SDavid Matlack 	role.quadrant = quadrant;
36802e65e842SDavid Matlack 
36817f497775SDavid Matlack 	WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
36827f497775SDavid Matlack 	WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
36837f497775SDavid Matlack 
368487654643SDavid Matlack 	sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
36858123f265SSean Christopherson 	++sp->root_count;
36868123f265SSean Christopherson 
36878123f265SSean Christopherson 	return __pa(sp->spt);
36888123f265SSean Christopherson }
36898123f265SSean Christopherson 
36908123f265SSean Christopherson static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
36918123f265SSean Christopherson {
3692b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3693a972e29cSPaolo Bonzini 	u8 shadow_root_level = mmu->root_role.level;
36948123f265SSean Christopherson 	hpa_t root;
3695c50d8ae3SPaolo Bonzini 	unsigned i;
36964a38162eSPaolo Bonzini 	int r;
36974a38162eSPaolo Bonzini 
3698f5238c2aSSean Christopherson 	if (tdp_mmu_enabled)
3699f5238c2aSSean Christopherson 		return kvm_tdp_mmu_alloc_root(vcpu);
3700f5238c2aSSean Christopherson 
37014a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
37024a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
37034a38162eSPaolo Bonzini 	if (r < 0)
37044a38162eSPaolo Bonzini 		goto out_unlock;
3705c50d8ae3SPaolo Bonzini 
3706f5238c2aSSean Christopherson 	if (shadow_root_level >= PT64_ROOT_4LEVEL) {
370786938ab6SDavid Matlack 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3708b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
37098123f265SSean Christopherson 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
37104a38162eSPaolo Bonzini 		if (WARN_ON_ONCE(!mmu->pae_root)) {
37114a38162eSPaolo Bonzini 			r = -EIO;
37124a38162eSPaolo Bonzini 			goto out_unlock;
37134a38162eSPaolo Bonzini 		}
371473ad1606SSean Christopherson 
3715c50d8ae3SPaolo Bonzini 		for (i = 0; i < 4; ++i) {
3716c834e5e4SSean Christopherson 			WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3717c50d8ae3SPaolo Bonzini 
37187f497775SDavid Matlack 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
37192e65e842SDavid Matlack 					      PT32_ROOT_LEVEL);
372017e368d9SSean Christopherson 			mmu->pae_root[i] = root | PT_PRESENT_MASK |
3721d2263de1SYuan Yao 					   shadow_me_value;
3722c50d8ae3SPaolo Bonzini 		}
3723b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
372473ad1606SSean Christopherson 	} else {
372573ad1606SSean Christopherson 		WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
37264a38162eSPaolo Bonzini 		r = -EIO;
37274a38162eSPaolo Bonzini 		goto out_unlock;
372873ad1606SSean Christopherson 	}
37293651c7fcSSean Christopherson 
3730b9e5603cSPaolo Bonzini 	/* root.pgd is ignored for direct MMUs. */
3731b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
37324a38162eSPaolo Bonzini out_unlock:
37334a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
37344a38162eSPaolo Bonzini 	return r;
3735c50d8ae3SPaolo Bonzini }
3736c50d8ae3SPaolo Bonzini 
37371e76a3ceSDavid Stevens static int mmu_first_shadow_root_alloc(struct kvm *kvm)
37381e76a3ceSDavid Stevens {
37391e76a3ceSDavid Stevens 	struct kvm_memslots *slots;
37401e76a3ceSDavid Stevens 	struct kvm_memory_slot *slot;
3741a54d8066SMaciej S. Szmigiero 	int r = 0, i, bkt;
37421e76a3ceSDavid Stevens 
37431e76a3ceSDavid Stevens 	/*
37441e76a3ceSDavid Stevens 	 * Check if this is the first shadow root being allocated before
37451e76a3ceSDavid Stevens 	 * taking the lock.
37461e76a3ceSDavid Stevens 	 */
37471e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
37481e76a3ceSDavid Stevens 		return 0;
37491e76a3ceSDavid Stevens 
37501e76a3ceSDavid Stevens 	mutex_lock(&kvm->slots_arch_lock);
37511e76a3ceSDavid Stevens 
37521e76a3ceSDavid Stevens 	/* Recheck, under the lock, whether this is the first shadow root. */
37531e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
37541e76a3ceSDavid Stevens 		goto out_unlock;
37551e76a3ceSDavid Stevens 
37561e76a3ceSDavid Stevens 	/*
37571e76a3ceSDavid Stevens 	 * Check if anything actually needs to be allocated, e.g. all metadata
37581e76a3ceSDavid Stevens 	 * will be allocated upfront if TDP is disabled.
37591e76a3ceSDavid Stevens 	 */
37601e76a3ceSDavid Stevens 	if (kvm_memslots_have_rmaps(kvm) &&
37611e76a3ceSDavid Stevens 	    kvm_page_track_write_tracking_enabled(kvm))
37621e76a3ceSDavid Stevens 		goto out_success;
37631e76a3ceSDavid Stevens 
3764eed52e43SSean Christopherson 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
37651e76a3ceSDavid Stevens 		slots = __kvm_memslots(kvm, i);
3766a54d8066SMaciej S. Szmigiero 		kvm_for_each_memslot(slot, bkt, slots) {
37671e76a3ceSDavid Stevens 			/*
37681e76a3ceSDavid Stevens 			 * Both of these functions are no-ops if the target is
37691e76a3ceSDavid Stevens 			 * already allocated, so unconditionally calling both
37701e76a3ceSDavid Stevens 			 * is safe.  Intentionally do NOT free allocations on
37711e76a3ceSDavid Stevens 			 * failure to avoid having to track which allocations
37721e76a3ceSDavid Stevens 			 * were made now versus when the memslot was created.
37731e76a3ceSDavid Stevens 			 * The metadata is guaranteed to be freed when the slot
37741e76a3ceSDavid Stevens 			 * is freed, and will be kept/used if userspace retries
37751e76a3ceSDavid Stevens 			 * KVM_RUN instead of killing the VM.
37761e76a3ceSDavid Stevens 			 */
37771e76a3ceSDavid Stevens 			r = memslot_rmap_alloc(slot, slot->npages);
37781e76a3ceSDavid Stevens 			if (r)
37791e76a3ceSDavid Stevens 				goto out_unlock;
37801e76a3ceSDavid Stevens 			r = kvm_page_track_write_tracking_alloc(slot);
37811e76a3ceSDavid Stevens 			if (r)
37821e76a3ceSDavid Stevens 				goto out_unlock;
37831e76a3ceSDavid Stevens 		}
37841e76a3ceSDavid Stevens 	}
37851e76a3ceSDavid Stevens 
37861e76a3ceSDavid Stevens 	/*
37871e76a3ceSDavid Stevens 	 * Ensure that shadow_root_allocated becomes true strictly after
37881e76a3ceSDavid Stevens 	 * all the related pointers are set.
37891e76a3ceSDavid Stevens 	 */
37901e76a3ceSDavid Stevens out_success:
37911e76a3ceSDavid Stevens 	smp_store_release(&kvm->arch.shadow_root_allocated, true);
37921e76a3ceSDavid Stevens 
37931e76a3ceSDavid Stevens out_unlock:
37941e76a3ceSDavid Stevens 	mutex_unlock(&kvm->slots_arch_lock);
37951e76a3ceSDavid Stevens 	return r;
37961e76a3ceSDavid Stevens }
37971e76a3ceSDavid Stevens 
3798c50d8ae3SPaolo Bonzini static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3799c50d8ae3SPaolo Bonzini {
3800b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
38016e0918aeSSean Christopherson 	u64 pdptrs[4], pm_mask;
3802be01e8e2SSean Christopherson 	gfn_t root_gfn, root_pgd;
38037f497775SDavid Matlack 	int quadrant, i, r;
38048123f265SSean Christopherson 	hpa_t root;
3805c50d8ae3SPaolo Bonzini 
38062fdcc1b3SPaolo Bonzini 	root_pgd = kvm_mmu_get_guest_pgd(vcpu, mmu);
3807a130066fSBinbin Wu 	root_gfn = (root_pgd & __PT_BASE_ADDR_MASK) >> PAGE_SHIFT;
3808c50d8ae3SPaolo Bonzini 
38090e3223d8SSean Christopherson 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
38100e3223d8SSean Christopherson 		mmu->root.hpa = kvm_mmu_get_dummy_root();
38110e3223d8SSean Christopherson 		return 0;
38120e3223d8SSean Christopherson 	}
3813c50d8ae3SPaolo Bonzini 
3814c50d8ae3SPaolo Bonzini 	/*
38154a38162eSPaolo Bonzini 	 * On SVM, reading PDPTRs might access guest memory, which might fault
38164a38162eSPaolo Bonzini 	 * and thus might sleep.  Grab the PDPTRs before acquiring mmu_lock.
38174a38162eSPaolo Bonzini 	 */
38184d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
38196e0918aeSSean Christopherson 		for (i = 0; i < 4; ++i) {
38206e0918aeSSean Christopherson 			pdptrs[i] = mmu->get_pdptr(vcpu, i);
38216e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK))
38226e0918aeSSean Christopherson 				continue;
38236e0918aeSSean Christopherson 
38240e3223d8SSean Christopherson 			if (!kvm_vcpu_is_visible_gfn(vcpu, pdptrs[i] >> PAGE_SHIFT))
38250e3223d8SSean Christopherson 				pdptrs[i] = 0;
38266e0918aeSSean Christopherson 		}
38276e0918aeSSean Christopherson 	}
38286e0918aeSSean Christopherson 
38291e76a3ceSDavid Stevens 	r = mmu_first_shadow_root_alloc(vcpu->kvm);
3830d501f747SBen Gardon 	if (r)
3831d501f747SBen Gardon 		return r;
3832d501f747SBen Gardon 
38334a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
38344a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
38354a38162eSPaolo Bonzini 	if (r < 0)
38364a38162eSPaolo Bonzini 		goto out_unlock;
38374a38162eSPaolo Bonzini 
3838c50d8ae3SPaolo Bonzini 	/*
3839c50d8ae3SPaolo Bonzini 	 * Do we shadow a long mode page table? If so we need to
3840c50d8ae3SPaolo Bonzini 	 * write-protect the guests page table root.
3841c50d8ae3SPaolo Bonzini 	 */
38424d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
38438123f265SSean Christopherson 		root = mmu_alloc_root(vcpu, root_gfn, 0,
384486938ab6SDavid Matlack 				      mmu->root_role.level);
3845b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
3846be01e8e2SSean Christopherson 		goto set_root_pgd;
3847c50d8ae3SPaolo Bonzini 	}
3848c50d8ae3SPaolo Bonzini 
38494a38162eSPaolo Bonzini 	if (WARN_ON_ONCE(!mmu->pae_root)) {
38504a38162eSPaolo Bonzini 		r = -EIO;
38514a38162eSPaolo Bonzini 		goto out_unlock;
38524a38162eSPaolo Bonzini 	}
385373ad1606SSean Christopherson 
3854c50d8ae3SPaolo Bonzini 	/*
3855c50d8ae3SPaolo Bonzini 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3856c50d8ae3SPaolo Bonzini 	 * or a PAE 3-level page table. In either case we need to be aware that
3857c50d8ae3SPaolo Bonzini 	 * the shadow page table may be a PAE or a long mode page table.
3858c50d8ae3SPaolo Bonzini 	 */
3859e54f1ff2SKai Huang 	pm_mask = PT_PRESENT_MASK | shadow_me_value;
3860a972e29cSPaolo Bonzini 	if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3861c50d8ae3SPaolo Bonzini 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3862c50d8ae3SPaolo Bonzini 
386303ca4589SSean Christopherson 		if (WARN_ON_ONCE(!mmu->pml4_root)) {
38644a38162eSPaolo Bonzini 			r = -EIO;
38654a38162eSPaolo Bonzini 			goto out_unlock;
38664a38162eSPaolo Bonzini 		}
386703ca4589SSean Christopherson 		mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3868cb0f722aSWei Huang 
3869a972e29cSPaolo Bonzini 		if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3870cb0f722aSWei Huang 			if (WARN_ON_ONCE(!mmu->pml5_root)) {
3871cb0f722aSWei Huang 				r = -EIO;
3872cb0f722aSWei Huang 				goto out_unlock;
3873cb0f722aSWei Huang 			}
3874cb0f722aSWei Huang 			mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3875cb0f722aSWei Huang 		}
387604d45551SSean Christopherson 	}
387704d45551SSean Christopherson 
3878c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3879c834e5e4SSean Christopherson 		WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
38806e6ec584SSean Christopherson 
38814d25502aSPaolo Bonzini 		if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
38826e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3883c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3884c50d8ae3SPaolo Bonzini 				continue;
3885c50d8ae3SPaolo Bonzini 			}
38866e0918aeSSean Christopherson 			root_gfn = pdptrs[i] >> PAGE_SHIFT;
3887c50d8ae3SPaolo Bonzini 		}
3888c50d8ae3SPaolo Bonzini 
38897f497775SDavid Matlack 		/*
38907f497775SDavid Matlack 		 * If shadowing 32-bit non-PAE page tables, each PAE page
38917f497775SDavid Matlack 		 * directory maps one quarter of the guest's non-PAE page
38927f497775SDavid Matlack 		 * directory. Othwerise each PAE page direct shadows one guest
38937f497775SDavid Matlack 		 * PAE page directory so that quadrant should be 0.
38947f497775SDavid Matlack 		 */
38957f497775SDavid Matlack 		quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
38967f497775SDavid Matlack 
38977f497775SDavid Matlack 		root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3898b37233c9SSean Christopherson 		mmu->pae_root[i] = root | pm_mask;
3899c50d8ae3SPaolo Bonzini 	}
3900c50d8ae3SPaolo Bonzini 
3901a972e29cSPaolo Bonzini 	if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3902b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml5_root);
3903a972e29cSPaolo Bonzini 	else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3904b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml4_root);
3905ba0a194fSSean Christopherson 	else
3906b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
3907c50d8ae3SPaolo Bonzini 
3908be01e8e2SSean Christopherson set_root_pgd:
3909b9e5603cSPaolo Bonzini 	mmu->root.pgd = root_pgd;
39104a38162eSPaolo Bonzini out_unlock:
39114a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
3912c50d8ae3SPaolo Bonzini 
3913c6c937d6SLike Xu 	return r;
3914c50d8ae3SPaolo Bonzini }
3915c50d8ae3SPaolo Bonzini 
3916748e52b9SSean Christopherson static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3917c50d8ae3SPaolo Bonzini {
3918748e52b9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3919a972e29cSPaolo Bonzini 	bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3920cb0f722aSWei Huang 	u64 *pml5_root = NULL;
3921cb0f722aSWei Huang 	u64 *pml4_root = NULL;
3922cb0f722aSWei Huang 	u64 *pae_root;
3923748e52b9SSean Christopherson 
3924748e52b9SSean Christopherson 	/*
3925748e52b9SSean Christopherson 	 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3926748e52b9SSean Christopherson 	 * tables are allocated and initialized at root creation as there is no
3927748e52b9SSean Christopherson 	 * equivalent level in the guest's NPT to shadow.  Allocate the tables
3928748e52b9SSean Christopherson 	 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3929748e52b9SSean Christopherson 	 */
3930347a0d0dSPaolo Bonzini 	if (mmu->root_role.direct ||
3931347a0d0dSPaolo Bonzini 	    mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3932a972e29cSPaolo Bonzini 	    mmu->root_role.level < PT64_ROOT_4LEVEL)
3933748e52b9SSean Christopherson 		return 0;
3934748e52b9SSean Christopherson 
3935a717a780SSean Christopherson 	/*
3936a717a780SSean Christopherson 	 * NPT, the only paging mode that uses this horror, uses a fixed number
3937a717a780SSean Christopherson 	 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3938a717a780SSean Christopherson 	 * all MMus are 5-level.  Thus, this can safely require that pml5_root
3939a717a780SSean Christopherson 	 * is allocated if the other roots are valid and pml5 is needed, as any
3940a717a780SSean Christopherson 	 * prior MMU would also have required pml5.
3941a717a780SSean Christopherson 	 */
3942a717a780SSean Christopherson 	if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3943748e52b9SSean Christopherson 		return 0;
3944748e52b9SSean Christopherson 
3945748e52b9SSean Christopherson 	/*
3946748e52b9SSean Christopherson 	 * The special roots should always be allocated in concert.  Yell and
3947748e52b9SSean Christopherson 	 * bail if KVM ends up in a state where only one of the roots is valid.
3948748e52b9SSean Christopherson 	 */
3949cb0f722aSWei Huang 	if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3950a717a780SSean Christopherson 			 (need_pml5 && mmu->pml5_root)))
3951748e52b9SSean Christopherson 		return -EIO;
3952748e52b9SSean Christopherson 
39534a98623dSSean Christopherson 	/*
39544a98623dSSean Christopherson 	 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
39554a98623dSSean Christopherson 	 * doesn't need to be decrypted.
39564a98623dSSean Christopherson 	 */
3957748e52b9SSean Christopherson 	pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3958748e52b9SSean Christopherson 	if (!pae_root)
3959748e52b9SSean Christopherson 		return -ENOMEM;
3960748e52b9SSean Christopherson 
3961cb0f722aSWei Huang #ifdef CONFIG_X86_64
396203ca4589SSean Christopherson 	pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3963cb0f722aSWei Huang 	if (!pml4_root)
3964cb0f722aSWei Huang 		goto err_pml4;
3965cb0f722aSWei Huang 
3966a717a780SSean Christopherson 	if (need_pml5) {
3967cb0f722aSWei Huang 		pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3968cb0f722aSWei Huang 		if (!pml5_root)
3969cb0f722aSWei Huang 			goto err_pml5;
3970748e52b9SSean Christopherson 	}
3971cb0f722aSWei Huang #endif
3972748e52b9SSean Christopherson 
3973748e52b9SSean Christopherson 	mmu->pae_root = pae_root;
397403ca4589SSean Christopherson 	mmu->pml4_root = pml4_root;
3975cb0f722aSWei Huang 	mmu->pml5_root = pml5_root;
3976748e52b9SSean Christopherson 
3977748e52b9SSean Christopherson 	return 0;
3978cb0f722aSWei Huang 
3979cb0f722aSWei Huang #ifdef CONFIG_X86_64
3980cb0f722aSWei Huang err_pml5:
3981cb0f722aSWei Huang 	free_page((unsigned long)pml4_root);
3982cb0f722aSWei Huang err_pml4:
3983cb0f722aSWei Huang 	free_page((unsigned long)pae_root);
3984cb0f722aSWei Huang 	return -ENOMEM;
3985cb0f722aSWei Huang #endif
3986c50d8ae3SPaolo Bonzini }
3987c50d8ae3SPaolo Bonzini 
3988264d3dc1SLai Jiangshan static bool is_unsync_root(hpa_t root)
3989264d3dc1SLai Jiangshan {
3990264d3dc1SLai Jiangshan 	struct kvm_mmu_page *sp;
3991264d3dc1SLai Jiangshan 
39920e3223d8SSean Christopherson 	if (!VALID_PAGE(root) || kvm_mmu_is_dummy_root(root))
399361b05a9fSLai Jiangshan 		return false;
399461b05a9fSLai Jiangshan 
3995264d3dc1SLai Jiangshan 	/*
3996264d3dc1SLai Jiangshan 	 * The read barrier orders the CPU's read of SPTE.W during the page table
3997264d3dc1SLai Jiangshan 	 * walk before the reads of sp->unsync/sp->unsync_children here.
3998264d3dc1SLai Jiangshan 	 *
3999264d3dc1SLai Jiangshan 	 * Even if another CPU was marking the SP as unsync-ed simultaneously,
4000264d3dc1SLai Jiangshan 	 * any guest page table changes are not guaranteed to be visible anyway
4001264d3dc1SLai Jiangshan 	 * until this VCPU issues a TLB flush strictly after those changes are
4002264d3dc1SLai Jiangshan 	 * made.  We only need to ensure that the other CPU sets these flags
4003264d3dc1SLai Jiangshan 	 * before any actual changes to the page tables are made.  The comments
4004264d3dc1SLai Jiangshan 	 * in mmu_try_to_unsync_pages() describe what could go wrong if this
4005264d3dc1SLai Jiangshan 	 * requirement isn't satisfied.
4006264d3dc1SLai Jiangshan 	 */
4007264d3dc1SLai Jiangshan 	smp_rmb();
4008c5f2d564SSean Christopherson 	sp = root_to_sp(root);
40095d6a3221SSean Christopherson 
40105d6a3221SSean Christopherson 	/*
40115d6a3221SSean Christopherson 	 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
40125d6a3221SSean Christopherson 	 * PDPTEs for a given PAE root need to be synchronized individually.
40135d6a3221SSean Christopherson 	 */
40145d6a3221SSean Christopherson 	if (WARN_ON_ONCE(!sp))
40155d6a3221SSean Christopherson 		return false;
40165d6a3221SSean Christopherson 
4017264d3dc1SLai Jiangshan 	if (sp->unsync || sp->unsync_children)
4018264d3dc1SLai Jiangshan 		return true;
4019264d3dc1SLai Jiangshan 
4020264d3dc1SLai Jiangshan 	return false;
4021264d3dc1SLai Jiangshan }
4022264d3dc1SLai Jiangshan 
4023c50d8ae3SPaolo Bonzini void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
4024c50d8ae3SPaolo Bonzini {
4025c50d8ae3SPaolo Bonzini 	int i;
4026c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
4027c50d8ae3SPaolo Bonzini 
4028347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
4029c50d8ae3SPaolo Bonzini 		return;
4030c50d8ae3SPaolo Bonzini 
4031b9e5603cSPaolo Bonzini 	if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
4032c50d8ae3SPaolo Bonzini 		return;
4033c50d8ae3SPaolo Bonzini 
4034c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4035c50d8ae3SPaolo Bonzini 
40364d25502aSPaolo Bonzini 	if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
4037b9e5603cSPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->root.hpa;
4038c50d8ae3SPaolo Bonzini 
4039264d3dc1SLai Jiangshan 		if (!is_unsync_root(root))
4040c50d8ae3SPaolo Bonzini 			return;
4041c50d8ae3SPaolo Bonzini 
4042c5f2d564SSean Christopherson 		sp = root_to_sp(root);
4043c5f2d564SSean Christopherson 
4044531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
404565855ed8SLai Jiangshan 		mmu_sync_children(vcpu, sp, true);
4046531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
4047c50d8ae3SPaolo Bonzini 		return;
4048c50d8ae3SPaolo Bonzini 	}
4049c50d8ae3SPaolo Bonzini 
4050531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
4051c50d8ae3SPaolo Bonzini 
4052c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
4053c50d8ae3SPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->pae_root[i];
4054c50d8ae3SPaolo Bonzini 
4055c834e5e4SSean Christopherson 		if (IS_VALID_PAE_ROOT(root)) {
40565e3edd7eSSean Christopherson 			sp = spte_to_child_sp(root);
405765855ed8SLai Jiangshan 			mmu_sync_children(vcpu, sp, true);
4058c50d8ae3SPaolo Bonzini 		}
4059c50d8ae3SPaolo Bonzini 	}
4060c50d8ae3SPaolo Bonzini 
4061531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
4062c50d8ae3SPaolo Bonzini }
4063c50d8ae3SPaolo Bonzini 
406461b05a9fSLai Jiangshan void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
406561b05a9fSLai Jiangshan {
406661b05a9fSLai Jiangshan 	unsigned long roots_to_free = 0;
406761b05a9fSLai Jiangshan 	int i;
406861b05a9fSLai Jiangshan 
406961b05a9fSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
407061b05a9fSLai Jiangshan 		if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
407161b05a9fSLai Jiangshan 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
407261b05a9fSLai Jiangshan 
407361b05a9fSLai Jiangshan 	/* sync prev_roots by simply freeing them */
40740c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
407561b05a9fSLai Jiangshan }
407661b05a9fSLai Jiangshan 
40771f5a21eeSLai Jiangshan static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
40785b22bbe7SLai Jiangshan 				  gpa_t vaddr, u64 access,
4079c50d8ae3SPaolo Bonzini 				  struct x86_exception *exception)
4080c50d8ae3SPaolo Bonzini {
4081c50d8ae3SPaolo Bonzini 	if (exception)
4082c50d8ae3SPaolo Bonzini 		exception->error_code = 0;
4083c59a0f57SLai Jiangshan 	return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
4084c50d8ae3SPaolo Bonzini }
4085c50d8ae3SPaolo Bonzini 
4086c50d8ae3SPaolo Bonzini static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4087c50d8ae3SPaolo Bonzini {
4088c50d8ae3SPaolo Bonzini 	/*
4089c50d8ae3SPaolo Bonzini 	 * A nested guest cannot use the MMIO cache if it is using nested
4090c50d8ae3SPaolo Bonzini 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4091c50d8ae3SPaolo Bonzini 	 */
4092c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
4093c50d8ae3SPaolo Bonzini 		return false;
4094c50d8ae3SPaolo Bonzini 
4095c50d8ae3SPaolo Bonzini 	if (direct)
4096c50d8ae3SPaolo Bonzini 		return vcpu_match_mmio_gpa(vcpu, addr);
4097c50d8ae3SPaolo Bonzini 
4098c50d8ae3SPaolo Bonzini 	return vcpu_match_mmio_gva(vcpu, addr);
4099c50d8ae3SPaolo Bonzini }
4100c50d8ae3SPaolo Bonzini 
410195fb5b02SBen Gardon /*
410295fb5b02SBen Gardon  * Return the level of the lowest level SPTE added to sptes.
410395fb5b02SBen Gardon  * That SPTE may be non-present.
4104c5c8c7c5SDavid Matlack  *
4105c5c8c7c5SDavid Matlack  * Must be called between walk_shadow_page_lockless_{begin,end}.
410695fb5b02SBen Gardon  */
410739b4d43eSSean Christopherson static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4108c50d8ae3SPaolo Bonzini {
4109c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
41102aa07893SSean Christopherson 	int leaf = -1;
411195fb5b02SBen Gardon 	u64 spte;
4112c50d8ae3SPaolo Bonzini 
411339b4d43eSSean Christopherson 	for (shadow_walk_init(&iterator, vcpu, addr),
411439b4d43eSSean Christopherson 	     *root_level = iterator.level;
4115c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&iterator);
4116c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&iterator, spte)) {
411795fb5b02SBen Gardon 		leaf = iterator.level;
4118c50d8ae3SPaolo Bonzini 		spte = mmu_spte_get_lockless(iterator.sptep);
4119c50d8ae3SPaolo Bonzini 
4120dde81f94SSean Christopherson 		sptes[leaf] = spte;
412195fb5b02SBen Gardon 	}
412295fb5b02SBen Gardon 
412395fb5b02SBen Gardon 	return leaf;
412495fb5b02SBen Gardon }
412595fb5b02SBen Gardon 
4126bca99c03SSean Christopherson static int get_sptes_lockless(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes,
4127bca99c03SSean Christopherson 			      int *root_level)
4128bca99c03SSean Christopherson {
4129bca99c03SSean Christopherson 	int leaf;
4130bca99c03SSean Christopherson 
4131bca99c03SSean Christopherson 	walk_shadow_page_lockless_begin(vcpu);
4132bca99c03SSean Christopherson 
4133bca99c03SSean Christopherson 	if (is_tdp_mmu_active(vcpu))
4134bca99c03SSean Christopherson 		leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, root_level);
4135bca99c03SSean Christopherson 	else
4136bca99c03SSean Christopherson 		leaf = get_walk(vcpu, addr, sptes, root_level);
4137bca99c03SSean Christopherson 
4138bca99c03SSean Christopherson 	walk_shadow_page_lockless_end(vcpu);
4139bca99c03SSean Christopherson 	return leaf;
4140bca99c03SSean Christopherson }
4141bca99c03SSean Christopherson 
41429aa41879SSean Christopherson /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
414395fb5b02SBen Gardon static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
414495fb5b02SBen Gardon {
4145dde81f94SSean Christopherson 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
414695fb5b02SBen Gardon 	struct rsvd_bits_validate *rsvd_check;
414739b4d43eSSean Christopherson 	int root, leaf, level;
414895fb5b02SBen Gardon 	bool reserved = false;
414995fb5b02SBen Gardon 
4150bca99c03SSean Christopherson 	leaf = get_sptes_lockless(vcpu, addr, sptes, &root);
41512aa07893SSean Christopherson 	if (unlikely(leaf < 0)) {
41522aa07893SSean Christopherson 		*sptep = 0ull;
41532aa07893SSean Christopherson 		return reserved;
41542aa07893SSean Christopherson 	}
41552aa07893SSean Christopherson 
41569aa41879SSean Christopherson 	*sptep = sptes[leaf];
41579aa41879SSean Christopherson 
41589aa41879SSean Christopherson 	/*
41599aa41879SSean Christopherson 	 * Skip reserved bits checks on the terminal leaf if it's not a valid
41609aa41879SSean Christopherson 	 * SPTE.  Note, this also (intentionally) skips MMIO SPTEs, which, by
41619aa41879SSean Christopherson 	 * design, always have reserved bits set.  The purpose of the checks is
41629aa41879SSean Christopherson 	 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
41639aa41879SSean Christopherson 	 */
41649aa41879SSean Christopherson 	if (!is_shadow_present_pte(sptes[leaf]))
41659aa41879SSean Christopherson 		leaf++;
416695fb5b02SBen Gardon 
416795fb5b02SBen Gardon 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
416895fb5b02SBen Gardon 
41699aa41879SSean Christopherson 	for (level = root; level >= leaf; level--)
4170961f8445SSean Christopherson 		reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4171c50d8ae3SPaolo Bonzini 
4172c50d8ae3SPaolo Bonzini 	if (reserved) {
4173bb4cdf3aSSean Christopherson 		pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4174c50d8ae3SPaolo Bonzini 		       __func__, addr);
417595fb5b02SBen Gardon 		for (level = root; level >= leaf; level--)
4176bb4cdf3aSSean Christopherson 			pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4177bb4cdf3aSSean Christopherson 			       sptes[level], level,
4178961f8445SSean Christopherson 			       get_rsvd_bits(rsvd_check, sptes[level], level));
4179c50d8ae3SPaolo Bonzini 	}
4180ddce6208SSean Christopherson 
4181c50d8ae3SPaolo Bonzini 	return reserved;
4182c50d8ae3SPaolo Bonzini }
4183c50d8ae3SPaolo Bonzini 
4184c50d8ae3SPaolo Bonzini static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4185c50d8ae3SPaolo Bonzini {
4186c50d8ae3SPaolo Bonzini 	u64 spte;
4187c50d8ae3SPaolo Bonzini 	bool reserved;
4188c50d8ae3SPaolo Bonzini 
4189c50d8ae3SPaolo Bonzini 	if (mmio_info_in_cache(vcpu, addr, direct))
4190c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4191c50d8ae3SPaolo Bonzini 
419295fb5b02SBen Gardon 	reserved = get_mmio_spte(vcpu, addr, &spte);
419320ba462dSSean Christopherson 	if (WARN_ON_ONCE(reserved))
4194c50d8ae3SPaolo Bonzini 		return -EINVAL;
4195c50d8ae3SPaolo Bonzini 
4196949019b9SSean Christopherson 	if (is_mmio_spte(vcpu->kvm, spte)) {
4197c50d8ae3SPaolo Bonzini 		gfn_t gfn = get_mmio_spte_gfn(spte);
41980a2b64c5SBen Gardon 		unsigned int access = get_mmio_spte_access(spte);
4199c50d8ae3SPaolo Bonzini 
4200c50d8ae3SPaolo Bonzini 		if (!check_mmio_spte(vcpu, spte))
4201c50d8ae3SPaolo Bonzini 			return RET_PF_INVALID;
4202c50d8ae3SPaolo Bonzini 
4203c50d8ae3SPaolo Bonzini 		if (direct)
4204c50d8ae3SPaolo Bonzini 			addr = 0;
4205c50d8ae3SPaolo Bonzini 
4206c50d8ae3SPaolo Bonzini 		trace_handle_mmio_page_fault(addr, gfn, access);
4207c50d8ae3SPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4208c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4209c50d8ae3SPaolo Bonzini 	}
4210c50d8ae3SPaolo Bonzini 
4211c50d8ae3SPaolo Bonzini 	/*
4212c50d8ae3SPaolo Bonzini 	 * If the page table is zapped by other cpus, let CPU fault again on
4213c50d8ae3SPaolo Bonzini 	 * the address.
4214c50d8ae3SPaolo Bonzini 	 */
4215c50d8ae3SPaolo Bonzini 	return RET_PF_RETRY;
4216c50d8ae3SPaolo Bonzini }
4217c50d8ae3SPaolo Bonzini 
4218c50d8ae3SPaolo Bonzini static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4219b8a5d551SPaolo Bonzini 					 struct kvm_page_fault *fault)
4220c50d8ae3SPaolo Bonzini {
4221b8a5d551SPaolo Bonzini 	if (unlikely(fault->rsvd))
4222c50d8ae3SPaolo Bonzini 		return false;
4223c50d8ae3SPaolo Bonzini 
4224b8a5d551SPaolo Bonzini 	if (!fault->present || !fault->write)
4225c50d8ae3SPaolo Bonzini 		return false;
4226c50d8ae3SPaolo Bonzini 
4227c50d8ae3SPaolo Bonzini 	/*
4228c50d8ae3SPaolo Bonzini 	 * guest is writing the page which is write tracked which can
4229c50d8ae3SPaolo Bonzini 	 * not be fixed by page fault handler.
4230c50d8ae3SPaolo Bonzini 	 */
42317b574863SSean Christopherson 	if (kvm_gfn_is_write_tracked(vcpu->kvm, fault->slot, fault->gfn))
4232c50d8ae3SPaolo Bonzini 		return true;
4233c50d8ae3SPaolo Bonzini 
4234c50d8ae3SPaolo Bonzini 	return false;
4235c50d8ae3SPaolo Bonzini }
4236c50d8ae3SPaolo Bonzini 
4237c50d8ae3SPaolo Bonzini static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4238c50d8ae3SPaolo Bonzini {
4239c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
4240c50d8ae3SPaolo Bonzini 	u64 spte;
4241c50d8ae3SPaolo Bonzini 
4242c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
42433e44dce4SLai Jiangshan 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4244c50d8ae3SPaolo Bonzini 		clear_sp_write_flooding_count(iterator.sptep);
4245c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
4246c50d8ae3SPaolo Bonzini }
4247c50d8ae3SPaolo Bonzini 
42486f3c1fc5SLiang Zhang static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
42496f3c1fc5SLiang Zhang {
42506f3c1fc5SLiang Zhang 	/* make sure the token value is not 0 */
42516f3c1fc5SLiang Zhang 	u32 id = vcpu->arch.apf.id;
42526f3c1fc5SLiang Zhang 
42536f3c1fc5SLiang Zhang 	if (id << 12 == 0)
42546f3c1fc5SLiang Zhang 		vcpu->arch.apf.id = 1;
42556f3c1fc5SLiang Zhang 
42566f3c1fc5SLiang Zhang 	return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
42576f3c1fc5SLiang Zhang }
42586f3c1fc5SLiang Zhang 
4259cd389f50SPaolo Bonzini static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu,
4260cd389f50SPaolo Bonzini 				    struct kvm_page_fault *fault)
4261c50d8ae3SPaolo Bonzini {
4262c50d8ae3SPaolo Bonzini 	struct kvm_arch_async_pf arch;
4263c50d8ae3SPaolo Bonzini 
42646f3c1fc5SLiang Zhang 	arch.token = alloc_apf_token(vcpu);
4265cd389f50SPaolo Bonzini 	arch.gfn = fault->gfn;
4266cd389f50SPaolo Bonzini 	arch.error_code = fault->error_code;
4267347a0d0dSPaolo Bonzini 	arch.direct_map = vcpu->arch.mmu->root_role.direct;
42682fdcc1b3SPaolo Bonzini 	arch.cr3 = kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu);
4269c50d8ae3SPaolo Bonzini 
4270cd389f50SPaolo Bonzini 	return kvm_setup_async_pf(vcpu, fault->addr,
4271cd389f50SPaolo Bonzini 				  kvm_vcpu_gfn_to_hva(vcpu, fault->gfn), &arch);
4272c50d8ae3SPaolo Bonzini }
4273c50d8ae3SPaolo Bonzini 
42748a009d5bSSean Christopherson void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
42758a009d5bSSean Christopherson {
42768a009d5bSSean Christopherson 	int r;
42778a009d5bSSean Christopherson 
4278cd389f50SPaolo Bonzini 	if (WARN_ON_ONCE(work->arch.error_code & PFERR_PRIVATE_ACCESS))
4279cd389f50SPaolo Bonzini 		return;
4280cd389f50SPaolo Bonzini 
42818a009d5bSSean Christopherson 	if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
42828a009d5bSSean Christopherson 	      work->wakeup_all)
42838a009d5bSSean Christopherson 		return;
42848a009d5bSSean Christopherson 
42858a009d5bSSean Christopherson 	r = kvm_mmu_reload(vcpu);
42868a009d5bSSean Christopherson 	if (unlikely(r))
42878a009d5bSSean Christopherson 		return;
42888a009d5bSSean Christopherson 
42898a009d5bSSean Christopherson 	if (!vcpu->arch.mmu->root_role.direct &&
42902fdcc1b3SPaolo Bonzini 	      work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
42918a009d5bSSean Christopherson 		return;
42928a009d5bSSean Christopherson 
4293f5e7f00cSSean Christopherson 	r = kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, work->arch.error_code,
429458ef2469SPaolo Bonzini 				  true, NULL, NULL);
4295f5e7f00cSSean Christopherson 
4296f5e7f00cSSean Christopherson 	/*
4297f5e7f00cSSean Christopherson 	 * Account fixed page faults, otherwise they'll never be counted, but
4298f5e7f00cSSean Christopherson 	 * ignore stats for all other return times.  Page-ready "faults" aren't
4299f5e7f00cSSean Christopherson 	 * truly spurious and never trigger emulation
4300f5e7f00cSSean Christopherson 	 */
4301f5e7f00cSSean Christopherson 	if (r == RET_PF_FIXED)
4302f5e7f00cSSean Christopherson 		vcpu->stat.pf_fixed++;
43038a009d5bSSean Christopherson }
43048a009d5bSSean Christopherson 
43058dd2eee9SChao Peng static inline u8 kvm_max_level_for_order(int order)
43068dd2eee9SChao Peng {
43078dd2eee9SChao Peng 	BUILD_BUG_ON(KVM_MAX_HUGEPAGE_LEVEL > PG_LEVEL_1G);
43088dd2eee9SChao Peng 
43098dd2eee9SChao Peng 	KVM_MMU_WARN_ON(order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G) &&
43108dd2eee9SChao Peng 			order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M) &&
43118dd2eee9SChao Peng 			order != KVM_HPAGE_GFN_SHIFT(PG_LEVEL_4K));
43128dd2eee9SChao Peng 
43138dd2eee9SChao Peng 	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_1G))
43148dd2eee9SChao Peng 		return PG_LEVEL_1G;
43158dd2eee9SChao Peng 
43168dd2eee9SChao Peng 	if (order >= KVM_HPAGE_GFN_SHIFT(PG_LEVEL_2M))
43178dd2eee9SChao Peng 		return PG_LEVEL_2M;
43188dd2eee9SChao Peng 
43198dd2eee9SChao Peng 	return PG_LEVEL_4K;
43208dd2eee9SChao Peng }
43218dd2eee9SChao Peng 
4322f32fb328SMichael Roth static u8 kvm_max_private_mapping_level(struct kvm *kvm, kvm_pfn_t pfn,
4323f32fb328SMichael Roth 					u8 max_level, int gmem_order)
4324f32fb328SMichael Roth {
4325f32fb328SMichael Roth 	u8 req_max_level;
4326f32fb328SMichael Roth 
4327f32fb328SMichael Roth 	if (max_level == PG_LEVEL_4K)
4328f32fb328SMichael Roth 		return PG_LEVEL_4K;
4329f32fb328SMichael Roth 
4330f32fb328SMichael Roth 	max_level = min(kvm_max_level_for_order(gmem_order), max_level);
4331f32fb328SMichael Roth 	if (max_level == PG_LEVEL_4K)
4332f32fb328SMichael Roth 		return PG_LEVEL_4K;
4333f32fb328SMichael Roth 
433489604647SWei Wang 	req_max_level = kvm_x86_call(private_max_mapping_level)(kvm, pfn);
4335f32fb328SMichael Roth 	if (req_max_level)
4336f32fb328SMichael Roth 		max_level = min(max_level, req_max_level);
4337f32fb328SMichael Roth 
4338aca0ec97SAckerley Tng 	return max_level;
4339f32fb328SMichael Roth }
4340f32fb328SMichael Roth 
43418dd2eee9SChao Peng static int kvm_faultin_pfn_private(struct kvm_vcpu *vcpu,
43428dd2eee9SChao Peng 				   struct kvm_page_fault *fault)
43438dd2eee9SChao Peng {
43448dd2eee9SChao Peng 	int max_order, r;
43458dd2eee9SChao Peng 
43468dd2eee9SChao Peng 	if (!kvm_slot_can_be_private(fault->slot)) {
43478dd2eee9SChao Peng 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
43488dd2eee9SChao Peng 		return -EFAULT;
43498dd2eee9SChao Peng 	}
43508dd2eee9SChao Peng 
43518dd2eee9SChao Peng 	r = kvm_gmem_get_pfn(vcpu->kvm, fault->slot, fault->gfn, &fault->pfn,
43528dd2eee9SChao Peng 			     &max_order);
43538dd2eee9SChao Peng 	if (r) {
43548dd2eee9SChao Peng 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
43558dd2eee9SChao Peng 		return r;
43568dd2eee9SChao Peng 	}
43578dd2eee9SChao Peng 
43588dd2eee9SChao Peng 	fault->map_writable = !(fault->slot->flags & KVM_MEM_READONLY);
4359f32fb328SMichael Roth 	fault->max_level = kvm_max_private_mapping_level(vcpu->kvm, fault->pfn,
4360f32fb328SMichael Roth 							 fault->max_level, max_order);
43618dd2eee9SChao Peng 
43628dd2eee9SChao Peng 	return RET_PF_CONTINUE;
43638dd2eee9SChao Peng }
43648dd2eee9SChao Peng 
4365ba6e3fe2SDavid Matlack static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4366c50d8ae3SPaolo Bonzini {
4367c50d8ae3SPaolo Bonzini 	bool async;
4368c50d8ae3SPaolo Bonzini 
43698dd2eee9SChao Peng 	if (fault->is_private)
43708dd2eee9SChao Peng 		return kvm_faultin_pfn_private(vcpu, fault);
43718dd2eee9SChao Peng 
4372c50d8ae3SPaolo Bonzini 	async = false;
4373cd272fc4SSean Christopherson 	fault->pfn = __gfn_to_pfn_memslot(fault->slot, fault->gfn, false, false,
4374cd272fc4SSean Christopherson 					  &async, fault->write,
4375cd272fc4SSean Christopherson 					  &fault->map_writable, &fault->hva);
4376c50d8ae3SPaolo Bonzini 	if (!async)
43775276c616SSean Christopherson 		return RET_PF_CONTINUE; /* *pfn has correct page already */
4378c50d8ae3SPaolo Bonzini 
43792839180cSPaolo Bonzini 	if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
43803647cd04SPaolo Bonzini 		trace_kvm_try_async_get_page(fault->addr, fault->gfn);
43813647cd04SPaolo Bonzini 		if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
43821685c0f3SMingwei Zhang 			trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4383c50d8ae3SPaolo Bonzini 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
43845276c616SSean Christopherson 			return RET_PF_RETRY;
4385cd272fc4SSean Christopherson 		} else if (kvm_arch_setup_async_pf(vcpu, fault)) {
43865276c616SSean Christopherson 			return RET_PF_RETRY;
43875276c616SSean Christopherson 		}
4388c50d8ae3SPaolo Bonzini 	}
4389c50d8ae3SPaolo Bonzini 
439076657687SPeter Xu 	/*
439176657687SPeter Xu 	 * Allow gup to bail on pending non-fatal signals when it's also allowed
439276657687SPeter Xu 	 * to wait for IO.  Note, gup always bails if it is unable to quickly
439376657687SPeter Xu 	 * get a page and a fatal signal, i.e. SIGKILL, is pending.
439476657687SPeter Xu 	 */
4395cd272fc4SSean Christopherson 	fault->pfn = __gfn_to_pfn_memslot(fault->slot, fault->gfn, false, true,
4396cd272fc4SSean Christopherson 					  NULL, fault->write,
4397cd272fc4SSean Christopherson 					  &fault->map_writable, &fault->hva);
43985276c616SSean Christopherson 	return RET_PF_CONTINUE;
4399c50d8ae3SPaolo Bonzini }
4400c50d8ae3SPaolo Bonzini 
4401354c908cSDavid Matlack static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
4402354c908cSDavid Matlack 			   unsigned int access)
4403ba6e3fe2SDavid Matlack {
4404cd272fc4SSean Christopherson 	struct kvm_memory_slot *slot = fault->slot;
440556c3a4e4SDavid Matlack 	int ret;
440656c3a4e4SDavid Matlack 
4407cd272fc4SSean Christopherson 	/*
4408cd272fc4SSean Christopherson 	 * Note that the mmu_invalidate_seq also serves to detect a concurrent
4409cd272fc4SSean Christopherson 	 * change in attributes.  is_page_fault_stale() will detect an
4410cd272fc4SSean Christopherson 	 * invalidation relate to fault->fn and resume the guest without
4411cd272fc4SSean Christopherson 	 * installing a mapping in the page tables.
4412cd272fc4SSean Christopherson 	 */
4413cd272fc4SSean Christopherson 	fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4414cd272fc4SSean Christopherson 	smp_rmb();
4415cd272fc4SSean Christopherson 
4416cd272fc4SSean Christopherson 	/*
4417cd272fc4SSean Christopherson 	 * Now that we have a snapshot of mmu_invalidate_seq we can check for a
4418cd272fc4SSean Christopherson 	 * private vs. shared mismatch.
4419cd272fc4SSean Christopherson 	 */
4420cd272fc4SSean Christopherson 	if (fault->is_private != kvm_mem_is_private(vcpu->kvm, fault->gfn)) {
4421cd272fc4SSean Christopherson 		kvm_mmu_prepare_memory_fault_exit(vcpu, fault);
4422cd272fc4SSean Christopherson 		return -EFAULT;
4423cd272fc4SSean Christopherson 	}
4424cd272fc4SSean Christopherson 
4425f6adeae8SSean Christopherson 	if (unlikely(!slot))
4426f6adeae8SSean Christopherson 		return kvm_handle_noslot_fault(vcpu, fault, access);
4427f6adeae8SSean Christopherson 
4428c50d8ae3SPaolo Bonzini 	/*
4429c50d8ae3SPaolo Bonzini 	 * Retry the page fault if the gfn hit a memslot that is being deleted
4430c50d8ae3SPaolo Bonzini 	 * or moved.  This ensures any existing SPTEs for the old memslot will
4431c50d8ae3SPaolo Bonzini 	 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4432c50d8ae3SPaolo Bonzini 	 */
4433f6adeae8SSean Christopherson 	if (slot->flags & KVM_MEMSLOT_INVALID)
4434c50d8ae3SPaolo Bonzini 		return RET_PF_RETRY;
4435c50d8ae3SPaolo Bonzini 
4436f6adeae8SSean Christopherson 	if (slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT) {
44375bd74f6eSSean Christopherson 		/*
44385bd74f6eSSean Christopherson 		 * Don't map L1's APIC access page into L2, KVM doesn't support
44395bd74f6eSSean Christopherson 		 * using APICv/AVIC to accelerate L2 accesses to L1's APIC,
44405bd74f6eSSean Christopherson 		 * i.e. the access needs to be emulated.  Emulating access to
44415bd74f6eSSean Christopherson 		 * L1's APIC is also correct if L1 is accelerating L2's own
44425bd74f6eSSean Christopherson 		 * virtual APIC, but for some reason L1 also maps _L1's_ APIC
44435bd74f6eSSean Christopherson 		 * into L2.  Note, vcpu_is_mmio_gpa() always treats access to
44445bd74f6eSSean Christopherson 		 * the APIC as MMIO.  Allow an MMIO SPTE to be created, as KVM
44455bd74f6eSSean Christopherson 		 * uses different roots for L1 vs. L2, i.e. there is no danger
44465bd74f6eSSean Christopherson 		 * of breaking APICv/AVIC for L1.
44475bd74f6eSSean Christopherson 		 */
4448f6adeae8SSean Christopherson 		if (is_guest_mode(vcpu))
4449f6adeae8SSean Christopherson 			return kvm_handle_noslot_fault(vcpu, fault, access);
4450f6adeae8SSean Christopherson 
4451c50d8ae3SPaolo Bonzini 		/*
4452c50d8ae3SPaolo Bonzini 		 * If the APIC access page exists but is disabled, go directly
4453c50d8ae3SPaolo Bonzini 		 * to emulation without caching the MMIO access or creating a
4454c50d8ae3SPaolo Bonzini 		 * MMIO SPTE.  That way the cache doesn't need to be purged
4455c50d8ae3SPaolo Bonzini 		 * when the AVIC is re-enabled.
4456c50d8ae3SPaolo Bonzini 		 */
44575bd74f6eSSean Christopherson 		if (!kvm_apicv_activated(vcpu->kvm))
4458c50d8ae3SPaolo Bonzini 			return RET_PF_EMULATE;
4459c50d8ae3SPaolo Bonzini 	}
4460c50d8ae3SPaolo Bonzini 
4461d02c357eSSean Christopherson 	/*
4462d02c357eSSean Christopherson 	 * Check for a relevant mmu_notifier invalidation event before getting
4463d02c357eSSean Christopherson 	 * the pfn from the primary MMU, and before acquiring mmu_lock.
4464d02c357eSSean Christopherson 	 *
4465d02c357eSSean Christopherson 	 * For mmu_lock, if there is an in-progress invalidation and the kernel
4466d02c357eSSean Christopherson 	 * allows preemption, the invalidation task may drop mmu_lock and yield
4467d02c357eSSean Christopherson 	 * in response to mmu_lock being contended, which is *very* counter-
4468d02c357eSSean Christopherson 	 * productive as this vCPU can't actually make forward progress until
4469d02c357eSSean Christopherson 	 * the invalidation completes.
4470d02c357eSSean Christopherson 	 *
4471d02c357eSSean Christopherson 	 * Retrying now can also avoid unnessary lock contention in the primary
4472d02c357eSSean Christopherson 	 * MMU, as the primary MMU doesn't necessarily hold a single lock for
4473d02c357eSSean Christopherson 	 * the duration of the invalidation, i.e. faulting in a conflicting pfn
4474d02c357eSSean Christopherson 	 * can cause the invalidation to take longer by holding locks that are
4475d02c357eSSean Christopherson 	 * needed to complete the invalidation.
4476d02c357eSSean Christopherson 	 *
4477d02c357eSSean Christopherson 	 * Do the pre-check even for non-preemtible kernels, i.e. even if KVM
4478d02c357eSSean Christopherson 	 * will never yield mmu_lock in response to contention, as this vCPU is
4479d02c357eSSean Christopherson 	 * *guaranteed* to need to retry, i.e. waiting until mmu_lock is held
4480d02c357eSSean Christopherson 	 * to detect retry guarantees the worst case latency for the vCPU.
4481d02c357eSSean Christopherson 	 */
4482f6adeae8SSean Christopherson 	if (mmu_invalidate_retry_gfn_unsafe(vcpu->kvm, fault->mmu_seq, fault->gfn))
4483d02c357eSSean Christopherson 		return RET_PF_RETRY;
4484d02c357eSSean Christopherson 
448556c3a4e4SDavid Matlack 	ret = __kvm_faultin_pfn(vcpu, fault);
448656c3a4e4SDavid Matlack 	if (ret != RET_PF_CONTINUE)
448756c3a4e4SDavid Matlack 		return ret;
448856c3a4e4SDavid Matlack 
448956c3a4e4SDavid Matlack 	if (unlikely(is_error_pfn(fault->pfn)))
4490cd08d178SDavid Matlack 		return kvm_handle_error_pfn(vcpu, fault);
449156c3a4e4SDavid Matlack 
44922b1f4355SSean Christopherson 	if (WARN_ON_ONCE(!fault->slot || is_noslot_pfn(fault->pfn)))
4493354c908cSDavid Matlack 		return kvm_handle_noslot_fault(vcpu, fault, access);
4494354c908cSDavid Matlack 
4495d02c357eSSean Christopherson 	/*
4496d02c357eSSean Christopherson 	 * Check again for a relevant mmu_notifier invalidation event purely to
4497d02c357eSSean Christopherson 	 * avoid contending mmu_lock.  Most invalidations will be detected by
4498d02c357eSSean Christopherson 	 * the previous check, but checking is extremely cheap relative to the
4499d02c357eSSean Christopherson 	 * overall cost of failing to detect the invalidation until after
4500d02c357eSSean Christopherson 	 * mmu_lock is acquired.
4501d02c357eSSean Christopherson 	 */
4502d02c357eSSean Christopherson 	if (mmu_invalidate_retry_gfn_unsafe(vcpu->kvm, fault->mmu_seq, fault->gfn)) {
4503d02c357eSSean Christopherson 		kvm_release_pfn_clean(fault->pfn);
4504d02c357eSSean Christopherson 		return RET_PF_RETRY;
4505d02c357eSSean Christopherson 	}
4506d02c357eSSean Christopherson 
450756c3a4e4SDavid Matlack 	return RET_PF_CONTINUE;
4508ba6e3fe2SDavid Matlack }
4509ba6e3fe2SDavid Matlack 
4510a955cad8SSean Christopherson /*
4511a955cad8SSean Christopherson  * Returns true if the page fault is stale and needs to be retried, i.e. if the
4512a955cad8SSean Christopherson  * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4513a955cad8SSean Christopherson  */
4514a955cad8SSean Christopherson static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4515ba6e3fe2SDavid Matlack 				struct kvm_page_fault *fault)
4516a955cad8SSean Christopherson {
4517c5f2d564SSean Christopherson 	struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
451818c841e1SSean Christopherson 
451918c841e1SSean Christopherson 	/* Special roots, e.g. pae_root, are not backed by shadow pages. */
452018c841e1SSean Christopherson 	if (sp && is_obsolete_sp(vcpu->kvm, sp))
452118c841e1SSean Christopherson 		return true;
452218c841e1SSean Christopherson 
452318c841e1SSean Christopherson 	/*
452418c841e1SSean Christopherson 	 * Roots without an associated shadow page are considered invalid if
452518c841e1SSean Christopherson 	 * there is a pending request to free obsolete roots.  The request is
452618c841e1SSean Christopherson 	 * only a hint that the current root _may_ be obsolete and needs to be
452718c841e1SSean Christopherson 	 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
452818c841e1SSean Christopherson 	 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
452918c841e1SSean Christopherson 	 * to reload even if no vCPU is actively using the root.
453018c841e1SSean Christopherson 	 */
4531527d5cd7SSean Christopherson 	if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4532a955cad8SSean Christopherson 		return true;
4533a955cad8SSean Christopherson 
4534d02c357eSSean Christopherson 	/*
4535d02c357eSSean Christopherson 	 * Check for a relevant mmu_notifier invalidation event one last time
4536d02c357eSSean Christopherson 	 * now that mmu_lock is held, as the "unsafe" checks performed without
4537d02c357eSSean Christopherson 	 * holding mmu_lock can get false negatives.
4538d02c357eSSean Christopherson 	 */
4539a955cad8SSean Christopherson 	return fault->slot &&
45408569992dSChao Peng 	       mmu_invalidate_retry_gfn(vcpu->kvm, fault->mmu_seq, fault->gfn);
4541a955cad8SSean Christopherson }
4542a955cad8SSean Christopherson 
45434326e57eSPaolo Bonzini static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4544c50d8ae3SPaolo Bonzini {
454583f06fa7SSean Christopherson 	int r;
4546c50d8ae3SPaolo Bonzini 
45470e3223d8SSean Christopherson 	/* Dummy roots are used only for shadowing bad guest roots. */
45480e3223d8SSean Christopherson 	if (WARN_ON_ONCE(kvm_mmu_is_dummy_root(vcpu->arch.mmu->root.hpa)))
45490e3223d8SSean Christopherson 		return RET_PF_RETRY;
45500e3223d8SSean Christopherson 
4551b8a5d551SPaolo Bonzini 	if (page_fault_handle_page_track(vcpu, fault))
4552c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4553c50d8ae3SPaolo Bonzini 
45543c8ad5a6SPaolo Bonzini 	r = fast_page_fault(vcpu, fault);
4555c4371c2aSSean Christopherson 	if (r != RET_PF_INVALID)
4556c4371c2aSSean Christopherson 		return r;
455783291445SSean Christopherson 
4558378f5cd6SSean Christopherson 	r = mmu_topup_memory_caches(vcpu, false);
4559c50d8ae3SPaolo Bonzini 	if (r)
4560c50d8ae3SPaolo Bonzini 		return r;
4561c50d8ae3SPaolo Bonzini 
4562354c908cSDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
45635276c616SSean Christopherson 	if (r != RET_PF_CONTINUE)
4564367fd790SSean Christopherson 		return r;
4565367fd790SSean Christopherson 
4566367fd790SSean Christopherson 	r = RET_PF_RETRY;
4567531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
4568a2855afcSBen Gardon 
4569ba6e3fe2SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
4570367fd790SSean Christopherson 		goto out_unlock;
4571a955cad8SSean Christopherson 
45727bd7ded6SSean Christopherson 	r = make_mmu_pages_available(vcpu);
45737bd7ded6SSean Christopherson 	if (r)
4574367fd790SSean Christopherson 		goto out_unlock;
4575bb18842eSBen Gardon 
45766c882ef4SDavid Matlack 	r = direct_map(vcpu, fault);
45770f90e1c1SSean Christopherson 
4578367fd790SSean Christopherson out_unlock:
4579531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
45803647cd04SPaolo Bonzini 	kvm_release_pfn_clean(fault->pfn);
4581367fd790SSean Christopherson 	return r;
4582c50d8ae3SPaolo Bonzini }
4583c50d8ae3SPaolo Bonzini 
4584c501040aSPaolo Bonzini static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4585c501040aSPaolo Bonzini 				struct kvm_page_fault *fault)
45860f90e1c1SSean Christopherson {
45870f90e1c1SSean Christopherson 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
45884326e57eSPaolo Bonzini 	fault->max_level = PG_LEVEL_2M;
45894326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
45900f90e1c1SSean Christopherson }
45910f90e1c1SSean Christopherson 
4592c50d8ae3SPaolo Bonzini int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4593c50d8ae3SPaolo Bonzini 				u64 fault_address, char *insn, int insn_len)
4594c50d8ae3SPaolo Bonzini {
4595c50d8ae3SPaolo Bonzini 	int r = 1;
45969ce372b3SVitaly Kuznetsov 	u32 flags = vcpu->arch.apf.host_apf_flags;
4597c50d8ae3SPaolo Bonzini 
4598736c291cSSean Christopherson #ifndef CONFIG_X86_64
4599736c291cSSean Christopherson 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4600736c291cSSean Christopherson 	if (WARN_ON_ONCE(fault_address >> 32))
4601736c291cSSean Christopherson 		return -EFAULT;
4602736c291cSSean Christopherson #endif
46037bdbb820SSean Christopherson 	/*
46047bdbb820SSean Christopherson 	 * Legacy #PF exception only have a 32-bit error code.  Simply drop the
46057bdbb820SSean Christopherson 	 * upper bits as KVM doesn't use them for #PF (because they are never
46067bdbb820SSean Christopherson 	 * set), and to ensure there are no collisions with KVM-defined bits.
46077bdbb820SSean Christopherson 	 */
46087bdbb820SSean Christopherson 	if (WARN_ON_ONCE(error_code >> 32))
46097bdbb820SSean Christopherson 		error_code = lower_32_bits(error_code);
4610736c291cSSean Christopherson 
4611caa72788SSean Christopherson 	/*
4612caa72788SSean Christopherson 	 * Restrict KVM-defined flags to bits 63:32 so that it's impossible for
4613caa72788SSean Christopherson 	 * them to conflict with #PF error codes, which are limited to 32 bits.
4614caa72788SSean Christopherson 	 */
4615dee281e4SSean Christopherson 	BUILD_BUG_ON(lower_32_bits(PFERR_SYNTHETIC_MASK));
4616c50d8ae3SPaolo Bonzini 
4617c50d8ae3SPaolo Bonzini 	vcpu->arch.l1tf_flush_l1d = true;
46189ce372b3SVitaly Kuznetsov 	if (!flags) {
4619faa03b39SWonhyuk Yang 		trace_kvm_page_fault(vcpu, fault_address, error_code);
4620c50d8ae3SPaolo Bonzini 
4621c50d8ae3SPaolo Bonzini 		if (kvm_event_needs_reinjection(vcpu))
4622c50d8ae3SPaolo Bonzini 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4623c50d8ae3SPaolo Bonzini 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4624c50d8ae3SPaolo Bonzini 				insn_len);
46259ce372b3SVitaly Kuznetsov 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
462668fd66f1SVitaly Kuznetsov 		vcpu->arch.apf.host_apf_flags = 0;
4627c50d8ae3SPaolo Bonzini 		local_irq_disable();
46286bca69adSThomas Gleixner 		kvm_async_pf_task_wait_schedule(fault_address);
4629c50d8ae3SPaolo Bonzini 		local_irq_enable();
46309ce372b3SVitaly Kuznetsov 	} else {
46319ce372b3SVitaly Kuznetsov 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4632c50d8ae3SPaolo Bonzini 	}
46339ce372b3SVitaly Kuznetsov 
4634c50d8ae3SPaolo Bonzini 	return r;
4635c50d8ae3SPaolo Bonzini }
4636c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4637c50d8ae3SPaolo Bonzini 
46389aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
46399aa8ab43SDavid Matlack static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
46409aa8ab43SDavid Matlack 				  struct kvm_page_fault *fault)
46419aa8ab43SDavid Matlack {
46429aa8ab43SDavid Matlack 	int r;
46439aa8ab43SDavid Matlack 
46449aa8ab43SDavid Matlack 	if (page_fault_handle_page_track(vcpu, fault))
46459aa8ab43SDavid Matlack 		return RET_PF_EMULATE;
46469aa8ab43SDavid Matlack 
46479aa8ab43SDavid Matlack 	r = fast_page_fault(vcpu, fault);
46489aa8ab43SDavid Matlack 	if (r != RET_PF_INVALID)
46499aa8ab43SDavid Matlack 		return r;
46509aa8ab43SDavid Matlack 
46519aa8ab43SDavid Matlack 	r = mmu_topup_memory_caches(vcpu, false);
46529aa8ab43SDavid Matlack 	if (r)
46539aa8ab43SDavid Matlack 		return r;
46549aa8ab43SDavid Matlack 
46559aa8ab43SDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
46569aa8ab43SDavid Matlack 	if (r != RET_PF_CONTINUE)
46579aa8ab43SDavid Matlack 		return r;
46589aa8ab43SDavid Matlack 
46599aa8ab43SDavid Matlack 	r = RET_PF_RETRY;
46609aa8ab43SDavid Matlack 	read_lock(&vcpu->kvm->mmu_lock);
46619aa8ab43SDavid Matlack 
46629aa8ab43SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
46639aa8ab43SDavid Matlack 		goto out_unlock;
46649aa8ab43SDavid Matlack 
46659aa8ab43SDavid Matlack 	r = kvm_tdp_mmu_map(vcpu, fault);
46669aa8ab43SDavid Matlack 
46679aa8ab43SDavid Matlack out_unlock:
46689aa8ab43SDavid Matlack 	read_unlock(&vcpu->kvm->mmu_lock);
46699aa8ab43SDavid Matlack 	kvm_release_pfn_clean(fault->pfn);
46709aa8ab43SDavid Matlack 	return r;
46719aa8ab43SDavid Matlack }
46729aa8ab43SDavid Matlack #endif
46739aa8ab43SDavid Matlack 
46740a7b7355SSean Christopherson bool kvm_mmu_may_ignore_guest_pat(void)
46751affe455SYan Zhao {
46761affe455SYan Zhao 	/*
4677*9d70f3feSPaolo Bonzini 	 * When EPT is enabled (shadow_memtype_mask is non-zero), and the VM
46780a7b7355SSean Christopherson 	 * has non-coherent DMA (DMA doesn't snoop CPU caches), KVM's ABI is to
46790a7b7355SSean Christopherson 	 * honor the memtype from the guest's PAT so that guest accesses to
46800a7b7355SSean Christopherson 	 * memory that is DMA'd aren't cached against the guest's wishes.  As a
46810a7b7355SSean Christopherson 	 * result, KVM _may_ ignore guest PAT, whereas without non-coherent DMA,
4682*9d70f3feSPaolo Bonzini 	 * KVM _always_ ignores guest PAT (when EPT is enabled).
46831affe455SYan Zhao 	 */
4684*9d70f3feSPaolo Bonzini 	return shadow_memtype_mask;
46851affe455SYan Zhao }
46861affe455SYan Zhao 
4687c501040aSPaolo Bonzini int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4688c50d8ae3SPaolo Bonzini {
46899aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
46909aa8ab43SDavid Matlack 	if (tdp_mmu_enabled)
46919aa8ab43SDavid Matlack 		return kvm_tdp_mmu_page_fault(vcpu, fault);
46929aa8ab43SDavid Matlack #endif
46939aa8ab43SDavid Matlack 
46944326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
4695c50d8ae3SPaolo Bonzini }
4696c50d8ae3SPaolo Bonzini 
46976e01b760SPaolo Bonzini static int kvm_tdp_map_page(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code,
46986e01b760SPaolo Bonzini 			    u8 *level)
46996e01b760SPaolo Bonzini {
47006e01b760SPaolo Bonzini 	int r;
47016e01b760SPaolo Bonzini 
47026e01b760SPaolo Bonzini 	/*
47036e01b760SPaolo Bonzini 	 * Restrict to TDP page fault, since that's the only case where the MMU
47046e01b760SPaolo Bonzini 	 * is indexed by GPA.
47056e01b760SPaolo Bonzini 	 */
47066e01b760SPaolo Bonzini 	if (vcpu->arch.mmu->page_fault != kvm_tdp_page_fault)
47076e01b760SPaolo Bonzini 		return -EOPNOTSUPP;
47086e01b760SPaolo Bonzini 
47096e01b760SPaolo Bonzini 	do {
47106e01b760SPaolo Bonzini 		if (signal_pending(current))
47116e01b760SPaolo Bonzini 			return -EINTR;
47126e01b760SPaolo Bonzini 		cond_resched();
47136e01b760SPaolo Bonzini 		r = kvm_mmu_do_page_fault(vcpu, gpa, error_code, true, NULL, level);
47146e01b760SPaolo Bonzini 	} while (r == RET_PF_RETRY);
47156e01b760SPaolo Bonzini 
47166e01b760SPaolo Bonzini 	if (r < 0)
47176e01b760SPaolo Bonzini 		return r;
47186e01b760SPaolo Bonzini 
47196e01b760SPaolo Bonzini 	switch (r) {
47206e01b760SPaolo Bonzini 	case RET_PF_FIXED:
47216e01b760SPaolo Bonzini 	case RET_PF_SPURIOUS:
47226e01b760SPaolo Bonzini 		return 0;
47236e01b760SPaolo Bonzini 
47246e01b760SPaolo Bonzini 	case RET_PF_EMULATE:
47256e01b760SPaolo Bonzini 		return -ENOENT;
47266e01b760SPaolo Bonzini 
47276e01b760SPaolo Bonzini 	case RET_PF_RETRY:
47286e01b760SPaolo Bonzini 	case RET_PF_CONTINUE:
47296e01b760SPaolo Bonzini 	case RET_PF_INVALID:
47306e01b760SPaolo Bonzini 	default:
47316e01b760SPaolo Bonzini 		WARN_ONCE(1, "could not fix page fault during prefault");
47326e01b760SPaolo Bonzini 		return -EIO;
47336e01b760SPaolo Bonzini 	}
47346e01b760SPaolo Bonzini }
47356e01b760SPaolo Bonzini 
47366e01b760SPaolo Bonzini long kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu,
47376e01b760SPaolo Bonzini 				    struct kvm_pre_fault_memory *range)
47386e01b760SPaolo Bonzini {
47396e01b760SPaolo Bonzini 	u64 error_code = PFERR_GUEST_FINAL_MASK;
47406e01b760SPaolo Bonzini 	u8 level = PG_LEVEL_4K;
47416e01b760SPaolo Bonzini 	u64 end;
47426e01b760SPaolo Bonzini 	int r;
47436e01b760SPaolo Bonzini 
47445932ca41SPaolo Bonzini 	if (!vcpu->kvm->arch.pre_fault_allowed)
47455932ca41SPaolo Bonzini 		return -EOPNOTSUPP;
47465932ca41SPaolo Bonzini 
47476e01b760SPaolo Bonzini 	/*
47486e01b760SPaolo Bonzini 	 * reload is efficient when called repeatedly, so we can do it on
47496e01b760SPaolo Bonzini 	 * every iteration.
47506e01b760SPaolo Bonzini 	 */
475128cec7f0SSean Christopherson 	r = kvm_mmu_reload(vcpu);
475228cec7f0SSean Christopherson 	if (r)
475328cec7f0SSean Christopherson 		return r;
47546e01b760SPaolo Bonzini 
47556e01b760SPaolo Bonzini 	if (kvm_arch_has_private_mem(vcpu->kvm) &&
47566e01b760SPaolo Bonzini 	    kvm_mem_is_private(vcpu->kvm, gpa_to_gfn(range->gpa)))
47576e01b760SPaolo Bonzini 		error_code |= PFERR_PRIVATE_ACCESS;
47586e01b760SPaolo Bonzini 
47596e01b760SPaolo Bonzini 	/*
47606e01b760SPaolo Bonzini 	 * Shadow paging uses GVA for kvm page fault, so restrict to
47616e01b760SPaolo Bonzini 	 * two-dimensional paging.
47626e01b760SPaolo Bonzini 	 */
47636e01b760SPaolo Bonzini 	r = kvm_tdp_map_page(vcpu, range->gpa, error_code, &level);
47646e01b760SPaolo Bonzini 	if (r < 0)
47656e01b760SPaolo Bonzini 		return r;
47666e01b760SPaolo Bonzini 
47676e01b760SPaolo Bonzini 	/*
47686e01b760SPaolo Bonzini 	 * If the mapping that covers range->gpa can use a huge page, it
47696e01b760SPaolo Bonzini 	 * may start below it or end after range->gpa + range->size.
47706e01b760SPaolo Bonzini 	 */
47716e01b760SPaolo Bonzini 	end = (range->gpa & KVM_HPAGE_MASK(level)) + KVM_HPAGE_SIZE(level);
47726e01b760SPaolo Bonzini 	return min(range->size, end - range->gpa);
47736e01b760SPaolo Bonzini }
47746e01b760SPaolo Bonzini 
477584a16226SSean Christopherson static void nonpaging_init_context(struct kvm_mmu *context)
4776c50d8ae3SPaolo Bonzini {
4777c50d8ae3SPaolo Bonzini 	context->page_fault = nonpaging_page_fault;
4778c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4779c3c6c9fcSLai Jiangshan 	context->sync_spte = NULL;
4780c50d8ae3SPaolo Bonzini }
4781c50d8ae3SPaolo Bonzini 
4782be01e8e2SSean Christopherson static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
47830be44352SSean Christopherson 				  union kvm_mmu_page_role role)
47840be44352SSean Christopherson {
4785c30e000eSSean Christopherson 	struct kvm_mmu_page *sp;
4786c30e000eSSean Christopherson 
4787c30e000eSSean Christopherson 	if (!VALID_PAGE(root->hpa))
4788c30e000eSSean Christopherson 		return false;
4789c30e000eSSean Christopherson 
4790c30e000eSSean Christopherson 	if (!role.direct && pgd != root->pgd)
4791c30e000eSSean Christopherson 		return false;
4792c30e000eSSean Christopherson 
4793c30e000eSSean Christopherson 	sp = root_to_sp(root->hpa);
4794c30e000eSSean Christopherson 	if (WARN_ON_ONCE(!sp))
4795c30e000eSSean Christopherson 		return false;
4796c30e000eSSean Christopherson 
4797c30e000eSSean Christopherson 	return role.word == sp->role.word;
47980be44352SSean Christopherson }
47990be44352SSean Christopherson 
4800c50d8ae3SPaolo Bonzini /*
48015499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available,
48025499ea73SPaolo Bonzini  * and insert the current root as the MRU in the cache.
48035499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root and
48045499ea73SPaolo Bonzini  * true is returned.
48055499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid, the LRU root is
48065499ea73SPaolo Bonzini  * evicted to make room for the current root, and false is returned.
4807c50d8ae3SPaolo Bonzini  */
48085499ea73SPaolo Bonzini static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
48095499ea73SPaolo Bonzini 					      gpa_t new_pgd,
4810c50d8ae3SPaolo Bonzini 					      union kvm_mmu_page_role new_role)
4811c50d8ae3SPaolo Bonzini {
4812c50d8ae3SPaolo Bonzini 	uint i;
4813c50d8ae3SPaolo Bonzini 
4814b9e5603cSPaolo Bonzini 	if (is_root_usable(&mmu->root, new_pgd, new_role))
48150be44352SSean Christopherson 		return true;
48160be44352SSean Christopherson 
4817c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
48185499ea73SPaolo Bonzini 		/*
48195499ea73SPaolo Bonzini 		 * The swaps end up rotating the cache like this:
48205499ea73SPaolo Bonzini 		 *   C   0 1 2 3   (on entry to the function)
48215499ea73SPaolo Bonzini 		 *   0   C 1 2 3
48225499ea73SPaolo Bonzini 		 *   1   C 0 2 3
48235499ea73SPaolo Bonzini 		 *   2   C 0 1 3
48245499ea73SPaolo Bonzini 		 *   3   C 0 1 2   (on exit from the loop)
48255499ea73SPaolo Bonzini 		 */
4826b9e5603cSPaolo Bonzini 		swap(mmu->root, mmu->prev_roots[i]);
4827b9e5603cSPaolo Bonzini 		if (is_root_usable(&mmu->root, new_pgd, new_role))
48285499ea73SPaolo Bonzini 			return true;
4829c50d8ae3SPaolo Bonzini 	}
4830c50d8ae3SPaolo Bonzini 
48315499ea73SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
48325499ea73SPaolo Bonzini 	return false;
4833c50d8ae3SPaolo Bonzini }
4834c50d8ae3SPaolo Bonzini 
4835c50d8ae3SPaolo Bonzini /*
48365499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available.
48375499ea73SPaolo Bonzini  * On entry, mmu->root is invalid.
48385499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
48395499ea73SPaolo Bonzini  * of the cache becomes invalid, and true is returned.
48405499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid and false is returned.
48415499ea73SPaolo Bonzini  */
48425499ea73SPaolo Bonzini static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
48435499ea73SPaolo Bonzini 					     gpa_t new_pgd,
48445499ea73SPaolo Bonzini 					     union kvm_mmu_page_role new_role)
48455499ea73SPaolo Bonzini {
48465499ea73SPaolo Bonzini 	uint i;
48475499ea73SPaolo Bonzini 
48485499ea73SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
48495499ea73SPaolo Bonzini 		if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
48505499ea73SPaolo Bonzini 			goto hit;
48515499ea73SPaolo Bonzini 
48525499ea73SPaolo Bonzini 	return false;
48535499ea73SPaolo Bonzini 
48545499ea73SPaolo Bonzini hit:
48555499ea73SPaolo Bonzini 	swap(mmu->root, mmu->prev_roots[i]);
48565499ea73SPaolo Bonzini 	/* Bubble up the remaining roots.  */
48575499ea73SPaolo Bonzini 	for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
48585499ea73SPaolo Bonzini 		mmu->prev_roots[i] = mmu->prev_roots[i + 1];
48595499ea73SPaolo Bonzini 	mmu->prev_roots[i].hpa = INVALID_PAGE;
48605499ea73SPaolo Bonzini 	return true;
48615499ea73SPaolo Bonzini }
48625499ea73SPaolo Bonzini 
48635499ea73SPaolo Bonzini static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
48645499ea73SPaolo Bonzini 			    gpa_t new_pgd, union kvm_mmu_page_role new_role)
48655499ea73SPaolo Bonzini {
48665499ea73SPaolo Bonzini 	/*
48670e3223d8SSean Christopherson 	 * Limit reuse to 64-bit hosts+VMs without "special" roots in order to
48680e3223d8SSean Christopherson 	 * avoid having to deal with PDPTEs and other complexities.
4869c50d8ae3SPaolo Bonzini 	 */
4870c5f2d564SSean Christopherson 	if (VALID_PAGE(mmu->root.hpa) && !root_to_sp(mmu->root.hpa))
48715499ea73SPaolo Bonzini 		kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4872c50d8ae3SPaolo Bonzini 
48735499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa))
48745499ea73SPaolo Bonzini 		return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
48755499ea73SPaolo Bonzini 	else
48765499ea73SPaolo Bonzini 		return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4877c50d8ae3SPaolo Bonzini }
4878c50d8ae3SPaolo Bonzini 
4879d2e5f333SPaolo Bonzini void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4880c50d8ae3SPaolo Bonzini {
48810c1c92f1SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
48827a458f0eSPaolo Bonzini 	union kvm_mmu_page_role new_role = mmu->root_role;
48830c1c92f1SPaolo Bonzini 
4884a7e48ef7SWei Liu 	/*
4885a7e48ef7SWei Liu 	 * Return immediately if no usable root was found, kvm_mmu_reload()
4886a7e48ef7SWei Liu 	 * will establish a valid root prior to the next VM-Enter.
4887a7e48ef7SWei Liu 	 */
4888a7e48ef7SWei Liu 	if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role))
4889b869855bSSean Christopherson 		return;
4890c50d8ae3SPaolo Bonzini 
4891c50d8ae3SPaolo Bonzini 	/*
4892b869855bSSean Christopherson 	 * It's possible that the cached previous root page is obsolete because
4893b869855bSSean Christopherson 	 * of a change in the MMU generation number. However, changing the
4894527d5cd7SSean Christopherson 	 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4895527d5cd7SSean Christopherson 	 * which will free the root set here and allocate a new one.
4896b869855bSSean Christopherson 	 */
4897b869855bSSean Christopherson 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4898b869855bSSean Christopherson 
4899b5129100SSean Christopherson 	if (force_flush_and_sync_on_reuse) {
4900b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4901b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4902b5129100SSean Christopherson 	}
4903b869855bSSean Christopherson 
4904b869855bSSean Christopherson 	/*
4905b869855bSSean Christopherson 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4906b869855bSSean Christopherson 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
4907b869855bSSean Christopherson 	 * valid. So clear any cached MMIO info even when we don't need to sync
4908b869855bSSean Christopherson 	 * the shadow page tables.
4909c50d8ae3SPaolo Bonzini 	 */
4910c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4911c50d8ae3SPaolo Bonzini 
4912daa5b6c1SBen Gardon 	/*
4913daa5b6c1SBen Gardon 	 * If this is a direct root page, it doesn't have a write flooding
4914daa5b6c1SBen Gardon 	 * count. Otherwise, clear the write flooding count.
4915daa5b6c1SBen Gardon 	 */
4916c30e000eSSean Christopherson 	if (!new_role.direct) {
4917c30e000eSSean Christopherson 		struct kvm_mmu_page *sp = root_to_sp(vcpu->arch.mmu->root.hpa);
4918c30e000eSSean Christopherson 
4919c30e000eSSean Christopherson 		if (!WARN_ON_ONCE(!sp))
4920c30e000eSSean Christopherson 			__clear_sp_write_flooding_count(sp);
4921c30e000eSSean Christopherson 	}
4922c50d8ae3SPaolo Bonzini }
4923be01e8e2SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4924c50d8ae3SPaolo Bonzini 
4925c50d8ae3SPaolo Bonzini static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4926c3e5e415SLai Jiangshan 			   unsigned int access)
4927c50d8ae3SPaolo Bonzini {
4928949019b9SSean Christopherson 	if (unlikely(is_mmio_spte(vcpu->kvm, *sptep))) {
4929c50d8ae3SPaolo Bonzini 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4930c50d8ae3SPaolo Bonzini 			mmu_spte_clear_no_track(sptep);
4931c50d8ae3SPaolo Bonzini 			return true;
4932c50d8ae3SPaolo Bonzini 		}
4933c50d8ae3SPaolo Bonzini 
4934c50d8ae3SPaolo Bonzini 		mark_mmio_spte(vcpu, sptep, gfn, access);
4935c50d8ae3SPaolo Bonzini 		return true;
4936c50d8ae3SPaolo Bonzini 	}
4937c50d8ae3SPaolo Bonzini 
4938c50d8ae3SPaolo Bonzini 	return false;
4939c50d8ae3SPaolo Bonzini }
4940c50d8ae3SPaolo Bonzini 
4941c50d8ae3SPaolo Bonzini #define PTTYPE_EPT 18 /* arbitrary */
4942c50d8ae3SPaolo Bonzini #define PTTYPE PTTYPE_EPT
4943c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4944c50d8ae3SPaolo Bonzini #undef PTTYPE
4945c50d8ae3SPaolo Bonzini 
4946c50d8ae3SPaolo Bonzini #define PTTYPE 64
4947c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4948c50d8ae3SPaolo Bonzini #undef PTTYPE
4949c50d8ae3SPaolo Bonzini 
4950c50d8ae3SPaolo Bonzini #define PTTYPE 32
4951c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4952c50d8ae3SPaolo Bonzini #undef PTTYPE
4953c50d8ae3SPaolo Bonzini 
4954f3d90f90SSean Christopherson static void __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
4955f3d90f90SSean Christopherson 				    u64 pa_bits_rsvd, int level, bool nx,
4956f3d90f90SSean Christopherson 				    bool gbpages, bool pse, bool amd)
4957c50d8ae3SPaolo Bonzini {
4958c50d8ae3SPaolo Bonzini 	u64 gbpages_bit_rsvd = 0;
4959c50d8ae3SPaolo Bonzini 	u64 nonleaf_bit8_rsvd = 0;
49605b7f575cSSean Christopherson 	u64 high_bits_rsvd;
4961c50d8ae3SPaolo Bonzini 
4962c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = 0;
4963c50d8ae3SPaolo Bonzini 
4964c50d8ae3SPaolo Bonzini 	if (!gbpages)
4965c50d8ae3SPaolo Bonzini 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4966c50d8ae3SPaolo Bonzini 
49675b7f575cSSean Christopherson 	if (level == PT32E_ROOT_LEVEL)
49685b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
49695b7f575cSSean Christopherson 	else
49705b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
49715b7f575cSSean Christopherson 
49725b7f575cSSean Christopherson 	/* Note, NX doesn't exist in PDPTEs, this is handled below. */
49735b7f575cSSean Christopherson 	if (!nx)
49745b7f575cSSean Christopherson 		high_bits_rsvd |= rsvd_bits(63, 63);
49755b7f575cSSean Christopherson 
4976c50d8ae3SPaolo Bonzini 	/*
4977c50d8ae3SPaolo Bonzini 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4978c50d8ae3SPaolo Bonzini 	 * leaf entries) on AMD CPUs only.
4979c50d8ae3SPaolo Bonzini 	 */
4980c50d8ae3SPaolo Bonzini 	if (amd)
4981c50d8ae3SPaolo Bonzini 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4982c50d8ae3SPaolo Bonzini 
4983c50d8ae3SPaolo Bonzini 	switch (level) {
4984c50d8ae3SPaolo Bonzini 	case PT32_ROOT_LEVEL:
4985c50d8ae3SPaolo Bonzini 		/* no rsvd bits for 2 level 4K page table entries */
4986c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4987c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4988c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4989c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4990c50d8ae3SPaolo Bonzini 
4991c50d8ae3SPaolo Bonzini 		if (!pse) {
4992c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4993c50d8ae3SPaolo Bonzini 			break;
4994c50d8ae3SPaolo Bonzini 		}
4995c50d8ae3SPaolo Bonzini 
4996c50d8ae3SPaolo Bonzini 		if (is_cpuid_PSE36())
4997c50d8ae3SPaolo Bonzini 			/* 36bits PSE 4MB page */
4998c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4999c50d8ae3SPaolo Bonzini 		else
5000c50d8ae3SPaolo Bonzini 			/* 32 bits PSE 4MB page */
5001c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
5002c50d8ae3SPaolo Bonzini 		break;
5003c50d8ae3SPaolo Bonzini 	case PT32E_ROOT_LEVEL:
50045b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
50055b7f575cSSean Christopherson 						   high_bits_rsvd |
50065b7f575cSSean Christopherson 						   rsvd_bits(5, 8) |
50075b7f575cSSean Christopherson 						   rsvd_bits(1, 2);	/* PDPTE */
50085b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;	/* PDE */
50095b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;	/* PTE */
50105b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
5011c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20);	/* large page */
5012c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
5013c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
5014c50d8ae3SPaolo Bonzini 		break;
5015c50d8ae3SPaolo Bonzini 	case PT64_ROOT_5LEVEL:
50165b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
50175b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
50185b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
5019c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][4] =
5020c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][4];
5021df561f66SGustavo A. R. Silva 		fallthrough;
5022c50d8ae3SPaolo Bonzini 	case PT64_ROOT_4LEVEL:
50235b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
50245b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
50255b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
50265b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
50275b7f575cSSean Christopherson 						   gbpages_bit_rsvd;
50285b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
50295b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
5030c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][3] =
5031c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][3];
50325b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
50335b7f575cSSean Christopherson 						   gbpages_bit_rsvd |
5034c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 29);
50355b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
5036c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20); /* large page */
5037c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
5038c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
5039c50d8ae3SPaolo Bonzini 		break;
5040c50d8ae3SPaolo Bonzini 	}
5041c50d8ae3SPaolo Bonzini }
5042c50d8ae3SPaolo Bonzini 
5043c919e881SKai Huang static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
5044c50d8ae3SPaolo Bonzini 					struct kvm_mmu *context)
5045c50d8ae3SPaolo Bonzini {
5046b705a277SSean Christopherson 	__reset_rsvds_bits_mask(&context->guest_rsvd_check,
50475b7f575cSSean Christopherson 				vcpu->arch.reserved_gpa_bits,
50484d25502aSPaolo Bonzini 				context->cpu_role.base.level, is_efer_nx(context),
5049ccf31d6eSSean Christopherson 				guest_can_use(vcpu, X86_FEATURE_GBPAGES),
50504e9c0d80SSean Christopherson 				is_cr4_pse(context),
5051fd706c9bSSean Christopherson 				guest_cpuid_is_amd_compatible(vcpu));
5052c50d8ae3SPaolo Bonzini }
5053c50d8ae3SPaolo Bonzini 
5054f3d90f90SSean Christopherson static void __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
5055f3d90f90SSean Christopherson 					u64 pa_bits_rsvd, bool execonly,
5056f3d90f90SSean Christopherson 					int huge_page_level)
5057c50d8ae3SPaolo Bonzini {
50585b7f575cSSean Christopherson 	u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
505984ea5c09SLai Jiangshan 	u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
5060c50d8ae3SPaolo Bonzini 	u64 bad_mt_xwr;
5061c50d8ae3SPaolo Bonzini 
506284ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_1G)
506384ea5c09SLai Jiangshan 		large_1g_rsvd = rsvd_bits(7, 7);
506484ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_2M)
506584ea5c09SLai Jiangshan 		large_2m_rsvd = rsvd_bits(7, 7);
506684ea5c09SLai Jiangshan 
50675b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
50685b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
506984ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
507084ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
50715b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
5072c50d8ae3SPaolo Bonzini 
5073c50d8ae3SPaolo Bonzini 	/* large page */
5074c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
5075c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
507684ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
507784ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
5078c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
5079c50d8ae3SPaolo Bonzini 
5080c50d8ae3SPaolo Bonzini 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
5081c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
5082c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
5083c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
5084c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
5085c50d8ae3SPaolo Bonzini 	if (!execonly) {
5086c50d8ae3SPaolo Bonzini 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
5087c50d8ae3SPaolo Bonzini 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
5088c50d8ae3SPaolo Bonzini 	}
5089c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
5090c50d8ae3SPaolo Bonzini }
5091c50d8ae3SPaolo Bonzini 
5092c50d8ae3SPaolo Bonzini static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
509384ea5c09SLai Jiangshan 		struct kvm_mmu *context, bool execonly, int huge_page_level)
5094c50d8ae3SPaolo Bonzini {
5095c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
509684ea5c09SLai Jiangshan 				    vcpu->arch.reserved_gpa_bits, execonly,
509784ea5c09SLai Jiangshan 				    huge_page_level);
5098c50d8ae3SPaolo Bonzini }
5099c50d8ae3SPaolo Bonzini 
51006f8e65a6SSean Christopherson static inline u64 reserved_hpa_bits(void)
51016f8e65a6SSean Christopherson {
510282897db9SSean Christopherson 	return rsvd_bits(kvm_host.maxphyaddr, 63);
51036f8e65a6SSean Christopherson }
51046f8e65a6SSean Christopherson 
5105c50d8ae3SPaolo Bonzini /*
5106c50d8ae3SPaolo Bonzini  * the page table on host is the shadow page table for the page
5107c50d8ae3SPaolo Bonzini  * table in guest or amd nested guest, its mmu features completely
5108c50d8ae3SPaolo Bonzini  * follow the features in guest.
5109c50d8ae3SPaolo Bonzini  */
511016be1d12SSean Christopherson static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
511116be1d12SSean Christopherson 					struct kvm_mmu *context)
5112c50d8ae3SPaolo Bonzini {
51138c985b2dSSean Christopherson 	/* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
51148c985b2dSSean Christopherson 	bool is_amd = true;
51158c985b2dSSean Christopherson 	/* KVM doesn't use 2-level page tables for the shadow MMU. */
51168c985b2dSSean Christopherson 	bool is_pse = false;
5117c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
5118c50d8ae3SPaolo Bonzini 	int i;
5119c50d8ae3SPaolo Bonzini 
5120a972e29cSPaolo Bonzini 	WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
51218c985b2dSSean Christopherson 
5122c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
5123b705a277SSean Christopherson 	__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
5124a972e29cSPaolo Bonzini 				context->root_role.level,
51257a458f0eSPaolo Bonzini 				context->root_role.efer_nx,
5126ccf31d6eSSean Christopherson 				guest_can_use(vcpu, X86_FEATURE_GBPAGES),
5127ccf31d6eSSean Christopherson 				is_pse, is_amd);
5128c50d8ae3SPaolo Bonzini 
5129c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
5130c50d8ae3SPaolo Bonzini 		return;
5131c50d8ae3SPaolo Bonzini 
5132a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
5133e54f1ff2SKai Huang 		/*
5134e54f1ff2SKai Huang 		 * So far shadow_me_value is a constant during KVM's life
5135e54f1ff2SKai Huang 		 * time.  Bits in shadow_me_value are allowed to be set.
5136e54f1ff2SKai Huang 		 * Bits in shadow_me_mask but not in shadow_me_value are
5137e54f1ff2SKai Huang 		 * not allowed to be set.
5138e54f1ff2SKai Huang 		 */
5139e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
5140e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
5141e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
5142e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
5143c50d8ae3SPaolo Bonzini 	}
5144c50d8ae3SPaolo Bonzini 
5145c50d8ae3SPaolo Bonzini }
5146c50d8ae3SPaolo Bonzini 
5147c50d8ae3SPaolo Bonzini static inline bool boot_cpu_is_amd(void)
5148c50d8ae3SPaolo Bonzini {
5149c50d8ae3SPaolo Bonzini 	WARN_ON_ONCE(!tdp_enabled);
5150c50d8ae3SPaolo Bonzini 	return shadow_x_mask == 0;
5151c50d8ae3SPaolo Bonzini }
5152c50d8ae3SPaolo Bonzini 
5153c50d8ae3SPaolo Bonzini /*
5154c50d8ae3SPaolo Bonzini  * the direct page table on host, use as much mmu features as
5155c50d8ae3SPaolo Bonzini  * possible, however, kvm currently does not do execution-protection.
5156c50d8ae3SPaolo Bonzini  */
5157f3d90f90SSean Christopherson static void reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
5158c50d8ae3SPaolo Bonzini {
5159c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
5160c50d8ae3SPaolo Bonzini 	int i;
5161c50d8ae3SPaolo Bonzini 
5162c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
5163c50d8ae3SPaolo Bonzini 
5164c50d8ae3SPaolo Bonzini 	if (boot_cpu_is_amd())
5165b705a277SSean Christopherson 		__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
51666c6ab524SSean Christopherson 					context->root_role.level, true,
5167c50d8ae3SPaolo Bonzini 					boot_cpu_has(X86_FEATURE_GBPAGES),
51688c985b2dSSean Christopherson 					false, true);
5169c50d8ae3SPaolo Bonzini 	else
5170c50d8ae3SPaolo Bonzini 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
517184ea5c09SLai Jiangshan 					    reserved_hpa_bits(), false,
517284ea5c09SLai Jiangshan 					    max_huge_page_level);
5173c50d8ae3SPaolo Bonzini 
5174c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
5175c50d8ae3SPaolo Bonzini 		return;
5176c50d8ae3SPaolo Bonzini 
5177a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
5178c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
5179c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
5180c50d8ae3SPaolo Bonzini 	}
5181c50d8ae3SPaolo Bonzini }
5182c50d8ae3SPaolo Bonzini 
5183c50d8ae3SPaolo Bonzini /*
5184c50d8ae3SPaolo Bonzini  * as the comments in reset_shadow_zero_bits_mask() except it
5185c50d8ae3SPaolo Bonzini  * is the shadow page table for intel nested guest.
5186c50d8ae3SPaolo Bonzini  */
5187c50d8ae3SPaolo Bonzini static void
5188e8f6e738SJinrong Liang reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
5189c50d8ae3SPaolo Bonzini {
5190c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
519184ea5c09SLai Jiangshan 				    reserved_hpa_bits(), execonly,
519284ea5c09SLai Jiangshan 				    max_huge_page_level);
5193c50d8ae3SPaolo Bonzini }
5194c50d8ae3SPaolo Bonzini 
5195c50d8ae3SPaolo Bonzini #define BYTE_MASK(access) \
5196c50d8ae3SPaolo Bonzini 	((1 & (access) ? 2 : 0) | \
5197c50d8ae3SPaolo Bonzini 	 (2 & (access) ? 4 : 0) | \
5198c50d8ae3SPaolo Bonzini 	 (3 & (access) ? 8 : 0) | \
5199c50d8ae3SPaolo Bonzini 	 (4 & (access) ? 16 : 0) | \
5200c50d8ae3SPaolo Bonzini 	 (5 & (access) ? 32 : 0) | \
5201c50d8ae3SPaolo Bonzini 	 (6 & (access) ? 64 : 0) | \
5202c50d8ae3SPaolo Bonzini 	 (7 & (access) ? 128 : 0))
5203c50d8ae3SPaolo Bonzini 
5204c50d8ae3SPaolo Bonzini 
5205c596f147SSean Christopherson static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
5206c50d8ae3SPaolo Bonzini {
5207c50d8ae3SPaolo Bonzini 	unsigned byte;
5208c50d8ae3SPaolo Bonzini 
5209c50d8ae3SPaolo Bonzini 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
5210c50d8ae3SPaolo Bonzini 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
5211c50d8ae3SPaolo Bonzini 	const u8 u = BYTE_MASK(ACC_USER_MASK);
5212c50d8ae3SPaolo Bonzini 
5213c596f147SSean Christopherson 	bool cr4_smep = is_cr4_smep(mmu);
5214c596f147SSean Christopherson 	bool cr4_smap = is_cr4_smap(mmu);
5215c596f147SSean Christopherson 	bool cr0_wp = is_cr0_wp(mmu);
521690599c28SSean Christopherson 	bool efer_nx = is_efer_nx(mmu);
5217c50d8ae3SPaolo Bonzini 
5218c50d8ae3SPaolo Bonzini 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
5219c50d8ae3SPaolo Bonzini 		unsigned pfec = byte << 1;
5220c50d8ae3SPaolo Bonzini 
5221c50d8ae3SPaolo Bonzini 		/*
5222c50d8ae3SPaolo Bonzini 		 * Each "*f" variable has a 1 bit for each UWX value
5223c50d8ae3SPaolo Bonzini 		 * that causes a fault with the given PFEC.
5224c50d8ae3SPaolo Bonzini 		 */
5225c50d8ae3SPaolo Bonzini 
5226c50d8ae3SPaolo Bonzini 		/* Faults from writes to non-writable pages */
5227c50d8ae3SPaolo Bonzini 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
5228c50d8ae3SPaolo Bonzini 		/* Faults from user mode accesses to supervisor pages */
5229c50d8ae3SPaolo Bonzini 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
5230c50d8ae3SPaolo Bonzini 		/* Faults from fetches of non-executable pages*/
5231c50d8ae3SPaolo Bonzini 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
5232c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode fetches of user pages */
5233c50d8ae3SPaolo Bonzini 		u8 smepf = 0;
5234c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode accesses of user pages */
5235c50d8ae3SPaolo Bonzini 		u8 smapf = 0;
5236c50d8ae3SPaolo Bonzini 
5237c50d8ae3SPaolo Bonzini 		if (!ept) {
5238c50d8ae3SPaolo Bonzini 			/* Faults from kernel mode accesses to user pages */
5239c50d8ae3SPaolo Bonzini 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
5240c50d8ae3SPaolo Bonzini 
5241c50d8ae3SPaolo Bonzini 			/* Not really needed: !nx will cause pte.nx to fault */
524290599c28SSean Christopherson 			if (!efer_nx)
5243c50d8ae3SPaolo Bonzini 				ff = 0;
5244c50d8ae3SPaolo Bonzini 
5245c50d8ae3SPaolo Bonzini 			/* Allow supervisor writes if !cr0.wp */
5246c50d8ae3SPaolo Bonzini 			if (!cr0_wp)
5247c50d8ae3SPaolo Bonzini 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
5248c50d8ae3SPaolo Bonzini 
5249c50d8ae3SPaolo Bonzini 			/* Disallow supervisor fetches of user code if cr4.smep */
5250c50d8ae3SPaolo Bonzini 			if (cr4_smep)
5251c50d8ae3SPaolo Bonzini 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
5252c50d8ae3SPaolo Bonzini 
5253c50d8ae3SPaolo Bonzini 			/*
5254c50d8ae3SPaolo Bonzini 			 * SMAP:kernel-mode data accesses from user-mode
5255c50d8ae3SPaolo Bonzini 			 * mappings should fault. A fault is considered
5256c50d8ae3SPaolo Bonzini 			 * as a SMAP violation if all of the following
5257c50d8ae3SPaolo Bonzini 			 * conditions are true:
5258c50d8ae3SPaolo Bonzini 			 *   - X86_CR4_SMAP is set in CR4
5259c50d8ae3SPaolo Bonzini 			 *   - A user page is accessed
5260c50d8ae3SPaolo Bonzini 			 *   - The access is not a fetch
52614f4aa80eSLai Jiangshan 			 *   - The access is supervisor mode
52624f4aa80eSLai Jiangshan 			 *   - If implicit supervisor access or X86_EFLAGS_AC is clear
5263c50d8ae3SPaolo Bonzini 			 *
526494b4a2f1SLai Jiangshan 			 * Here, we cover the first four conditions.
526594b4a2f1SLai Jiangshan 			 * The fifth is computed dynamically in permission_fault();
5266c50d8ae3SPaolo Bonzini 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
5267c50d8ae3SPaolo Bonzini 			 * *not* subject to SMAP restrictions.
5268c50d8ae3SPaolo Bonzini 			 */
5269c50d8ae3SPaolo Bonzini 			if (cr4_smap)
5270c50d8ae3SPaolo Bonzini 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
5271c50d8ae3SPaolo Bonzini 		}
5272c50d8ae3SPaolo Bonzini 
5273c50d8ae3SPaolo Bonzini 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
5274c50d8ae3SPaolo Bonzini 	}
5275c50d8ae3SPaolo Bonzini }
5276c50d8ae3SPaolo Bonzini 
5277c50d8ae3SPaolo Bonzini /*
5278c50d8ae3SPaolo Bonzini * PKU is an additional mechanism by which the paging controls access to
5279c50d8ae3SPaolo Bonzini * user-mode addresses based on the value in the PKRU register.  Protection
5280c50d8ae3SPaolo Bonzini * key violations are reported through a bit in the page fault error code.
5281c50d8ae3SPaolo Bonzini * Unlike other bits of the error code, the PK bit is not known at the
5282c50d8ae3SPaolo Bonzini * call site of e.g. gva_to_gpa; it must be computed directly in
5283c50d8ae3SPaolo Bonzini * permission_fault based on two bits of PKRU, on some machine state (CR4,
5284c50d8ae3SPaolo Bonzini * CR0, EFER, CPL), and on other bits of the error code and the page tables.
5285c50d8ae3SPaolo Bonzini *
5286c50d8ae3SPaolo Bonzini * In particular the following conditions come from the error code, the
5287c50d8ae3SPaolo Bonzini * page tables and the machine state:
5288c50d8ae3SPaolo Bonzini * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
5289c50d8ae3SPaolo Bonzini * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
5290c50d8ae3SPaolo Bonzini * - PK is always zero if U=0 in the page tables
5291c50d8ae3SPaolo Bonzini * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
5292c50d8ae3SPaolo Bonzini *
5293c50d8ae3SPaolo Bonzini * The PKRU bitmask caches the result of these four conditions.  The error
5294c50d8ae3SPaolo Bonzini * code (minus the P bit) and the page table's U bit form an index into the
5295c50d8ae3SPaolo Bonzini * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
5296c50d8ae3SPaolo Bonzini * with the two bits of the PKRU register corresponding to the protection key.
5297c50d8ae3SPaolo Bonzini * For the first three conditions above the bits will be 00, thus masking
5298c50d8ae3SPaolo Bonzini * away both AD and WD.  For all reads or if the last condition holds, WD
5299c50d8ae3SPaolo Bonzini * only will be masked away.
5300c50d8ae3SPaolo Bonzini */
53012e4c0661SSean Christopherson static void update_pkru_bitmask(struct kvm_mmu *mmu)
5302c50d8ae3SPaolo Bonzini {
5303c50d8ae3SPaolo Bonzini 	unsigned bit;
5304c50d8ae3SPaolo Bonzini 	bool wp;
5305c50d8ae3SPaolo Bonzini 
5306c50d8ae3SPaolo Bonzini 	mmu->pkru_mask = 0;
5307a3ca5281SChenyi Qiang 
5308a3ca5281SChenyi Qiang 	if (!is_cr4_pke(mmu))
5309c50d8ae3SPaolo Bonzini 		return;
5310c50d8ae3SPaolo Bonzini 
53112e4c0661SSean Christopherson 	wp = is_cr0_wp(mmu);
5312c50d8ae3SPaolo Bonzini 
5313c50d8ae3SPaolo Bonzini 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5314c50d8ae3SPaolo Bonzini 		unsigned pfec, pkey_bits;
5315c50d8ae3SPaolo Bonzini 		bool check_pkey, check_write, ff, uf, wf, pte_user;
5316c50d8ae3SPaolo Bonzini 
5317c50d8ae3SPaolo Bonzini 		pfec = bit << 1;
5318c50d8ae3SPaolo Bonzini 		ff = pfec & PFERR_FETCH_MASK;
5319c50d8ae3SPaolo Bonzini 		uf = pfec & PFERR_USER_MASK;
5320c50d8ae3SPaolo Bonzini 		wf = pfec & PFERR_WRITE_MASK;
5321c50d8ae3SPaolo Bonzini 
5322c50d8ae3SPaolo Bonzini 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
5323c50d8ae3SPaolo Bonzini 		pte_user = pfec & PFERR_RSVD_MASK;
5324c50d8ae3SPaolo Bonzini 
5325c50d8ae3SPaolo Bonzini 		/*
5326c50d8ae3SPaolo Bonzini 		 * Only need to check the access which is not an
5327c50d8ae3SPaolo Bonzini 		 * instruction fetch and is to a user page.
5328c50d8ae3SPaolo Bonzini 		 */
5329c50d8ae3SPaolo Bonzini 		check_pkey = (!ff && pte_user);
5330c50d8ae3SPaolo Bonzini 		/*
5331c50d8ae3SPaolo Bonzini 		 * write access is controlled by PKRU if it is a
5332c50d8ae3SPaolo Bonzini 		 * user access or CR0.WP = 1.
5333c50d8ae3SPaolo Bonzini 		 */
5334c50d8ae3SPaolo Bonzini 		check_write = check_pkey && wf && (uf || wp);
5335c50d8ae3SPaolo Bonzini 
5336c50d8ae3SPaolo Bonzini 		/* PKRU.AD stops both read and write access. */
5337c50d8ae3SPaolo Bonzini 		pkey_bits = !!check_pkey;
5338c50d8ae3SPaolo Bonzini 		/* PKRU.WD stops write access. */
5339c50d8ae3SPaolo Bonzini 		pkey_bits |= (!!check_write) << 1;
5340c50d8ae3SPaolo Bonzini 
5341c50d8ae3SPaolo Bonzini 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5342c50d8ae3SPaolo Bonzini 	}
5343c50d8ae3SPaolo Bonzini }
5344c50d8ae3SPaolo Bonzini 
5345533f9a4bSSean Christopherson static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5346533f9a4bSSean Christopherson 					struct kvm_mmu *mmu)
5347c50d8ae3SPaolo Bonzini {
5348533f9a4bSSean Christopherson 	if (!is_cr0_pg(mmu))
5349533f9a4bSSean Christopherson 		return;
5350c50d8ae3SPaolo Bonzini 
5351c919e881SKai Huang 	reset_guest_rsvds_bits_mask(vcpu, mmu);
5352533f9a4bSSean Christopherson 	update_permission_bitmask(mmu, false);
5353533f9a4bSSean Christopherson 	update_pkru_bitmask(mmu);
5354c50d8ae3SPaolo Bonzini }
5355c50d8ae3SPaolo Bonzini 
5356fe660f72SSean Christopherson static void paging64_init_context(struct kvm_mmu *context)
5357c50d8ae3SPaolo Bonzini {
5358c50d8ae3SPaolo Bonzini 	context->page_fault = paging64_page_fault;
5359c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging64_gva_to_gpa;
5360c3c6c9fcSLai Jiangshan 	context->sync_spte = paging64_sync_spte;
5361c50d8ae3SPaolo Bonzini }
5362c50d8ae3SPaolo Bonzini 
536384a16226SSean Christopherson static void paging32_init_context(struct kvm_mmu *context)
5364c50d8ae3SPaolo Bonzini {
5365c50d8ae3SPaolo Bonzini 	context->page_fault = paging32_page_fault;
5366c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging32_gva_to_gpa;
5367c3c6c9fcSLai Jiangshan 	context->sync_spte = paging32_sync_spte;
5368c50d8ae3SPaolo Bonzini }
5369c50d8ae3SPaolo Bonzini 
5370f3d90f90SSean Christopherson static union kvm_cpu_role kvm_calc_cpu_role(struct kvm_vcpu *vcpu,
5371f3d90f90SSean Christopherson 					    const struct kvm_mmu_role_regs *regs)
5372e5ed0fb0SPaolo Bonzini {
53737a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5374e5ed0fb0SPaolo Bonzini 
5375e5ed0fb0SPaolo Bonzini 	role.base.access = ACC_ALL;
5376e5ed0fb0SPaolo Bonzini 	role.base.smm = is_smm(vcpu);
5377e5ed0fb0SPaolo Bonzini 	role.base.guest_mode = is_guest_mode(vcpu);
5378e5ed0fb0SPaolo Bonzini 	role.ext.valid = 1;
5379e5ed0fb0SPaolo Bonzini 
5380e5ed0fb0SPaolo Bonzini 	if (!____is_cr0_pg(regs)) {
5381e5ed0fb0SPaolo Bonzini 		role.base.direct = 1;
5382e5ed0fb0SPaolo Bonzini 		return role;
5383e5ed0fb0SPaolo Bonzini 	}
5384e5ed0fb0SPaolo Bonzini 
5385e5ed0fb0SPaolo Bonzini 	role.base.efer_nx = ____is_efer_nx(regs);
5386e5ed0fb0SPaolo Bonzini 	role.base.cr0_wp = ____is_cr0_wp(regs);
5387e5ed0fb0SPaolo Bonzini 	role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5388e5ed0fb0SPaolo Bonzini 	role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5389e5ed0fb0SPaolo Bonzini 	role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
539060f3cb60SPaolo Bonzini 
539160f3cb60SPaolo Bonzini 	if (____is_efer_lma(regs))
539260f3cb60SPaolo Bonzini 		role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
539360f3cb60SPaolo Bonzini 							: PT64_ROOT_4LEVEL;
539460f3cb60SPaolo Bonzini 	else if (____is_cr4_pae(regs))
539560f3cb60SPaolo Bonzini 		role.base.level = PT32E_ROOT_LEVEL;
539660f3cb60SPaolo Bonzini 	else
539760f3cb60SPaolo Bonzini 		role.base.level = PT32_ROOT_LEVEL;
5398e5ed0fb0SPaolo Bonzini 
5399e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smep = ____is_cr4_smep(regs);
5400e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smap = ____is_cr4_smap(regs);
5401e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pse = ____is_cr4_pse(regs);
5402e5ed0fb0SPaolo Bonzini 
5403e5ed0fb0SPaolo Bonzini 	/* PKEY and LA57 are active iff long mode is active. */
5404e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5405e5ed0fb0SPaolo Bonzini 	role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5406e5ed0fb0SPaolo Bonzini 	role.ext.efer_lma = ____is_efer_lma(regs);
5407e5ed0fb0SPaolo Bonzini 	return role;
5408e5ed0fb0SPaolo Bonzini }
5409e5ed0fb0SPaolo Bonzini 
5410cf9f4c0eSSean Christopherson void __kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
5411cf9f4c0eSSean Christopherson 					struct kvm_mmu *mmu)
5412cf9f4c0eSSean Christopherson {
5413cf9f4c0eSSean Christopherson 	const bool cr0_wp = kvm_is_cr0_bit_set(vcpu, X86_CR0_WP);
5414cf9f4c0eSSean Christopherson 
5415cf9f4c0eSSean Christopherson 	BUILD_BUG_ON((KVM_MMU_CR0_ROLE_BITS & KVM_POSSIBLE_CR0_GUEST_BITS) != X86_CR0_WP);
5416cf9f4c0eSSean Christopherson 	BUILD_BUG_ON((KVM_MMU_CR4_ROLE_BITS & KVM_POSSIBLE_CR4_GUEST_BITS));
5417cf9f4c0eSSean Christopherson 
5418cf9f4c0eSSean Christopherson 	if (is_cr0_wp(mmu) == cr0_wp)
5419cf9f4c0eSSean Christopherson 		return;
5420cf9f4c0eSSean Christopherson 
5421cf9f4c0eSSean Christopherson 	mmu->cpu_role.base.cr0_wp = cr0_wp;
5422cf9f4c0eSSean Christopherson 	reset_guest_paging_metadata(vcpu, mmu);
5423cf9f4c0eSSean Christopherson }
5424cf9f4c0eSSean Christopherson 
5425d468d94bSSean Christopherson static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5426d468d94bSSean Christopherson {
5427746700d2SWei Huang 	/* tdp_root_level is architecture forced level, use it if nonzero */
5428746700d2SWei Huang 	if (tdp_root_level)
5429746700d2SWei Huang 		return tdp_root_level;
5430746700d2SWei Huang 
5431d468d94bSSean Christopherson 	/* Use 5-level TDP if and only if it's useful/necessary. */
543283013059SSean Christopherson 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5433d468d94bSSean Christopherson 		return 4;
5434d468d94bSSean Christopherson 
543583013059SSean Christopherson 	return max_tdp_level;
5436d468d94bSSean Christopherson }
5437d468d94bSSean Christopherson 
5438b628cb52SGerd Hoffmann u8 kvm_mmu_get_max_tdp_level(void)
5439b628cb52SGerd Hoffmann {
5440b628cb52SGerd Hoffmann 	return tdp_root_level ? tdp_root_level : max_tdp_level;
5441b628cb52SGerd Hoffmann }
5442b628cb52SGerd Hoffmann 
54437a458f0eSPaolo Bonzini static union kvm_mmu_page_role
54448626c120SSean Christopherson kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
54457a7ae829SPaolo Bonzini 				union kvm_cpu_role cpu_role)
5446c50d8ae3SPaolo Bonzini {
54477a458f0eSPaolo Bonzini 	union kvm_mmu_page_role role = {0};
5448c50d8ae3SPaolo Bonzini 
54497a458f0eSPaolo Bonzini 	role.access = ACC_ALL;
54507a458f0eSPaolo Bonzini 	role.cr0_wp = true;
54517a458f0eSPaolo Bonzini 	role.efer_nx = true;
54527a458f0eSPaolo Bonzini 	role.smm = cpu_role.base.smm;
54537a458f0eSPaolo Bonzini 	role.guest_mode = cpu_role.base.guest_mode;
545454275f74SSean Christopherson 	role.ad_disabled = !kvm_ad_enabled();
54557a458f0eSPaolo Bonzini 	role.level = kvm_mmu_get_tdp_level(vcpu);
54567a458f0eSPaolo Bonzini 	role.direct = true;
54577a458f0eSPaolo Bonzini 	role.has_4_byte_gpte = false;
5458c50d8ae3SPaolo Bonzini 
5459c50d8ae3SPaolo Bonzini 	return role;
5460c50d8ae3SPaolo Bonzini }
5461c50d8ae3SPaolo Bonzini 
546239e7e2bfSPaolo Bonzini static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5463a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5464c50d8ae3SPaolo Bonzini {
54658c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
54667a458f0eSPaolo Bonzini 	union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5467c50d8ae3SPaolo Bonzini 
5468e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
54697a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
5470c50d8ae3SPaolo Bonzini 		return;
5471c50d8ae3SPaolo Bonzini 
5472e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
54737a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
54747a02674dSSean Christopherson 	context->page_fault = kvm_tdp_page_fault;
5475c3c6c9fcSLai Jiangshan 	context->sync_spte = NULL;
54762fdcc1b3SPaolo Bonzini 	context->get_guest_pgd = get_guest_cr3;
5477c50d8ae3SPaolo Bonzini 	context->get_pdptr = kvm_pdptr_read;
5478c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5479c50d8ae3SPaolo Bonzini 
548036f26787SSean Christopherson 	if (!is_cr0_pg(context))
5481c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = nonpaging_gva_to_gpa;
548236f26787SSean Christopherson 	else if (is_cr4_pae(context))
5483c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging64_gva_to_gpa;
5484f4bd6f73SSean Christopherson 	else
5485c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging32_gva_to_gpa;
5486c50d8ae3SPaolo Bonzini 
5487533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5488e8f6e738SJinrong Liang 	reset_tdp_shadow_zero_bits_mask(context);
5489c50d8ae3SPaolo Bonzini }
5490c50d8ae3SPaolo Bonzini 
54918c008659SPaolo Bonzini static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
54927a7ae829SPaolo Bonzini 				    union kvm_cpu_role cpu_role,
54937a458f0eSPaolo Bonzini 				    union kvm_mmu_page_role root_role)
5494c50d8ae3SPaolo Bonzini {
5495e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
54967a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
549718db1b17SSean Christopherson 		return;
5498c50d8ae3SPaolo Bonzini 
5499e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
55007a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
550118db1b17SSean Christopherson 
550236f26787SSean Christopherson 	if (!is_cr0_pg(context))
550384a16226SSean Christopherson 		nonpaging_init_context(context);
550436f26787SSean Christopherson 	else if (is_cr4_pae(context))
5505fe660f72SSean Christopherson 		paging64_init_context(context);
5506c50d8ae3SPaolo Bonzini 	else
550784a16226SSean Christopherson 		paging32_init_context(context);
5508c50d8ae3SPaolo Bonzini 
5509533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5510c50d8ae3SPaolo Bonzini 	reset_shadow_zero_bits_mask(vcpu, context);
5511c50d8ae3SPaolo Bonzini }
55120f04a2acSVitaly Kuznetsov 
5513594e91a1SSean Christopherson static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5514a7f1de9bSPaolo Bonzini 				union kvm_cpu_role cpu_role)
55150f04a2acSVitaly Kuznetsov {
55168c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
551756b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
551856b321f9SPaolo Bonzini 
551956b321f9SPaolo Bonzini 	root_role = cpu_role.base;
552056b321f9SPaolo Bonzini 
552156b321f9SPaolo Bonzini 	/* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
552256b321f9SPaolo Bonzini 	root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
552356b321f9SPaolo Bonzini 
552456b321f9SPaolo Bonzini 	/*
552556b321f9SPaolo Bonzini 	 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
552656b321f9SPaolo Bonzini 	 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
552756b321f9SPaolo Bonzini 	 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
552856b321f9SPaolo Bonzini 	 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
552956b321f9SPaolo Bonzini 	 * The iTLB multi-hit workaround can be toggled at any time, so assume
553056b321f9SPaolo Bonzini 	 * NX can be used by any non-nested shadow MMU to avoid having to reset
553156b321f9SPaolo Bonzini 	 * MMU contexts.
553256b321f9SPaolo Bonzini 	 */
553356b321f9SPaolo Bonzini 	root_role.efer_nx = true;
55340f04a2acSVitaly Kuznetsov 
55357a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
55360f04a2acSVitaly Kuznetsov }
55370f04a2acSVitaly Kuznetsov 
5538dbc4739bSSean Christopherson void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5539dbc4739bSSean Christopherson 			     unsigned long cr4, u64 efer, gpa_t nested_cr3)
55400f04a2acSVitaly Kuznetsov {
55418c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5542594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
5543594e91a1SSean Christopherson 		.cr0 = cr0,
554428f091bcSPaolo Bonzini 		.cr4 = cr4 & ~X86_CR4_PKE,
5545594e91a1SSean Christopherson 		.efer = efer,
5546594e91a1SSean Christopherson 	};
55477a7ae829SPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
554856b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
554956b321f9SPaolo Bonzini 
555056b321f9SPaolo Bonzini 	/* NPT requires CR0.PG=1. */
555156b321f9SPaolo Bonzini 	WARN_ON_ONCE(cpu_role.base.direct);
555256b321f9SPaolo Bonzini 
555356b321f9SPaolo Bonzini 	root_role = cpu_role.base;
555456b321f9SPaolo Bonzini 	root_role.level = kvm_mmu_get_tdp_level(vcpu);
555584e5ffd0SLai Jiangshan 	if (root_role.level == PT64_ROOT_5LEVEL &&
555684e5ffd0SLai Jiangshan 	    cpu_role.base.level == PT64_ROOT_4LEVEL)
555784e5ffd0SLai Jiangshan 		root_role.passthrough = 1;
55580f04a2acSVitaly Kuznetsov 
55597a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5560d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, nested_cr3);
55610f04a2acSVitaly Kuznetsov }
55620f04a2acSVitaly Kuznetsov EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5563c50d8ae3SPaolo Bonzini 
55647a7ae829SPaolo Bonzini static union kvm_cpu_role
5565c50d8ae3SPaolo Bonzini kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5566bb1fcc70SSean Christopherson 				   bool execonly, u8 level)
5567c50d8ae3SPaolo Bonzini {
55687a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5569c50d8ae3SPaolo Bonzini 
5570daed87b8SPaolo Bonzini 	/*
5571daed87b8SPaolo Bonzini 	 * KVM does not support SMM transfer monitors, and consequently does not
5572daed87b8SPaolo Bonzini 	 * support the "entry to SMM" control either.  role.base.smm is always 0.
5573daed87b8SPaolo Bonzini 	 */
5574daed87b8SPaolo Bonzini 	WARN_ON_ONCE(is_smm(vcpu));
5575bb1fcc70SSean Christopherson 	role.base.level = level;
5576bb3b394dSLai Jiangshan 	role.base.has_4_byte_gpte = false;
5577c50d8ae3SPaolo Bonzini 	role.base.direct = false;
5578c50d8ae3SPaolo Bonzini 	role.base.ad_disabled = !accessed_dirty;
5579c50d8ae3SPaolo Bonzini 	role.base.guest_mode = true;
5580c50d8ae3SPaolo Bonzini 	role.base.access = ACC_ALL;
5581c50d8ae3SPaolo Bonzini 
5582cd6767c3SSean Christopherson 	role.ext.word = 0;
5583c50d8ae3SPaolo Bonzini 	role.ext.execonly = execonly;
5584cd6767c3SSean Christopherson 	role.ext.valid = 1;
5585c50d8ae3SPaolo Bonzini 
5586c50d8ae3SPaolo Bonzini 	return role;
5587c50d8ae3SPaolo Bonzini }
5588c50d8ae3SPaolo Bonzini 
5589c50d8ae3SPaolo Bonzini void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5590cc022ae1SLai Jiangshan 			     int huge_page_level, bool accessed_dirty,
5591cc022ae1SLai Jiangshan 			     gpa_t new_eptp)
5592c50d8ae3SPaolo Bonzini {
55938c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5594bb1fcc70SSean Christopherson 	u8 level = vmx_eptp_page_walk_level(new_eptp);
55957a7ae829SPaolo Bonzini 	union kvm_cpu_role new_mode =
5596c50d8ae3SPaolo Bonzini 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5597bb1fcc70SSean Christopherson 						   execonly, level);
5598c50d8ae3SPaolo Bonzini 
5599e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 != context->cpu_role.as_u64) {
5600e5ed0fb0SPaolo Bonzini 		/* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5601e5ed0fb0SPaolo Bonzini 		context->cpu_role.as_u64 = new_mode.as_u64;
56027a458f0eSPaolo Bonzini 		context->root_role.word = new_mode.base.word;
560318db1b17SSean Christopherson 
5604c50d8ae3SPaolo Bonzini 		context->page_fault = ept_page_fault;
5605c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = ept_gva_to_gpa;
5606c3c6c9fcSLai Jiangshan 		context->sync_spte = ept_sync_spte;
5607347a0d0dSPaolo Bonzini 
5608c596f147SSean Christopherson 		update_permission_bitmask(context, true);
560928f091bcSPaolo Bonzini 		context->pkru_mask = 0;
5610cc022ae1SLai Jiangshan 		reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5611e8f6e738SJinrong Liang 		reset_ept_shadow_zero_bits_mask(context, execonly);
5612c50d8ae3SPaolo Bonzini 	}
56133cffc89dSPaolo Bonzini 
5614d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, new_eptp);
56153cffc89dSPaolo Bonzini }
5616c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5617c50d8ae3SPaolo Bonzini 
561839e7e2bfSPaolo Bonzini static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5619a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5620c50d8ae3SPaolo Bonzini {
56218c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5622c50d8ae3SPaolo Bonzini 
5623a7f1de9bSPaolo Bonzini 	kvm_init_shadow_mmu(vcpu, cpu_role);
5624929d1cfaSPaolo Bonzini 
56252fdcc1b3SPaolo Bonzini 	context->get_guest_pgd     = get_guest_cr3;
5626c50d8ae3SPaolo Bonzini 	context->get_pdptr         = kvm_pdptr_read;
5627c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5628c50d8ae3SPaolo Bonzini }
5629c50d8ae3SPaolo Bonzini 
563039e7e2bfSPaolo Bonzini static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5631a7f1de9bSPaolo Bonzini 				union kvm_cpu_role new_mode)
5632c50d8ae3SPaolo Bonzini {
5633c50d8ae3SPaolo Bonzini 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5634c50d8ae3SPaolo Bonzini 
5635e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5636c50d8ae3SPaolo Bonzini 		return;
5637c50d8ae3SPaolo Bonzini 
5638e5ed0fb0SPaolo Bonzini 	g_context->cpu_role.as_u64   = new_mode.as_u64;
56392fdcc1b3SPaolo Bonzini 	g_context->get_guest_pgd     = get_guest_cr3;
5640c50d8ae3SPaolo Bonzini 	g_context->get_pdptr         = kvm_pdptr_read;
5641c50d8ae3SPaolo Bonzini 	g_context->inject_page_fault = kvm_inject_page_fault;
5642c50d8ae3SPaolo Bonzini 
5643c50d8ae3SPaolo Bonzini 	/*
56445efac074SPaolo Bonzini 	 * L2 page tables are never shadowed, so there is no need to sync
56455efac074SPaolo Bonzini 	 * SPTEs.
56465efac074SPaolo Bonzini 	 */
56479fd4a4e3SLai Jiangshan 	g_context->sync_spte         = NULL;
56485efac074SPaolo Bonzini 
56495efac074SPaolo Bonzini 	/*
5650c50d8ae3SPaolo Bonzini 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5651c50d8ae3SPaolo Bonzini 	 * L1's nested page tables (e.g. EPT12). The nested translation
5652c50d8ae3SPaolo Bonzini 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5653c50d8ae3SPaolo Bonzini 	 * L2's page tables as the first level of translation and L1's
5654c50d8ae3SPaolo Bonzini 	 * nested page tables as the second level of translation. Basically
5655c50d8ae3SPaolo Bonzini 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5656c50d8ae3SPaolo Bonzini 	 */
5657fa4b5588SSean Christopherson 	if (!is_paging(vcpu))
56581f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5659fa4b5588SSean Christopherson 	else if (is_long_mode(vcpu))
56601f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5661fa4b5588SSean Christopherson 	else if (is_pae(vcpu))
56621f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5663fa4b5588SSean Christopherson 	else
56641f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging32_gva_to_gpa;
5665fa4b5588SSean Christopherson 
5666533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, g_context);
5667c50d8ae3SPaolo Bonzini }
5668c50d8ae3SPaolo Bonzini 
5669c9060662SSean Christopherson void kvm_init_mmu(struct kvm_vcpu *vcpu)
5670c50d8ae3SPaolo Bonzini {
567139e7e2bfSPaolo Bonzini 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5672a7f1de9bSPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
567339e7e2bfSPaolo Bonzini 
5674c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
5675a7f1de9bSPaolo Bonzini 		init_kvm_nested_mmu(vcpu, cpu_role);
5676c50d8ae3SPaolo Bonzini 	else if (tdp_enabled)
5677a7f1de9bSPaolo Bonzini 		init_kvm_tdp_mmu(vcpu, cpu_role);
5678c50d8ae3SPaolo Bonzini 	else
5679a7f1de9bSPaolo Bonzini 		init_kvm_softmmu(vcpu, cpu_role);
5680c50d8ae3SPaolo Bonzini }
5681c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_mmu);
5682c50d8ae3SPaolo Bonzini 
568349c6f875SSean Christopherson void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
568449c6f875SSean Christopherson {
568549c6f875SSean Christopherson 	/*
568649c6f875SSean Christopherson 	 * Invalidate all MMU roles to force them to reinitialize as CPUID
568749c6f875SSean Christopherson 	 * information is factored into reserved bit calculations.
5688feb627e8SVitaly Kuznetsov 	 *
5689feb627e8SVitaly Kuznetsov 	 * Correctly handling multiple vCPU models with respect to paging and
5690feb627e8SVitaly Kuznetsov 	 * physical address properties) in a single VM would require tracking
5691feb627e8SVitaly Kuznetsov 	 * all relevant CPUID information in kvm_mmu_page_role. That is very
5692feb627e8SVitaly Kuznetsov 	 * undesirable as it would increase the memory requirements for
5693338068b5SSean Christopherson 	 * gfn_write_track (see struct kvm_mmu_page_role comments).  For now
5694338068b5SSean Christopherson 	 * that problem is swept under the rug; KVM's CPUID API is horrific and
5695feb627e8SVitaly Kuznetsov 	 * it's all but impossible to solve it without introducing a new API.
569649c6f875SSean Christopherson 	 */
56971bc26cb9SSean Christopherson 	vcpu->arch.root_mmu.root_role.invalid = 1;
56981bc26cb9SSean Christopherson 	vcpu->arch.guest_mmu.root_role.invalid = 1;
56991bc26cb9SSean Christopherson 	vcpu->arch.nested_mmu.root_role.invalid = 1;
5700e5ed0fb0SPaolo Bonzini 	vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5701e5ed0fb0SPaolo Bonzini 	vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5702e5ed0fb0SPaolo Bonzini 	vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
570349c6f875SSean Christopherson 	kvm_mmu_reset_context(vcpu);
570463f5a190SSean Christopherson 
570563f5a190SSean Christopherson 	/*
5706feb627e8SVitaly Kuznetsov 	 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5707feb627e8SVitaly Kuznetsov 	 * kvm_arch_vcpu_ioctl().
570863f5a190SSean Christopherson 	 */
5709fb3146b4SSean Christopherson 	KVM_BUG_ON(kvm_vcpu_has_run(vcpu), vcpu->kvm);
571049c6f875SSean Christopherson }
571149c6f875SSean Christopherson 
5712c50d8ae3SPaolo Bonzini void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5713c50d8ae3SPaolo Bonzini {
5714c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
5715c9060662SSean Christopherson 	kvm_init_mmu(vcpu);
5716c50d8ae3SPaolo Bonzini }
5717c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5718c50d8ae3SPaolo Bonzini 
5719c50d8ae3SPaolo Bonzini int kvm_mmu_load(struct kvm_vcpu *vcpu)
5720c50d8ae3SPaolo Bonzini {
5721c50d8ae3SPaolo Bonzini 	int r;
5722c50d8ae3SPaolo Bonzini 
5723347a0d0dSPaolo Bonzini 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5724c50d8ae3SPaolo Bonzini 	if (r)
5725c50d8ae3SPaolo Bonzini 		goto out;
5726748e52b9SSean Christopherson 	r = mmu_alloc_special_roots(vcpu);
5727c50d8ae3SPaolo Bonzini 	if (r)
5728c50d8ae3SPaolo Bonzini 		goto out;
5729347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
57306e6ec584SSean Christopherson 		r = mmu_alloc_direct_roots(vcpu);
57316e6ec584SSean Christopherson 	else
57326e6ec584SSean Christopherson 		r = mmu_alloc_shadow_roots(vcpu);
5733c50d8ae3SPaolo Bonzini 	if (r)
5734c50d8ae3SPaolo Bonzini 		goto out;
5735a91f387bSSean Christopherson 
5736a91f387bSSean Christopherson 	kvm_mmu_sync_roots(vcpu);
5737a91f387bSSean Christopherson 
5738727a7e27SPaolo Bonzini 	kvm_mmu_load_pgd(vcpu);
5739db01416bSSean Christopherson 
5740db01416bSSean Christopherson 	/*
5741db01416bSSean Christopherson 	 * Flush any TLB entries for the new root, the provenance of the root
5742db01416bSSean Christopherson 	 * is unknown.  Even if KVM ensures there are no stale TLB entries
5743db01416bSSean Christopherson 	 * for a freed root, in theory another hypervisor could have left
5744db01416bSSean Christopherson 	 * stale entries.  Flushing on alloc also allows KVM to skip the TLB
5745db01416bSSean Christopherson 	 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5746db01416bSSean Christopherson 	 */
574789604647SWei Wang 	kvm_x86_call(flush_tlb_current)(vcpu);
5748c50d8ae3SPaolo Bonzini out:
5749c50d8ae3SPaolo Bonzini 	return r;
5750c50d8ae3SPaolo Bonzini }
5751c50d8ae3SPaolo Bonzini 
5752c50d8ae3SPaolo Bonzini void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5753c50d8ae3SPaolo Bonzini {
57540c1c92f1SPaolo Bonzini 	struct kvm *kvm = vcpu->kvm;
57550c1c92f1SPaolo Bonzini 
57560c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
575720ba462dSSean Christopherson 	WARN_ON_ONCE(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
57580c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
575920ba462dSSean Christopherson 	WARN_ON_ONCE(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
57606d58f275SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5761c50d8ae3SPaolo Bonzini }
5762c50d8ae3SPaolo Bonzini 
5763527d5cd7SSean Christopherson static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5764527d5cd7SSean Christopherson {
5765527d5cd7SSean Christopherson 	struct kvm_mmu_page *sp;
5766527d5cd7SSean Christopherson 
5767527d5cd7SSean Christopherson 	if (!VALID_PAGE(root_hpa))
5768527d5cd7SSean Christopherson 		return false;
5769527d5cd7SSean Christopherson 
5770527d5cd7SSean Christopherson 	/*
5771527d5cd7SSean Christopherson 	 * When freeing obsolete roots, treat roots as obsolete if they don't
57720e3223d8SSean Christopherson 	 * have an associated shadow page, as it's impossible to determine if
57730e3223d8SSean Christopherson 	 * such roots are fresh or stale.  This does mean KVM will get false
5774527d5cd7SSean Christopherson 	 * positives and free roots that don't strictly need to be freed, but
5775527d5cd7SSean Christopherson 	 * such false positives are relatively rare:
5776527d5cd7SSean Christopherson 	 *
57770e3223d8SSean Christopherson 	 *  (a) only PAE paging and nested NPT have roots without shadow pages
57780e3223d8SSean Christopherson 	 *      (or any shadow paging flavor with a dummy root, see note below)
5779527d5cd7SSean Christopherson 	 *  (b) remote reloads due to a memslot update obsoletes _all_ roots
5780527d5cd7SSean Christopherson 	 *  (c) KVM doesn't track previous roots for PAE paging, and the guest
5781527d5cd7SSean Christopherson 	 *      is unlikely to zap an in-use PGD.
57820e3223d8SSean Christopherson 	 *
57830e3223d8SSean Christopherson 	 * Note!  Dummy roots are unique in that they are obsoleted by memslot
57840e3223d8SSean Christopherson 	 * _creation_!  See also FNAME(fetch).
5785527d5cd7SSean Christopherson 	 */
5786c5f2d564SSean Christopherson 	sp = root_to_sp(root_hpa);
5787527d5cd7SSean Christopherson 	return !sp || is_obsolete_sp(kvm, sp);
5788527d5cd7SSean Christopherson }
5789527d5cd7SSean Christopherson 
5790527d5cd7SSean Christopherson static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5791527d5cd7SSean Christopherson {
5792527d5cd7SSean Christopherson 	unsigned long roots_to_free = 0;
5793527d5cd7SSean Christopherson 	int i;
5794527d5cd7SSean Christopherson 
5795527d5cd7SSean Christopherson 	if (is_obsolete_root(kvm, mmu->root.hpa))
5796527d5cd7SSean Christopherson 		roots_to_free |= KVM_MMU_ROOT_CURRENT;
5797527d5cd7SSean Christopherson 
5798527d5cd7SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5799cf4a8693SShaoqin Huang 		if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5800527d5cd7SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5801527d5cd7SSean Christopherson 	}
5802527d5cd7SSean Christopherson 
5803527d5cd7SSean Christopherson 	if (roots_to_free)
5804527d5cd7SSean Christopherson 		kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5805527d5cd7SSean Christopherson }
5806527d5cd7SSean Christopherson 
5807527d5cd7SSean Christopherson void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5808527d5cd7SSean Christopherson {
5809527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5810527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5811527d5cd7SSean Christopherson }
5812527d5cd7SSean Christopherson 
5813c50d8ae3SPaolo Bonzini static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5814c50d8ae3SPaolo Bonzini 				    int *bytes)
5815c50d8ae3SPaolo Bonzini {
5816c50d8ae3SPaolo Bonzini 	u64 gentry = 0;
5817c50d8ae3SPaolo Bonzini 	int r;
5818c50d8ae3SPaolo Bonzini 
5819c50d8ae3SPaolo Bonzini 	/*
5820c50d8ae3SPaolo Bonzini 	 * Assume that the pte write on a page table of the same type
5821c50d8ae3SPaolo Bonzini 	 * as the current vcpu paging mode since we update the sptes only
5822c50d8ae3SPaolo Bonzini 	 * when they have the same mode.
5823c50d8ae3SPaolo Bonzini 	 */
5824c50d8ae3SPaolo Bonzini 	if (is_pae(vcpu) && *bytes == 4) {
5825c50d8ae3SPaolo Bonzini 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5826c50d8ae3SPaolo Bonzini 		*gpa &= ~(gpa_t)7;
5827c50d8ae3SPaolo Bonzini 		*bytes = 8;
5828c50d8ae3SPaolo Bonzini 	}
5829c50d8ae3SPaolo Bonzini 
5830c50d8ae3SPaolo Bonzini 	if (*bytes == 4 || *bytes == 8) {
5831c50d8ae3SPaolo Bonzini 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5832c50d8ae3SPaolo Bonzini 		if (r)
5833c50d8ae3SPaolo Bonzini 			gentry = 0;
5834c50d8ae3SPaolo Bonzini 	}
5835c50d8ae3SPaolo Bonzini 
5836c50d8ae3SPaolo Bonzini 	return gentry;
5837c50d8ae3SPaolo Bonzini }
5838c50d8ae3SPaolo Bonzini 
5839c50d8ae3SPaolo Bonzini /*
5840c50d8ae3SPaolo Bonzini  * If we're seeing too many writes to a page, it may no longer be a page table,
5841c50d8ae3SPaolo Bonzini  * or we may be forking, in which case it is better to unmap the page.
5842c50d8ae3SPaolo Bonzini  */
5843c50d8ae3SPaolo Bonzini static bool detect_write_flooding(struct kvm_mmu_page *sp)
5844c50d8ae3SPaolo Bonzini {
5845c50d8ae3SPaolo Bonzini 	/*
5846c50d8ae3SPaolo Bonzini 	 * Skip write-flooding detected for the sp whose level is 1, because
5847c50d8ae3SPaolo Bonzini 	 * it can become unsync, then the guest page is not write-protected.
5848c50d8ae3SPaolo Bonzini 	 */
58493bae0459SSean Christopherson 	if (sp->role.level == PG_LEVEL_4K)
5850c50d8ae3SPaolo Bonzini 		return false;
5851c50d8ae3SPaolo Bonzini 
5852c50d8ae3SPaolo Bonzini 	atomic_inc(&sp->write_flooding_count);
5853c50d8ae3SPaolo Bonzini 	return atomic_read(&sp->write_flooding_count) >= 3;
5854c50d8ae3SPaolo Bonzini }
5855c50d8ae3SPaolo Bonzini 
5856c50d8ae3SPaolo Bonzini /*
5857c50d8ae3SPaolo Bonzini  * Misaligned accesses are too much trouble to fix up; also, they usually
5858c50d8ae3SPaolo Bonzini  * indicate a page is not used as a page table.
5859c50d8ae3SPaolo Bonzini  */
5860c50d8ae3SPaolo Bonzini static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5861c50d8ae3SPaolo Bonzini 				    int bytes)
5862c50d8ae3SPaolo Bonzini {
5863c50d8ae3SPaolo Bonzini 	unsigned offset, pte_size, misaligned;
5864c50d8ae3SPaolo Bonzini 
5865c50d8ae3SPaolo Bonzini 	offset = offset_in_page(gpa);
5866bb3b394dSLai Jiangshan 	pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5867c50d8ae3SPaolo Bonzini 
5868c50d8ae3SPaolo Bonzini 	/*
5869c50d8ae3SPaolo Bonzini 	 * Sometimes, the OS only writes the last one bytes to update status
5870c50d8ae3SPaolo Bonzini 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5871c50d8ae3SPaolo Bonzini 	 */
5872c50d8ae3SPaolo Bonzini 	if (!(offset & (pte_size - 1)) && bytes == 1)
5873c50d8ae3SPaolo Bonzini 		return false;
5874c50d8ae3SPaolo Bonzini 
5875c50d8ae3SPaolo Bonzini 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5876c50d8ae3SPaolo Bonzini 	misaligned |= bytes < 4;
5877c50d8ae3SPaolo Bonzini 
5878c50d8ae3SPaolo Bonzini 	return misaligned;
5879c50d8ae3SPaolo Bonzini }
5880c50d8ae3SPaolo Bonzini 
5881c50d8ae3SPaolo Bonzini static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5882c50d8ae3SPaolo Bonzini {
5883c50d8ae3SPaolo Bonzini 	unsigned page_offset, quadrant;
5884c50d8ae3SPaolo Bonzini 	u64 *spte;
5885c50d8ae3SPaolo Bonzini 	int level;
5886c50d8ae3SPaolo Bonzini 
5887c50d8ae3SPaolo Bonzini 	page_offset = offset_in_page(gpa);
5888c50d8ae3SPaolo Bonzini 	level = sp->role.level;
5889c50d8ae3SPaolo Bonzini 	*nspte = 1;
5890bb3b394dSLai Jiangshan 	if (sp->role.has_4_byte_gpte) {
5891c50d8ae3SPaolo Bonzini 		page_offset <<= 1;	/* 32->64 */
5892c50d8ae3SPaolo Bonzini 		/*
5893c50d8ae3SPaolo Bonzini 		 * A 32-bit pde maps 4MB while the shadow pdes map
5894c50d8ae3SPaolo Bonzini 		 * only 2MB.  So we need to double the offset again
5895c50d8ae3SPaolo Bonzini 		 * and zap two pdes instead of one.
5896c50d8ae3SPaolo Bonzini 		 */
5897c50d8ae3SPaolo Bonzini 		if (level == PT32_ROOT_LEVEL) {
5898c50d8ae3SPaolo Bonzini 			page_offset &= ~7; /* kill rounding error */
5899c50d8ae3SPaolo Bonzini 			page_offset <<= 1;
5900c50d8ae3SPaolo Bonzini 			*nspte = 2;
5901c50d8ae3SPaolo Bonzini 		}
5902c50d8ae3SPaolo Bonzini 		quadrant = page_offset >> PAGE_SHIFT;
5903c50d8ae3SPaolo Bonzini 		page_offset &= ~PAGE_MASK;
5904c50d8ae3SPaolo Bonzini 		if (quadrant != sp->role.quadrant)
5905c50d8ae3SPaolo Bonzini 			return NULL;
5906c50d8ae3SPaolo Bonzini 	}
5907c50d8ae3SPaolo Bonzini 
5908c50d8ae3SPaolo Bonzini 	spte = &sp->spt[page_offset / sizeof(*spte)];
5909c50d8ae3SPaolo Bonzini 	return spte;
5910c50d8ae3SPaolo Bonzini }
5911c50d8ae3SPaolo Bonzini 
591293284446SSean Christopherson void kvm_mmu_track_write(struct kvm_vcpu *vcpu, gpa_t gpa, const u8 *new,
591393284446SSean Christopherson 			 int bytes)
5914c50d8ae3SPaolo Bonzini {
5915c50d8ae3SPaolo Bonzini 	gfn_t gfn = gpa >> PAGE_SHIFT;
5916c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
5917c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
5918c50d8ae3SPaolo Bonzini 	u64 entry, gentry, *spte;
5919c50d8ae3SPaolo Bonzini 	int npte;
592006152b2dSLai Jiangshan 	bool flush = false;
5921c50d8ae3SPaolo Bonzini 
5922c50d8ae3SPaolo Bonzini 	/*
5923226d9b8fSSean Christopherson 	 * When emulating guest writes, ensure the written value is visible to
5924226d9b8fSSean Christopherson 	 * any task that is handling page faults before checking whether or not
5925226d9b8fSSean Christopherson 	 * KVM is shadowing a guest PTE.  This ensures either KVM will create
5926226d9b8fSSean Christopherson 	 * the correct SPTE in the page fault handler, or this task will see
5927226d9b8fSSean Christopherson 	 * a non-zero indirect_shadow_pages.  Pairs with the smp_mb() in
5928226d9b8fSSean Christopherson 	 * account_shadowed().
5929c50d8ae3SPaolo Bonzini 	 */
5930226d9b8fSSean Christopherson 	smp_mb();
5931226d9b8fSSean Christopherson 	if (!vcpu->kvm->arch.indirect_shadow_pages)
5932c50d8ae3SPaolo Bonzini 		return;
5933c50d8ae3SPaolo Bonzini 
5934531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
5935c50d8ae3SPaolo Bonzini 
5936c50d8ae3SPaolo Bonzini 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5937c50d8ae3SPaolo Bonzini 
5938c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_pte_write;
5939c50d8ae3SPaolo Bonzini 
5940767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5941c50d8ae3SPaolo Bonzini 		if (detect_write_misaligned(sp, gpa, bytes) ||
5942c50d8ae3SPaolo Bonzini 		      detect_write_flooding(sp)) {
5943c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5944c50d8ae3SPaolo Bonzini 			++vcpu->kvm->stat.mmu_flooded;
5945c50d8ae3SPaolo Bonzini 			continue;
5946c50d8ae3SPaolo Bonzini 		}
5947c50d8ae3SPaolo Bonzini 
5948c50d8ae3SPaolo Bonzini 		spte = get_written_sptes(sp, gpa, &npte);
5949c50d8ae3SPaolo Bonzini 		if (!spte)
5950c50d8ae3SPaolo Bonzini 			continue;
5951c50d8ae3SPaolo Bonzini 
5952c50d8ae3SPaolo Bonzini 		while (npte--) {
5953c50d8ae3SPaolo Bonzini 			entry = *spte;
59542de4085cSBen Gardon 			mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5955c5e2184dSSean Christopherson 			if (gentry && sp->role.level != PG_LEVEL_4K)
5956c5e2184dSSean Christopherson 				++vcpu->kvm->stat.mmu_pde_zapped;
59571441ca14SJunaid Shahid 			if (is_shadow_present_pte(entry))
595806152b2dSLai Jiangshan 				flush = true;
5959c50d8ae3SPaolo Bonzini 			++spte;
5960c50d8ae3SPaolo Bonzini 		}
5961c50d8ae3SPaolo Bonzini 	}
596206152b2dSLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5963531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
5964c50d8ae3SPaolo Bonzini }
5965c50d8ae3SPaolo Bonzini 
59661075d41eSSean Christopherson int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5967c50d8ae3SPaolo Bonzini 		       void *insn, int insn_len)
5968c50d8ae3SPaolo Bonzini {
596992daa48bSSean Christopherson 	int r, emulation_type = EMULTYPE_PF;
5970347a0d0dSPaolo Bonzini 	bool direct = vcpu->arch.mmu->root_role.direct;
5971c50d8ae3SPaolo Bonzini 
597220ba462dSSean Christopherson 	if (WARN_ON_ONCE(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5973ddce6208SSean Christopherson 		return RET_PF_RETRY;
5974ddce6208SSean Christopherson 
5975b3d5dc62SSean Christopherson 	/*
5976b3d5dc62SSean Christopherson 	 * Except for reserved faults (emulated MMIO is shared-only), set the
5977b3d5dc62SSean Christopherson 	 * PFERR_PRIVATE_ACCESS flag for software-protected VMs based on the gfn's
5978b3d5dc62SSean Christopherson 	 * current attributes, which are the source of truth for such VMs.  Note,
5979b3d5dc62SSean Christopherson 	 * this wrong for nested MMUs as the GPA is an L2 GPA, but KVM doesn't
5980b3d5dc62SSean Christopherson 	 * currently supported nested virtualization (among many other things)
5981b3d5dc62SSean Christopherson 	 * for software-protected VMs.
5982b3d5dc62SSean Christopherson 	 */
5983b3d5dc62SSean Christopherson 	if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) &&
5984b3d5dc62SSean Christopherson 	    !(error_code & PFERR_RSVD_MASK) &&
5985b3d5dc62SSean Christopherson 	    vcpu->kvm->arch.vm_type == KVM_X86_SW_PROTECTED_VM &&
5986b3d5dc62SSean Christopherson 	    kvm_mem_is_private(vcpu->kvm, gpa_to_gfn(cr2_or_gpa)))
5987b3d5dc62SSean Christopherson 		error_code |= PFERR_PRIVATE_ACCESS;
5988b3d5dc62SSean Christopherson 
5989c50d8ae3SPaolo Bonzini 	r = RET_PF_INVALID;
5990c50d8ae3SPaolo Bonzini 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
599107702e5aSSean Christopherson 		if (WARN_ON_ONCE(error_code & PFERR_PRIVATE_ACCESS))
599207702e5aSSean Christopherson 			return -EFAULT;
599307702e5aSSean Christopherson 
5994736c291cSSean Christopherson 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5995c50d8ae3SPaolo Bonzini 		if (r == RET_PF_EMULATE)
5996c50d8ae3SPaolo Bonzini 			goto emulate;
5997c50d8ae3SPaolo Bonzini 	}
5998c50d8ae3SPaolo Bonzini 
5999c50d8ae3SPaolo Bonzini 	if (r == RET_PF_INVALID) {
60005186ec22SSean Christopherson 		vcpu->stat.pf_taken++;
60015186ec22SSean Christopherson 
6002c9710130SIsaku Yamahata 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa, error_code, false,
600358ef2469SPaolo Bonzini 					  &emulation_type, NULL);
600419025e7bSSean Christopherson 		if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
60057b367bc9SSean Christopherson 			return -EIO;
6006c50d8ae3SPaolo Bonzini 	}
6007c50d8ae3SPaolo Bonzini 
6008c50d8ae3SPaolo Bonzini 	if (r < 0)
6009c50d8ae3SPaolo Bonzini 		return r;
6010f5e7f00cSSean Christopherson 
6011f5e7f00cSSean Christopherson 	if (r == RET_PF_FIXED)
6012f5e7f00cSSean Christopherson 		vcpu->stat.pf_fixed++;
6013f5e7f00cSSean Christopherson 	else if (r == RET_PF_EMULATE)
6014f5e7f00cSSean Christopherson 		vcpu->stat.pf_emulate++;
6015f5e7f00cSSean Christopherson 	else if (r == RET_PF_SPURIOUS)
6016f5e7f00cSSean Christopherson 		vcpu->stat.pf_spurious++;
6017f5e7f00cSSean Christopherson 
601883a2ba4cSSean Christopherson 	if (r != RET_PF_EMULATE)
601983a2ba4cSSean Christopherson 		return 1;
6020c50d8ae3SPaolo Bonzini 
6021c50d8ae3SPaolo Bonzini 	/*
6022c50d8ae3SPaolo Bonzini 	 * Before emulating the instruction, check if the error code
6023c50d8ae3SPaolo Bonzini 	 * was due to a RO violation while translating the guest page.
6024c50d8ae3SPaolo Bonzini 	 * This can occur when using nested virtualization with nested
6025c50d8ae3SPaolo Bonzini 	 * paging in both guests. If true, we simply unprotect the page
6026c50d8ae3SPaolo Bonzini 	 * and resume the guest.
6027c50d8ae3SPaolo Bonzini 	 */
6028347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct &&
6029c50d8ae3SPaolo Bonzini 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
6030736c291cSSean Christopherson 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
6031c50d8ae3SPaolo Bonzini 		return 1;
6032c50d8ae3SPaolo Bonzini 	}
6033c50d8ae3SPaolo Bonzini 
6034c50d8ae3SPaolo Bonzini 	/*
6035c50d8ae3SPaolo Bonzini 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
6036c50d8ae3SPaolo Bonzini 	 * optimistically try to just unprotect the page and let the processor
6037c50d8ae3SPaolo Bonzini 	 * re-execute the instruction that caused the page fault.  Do not allow
6038c50d8ae3SPaolo Bonzini 	 * retrying MMIO emulation, as it's not only pointless but could also
6039c50d8ae3SPaolo Bonzini 	 * cause us to enter an infinite loop because the processor will keep
6040c50d8ae3SPaolo Bonzini 	 * faulting on the non-existent MMIO address.  Retrying an instruction
6041c50d8ae3SPaolo Bonzini 	 * from a nested guest is also pointless and dangerous as we are only
6042c50d8ae3SPaolo Bonzini 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
6043c50d8ae3SPaolo Bonzini 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
6044c50d8ae3SPaolo Bonzini 	 */
6045736c291cSSean Christopherson 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
604692daa48bSSean Christopherson 		emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
6047c50d8ae3SPaolo Bonzini emulate:
6048736c291cSSean Christopherson 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
6049c50d8ae3SPaolo Bonzini 				       insn_len);
6050c50d8ae3SPaolo Bonzini }
6051c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
6052c50d8ae3SPaolo Bonzini 
6053bca99c03SSean Christopherson void kvm_mmu_print_sptes(struct kvm_vcpu *vcpu, gpa_t gpa, const char *msg)
6054bca99c03SSean Christopherson {
6055bca99c03SSean Christopherson 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
6056bca99c03SSean Christopherson 	int root_level, leaf, level;
6057bca99c03SSean Christopherson 
6058bca99c03SSean Christopherson 	leaf = get_sptes_lockless(vcpu, gpa, sptes, &root_level);
6059bca99c03SSean Christopherson 	if (unlikely(leaf < 0))
6060bca99c03SSean Christopherson 		return;
6061bca99c03SSean Christopherson 
6062bca99c03SSean Christopherson 	pr_err("%s %llx", msg, gpa);
6063bca99c03SSean Christopherson 	for (level = root_level; level >= leaf; level--)
6064bca99c03SSean Christopherson 		pr_cont(", spte[%d] = 0x%llx", level, sptes[level]);
6065bca99c03SSean Christopherson 	pr_cont("\n");
6066bca99c03SSean Christopherson }
6067bca99c03SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_print_sptes);
6068bca99c03SSean Christopherson 
60699fd4a4e3SLai Jiangshan static void __kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
60709fd4a4e3SLai Jiangshan 				      u64 addr, hpa_t root_hpa)
60719fd4a4e3SLai Jiangshan {
60729fd4a4e3SLai Jiangshan 	struct kvm_shadow_walk_iterator iterator;
60739fd4a4e3SLai Jiangshan 
60749fd4a4e3SLai Jiangshan 	vcpu_clear_mmio_info(vcpu, addr);
60759fd4a4e3SLai Jiangshan 
6076762b33ebSLike Xu 	/*
6077762b33ebSLike Xu 	 * Walking and synchronizing SPTEs both assume they are operating in
6078762b33ebSLike Xu 	 * the context of the current MMU, and would need to be reworked if
6079762b33ebSLike Xu 	 * this is ever used to sync the guest_mmu, e.g. to emulate INVEPT.
6080762b33ebSLike Xu 	 */
6081762b33ebSLike Xu 	if (WARN_ON_ONCE(mmu != vcpu->arch.mmu))
6082762b33ebSLike Xu 		return;
6083762b33ebSLike Xu 
60849fd4a4e3SLai Jiangshan 	if (!VALID_PAGE(root_hpa))
60859fd4a4e3SLai Jiangshan 		return;
60869fd4a4e3SLai Jiangshan 
60879fd4a4e3SLai Jiangshan 	write_lock(&vcpu->kvm->mmu_lock);
60889fd4a4e3SLai Jiangshan 	for_each_shadow_entry_using_root(vcpu, root_hpa, addr, iterator) {
60899fd4a4e3SLai Jiangshan 		struct kvm_mmu_page *sp = sptep_to_sp(iterator.sptep);
60909fd4a4e3SLai Jiangshan 
60919fd4a4e3SLai Jiangshan 		if (sp->unsync) {
609219ace7d6SLai Jiangshan 			int ret = kvm_sync_spte(vcpu, sp, iterator.index);
60939fd4a4e3SLai Jiangshan 
60949fd4a4e3SLai Jiangshan 			if (ret < 0)
60959fd4a4e3SLai Jiangshan 				mmu_page_zap_pte(vcpu->kvm, sp, iterator.sptep, NULL);
60969fd4a4e3SLai Jiangshan 			if (ret)
60979fd4a4e3SLai Jiangshan 				kvm_flush_remote_tlbs_sptep(vcpu->kvm, iterator.sptep);
60989fd4a4e3SLai Jiangshan 		}
60999fd4a4e3SLai Jiangshan 
61009fd4a4e3SLai Jiangshan 		if (!sp->unsync_children)
61019fd4a4e3SLai Jiangshan 			break;
61029fd4a4e3SLai Jiangshan 	}
61039fd4a4e3SLai Jiangshan 	write_unlock(&vcpu->kvm->mmu_lock);
61049fd4a4e3SLai Jiangshan }
61059fd4a4e3SLai Jiangshan 
6106753b43c9SLai Jiangshan void kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
6107cd42853eSLai Jiangshan 			     u64 addr, unsigned long roots)
6108c50d8ae3SPaolo Bonzini {
6109c50d8ae3SPaolo Bonzini 	int i;
6110c50d8ae3SPaolo Bonzini 
6111cd42853eSLai Jiangshan 	WARN_ON_ONCE(roots & ~KVM_MMU_ROOTS_ALL);
6112cd42853eSLai Jiangshan 
61135efac074SPaolo Bonzini 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
61145efac074SPaolo Bonzini 	if (mmu != &vcpu->arch.guest_mmu) {
61155efac074SPaolo Bonzini 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
6116753b43c9SLai Jiangshan 		if (is_noncanonical_address(addr, vcpu))
6117c50d8ae3SPaolo Bonzini 			return;
6118c50d8ae3SPaolo Bonzini 
611989604647SWei Wang 		kvm_x86_call(flush_tlb_gva)(vcpu, addr);
61205efac074SPaolo Bonzini 	}
61215efac074SPaolo Bonzini 
61229fd4a4e3SLai Jiangshan 	if (!mmu->sync_spte)
61235efac074SPaolo Bonzini 		return;
61245efac074SPaolo Bonzini 
6125cd42853eSLai Jiangshan 	if (roots & KVM_MMU_ROOT_CURRENT)
61269fd4a4e3SLai Jiangshan 		__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->root.hpa);
6127c50d8ae3SPaolo Bonzini 
6128cd42853eSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
6129ed335278SLai Jiangshan 		if (roots & KVM_MMU_ROOT_PREVIOUS(i))
61309fd4a4e3SLai Jiangshan 			__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->prev_roots[i].hpa);
61315efac074SPaolo Bonzini 	}
61325efac074SPaolo Bonzini }
61332c86c444SLai Jiangshan EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_addr);
6134c50d8ae3SPaolo Bonzini 
61355efac074SPaolo Bonzini void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
61365efac074SPaolo Bonzini {
6137cd42853eSLai Jiangshan 	/*
6138cd42853eSLai Jiangshan 	 * INVLPG is required to invalidate any global mappings for the VA,
6139cd42853eSLai Jiangshan 	 * irrespective of PCID.  Blindly sync all roots as it would take
6140cd42853eSLai Jiangshan 	 * roughly the same amount of work/time to determine whether any of the
6141cd42853eSLai Jiangshan 	 * previous roots have a global mapping.
6142cd42853eSLai Jiangshan 	 *
6143cd42853eSLai Jiangshan 	 * Mappings not reachable via the current or previous cached roots will
6144cd42853eSLai Jiangshan 	 * be synced when switching to that new cr3, so nothing needs to be
6145cd42853eSLai Jiangshan 	 * done here for them.
6146cd42853eSLai Jiangshan 	 */
6147cd42853eSLai Jiangshan 	kvm_mmu_invalidate_addr(vcpu, vcpu->arch.walk_mmu, gva, KVM_MMU_ROOTS_ALL);
6148c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
6149c50d8ae3SPaolo Bonzini }
6150c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
6151c50d8ae3SPaolo Bonzini 
61525efac074SPaolo Bonzini 
6153c50d8ae3SPaolo Bonzini void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
6154c50d8ae3SPaolo Bonzini {
6155c50d8ae3SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
61569ebc3f51SLai Jiangshan 	unsigned long roots = 0;
6157c50d8ae3SPaolo Bonzini 	uint i;
6158c50d8ae3SPaolo Bonzini 
61599ebc3f51SLai Jiangshan 	if (pcid == kvm_get_active_pcid(vcpu))
61609ebc3f51SLai Jiangshan 		roots |= KVM_MMU_ROOT_CURRENT;
6161c50d8ae3SPaolo Bonzini 
6162c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
6163c50d8ae3SPaolo Bonzini 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
61649ebc3f51SLai Jiangshan 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd))
61659ebc3f51SLai Jiangshan 			roots |= KVM_MMU_ROOT_PREVIOUS(i);
6166c50d8ae3SPaolo Bonzini 	}
6167c50d8ae3SPaolo Bonzini 
61689ebc3f51SLai Jiangshan 	if (roots)
61699ebc3f51SLai Jiangshan 		kvm_mmu_invalidate_addr(vcpu, mmu, gva, roots);
6170c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
6171c50d8ae3SPaolo Bonzini 
6172c50d8ae3SPaolo Bonzini 	/*
6173c50d8ae3SPaolo Bonzini 	 * Mappings not reachable via the current cr3 or the prev_roots will be
6174c50d8ae3SPaolo Bonzini 	 * synced when switching to that cr3, so nothing needs to be done here
6175c50d8ae3SPaolo Bonzini 	 * for them.
6176c50d8ae3SPaolo Bonzini 	 */
6177c50d8ae3SPaolo Bonzini }
6178c50d8ae3SPaolo Bonzini 
6179746700d2SWei Huang void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
6180746700d2SWei Huang 		       int tdp_max_root_level, int tdp_huge_page_level)
6181c50d8ae3SPaolo Bonzini {
6182bde77235SSean Christopherson 	tdp_enabled = enable_tdp;
6183746700d2SWei Huang 	tdp_root_level = tdp_forced_root_level;
618483013059SSean Christopherson 	max_tdp_level = tdp_max_root_level;
6185703c335dSSean Christopherson 
61861f98f2bdSDavid Matlack #ifdef CONFIG_X86_64
61871f98f2bdSDavid Matlack 	tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
61881f98f2bdSDavid Matlack #endif
6189703c335dSSean Christopherson 	/*
61901d92d2e8SSean Christopherson 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
6191703c335dSSean Christopherson 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
6192703c335dSSean Christopherson 	 * the kernel is not.  But, KVM never creates a page size greater than
6193703c335dSSean Christopherson 	 * what is used by the kernel for any given HVA, i.e. the kernel's
6194703c335dSSean Christopherson 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
6195703c335dSSean Christopherson 	 */
6196703c335dSSean Christopherson 	if (tdp_enabled)
61971d92d2e8SSean Christopherson 		max_huge_page_level = tdp_huge_page_level;
6198703c335dSSean Christopherson 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
61991d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_1G;
6200703c335dSSean Christopherson 	else
62011d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_2M;
6202c50d8ae3SPaolo Bonzini }
6203bde77235SSean Christopherson EXPORT_SYMBOL_GPL(kvm_configure_mmu);
6204c50d8ae3SPaolo Bonzini 
6205c50d8ae3SPaolo Bonzini /* The return value indicates if tlb flush on all vcpus is needed. */
6206727ae377SSean Christopherson typedef bool (*slot_rmaps_handler) (struct kvm *kvm,
6207269e9552SHamza Mahfooz 				    struct kvm_rmap_head *rmap_head,
6208269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot);
6209c50d8ae3SPaolo Bonzini 
6210727ae377SSean Christopherson static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,
6211727ae377SSean Christopherson 					      const struct kvm_memory_slot *slot,
6212727ae377SSean Christopherson 					      slot_rmaps_handler fn,
6213727ae377SSean Christopherson 					      int start_level, int end_level,
6214727ae377SSean Christopherson 					      gfn_t start_gfn, gfn_t end_gfn,
6215727ae377SSean Christopherson 					      bool flush_on_yield, bool flush)
6216c50d8ae3SPaolo Bonzini {
6217c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
6218c50d8ae3SPaolo Bonzini 
6219eddd9e83SSean Christopherson 	lockdep_assert_held_write(&kvm->mmu_lock);
6220eddd9e83SSean Christopherson 
6221727ae377SSean Christopherson 	for_each_slot_rmap_range(slot, start_level, end_level, start_gfn,
6222c50d8ae3SPaolo Bonzini 			end_gfn, &iterator) {
6223c50d8ae3SPaolo Bonzini 		if (iterator.rmap)
6224727ae377SSean Christopherson 			flush |= fn(kvm, iterator.rmap, slot);
6225c50d8ae3SPaolo Bonzini 
6226531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
6227302695a5SSean Christopherson 			if (flush && flush_on_yield) {
62288c63e8c2SDavid Matlack 				kvm_flush_remote_tlbs_range(kvm, start_gfn,
6229c50d8ae3SPaolo Bonzini 							    iterator.gfn - start_gfn + 1);
6230c50d8ae3SPaolo Bonzini 				flush = false;
6231c50d8ae3SPaolo Bonzini 			}
6232531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
6233c50d8ae3SPaolo Bonzini 		}
6234c50d8ae3SPaolo Bonzini 	}
6235c50d8ae3SPaolo Bonzini 
6236c50d8ae3SPaolo Bonzini 	return flush;
6237c50d8ae3SPaolo Bonzini }
6238c50d8ae3SPaolo Bonzini 
6239727ae377SSean Christopherson static __always_inline bool walk_slot_rmaps(struct kvm *kvm,
6240727ae377SSean Christopherson 					    const struct kvm_memory_slot *slot,
6241727ae377SSean Christopherson 					    slot_rmaps_handler fn,
6242727ae377SSean Christopherson 					    int start_level, int end_level,
6243302695a5SSean Christopherson 					    bool flush_on_yield)
6244c50d8ae3SPaolo Bonzini {
6245727ae377SSean Christopherson 	return __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,
6246727ae377SSean Christopherson 				 slot->base_gfn, slot->base_gfn + slot->npages - 1,
62471a61b7dbSSean Christopherson 				 flush_on_yield, false);
6248c50d8ae3SPaolo Bonzini }
6249c50d8ae3SPaolo Bonzini 
6250727ae377SSean Christopherson static __always_inline bool walk_slot_rmaps_4k(struct kvm *kvm,
6251727ae377SSean Christopherson 					       const struct kvm_memory_slot *slot,
6252727ae377SSean Christopherson 					       slot_rmaps_handler fn,
6253727ae377SSean Christopherson 					       bool flush_on_yield)
6254c50d8ae3SPaolo Bonzini {
6255727ae377SSean Christopherson 	return walk_slot_rmaps(kvm, slot, fn, PG_LEVEL_4K, PG_LEVEL_4K, flush_on_yield);
6256c50d8ae3SPaolo Bonzini }
6257c50d8ae3SPaolo Bonzini 
6258c50d8ae3SPaolo Bonzini static void free_mmu_pages(struct kvm_mmu *mmu)
6259c50d8ae3SPaolo Bonzini {
62604a98623dSSean Christopherson 	if (!tdp_enabled && mmu->pae_root)
62614a98623dSSean Christopherson 		set_memory_encrypted((unsigned long)mmu->pae_root, 1);
6262c50d8ae3SPaolo Bonzini 	free_page((unsigned long)mmu->pae_root);
626303ca4589SSean Christopherson 	free_page((unsigned long)mmu->pml4_root);
6264cb0f722aSWei Huang 	free_page((unsigned long)mmu->pml5_root);
6265c50d8ae3SPaolo Bonzini }
6266c50d8ae3SPaolo Bonzini 
626704d28e37SSean Christopherson static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
6268c50d8ae3SPaolo Bonzini {
6269c50d8ae3SPaolo Bonzini 	struct page *page;
6270c50d8ae3SPaolo Bonzini 	int i;
6271c50d8ae3SPaolo Bonzini 
6272b9e5603cSPaolo Bonzini 	mmu->root.hpa = INVALID_PAGE;
6273b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
627404d28e37SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
627504d28e37SSean Christopherson 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
627604d28e37SSean Christopherson 
627727f4fca2SLai Jiangshan 	/* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
627827f4fca2SLai Jiangshan 	if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
627927f4fca2SLai Jiangshan 		return 0;
628027f4fca2SLai Jiangshan 
6281c50d8ae3SPaolo Bonzini 	/*
6282c50d8ae3SPaolo Bonzini 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
6283c50d8ae3SPaolo Bonzini 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
6284c50d8ae3SPaolo Bonzini 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
6285c50d8ae3SPaolo Bonzini 	 * x86_64.  Therefore we need to allocate the PDP table in the first
628604d45551SSean Christopherson 	 * 4GB of memory, which happens to fit the DMA32 zone.  TDP paging
628704d45551SSean Christopherson 	 * generally doesn't use PAE paging and can skip allocating the PDP
628804d45551SSean Christopherson 	 * table.  The main exception, handled here, is SVM's 32-bit NPT.  The
628904d45551SSean Christopherson 	 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
629084432316SLai Jiangshan 	 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
6291c50d8ae3SPaolo Bonzini 	 */
6292d468d94bSSean Christopherson 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
6293c50d8ae3SPaolo Bonzini 		return 0;
6294c50d8ae3SPaolo Bonzini 
6295c50d8ae3SPaolo Bonzini 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
6296c50d8ae3SPaolo Bonzini 	if (!page)
6297c50d8ae3SPaolo Bonzini 		return -ENOMEM;
6298c50d8ae3SPaolo Bonzini 
6299c50d8ae3SPaolo Bonzini 	mmu->pae_root = page_address(page);
63004a98623dSSean Christopherson 
63014a98623dSSean Christopherson 	/*
63024a98623dSSean Christopherson 	 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
63034a98623dSSean Christopherson 	 * get the CPU to treat the PDPTEs as encrypted.  Decrypt the page so
63044a98623dSSean Christopherson 	 * that KVM's writes and the CPU's reads get along.  Note, this is
63054a98623dSSean Christopherson 	 * only necessary when using shadow paging, as 64-bit NPT can get at
63064a98623dSSean Christopherson 	 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
63074a98623dSSean Christopherson 	 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
63084a98623dSSean Christopherson 	 */
63094a98623dSSean Christopherson 	if (!tdp_enabled)
63104a98623dSSean Christopherson 		set_memory_decrypted((unsigned long)mmu->pae_root, 1);
63114a98623dSSean Christopherson 	else
6312e54f1ff2SKai Huang 		WARN_ON_ONCE(shadow_me_value);
63134a98623dSSean Christopherson 
6314c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i)
6315c834e5e4SSean Christopherson 		mmu->pae_root[i] = INVALID_PAE_ROOT;
6316c50d8ae3SPaolo Bonzini 
6317c50d8ae3SPaolo Bonzini 	return 0;
6318c50d8ae3SPaolo Bonzini }
6319c50d8ae3SPaolo Bonzini 
6320c50d8ae3SPaolo Bonzini int kvm_mmu_create(struct kvm_vcpu *vcpu)
6321c50d8ae3SPaolo Bonzini {
6322c50d8ae3SPaolo Bonzini 	int ret;
6323c50d8ae3SPaolo Bonzini 
63245962bfb7SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
63255f6078f9SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
63265f6078f9SSean Christopherson 
63275962bfb7SSean Christopherson 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
63285f6078f9SSean Christopherson 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
63295962bfb7SSean Christopherson 
6330d8fa2031SSean Christopherson 	vcpu->arch.mmu_shadow_page_cache.init_value =
6331d8fa2031SSean Christopherson 		SHADOW_NONPRESENT_VALUE;
6332d8fa2031SSean Christopherson 	if (!vcpu->arch.mmu_shadow_page_cache.init_value)
633396880883SSean Christopherson 		vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
633496880883SSean Christopherson 
6335c50d8ae3SPaolo Bonzini 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
6336c50d8ae3SPaolo Bonzini 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6337c50d8ae3SPaolo Bonzini 
633804d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
6339c50d8ae3SPaolo Bonzini 	if (ret)
6340c50d8ae3SPaolo Bonzini 		return ret;
6341c50d8ae3SPaolo Bonzini 
634204d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
6343c50d8ae3SPaolo Bonzini 	if (ret)
6344c50d8ae3SPaolo Bonzini 		goto fail_allocate_root;
6345c50d8ae3SPaolo Bonzini 
6346c50d8ae3SPaolo Bonzini 	return ret;
6347c50d8ae3SPaolo Bonzini  fail_allocate_root:
6348c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
6349c50d8ae3SPaolo Bonzini 	return ret;
6350c50d8ae3SPaolo Bonzini }
6351c50d8ae3SPaolo Bonzini 
6352c50d8ae3SPaolo Bonzini #define BATCH_ZAP_PAGES	10
6353c50d8ae3SPaolo Bonzini static void kvm_zap_obsolete_pages(struct kvm *kvm)
6354c50d8ae3SPaolo Bonzini {
6355c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6356c50d8ae3SPaolo Bonzini 	int nr_zapped, batch = 0;
6357b28cb0cdSSean Christopherson 	bool unstable;
6358c50d8ae3SPaolo Bonzini 
6359c50d8ae3SPaolo Bonzini restart:
6360c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe_reverse(sp, node,
6361c50d8ae3SPaolo Bonzini 	      &kvm->arch.active_mmu_pages, link) {
6362c50d8ae3SPaolo Bonzini 		/*
6363c50d8ae3SPaolo Bonzini 		 * No obsolete valid page exists before a newly created page
6364c50d8ae3SPaolo Bonzini 		 * since active_mmu_pages is a FIFO list.
6365c50d8ae3SPaolo Bonzini 		 */
6366c50d8ae3SPaolo Bonzini 		if (!is_obsolete_sp(kvm, sp))
6367c50d8ae3SPaolo Bonzini 			break;
6368c50d8ae3SPaolo Bonzini 
6369c50d8ae3SPaolo Bonzini 		/*
6370f95eec9bSSean Christopherson 		 * Invalid pages should never land back on the list of active
6371f95eec9bSSean Christopherson 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
6372f95eec9bSSean Christopherson 		 * infinite loop if the page gets put back on the list (again).
6373c50d8ae3SPaolo Bonzini 		 */
637420ba462dSSean Christopherson 		if (WARN_ON_ONCE(sp->role.invalid))
6375c50d8ae3SPaolo Bonzini 			continue;
6376c50d8ae3SPaolo Bonzini 
6377c50d8ae3SPaolo Bonzini 		/*
6378c50d8ae3SPaolo Bonzini 		 * No need to flush the TLB since we're only zapping shadow
6379c50d8ae3SPaolo Bonzini 		 * pages with an obsolete generation number and all vCPUS have
6380c50d8ae3SPaolo Bonzini 		 * loaded a new root, i.e. the shadow pages being zapped cannot
6381c50d8ae3SPaolo Bonzini 		 * be in active use by the guest.
6382c50d8ae3SPaolo Bonzini 		 */
6383c50d8ae3SPaolo Bonzini 		if (batch >= BATCH_ZAP_PAGES &&
6384531810caSBen Gardon 		    cond_resched_rwlock_write(&kvm->mmu_lock)) {
6385c50d8ae3SPaolo Bonzini 			batch = 0;
6386c50d8ae3SPaolo Bonzini 			goto restart;
6387c50d8ae3SPaolo Bonzini 		}
6388c50d8ae3SPaolo Bonzini 
6389b28cb0cdSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
6390b28cb0cdSSean Christopherson 				&kvm->arch.zapped_obsolete_pages, &nr_zapped);
6391c50d8ae3SPaolo Bonzini 		batch += nr_zapped;
6392b28cb0cdSSean Christopherson 
6393b28cb0cdSSean Christopherson 		if (unstable)
6394c50d8ae3SPaolo Bonzini 			goto restart;
6395c50d8ae3SPaolo Bonzini 	}
6396c50d8ae3SPaolo Bonzini 
6397c50d8ae3SPaolo Bonzini 	/*
63987ae5840eSSean Christopherson 	 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
63997ae5840eSSean Christopherson 	 * to ensure KVM is not in the middle of a lockless shadow page table
64007ae5840eSSean Christopherson 	 * walk, which may reference the pages.  The remote TLB flush itself is
64017ae5840eSSean Christopherson 	 * not required and is simply a convenient way to kick vCPUs as needed.
64027ae5840eSSean Christopherson 	 * KVM performs a local TLB flush when allocating a new root (see
64037ae5840eSSean Christopherson 	 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
64047ae5840eSSean Christopherson 	 * running with an obsolete MMU.
6405c50d8ae3SPaolo Bonzini 	 */
6406c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
6407c50d8ae3SPaolo Bonzini }
6408c50d8ae3SPaolo Bonzini 
6409c50d8ae3SPaolo Bonzini /*
6410c50d8ae3SPaolo Bonzini  * Fast invalidate all shadow pages and use lock-break technique
6411c50d8ae3SPaolo Bonzini  * to zap obsolete pages.
6412c50d8ae3SPaolo Bonzini  *
6413c50d8ae3SPaolo Bonzini  * It's required when memslot is being deleted or VM is being
6414c50d8ae3SPaolo Bonzini  * destroyed, in these cases, we should ensure that KVM MMU does
6415c50d8ae3SPaolo Bonzini  * not use any resource of the being-deleted slot or all slots
6416c50d8ae3SPaolo Bonzini  * after calling the function.
6417c50d8ae3SPaolo Bonzini  */
6418c50d8ae3SPaolo Bonzini static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6419c50d8ae3SPaolo Bonzini {
6420c50d8ae3SPaolo Bonzini 	lockdep_assert_held(&kvm->slots_lock);
6421c50d8ae3SPaolo Bonzini 
6422531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6423c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_zap_all_fast(kvm);
6424c50d8ae3SPaolo Bonzini 
6425c50d8ae3SPaolo Bonzini 	/*
6426c50d8ae3SPaolo Bonzini 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
6427c50d8ae3SPaolo Bonzini 	 * held for the entire duration of zapping obsolete pages, it's
6428c50d8ae3SPaolo Bonzini 	 * impossible for there to be multiple invalid generations associated
6429c50d8ae3SPaolo Bonzini 	 * with *valid* shadow pages at any given time, i.e. there is exactly
6430c50d8ae3SPaolo Bonzini 	 * one valid generation and (at most) one invalid generation.
6431c50d8ae3SPaolo Bonzini 	 */
6432c50d8ae3SPaolo Bonzini 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6433c50d8ae3SPaolo Bonzini 
64342f6f66ccSSean Christopherson 	/*
64352f6f66ccSSean Christopherson 	 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
64362f6f66ccSSean Christopherson 	 * invalidating TDP MMU roots must be done while holding mmu_lock for
64372f6f66ccSSean Christopherson 	 * write and in the same critical section as making the reload request,
64382f6f66ccSSean Christopherson 	 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6439b7cccd39SBen Gardon 	 */
64401f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6441b7cccd39SBen Gardon 		kvm_tdp_mmu_invalidate_all_roots(kvm);
6442b7cccd39SBen Gardon 
6443c50d8ae3SPaolo Bonzini 	/*
6444c50d8ae3SPaolo Bonzini 	 * Notify all vcpus to reload its shadow page table and flush TLB.
6445c50d8ae3SPaolo Bonzini 	 * Then all vcpus will switch to new shadow page table with the new
6446c50d8ae3SPaolo Bonzini 	 * mmu_valid_gen.
6447c50d8ae3SPaolo Bonzini 	 *
6448c50d8ae3SPaolo Bonzini 	 * Note: we need to do this under the protection of mmu_lock,
6449c50d8ae3SPaolo Bonzini 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
6450c50d8ae3SPaolo Bonzini 	 */
6451527d5cd7SSean Christopherson 	kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6452c50d8ae3SPaolo Bonzini 
6453c50d8ae3SPaolo Bonzini 	kvm_zap_obsolete_pages(kvm);
6454faaf05b0SBen Gardon 
6455531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
64564c6654bdSBen Gardon 
6457f28e9c7fSSean Christopherson 	/*
6458f28e9c7fSSean Christopherson 	 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6459f28e9c7fSSean Christopherson 	 * returning to the caller, e.g. if the zap is in response to a memslot
6460f28e9c7fSSean Christopherson 	 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6461f28e9c7fSSean Christopherson 	 * associated with the deleted memslot once the update completes, and
6462f28e9c7fSSean Christopherson 	 * Deferring the zap until the final reference to the root is put would
6463f28e9c7fSSean Christopherson 	 * lead to use-after-free.
6464f28e9c7fSSean Christopherson 	 */
64651f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
64664c6654bdSBen Gardon 		kvm_tdp_mmu_zap_invalidated_roots(kvm);
6467c50d8ae3SPaolo Bonzini }
6468c50d8ae3SPaolo Bonzini 
6469c50d8ae3SPaolo Bonzini static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
6470c50d8ae3SPaolo Bonzini {
6471c50d8ae3SPaolo Bonzini 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
6472c50d8ae3SPaolo Bonzini }
6473c50d8ae3SPaolo Bonzini 
64740df9dab8SSean Christopherson void kvm_mmu_init_vm(struct kvm *kvm)
6475c50d8ae3SPaolo Bonzini {
6476949019b9SSean Christopherson 	kvm->arch.shadow_mmio_value = shadow_mmio_value;
6477a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6478a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
647955c510e2SSean Christopherson 	INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6480ce25681dSSean Christopherson 	spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6481ce25681dSSean Christopherson 
64820df9dab8SSean Christopherson 	if (tdp_mmu_enabled)
64830df9dab8SSean Christopherson 		kvm_mmu_init_tdp_mmu(kvm);
6484fe5db27dSBen Gardon 
6485ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6486ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6487ada51a9dSDavid Matlack 
6488ada51a9dSDavid Matlack 	kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6489ada51a9dSDavid Matlack 
6490ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6491ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6492c50d8ae3SPaolo Bonzini }
6493c50d8ae3SPaolo Bonzini 
6494ada51a9dSDavid Matlack static void mmu_free_vm_memory_caches(struct kvm *kvm)
6495ada51a9dSDavid Matlack {
6496ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6497ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6498ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6499ada51a9dSDavid Matlack }
6500ada51a9dSDavid Matlack 
6501c50d8ae3SPaolo Bonzini void kvm_mmu_uninit_vm(struct kvm *kvm)
6502c50d8ae3SPaolo Bonzini {
650309732d2bSDavid Matlack 	if (tdp_mmu_enabled)
6504fe5db27dSBen Gardon 		kvm_mmu_uninit_tdp_mmu(kvm);
6505ada51a9dSDavid Matlack 
6506ada51a9dSDavid Matlack 	mmu_free_vm_memory_caches(kvm);
6507c50d8ae3SPaolo Bonzini }
6508c50d8ae3SPaolo Bonzini 
65092833eda0SSean Christopherson static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
651021fa3246SSean Christopherson {
651121fa3246SSean Christopherson 	const struct kvm_memory_slot *memslot;
651221fa3246SSean Christopherson 	struct kvm_memslots *slots;
6513f4209439SMaciej S. Szmigiero 	struct kvm_memslot_iter iter;
651421fa3246SSean Christopherson 	bool flush = false;
651521fa3246SSean Christopherson 	gfn_t start, end;
6516f4209439SMaciej S. Szmigiero 	int i;
651721fa3246SSean Christopherson 
651821fa3246SSean Christopherson 	if (!kvm_memslots_have_rmaps(kvm))
651921fa3246SSean Christopherson 		return flush;
652021fa3246SSean Christopherson 
6521eed52e43SSean Christopherson 	for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) {
652221fa3246SSean Christopherson 		slots = __kvm_memslots(kvm, i);
6523f4209439SMaciej S. Szmigiero 
6524f4209439SMaciej S. Szmigiero 		kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6525f4209439SMaciej S. Szmigiero 			memslot = iter.slot;
652621fa3246SSean Christopherson 			start = max(gfn_start, memslot->base_gfn);
652721fa3246SSean Christopherson 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
6528f4209439SMaciej S. Szmigiero 			if (WARN_ON_ONCE(start >= end))
652921fa3246SSean Christopherson 				continue;
653021fa3246SSean Christopherson 
6531727ae377SSean Christopherson 			flush = __walk_slot_rmaps(kvm, memslot, __kvm_zap_rmap,
653221fa3246SSean Christopherson 						  PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
653321fa3246SSean Christopherson 						  start, end - 1, true, flush);
653421fa3246SSean Christopherson 		}
653521fa3246SSean Christopherson 	}
653621fa3246SSean Christopherson 
653721fa3246SSean Christopherson 	return flush;
653821fa3246SSean Christopherson }
653921fa3246SSean Christopherson 
654088f58535SMaxim Levitsky /*
654188f58535SMaxim Levitsky  * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
654288f58535SMaxim Levitsky  * (not including it)
654388f58535SMaxim Levitsky  */
6544c50d8ae3SPaolo Bonzini void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6545c50d8ae3SPaolo Bonzini {
654621fa3246SSean Christopherson 	bool flush;
6547c50d8ae3SPaolo Bonzini 
6548f4209439SMaciej S. Szmigiero 	if (WARN_ON_ONCE(gfn_end <= gfn_start))
6549f4209439SMaciej S. Szmigiero 		return;
6550f4209439SMaciej S. Szmigiero 
6551531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
65525a324c24SSean Christopherson 
65538569992dSChao Peng 	kvm_mmu_invalidate_begin(kvm);
65548569992dSChao Peng 
65558569992dSChao Peng 	kvm_mmu_invalidate_range_add(kvm, gfn_start, gfn_end);
6556edb298c6SMaxim Levitsky 
65572833eda0SSean Christopherson 	flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
65586103bc07SBen Gardon 
6559441a5dfcSPaolo Bonzini 	if (tdp_mmu_enabled)
6560441a5dfcSPaolo Bonzini 		flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush);
65615a324c24SSean Christopherson 
65625a324c24SSean Christopherson 	if (flush)
65638c63e8c2SDavid Matlack 		kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);
65645a324c24SSean Christopherson 
65658569992dSChao Peng 	kvm_mmu_invalidate_end(kvm);
6566edb298c6SMaxim Levitsky 
65675a324c24SSean Christopherson 	write_unlock(&kvm->mmu_lock);
6568c50d8ae3SPaolo Bonzini }
6569c50d8ae3SPaolo Bonzini 
6570c50d8ae3SPaolo Bonzini static bool slot_rmap_write_protect(struct kvm *kvm,
65710a234f5dSSean Christopherson 				    struct kvm_rmap_head *rmap_head,
6572269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot)
6573c50d8ae3SPaolo Bonzini {
65741346bbb6SDavid Matlack 	return rmap_write_protect(rmap_head, false);
6575c50d8ae3SPaolo Bonzini }
6576c50d8ae3SPaolo Bonzini 
6577c50d8ae3SPaolo Bonzini void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6578269e9552SHamza Mahfooz 				      const struct kvm_memory_slot *memslot,
65793c9bd400SJay Zhou 				      int start_level)
6580c50d8ae3SPaolo Bonzini {
6581e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6582531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6583727ae377SSean Christopherson 		walk_slot_rmaps(kvm, memslot, slot_rmap_write_protect,
6584b64d740eSJunaid Shahid 				start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6585531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6586e2209710SBen Gardon 	}
6587c50d8ae3SPaolo Bonzini 
65881f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
658924ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6590b64d740eSJunaid Shahid 		kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
659124ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
659224ae4cfaSBen Gardon 	}
6593c50d8ae3SPaolo Bonzini }
6594c50d8ae3SPaolo Bonzini 
6595ada51a9dSDavid Matlack static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6596ada51a9dSDavid Matlack {
6597ada51a9dSDavid Matlack 	return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6598ada51a9dSDavid Matlack }
6599ada51a9dSDavid Matlack 
6600ada51a9dSDavid Matlack static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6601ada51a9dSDavid Matlack {
6602ada51a9dSDavid Matlack 	if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6603ada51a9dSDavid Matlack 		return true;
6604ada51a9dSDavid Matlack 
6605ada51a9dSDavid Matlack 	/*
6606ada51a9dSDavid Matlack 	 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6607ada51a9dSDavid Matlack 	 * to split a single huge page. Calculating how many are actually needed
6608ada51a9dSDavid Matlack 	 * is possible but not worth the complexity.
6609ada51a9dSDavid Matlack 	 */
6610ada51a9dSDavid Matlack 	return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6611ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_page_header_cache, 1) ||
6612ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_shadow_page_cache, 1);
6613ada51a9dSDavid Matlack }
6614ada51a9dSDavid Matlack 
6615ada51a9dSDavid Matlack static int topup_split_caches(struct kvm *kvm)
6616ada51a9dSDavid Matlack {
6617b9b71f43SSean Christopherson 	/*
6618b9b71f43SSean Christopherson 	 * Allocating rmap list entries when splitting huge pages for nested
6619dfd4eb44SSean Christopherson 	 * MMUs is uncommon as KVM needs to use a list if and only if there is
6620b9b71f43SSean Christopherson 	 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6621dfd4eb44SSean Christopherson 	 * aliased by multiple L2 gfns and/or from multiple nested roots with
6622dfd4eb44SSean Christopherson 	 * different roles.  Aliasing gfns when using TDP is atypical for VMMs;
6623dfd4eb44SSean Christopherson 	 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6624dfd4eb44SSean Christopherson 	 * but aliasing rarely occurs post-boot or for many gfns.  If there is
6625dfd4eb44SSean Christopherson 	 * only one rmap entry, rmap->val points directly at that one entry and
6626dfd4eb44SSean Christopherson 	 * doesn't need to allocate a list.  Buffer the cache by the default
6627dfd4eb44SSean Christopherson 	 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6628b9b71f43SSean Christopherson 	 * encounters an aliased gfn or two.
6629b9b71f43SSean Christopherson 	 */
6630b9b71f43SSean Christopherson 	const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6631b9b71f43SSean Christopherson 			     KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6632ada51a9dSDavid Matlack 	int r;
6633ada51a9dSDavid Matlack 
6634ada51a9dSDavid Matlack 	lockdep_assert_held(&kvm->slots_lock);
6635ada51a9dSDavid Matlack 
6636b9b71f43SSean Christopherson 	r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6637ada51a9dSDavid Matlack 					 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6638ada51a9dSDavid Matlack 	if (r)
6639ada51a9dSDavid Matlack 		return r;
6640ada51a9dSDavid Matlack 
6641ada51a9dSDavid Matlack 	r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6642ada51a9dSDavid Matlack 	if (r)
6643ada51a9dSDavid Matlack 		return r;
6644ada51a9dSDavid Matlack 
6645ada51a9dSDavid Matlack 	return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6646ada51a9dSDavid Matlack }
6647ada51a9dSDavid Matlack 
6648ada51a9dSDavid Matlack static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6649ada51a9dSDavid Matlack {
6650ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6651ada51a9dSDavid Matlack 	struct shadow_page_caches caches = {};
6652ada51a9dSDavid Matlack 	union kvm_mmu_page_role role;
6653ada51a9dSDavid Matlack 	unsigned int access;
6654ada51a9dSDavid Matlack 	gfn_t gfn;
6655ada51a9dSDavid Matlack 
665679e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
665779e48cecSSean Christopherson 	access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6658ada51a9dSDavid Matlack 
6659ada51a9dSDavid Matlack 	/*
6660ada51a9dSDavid Matlack 	 * Note, huge page splitting always uses direct shadow pages, regardless
6661ada51a9dSDavid Matlack 	 * of whether the huge page itself is mapped by a direct or indirect
6662ada51a9dSDavid Matlack 	 * shadow page, since the huge page region itself is being directly
6663ada51a9dSDavid Matlack 	 * mapped with smaller pages.
6664ada51a9dSDavid Matlack 	 */
6665ada51a9dSDavid Matlack 	role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6666ada51a9dSDavid Matlack 
6667ada51a9dSDavid Matlack 	/* Direct SPs do not require a shadowed_info_cache. */
6668ada51a9dSDavid Matlack 	caches.page_header_cache = &kvm->arch.split_page_header_cache;
6669ada51a9dSDavid Matlack 	caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6670ada51a9dSDavid Matlack 
6671ada51a9dSDavid Matlack 	/* Safe to pass NULL for vCPU since requesting a direct SP. */
6672ada51a9dSDavid Matlack 	return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6673ada51a9dSDavid Matlack }
6674ada51a9dSDavid Matlack 
6675ada51a9dSDavid Matlack static void shadow_mmu_split_huge_page(struct kvm *kvm,
6676ada51a9dSDavid Matlack 				       const struct kvm_memory_slot *slot,
6677ada51a9dSDavid Matlack 				       u64 *huge_sptep)
6678ada51a9dSDavid Matlack 
6679ada51a9dSDavid Matlack {
6680ada51a9dSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6681ada51a9dSDavid Matlack 	u64 huge_spte = READ_ONCE(*huge_sptep);
6682ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
668303787394SPaolo Bonzini 	bool flush = false;
6684ada51a9dSDavid Matlack 	u64 *sptep, spte;
6685ada51a9dSDavid Matlack 	gfn_t gfn;
6686ada51a9dSDavid Matlack 	int index;
6687ada51a9dSDavid Matlack 
6688ada51a9dSDavid Matlack 	sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6689ada51a9dSDavid Matlack 
6690ada51a9dSDavid Matlack 	for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6691ada51a9dSDavid Matlack 		sptep = &sp->spt[index];
6692ada51a9dSDavid Matlack 		gfn = kvm_mmu_page_get_gfn(sp, index);
6693ada51a9dSDavid Matlack 
6694ada51a9dSDavid Matlack 		/*
6695ada51a9dSDavid Matlack 		 * The SP may already have populated SPTEs, e.g. if this huge
6696ada51a9dSDavid Matlack 		 * page is aliased by multiple sptes with the same access
6697ada51a9dSDavid Matlack 		 * permissions. These entries are guaranteed to map the same
6698ada51a9dSDavid Matlack 		 * gfn-to-pfn translation since the SP is direct, so no need to
6699ada51a9dSDavid Matlack 		 * modify them.
6700ada51a9dSDavid Matlack 		 *
670103787394SPaolo Bonzini 		 * However, if a given SPTE points to a lower level page table,
670203787394SPaolo Bonzini 		 * that lower level page table may only be partially populated.
670303787394SPaolo Bonzini 		 * Installing such SPTEs would effectively unmap a potion of the
670403787394SPaolo Bonzini 		 * huge page. Unmapping guest memory always requires a TLB flush
670503787394SPaolo Bonzini 		 * since a subsequent operation on the unmapped regions would
670603787394SPaolo Bonzini 		 * fail to detect the need to flush.
6707ada51a9dSDavid Matlack 		 */
670803787394SPaolo Bonzini 		if (is_shadow_present_pte(*sptep)) {
670903787394SPaolo Bonzini 			flush |= !is_last_spte(*sptep, sp->role.level);
6710ada51a9dSDavid Matlack 			continue;
671103787394SPaolo Bonzini 		}
6712ada51a9dSDavid Matlack 
6713ada51a9dSDavid Matlack 		spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
6714ada51a9dSDavid Matlack 		mmu_spte_set(sptep, spte);
6715ada51a9dSDavid Matlack 		__rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6716ada51a9dSDavid Matlack 	}
6717ada51a9dSDavid Matlack 
671803787394SPaolo Bonzini 	__link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6719ada51a9dSDavid Matlack }
6720ada51a9dSDavid Matlack 
6721ada51a9dSDavid Matlack static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6722ada51a9dSDavid Matlack 					  const struct kvm_memory_slot *slot,
6723ada51a9dSDavid Matlack 					  u64 *huge_sptep)
6724ada51a9dSDavid Matlack {
6725ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6726ada51a9dSDavid Matlack 	int level, r = 0;
6727ada51a9dSDavid Matlack 	gfn_t gfn;
6728ada51a9dSDavid Matlack 	u64 spte;
6729ada51a9dSDavid Matlack 
6730ada51a9dSDavid Matlack 	/* Grab information for the tracepoint before dropping the MMU lock. */
673179e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6732ada51a9dSDavid Matlack 	level = huge_sp->role.level;
6733ada51a9dSDavid Matlack 	spte = *huge_sptep;
6734ada51a9dSDavid Matlack 
6735ada51a9dSDavid Matlack 	if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6736ada51a9dSDavid Matlack 		r = -ENOSPC;
6737ada51a9dSDavid Matlack 		goto out;
6738ada51a9dSDavid Matlack 	}
6739ada51a9dSDavid Matlack 
6740ada51a9dSDavid Matlack 	if (need_topup_split_caches_or_resched(kvm)) {
6741ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6742ada51a9dSDavid Matlack 		cond_resched();
6743ada51a9dSDavid Matlack 		/*
6744ada51a9dSDavid Matlack 		 * If the topup succeeds, return -EAGAIN to indicate that the
6745ada51a9dSDavid Matlack 		 * rmap iterator should be restarted because the MMU lock was
6746ada51a9dSDavid Matlack 		 * dropped.
6747ada51a9dSDavid Matlack 		 */
6748ada51a9dSDavid Matlack 		r = topup_split_caches(kvm) ?: -EAGAIN;
6749ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6750ada51a9dSDavid Matlack 		goto out;
6751ada51a9dSDavid Matlack 	}
6752ada51a9dSDavid Matlack 
6753ada51a9dSDavid Matlack 	shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6754ada51a9dSDavid Matlack 
6755ada51a9dSDavid Matlack out:
6756ada51a9dSDavid Matlack 	trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6757ada51a9dSDavid Matlack 	return r;
6758ada51a9dSDavid Matlack }
6759ada51a9dSDavid Matlack 
6760ada51a9dSDavid Matlack static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6761ada51a9dSDavid Matlack 					    struct kvm_rmap_head *rmap_head,
6762ada51a9dSDavid Matlack 					    const struct kvm_memory_slot *slot)
6763ada51a9dSDavid Matlack {
6764ada51a9dSDavid Matlack 	struct rmap_iterator iter;
6765ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
6766ada51a9dSDavid Matlack 	u64 *huge_sptep;
6767ada51a9dSDavid Matlack 	int r;
6768ada51a9dSDavid Matlack 
6769ada51a9dSDavid Matlack restart:
6770ada51a9dSDavid Matlack 	for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6771ada51a9dSDavid Matlack 		sp = sptep_to_sp(huge_sptep);
6772ada51a9dSDavid Matlack 
6773ada51a9dSDavid Matlack 		/* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6774ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!sp->role.guest_mode))
6775ada51a9dSDavid Matlack 			continue;
6776ada51a9dSDavid Matlack 
6777ada51a9dSDavid Matlack 		/* The rmaps should never contain non-leaf SPTEs. */
6778ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6779ada51a9dSDavid Matlack 			continue;
6780ada51a9dSDavid Matlack 
6781ada51a9dSDavid Matlack 		/* SPs with level >PG_LEVEL_4K should never by unsync. */
6782ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(sp->unsync))
6783ada51a9dSDavid Matlack 			continue;
6784ada51a9dSDavid Matlack 
6785ada51a9dSDavid Matlack 		/* Don't bother splitting huge pages on invalid SPs. */
6786ada51a9dSDavid Matlack 		if (sp->role.invalid)
6787ada51a9dSDavid Matlack 			continue;
6788ada51a9dSDavid Matlack 
6789ada51a9dSDavid Matlack 		r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6790ada51a9dSDavid Matlack 
6791ada51a9dSDavid Matlack 		/*
6792ada51a9dSDavid Matlack 		 * The split succeeded or needs to be retried because the MMU
6793ada51a9dSDavid Matlack 		 * lock was dropped. Either way, restart the iterator to get it
6794ada51a9dSDavid Matlack 		 * back into a consistent state.
6795ada51a9dSDavid Matlack 		 */
6796ada51a9dSDavid Matlack 		if (!r || r == -EAGAIN)
6797ada51a9dSDavid Matlack 			goto restart;
6798ada51a9dSDavid Matlack 
6799ada51a9dSDavid Matlack 		/* The split failed and shouldn't be retried (e.g. -ENOMEM). */
6800ada51a9dSDavid Matlack 		break;
6801ada51a9dSDavid Matlack 	}
6802ada51a9dSDavid Matlack 
6803ada51a9dSDavid Matlack 	return false;
6804ada51a9dSDavid Matlack }
6805ada51a9dSDavid Matlack 
6806ada51a9dSDavid Matlack static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6807ada51a9dSDavid Matlack 						const struct kvm_memory_slot *slot,
6808ada51a9dSDavid Matlack 						gfn_t start, gfn_t end,
6809ada51a9dSDavid Matlack 						int target_level)
6810ada51a9dSDavid Matlack {
6811ada51a9dSDavid Matlack 	int level;
6812ada51a9dSDavid Matlack 
6813ada51a9dSDavid Matlack 	/*
6814ada51a9dSDavid Matlack 	 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
6815ada51a9dSDavid Matlack 	 * down to the target level. This ensures pages are recursively split
6816ada51a9dSDavid Matlack 	 * all the way to the target level. There's no need to split pages
6817ada51a9dSDavid Matlack 	 * already at the target level.
6818ada51a9dSDavid Matlack 	 */
6819727ae377SSean Christopherson 	for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--)
6820727ae377SSean Christopherson 		__walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,
6821ada51a9dSDavid Matlack 				  level, level, start, end - 1, true, false);
6822ada51a9dSDavid Matlack }
6823ada51a9dSDavid Matlack 
6824cb00a70bSDavid Matlack /* Must be called with the mmu_lock held in write-mode. */
6825cb00a70bSDavid Matlack void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6826cb00a70bSDavid Matlack 				   const struct kvm_memory_slot *memslot,
6827cb00a70bSDavid Matlack 				   u64 start, u64 end,
6828cb00a70bSDavid Matlack 				   int target_level)
6829cb00a70bSDavid Matlack {
68301f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6831ada51a9dSDavid Matlack 		return;
6832ada51a9dSDavid Matlack 
6833ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm))
6834ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6835ada51a9dSDavid Matlack 
6836ada51a9dSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
6837cb00a70bSDavid Matlack 
6838cb00a70bSDavid Matlack 	/*
683954aa699eSBjorn Helgaas 	 * A TLB flush is unnecessary at this point for the same reasons as in
6840cb00a70bSDavid Matlack 	 * kvm_mmu_slot_try_split_huge_pages().
6841cb00a70bSDavid Matlack 	 */
6842cb00a70bSDavid Matlack }
6843cb00a70bSDavid Matlack 
6844a3fe5dbdSDavid Matlack void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6845a3fe5dbdSDavid Matlack 					const struct kvm_memory_slot *memslot,
6846a3fe5dbdSDavid Matlack 					int target_level)
6847a3fe5dbdSDavid Matlack {
6848a3fe5dbdSDavid Matlack 	u64 start = memslot->base_gfn;
6849a3fe5dbdSDavid Matlack 	u64 end = start + memslot->npages;
6850a3fe5dbdSDavid Matlack 
68511f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6852ada51a9dSDavid Matlack 		return;
6853ada51a9dSDavid Matlack 
6854ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm)) {
6855ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6856ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6857ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6858ada51a9dSDavid Matlack 	}
6859ada51a9dSDavid Matlack 
6860a3fe5dbdSDavid Matlack 	read_lock(&kvm->mmu_lock);
6861cb00a70bSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6862a3fe5dbdSDavid Matlack 	read_unlock(&kvm->mmu_lock);
6863a3fe5dbdSDavid Matlack 
6864a3fe5dbdSDavid Matlack 	/*
6865a3fe5dbdSDavid Matlack 	 * No TLB flush is necessary here. KVM will flush TLBs after
6866a3fe5dbdSDavid Matlack 	 * write-protecting and/or clearing dirty on the newly split SPTEs to
6867a3fe5dbdSDavid Matlack 	 * ensure that guest writes are reflected in the dirty log before the
6868a3fe5dbdSDavid Matlack 	 * ioctl to enable dirty logging on this memslot completes. Since the
6869a3fe5dbdSDavid Matlack 	 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6870a3fe5dbdSDavid Matlack 	 * safe for KVM to decide if a TLB flush is necessary based on the split
6871a3fe5dbdSDavid Matlack 	 * SPTEs.
6872a3fe5dbdSDavid Matlack 	 */
6873a3fe5dbdSDavid Matlack }
6874a3fe5dbdSDavid Matlack 
6875c50d8ae3SPaolo Bonzini static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
68760a234f5dSSean Christopherson 					 struct kvm_rmap_head *rmap_head,
6877269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
6878c50d8ae3SPaolo Bonzini {
6879c50d8ae3SPaolo Bonzini 	u64 *sptep;
6880c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
6881c50d8ae3SPaolo Bonzini 	int need_tlb_flush = 0;
6882c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6883c50d8ae3SPaolo Bonzini 
6884c50d8ae3SPaolo Bonzini restart:
6885c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
688657354682SSean Christopherson 		sp = sptep_to_sp(sptep);
6887c50d8ae3SPaolo Bonzini 
6888c50d8ae3SPaolo Bonzini 		/*
6889c50d8ae3SPaolo Bonzini 		 * We cannot do huge page mapping for indirect shadow pages,
6890c50d8ae3SPaolo Bonzini 		 * which are found on the last rmap (level = 1) when not using
6891c50d8ae3SPaolo Bonzini 		 * tdp; such shadow pages are synced with the page table in
6892c50d8ae3SPaolo Bonzini 		 * the guest, and the guest page table is using 4K page size
6893c50d8ae3SPaolo Bonzini 		 * mapping if the indirect sp has level = 1.
6894c50d8ae3SPaolo Bonzini 		 */
68955d49f08cSSean Christopherson 		if (sp->role.direct &&
68969eba50f8SSean Christopherson 		    sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
6897a8ac499bSSean Christopherson 							       PG_LEVEL_NUM)) {
68989202aee8SSean Christopherson 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
6899c50d8ae3SPaolo Bonzini 
69008a1300ffSSean Christopherson 			if (kvm_available_flush_remote_tlbs_range())
69011b2dc736SHou Wenlong 				kvm_flush_remote_tlbs_sptep(kvm, sptep);
6902c50d8ae3SPaolo Bonzini 			else
6903c50d8ae3SPaolo Bonzini 				need_tlb_flush = 1;
6904c50d8ae3SPaolo Bonzini 
6905c50d8ae3SPaolo Bonzini 			goto restart;
6906c50d8ae3SPaolo Bonzini 		}
6907c50d8ae3SPaolo Bonzini 	}
6908c50d8ae3SPaolo Bonzini 
6909c50d8ae3SPaolo Bonzini 	return need_tlb_flush;
6910c50d8ae3SPaolo Bonzini }
6911c63cf135SBrijesh Singh EXPORT_SYMBOL_GPL(kvm_zap_gfn_range);
6912c50d8ae3SPaolo Bonzini 
691320d49186SDavid Matlack static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
691420d49186SDavid Matlack 					   const struct kvm_memory_slot *slot)
691520d49186SDavid Matlack {
691620d49186SDavid Matlack 	/*
691720d49186SDavid Matlack 	 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
691820d49186SDavid Matlack 	 * pages that are already mapped at the maximum hugepage level.
691920d49186SDavid Matlack 	 */
6920727ae377SSean Christopherson 	if (walk_slot_rmaps(kvm, slot, kvm_mmu_zap_collapsible_spte,
692120d49186SDavid Matlack 			    PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
6922619b5072SDavid Matlack 		kvm_flush_remote_tlbs_memslot(kvm, slot);
692320d49186SDavid Matlack }
692420d49186SDavid Matlack 
6925c50d8ae3SPaolo Bonzini void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6926269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *slot)
6927c50d8ae3SPaolo Bonzini {
6928e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6929531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
693020d49186SDavid Matlack 		kvm_rmap_zap_collapsible_sptes(kvm, slot);
6931531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6932e2209710SBen Gardon 	}
69332db6f772SBen Gardon 
69341f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
69352db6f772SBen Gardon 		read_lock(&kvm->mmu_lock);
69364b85c921SSean Christopherson 		kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
69372db6f772SBen Gardon 		read_unlock(&kvm->mmu_lock);
69382db6f772SBen Gardon 	}
6939c50d8ae3SPaolo Bonzini }
6940c50d8ae3SPaolo Bonzini 
6941c50d8ae3SPaolo Bonzini void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6942269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *memslot)
6943c50d8ae3SPaolo Bonzini {
6944e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6945531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6946610265eaSDavid Matlack 		/*
6947610265eaSDavid Matlack 		 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6948610265eaSDavid Matlack 		 * support dirty logging at a 4k granularity.
6949610265eaSDavid Matlack 		 */
6950727ae377SSean Christopherson 		walk_slot_rmaps_4k(kvm, memslot, __rmap_clear_dirty, false);
6951531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6952e2209710SBen Gardon 	}
6953c50d8ae3SPaolo Bonzini 
69541f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
695524ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6956b64d740eSJunaid Shahid 		kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
695724ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
695824ae4cfaSBen Gardon 	}
695924ae4cfaSBen Gardon 
6960c50d8ae3SPaolo Bonzini 	/*
6961b64d740eSJunaid Shahid 	 * The caller will flush the TLBs after this function returns.
6962b64d740eSJunaid Shahid 	 *
6963c50d8ae3SPaolo Bonzini 	 * It's also safe to flush TLBs out of mmu lock here as currently this
6964c50d8ae3SPaolo Bonzini 	 * function is only used for dirty logging, in which case flushing TLB
6965c50d8ae3SPaolo Bonzini 	 * out of mmu lock also guarantees no dirty pages will be lost in
6966c50d8ae3SPaolo Bonzini 	 * dirty_bitmap.
6967c50d8ae3SPaolo Bonzini 	 */
6968c50d8ae3SPaolo Bonzini }
6969c50d8ae3SPaolo Bonzini 
6970db0d70e6SSean Christopherson static void kvm_mmu_zap_all(struct kvm *kvm)
6971c50d8ae3SPaolo Bonzini {
6972c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6973c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6974c50d8ae3SPaolo Bonzini 	int ign;
6975c50d8ae3SPaolo Bonzini 
6976531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6977c50d8ae3SPaolo Bonzini restart:
6978c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
697920ba462dSSean Christopherson 		if (WARN_ON_ONCE(sp->role.invalid))
6980c50d8ae3SPaolo Bonzini 			continue;
6981c50d8ae3SPaolo Bonzini 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6982c50d8ae3SPaolo Bonzini 			goto restart;
6983531810caSBen Gardon 		if (cond_resched_rwlock_write(&kvm->mmu_lock))
6984c50d8ae3SPaolo Bonzini 			goto restart;
6985c50d8ae3SPaolo Bonzini 	}
6986c50d8ae3SPaolo Bonzini 
6987c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6988faaf05b0SBen Gardon 
69891f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6990faaf05b0SBen Gardon 		kvm_tdp_mmu_zap_all(kvm);
6991faaf05b0SBen Gardon 
6992531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
6993c50d8ae3SPaolo Bonzini }
6994c50d8ae3SPaolo Bonzini 
6995db0d70e6SSean Christopherson void kvm_arch_flush_shadow_all(struct kvm *kvm)
6996db0d70e6SSean Christopherson {
6997db0d70e6SSean Christopherson 	kvm_mmu_zap_all(kvm);
6998db0d70e6SSean Christopherson }
6999db0d70e6SSean Christopherson 
7000db0d70e6SSean Christopherson void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
7001db0d70e6SSean Christopherson 				   struct kvm_memory_slot *slot)
7002db0d70e6SSean Christopherson {
7003eeb87272SSean Christopherson 	kvm_mmu_zap_all_fast(kvm);
7004db0d70e6SSean Christopherson }
7005db0d70e6SSean Christopherson 
7006c50d8ae3SPaolo Bonzini void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
7007c50d8ae3SPaolo Bonzini {
700820ba462dSSean Christopherson 	WARN_ON_ONCE(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
7009c50d8ae3SPaolo Bonzini 
7010c50d8ae3SPaolo Bonzini 	gen &= MMIO_SPTE_GEN_MASK;
7011c50d8ae3SPaolo Bonzini 
7012c50d8ae3SPaolo Bonzini 	/*
7013c50d8ae3SPaolo Bonzini 	 * Generation numbers are incremented in multiples of the number of
7014c50d8ae3SPaolo Bonzini 	 * address spaces in order to provide unique generations across all
7015c50d8ae3SPaolo Bonzini 	 * address spaces.  Strip what is effectively the address space
7016c50d8ae3SPaolo Bonzini 	 * modifier prior to checking for a wrap of the MMIO generation so
7017c50d8ae3SPaolo Bonzini 	 * that a wrap in any address space is detected.
7018c50d8ae3SPaolo Bonzini 	 */
7019eed52e43SSean Christopherson 	gen &= ~((u64)kvm_arch_nr_memslot_as_ids(kvm) - 1);
7020c50d8ae3SPaolo Bonzini 
7021c50d8ae3SPaolo Bonzini 	/*
7022c50d8ae3SPaolo Bonzini 	 * The very rare case: if the MMIO generation number has wrapped,
7023c50d8ae3SPaolo Bonzini 	 * zap all shadow pages.
7024c50d8ae3SPaolo Bonzini 	 */
7025c50d8ae3SPaolo Bonzini 	if (unlikely(gen == 0)) {
70268d20bd63SSean Christopherson 		kvm_debug_ratelimited("zapping shadow pages for mmio generation wraparound\n");
7027c50d8ae3SPaolo Bonzini 		kvm_mmu_zap_all_fast(kvm);
7028c50d8ae3SPaolo Bonzini 	}
7029c50d8ae3SPaolo Bonzini }
7030c50d8ae3SPaolo Bonzini 
7031f3d90f90SSean Christopherson static unsigned long mmu_shrink_scan(struct shrinker *shrink,
7032f3d90f90SSean Christopherson 				     struct shrink_control *sc)
7033c50d8ae3SPaolo Bonzini {
7034c50d8ae3SPaolo Bonzini 	struct kvm *kvm;
7035c50d8ae3SPaolo Bonzini 	int nr_to_scan = sc->nr_to_scan;
7036c50d8ae3SPaolo Bonzini 	unsigned long freed = 0;
7037c50d8ae3SPaolo Bonzini 
7038c50d8ae3SPaolo Bonzini 	mutex_lock(&kvm_lock);
7039c50d8ae3SPaolo Bonzini 
7040c50d8ae3SPaolo Bonzini 	list_for_each_entry(kvm, &vm_list, vm_list) {
7041c50d8ae3SPaolo Bonzini 		int idx;
7042c50d8ae3SPaolo Bonzini 
7043c50d8ae3SPaolo Bonzini 		/*
7044c50d8ae3SPaolo Bonzini 		 * Never scan more than sc->nr_to_scan VM instances.
7045c50d8ae3SPaolo Bonzini 		 * Will not hit this condition practically since we do not try
7046c50d8ae3SPaolo Bonzini 		 * to shrink more than one VM and it is very unlikely to see
7047c50d8ae3SPaolo Bonzini 		 * !n_used_mmu_pages so many times.
7048c50d8ae3SPaolo Bonzini 		 */
7049c50d8ae3SPaolo Bonzini 		if (!nr_to_scan--)
7050c50d8ae3SPaolo Bonzini 			break;
7051c50d8ae3SPaolo Bonzini 		/*
7052c50d8ae3SPaolo Bonzini 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
7053c50d8ae3SPaolo Bonzini 		 * here. We may skip a VM instance errorneosly, but we do not
7054c50d8ae3SPaolo Bonzini 		 * want to shrink a VM that only started to populate its MMU
7055c50d8ae3SPaolo Bonzini 		 * anyway.
7056c50d8ae3SPaolo Bonzini 		 */
7057c50d8ae3SPaolo Bonzini 		if (!kvm->arch.n_used_mmu_pages &&
7058c50d8ae3SPaolo Bonzini 		    !kvm_has_zapped_obsolete_pages(kvm))
7059c50d8ae3SPaolo Bonzini 			continue;
7060c50d8ae3SPaolo Bonzini 
7061c50d8ae3SPaolo Bonzini 		idx = srcu_read_lock(&kvm->srcu);
7062531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
7063c50d8ae3SPaolo Bonzini 
7064c50d8ae3SPaolo Bonzini 		if (kvm_has_zapped_obsolete_pages(kvm)) {
7065c50d8ae3SPaolo Bonzini 			kvm_mmu_commit_zap_page(kvm,
7066c50d8ae3SPaolo Bonzini 			      &kvm->arch.zapped_obsolete_pages);
7067c50d8ae3SPaolo Bonzini 			goto unlock;
7068c50d8ae3SPaolo Bonzini 		}
7069c50d8ae3SPaolo Bonzini 
7070ebdb292dSSean Christopherson 		freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
7071c50d8ae3SPaolo Bonzini 
7072c50d8ae3SPaolo Bonzini unlock:
7073531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
7074c50d8ae3SPaolo Bonzini 		srcu_read_unlock(&kvm->srcu, idx);
7075c50d8ae3SPaolo Bonzini 
7076c50d8ae3SPaolo Bonzini 		/*
7077c50d8ae3SPaolo Bonzini 		 * unfair on small ones
7078c50d8ae3SPaolo Bonzini 		 * per-vm shrinkers cry out
7079c50d8ae3SPaolo Bonzini 		 * sadness comes quickly
7080c50d8ae3SPaolo Bonzini 		 */
7081c50d8ae3SPaolo Bonzini 		list_move_tail(&kvm->vm_list, &vm_list);
7082c50d8ae3SPaolo Bonzini 		break;
7083c50d8ae3SPaolo Bonzini 	}
7084c50d8ae3SPaolo Bonzini 
7085c50d8ae3SPaolo Bonzini 	mutex_unlock(&kvm_lock);
7086c50d8ae3SPaolo Bonzini 	return freed;
7087c50d8ae3SPaolo Bonzini }
7088c50d8ae3SPaolo Bonzini 
7089f3d90f90SSean Christopherson static unsigned long mmu_shrink_count(struct shrinker *shrink,
7090f3d90f90SSean Christopherson 				      struct shrink_control *sc)
7091c50d8ae3SPaolo Bonzini {
7092c50d8ae3SPaolo Bonzini 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
7093c50d8ae3SPaolo Bonzini }
7094c50d8ae3SPaolo Bonzini 
7095e5985c40SQi Zheng static struct shrinker *mmu_shrinker;
7096c50d8ae3SPaolo Bonzini 
7097c50d8ae3SPaolo Bonzini static void mmu_destroy_caches(void)
7098c50d8ae3SPaolo Bonzini {
7099c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(pte_list_desc_cache);
7100c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(mmu_page_header_cache);
7101c50d8ae3SPaolo Bonzini }
7102c50d8ae3SPaolo Bonzini 
71030b210fafSSean Christopherson static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp)
71040b210fafSSean Christopherson {
71050b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
71061d6664faSLike Xu 		return sysfs_emit(buffer, "never\n");
71070b210fafSSean Christopherson 
71080b210fafSSean Christopherson 	return param_get_bool(buffer, kp);
71090b210fafSSean Christopherson }
71100b210fafSSean Christopherson 
7111c50d8ae3SPaolo Bonzini static bool get_nx_auto_mode(void)
7112c50d8ae3SPaolo Bonzini {
7113c50d8ae3SPaolo Bonzini 	/* Return true when CPU has the bug, and mitigations are ON */
7114c50d8ae3SPaolo Bonzini 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
7115c50d8ae3SPaolo Bonzini }
7116c50d8ae3SPaolo Bonzini 
7117c50d8ae3SPaolo Bonzini static void __set_nx_huge_pages(bool val)
7118c50d8ae3SPaolo Bonzini {
7119c50d8ae3SPaolo Bonzini 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
7120c50d8ae3SPaolo Bonzini }
7121c50d8ae3SPaolo Bonzini 
7122c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
7123c50d8ae3SPaolo Bonzini {
7124c50d8ae3SPaolo Bonzini 	bool old_val = nx_huge_pages;
7125c50d8ae3SPaolo Bonzini 	bool new_val;
7126c50d8ae3SPaolo Bonzini 
71270b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
71280b210fafSSean Christopherson 		return -EPERM;
71290b210fafSSean Christopherson 
7130c50d8ae3SPaolo Bonzini 	/* In "auto" mode deploy workaround only if CPU has the bug. */
71310b210fafSSean Christopherson 	if (sysfs_streq(val, "off")) {
7132c50d8ae3SPaolo Bonzini 		new_val = 0;
71330b210fafSSean Christopherson 	} else if (sysfs_streq(val, "force")) {
7134c50d8ae3SPaolo Bonzini 		new_val = 1;
71350b210fafSSean Christopherson 	} else if (sysfs_streq(val, "auto")) {
7136c50d8ae3SPaolo Bonzini 		new_val = get_nx_auto_mode();
71370b210fafSSean Christopherson 	} else if (sysfs_streq(val, "never")) {
71380b210fafSSean Christopherson 		new_val = 0;
71390b210fafSSean Christopherson 
71400b210fafSSean Christopherson 		mutex_lock(&kvm_lock);
71410b210fafSSean Christopherson 		if (!list_empty(&vm_list)) {
71420b210fafSSean Christopherson 			mutex_unlock(&kvm_lock);
71430b210fafSSean Christopherson 			return -EBUSY;
71440b210fafSSean Christopherson 		}
71450b210fafSSean Christopherson 		nx_hugepage_mitigation_hard_disabled = true;
71460b210fafSSean Christopherson 		mutex_unlock(&kvm_lock);
71470b210fafSSean Christopherson 	} else if (kstrtobool(val, &new_val) < 0) {
7148c50d8ae3SPaolo Bonzini 		return -EINVAL;
71490b210fafSSean Christopherson 	}
7150c50d8ae3SPaolo Bonzini 
7151c50d8ae3SPaolo Bonzini 	__set_nx_huge_pages(new_val);
7152c50d8ae3SPaolo Bonzini 
7153c50d8ae3SPaolo Bonzini 	if (new_val != old_val) {
7154c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
7155c50d8ae3SPaolo Bonzini 
7156c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
7157c50d8ae3SPaolo Bonzini 
7158c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list) {
7159c50d8ae3SPaolo Bonzini 			mutex_lock(&kvm->slots_lock);
7160c50d8ae3SPaolo Bonzini 			kvm_mmu_zap_all_fast(kvm);
7161c50d8ae3SPaolo Bonzini 			mutex_unlock(&kvm->slots_lock);
7162c50d8ae3SPaolo Bonzini 
716355c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
7164c50d8ae3SPaolo Bonzini 		}
7165c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
7166c50d8ae3SPaolo Bonzini 	}
7167c50d8ae3SPaolo Bonzini 
7168c50d8ae3SPaolo Bonzini 	return 0;
7169c50d8ae3SPaolo Bonzini }
7170c50d8ae3SPaolo Bonzini 
71711d0e8480SSean Christopherson /*
71721d0e8480SSean Christopherson  * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
71731d0e8480SSean Christopherson  * its default value of -1 is technically undefined behavior for a boolean.
7174c3e0c8c2SSean Christopherson  * Forward the module init call to SPTE code so that it too can handle module
7175c3e0c8c2SSean Christopherson  * params that need to be resolved/snapshot.
71761d0e8480SSean Christopherson  */
7177982bae43SSean Christopherson void __init kvm_mmu_x86_module_init(void)
7178c50d8ae3SPaolo Bonzini {
7179c50d8ae3SPaolo Bonzini 	if (nx_huge_pages == -1)
7180c50d8ae3SPaolo Bonzini 		__set_nx_huge_pages(get_nx_auto_mode());
7181c3e0c8c2SSean Christopherson 
71821f98f2bdSDavid Matlack 	/*
71831f98f2bdSDavid Matlack 	 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
71841f98f2bdSDavid Matlack 	 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
71851f98f2bdSDavid Matlack 	 * when the vendor module is loaded.
71861f98f2bdSDavid Matlack 	 */
71871f98f2bdSDavid Matlack 	tdp_mmu_allowed = tdp_mmu_enabled;
71881f98f2bdSDavid Matlack 
7189c3e0c8c2SSean Christopherson 	kvm_mmu_spte_module_init();
71901d0e8480SSean Christopherson }
71911d0e8480SSean Christopherson 
71921d0e8480SSean Christopherson /*
71931d0e8480SSean Christopherson  * The bulk of the MMU initialization is deferred until the vendor module is
71941d0e8480SSean Christopherson  * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
71951d0e8480SSean Christopherson  * to be reset when a potentially different vendor module is loaded.
71961d0e8480SSean Christopherson  */
71971d0e8480SSean Christopherson int kvm_mmu_vendor_module_init(void)
71981d0e8480SSean Christopherson {
71991d0e8480SSean Christopherson 	int ret = -ENOMEM;
7200c50d8ae3SPaolo Bonzini 
7201c50d8ae3SPaolo Bonzini 	/*
7202c50d8ae3SPaolo Bonzini 	 * MMU roles use union aliasing which is, generally speaking, an
7203c50d8ae3SPaolo Bonzini 	 * undefined behavior. However, we supposedly know how compilers behave
7204c50d8ae3SPaolo Bonzini 	 * and the current status quo is unlikely to change. Guardians below are
7205c50d8ae3SPaolo Bonzini 	 * supposed to let us know if the assumption becomes false.
7206c50d8ae3SPaolo Bonzini 	 */
7207c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
7208c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
72097a7ae829SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
7210c50d8ae3SPaolo Bonzini 
7211c50d8ae3SPaolo Bonzini 	kvm_mmu_reset_all_pte_masks();
7212c50d8ae3SPaolo Bonzini 
72130dbd0546SKunwu Chan 	pte_list_desc_cache = KMEM_CACHE(pte_list_desc, SLAB_ACCOUNT);
7214c50d8ae3SPaolo Bonzini 	if (!pte_list_desc_cache)
7215c50d8ae3SPaolo Bonzini 		goto out;
7216c50d8ae3SPaolo Bonzini 
7217c50d8ae3SPaolo Bonzini 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
7218c50d8ae3SPaolo Bonzini 						  sizeof(struct kvm_mmu_page),
7219c50d8ae3SPaolo Bonzini 						  0, SLAB_ACCOUNT, NULL);
7220c50d8ae3SPaolo Bonzini 	if (!mmu_page_header_cache)
7221c50d8ae3SPaolo Bonzini 		goto out;
7222c50d8ae3SPaolo Bonzini 
7223c50d8ae3SPaolo Bonzini 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
7224c50d8ae3SPaolo Bonzini 		goto out;
7225c50d8ae3SPaolo Bonzini 
7226e5985c40SQi Zheng 	mmu_shrinker = shrinker_alloc(0, "x86-mmu");
7227e5985c40SQi Zheng 	if (!mmu_shrinker)
7228d7c9bfb9SMiaohe Lin 		goto out_shrinker;
7229c50d8ae3SPaolo Bonzini 
7230e5985c40SQi Zheng 	mmu_shrinker->count_objects = mmu_shrink_count;
7231e5985c40SQi Zheng 	mmu_shrinker->scan_objects = mmu_shrink_scan;
7232e5985c40SQi Zheng 	mmu_shrinker->seeks = DEFAULT_SEEKS * 10;
7233e5985c40SQi Zheng 
7234e5985c40SQi Zheng 	shrinker_register(mmu_shrinker);
7235e5985c40SQi Zheng 
7236c50d8ae3SPaolo Bonzini 	return 0;
7237c50d8ae3SPaolo Bonzini 
7238d7c9bfb9SMiaohe Lin out_shrinker:
7239d7c9bfb9SMiaohe Lin 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
7240c50d8ae3SPaolo Bonzini out:
7241c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
7242c50d8ae3SPaolo Bonzini 	return ret;
7243c50d8ae3SPaolo Bonzini }
7244c50d8ae3SPaolo Bonzini 
7245c50d8ae3SPaolo Bonzini void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
7246c50d8ae3SPaolo Bonzini {
7247c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
7248c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.root_mmu);
7249c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
7250c50d8ae3SPaolo Bonzini 	mmu_free_memory_caches(vcpu);
7251c50d8ae3SPaolo Bonzini }
7252c50d8ae3SPaolo Bonzini 
72531d0e8480SSean Christopherson void kvm_mmu_vendor_module_exit(void)
7254c50d8ae3SPaolo Bonzini {
7255c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
7256c50d8ae3SPaolo Bonzini 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
7257e5985c40SQi Zheng 	shrinker_free(mmu_shrinker);
7258c50d8ae3SPaolo Bonzini }
7259c50d8ae3SPaolo Bonzini 
7260f47491d7SSean Christopherson /*
7261f47491d7SSean Christopherson  * Calculate the effective recovery period, accounting for '0' meaning "let KVM
7262f47491d7SSean Christopherson  * select a halving time of 1 hour".  Returns true if recovery is enabled.
7263f47491d7SSean Christopherson  */
7264f47491d7SSean Christopherson static bool calc_nx_huge_pages_recovery_period(uint *period)
7265f47491d7SSean Christopherson {
7266f47491d7SSean Christopherson 	/*
7267f47491d7SSean Christopherson 	 * Use READ_ONCE to get the params, this may be called outside of the
7268f47491d7SSean Christopherson 	 * param setters, e.g. by the kthread to compute its next timeout.
7269f47491d7SSean Christopherson 	 */
7270f47491d7SSean Christopherson 	bool enabled = READ_ONCE(nx_huge_pages);
7271f47491d7SSean Christopherson 	uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7272f47491d7SSean Christopherson 
7273f47491d7SSean Christopherson 	if (!enabled || !ratio)
7274f47491d7SSean Christopherson 		return false;
7275f47491d7SSean Christopherson 
7276f47491d7SSean Christopherson 	*period = READ_ONCE(nx_huge_pages_recovery_period_ms);
7277f47491d7SSean Christopherson 	if (!*period) {
7278f47491d7SSean Christopherson 		/* Make sure the period is not less than one second.  */
7279f47491d7SSean Christopherson 		ratio = min(ratio, 3600u);
7280f47491d7SSean Christopherson 		*period = 60 * 60 * 1000 / ratio;
7281f47491d7SSean Christopherson 	}
7282f47491d7SSean Christopherson 	return true;
7283f47491d7SSean Christopherson }
7284f47491d7SSean Christopherson 
72854dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
7286c50d8ae3SPaolo Bonzini {
72874dfe4f40SJunaid Shahid 	bool was_recovery_enabled, is_recovery_enabled;
72884dfe4f40SJunaid Shahid 	uint old_period, new_period;
7289c50d8ae3SPaolo Bonzini 	int err;
7290c50d8ae3SPaolo Bonzini 
72910b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
72920b210fafSSean Christopherson 		return -EPERM;
72930b210fafSSean Christopherson 
7294f47491d7SSean Christopherson 	was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
72954dfe4f40SJunaid Shahid 
7296c50d8ae3SPaolo Bonzini 	err = param_set_uint(val, kp);
7297c50d8ae3SPaolo Bonzini 	if (err)
7298c50d8ae3SPaolo Bonzini 		return err;
7299c50d8ae3SPaolo Bonzini 
7300f47491d7SSean Christopherson 	is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
73014dfe4f40SJunaid Shahid 
7302f47491d7SSean Christopherson 	if (is_recovery_enabled &&
73034dfe4f40SJunaid Shahid 	    (!was_recovery_enabled || old_period > new_period)) {
7304c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
7305c50d8ae3SPaolo Bonzini 
7306c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
7307c50d8ae3SPaolo Bonzini 
7308c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list)
730955c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
7310c50d8ae3SPaolo Bonzini 
7311c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
7312c50d8ae3SPaolo Bonzini 	}
7313c50d8ae3SPaolo Bonzini 
7314c50d8ae3SPaolo Bonzini 	return err;
7315c50d8ae3SPaolo Bonzini }
7316c50d8ae3SPaolo Bonzini 
731755c510e2SSean Christopherson static void kvm_recover_nx_huge_pages(struct kvm *kvm)
7318c50d8ae3SPaolo Bonzini {
7319ade74e14SSean Christopherson 	unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
7320eb298605SDavid Matlack 	struct kvm_memory_slot *slot;
7321c50d8ae3SPaolo Bonzini 	int rcu_idx;
7322c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
7323c50d8ae3SPaolo Bonzini 	unsigned int ratio;
7324c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
7325048f4980SSean Christopherson 	bool flush = false;
7326c50d8ae3SPaolo Bonzini 	ulong to_zap;
7327c50d8ae3SPaolo Bonzini 
7328c50d8ae3SPaolo Bonzini 	rcu_idx = srcu_read_lock(&kvm->srcu);
7329531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
7330c50d8ae3SPaolo Bonzini 
7331bb95dfb9SSean Christopherson 	/*
7332bb95dfb9SSean Christopherson 	 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
7333bb95dfb9SSean Christopherson 	 * be done under RCU protection, because the pages are freed via RCU
7334bb95dfb9SSean Christopherson 	 * callback.
7335bb95dfb9SSean Christopherson 	 */
7336bb95dfb9SSean Christopherson 	rcu_read_lock();
7337bb95dfb9SSean Christopherson 
7338c50d8ae3SPaolo Bonzini 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7339ade74e14SSean Christopherson 	to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
73407d919c7aSSean Christopherson 	for ( ; to_zap; --to_zap) {
734155c510e2SSean Christopherson 		if (list_empty(&kvm->arch.possible_nx_huge_pages))
73427d919c7aSSean Christopherson 			break;
73437d919c7aSSean Christopherson 
7344c50d8ae3SPaolo Bonzini 		/*
7345c50d8ae3SPaolo Bonzini 		 * We use a separate list instead of just using active_mmu_pages
734655c510e2SSean Christopherson 		 * because the number of shadow pages that be replaced with an
734755c510e2SSean Christopherson 		 * NX huge page is expected to be relatively small compared to
734855c510e2SSean Christopherson 		 * the total number of shadow pages.  And because the TDP MMU
734955c510e2SSean Christopherson 		 * doesn't use active_mmu_pages.
7350c50d8ae3SPaolo Bonzini 		 */
735155c510e2SSean Christopherson 		sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
7352c50d8ae3SPaolo Bonzini 				      struct kvm_mmu_page,
735355c510e2SSean Christopherson 				      possible_nx_huge_page_link);
735455c510e2SSean Christopherson 		WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
7355eb298605SDavid Matlack 		WARN_ON_ONCE(!sp->role.direct);
7356eb298605SDavid Matlack 
7357eb298605SDavid Matlack 		/*
7358eb298605SDavid Matlack 		 * Unaccount and do not attempt to recover any NX Huge Pages
7359eb298605SDavid Matlack 		 * that are being dirty tracked, as they would just be faulted
7360eb298605SDavid Matlack 		 * back in as 4KiB pages. The NX Huge Pages in this slot will be
7361eb298605SDavid Matlack 		 * recovered, along with all the other huge pages in the slot,
7362eb298605SDavid Matlack 		 * when dirty logging is disabled.
73636c7b2202SPaolo Bonzini 		 *
73646c7b2202SPaolo Bonzini 		 * Since gfn_to_memslot() is relatively expensive, it helps to
73656c7b2202SPaolo Bonzini 		 * skip it if it the test cannot possibly return true.  On the
73666c7b2202SPaolo Bonzini 		 * other hand, if any memslot has logging enabled, chances are
73676c7b2202SPaolo Bonzini 		 * good that all of them do, in which case unaccount_nx_huge_page()
73686c7b2202SPaolo Bonzini 		 * is much cheaper than zapping the page.
73696c7b2202SPaolo Bonzini 		 *
73706c7b2202SPaolo Bonzini 		 * If a memslot update is in progress, reading an incorrect value
73716c7b2202SPaolo Bonzini 		 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
73726c7b2202SPaolo Bonzini 		 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
73736c7b2202SPaolo Bonzini 		 * it is becoming nonzero, the page will be zapped unnecessarily.
73746c7b2202SPaolo Bonzini 		 * Either way, this only affects efficiency in racy situations,
73756c7b2202SPaolo Bonzini 		 * and not correctness.
7376eb298605SDavid Matlack 		 */
73776c7b2202SPaolo Bonzini 		slot = NULL;
73786c7b2202SPaolo Bonzini 		if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
7379817fa998SSean Christopherson 			struct kvm_memslots *slots;
7380817fa998SSean Christopherson 
7381817fa998SSean Christopherson 			slots = kvm_memslots_for_spte_role(kvm, sp->role);
7382817fa998SSean Christopherson 			slot = __gfn_to_memslot(slots, sp->gfn);
73836c7b2202SPaolo Bonzini 			WARN_ON_ONCE(!slot);
738429cf0f50SBen Gardon 		}
7385c50d8ae3SPaolo Bonzini 
7386eb298605SDavid Matlack 		if (slot && kvm_slot_dirty_track_enabled(slot))
7387eb298605SDavid Matlack 			unaccount_nx_huge_page(kvm, sp);
7388eb298605SDavid Matlack 		else if (is_tdp_mmu_page(sp))
7389c50d8ae3SPaolo Bonzini 			flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
73903a056757SSean Christopherson 		else
7391c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
739255c510e2SSean Christopherson 		WARN_ON_ONCE(sp->nx_huge_page_disallowed);
7393c50d8ae3SPaolo Bonzini 
7394531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7395048f4980SSean Christopherson 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7396bb95dfb9SSean Christopherson 			rcu_read_unlock();
7397bb95dfb9SSean Christopherson 
7398531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
7399048f4980SSean Christopherson 			flush = false;
7400bb95dfb9SSean Christopherson 
7401bb95dfb9SSean Christopherson 			rcu_read_lock();
7402c50d8ae3SPaolo Bonzini 		}
7403c50d8ae3SPaolo Bonzini 	}
7404048f4980SSean Christopherson 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7405c50d8ae3SPaolo Bonzini 
7406bb95dfb9SSean Christopherson 	rcu_read_unlock();
7407bb95dfb9SSean Christopherson 
7408531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
7409c50d8ae3SPaolo Bonzini 	srcu_read_unlock(&kvm->srcu, rcu_idx);
7410c50d8ae3SPaolo Bonzini }
7411c50d8ae3SPaolo Bonzini 
741255c510e2SSean Christopherson static long get_nx_huge_page_recovery_timeout(u64 start_time)
7413c50d8ae3SPaolo Bonzini {
7414f47491d7SSean Christopherson 	bool enabled;
7415f47491d7SSean Christopherson 	uint period;
74164dfe4f40SJunaid Shahid 
7417f47491d7SSean Christopherson 	enabled = calc_nx_huge_pages_recovery_period(&period);
74184dfe4f40SJunaid Shahid 
7419f47491d7SSean Christopherson 	return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
7420c50d8ae3SPaolo Bonzini 		       : MAX_SCHEDULE_TIMEOUT;
7421c50d8ae3SPaolo Bonzini }
7422c50d8ae3SPaolo Bonzini 
742355c510e2SSean Christopherson static int kvm_nx_huge_page_recovery_worker(struct kvm *kvm, uintptr_t data)
7424c50d8ae3SPaolo Bonzini {
7425c50d8ae3SPaolo Bonzini 	u64 start_time;
7426c50d8ae3SPaolo Bonzini 	long remaining_time;
7427c50d8ae3SPaolo Bonzini 
7428c50d8ae3SPaolo Bonzini 	while (true) {
7429c50d8ae3SPaolo Bonzini 		start_time = get_jiffies_64();
743055c510e2SSean Christopherson 		remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7431c50d8ae3SPaolo Bonzini 
7432c50d8ae3SPaolo Bonzini 		set_current_state(TASK_INTERRUPTIBLE);
7433c50d8ae3SPaolo Bonzini 		while (!kthread_should_stop() && remaining_time > 0) {
7434c50d8ae3SPaolo Bonzini 			schedule_timeout(remaining_time);
743555c510e2SSean Christopherson 			remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7436c50d8ae3SPaolo Bonzini 			set_current_state(TASK_INTERRUPTIBLE);
7437c50d8ae3SPaolo Bonzini 		}
7438c50d8ae3SPaolo Bonzini 
7439c50d8ae3SPaolo Bonzini 		set_current_state(TASK_RUNNING);
7440c50d8ae3SPaolo Bonzini 
7441c50d8ae3SPaolo Bonzini 		if (kthread_should_stop())
7442c50d8ae3SPaolo Bonzini 			return 0;
7443c50d8ae3SPaolo Bonzini 
744455c510e2SSean Christopherson 		kvm_recover_nx_huge_pages(kvm);
7445c50d8ae3SPaolo Bonzini 	}
7446c50d8ae3SPaolo Bonzini }
7447c50d8ae3SPaolo Bonzini 
7448c50d8ae3SPaolo Bonzini int kvm_mmu_post_init_vm(struct kvm *kvm)
7449c50d8ae3SPaolo Bonzini {
7450c50d8ae3SPaolo Bonzini 	int err;
7451c50d8ae3SPaolo Bonzini 
74520b210fafSSean Christopherson 	if (nx_hugepage_mitigation_hard_disabled)
74530b210fafSSean Christopherson 		return 0;
74540b210fafSSean Christopherson 
745555c510e2SSean Christopherson 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_huge_page_recovery_worker, 0,
7456c50d8ae3SPaolo Bonzini 					  "kvm-nx-lpage-recovery",
745755c510e2SSean Christopherson 					  &kvm->arch.nx_huge_page_recovery_thread);
7458c50d8ae3SPaolo Bonzini 	if (!err)
745955c510e2SSean Christopherson 		kthread_unpark(kvm->arch.nx_huge_page_recovery_thread);
7460c50d8ae3SPaolo Bonzini 
7461c50d8ae3SPaolo Bonzini 	return err;
7462c50d8ae3SPaolo Bonzini }
7463c50d8ae3SPaolo Bonzini 
7464c50d8ae3SPaolo Bonzini void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7465c50d8ae3SPaolo Bonzini {
746655c510e2SSean Christopherson 	if (kvm->arch.nx_huge_page_recovery_thread)
746755c510e2SSean Christopherson 		kthread_stop(kvm->arch.nx_huge_page_recovery_thread);
7468c50d8ae3SPaolo Bonzini }
746990b4fe17SChao Peng 
747090b4fe17SChao Peng #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
74718dd2eee9SChao Peng bool kvm_arch_pre_set_memory_attributes(struct kvm *kvm,
74728dd2eee9SChao Peng 					struct kvm_gfn_range *range)
74738dd2eee9SChao Peng {
74748dd2eee9SChao Peng 	/*
74758dd2eee9SChao Peng 	 * Zap SPTEs even if the slot can't be mapped PRIVATE.  KVM x86 only
74768dd2eee9SChao Peng 	 * supports KVM_MEMORY_ATTRIBUTE_PRIVATE, and so it *seems* like KVM
74778dd2eee9SChao Peng 	 * can simply ignore such slots.  But if userspace is making memory
74788dd2eee9SChao Peng 	 * PRIVATE, then KVM must prevent the guest from accessing the memory
74798dd2eee9SChao Peng 	 * as shared.  And if userspace is making memory SHARED and this point
74808dd2eee9SChao Peng 	 * is reached, then at least one page within the range was previously
74818dd2eee9SChao Peng 	 * PRIVATE, i.e. the slot's possible hugepage ranges are changing.
74828dd2eee9SChao Peng 	 * Zapping SPTEs in this case ensures KVM will reassess whether or not
74838dd2eee9SChao Peng 	 * a hugepage can be used for affected ranges.
74848dd2eee9SChao Peng 	 */
74858dd2eee9SChao Peng 	if (WARN_ON_ONCE(!kvm_arch_has_private_mem(kvm)))
74868dd2eee9SChao Peng 		return false;
74878dd2eee9SChao Peng 
74888dd2eee9SChao Peng 	return kvm_unmap_gfn_range(kvm, range);
74898dd2eee9SChao Peng }
74908dd2eee9SChao Peng 
749190b4fe17SChao Peng static bool hugepage_test_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
749290b4fe17SChao Peng 				int level)
749390b4fe17SChao Peng {
749490b4fe17SChao Peng 	return lpage_info_slot(gfn, slot, level)->disallow_lpage & KVM_LPAGE_MIXED_FLAG;
749590b4fe17SChao Peng }
749690b4fe17SChao Peng 
749790b4fe17SChao Peng static void hugepage_clear_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
749890b4fe17SChao Peng 				 int level)
749990b4fe17SChao Peng {
750090b4fe17SChao Peng 	lpage_info_slot(gfn, slot, level)->disallow_lpage &= ~KVM_LPAGE_MIXED_FLAG;
750190b4fe17SChao Peng }
750290b4fe17SChao Peng 
750390b4fe17SChao Peng static void hugepage_set_mixed(struct kvm_memory_slot *slot, gfn_t gfn,
750490b4fe17SChao Peng 			       int level)
750590b4fe17SChao Peng {
750690b4fe17SChao Peng 	lpage_info_slot(gfn, slot, level)->disallow_lpage |= KVM_LPAGE_MIXED_FLAG;
750790b4fe17SChao Peng }
750890b4fe17SChao Peng 
750990b4fe17SChao Peng static bool hugepage_has_attrs(struct kvm *kvm, struct kvm_memory_slot *slot,
751090b4fe17SChao Peng 			       gfn_t gfn, int level, unsigned long attrs)
751190b4fe17SChao Peng {
751290b4fe17SChao Peng 	const unsigned long start = gfn;
751390b4fe17SChao Peng 	const unsigned long end = start + KVM_PAGES_PER_HPAGE(level);
751490b4fe17SChao Peng 
751590b4fe17SChao Peng 	if (level == PG_LEVEL_2M)
75164b5f6712SPaolo Bonzini 		return kvm_range_has_memory_attributes(kvm, start, end, ~0, attrs);
751790b4fe17SChao Peng 
751890b4fe17SChao Peng 	for (gfn = start; gfn < end; gfn += KVM_PAGES_PER_HPAGE(level - 1)) {
751990b4fe17SChao Peng 		if (hugepage_test_mixed(slot, gfn, level - 1) ||
752090b4fe17SChao Peng 		    attrs != kvm_get_memory_attributes(kvm, gfn))
752190b4fe17SChao Peng 			return false;
752290b4fe17SChao Peng 	}
752390b4fe17SChao Peng 	return true;
752490b4fe17SChao Peng }
752590b4fe17SChao Peng 
752690b4fe17SChao Peng bool kvm_arch_post_set_memory_attributes(struct kvm *kvm,
752790b4fe17SChao Peng 					 struct kvm_gfn_range *range)
752890b4fe17SChao Peng {
752990b4fe17SChao Peng 	unsigned long attrs = range->arg.attributes;
753090b4fe17SChao Peng 	struct kvm_memory_slot *slot = range->slot;
753190b4fe17SChao Peng 	int level;
753290b4fe17SChao Peng 
753390b4fe17SChao Peng 	lockdep_assert_held_write(&kvm->mmu_lock);
753490b4fe17SChao Peng 	lockdep_assert_held(&kvm->slots_lock);
753590b4fe17SChao Peng 
753690b4fe17SChao Peng 	/*
753790b4fe17SChao Peng 	 * Calculate which ranges can be mapped with hugepages even if the slot
753890b4fe17SChao Peng 	 * can't map memory PRIVATE.  KVM mustn't create a SHARED hugepage over
753990b4fe17SChao Peng 	 * a range that has PRIVATE GFNs, and conversely converting a range to
754090b4fe17SChao Peng 	 * SHARED may now allow hugepages.
754190b4fe17SChao Peng 	 */
754290b4fe17SChao Peng 	if (WARN_ON_ONCE(!kvm_arch_has_private_mem(kvm)))
754390b4fe17SChao Peng 		return false;
754490b4fe17SChao Peng 
754590b4fe17SChao Peng 	/*
754690b4fe17SChao Peng 	 * The sequence matters here: upper levels consume the result of lower
754790b4fe17SChao Peng 	 * level's scanning.
754890b4fe17SChao Peng 	 */
754990b4fe17SChao Peng 	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
755090b4fe17SChao Peng 		gfn_t nr_pages = KVM_PAGES_PER_HPAGE(level);
755190b4fe17SChao Peng 		gfn_t gfn = gfn_round_for_level(range->start, level);
755290b4fe17SChao Peng 
755390b4fe17SChao Peng 		/* Process the head page if it straddles the range. */
755490b4fe17SChao Peng 		if (gfn != range->start || gfn + nr_pages > range->end) {
755590b4fe17SChao Peng 			/*
755690b4fe17SChao Peng 			 * Skip mixed tracking if the aligned gfn isn't covered
755790b4fe17SChao Peng 			 * by the memslot, KVM can't use a hugepage due to the
755890b4fe17SChao Peng 			 * misaligned address regardless of memory attributes.
755990b4fe17SChao Peng 			 */
7560992b54bdSRick Edgecombe 			if (gfn >= slot->base_gfn &&
7561992b54bdSRick Edgecombe 			    gfn + nr_pages <= slot->base_gfn + slot->npages) {
756290b4fe17SChao Peng 				if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
756390b4fe17SChao Peng 					hugepage_clear_mixed(slot, gfn, level);
756490b4fe17SChao Peng 				else
756590b4fe17SChao Peng 					hugepage_set_mixed(slot, gfn, level);
756690b4fe17SChao Peng 			}
756790b4fe17SChao Peng 			gfn += nr_pages;
756890b4fe17SChao Peng 		}
756990b4fe17SChao Peng 
757090b4fe17SChao Peng 		/*
757190b4fe17SChao Peng 		 * Pages entirely covered by the range are guaranteed to have
757290b4fe17SChao Peng 		 * only the attributes which were just set.
757390b4fe17SChao Peng 		 */
757490b4fe17SChao Peng 		for ( ; gfn + nr_pages <= range->end; gfn += nr_pages)
757590b4fe17SChao Peng 			hugepage_clear_mixed(slot, gfn, level);
757690b4fe17SChao Peng 
757790b4fe17SChao Peng 		/*
757890b4fe17SChao Peng 		 * Process the last tail page if it straddles the range and is
757990b4fe17SChao Peng 		 * contained by the memslot.  Like the head page, KVM can't
758090b4fe17SChao Peng 		 * create a hugepage if the slot size is misaligned.
758190b4fe17SChao Peng 		 */
758290b4fe17SChao Peng 		if (gfn < range->end &&
758390b4fe17SChao Peng 		    (gfn + nr_pages) <= (slot->base_gfn + slot->npages)) {
758490b4fe17SChao Peng 			if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
758590b4fe17SChao Peng 				hugepage_clear_mixed(slot, gfn, level);
758690b4fe17SChao Peng 			else
758790b4fe17SChao Peng 				hugepage_set_mixed(slot, gfn, level);
758890b4fe17SChao Peng 		}
758990b4fe17SChao Peng 	}
759090b4fe17SChao Peng 	return false;
759190b4fe17SChao Peng }
759290b4fe17SChao Peng 
759390b4fe17SChao Peng void kvm_mmu_init_memslot_memory_attributes(struct kvm *kvm,
759490b4fe17SChao Peng 					    struct kvm_memory_slot *slot)
759590b4fe17SChao Peng {
759690b4fe17SChao Peng 	int level;
759790b4fe17SChao Peng 
759890b4fe17SChao Peng 	if (!kvm_arch_has_private_mem(kvm))
759990b4fe17SChao Peng 		return;
760090b4fe17SChao Peng 
760190b4fe17SChao Peng 	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
760290b4fe17SChao Peng 		/*
760390b4fe17SChao Peng 		 * Don't bother tracking mixed attributes for pages that can't
760490b4fe17SChao Peng 		 * be huge due to alignment, i.e. process only pages that are
760590b4fe17SChao Peng 		 * entirely contained by the memslot.
760690b4fe17SChao Peng 		 */
760790b4fe17SChao Peng 		gfn_t end = gfn_round_for_level(slot->base_gfn + slot->npages, level);
760890b4fe17SChao Peng 		gfn_t start = gfn_round_for_level(slot->base_gfn, level);
760990b4fe17SChao Peng 		gfn_t nr_pages = KVM_PAGES_PER_HPAGE(level);
761090b4fe17SChao Peng 		gfn_t gfn;
761190b4fe17SChao Peng 
761290b4fe17SChao Peng 		if (start < slot->base_gfn)
761390b4fe17SChao Peng 			start += nr_pages;
761490b4fe17SChao Peng 
761590b4fe17SChao Peng 		/*
761690b4fe17SChao Peng 		 * Unlike setting attributes, every potential hugepage needs to
761790b4fe17SChao Peng 		 * be manually checked as the attributes may already be mixed.
761890b4fe17SChao Peng 		 */
761990b4fe17SChao Peng 		for (gfn = start; gfn < end; gfn += nr_pages) {
762090b4fe17SChao Peng 			unsigned long attrs = kvm_get_memory_attributes(kvm, gfn);
762190b4fe17SChao Peng 
762290b4fe17SChao Peng 			if (hugepage_has_attrs(kvm, slot, gfn, level, attrs))
762390b4fe17SChao Peng 				hugepage_clear_mixed(slot, gfn, level);
762490b4fe17SChao Peng 			else
762590b4fe17SChao Peng 				hugepage_set_mixed(slot, gfn, level);
762690b4fe17SChao Peng 		}
762790b4fe17SChao Peng 	}
762890b4fe17SChao Peng }
762990b4fe17SChao Peng #endif
7630