xref: /linux/arch/x86/kvm/mmu/mmu.c (revision 3cdf93746f9a9a8a81b044219dcf51ce98bd0abf)
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"
28c50d8ae3SPaolo Bonzini #include "cpuid.h"
295a9624afSPaolo Bonzini #include "spte.h"
30c50d8ae3SPaolo Bonzini 
31c50d8ae3SPaolo Bonzini #include <linux/kvm_host.h>
32c50d8ae3SPaolo Bonzini #include <linux/types.h>
33c50d8ae3SPaolo Bonzini #include <linux/string.h>
34c50d8ae3SPaolo Bonzini #include <linux/mm.h>
35c50d8ae3SPaolo Bonzini #include <linux/highmem.h>
36c50d8ae3SPaolo Bonzini #include <linux/moduleparam.h>
37c50d8ae3SPaolo Bonzini #include <linux/export.h>
38c50d8ae3SPaolo Bonzini #include <linux/swap.h>
39c50d8ae3SPaolo Bonzini #include <linux/hugetlb.h>
40c50d8ae3SPaolo Bonzini #include <linux/compiler.h>
41c50d8ae3SPaolo Bonzini #include <linux/srcu.h>
42c50d8ae3SPaolo Bonzini #include <linux/slab.h>
43c50d8ae3SPaolo Bonzini #include <linux/sched/signal.h>
44c50d8ae3SPaolo Bonzini #include <linux/uaccess.h>
45c50d8ae3SPaolo Bonzini #include <linux/hash.h>
46c50d8ae3SPaolo Bonzini #include <linux/kern_levels.h>
47c50d8ae3SPaolo Bonzini #include <linux/kthread.h>
48c50d8ae3SPaolo Bonzini 
49c50d8ae3SPaolo Bonzini #include <asm/page.h>
50eb243d1dSIngo Molnar #include <asm/memtype.h>
51c50d8ae3SPaolo Bonzini #include <asm/cmpxchg.h>
52c50d8ae3SPaolo Bonzini #include <asm/io.h>
534a98623dSSean Christopherson #include <asm/set_memory.h>
54c50d8ae3SPaolo Bonzini #include <asm/vmx.h>
55c50d8ae3SPaolo Bonzini #include <asm/kvm_page_track.h>
56c50d8ae3SPaolo Bonzini #include "trace.h"
57c50d8ae3SPaolo Bonzini 
58c50d8ae3SPaolo Bonzini extern bool itlb_multihit_kvm_mitigation;
59c50d8ae3SPaolo Bonzini 
60a9d6496dSShaokun Zhang int __read_mostly nx_huge_pages = -1;
614dfe4f40SJunaid Shahid static uint __read_mostly nx_huge_pages_recovery_period_ms;
62c50d8ae3SPaolo Bonzini #ifdef CONFIG_PREEMPT_RT
63c50d8ae3SPaolo Bonzini /* Recovery can cause latency spikes, disable it for PREEMPT_RT.  */
64c50d8ae3SPaolo Bonzini static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
65c50d8ae3SPaolo Bonzini #else
66c50d8ae3SPaolo Bonzini static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
67c50d8ae3SPaolo Bonzini #endif
68c50d8ae3SPaolo Bonzini 
69c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
704dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp);
71c50d8ae3SPaolo Bonzini 
72d5d6c18dSJoe Perches static const struct kernel_param_ops nx_huge_pages_ops = {
73c50d8ae3SPaolo Bonzini 	.set = set_nx_huge_pages,
74c50d8ae3SPaolo Bonzini 	.get = param_get_bool,
75c50d8ae3SPaolo Bonzini };
76c50d8ae3SPaolo Bonzini 
774dfe4f40SJunaid Shahid static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
784dfe4f40SJunaid Shahid 	.set = set_nx_huge_pages_recovery_param,
79c50d8ae3SPaolo Bonzini 	.get = param_get_uint,
80c50d8ae3SPaolo Bonzini };
81c50d8ae3SPaolo Bonzini 
82c50d8ae3SPaolo Bonzini module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
83c50d8ae3SPaolo Bonzini __MODULE_PARM_TYPE(nx_huge_pages, "bool");
844dfe4f40SJunaid Shahid module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_param_ops,
85c50d8ae3SPaolo Bonzini 		&nx_huge_pages_recovery_ratio, 0644);
86c50d8ae3SPaolo Bonzini __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
874dfe4f40SJunaid Shahid module_param_cb(nx_huge_pages_recovery_period_ms, &nx_huge_pages_recovery_param_ops,
884dfe4f40SJunaid Shahid 		&nx_huge_pages_recovery_period_ms, 0644);
894dfe4f40SJunaid Shahid __MODULE_PARM_TYPE(nx_huge_pages_recovery_period_ms, "uint");
90c50d8ae3SPaolo Bonzini 
9171fe7013SSean Christopherson static bool __read_mostly force_flush_and_sync_on_reuse;
9271fe7013SSean Christopherson module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
9371fe7013SSean Christopherson 
94c50d8ae3SPaolo Bonzini /*
95c50d8ae3SPaolo Bonzini  * When setting this variable to true it enables Two-Dimensional-Paging
96c50d8ae3SPaolo Bonzini  * where the hardware walks 2 page tables:
97c50d8ae3SPaolo Bonzini  * 1. the guest-virtual to guest-physical
98c50d8ae3SPaolo Bonzini  * 2. while doing 1. it walks guest-physical to host-physical
99c50d8ae3SPaolo Bonzini  * If the hardware supports that we don't need to do shadow paging.
100c50d8ae3SPaolo Bonzini  */
101c50d8ae3SPaolo Bonzini bool tdp_enabled = false;
102c50d8ae3SPaolo Bonzini 
1031f98f2bdSDavid Matlack bool __ro_after_init tdp_mmu_allowed;
1041f98f2bdSDavid Matlack 
1051f98f2bdSDavid Matlack #ifdef CONFIG_X86_64
1061f98f2bdSDavid Matlack bool __read_mostly tdp_mmu_enabled = true;
1071f98f2bdSDavid Matlack module_param_named(tdp_mmu, tdp_mmu_enabled, bool, 0444);
1081f98f2bdSDavid Matlack #endif
1091f98f2bdSDavid Matlack 
1101d92d2e8SSean Christopherson static int max_huge_page_level __read_mostly;
111746700d2SWei Huang static int tdp_root_level __read_mostly;
11283013059SSean Christopherson static int max_tdp_level __read_mostly;
113703c335dSSean Christopherson 
114c50d8ae3SPaolo Bonzini #ifdef MMU_DEBUG
1155a9624afSPaolo Bonzini bool dbg = 0;
116c50d8ae3SPaolo Bonzini module_param(dbg, bool, 0644);
117c50d8ae3SPaolo Bonzini #endif
118c50d8ae3SPaolo Bonzini 
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 /*
12713236e25SPeter Xu  * Slight optimization of cacheline layout, by putting `more' and `spte_count'
12813236e25SPeter Xu  * at the start; then accessing it will only use one single cacheline for
12913236e25SPeter Xu  * either full (entries==PTE_LIST_EXT) case or entries<=6.
13013236e25SPeter Xu  */
131c50d8ae3SPaolo Bonzini struct pte_list_desc {
132c50d8ae3SPaolo Bonzini 	struct pte_list_desc *more;
13313236e25SPeter Xu 	/*
13413236e25SPeter Xu 	 * Stores number of entries stored in the pte_list_desc.  No need to be
13513236e25SPeter Xu 	 * u64 but just for easier alignment.  When PTE_LIST_EXT, means full.
13613236e25SPeter Xu 	 */
13713236e25SPeter Xu 	u64 spte_count;
13813236e25SPeter Xu 	u64 *sptes[PTE_LIST_EXT];
139c50d8ae3SPaolo Bonzini };
140c50d8ae3SPaolo Bonzini 
141c50d8ae3SPaolo Bonzini struct kvm_shadow_walk_iterator {
142c50d8ae3SPaolo Bonzini 	u64 addr;
143c50d8ae3SPaolo Bonzini 	hpa_t shadow_addr;
144c50d8ae3SPaolo Bonzini 	u64 *sptep;
145c50d8ae3SPaolo Bonzini 	int level;
146c50d8ae3SPaolo Bonzini 	unsigned index;
147c50d8ae3SPaolo Bonzini };
148c50d8ae3SPaolo Bonzini 
149c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
150c50d8ae3SPaolo Bonzini 	for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
151c50d8ae3SPaolo Bonzini 					 (_root), (_addr));                \
152c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			           \
153c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
154c50d8ae3SPaolo Bonzini 
155c50d8ae3SPaolo Bonzini #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
156c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);	\
157c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			\
158c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
159c50d8ae3SPaolo Bonzini 
160c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)	\
161c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);		\
162c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker)) &&				\
163c50d8ae3SPaolo Bonzini 		({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });	\
164c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&(_walker), spte))
165c50d8ae3SPaolo Bonzini 
166c50d8ae3SPaolo Bonzini static struct kmem_cache *pte_list_desc_cache;
16702c00b3aSBen Gardon struct kmem_cache *mmu_page_header_cache;
168c50d8ae3SPaolo Bonzini static struct percpu_counter kvm_total_used_mmu_pages;
169c50d8ae3SPaolo Bonzini 
170c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 spte);
171c50d8ae3SPaolo Bonzini 
172594e91a1SSean Christopherson struct kvm_mmu_role_regs {
173594e91a1SSean Christopherson 	const unsigned long cr0;
174594e91a1SSean Christopherson 	const unsigned long cr4;
175594e91a1SSean Christopherson 	const u64 efer;
176594e91a1SSean Christopherson };
177594e91a1SSean Christopherson 
178c50d8ae3SPaolo Bonzini #define CREATE_TRACE_POINTS
179c50d8ae3SPaolo Bonzini #include "mmutrace.h"
180c50d8ae3SPaolo Bonzini 
181594e91a1SSean Christopherson /*
182594e91a1SSean Christopherson  * Yes, lot's of underscores.  They're a hint that you probably shouldn't be
1837a458f0eSPaolo Bonzini  * reading from the role_regs.  Once the root_role is constructed, it becomes
184594e91a1SSean Christopherson  * the single source of truth for the MMU's state.
185594e91a1SSean Christopherson  */
186594e91a1SSean Christopherson #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag)			\
18782ffa13fSPaolo Bonzini static inline bool __maybe_unused					\
18882ffa13fSPaolo Bonzini ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs)		\
189594e91a1SSean Christopherson {									\
190594e91a1SSean Christopherson 	return !!(regs->reg & flag);					\
191594e91a1SSean Christopherson }
192594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
193594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
194594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
195594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
196594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
197594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
198594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
199594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
200594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
201594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
202594e91a1SSean Christopherson 
20360667724SSean Christopherson /*
20460667724SSean Christopherson  * The MMU itself (with a valid role) is the single source of truth for the
20560667724SSean Christopherson  * MMU.  Do not use the regs used to build the MMU/role, nor the vCPU.  The
20660667724SSean Christopherson  * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
20760667724SSean Christopherson  * and the vCPU may be incorrect/irrelevant.
20860667724SSean Christopherson  */
20960667724SSean Christopherson #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name)		\
2104ac21457SPaolo Bonzini static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu)	\
21160667724SSean Christopherson {								\
212e5ed0fb0SPaolo Bonzini 	return !!(mmu->cpu_role. base_or_ext . reg##_##name);	\
21360667724SSean Christopherson }
21460667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
21560667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pse);
21660667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smep);
21760667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smap);
21860667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pke);
21960667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, la57);
22060667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
22156b321f9SPaolo Bonzini BUILD_MMU_ROLE_ACCESSOR(ext,  efer, lma);
22260667724SSean Christopherson 
223faf72962SPaolo Bonzini static inline bool is_cr0_pg(struct kvm_mmu *mmu)
224faf72962SPaolo Bonzini {
225faf72962SPaolo Bonzini         return mmu->cpu_role.base.level > 0;
226faf72962SPaolo Bonzini }
227faf72962SPaolo Bonzini 
228faf72962SPaolo Bonzini static inline bool is_cr4_pae(struct kvm_mmu *mmu)
229faf72962SPaolo Bonzini {
230faf72962SPaolo Bonzini         return !mmu->cpu_role.base.has_4_byte_gpte;
231faf72962SPaolo Bonzini }
232faf72962SPaolo Bonzini 
233594e91a1SSean Christopherson static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
234594e91a1SSean Christopherson {
235594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
236594e91a1SSean Christopherson 		.cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
237594e91a1SSean Christopherson 		.cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
238594e91a1SSean Christopherson 		.efer = vcpu->arch.efer,
239594e91a1SSean Christopherson 	};
240594e91a1SSean Christopherson 
241594e91a1SSean Christopherson 	return regs;
242594e91a1SSean Christopherson }
243c50d8ae3SPaolo Bonzini 
244c50d8ae3SPaolo Bonzini static inline bool kvm_available_flush_tlb_with_range(void)
245c50d8ae3SPaolo Bonzini {
246afaf0b2fSSean Christopherson 	return kvm_x86_ops.tlb_remote_flush_with_range;
247c50d8ae3SPaolo Bonzini }
248c50d8ae3SPaolo Bonzini 
249c50d8ae3SPaolo Bonzini static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
250c50d8ae3SPaolo Bonzini 		struct kvm_tlb_range *range)
251c50d8ae3SPaolo Bonzini {
252c50d8ae3SPaolo Bonzini 	int ret = -ENOTSUPP;
253c50d8ae3SPaolo Bonzini 
254afaf0b2fSSean Christopherson 	if (range && kvm_x86_ops.tlb_remote_flush_with_range)
255b3646477SJason Baron 		ret = static_call(kvm_x86_tlb_remote_flush_with_range)(kvm, range);
256c50d8ae3SPaolo Bonzini 
257c50d8ae3SPaolo Bonzini 	if (ret)
258c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
259c50d8ae3SPaolo Bonzini }
260c50d8ae3SPaolo Bonzini 
2612f2fad08SBen Gardon void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
262c50d8ae3SPaolo Bonzini 		u64 start_gfn, u64 pages)
263c50d8ae3SPaolo Bonzini {
264c50d8ae3SPaolo Bonzini 	struct kvm_tlb_range range;
265c50d8ae3SPaolo Bonzini 
266c50d8ae3SPaolo Bonzini 	range.start_gfn = start_gfn;
267c50d8ae3SPaolo Bonzini 	range.pages = pages;
268c50d8ae3SPaolo Bonzini 
269c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs_with_range(kvm, &range);
270c50d8ae3SPaolo Bonzini }
271c50d8ae3SPaolo Bonzini 
2721b2dc736SHou Wenlong static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index);
2731b2dc736SHou Wenlong 
2741b2dc736SHou Wenlong /* Flush the range of guest memory mapped by the given SPTE. */
2751b2dc736SHou Wenlong static void kvm_flush_remote_tlbs_sptep(struct kvm *kvm, u64 *sptep)
2761b2dc736SHou Wenlong {
2771b2dc736SHou Wenlong 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2781b2dc736SHou Wenlong 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, spte_index(sptep));
2791b2dc736SHou Wenlong 
2801b2dc736SHou Wenlong 	kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
2811b2dc736SHou Wenlong }
2821b2dc736SHou Wenlong 
2838f79b064SBen Gardon static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
2848f79b064SBen Gardon 			   unsigned int access)
2858f79b064SBen Gardon {
286c236d962SSean Christopherson 	u64 spte = make_mmio_spte(vcpu, gfn, access);
2878f79b064SBen Gardon 
288c236d962SSean Christopherson 	trace_mark_mmio_spte(sptep, gfn, spte);
289c236d962SSean Christopherson 	mmu_spte_set(sptep, spte);
290c50d8ae3SPaolo Bonzini }
291c50d8ae3SPaolo Bonzini 
292c50d8ae3SPaolo Bonzini static gfn_t get_mmio_spte_gfn(u64 spte)
293c50d8ae3SPaolo Bonzini {
294c50d8ae3SPaolo Bonzini 	u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
295c50d8ae3SPaolo Bonzini 
2968a967d65SPaolo Bonzini 	gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
297c50d8ae3SPaolo Bonzini 	       & shadow_nonpresent_or_rsvd_mask;
298c50d8ae3SPaolo Bonzini 
299c50d8ae3SPaolo Bonzini 	return gpa >> PAGE_SHIFT;
300c50d8ae3SPaolo Bonzini }
301c50d8ae3SPaolo Bonzini 
302c50d8ae3SPaolo Bonzini static unsigned get_mmio_spte_access(u64 spte)
303c50d8ae3SPaolo Bonzini {
304c50d8ae3SPaolo Bonzini 	return spte & shadow_mmio_access_mask;
305c50d8ae3SPaolo Bonzini }
306c50d8ae3SPaolo Bonzini 
307c50d8ae3SPaolo Bonzini static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
308c50d8ae3SPaolo Bonzini {
309c50d8ae3SPaolo Bonzini 	u64 kvm_gen, spte_gen, gen;
310c50d8ae3SPaolo Bonzini 
311c50d8ae3SPaolo Bonzini 	gen = kvm_vcpu_memslots(vcpu)->generation;
312c50d8ae3SPaolo Bonzini 	if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
313c50d8ae3SPaolo Bonzini 		return false;
314c50d8ae3SPaolo Bonzini 
315c50d8ae3SPaolo Bonzini 	kvm_gen = gen & MMIO_SPTE_GEN_MASK;
316c50d8ae3SPaolo Bonzini 	spte_gen = get_mmio_spte_generation(spte);
317c50d8ae3SPaolo Bonzini 
318c50d8ae3SPaolo Bonzini 	trace_check_mmio_spte(spte, kvm_gen, spte_gen);
319c50d8ae3SPaolo Bonzini 	return likely(kvm_gen == spte_gen);
320c50d8ae3SPaolo Bonzini }
321c50d8ae3SPaolo Bonzini 
322c50d8ae3SPaolo Bonzini static int is_cpuid_PSE36(void)
323c50d8ae3SPaolo Bonzini {
324c50d8ae3SPaolo Bonzini 	return 1;
325c50d8ae3SPaolo Bonzini }
326c50d8ae3SPaolo Bonzini 
327c50d8ae3SPaolo Bonzini #ifdef CONFIG_X86_64
328c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
329c50d8ae3SPaolo Bonzini {
330c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
331c50d8ae3SPaolo Bonzini }
332c50d8ae3SPaolo Bonzini 
333c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
334c50d8ae3SPaolo Bonzini {
335c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
336c50d8ae3SPaolo Bonzini }
337c50d8ae3SPaolo Bonzini 
338c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
339c50d8ae3SPaolo Bonzini {
340c50d8ae3SPaolo Bonzini 	return xchg(sptep, spte);
341c50d8ae3SPaolo Bonzini }
342c50d8ae3SPaolo Bonzini 
343c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
344c50d8ae3SPaolo Bonzini {
345c50d8ae3SPaolo Bonzini 	return READ_ONCE(*sptep);
346c50d8ae3SPaolo Bonzini }
347c50d8ae3SPaolo Bonzini #else
348c50d8ae3SPaolo Bonzini union split_spte {
349c50d8ae3SPaolo Bonzini 	struct {
350c50d8ae3SPaolo Bonzini 		u32 spte_low;
351c50d8ae3SPaolo Bonzini 		u32 spte_high;
352c50d8ae3SPaolo Bonzini 	};
353c50d8ae3SPaolo Bonzini 	u64 spte;
354c50d8ae3SPaolo Bonzini };
355c50d8ae3SPaolo Bonzini 
356c50d8ae3SPaolo Bonzini static void count_spte_clear(u64 *sptep, u64 spte)
357c50d8ae3SPaolo Bonzini {
35857354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
359c50d8ae3SPaolo Bonzini 
360c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(spte))
361c50d8ae3SPaolo Bonzini 		return;
362c50d8ae3SPaolo Bonzini 
363c50d8ae3SPaolo Bonzini 	/* Ensure the spte is completely set before we increase the count */
364c50d8ae3SPaolo Bonzini 	smp_wmb();
365c50d8ae3SPaolo Bonzini 	sp->clear_spte_count++;
366c50d8ae3SPaolo Bonzini }
367c50d8ae3SPaolo Bonzini 
368c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
369c50d8ae3SPaolo Bonzini {
370c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
371c50d8ae3SPaolo Bonzini 
372c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
373c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
374c50d8ae3SPaolo Bonzini 
375c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
376c50d8ae3SPaolo Bonzini 
377c50d8ae3SPaolo Bonzini 	/*
378c50d8ae3SPaolo Bonzini 	 * If we map the spte from nonpresent to present, We should store
379c50d8ae3SPaolo Bonzini 	 * the high bits firstly, then set present bit, so cpu can not
380c50d8ae3SPaolo Bonzini 	 * fetch this spte while we are setting the spte.
381c50d8ae3SPaolo Bonzini 	 */
382c50d8ae3SPaolo Bonzini 	smp_wmb();
383c50d8ae3SPaolo Bonzini 
384c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
385c50d8ae3SPaolo Bonzini }
386c50d8ae3SPaolo Bonzini 
387c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
388c50d8ae3SPaolo Bonzini {
389c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
390c50d8ae3SPaolo Bonzini 
391c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
392c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
393c50d8ae3SPaolo Bonzini 
394c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
395c50d8ae3SPaolo Bonzini 
396c50d8ae3SPaolo Bonzini 	/*
397c50d8ae3SPaolo Bonzini 	 * If we map the spte from present to nonpresent, we should clear
398c50d8ae3SPaolo Bonzini 	 * present bit firstly to avoid vcpu fetch the old high bits.
399c50d8ae3SPaolo Bonzini 	 */
400c50d8ae3SPaolo Bonzini 	smp_wmb();
401c50d8ae3SPaolo Bonzini 
402c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
403c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
404c50d8ae3SPaolo Bonzini }
405c50d8ae3SPaolo Bonzini 
406c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
407c50d8ae3SPaolo Bonzini {
408c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte, orig;
409c50d8ae3SPaolo Bonzini 
410c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
411c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
412c50d8ae3SPaolo Bonzini 
413c50d8ae3SPaolo Bonzini 	/* xchg acts as a barrier before the setting of the high bits */
414c50d8ae3SPaolo Bonzini 	orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
415c50d8ae3SPaolo Bonzini 	orig.spte_high = ssptep->spte_high;
416c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
417c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
418c50d8ae3SPaolo Bonzini 
419c50d8ae3SPaolo Bonzini 	return orig.spte;
420c50d8ae3SPaolo Bonzini }
421c50d8ae3SPaolo Bonzini 
422c50d8ae3SPaolo Bonzini /*
423c50d8ae3SPaolo Bonzini  * The idea using the light way get the spte on x86_32 guest is from
424c50d8ae3SPaolo Bonzini  * gup_get_pte (mm/gup.c).
425c50d8ae3SPaolo Bonzini  *
426aed02fe3SSean Christopherson  * An spte tlb flush may be pending, because kvm_set_pte_rmap
427c50d8ae3SPaolo Bonzini  * coalesces them and we are running out of the MMU lock.  Therefore
428c50d8ae3SPaolo Bonzini  * we need to protect against in-progress updates of the spte.
429c50d8ae3SPaolo Bonzini  *
430c50d8ae3SPaolo Bonzini  * Reading the spte while an update is in progress may get the old value
431c50d8ae3SPaolo Bonzini  * for the high part of the spte.  The race is fine for a present->non-present
432c50d8ae3SPaolo Bonzini  * change (because the high part of the spte is ignored for non-present spte),
433c50d8ae3SPaolo Bonzini  * but for a present->present change we must reread the spte.
434c50d8ae3SPaolo Bonzini  *
435c50d8ae3SPaolo Bonzini  * All such changes are done in two steps (present->non-present and
436c50d8ae3SPaolo Bonzini  * non-present->present), hence it is enough to count the number of
437c50d8ae3SPaolo Bonzini  * present->non-present updates: if it changed while reading the spte,
438c50d8ae3SPaolo Bonzini  * we might have hit the race.  This is done using clear_spte_count.
439c50d8ae3SPaolo Bonzini  */
440c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
441c50d8ae3SPaolo Bonzini {
44257354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
443c50d8ae3SPaolo Bonzini 	union split_spte spte, *orig = (union split_spte *)sptep;
444c50d8ae3SPaolo Bonzini 	int count;
445c50d8ae3SPaolo Bonzini 
446c50d8ae3SPaolo Bonzini retry:
447c50d8ae3SPaolo Bonzini 	count = sp->clear_spte_count;
448c50d8ae3SPaolo Bonzini 	smp_rmb();
449c50d8ae3SPaolo Bonzini 
450c50d8ae3SPaolo Bonzini 	spte.spte_low = orig->spte_low;
451c50d8ae3SPaolo Bonzini 	smp_rmb();
452c50d8ae3SPaolo Bonzini 
453c50d8ae3SPaolo Bonzini 	spte.spte_high = orig->spte_high;
454c50d8ae3SPaolo Bonzini 	smp_rmb();
455c50d8ae3SPaolo Bonzini 
456c50d8ae3SPaolo Bonzini 	if (unlikely(spte.spte_low != orig->spte_low ||
457c50d8ae3SPaolo Bonzini 	      count != sp->clear_spte_count))
458c50d8ae3SPaolo Bonzini 		goto retry;
459c50d8ae3SPaolo Bonzini 
460c50d8ae3SPaolo Bonzini 	return spte.spte;
461c50d8ae3SPaolo Bonzini }
462c50d8ae3SPaolo Bonzini #endif
463c50d8ae3SPaolo Bonzini 
464c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_set:
465c50d8ae3SPaolo Bonzini  * Set the sptep from nonpresent to present.
466c50d8ae3SPaolo Bonzini  * Note: the sptep being assigned *must* be either not present
467c50d8ae3SPaolo Bonzini  * or in a state where the hardware will not attempt to update
468c50d8ae3SPaolo Bonzini  * the spte.
469c50d8ae3SPaolo Bonzini  */
470c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 new_spte)
471c50d8ae3SPaolo Bonzini {
472c50d8ae3SPaolo Bonzini 	WARN_ON(is_shadow_present_pte(*sptep));
473c50d8ae3SPaolo Bonzini 	__set_spte(sptep, new_spte);
474c50d8ae3SPaolo Bonzini }
475c50d8ae3SPaolo Bonzini 
476c50d8ae3SPaolo Bonzini /*
477c50d8ae3SPaolo Bonzini  * Update the SPTE (excluding the PFN), but do not track changes in its
478c50d8ae3SPaolo Bonzini  * accessed/dirty status.
479c50d8ae3SPaolo Bonzini  */
480c50d8ae3SPaolo Bonzini static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
481c50d8ae3SPaolo Bonzini {
482c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
483c50d8ae3SPaolo Bonzini 
484c50d8ae3SPaolo Bonzini 	WARN_ON(!is_shadow_present_pte(new_spte));
485115111efSDavid Matlack 	check_spte_writable_invariants(new_spte);
486c50d8ae3SPaolo Bonzini 
487c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte)) {
488c50d8ae3SPaolo Bonzini 		mmu_spte_set(sptep, new_spte);
489c50d8ae3SPaolo Bonzini 		return old_spte;
490c50d8ae3SPaolo Bonzini 	}
491c50d8ae3SPaolo Bonzini 
492c50d8ae3SPaolo Bonzini 	if (!spte_has_volatile_bits(old_spte))
493c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, new_spte);
494c50d8ae3SPaolo Bonzini 	else
495c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, new_spte);
496c50d8ae3SPaolo Bonzini 
497c50d8ae3SPaolo Bonzini 	WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
498c50d8ae3SPaolo Bonzini 
499c50d8ae3SPaolo Bonzini 	return old_spte;
500c50d8ae3SPaolo Bonzini }
501c50d8ae3SPaolo Bonzini 
502c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_update:
503c50d8ae3SPaolo Bonzini  * Update the state bits, it means the mapped pfn is not changed.
504c50d8ae3SPaolo Bonzini  *
50502844ac1SDavid Matlack  * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
50602844ac1SDavid Matlack  * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
50702844ac1SDavid Matlack  * spte, even though the writable spte might be cached on a CPU's TLB.
508c50d8ae3SPaolo Bonzini  *
509c50d8ae3SPaolo Bonzini  * Returns true if the TLB needs to be flushed
510c50d8ae3SPaolo Bonzini  */
511c50d8ae3SPaolo Bonzini static bool mmu_spte_update(u64 *sptep, u64 new_spte)
512c50d8ae3SPaolo Bonzini {
513c50d8ae3SPaolo Bonzini 	bool flush = false;
514c50d8ae3SPaolo Bonzini 	u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
515c50d8ae3SPaolo Bonzini 
516c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
517c50d8ae3SPaolo Bonzini 		return false;
518c50d8ae3SPaolo Bonzini 
519c50d8ae3SPaolo Bonzini 	/*
520c50d8ae3SPaolo Bonzini 	 * For the spte updated out of mmu-lock is safe, since
521c50d8ae3SPaolo Bonzini 	 * we always atomically update it, see the comments in
522c50d8ae3SPaolo Bonzini 	 * spte_has_volatile_bits().
523c50d8ae3SPaolo Bonzini 	 */
524706c9c55SSean Christopherson 	if (is_mmu_writable_spte(old_spte) &&
525c50d8ae3SPaolo Bonzini 	      !is_writable_pte(new_spte))
526c50d8ae3SPaolo Bonzini 		flush = true;
527c50d8ae3SPaolo Bonzini 
528c50d8ae3SPaolo Bonzini 	/*
529c50d8ae3SPaolo Bonzini 	 * Flush TLB when accessed/dirty states are changed in the page tables,
530c50d8ae3SPaolo Bonzini 	 * to guarantee consistency between TLB and page tables.
531c50d8ae3SPaolo Bonzini 	 */
532c50d8ae3SPaolo Bonzini 
533c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
534c50d8ae3SPaolo Bonzini 		flush = true;
535c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(spte_to_pfn(old_spte));
536c50d8ae3SPaolo Bonzini 	}
537c50d8ae3SPaolo Bonzini 
538c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
539c50d8ae3SPaolo Bonzini 		flush = true;
540c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(old_spte));
541c50d8ae3SPaolo Bonzini 	}
542c50d8ae3SPaolo Bonzini 
543c50d8ae3SPaolo Bonzini 	return flush;
544c50d8ae3SPaolo Bonzini }
545c50d8ae3SPaolo Bonzini 
546c50d8ae3SPaolo Bonzini /*
547c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_track_bits:
548c50d8ae3SPaolo Bonzini  * It sets the sptep from present to nonpresent, and track the
549c50d8ae3SPaolo Bonzini  * state bits, it is used to clear the last level sptep.
5507fa2a347SSean Christopherson  * Returns the old PTE.
551c50d8ae3SPaolo Bonzini  */
55235d539c3SSean Christopherson static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
553c50d8ae3SPaolo Bonzini {
554c50d8ae3SPaolo Bonzini 	kvm_pfn_t pfn;
555c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
55671f51d2cSMingwei Zhang 	int level = sptep_to_sp(sptep)->role.level;
557b14b2690SSean Christopherson 	struct page *page;
558c50d8ae3SPaolo Bonzini 
55954eb3ef5SSean Christopherson 	if (!is_shadow_present_pte(old_spte) ||
56054eb3ef5SSean Christopherson 	    !spte_has_volatile_bits(old_spte))
561c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, 0ull);
562c50d8ae3SPaolo Bonzini 	else
563c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, 0ull);
564c50d8ae3SPaolo Bonzini 
565c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
5667fa2a347SSean Christopherson 		return old_spte;
567c50d8ae3SPaolo Bonzini 
56871f51d2cSMingwei Zhang 	kvm_update_page_stats(kvm, level, -1);
56971f51d2cSMingwei Zhang 
570c50d8ae3SPaolo Bonzini 	pfn = spte_to_pfn(old_spte);
571c50d8ae3SPaolo Bonzini 
572c50d8ae3SPaolo Bonzini 	/*
573b14b2690SSean Christopherson 	 * KVM doesn't hold a reference to any pages mapped into the guest, and
574b14b2690SSean Christopherson 	 * instead uses the mmu_notifier to ensure that KVM unmaps any pages
575b14b2690SSean Christopherson 	 * before they are reclaimed.  Sanity check that, if the pfn is backed
576b14b2690SSean Christopherson 	 * by a refcounted page, the refcount is elevated.
577c50d8ae3SPaolo Bonzini 	 */
578b14b2690SSean Christopherson 	page = kvm_pfn_to_refcounted_page(pfn);
579b14b2690SSean Christopherson 	WARN_ON(page && !page_count(page));
580c50d8ae3SPaolo Bonzini 
581c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte))
582c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(pfn);
583c50d8ae3SPaolo Bonzini 
584c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte))
585c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(pfn);
586c50d8ae3SPaolo Bonzini 
5877fa2a347SSean Christopherson 	return old_spte;
588c50d8ae3SPaolo Bonzini }
589c50d8ae3SPaolo Bonzini 
590c50d8ae3SPaolo Bonzini /*
591c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_no_track:
592c50d8ae3SPaolo Bonzini  * Directly clear spte without caring the state bits of sptep,
593c50d8ae3SPaolo Bonzini  * it is used to set the upper level spte.
594c50d8ae3SPaolo Bonzini  */
595c50d8ae3SPaolo Bonzini static void mmu_spte_clear_no_track(u64 *sptep)
596c50d8ae3SPaolo Bonzini {
597c50d8ae3SPaolo Bonzini 	__update_clear_spte_fast(sptep, 0ull);
598c50d8ae3SPaolo Bonzini }
599c50d8ae3SPaolo Bonzini 
600c50d8ae3SPaolo Bonzini static u64 mmu_spte_get_lockless(u64 *sptep)
601c50d8ae3SPaolo Bonzini {
602c50d8ae3SPaolo Bonzini 	return __get_spte_lockless(sptep);
603c50d8ae3SPaolo Bonzini }
604c50d8ae3SPaolo Bonzini 
605c50d8ae3SPaolo Bonzini /* Returns the Accessed status of the PTE and resets it at the same time. */
606c50d8ae3SPaolo Bonzini static bool mmu_spte_age(u64 *sptep)
607c50d8ae3SPaolo Bonzini {
608c50d8ae3SPaolo Bonzini 	u64 spte = mmu_spte_get_lockless(sptep);
609c50d8ae3SPaolo Bonzini 
610c50d8ae3SPaolo Bonzini 	if (!is_accessed_spte(spte))
611c50d8ae3SPaolo Bonzini 		return false;
612c50d8ae3SPaolo Bonzini 
613c50d8ae3SPaolo Bonzini 	if (spte_ad_enabled(spte)) {
614c50d8ae3SPaolo Bonzini 		clear_bit((ffs(shadow_accessed_mask) - 1),
615c50d8ae3SPaolo Bonzini 			  (unsigned long *)sptep);
616c50d8ae3SPaolo Bonzini 	} else {
617c50d8ae3SPaolo Bonzini 		/*
618c50d8ae3SPaolo Bonzini 		 * Capture the dirty status of the page, so that it doesn't get
619c50d8ae3SPaolo Bonzini 		 * lost when the SPTE is marked for access tracking.
620c50d8ae3SPaolo Bonzini 		 */
621c50d8ae3SPaolo Bonzini 		if (is_writable_pte(spte))
622c50d8ae3SPaolo Bonzini 			kvm_set_pfn_dirty(spte_to_pfn(spte));
623c50d8ae3SPaolo Bonzini 
624c50d8ae3SPaolo Bonzini 		spte = mark_spte_for_access_track(spte);
625c50d8ae3SPaolo Bonzini 		mmu_spte_update_no_track(sptep, spte);
626c50d8ae3SPaolo Bonzini 	}
627c50d8ae3SPaolo Bonzini 
628c50d8ae3SPaolo Bonzini 	return true;
629c50d8ae3SPaolo Bonzini }
630c50d8ae3SPaolo Bonzini 
63178fdd2f0SSean Christopherson static inline bool is_tdp_mmu_active(struct kvm_vcpu *vcpu)
63278fdd2f0SSean Christopherson {
63378fdd2f0SSean Christopherson 	return tdp_mmu_enabled && vcpu->arch.mmu->root_role.direct;
63478fdd2f0SSean Christopherson }
63578fdd2f0SSean Christopherson 
636c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
637c50d8ae3SPaolo Bonzini {
63878fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu)) {
639c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_begin();
640c5c8c7c5SDavid Matlack 	} else {
641c50d8ae3SPaolo Bonzini 		/*
642c50d8ae3SPaolo Bonzini 		 * Prevent page table teardown by making any free-er wait during
643c50d8ae3SPaolo Bonzini 		 * kvm_flush_remote_tlbs() IPI to all active vcpus.
644c50d8ae3SPaolo Bonzini 		 */
645c50d8ae3SPaolo Bonzini 		local_irq_disable();
646c50d8ae3SPaolo Bonzini 
647c50d8ae3SPaolo Bonzini 		/*
648c50d8ae3SPaolo Bonzini 		 * Make sure a following spte read is not reordered ahead of the write
649c50d8ae3SPaolo Bonzini 		 * to vcpu->mode.
650c50d8ae3SPaolo Bonzini 		 */
651c50d8ae3SPaolo Bonzini 		smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
652c50d8ae3SPaolo Bonzini 	}
653c5c8c7c5SDavid Matlack }
654c50d8ae3SPaolo Bonzini 
655c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
656c50d8ae3SPaolo Bonzini {
65778fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu)) {
658c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_end();
659c5c8c7c5SDavid Matlack 	} else {
660c50d8ae3SPaolo Bonzini 		/*
661c50d8ae3SPaolo Bonzini 		 * Make sure the write to vcpu->mode is not reordered in front of
662c50d8ae3SPaolo Bonzini 		 * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
663c50d8ae3SPaolo Bonzini 		 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
664c50d8ae3SPaolo Bonzini 		 */
665c50d8ae3SPaolo Bonzini 		smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
666c50d8ae3SPaolo Bonzini 		local_irq_enable();
667c50d8ae3SPaolo Bonzini 	}
668c5c8c7c5SDavid Matlack }
669c50d8ae3SPaolo Bonzini 
670378f5cd6SSean Christopherson static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
671c50d8ae3SPaolo Bonzini {
672c50d8ae3SPaolo Bonzini 	int r;
673c50d8ae3SPaolo Bonzini 
674531281adSSean Christopherson 	/* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
67594ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
676531281adSSean Christopherson 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
677c50d8ae3SPaolo Bonzini 	if (r)
678c50d8ae3SPaolo Bonzini 		return r;
67994ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
680171a90d7SSean Christopherson 				       PT64_ROOT_MAX_LEVEL);
681171a90d7SSean Christopherson 	if (r)
682171a90d7SSean Christopherson 		return r;
683378f5cd6SSean Christopherson 	if (maybe_indirect) {
6846a97575dSDavid Matlack 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
685171a90d7SSean Christopherson 					       PT64_ROOT_MAX_LEVEL);
686c50d8ae3SPaolo Bonzini 		if (r)
687c50d8ae3SPaolo Bonzini 			return r;
688378f5cd6SSean Christopherson 	}
68994ce87efSSean Christopherson 	return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
690531281adSSean Christopherson 					  PT64_ROOT_MAX_LEVEL);
691c50d8ae3SPaolo Bonzini }
692c50d8ae3SPaolo Bonzini 
693c50d8ae3SPaolo Bonzini static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
694c50d8ae3SPaolo Bonzini {
69594ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
69694ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
6976a97575dSDavid Matlack 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
69894ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
699c50d8ae3SPaolo Bonzini }
700c50d8ae3SPaolo Bonzini 
701c50d8ae3SPaolo Bonzini static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
702c50d8ae3SPaolo Bonzini {
703c50d8ae3SPaolo Bonzini 	kmem_cache_free(pte_list_desc_cache, pte_list_desc);
704c50d8ae3SPaolo Bonzini }
705c50d8ae3SPaolo Bonzini 
7066a97575dSDavid Matlack static bool sp_has_gptes(struct kvm_mmu_page *sp);
7076a97575dSDavid Matlack 
708c50d8ae3SPaolo Bonzini static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
709c50d8ae3SPaolo Bonzini {
71084e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
71184e5ffd0SLai Jiangshan 		return sp->gfn;
71284e5ffd0SLai Jiangshan 
713c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
7146a97575dSDavid Matlack 		return sp->shadowed_translation[index] >> PAGE_SHIFT;
715c50d8ae3SPaolo Bonzini 
7162ca3129eSSean Christopherson 	return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
717c50d8ae3SPaolo Bonzini }
718c50d8ae3SPaolo Bonzini 
7196a97575dSDavid Matlack /*
7206a97575dSDavid Matlack  * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
7216a97575dSDavid Matlack  * that the SPTE itself may have a more constrained access permissions that
7226a97575dSDavid Matlack  * what the guest enforces. For example, a guest may create an executable
7236a97575dSDavid Matlack  * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
7246a97575dSDavid Matlack  */
7256a97575dSDavid Matlack static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
726c50d8ae3SPaolo Bonzini {
7276a97575dSDavid Matlack 	if (sp_has_gptes(sp))
7286a97575dSDavid Matlack 		return sp->shadowed_translation[index] & ACC_ALL;
7296a97575dSDavid Matlack 
7306a97575dSDavid Matlack 	/*
7316a97575dSDavid Matlack 	 * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
7326a97575dSDavid Matlack 	 * KVM is not shadowing any guest page tables, so the "guest access
7336a97575dSDavid Matlack 	 * permissions" are just ACC_ALL.
7346a97575dSDavid Matlack 	 *
7356a97575dSDavid Matlack 	 * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
7366a97575dSDavid Matlack 	 * is shadowing a guest huge page with small pages, the guest access
7376a97575dSDavid Matlack 	 * permissions being shadowed are the access permissions of the huge
7386a97575dSDavid Matlack 	 * page.
7396a97575dSDavid Matlack 	 *
7406a97575dSDavid Matlack 	 * In both cases, sp->role.access contains the correct access bits.
7416a97575dSDavid Matlack 	 */
7426a97575dSDavid Matlack 	return sp->role.access;
7436a97575dSDavid Matlack }
7446a97575dSDavid Matlack 
74572ae5822SSean Christopherson static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
74672ae5822SSean Christopherson 					 gfn_t gfn, unsigned int access)
7476a97575dSDavid Matlack {
7486a97575dSDavid Matlack 	if (sp_has_gptes(sp)) {
7496a97575dSDavid Matlack 		sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
75084e5ffd0SLai Jiangshan 		return;
75184e5ffd0SLai Jiangshan 	}
75284e5ffd0SLai Jiangshan 
7536a97575dSDavid Matlack 	WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
7546a97575dSDavid Matlack 	          "access mismatch under %s page %llx (expected %u, got %u)\n",
7556a97575dSDavid Matlack 	          sp->role.passthrough ? "passthrough" : "direct",
7566a97575dSDavid Matlack 	          sp->gfn, kvm_mmu_page_get_access(sp, index), access);
7576a97575dSDavid Matlack 
7586a97575dSDavid Matlack 	WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
7596a97575dSDavid Matlack 	          "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
7606a97575dSDavid Matlack 	          sp->role.passthrough ? "passthrough" : "direct",
7616a97575dSDavid Matlack 	          sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
762c50d8ae3SPaolo Bonzini }
763c50d8ae3SPaolo Bonzini 
76472ae5822SSean Christopherson static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
76572ae5822SSean Christopherson 				    unsigned int access)
7666a97575dSDavid Matlack {
7676a97575dSDavid Matlack 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
7686a97575dSDavid Matlack 
7696a97575dSDavid Matlack 	kvm_mmu_page_set_translation(sp, index, gfn, access);
770c50d8ae3SPaolo Bonzini }
771c50d8ae3SPaolo Bonzini 
772c50d8ae3SPaolo Bonzini /*
773c50d8ae3SPaolo Bonzini  * Return the pointer to the large page information for a given gfn,
774c50d8ae3SPaolo Bonzini  * handling slots that are not large page aligned.
775c50d8ae3SPaolo Bonzini  */
776c50d8ae3SPaolo Bonzini static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
7778ca6f063SBen Gardon 		const struct kvm_memory_slot *slot, int level)
778c50d8ae3SPaolo Bonzini {
779c50d8ae3SPaolo Bonzini 	unsigned long idx;
780c50d8ae3SPaolo Bonzini 
781c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
782c50d8ae3SPaolo Bonzini 	return &slot->arch.lpage_info[level - 2][idx];
783c50d8ae3SPaolo Bonzini }
784c50d8ae3SPaolo Bonzini 
785269e9552SHamza Mahfooz static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
786c50d8ae3SPaolo Bonzini 					    gfn_t gfn, int count)
787c50d8ae3SPaolo Bonzini {
788c50d8ae3SPaolo Bonzini 	struct kvm_lpage_info *linfo;
789c50d8ae3SPaolo Bonzini 	int i;
790c50d8ae3SPaolo Bonzini 
7913bae0459SSean Christopherson 	for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
792c50d8ae3SPaolo Bonzini 		linfo = lpage_info_slot(gfn, slot, i);
793c50d8ae3SPaolo Bonzini 		linfo->disallow_lpage += count;
794c50d8ae3SPaolo Bonzini 		WARN_ON(linfo->disallow_lpage < 0);
795c50d8ae3SPaolo Bonzini 	}
796c50d8ae3SPaolo Bonzini }
797c50d8ae3SPaolo Bonzini 
798269e9552SHamza Mahfooz void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
799c50d8ae3SPaolo Bonzini {
800c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, 1);
801c50d8ae3SPaolo Bonzini }
802c50d8ae3SPaolo Bonzini 
803269e9552SHamza Mahfooz void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
804c50d8ae3SPaolo Bonzini {
805c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, -1);
806c50d8ae3SPaolo Bonzini }
807c50d8ae3SPaolo Bonzini 
808c50d8ae3SPaolo Bonzini static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
809c50d8ae3SPaolo Bonzini {
810c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
811c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
812c50d8ae3SPaolo Bonzini 	gfn_t gfn;
813c50d8ae3SPaolo Bonzini 
814c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages++;
815c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
816c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
817c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
818c50d8ae3SPaolo Bonzini 
819c50d8ae3SPaolo Bonzini 	/* the non-leaf shadow pages are keeping readonly. */
8203bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
821c50d8ae3SPaolo Bonzini 		return kvm_slot_page_track_add_page(kvm, slot, gfn,
822c50d8ae3SPaolo Bonzini 						    KVM_PAGE_TRACK_WRITE);
823c50d8ae3SPaolo Bonzini 
824c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
825be911771SDavid Matlack 
826be911771SDavid Matlack 	if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
827be911771SDavid Matlack 		kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
828c50d8ae3SPaolo Bonzini }
829c50d8ae3SPaolo Bonzini 
83061f94478SSean Christopherson void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
831c50d8ae3SPaolo Bonzini {
832428e9216SSean Christopherson 	/*
833428e9216SSean Christopherson 	 * If it's possible to replace the shadow page with an NX huge page,
834428e9216SSean Christopherson 	 * i.e. if the shadow page is the only thing currently preventing KVM
835428e9216SSean Christopherson 	 * from using a huge page, add the shadow page to the list of "to be
836428e9216SSean Christopherson 	 * zapped for NX recovery" pages.  Note, the shadow page can already be
837428e9216SSean Christopherson 	 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
838428e9216SSean Christopherson 	 * links a shadow page at multiple points.
839428e9216SSean Christopherson 	 */
84061f94478SSean Christopherson 	if (!list_empty(&sp->possible_nx_huge_page_link))
841c50d8ae3SPaolo Bonzini 		return;
842c50d8ae3SPaolo Bonzini 
843c50d8ae3SPaolo Bonzini 	++kvm->stat.nx_lpage_splits;
84455c510e2SSean Christopherson 	list_add_tail(&sp->possible_nx_huge_page_link,
84555c510e2SSean Christopherson 		      &kvm->arch.possible_nx_huge_pages);
846c50d8ae3SPaolo Bonzini }
847c50d8ae3SPaolo Bonzini 
84861f94478SSean Christopherson static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
84961f94478SSean Christopherson 				 bool nx_huge_page_possible)
85061f94478SSean Christopherson {
85161f94478SSean Christopherson 	sp->nx_huge_page_disallowed = true;
85261f94478SSean Christopherson 
85361f94478SSean Christopherson 	if (nx_huge_page_possible)
85461f94478SSean Christopherson 		track_possible_nx_huge_page(kvm, sp);
855c50d8ae3SPaolo Bonzini }
856c50d8ae3SPaolo Bonzini 
857c50d8ae3SPaolo Bonzini static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
858c50d8ae3SPaolo Bonzini {
859c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
860c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
861c50d8ae3SPaolo Bonzini 	gfn_t gfn;
862c50d8ae3SPaolo Bonzini 
863c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages--;
864c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
865c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
866c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
8673bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
868c50d8ae3SPaolo Bonzini 		return kvm_slot_page_track_remove_page(kvm, slot, gfn,
869c50d8ae3SPaolo Bonzini 						       KVM_PAGE_TRACK_WRITE);
870c50d8ae3SPaolo Bonzini 
871c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_allow_lpage(slot, gfn);
872c50d8ae3SPaolo Bonzini }
873c50d8ae3SPaolo Bonzini 
87461f94478SSean Christopherson void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
875c50d8ae3SPaolo Bonzini {
87655c510e2SSean Christopherson 	if (list_empty(&sp->possible_nx_huge_page_link))
877428e9216SSean Christopherson 		return;
878428e9216SSean Christopherson 
879c50d8ae3SPaolo Bonzini 	--kvm->stat.nx_lpage_splits;
88055c510e2SSean Christopherson 	list_del_init(&sp->possible_nx_huge_page_link);
881c50d8ae3SPaolo Bonzini }
882c50d8ae3SPaolo Bonzini 
88361f94478SSean Christopherson static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
88461f94478SSean Christopherson {
88561f94478SSean Christopherson 	sp->nx_huge_page_disallowed = false;
88661f94478SSean Christopherson 
88761f94478SSean Christopherson 	untrack_possible_nx_huge_page(kvm, sp);
888c50d8ae3SPaolo Bonzini }
889c50d8ae3SPaolo Bonzini 
890c50d8ae3SPaolo Bonzini static struct kvm_memory_slot *
891c50d8ae3SPaolo Bonzini gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
892c50d8ae3SPaolo Bonzini 			    bool no_dirty_log)
893c50d8ae3SPaolo Bonzini {
894c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
895c50d8ae3SPaolo Bonzini 
896c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
89791b0d268SPaolo Bonzini 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
89891b0d268SPaolo Bonzini 		return NULL;
899044c59c4SPeter Xu 	if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
90091b0d268SPaolo Bonzini 		return NULL;
901c50d8ae3SPaolo Bonzini 
902c50d8ae3SPaolo Bonzini 	return slot;
903c50d8ae3SPaolo Bonzini }
904c50d8ae3SPaolo Bonzini 
905c50d8ae3SPaolo Bonzini /*
906c50d8ae3SPaolo Bonzini  * About rmap_head encoding:
907c50d8ae3SPaolo Bonzini  *
908c50d8ae3SPaolo Bonzini  * If the bit zero of rmap_head->val is clear, then it points to the only spte
909c50d8ae3SPaolo Bonzini  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
910c50d8ae3SPaolo Bonzini  * pte_list_desc containing more mappings.
911c50d8ae3SPaolo Bonzini  */
912c50d8ae3SPaolo Bonzini 
913c50d8ae3SPaolo Bonzini /*
914c50d8ae3SPaolo Bonzini  * Returns the number of pointers in the rmap chain, not counting the new one.
915c50d8ae3SPaolo Bonzini  */
9162ff9039aSDavid Matlack static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
917c50d8ae3SPaolo Bonzini 			struct kvm_rmap_head *rmap_head)
918c50d8ae3SPaolo Bonzini {
919c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
92013236e25SPeter Xu 	int count = 0;
921c50d8ae3SPaolo Bonzini 
922c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
923805a0f83SStephen Zhang 		rmap_printk("%p %llx 0->1\n", spte, *spte);
924c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)spte;
925c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
926805a0f83SStephen Zhang 		rmap_printk("%p %llx 1->many\n", spte, *spte);
9272ff9039aSDavid Matlack 		desc = kvm_mmu_memory_cache_alloc(cache);
928c50d8ae3SPaolo Bonzini 		desc->sptes[0] = (u64 *)rmap_head->val;
929c50d8ae3SPaolo Bonzini 		desc->sptes[1] = spte;
93013236e25SPeter Xu 		desc->spte_count = 2;
931c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)desc | 1;
932c50d8ae3SPaolo Bonzini 		++count;
933c50d8ae3SPaolo Bonzini 	} else {
934805a0f83SStephen Zhang 		rmap_printk("%p %llx many->many\n", spte, *spte);
935c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
93613236e25SPeter Xu 		while (desc->spte_count == PTE_LIST_EXT) {
937c50d8ae3SPaolo Bonzini 			count += PTE_LIST_EXT;
938c6c4f961SLi RongQing 			if (!desc->more) {
9392ff9039aSDavid Matlack 				desc->more = kvm_mmu_memory_cache_alloc(cache);
940c50d8ae3SPaolo Bonzini 				desc = desc->more;
94113236e25SPeter Xu 				desc->spte_count = 0;
942c6c4f961SLi RongQing 				break;
943c6c4f961SLi RongQing 			}
944c6c4f961SLi RongQing 			desc = desc->more;
945c50d8ae3SPaolo Bonzini 		}
94613236e25SPeter Xu 		count += desc->spte_count;
94713236e25SPeter Xu 		desc->sptes[desc->spte_count++] = spte;
948c50d8ae3SPaolo Bonzini 	}
949c50d8ae3SPaolo Bonzini 	return count;
950c50d8ae3SPaolo Bonzini }
951c50d8ae3SPaolo Bonzini 
952c50d8ae3SPaolo Bonzini static void
953c50d8ae3SPaolo Bonzini pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
954c50d8ae3SPaolo Bonzini 			   struct pte_list_desc *desc, int i,
955c50d8ae3SPaolo Bonzini 			   struct pte_list_desc *prev_desc)
956c50d8ae3SPaolo Bonzini {
95713236e25SPeter Xu 	int j = desc->spte_count - 1;
958c50d8ae3SPaolo Bonzini 
959c50d8ae3SPaolo Bonzini 	desc->sptes[i] = desc->sptes[j];
960c50d8ae3SPaolo Bonzini 	desc->sptes[j] = NULL;
96113236e25SPeter Xu 	desc->spte_count--;
96213236e25SPeter Xu 	if (desc->spte_count)
963c50d8ae3SPaolo Bonzini 		return;
964c50d8ae3SPaolo Bonzini 	if (!prev_desc && !desc->more)
965fe3c2b4cSMiaohe Lin 		rmap_head->val = 0;
966c50d8ae3SPaolo Bonzini 	else
967c50d8ae3SPaolo Bonzini 		if (prev_desc)
968c50d8ae3SPaolo Bonzini 			prev_desc->more = desc->more;
969c50d8ae3SPaolo Bonzini 		else
970c50d8ae3SPaolo Bonzini 			rmap_head->val = (unsigned long)desc->more | 1;
971c50d8ae3SPaolo Bonzini 	mmu_free_pte_list_desc(desc);
972c50d8ae3SPaolo Bonzini }
973c50d8ae3SPaolo Bonzini 
9743c2e1037SSean Christopherson static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
975c50d8ae3SPaolo Bonzini {
976c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
977c50d8ae3SPaolo Bonzini 	struct pte_list_desc *prev_desc;
978c50d8ae3SPaolo Bonzini 	int i;
979c50d8ae3SPaolo Bonzini 
980c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
981c50d8ae3SPaolo Bonzini 		pr_err("%s: %p 0->BUG\n", __func__, spte);
982c50d8ae3SPaolo Bonzini 		BUG();
983c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
984805a0f83SStephen Zhang 		rmap_printk("%p 1->0\n", spte);
985c50d8ae3SPaolo Bonzini 		if ((u64 *)rmap_head->val != spte) {
986c50d8ae3SPaolo Bonzini 			pr_err("%s:  %p 1->BUG\n", __func__, spte);
987c50d8ae3SPaolo Bonzini 			BUG();
988c50d8ae3SPaolo Bonzini 		}
989c50d8ae3SPaolo Bonzini 		rmap_head->val = 0;
990c50d8ae3SPaolo Bonzini 	} else {
991805a0f83SStephen Zhang 		rmap_printk("%p many->many\n", spte);
992c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
993c50d8ae3SPaolo Bonzini 		prev_desc = NULL;
994c50d8ae3SPaolo Bonzini 		while (desc) {
99513236e25SPeter Xu 			for (i = 0; i < desc->spte_count; ++i) {
996c50d8ae3SPaolo Bonzini 				if (desc->sptes[i] == spte) {
997c50d8ae3SPaolo Bonzini 					pte_list_desc_remove_entry(rmap_head,
998c50d8ae3SPaolo Bonzini 							desc, i, prev_desc);
999c50d8ae3SPaolo Bonzini 					return;
1000c50d8ae3SPaolo Bonzini 				}
1001c50d8ae3SPaolo Bonzini 			}
1002c50d8ae3SPaolo Bonzini 			prev_desc = desc;
1003c50d8ae3SPaolo Bonzini 			desc = desc->more;
1004c50d8ae3SPaolo Bonzini 		}
1005c50d8ae3SPaolo Bonzini 		pr_err("%s: %p many->many\n", __func__, spte);
1006c50d8ae3SPaolo Bonzini 		BUG();
1007c50d8ae3SPaolo Bonzini 	}
1008c50d8ae3SPaolo Bonzini }
1009c50d8ae3SPaolo Bonzini 
10109202aee8SSean Christopherson static void kvm_zap_one_rmap_spte(struct kvm *kvm,
10119202aee8SSean Christopherson 				  struct kvm_rmap_head *rmap_head, u64 *sptep)
1012c50d8ae3SPaolo Bonzini {
101371f51d2cSMingwei Zhang 	mmu_spte_clear_track_bits(kvm, sptep);
10143c2e1037SSean Christopherson 	pte_list_remove(sptep, rmap_head);
1015c50d8ae3SPaolo Bonzini }
1016c50d8ae3SPaolo Bonzini 
10179202aee8SSean Christopherson /* Return true if at least one SPTE was zapped, false otherwise */
10189202aee8SSean Christopherson static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
10199202aee8SSean Christopherson 				   struct kvm_rmap_head *rmap_head)
1020a75b5404SPeter Xu {
1021a75b5404SPeter Xu 	struct pte_list_desc *desc, *next;
1022a75b5404SPeter Xu 	int i;
1023a75b5404SPeter Xu 
1024a75b5404SPeter Xu 	if (!rmap_head->val)
1025a75b5404SPeter Xu 		return false;
1026a75b5404SPeter Xu 
1027a75b5404SPeter Xu 	if (!(rmap_head->val & 1)) {
102871f51d2cSMingwei Zhang 		mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
1029a75b5404SPeter Xu 		goto out;
1030a75b5404SPeter Xu 	}
1031a75b5404SPeter Xu 
1032a75b5404SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1033a75b5404SPeter Xu 
1034a75b5404SPeter Xu 	for (; desc; desc = next) {
1035a75b5404SPeter Xu 		for (i = 0; i < desc->spte_count; i++)
103671f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1037a75b5404SPeter Xu 		next = desc->more;
1038a75b5404SPeter Xu 		mmu_free_pte_list_desc(desc);
1039a75b5404SPeter Xu 	}
1040a75b5404SPeter Xu out:
1041a75b5404SPeter Xu 	/* rmap_head is meaningless now, remember to reset it */
1042a75b5404SPeter Xu 	rmap_head->val = 0;
1043a75b5404SPeter Xu 	return true;
1044a75b5404SPeter Xu }
1045a75b5404SPeter Xu 
10463bcd0662SPeter Xu unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
10473bcd0662SPeter Xu {
10483bcd0662SPeter Xu 	struct pte_list_desc *desc;
10493bcd0662SPeter Xu 	unsigned int count = 0;
10503bcd0662SPeter Xu 
10513bcd0662SPeter Xu 	if (!rmap_head->val)
10523bcd0662SPeter Xu 		return 0;
10533bcd0662SPeter Xu 	else if (!(rmap_head->val & 1))
10543bcd0662SPeter Xu 		return 1;
10553bcd0662SPeter Xu 
10563bcd0662SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
10573bcd0662SPeter Xu 
10583bcd0662SPeter Xu 	while (desc) {
10593bcd0662SPeter Xu 		count += desc->spte_count;
10603bcd0662SPeter Xu 		desc = desc->more;
10613bcd0662SPeter Xu 	}
10623bcd0662SPeter Xu 
10633bcd0662SPeter Xu 	return count;
10643bcd0662SPeter Xu }
10653bcd0662SPeter Xu 
106693e083d4SDavid Matlack static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1067269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
1068c50d8ae3SPaolo Bonzini {
1069c50d8ae3SPaolo Bonzini 	unsigned long idx;
1070c50d8ae3SPaolo Bonzini 
1071c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
10723bae0459SSean Christopherson 	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1073c50d8ae3SPaolo Bonzini }
1074c50d8ae3SPaolo Bonzini 
1075c50d8ae3SPaolo Bonzini static bool rmap_can_add(struct kvm_vcpu *vcpu)
1076c50d8ae3SPaolo Bonzini {
1077356ec69aSSean Christopherson 	struct kvm_mmu_memory_cache *mc;
1078c50d8ae3SPaolo Bonzini 
1079356ec69aSSean Christopherson 	mc = &vcpu->arch.mmu_pte_list_desc_cache;
108094ce87efSSean Christopherson 	return kvm_mmu_memory_cache_nr_free_objects(mc);
1081c50d8ae3SPaolo Bonzini }
1082c50d8ae3SPaolo Bonzini 
1083c50d8ae3SPaolo Bonzini static void rmap_remove(struct kvm *kvm, u64 *spte)
1084c50d8ae3SPaolo Bonzini {
1085601f8af0SDavid Matlack 	struct kvm_memslots *slots;
1086601f8af0SDavid Matlack 	struct kvm_memory_slot *slot;
1087c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1088c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1089c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1090c50d8ae3SPaolo Bonzini 
109157354682SSean Christopherson 	sp = sptep_to_sp(spte);
109279e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1093601f8af0SDavid Matlack 
1094601f8af0SDavid Matlack 	/*
109568be1306SDavid Matlack 	 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
109668be1306SDavid Matlack 	 * so we have to determine which memslots to use based on context
109768be1306SDavid Matlack 	 * information in sp->role.
1098601f8af0SDavid Matlack 	 */
1099601f8af0SDavid Matlack 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1100601f8af0SDavid Matlack 
1101601f8af0SDavid Matlack 	slot = __gfn_to_memslot(slots, gfn);
110293e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1103601f8af0SDavid Matlack 
11043c2e1037SSean Christopherson 	pte_list_remove(spte, rmap_head);
1105c50d8ae3SPaolo Bonzini }
1106c50d8ae3SPaolo Bonzini 
1107c50d8ae3SPaolo Bonzini /*
1108c50d8ae3SPaolo Bonzini  * Used by the following functions to iterate through the sptes linked by a
1109c50d8ae3SPaolo Bonzini  * rmap.  All fields are private and not assumed to be used outside.
1110c50d8ae3SPaolo Bonzini  */
1111c50d8ae3SPaolo Bonzini struct rmap_iterator {
1112c50d8ae3SPaolo Bonzini 	/* private fields */
1113c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1114c50d8ae3SPaolo Bonzini 	int pos;			/* index of the sptep */
1115c50d8ae3SPaolo Bonzini };
1116c50d8ae3SPaolo Bonzini 
1117c50d8ae3SPaolo Bonzini /*
1118c50d8ae3SPaolo Bonzini  * Iteration must be started by this function.  This should also be used after
1119c50d8ae3SPaolo Bonzini  * removing/dropping sptes from the rmap link because in such cases the
11200a03cbdaSMiaohe Lin  * information in the iterator may not be valid.
1121c50d8ae3SPaolo Bonzini  *
1122c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1123c50d8ae3SPaolo Bonzini  */
1124c50d8ae3SPaolo Bonzini static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1125c50d8ae3SPaolo Bonzini 			   struct rmap_iterator *iter)
1126c50d8ae3SPaolo Bonzini {
1127c50d8ae3SPaolo Bonzini 	u64 *sptep;
1128c50d8ae3SPaolo Bonzini 
1129c50d8ae3SPaolo Bonzini 	if (!rmap_head->val)
1130c50d8ae3SPaolo Bonzini 		return NULL;
1131c50d8ae3SPaolo Bonzini 
1132c50d8ae3SPaolo Bonzini 	if (!(rmap_head->val & 1)) {
1133c50d8ae3SPaolo Bonzini 		iter->desc = NULL;
1134c50d8ae3SPaolo Bonzini 		sptep = (u64 *)rmap_head->val;
1135c50d8ae3SPaolo Bonzini 		goto out;
1136c50d8ae3SPaolo Bonzini 	}
1137c50d8ae3SPaolo Bonzini 
1138c50d8ae3SPaolo Bonzini 	iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1139c50d8ae3SPaolo Bonzini 	iter->pos = 0;
1140c50d8ae3SPaolo Bonzini 	sptep = iter->desc->sptes[iter->pos];
1141c50d8ae3SPaolo Bonzini out:
1142c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1143c50d8ae3SPaolo Bonzini 	return sptep;
1144c50d8ae3SPaolo Bonzini }
1145c50d8ae3SPaolo Bonzini 
1146c50d8ae3SPaolo Bonzini /*
1147c50d8ae3SPaolo Bonzini  * Must be used with a valid iterator: e.g. after rmap_get_first().
1148c50d8ae3SPaolo Bonzini  *
1149c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1150c50d8ae3SPaolo Bonzini  */
1151c50d8ae3SPaolo Bonzini static u64 *rmap_get_next(struct rmap_iterator *iter)
1152c50d8ae3SPaolo Bonzini {
1153c50d8ae3SPaolo Bonzini 	u64 *sptep;
1154c50d8ae3SPaolo Bonzini 
1155c50d8ae3SPaolo Bonzini 	if (iter->desc) {
1156c50d8ae3SPaolo Bonzini 		if (iter->pos < PTE_LIST_EXT - 1) {
1157c50d8ae3SPaolo Bonzini 			++iter->pos;
1158c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1159c50d8ae3SPaolo Bonzini 			if (sptep)
1160c50d8ae3SPaolo Bonzini 				goto out;
1161c50d8ae3SPaolo Bonzini 		}
1162c50d8ae3SPaolo Bonzini 
1163c50d8ae3SPaolo Bonzini 		iter->desc = iter->desc->more;
1164c50d8ae3SPaolo Bonzini 
1165c50d8ae3SPaolo Bonzini 		if (iter->desc) {
1166c50d8ae3SPaolo Bonzini 			iter->pos = 0;
1167c50d8ae3SPaolo Bonzini 			/* desc->sptes[0] cannot be NULL */
1168c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1169c50d8ae3SPaolo Bonzini 			goto out;
1170c50d8ae3SPaolo Bonzini 		}
1171c50d8ae3SPaolo Bonzini 	}
1172c50d8ae3SPaolo Bonzini 
1173c50d8ae3SPaolo Bonzini 	return NULL;
1174c50d8ae3SPaolo Bonzini out:
1175c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1176c50d8ae3SPaolo Bonzini 	return sptep;
1177c50d8ae3SPaolo Bonzini }
1178c50d8ae3SPaolo Bonzini 
1179c50d8ae3SPaolo Bonzini #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)			\
1180c50d8ae3SPaolo Bonzini 	for (_spte_ = rmap_get_first(_rmap_head_, _iter_);		\
1181c50d8ae3SPaolo Bonzini 	     _spte_; _spte_ = rmap_get_next(_iter_))
1182c50d8ae3SPaolo Bonzini 
1183c50d8ae3SPaolo Bonzini static void drop_spte(struct kvm *kvm, u64 *sptep)
1184c50d8ae3SPaolo Bonzini {
118571f51d2cSMingwei Zhang 	u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
11867fa2a347SSean Christopherson 
11877fa2a347SSean Christopherson 	if (is_shadow_present_pte(old_spte))
1188c50d8ae3SPaolo Bonzini 		rmap_remove(kvm, sptep);
1189c50d8ae3SPaolo Bonzini }
1190c50d8ae3SPaolo Bonzini 
119103787394SPaolo Bonzini static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1192c50d8ae3SPaolo Bonzini {
11930cd8dc73SPaolo Bonzini 	struct kvm_mmu_page *sp;
11940cd8dc73SPaolo Bonzini 
11950cd8dc73SPaolo Bonzini 	sp = sptep_to_sp(sptep);
11960cd8dc73SPaolo Bonzini 	WARN_ON(sp->role.level == PG_LEVEL_4K);
11970cd8dc73SPaolo Bonzini 
1198c50d8ae3SPaolo Bonzini 	drop_spte(kvm, sptep);
119903787394SPaolo Bonzini 
120003787394SPaolo Bonzini 	if (flush)
12011b2dc736SHou Wenlong 		kvm_flush_remote_tlbs_sptep(kvm, sptep);
1202c50d8ae3SPaolo Bonzini }
1203c50d8ae3SPaolo Bonzini 
1204c50d8ae3SPaolo Bonzini /*
1205c50d8ae3SPaolo Bonzini  * Write-protect on the specified @sptep, @pt_protect indicates whether
1206c50d8ae3SPaolo Bonzini  * spte write-protection is caused by protecting shadow page table.
1207c50d8ae3SPaolo Bonzini  *
1208c50d8ae3SPaolo Bonzini  * Note: write protection is difference between dirty logging and spte
1209c50d8ae3SPaolo Bonzini  * protection:
1210c50d8ae3SPaolo Bonzini  * - for dirty logging, the spte can be set to writable at anytime if
1211c50d8ae3SPaolo Bonzini  *   its dirty bitmap is properly set.
1212c50d8ae3SPaolo Bonzini  * - for spte protection, the spte can be writable only after unsync-ing
1213c50d8ae3SPaolo Bonzini  *   shadow page.
1214c50d8ae3SPaolo Bonzini  *
1215c50d8ae3SPaolo Bonzini  * Return true if tlb need be flushed.
1216c50d8ae3SPaolo Bonzini  */
1217c50d8ae3SPaolo Bonzini static bool spte_write_protect(u64 *sptep, bool pt_protect)
1218c50d8ae3SPaolo Bonzini {
1219c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1220c50d8ae3SPaolo Bonzini 
1221c50d8ae3SPaolo Bonzini 	if (!is_writable_pte(spte) &&
1222706c9c55SSean Christopherson 	    !(pt_protect && is_mmu_writable_spte(spte)))
1223c50d8ae3SPaolo Bonzini 		return false;
1224c50d8ae3SPaolo Bonzini 
1225805a0f83SStephen Zhang 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1226c50d8ae3SPaolo Bonzini 
1227c50d8ae3SPaolo Bonzini 	if (pt_protect)
12285fc3424fSSean Christopherson 		spte &= ~shadow_mmu_writable_mask;
1229c50d8ae3SPaolo Bonzini 	spte = spte & ~PT_WRITABLE_MASK;
1230c50d8ae3SPaolo Bonzini 
1231c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1232c50d8ae3SPaolo Bonzini }
1233c50d8ae3SPaolo Bonzini 
12341346bbb6SDavid Matlack static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1235c50d8ae3SPaolo Bonzini 			       bool pt_protect)
1236c50d8ae3SPaolo Bonzini {
1237c50d8ae3SPaolo Bonzini 	u64 *sptep;
1238c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1239c50d8ae3SPaolo Bonzini 	bool flush = false;
1240c50d8ae3SPaolo Bonzini 
1241c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1242c50d8ae3SPaolo Bonzini 		flush |= spte_write_protect(sptep, pt_protect);
1243c50d8ae3SPaolo Bonzini 
1244c50d8ae3SPaolo Bonzini 	return flush;
1245c50d8ae3SPaolo Bonzini }
1246c50d8ae3SPaolo Bonzini 
1247c50d8ae3SPaolo Bonzini static bool spte_clear_dirty(u64 *sptep)
1248c50d8ae3SPaolo Bonzini {
1249c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1250c50d8ae3SPaolo Bonzini 
1251805a0f83SStephen Zhang 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1252c50d8ae3SPaolo Bonzini 
1253c50d8ae3SPaolo Bonzini 	MMU_WARN_ON(!spte_ad_enabled(spte));
1254c50d8ae3SPaolo Bonzini 	spte &= ~shadow_dirty_mask;
1255c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1256c50d8ae3SPaolo Bonzini }
1257c50d8ae3SPaolo Bonzini 
1258c50d8ae3SPaolo Bonzini static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1259c50d8ae3SPaolo Bonzini {
1260c50d8ae3SPaolo Bonzini 	bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1261c50d8ae3SPaolo Bonzini 					       (unsigned long *)sptep);
1262c50d8ae3SPaolo Bonzini 	if (was_writable && !spte_ad_enabled(*sptep))
1263c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1264c50d8ae3SPaolo Bonzini 
1265c50d8ae3SPaolo Bonzini 	return was_writable;
1266c50d8ae3SPaolo Bonzini }
1267c50d8ae3SPaolo Bonzini 
1268c50d8ae3SPaolo Bonzini /*
1269c50d8ae3SPaolo Bonzini  * Gets the GFN ready for another round of dirty logging by clearing the
1270c50d8ae3SPaolo Bonzini  *	- D bit on ad-enabled SPTEs, and
1271c50d8ae3SPaolo Bonzini  *	- W bit on ad-disabled SPTEs.
1272c50d8ae3SPaolo Bonzini  * Returns true iff any D or W bits were cleared.
1273c50d8ae3SPaolo Bonzini  */
12740a234f5dSSean Christopherson static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1275269e9552SHamza Mahfooz 			       const struct kvm_memory_slot *slot)
1276c50d8ae3SPaolo Bonzini {
1277c50d8ae3SPaolo Bonzini 	u64 *sptep;
1278c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1279c50d8ae3SPaolo Bonzini 	bool flush = false;
1280c50d8ae3SPaolo Bonzini 
1281c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1282c50d8ae3SPaolo Bonzini 		if (spte_ad_need_write_protect(*sptep))
1283c50d8ae3SPaolo Bonzini 			flush |= spte_wrprot_for_clear_dirty(sptep);
1284c50d8ae3SPaolo Bonzini 		else
1285c50d8ae3SPaolo Bonzini 			flush |= spte_clear_dirty(sptep);
1286c50d8ae3SPaolo Bonzini 
1287c50d8ae3SPaolo Bonzini 	return flush;
1288c50d8ae3SPaolo Bonzini }
1289c50d8ae3SPaolo Bonzini 
1290c50d8ae3SPaolo Bonzini /**
1291c50d8ae3SPaolo Bonzini  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1292c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1293c50d8ae3SPaolo Bonzini  * @slot: slot to protect
1294c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1295c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should protect
1296c50d8ae3SPaolo Bonzini  *
129789212919SKeqian Zhu  * Used when we do not need to care about huge page mappings.
1298c50d8ae3SPaolo Bonzini  */
1299c50d8ae3SPaolo Bonzini static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1300c50d8ae3SPaolo Bonzini 				     struct kvm_memory_slot *slot,
1301c50d8ae3SPaolo Bonzini 				     gfn_t gfn_offset, unsigned long mask)
1302c50d8ae3SPaolo Bonzini {
1303c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1304c50d8ae3SPaolo Bonzini 
13051f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1306a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1307a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, true);
1308e2209710SBen Gardon 
1309e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1310e2209710SBen Gardon 		return;
1311e2209710SBen Gardon 
1312c50d8ae3SPaolo Bonzini 	while (mask) {
131393e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13143bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13151346bbb6SDavid Matlack 		rmap_write_protect(rmap_head, false);
1316c50d8ae3SPaolo Bonzini 
1317c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1318c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1319c50d8ae3SPaolo Bonzini 	}
1320c50d8ae3SPaolo Bonzini }
1321c50d8ae3SPaolo Bonzini 
1322c50d8ae3SPaolo Bonzini /**
1323c50d8ae3SPaolo Bonzini  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1324c50d8ae3SPaolo Bonzini  * protect the page if the D-bit isn't supported.
1325c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1326c50d8ae3SPaolo Bonzini  * @slot: slot to clear D-bit
1327c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1328c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should clear D-bit
1329c50d8ae3SPaolo Bonzini  *
1330c50d8ae3SPaolo Bonzini  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1331c50d8ae3SPaolo Bonzini  */
1332a018eba5SSean Christopherson static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1333c50d8ae3SPaolo Bonzini 					 struct kvm_memory_slot *slot,
1334c50d8ae3SPaolo Bonzini 					 gfn_t gfn_offset, unsigned long mask)
1335c50d8ae3SPaolo Bonzini {
1336c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1337c50d8ae3SPaolo Bonzini 
13381f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1339a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1340a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, false);
1341e2209710SBen Gardon 
1342e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1343e2209710SBen Gardon 		return;
1344e2209710SBen Gardon 
1345c50d8ae3SPaolo Bonzini 	while (mask) {
134693e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13473bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13480a234f5dSSean Christopherson 		__rmap_clear_dirty(kvm, rmap_head, slot);
1349c50d8ae3SPaolo Bonzini 
1350c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1351c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1352c50d8ae3SPaolo Bonzini 	}
1353c50d8ae3SPaolo Bonzini }
1354c50d8ae3SPaolo Bonzini 
1355c50d8ae3SPaolo Bonzini /**
1356c50d8ae3SPaolo Bonzini  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1357c50d8ae3SPaolo Bonzini  * PT level pages.
1358c50d8ae3SPaolo Bonzini  *
1359c50d8ae3SPaolo Bonzini  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1360c50d8ae3SPaolo Bonzini  * enable dirty logging for them.
1361c50d8ae3SPaolo Bonzini  *
136289212919SKeqian Zhu  * We need to care about huge page mappings: e.g. during dirty logging we may
136389212919SKeqian Zhu  * have such mappings.
1364c50d8ae3SPaolo Bonzini  */
1365c50d8ae3SPaolo Bonzini void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1366c50d8ae3SPaolo Bonzini 				struct kvm_memory_slot *slot,
1367c50d8ae3SPaolo Bonzini 				gfn_t gfn_offset, unsigned long mask)
1368c50d8ae3SPaolo Bonzini {
136989212919SKeqian Zhu 	/*
137089212919SKeqian Zhu 	 * Huge pages are NOT write protected when we start dirty logging in
137189212919SKeqian Zhu 	 * initially-all-set mode; must write protect them here so that they
137289212919SKeqian Zhu 	 * are split to 4K on the first write.
137389212919SKeqian Zhu 	 *
137489212919SKeqian Zhu 	 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
137589212919SKeqian Zhu 	 * of memslot has no such restriction, so the range can cross two large
137689212919SKeqian Zhu 	 * pages.
137789212919SKeqian Zhu 	 */
137889212919SKeqian Zhu 	if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
137989212919SKeqian Zhu 		gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
138089212919SKeqian Zhu 		gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
138189212919SKeqian Zhu 
1382cb00a70bSDavid Matlack 		if (READ_ONCE(eager_page_split))
1383cb00a70bSDavid Matlack 			kvm_mmu_try_split_huge_pages(kvm, slot, start, end, PG_LEVEL_4K);
1384cb00a70bSDavid Matlack 
138589212919SKeqian Zhu 		kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
138689212919SKeqian Zhu 
138789212919SKeqian Zhu 		/* Cross two large pages? */
138889212919SKeqian Zhu 		if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
138989212919SKeqian Zhu 		    ALIGN(end << PAGE_SHIFT, PMD_SIZE))
139089212919SKeqian Zhu 			kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
139189212919SKeqian Zhu 						       PG_LEVEL_2M);
139289212919SKeqian Zhu 	}
139389212919SKeqian Zhu 
139489212919SKeqian Zhu 	/* Now handle 4K PTEs.  */
1395a018eba5SSean Christopherson 	if (kvm_x86_ops.cpu_dirty_log_size)
1396a018eba5SSean Christopherson 		kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1397c50d8ae3SPaolo Bonzini 	else
1398c50d8ae3SPaolo Bonzini 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1399c50d8ae3SPaolo Bonzini }
1400c50d8ae3SPaolo Bonzini 
1401fb04a1edSPeter Xu int kvm_cpu_dirty_log_size(void)
1402fb04a1edSPeter Xu {
14036dd03800SSean Christopherson 	return kvm_x86_ops.cpu_dirty_log_size;
1404fb04a1edSPeter Xu }
1405fb04a1edSPeter Xu 
1406c50d8ae3SPaolo Bonzini bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
14073ad93562SKeqian Zhu 				    struct kvm_memory_slot *slot, u64 gfn,
14083ad93562SKeqian Zhu 				    int min_level)
1409c50d8ae3SPaolo Bonzini {
1410c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1411c50d8ae3SPaolo Bonzini 	int i;
1412c50d8ae3SPaolo Bonzini 	bool write_protected = false;
1413c50d8ae3SPaolo Bonzini 
1414e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
14153ad93562SKeqian Zhu 		for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
141693e083d4SDavid Matlack 			rmap_head = gfn_to_rmap(gfn, i, slot);
14171346bbb6SDavid Matlack 			write_protected |= rmap_write_protect(rmap_head, true);
1418c50d8ae3SPaolo Bonzini 		}
1419e2209710SBen Gardon 	}
1420c50d8ae3SPaolo Bonzini 
14211f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
142246044f72SBen Gardon 		write_protected |=
14233ad93562SKeqian Zhu 			kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
142446044f72SBen Gardon 
1425c50d8ae3SPaolo Bonzini 	return write_protected;
1426c50d8ae3SPaolo Bonzini }
1427c50d8ae3SPaolo Bonzini 
1428cf48f9e2SDavid Matlack static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1429c50d8ae3SPaolo Bonzini {
1430c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
1431c50d8ae3SPaolo Bonzini 
1432c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
14333ad93562SKeqian Zhu 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1434c50d8ae3SPaolo Bonzini }
1435c50d8ae3SPaolo Bonzini 
1436f8480721SSean Christopherson static bool __kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1437269e9552SHamza Mahfooz 			   const struct kvm_memory_slot *slot)
1438c50d8ae3SPaolo Bonzini {
14399202aee8SSean Christopherson 	return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1440c50d8ae3SPaolo Bonzini }
1441c50d8ae3SPaolo Bonzini 
1442f8480721SSean Christopherson static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1443c50d8ae3SPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
14443039bcc7SSean Christopherson 			 pte_t unused)
1445c50d8ae3SPaolo Bonzini {
1446f8480721SSean Christopherson 	return __kvm_zap_rmap(kvm, rmap_head, slot);
1447c50d8ae3SPaolo Bonzini }
1448c50d8ae3SPaolo Bonzini 
1449aed02fe3SSean Christopherson static bool kvm_set_pte_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1450c50d8ae3SPaolo Bonzini 			     struct kvm_memory_slot *slot, gfn_t gfn, int level,
14513039bcc7SSean Christopherson 			     pte_t pte)
1452c50d8ae3SPaolo Bonzini {
1453c50d8ae3SPaolo Bonzini 	u64 *sptep;
1454c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
145598a26b69SVihas Mak 	bool need_flush = false;
1456c50d8ae3SPaolo Bonzini 	u64 new_spte;
1457c50d8ae3SPaolo Bonzini 	kvm_pfn_t new_pfn;
1458c50d8ae3SPaolo Bonzini 
14593039bcc7SSean Christopherson 	WARN_ON(pte_huge(pte));
14603039bcc7SSean Christopherson 	new_pfn = pte_pfn(pte);
1461c50d8ae3SPaolo Bonzini 
1462c50d8ae3SPaolo Bonzini restart:
1463c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
1464805a0f83SStephen Zhang 		rmap_printk("spte %p %llx gfn %llx (%d)\n",
1465c50d8ae3SPaolo Bonzini 			    sptep, *sptep, gfn, level);
1466c50d8ae3SPaolo Bonzini 
146798a26b69SVihas Mak 		need_flush = true;
1468c50d8ae3SPaolo Bonzini 
14693039bcc7SSean Christopherson 		if (pte_write(pte)) {
14709202aee8SSean Christopherson 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
1471c50d8ae3SPaolo Bonzini 			goto restart;
1472c50d8ae3SPaolo Bonzini 		} else {
1473cb3eedabSPaolo Bonzini 			new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1474cb3eedabSPaolo Bonzini 					*sptep, new_pfn);
1475c50d8ae3SPaolo Bonzini 
147671f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, sptep);
1477c50d8ae3SPaolo Bonzini 			mmu_spte_set(sptep, new_spte);
1478c50d8ae3SPaolo Bonzini 		}
1479c50d8ae3SPaolo Bonzini 	}
1480c50d8ae3SPaolo Bonzini 
1481c50d8ae3SPaolo Bonzini 	if (need_flush && kvm_available_flush_tlb_with_range()) {
14829ffe9265SHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, level);
148398a26b69SVihas Mak 		return false;
1484c50d8ae3SPaolo Bonzini 	}
1485c50d8ae3SPaolo Bonzini 
1486c50d8ae3SPaolo Bonzini 	return need_flush;
1487c50d8ae3SPaolo Bonzini }
1488c50d8ae3SPaolo Bonzini 
1489c50d8ae3SPaolo Bonzini struct slot_rmap_walk_iterator {
1490c50d8ae3SPaolo Bonzini 	/* input fields. */
1491269e9552SHamza Mahfooz 	const struct kvm_memory_slot *slot;
1492c50d8ae3SPaolo Bonzini 	gfn_t start_gfn;
1493c50d8ae3SPaolo Bonzini 	gfn_t end_gfn;
1494c50d8ae3SPaolo Bonzini 	int start_level;
1495c50d8ae3SPaolo Bonzini 	int end_level;
1496c50d8ae3SPaolo Bonzini 
1497c50d8ae3SPaolo Bonzini 	/* output fields. */
1498c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1499c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap;
1500c50d8ae3SPaolo Bonzini 	int level;
1501c50d8ae3SPaolo Bonzini 
1502c50d8ae3SPaolo Bonzini 	/* private field. */
1503c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *end_rmap;
1504c50d8ae3SPaolo Bonzini };
1505c50d8ae3SPaolo Bonzini 
1506c50d8ae3SPaolo Bonzini static void
1507c50d8ae3SPaolo Bonzini rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1508c50d8ae3SPaolo Bonzini {
1509c50d8ae3SPaolo Bonzini 	iterator->level = level;
1510c50d8ae3SPaolo Bonzini 	iterator->gfn = iterator->start_gfn;
151193e083d4SDavid Matlack 	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
151293e083d4SDavid Matlack 	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1513c50d8ae3SPaolo Bonzini }
1514c50d8ae3SPaolo Bonzini 
1515c50d8ae3SPaolo Bonzini static void
1516c50d8ae3SPaolo Bonzini slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1517269e9552SHamza Mahfooz 		    const struct kvm_memory_slot *slot, int start_level,
1518c50d8ae3SPaolo Bonzini 		    int end_level, gfn_t start_gfn, gfn_t end_gfn)
1519c50d8ae3SPaolo Bonzini {
1520c50d8ae3SPaolo Bonzini 	iterator->slot = slot;
1521c50d8ae3SPaolo Bonzini 	iterator->start_level = start_level;
1522c50d8ae3SPaolo Bonzini 	iterator->end_level = end_level;
1523c50d8ae3SPaolo Bonzini 	iterator->start_gfn = start_gfn;
1524c50d8ae3SPaolo Bonzini 	iterator->end_gfn = end_gfn;
1525c50d8ae3SPaolo Bonzini 
1526c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->start_level);
1527c50d8ae3SPaolo Bonzini }
1528c50d8ae3SPaolo Bonzini 
1529c50d8ae3SPaolo Bonzini static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1530c50d8ae3SPaolo Bonzini {
1531c50d8ae3SPaolo Bonzini 	return !!iterator->rmap;
1532c50d8ae3SPaolo Bonzini }
1533c50d8ae3SPaolo Bonzini 
1534c50d8ae3SPaolo Bonzini static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1535c50d8ae3SPaolo Bonzini {
15366ba1e04fSVipin Sharma 	while (++iterator->rmap <= iterator->end_rmap) {
1537c50d8ae3SPaolo Bonzini 		iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
15386ba1e04fSVipin Sharma 
15396ba1e04fSVipin Sharma 		if (iterator->rmap->val)
1540c50d8ae3SPaolo Bonzini 			return;
1541c50d8ae3SPaolo Bonzini 	}
1542c50d8ae3SPaolo Bonzini 
1543c50d8ae3SPaolo Bonzini 	if (++iterator->level > iterator->end_level) {
1544c50d8ae3SPaolo Bonzini 		iterator->rmap = NULL;
1545c50d8ae3SPaolo Bonzini 		return;
1546c50d8ae3SPaolo Bonzini 	}
1547c50d8ae3SPaolo Bonzini 
1548c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->level);
1549c50d8ae3SPaolo Bonzini }
1550c50d8ae3SPaolo Bonzini 
1551c50d8ae3SPaolo Bonzini #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1552c50d8ae3SPaolo Bonzini 	   _start_gfn, _end_gfn, _iter_)				\
1553c50d8ae3SPaolo Bonzini 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1554c50d8ae3SPaolo Bonzini 				 _end_level_, _start_gfn, _end_gfn);	\
1555c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_okay(_iter_);				\
1556c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_next(_iter_))
1557c50d8ae3SPaolo Bonzini 
15583039bcc7SSean Christopherson typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1559c1b91493SSean Christopherson 			       struct kvm_memory_slot *slot, gfn_t gfn,
15603039bcc7SSean Christopherson 			       int level, pte_t pte);
1561c1b91493SSean Christopherson 
15623039bcc7SSean Christopherson static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
15633039bcc7SSean Christopherson 						 struct kvm_gfn_range *range,
1564c1b91493SSean Christopherson 						 rmap_handler_t handler)
1565c50d8ae3SPaolo Bonzini {
1566c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
15673039bcc7SSean Christopherson 	bool ret = false;
1568c50d8ae3SPaolo Bonzini 
15693039bcc7SSean Christopherson 	for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
15703039bcc7SSean Christopherson 				 range->start, range->end - 1, &iterator)
15713039bcc7SSean Christopherson 		ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
15723039bcc7SSean Christopherson 			       iterator.level, range->pte);
1573c50d8ae3SPaolo Bonzini 
1574c50d8ae3SPaolo Bonzini 	return ret;
1575c50d8ae3SPaolo Bonzini }
1576c50d8ae3SPaolo Bonzini 
15773039bcc7SSean Christopherson bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1578c50d8ae3SPaolo Bonzini {
1579e2209710SBen Gardon 	bool flush = false;
1580c50d8ae3SPaolo Bonzini 
1581e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1582f8480721SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
1583063afacdSBen Gardon 
15841f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1585c7785d85SHou Wenlong 		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1586063afacdSBen Gardon 
15873039bcc7SSean Christopherson 	return flush;
1588c50d8ae3SPaolo Bonzini }
1589c50d8ae3SPaolo Bonzini 
15903039bcc7SSean Christopherson bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1591c50d8ae3SPaolo Bonzini {
1592e2209710SBen Gardon 	bool flush = false;
15931d8dd6b3SBen Gardon 
1594e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1595aed02fe3SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmap);
15961d8dd6b3SBen Gardon 
15971f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
15983039bcc7SSean Christopherson 		flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
15991d8dd6b3SBen Gardon 
16003039bcc7SSean Christopherson 	return flush;
1601c50d8ae3SPaolo Bonzini }
1602c50d8ae3SPaolo Bonzini 
1603aed02fe3SSean Christopherson static bool kvm_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1604c50d8ae3SPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
16053039bcc7SSean Christopherson 			 pte_t unused)
1606c50d8ae3SPaolo Bonzini {
1607c50d8ae3SPaolo Bonzini 	u64 *sptep;
16083f649ab7SKees Cook 	struct rmap_iterator iter;
1609c50d8ae3SPaolo Bonzini 	int young = 0;
1610c50d8ae3SPaolo Bonzini 
1611c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1612c50d8ae3SPaolo Bonzini 		young |= mmu_spte_age(sptep);
1613c50d8ae3SPaolo Bonzini 
1614c50d8ae3SPaolo Bonzini 	return young;
1615c50d8ae3SPaolo Bonzini }
1616c50d8ae3SPaolo Bonzini 
1617aed02fe3SSean Christopherson static bool kvm_test_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1618c50d8ae3SPaolo Bonzini 			      struct kvm_memory_slot *slot, gfn_t gfn,
16193039bcc7SSean Christopherson 			      int level, pte_t unused)
1620c50d8ae3SPaolo Bonzini {
1621c50d8ae3SPaolo Bonzini 	u64 *sptep;
1622c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1623c50d8ae3SPaolo Bonzini 
1624c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1625c50d8ae3SPaolo Bonzini 		if (is_accessed_spte(*sptep))
162698a26b69SVihas Mak 			return true;
162798a26b69SVihas Mak 	return false;
1628c50d8ae3SPaolo Bonzini }
1629c50d8ae3SPaolo Bonzini 
1630c50d8ae3SPaolo Bonzini #define RMAP_RECYCLE_THRESHOLD 1000
1631c50d8ae3SPaolo Bonzini 
16322ff9039aSDavid Matlack static void __rmap_add(struct kvm *kvm,
16332ff9039aSDavid Matlack 		       struct kvm_mmu_memory_cache *cache,
16342ff9039aSDavid Matlack 		       const struct kvm_memory_slot *slot,
163572ae5822SSean Christopherson 		       u64 *spte, gfn_t gfn, unsigned int access)
1636c50d8ae3SPaolo Bonzini {
1637c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
163868be1306SDavid Matlack 	struct kvm_rmap_head *rmap_head;
163968be1306SDavid Matlack 	int rmap_count;
1640c50d8ae3SPaolo Bonzini 
164157354682SSean Christopherson 	sp = sptep_to_sp(spte);
164279e48cecSSean Christopherson 	kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
164381cb4657SDavid Matlack 	kvm_update_page_stats(kvm, sp->role.level, 1);
164481cb4657SDavid Matlack 
164593e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
16462ff9039aSDavid Matlack 	rmap_count = pte_list_add(cache, spte, rmap_head);
1647c50d8ae3SPaolo Bonzini 
1648604f5332SMiaohe Lin 	if (rmap_count > kvm->stat.max_mmu_rmap_size)
1649604f5332SMiaohe Lin 		kvm->stat.max_mmu_rmap_size = rmap_count;
165068be1306SDavid Matlack 	if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
16519202aee8SSean Christopherson 		kvm_zap_all_rmap_sptes(kvm, rmap_head);
16521b2dc736SHou Wenlong 		kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
165368be1306SDavid Matlack 	}
1654c50d8ae3SPaolo Bonzini }
1655c50d8ae3SPaolo Bonzini 
16562ff9039aSDavid Matlack static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
165772ae5822SSean Christopherson 		     u64 *spte, gfn_t gfn, unsigned int access)
16582ff9039aSDavid Matlack {
16592ff9039aSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
16602ff9039aSDavid Matlack 
16616a97575dSDavid Matlack 	__rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
16622ff9039aSDavid Matlack }
16632ff9039aSDavid Matlack 
16643039bcc7SSean Christopherson bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1665c50d8ae3SPaolo Bonzini {
1666e2209710SBen Gardon 	bool young = false;
1667f8e14497SBen Gardon 
1668e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1669aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_age_rmap);
16703039bcc7SSean Christopherson 
16711f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16723039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1673f8e14497SBen Gardon 
1674f8e14497SBen Gardon 	return young;
1675c50d8ae3SPaolo Bonzini }
1676c50d8ae3SPaolo Bonzini 
16773039bcc7SSean Christopherson bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1678c50d8ae3SPaolo Bonzini {
1679e2209710SBen Gardon 	bool young = false;
1680f8e14497SBen Gardon 
1681e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1682aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmap);
16833039bcc7SSean Christopherson 
16841f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16853039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1686f8e14497SBen Gardon 
1687f8e14497SBen Gardon 	return young;
1688c50d8ae3SPaolo Bonzini }
1689c50d8ae3SPaolo Bonzini 
1690c50d8ae3SPaolo Bonzini #ifdef MMU_DEBUG
1691c50d8ae3SPaolo Bonzini static int is_empty_shadow_page(u64 *spt)
1692c50d8ae3SPaolo Bonzini {
1693c50d8ae3SPaolo Bonzini 	u64 *pos;
1694c50d8ae3SPaolo Bonzini 	u64 *end;
1695c50d8ae3SPaolo Bonzini 
16963adbdf81SMiaohe Lin 	for (pos = spt, end = pos + SPTE_ENT_PER_PAGE; pos != end; pos++)
1697c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*pos)) {
1698c50d8ae3SPaolo Bonzini 			printk(KERN_ERR "%s: %p %llx\n", __func__,
1699c50d8ae3SPaolo Bonzini 			       pos, *pos);
1700c50d8ae3SPaolo Bonzini 			return 0;
1701c50d8ae3SPaolo Bonzini 		}
1702c50d8ae3SPaolo Bonzini 	return 1;
1703c50d8ae3SPaolo Bonzini }
1704c50d8ae3SPaolo Bonzini #endif
1705c50d8ae3SPaolo Bonzini 
1706c50d8ae3SPaolo Bonzini /*
1707c50d8ae3SPaolo Bonzini  * This value is the sum of all of the kvm instances's
1708c50d8ae3SPaolo Bonzini  * kvm->arch.n_used_mmu_pages values.  We need a global,
1709c50d8ae3SPaolo Bonzini  * aggregate version in order to make the slab shrinker
1710c50d8ae3SPaolo Bonzini  * faster
1711c50d8ae3SPaolo Bonzini  */
1712d5aaad6fSSean Christopherson static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1713c50d8ae3SPaolo Bonzini {
1714c50d8ae3SPaolo Bonzini 	kvm->arch.n_used_mmu_pages += nr;
1715c50d8ae3SPaolo Bonzini 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1716c50d8ae3SPaolo Bonzini }
1717c50d8ae3SPaolo Bonzini 
171843a063caSYosry Ahmed static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
171943a063caSYosry Ahmed {
172043a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, +1);
172143a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, +1);
172243a063caSYosry Ahmed }
172343a063caSYosry Ahmed 
172443a063caSYosry Ahmed static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
172543a063caSYosry Ahmed {
172643a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, -1);
172743a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, -1);
172843a063caSYosry Ahmed }
172943a063caSYosry Ahmed 
173087654643SDavid Matlack static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1731c50d8ae3SPaolo Bonzini {
1732c50d8ae3SPaolo Bonzini 	MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1733c50d8ae3SPaolo Bonzini 	hlist_del(&sp->hash_link);
1734c50d8ae3SPaolo Bonzini 	list_del(&sp->link);
1735c50d8ae3SPaolo Bonzini 	free_page((unsigned long)sp->spt);
1736c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
17376a97575dSDavid Matlack 		free_page((unsigned long)sp->shadowed_translation);
1738c50d8ae3SPaolo Bonzini 	kmem_cache_free(mmu_page_header_cache, sp);
1739c50d8ae3SPaolo Bonzini }
1740c50d8ae3SPaolo Bonzini 
1741c50d8ae3SPaolo Bonzini static unsigned kvm_page_table_hashfn(gfn_t gfn)
1742c50d8ae3SPaolo Bonzini {
1743c50d8ae3SPaolo Bonzini 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1744c50d8ae3SPaolo Bonzini }
1745c50d8ae3SPaolo Bonzini 
17462ff9039aSDavid Matlack static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
1747c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp, u64 *parent_pte)
1748c50d8ae3SPaolo Bonzini {
1749c50d8ae3SPaolo Bonzini 	if (!parent_pte)
1750c50d8ae3SPaolo Bonzini 		return;
1751c50d8ae3SPaolo Bonzini 
17522ff9039aSDavid Matlack 	pte_list_add(cache, parent_pte, &sp->parent_ptes);
1753c50d8ae3SPaolo Bonzini }
1754c50d8ae3SPaolo Bonzini 
1755c50d8ae3SPaolo Bonzini static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1756c50d8ae3SPaolo Bonzini 				       u64 *parent_pte)
1757c50d8ae3SPaolo Bonzini {
17583c2e1037SSean Christopherson 	pte_list_remove(parent_pte, &sp->parent_ptes);
1759c50d8ae3SPaolo Bonzini }
1760c50d8ae3SPaolo Bonzini 
1761c50d8ae3SPaolo Bonzini static void drop_parent_pte(struct kvm_mmu_page *sp,
1762c50d8ae3SPaolo Bonzini 			    u64 *parent_pte)
1763c50d8ae3SPaolo Bonzini {
1764c50d8ae3SPaolo Bonzini 	mmu_page_remove_parent_pte(sp, parent_pte);
1765c50d8ae3SPaolo Bonzini 	mmu_spte_clear_no_track(parent_pte);
1766c50d8ae3SPaolo Bonzini }
1767c50d8ae3SPaolo Bonzini 
1768c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte);
1769c50d8ae3SPaolo Bonzini static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1770c50d8ae3SPaolo Bonzini {
1771c50d8ae3SPaolo Bonzini 	u64 *sptep;
1772c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1773c50d8ae3SPaolo Bonzini 
1774c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1775c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
1776c50d8ae3SPaolo Bonzini 	}
1777c50d8ae3SPaolo Bonzini }
1778c50d8ae3SPaolo Bonzini 
1779c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte)
1780c50d8ae3SPaolo Bonzini {
1781c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1782c50d8ae3SPaolo Bonzini 
178357354682SSean Christopherson 	sp = sptep_to_sp(spte);
178479e48cecSSean Christopherson 	if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1785c50d8ae3SPaolo Bonzini 		return;
1786c50d8ae3SPaolo Bonzini 	if (sp->unsync_children++)
1787c50d8ae3SPaolo Bonzini 		return;
1788c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
1789c50d8ae3SPaolo Bonzini }
1790c50d8ae3SPaolo Bonzini 
1791c50d8ae3SPaolo Bonzini static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
1792c50d8ae3SPaolo Bonzini 			       struct kvm_mmu_page *sp)
1793c50d8ae3SPaolo Bonzini {
1794c3e5e415SLai Jiangshan 	return -1;
1795c50d8ae3SPaolo Bonzini }
1796c50d8ae3SPaolo Bonzini 
1797c50d8ae3SPaolo Bonzini #define KVM_PAGE_ARRAY_NR 16
1798c50d8ae3SPaolo Bonzini 
1799c50d8ae3SPaolo Bonzini struct kvm_mmu_pages {
1800c50d8ae3SPaolo Bonzini 	struct mmu_page_and_offset {
1801c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
1802c50d8ae3SPaolo Bonzini 		unsigned int idx;
1803c50d8ae3SPaolo Bonzini 	} page[KVM_PAGE_ARRAY_NR];
1804c50d8ae3SPaolo Bonzini 	unsigned int nr;
1805c50d8ae3SPaolo Bonzini };
1806c50d8ae3SPaolo Bonzini 
1807c50d8ae3SPaolo Bonzini static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1808c50d8ae3SPaolo Bonzini 			 int idx)
1809c50d8ae3SPaolo Bonzini {
1810c50d8ae3SPaolo Bonzini 	int i;
1811c50d8ae3SPaolo Bonzini 
1812c50d8ae3SPaolo Bonzini 	if (sp->unsync)
1813c50d8ae3SPaolo Bonzini 		for (i=0; i < pvec->nr; i++)
1814c50d8ae3SPaolo Bonzini 			if (pvec->page[i].sp == sp)
1815c50d8ae3SPaolo Bonzini 				return 0;
1816c50d8ae3SPaolo Bonzini 
1817c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].sp = sp;
1818c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].idx = idx;
1819c50d8ae3SPaolo Bonzini 	pvec->nr++;
1820c50d8ae3SPaolo Bonzini 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
1821c50d8ae3SPaolo Bonzini }
1822c50d8ae3SPaolo Bonzini 
1823c50d8ae3SPaolo Bonzini static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1824c50d8ae3SPaolo Bonzini {
1825c50d8ae3SPaolo Bonzini 	--sp->unsync_children;
1826c50d8ae3SPaolo Bonzini 	WARN_ON((int)sp->unsync_children < 0);
1827c50d8ae3SPaolo Bonzini 	__clear_bit(idx, sp->unsync_child_bitmap);
1828c50d8ae3SPaolo Bonzini }
1829c50d8ae3SPaolo Bonzini 
1830c50d8ae3SPaolo Bonzini static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1831c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1832c50d8ae3SPaolo Bonzini {
1833c50d8ae3SPaolo Bonzini 	int i, ret, nr_unsync_leaf = 0;
1834c50d8ae3SPaolo Bonzini 
1835c50d8ae3SPaolo Bonzini 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1836c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
1837c50d8ae3SPaolo Bonzini 		u64 ent = sp->spt[i];
1838c50d8ae3SPaolo Bonzini 
1839c50d8ae3SPaolo Bonzini 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1840c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1841c50d8ae3SPaolo Bonzini 			continue;
1842c50d8ae3SPaolo Bonzini 		}
1843c50d8ae3SPaolo Bonzini 
18445e3edd7eSSean Christopherson 		child = spte_to_child_sp(ent);
1845c50d8ae3SPaolo Bonzini 
1846c50d8ae3SPaolo Bonzini 		if (child->unsync_children) {
1847c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1848c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1849c50d8ae3SPaolo Bonzini 
1850c50d8ae3SPaolo Bonzini 			ret = __mmu_unsync_walk(child, pvec);
1851c50d8ae3SPaolo Bonzini 			if (!ret) {
1852c50d8ae3SPaolo Bonzini 				clear_unsync_child_bit(sp, i);
1853c50d8ae3SPaolo Bonzini 				continue;
1854c50d8ae3SPaolo Bonzini 			} else if (ret > 0) {
1855c50d8ae3SPaolo Bonzini 				nr_unsync_leaf += ret;
1856c50d8ae3SPaolo Bonzini 			} else
1857c50d8ae3SPaolo Bonzini 				return ret;
1858c50d8ae3SPaolo Bonzini 		} else if (child->unsync) {
1859c50d8ae3SPaolo Bonzini 			nr_unsync_leaf++;
1860c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1861c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1862c50d8ae3SPaolo Bonzini 		} else
1863c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1864c50d8ae3SPaolo Bonzini 	}
1865c50d8ae3SPaolo Bonzini 
1866c50d8ae3SPaolo Bonzini 	return nr_unsync_leaf;
1867c50d8ae3SPaolo Bonzini }
1868c50d8ae3SPaolo Bonzini 
1869c50d8ae3SPaolo Bonzini #define INVALID_INDEX (-1)
1870c50d8ae3SPaolo Bonzini 
1871c50d8ae3SPaolo Bonzini static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1872c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1873c50d8ae3SPaolo Bonzini {
1874c50d8ae3SPaolo Bonzini 	pvec->nr = 0;
1875c50d8ae3SPaolo Bonzini 	if (!sp->unsync_children)
1876c50d8ae3SPaolo Bonzini 		return 0;
1877c50d8ae3SPaolo Bonzini 
1878c50d8ae3SPaolo Bonzini 	mmu_pages_add(pvec, sp, INVALID_INDEX);
1879c50d8ae3SPaolo Bonzini 	return __mmu_unsync_walk(sp, pvec);
1880c50d8ae3SPaolo Bonzini }
1881c50d8ae3SPaolo Bonzini 
1882c50d8ae3SPaolo Bonzini static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1883c50d8ae3SPaolo Bonzini {
1884c50d8ae3SPaolo Bonzini 	WARN_ON(!sp->unsync);
1885c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_sync_page(sp);
1886c50d8ae3SPaolo Bonzini 	sp->unsync = 0;
1887c50d8ae3SPaolo Bonzini 	--kvm->stat.mmu_unsync;
1888c50d8ae3SPaolo Bonzini }
1889c50d8ae3SPaolo Bonzini 
1890c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1891c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list);
1892c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1893c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list);
1894c50d8ae3SPaolo Bonzini 
1895767d8d8dSLai Jiangshan static bool sp_has_gptes(struct kvm_mmu_page *sp)
1896767d8d8dSLai Jiangshan {
1897767d8d8dSLai Jiangshan 	if (sp->role.direct)
1898767d8d8dSLai Jiangshan 		return false;
1899767d8d8dSLai Jiangshan 
190084e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
190184e5ffd0SLai Jiangshan 		return false;
190284e5ffd0SLai Jiangshan 
1903767d8d8dSLai Jiangshan 	return true;
1904767d8d8dSLai Jiangshan }
1905767d8d8dSLai Jiangshan 
1906ac101b7cSSean Christopherson #define for_each_valid_sp(_kvm, _sp, _list)				\
1907ac101b7cSSean Christopherson 	hlist_for_each_entry(_sp, _list, hash_link)			\
1908c50d8ae3SPaolo Bonzini 		if (is_obsolete_sp((_kvm), (_sp))) {			\
1909c50d8ae3SPaolo Bonzini 		} else
1910c50d8ae3SPaolo Bonzini 
1911767d8d8dSLai Jiangshan #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn)		\
1912ac101b7cSSean Christopherson 	for_each_valid_sp(_kvm, _sp,					\
1913ac101b7cSSean Christopherson 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
1914767d8d8dSLai Jiangshan 		if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1915c50d8ae3SPaolo Bonzini 
19168d5678a7SHou Wenlong static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1917c50d8ae3SPaolo Bonzini 			 struct list_head *invalid_list)
1918c50d8ae3SPaolo Bonzini {
1919c3e5e415SLai Jiangshan 	int ret = vcpu->arch.mmu->sync_page(vcpu, sp);
1920c3e5e415SLai Jiangshan 
19218d5678a7SHou Wenlong 	if (ret < 0)
1922c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
19238d5678a7SHou Wenlong 	return ret;
1924c50d8ae3SPaolo Bonzini }
1925c50d8ae3SPaolo Bonzini 
1926c50d8ae3SPaolo Bonzini static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1927c50d8ae3SPaolo Bonzini 					struct list_head *invalid_list,
1928c50d8ae3SPaolo Bonzini 					bool remote_flush)
1929c50d8ae3SPaolo Bonzini {
1930c50d8ae3SPaolo Bonzini 	if (!remote_flush && list_empty(invalid_list))
1931c50d8ae3SPaolo Bonzini 		return false;
1932c50d8ae3SPaolo Bonzini 
1933c50d8ae3SPaolo Bonzini 	if (!list_empty(invalid_list))
1934c50d8ae3SPaolo Bonzini 		kvm_mmu_commit_zap_page(kvm, invalid_list);
1935c50d8ae3SPaolo Bonzini 	else
1936c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
1937c50d8ae3SPaolo Bonzini 	return true;
1938c50d8ae3SPaolo Bonzini }
1939c50d8ae3SPaolo Bonzini 
1940c50d8ae3SPaolo Bonzini static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
1941c50d8ae3SPaolo Bonzini {
1942a955cad8SSean Christopherson 	if (sp->role.invalid)
1943a955cad8SSean Christopherson 		return true;
1944a955cad8SSean Christopherson 
1945fa3e4203SMiaohe Lin 	/* TDP MMU pages do not use the MMU generation. */
1946de0322f5SSean Christopherson 	return !is_tdp_mmu_page(sp) &&
1947c50d8ae3SPaolo Bonzini 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
1948c50d8ae3SPaolo Bonzini }
1949c50d8ae3SPaolo Bonzini 
1950c50d8ae3SPaolo Bonzini struct mmu_page_path {
1951c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
1952c50d8ae3SPaolo Bonzini 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
1953c50d8ae3SPaolo Bonzini };
1954c50d8ae3SPaolo Bonzini 
1955c50d8ae3SPaolo Bonzini #define for_each_sp(pvec, sp, parents, i)			\
1956c50d8ae3SPaolo Bonzini 		for (i = mmu_pages_first(&pvec, &parents);	\
1957c50d8ae3SPaolo Bonzini 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
1958c50d8ae3SPaolo Bonzini 			i = mmu_pages_next(&pvec, &parents, i))
1959c50d8ae3SPaolo Bonzini 
1960c50d8ae3SPaolo Bonzini static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1961c50d8ae3SPaolo Bonzini 			  struct mmu_page_path *parents,
1962c50d8ae3SPaolo Bonzini 			  int i)
1963c50d8ae3SPaolo Bonzini {
1964c50d8ae3SPaolo Bonzini 	int n;
1965c50d8ae3SPaolo Bonzini 
1966c50d8ae3SPaolo Bonzini 	for (n = i+1; n < pvec->nr; n++) {
1967c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp = pvec->page[n].sp;
1968c50d8ae3SPaolo Bonzini 		unsigned idx = pvec->page[n].idx;
1969c50d8ae3SPaolo Bonzini 		int level = sp->role.level;
1970c50d8ae3SPaolo Bonzini 
1971c50d8ae3SPaolo Bonzini 		parents->idx[level-1] = idx;
19723bae0459SSean Christopherson 		if (level == PG_LEVEL_4K)
1973c50d8ae3SPaolo Bonzini 			break;
1974c50d8ae3SPaolo Bonzini 
1975c50d8ae3SPaolo Bonzini 		parents->parent[level-2] = sp;
1976c50d8ae3SPaolo Bonzini 	}
1977c50d8ae3SPaolo Bonzini 
1978c50d8ae3SPaolo Bonzini 	return n;
1979c50d8ae3SPaolo Bonzini }
1980c50d8ae3SPaolo Bonzini 
1981c50d8ae3SPaolo Bonzini static int mmu_pages_first(struct kvm_mmu_pages *pvec,
1982c50d8ae3SPaolo Bonzini 			   struct mmu_page_path *parents)
1983c50d8ae3SPaolo Bonzini {
1984c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1985c50d8ae3SPaolo Bonzini 	int level;
1986c50d8ae3SPaolo Bonzini 
1987c50d8ae3SPaolo Bonzini 	if (pvec->nr == 0)
1988c50d8ae3SPaolo Bonzini 		return 0;
1989c50d8ae3SPaolo Bonzini 
1990c50d8ae3SPaolo Bonzini 	WARN_ON(pvec->page[0].idx != INVALID_INDEX);
1991c50d8ae3SPaolo Bonzini 
1992c50d8ae3SPaolo Bonzini 	sp = pvec->page[0].sp;
1993c50d8ae3SPaolo Bonzini 	level = sp->role.level;
19943bae0459SSean Christopherson 	WARN_ON(level == PG_LEVEL_4K);
1995c50d8ae3SPaolo Bonzini 
1996c50d8ae3SPaolo Bonzini 	parents->parent[level-2] = sp;
1997c50d8ae3SPaolo Bonzini 
1998c50d8ae3SPaolo Bonzini 	/* Also set up a sentinel.  Further entries in pvec are all
1999c50d8ae3SPaolo Bonzini 	 * children of sp, so this element is never overwritten.
2000c50d8ae3SPaolo Bonzini 	 */
2001c50d8ae3SPaolo Bonzini 	parents->parent[level-1] = NULL;
2002c50d8ae3SPaolo Bonzini 	return mmu_pages_next(pvec, parents, 0);
2003c50d8ae3SPaolo Bonzini }
2004c50d8ae3SPaolo Bonzini 
2005c50d8ae3SPaolo Bonzini static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2006c50d8ae3SPaolo Bonzini {
2007c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2008c50d8ae3SPaolo Bonzini 	unsigned int level = 0;
2009c50d8ae3SPaolo Bonzini 
2010c50d8ae3SPaolo Bonzini 	do {
2011c50d8ae3SPaolo Bonzini 		unsigned int idx = parents->idx[level];
2012c50d8ae3SPaolo Bonzini 		sp = parents->parent[level];
2013c50d8ae3SPaolo Bonzini 		if (!sp)
2014c50d8ae3SPaolo Bonzini 			return;
2015c50d8ae3SPaolo Bonzini 
2016c50d8ae3SPaolo Bonzini 		WARN_ON(idx == INVALID_INDEX);
2017c50d8ae3SPaolo Bonzini 		clear_unsync_child_bit(sp, idx);
2018c50d8ae3SPaolo Bonzini 		level++;
2019c50d8ae3SPaolo Bonzini 	} while (!sp->unsync_children);
2020c50d8ae3SPaolo Bonzini }
2021c50d8ae3SPaolo Bonzini 
202265855ed8SLai Jiangshan static int mmu_sync_children(struct kvm_vcpu *vcpu,
202365855ed8SLai Jiangshan 			     struct kvm_mmu_page *parent, bool can_yield)
2024c50d8ae3SPaolo Bonzini {
2025c50d8ae3SPaolo Bonzini 	int i;
2026c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2027c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2028c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2029c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2030c50d8ae3SPaolo Bonzini 	bool flush = false;
2031c50d8ae3SPaolo Bonzini 
2032c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2033c50d8ae3SPaolo Bonzini 		bool protected = false;
2034c50d8ae3SPaolo Bonzini 
2035c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i)
2036cf48f9e2SDavid Matlack 			protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2037c50d8ae3SPaolo Bonzini 
2038c50d8ae3SPaolo Bonzini 		if (protected) {
20395591c069SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2040c50d8ae3SPaolo Bonzini 			flush = false;
2041c50d8ae3SPaolo Bonzini 		}
2042c50d8ae3SPaolo Bonzini 
2043c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2044479a1efcSSean Christopherson 			kvm_unlink_unsync_page(vcpu->kvm, sp);
20458d5678a7SHou Wenlong 			flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2046c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2047c50d8ae3SPaolo Bonzini 		}
2048531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2049c3e5e415SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
205065855ed8SLai Jiangshan 			if (!can_yield) {
205165855ed8SLai Jiangshan 				kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
205265855ed8SLai Jiangshan 				return -EINTR;
205365855ed8SLai Jiangshan 			}
205465855ed8SLai Jiangshan 
2055531810caSBen Gardon 			cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2056c50d8ae3SPaolo Bonzini 			flush = false;
2057c50d8ae3SPaolo Bonzini 		}
2058c50d8ae3SPaolo Bonzini 	}
2059c50d8ae3SPaolo Bonzini 
2060c3e5e415SLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
206165855ed8SLai Jiangshan 	return 0;
2062c50d8ae3SPaolo Bonzini }
2063c50d8ae3SPaolo Bonzini 
2064c50d8ae3SPaolo Bonzini static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2065c50d8ae3SPaolo Bonzini {
2066c50d8ae3SPaolo Bonzini 	atomic_set(&sp->write_flooding_count,  0);
2067c50d8ae3SPaolo Bonzini }
2068c50d8ae3SPaolo Bonzini 
2069c50d8ae3SPaolo Bonzini static void clear_sp_write_flooding_count(u64 *spte)
2070c50d8ae3SPaolo Bonzini {
207157354682SSean Christopherson 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
2072c50d8ae3SPaolo Bonzini }
2073c50d8ae3SPaolo Bonzini 
2074cbd858b1SDavid Matlack /*
2075cbd858b1SDavid Matlack  * The vCPU is required when finding indirect shadow pages; the shadow
2076cbd858b1SDavid Matlack  * page may already exist and syncing it needs the vCPU pointer in
2077cbd858b1SDavid Matlack  * order to read guest page tables.  Direct shadow pages are never
2078cbd858b1SDavid Matlack  * unsync, thus @vcpu can be NULL if @role.direct is true.
2079cbd858b1SDavid Matlack  */
20803cc736b3SDavid Matlack static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
20813cc736b3SDavid Matlack 						     struct kvm_vcpu *vcpu,
208294c81364SDavid Matlack 						     gfn_t gfn,
208394c81364SDavid Matlack 						     struct hlist_head *sp_list,
20842e65e842SDavid Matlack 						     union kvm_mmu_page_role role)
2085c50d8ae3SPaolo Bonzini {
2086c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
20878d5678a7SHou Wenlong 	int ret;
2088c50d8ae3SPaolo Bonzini 	int collisions = 0;
2089c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2090c50d8ae3SPaolo Bonzini 
20913cc736b3SDavid Matlack 	for_each_valid_sp(kvm, sp, sp_list) {
2092c50d8ae3SPaolo Bonzini 		if (sp->gfn != gfn) {
2093c50d8ae3SPaolo Bonzini 			collisions++;
2094c50d8ae3SPaolo Bonzini 			continue;
2095c50d8ae3SPaolo Bonzini 		}
2096c50d8ae3SPaolo Bonzini 
2097ddc16abbSSean Christopherson 		if (sp->role.word != role.word) {
2098ddc16abbSSean Christopherson 			/*
2099ddc16abbSSean Christopherson 			 * If the guest is creating an upper-level page, zap
2100ddc16abbSSean Christopherson 			 * unsync pages for the same gfn.  While it's possible
2101ddc16abbSSean Christopherson 			 * the guest is using recursive page tables, in all
2102ddc16abbSSean Christopherson 			 * likelihood the guest has stopped using the unsync
2103ddc16abbSSean Christopherson 			 * page and is installing a completely unrelated page.
2104ddc16abbSSean Christopherson 			 * Unsync pages must not be left as is, because the new
2105ddc16abbSSean Christopherson 			 * upper-level page will be write-protected.
2106ddc16abbSSean Christopherson 			 */
21072e65e842SDavid Matlack 			if (role.level > PG_LEVEL_4K && sp->unsync)
21083cc736b3SDavid Matlack 				kvm_mmu_prepare_zap_page(kvm, sp,
2109ddc16abbSSean Christopherson 							 &invalid_list);
2110c50d8ae3SPaolo Bonzini 			continue;
2111ddc16abbSSean Christopherson 		}
2112c50d8ae3SPaolo Bonzini 
2113bb924ca6SDavid Matlack 		/* unsync and write-flooding only apply to indirect SPs. */
2114bb924ca6SDavid Matlack 		if (sp->role.direct)
211594c81364SDavid Matlack 			goto out;
2116fb58a9c3SSean Christopherson 
2117c50d8ae3SPaolo Bonzini 		if (sp->unsync) {
2118cbd858b1SDavid Matlack 			if (KVM_BUG_ON(!vcpu, kvm))
2119cbd858b1SDavid Matlack 				break;
2120cbd858b1SDavid Matlack 
212107dc4f35SSean Christopherson 			/*
2122479a1efcSSean Christopherson 			 * The page is good, but is stale.  kvm_sync_page does
212307dc4f35SSean Christopherson 			 * get the latest guest state, but (unlike mmu_unsync_children)
212407dc4f35SSean Christopherson 			 * it doesn't write-protect the page or mark it synchronized!
212507dc4f35SSean Christopherson 			 * This way the validity of the mapping is ensured, but the
212607dc4f35SSean Christopherson 			 * overhead of write protection is not incurred until the
212707dc4f35SSean Christopherson 			 * guest invalidates the TLB mapping.  This allows multiple
212807dc4f35SSean Christopherson 			 * SPs for a single gfn to be unsync.
212907dc4f35SSean Christopherson 			 *
213007dc4f35SSean Christopherson 			 * If the sync fails, the page is zapped.  If so, break
213107dc4f35SSean Christopherson 			 * in order to rebuild it.
2132c50d8ae3SPaolo Bonzini 			 */
21338d5678a7SHou Wenlong 			ret = kvm_sync_page(vcpu, sp, &invalid_list);
21348d5678a7SHou Wenlong 			if (ret < 0)
2135c50d8ae3SPaolo Bonzini 				break;
2136c50d8ae3SPaolo Bonzini 
2137c50d8ae3SPaolo Bonzini 			WARN_ON(!list_empty(&invalid_list));
21388d5678a7SHou Wenlong 			if (ret > 0)
21393cc736b3SDavid Matlack 				kvm_flush_remote_tlbs(kvm);
2140c50d8ae3SPaolo Bonzini 		}
2141c50d8ae3SPaolo Bonzini 
2142c50d8ae3SPaolo Bonzini 		__clear_sp_write_flooding_count(sp);
2143fb58a9c3SSean Christopherson 
2144c50d8ae3SPaolo Bonzini 		goto out;
2145c50d8ae3SPaolo Bonzini 	}
2146c50d8ae3SPaolo Bonzini 
214794c81364SDavid Matlack 	sp = NULL;
21483cc736b3SDavid Matlack 	++kvm->stat.mmu_cache_miss;
2149c50d8ae3SPaolo Bonzini 
215094c81364SDavid Matlack out:
21513cc736b3SDavid Matlack 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
215294c81364SDavid Matlack 
21533cc736b3SDavid Matlack 	if (collisions > kvm->stat.max_mmu_page_hash_collisions)
21543cc736b3SDavid Matlack 		kvm->stat.max_mmu_page_hash_collisions = collisions;
215594c81364SDavid Matlack 	return sp;
215694c81364SDavid Matlack }
215794c81364SDavid Matlack 
21582f8b1b53SDavid Matlack /* Caches used when allocating a new shadow page. */
21592f8b1b53SDavid Matlack struct shadow_page_caches {
21602f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *page_header_cache;
21612f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *shadow_page_cache;
21626a97575dSDavid Matlack 	struct kvm_mmu_memory_cache *shadowed_info_cache;
21632f8b1b53SDavid Matlack };
21642f8b1b53SDavid Matlack 
2165336081fbSDavid Matlack static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
21662f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
216794c81364SDavid Matlack 						      gfn_t gfn,
216894c81364SDavid Matlack 						      struct hlist_head *sp_list,
216994c81364SDavid Matlack 						      union kvm_mmu_page_role role)
217094c81364SDavid Matlack {
2171c306aec8SDavid Matlack 	struct kvm_mmu_page *sp;
2172c306aec8SDavid Matlack 
21732f8b1b53SDavid Matlack 	sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
21742f8b1b53SDavid Matlack 	sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
2175c306aec8SDavid Matlack 	if (!role.direct)
21766a97575dSDavid Matlack 		sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2177c306aec8SDavid Matlack 
2178c306aec8SDavid Matlack 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2179c306aec8SDavid Matlack 
218055c510e2SSean Christopherson 	INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2181428e9216SSean Christopherson 
2182c306aec8SDavid Matlack 	/*
2183c306aec8SDavid Matlack 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2184c306aec8SDavid Matlack 	 * depends on valid pages being added to the head of the list.  See
2185c306aec8SDavid Matlack 	 * comments in kvm_zap_obsolete_pages().
2186c306aec8SDavid Matlack 	 */
2187336081fbSDavid Matlack 	sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2188336081fbSDavid Matlack 	list_add(&sp->link, &kvm->arch.active_mmu_pages);
218943a063caSYosry Ahmed 	kvm_account_mmu_page(kvm, sp);
2190c50d8ae3SPaolo Bonzini 
2191c50d8ae3SPaolo Bonzini 	sp->gfn = gfn;
2192c50d8ae3SPaolo Bonzini 	sp->role = role;
2193ac101b7cSSean Christopherson 	hlist_add_head(&sp->hash_link, sp_list);
2194be911771SDavid Matlack 	if (sp_has_gptes(sp))
2195336081fbSDavid Matlack 		account_shadowed(kvm, sp);
2196ddc16abbSSean Christopherson 
219794c81364SDavid Matlack 	return sp;
219894c81364SDavid Matlack }
219994c81364SDavid Matlack 
2200cbd858b1SDavid Matlack /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
22013cc736b3SDavid Matlack static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
22023cc736b3SDavid Matlack 						      struct kvm_vcpu *vcpu,
22032f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
220487654643SDavid Matlack 						      gfn_t gfn,
220594c81364SDavid Matlack 						      union kvm_mmu_page_role role)
220694c81364SDavid Matlack {
220794c81364SDavid Matlack 	struct hlist_head *sp_list;
220894c81364SDavid Matlack 	struct kvm_mmu_page *sp;
220994c81364SDavid Matlack 	bool created = false;
221094c81364SDavid Matlack 
22113cc736b3SDavid Matlack 	sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
221294c81364SDavid Matlack 
22133cc736b3SDavid Matlack 	sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
221494c81364SDavid Matlack 	if (!sp) {
221594c81364SDavid Matlack 		created = true;
22163cc736b3SDavid Matlack 		sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
221794c81364SDavid Matlack 	}
221894c81364SDavid Matlack 
221994c81364SDavid Matlack 	trace_kvm_mmu_get_page(sp, created);
2220c50d8ae3SPaolo Bonzini 	return sp;
2221c50d8ae3SPaolo Bonzini }
2222c50d8ae3SPaolo Bonzini 
22232f8b1b53SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
22242f8b1b53SDavid Matlack 						    gfn_t gfn,
22252f8b1b53SDavid Matlack 						    union kvm_mmu_page_role role)
22262f8b1b53SDavid Matlack {
22272f8b1b53SDavid Matlack 	struct shadow_page_caches caches = {
22282f8b1b53SDavid Matlack 		.page_header_cache = &vcpu->arch.mmu_page_header_cache,
22292f8b1b53SDavid Matlack 		.shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
22306a97575dSDavid Matlack 		.shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
22312f8b1b53SDavid Matlack 	};
22322f8b1b53SDavid Matlack 
22333cc736b3SDavid Matlack 	return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
22342f8b1b53SDavid Matlack }
22352f8b1b53SDavid Matlack 
223639944ab9SSean Christopherson static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
223739944ab9SSean Christopherson 						  unsigned int access)
22382e65e842SDavid Matlack {
22392e65e842SDavid Matlack 	struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
22402e65e842SDavid Matlack 	union kvm_mmu_page_role role;
22412e65e842SDavid Matlack 
22422e65e842SDavid Matlack 	role = parent_sp->role;
22432e65e842SDavid Matlack 	role.level--;
22442e65e842SDavid Matlack 	role.access = access;
22452e65e842SDavid Matlack 	role.direct = direct;
22462e65e842SDavid Matlack 	role.passthrough = 0;
22472e65e842SDavid Matlack 
22482e65e842SDavid Matlack 	/*
22492e65e842SDavid Matlack 	 * If the guest has 4-byte PTEs then that means it's using 32-bit,
22502e65e842SDavid Matlack 	 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
22512e65e842SDavid Matlack 	 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
22522e65e842SDavid Matlack 	 * shadow each guest page table with multiple shadow page tables, which
22532e65e842SDavid Matlack 	 * requires extra bookkeeping in the role.
22542e65e842SDavid Matlack 	 *
22552e65e842SDavid Matlack 	 * Specifically, to shadow the guest's page directory (which covers a
22562e65e842SDavid Matlack 	 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
22572e65e842SDavid Matlack 	 * 1GiB of the address space. @role.quadrant encodes which quarter of
22582e65e842SDavid Matlack 	 * the address space each maps.
22592e65e842SDavid Matlack 	 *
22602e65e842SDavid Matlack 	 * To shadow the guest's page tables (which each map a 4MiB region), KVM
22612e65e842SDavid Matlack 	 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
22622e65e842SDavid Matlack 	 * @role.quadrant encodes which half of the region they map.
22632e65e842SDavid Matlack 	 *
226439944ab9SSean Christopherson 	 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
226539944ab9SSean Christopherson 	 * consumes bits 29:21.  To consume bits 31:30, KVM's uses 4 shadow
226639944ab9SSean Christopherson 	 * PDPTEs; those 4 PAE page directories are pre-allocated and their
226739944ab9SSean Christopherson 	 * quadrant is assigned in mmu_alloc_root().   A 4-byte PTE consumes
226839944ab9SSean Christopherson 	 * bits 21:12, while an 8-byte PTE consumes bits 20:12.  To consume
226939944ab9SSean Christopherson 	 * bit 21 in the PTE (the child here), KVM propagates that bit to the
227039944ab9SSean Christopherson 	 * quadrant, i.e. sets quadrant to '0' or '1'.  The parent 8-byte PDE
227139944ab9SSean Christopherson 	 * covers bit 21 (see above), thus the quadrant is calculated from the
227239944ab9SSean Christopherson 	 * _least_ significant bit of the PDE index.
22732e65e842SDavid Matlack 	 */
22742e65e842SDavid Matlack 	if (role.has_4_byte_gpte) {
22752e65e842SDavid Matlack 		WARN_ON_ONCE(role.level != PG_LEVEL_4K);
227679e48cecSSean Christopherson 		role.quadrant = spte_index(sptep) & 1;
22772e65e842SDavid Matlack 	}
22782e65e842SDavid Matlack 
22792e65e842SDavid Matlack 	return role;
22802e65e842SDavid Matlack }
22812e65e842SDavid Matlack 
22822e65e842SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
22832e65e842SDavid Matlack 						 u64 *sptep, gfn_t gfn,
22842e65e842SDavid Matlack 						 bool direct, unsigned int access)
22852e65e842SDavid Matlack {
22862e65e842SDavid Matlack 	union kvm_mmu_page_role role;
22872e65e842SDavid Matlack 
22880cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
22890cd8dc73SPaolo Bonzini 		return ERR_PTR(-EEXIST);
22900cd8dc73SPaolo Bonzini 
22912e65e842SDavid Matlack 	role = kvm_mmu_child_role(sptep, direct, access);
229287654643SDavid Matlack 	return kvm_mmu_get_shadow_page(vcpu, gfn, role);
22932e65e842SDavid Matlack }
22942e65e842SDavid Matlack 
2295c50d8ae3SPaolo Bonzini static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2296c50d8ae3SPaolo Bonzini 					struct kvm_vcpu *vcpu, hpa_t root,
2297c50d8ae3SPaolo Bonzini 					u64 addr)
2298c50d8ae3SPaolo Bonzini {
2299c50d8ae3SPaolo Bonzini 	iterator->addr = addr;
2300c50d8ae3SPaolo Bonzini 	iterator->shadow_addr = root;
2301a972e29cSPaolo Bonzini 	iterator->level = vcpu->arch.mmu->root_role.level;
2302c50d8ae3SPaolo Bonzini 
230312ec33a7SLai Jiangshan 	if (iterator->level >= PT64_ROOT_4LEVEL &&
23044d25502aSPaolo Bonzini 	    vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2305347a0d0dSPaolo Bonzini 	    !vcpu->arch.mmu->root_role.direct)
230612ec33a7SLai Jiangshan 		iterator->level = PT32E_ROOT_LEVEL;
2307c50d8ae3SPaolo Bonzini 
2308c50d8ae3SPaolo Bonzini 	if (iterator->level == PT32E_ROOT_LEVEL) {
2309c50d8ae3SPaolo Bonzini 		/*
2310c50d8ae3SPaolo Bonzini 		 * prev_root is currently only used for 64-bit hosts. So only
2311c50d8ae3SPaolo Bonzini 		 * the active root_hpa is valid here.
2312c50d8ae3SPaolo Bonzini 		 */
2313b9e5603cSPaolo Bonzini 		BUG_ON(root != vcpu->arch.mmu->root.hpa);
2314c50d8ae3SPaolo Bonzini 
2315c50d8ae3SPaolo Bonzini 		iterator->shadow_addr
2316c50d8ae3SPaolo Bonzini 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
23172ca3129eSSean Christopherson 		iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2318c50d8ae3SPaolo Bonzini 		--iterator->level;
2319c50d8ae3SPaolo Bonzini 		if (!iterator->shadow_addr)
2320c50d8ae3SPaolo Bonzini 			iterator->level = 0;
2321c50d8ae3SPaolo Bonzini 	}
2322c50d8ae3SPaolo Bonzini }
2323c50d8ae3SPaolo Bonzini 
2324c50d8ae3SPaolo Bonzini static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2325c50d8ae3SPaolo Bonzini 			     struct kvm_vcpu *vcpu, u64 addr)
2326c50d8ae3SPaolo Bonzini {
2327b9e5603cSPaolo Bonzini 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2328c50d8ae3SPaolo Bonzini 				    addr);
2329c50d8ae3SPaolo Bonzini }
2330c50d8ae3SPaolo Bonzini 
2331c50d8ae3SPaolo Bonzini static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2332c50d8ae3SPaolo Bonzini {
23333bae0459SSean Christopherson 	if (iterator->level < PG_LEVEL_4K)
2334c50d8ae3SPaolo Bonzini 		return false;
2335c50d8ae3SPaolo Bonzini 
23362ca3129eSSean Christopherson 	iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2337c50d8ae3SPaolo Bonzini 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2338c50d8ae3SPaolo Bonzini 	return true;
2339c50d8ae3SPaolo Bonzini }
2340c50d8ae3SPaolo Bonzini 
2341c50d8ae3SPaolo Bonzini static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2342c50d8ae3SPaolo Bonzini 			       u64 spte)
2343c50d8ae3SPaolo Bonzini {
23443e44dce4SLai Jiangshan 	if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2345c50d8ae3SPaolo Bonzini 		iterator->level = 0;
2346c50d8ae3SPaolo Bonzini 		return;
2347c50d8ae3SPaolo Bonzini 	}
2348c50d8ae3SPaolo Bonzini 
23492ca3129eSSean Christopherson 	iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2350c50d8ae3SPaolo Bonzini 	--iterator->level;
2351c50d8ae3SPaolo Bonzini }
2352c50d8ae3SPaolo Bonzini 
2353c50d8ae3SPaolo Bonzini static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2354c50d8ae3SPaolo Bonzini {
2355c50d8ae3SPaolo Bonzini 	__shadow_walk_next(iterator, *iterator->sptep);
2356c50d8ae3SPaolo Bonzini }
2357c50d8ae3SPaolo Bonzini 
23580cd8dc73SPaolo Bonzini static void __link_shadow_page(struct kvm *kvm,
23590cd8dc73SPaolo Bonzini 			       struct kvm_mmu_memory_cache *cache, u64 *sptep,
236003787394SPaolo Bonzini 			       struct kvm_mmu_page *sp, bool flush)
2361c50d8ae3SPaolo Bonzini {
2362c50d8ae3SPaolo Bonzini 	u64 spte;
2363c50d8ae3SPaolo Bonzini 
2364c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2365c50d8ae3SPaolo Bonzini 
23660cd8dc73SPaolo Bonzini 	/*
23670cd8dc73SPaolo Bonzini 	 * If an SPTE is present already, it must be a leaf and therefore
236803787394SPaolo Bonzini 	 * a large one.  Drop it, and flush the TLB if needed, before
236903787394SPaolo Bonzini 	 * installing sp.
23700cd8dc73SPaolo Bonzini 	 */
23710cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep))
237203787394SPaolo Bonzini 		drop_large_spte(kvm, sptep, flush);
23730cd8dc73SPaolo Bonzini 
2374cc4674d0SBen Gardon 	spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2375c50d8ae3SPaolo Bonzini 
2376c50d8ae3SPaolo Bonzini 	mmu_spte_set(sptep, spte);
2377c50d8ae3SPaolo Bonzini 
23782ff9039aSDavid Matlack 	mmu_page_add_parent_pte(cache, sp, sptep);
2379c50d8ae3SPaolo Bonzini 
2380c4a48868SLai Jiangshan 	/*
2381c4a48868SLai Jiangshan 	 * The non-direct sub-pagetable must be updated before linking.  For
2382c4a48868SLai Jiangshan 	 * L1 sp, the pagetable is updated via kvm_sync_page() in
2383c4a48868SLai Jiangshan 	 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2384c4a48868SLai Jiangshan 	 * so sp->unsync can be true or false.  For higher level non-direct
2385c4a48868SLai Jiangshan 	 * sp, the pagetable is updated/synced via mmu_sync_children() in
2386c4a48868SLai Jiangshan 	 * FNAME(fetch)(), so sp->unsync_children can only be false.
2387c4a48868SLai Jiangshan 	 * WARN_ON_ONCE() if anything happens unexpectedly.
2388c4a48868SLai Jiangshan 	 */
2389c4a48868SLai Jiangshan 	if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2390c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
2391c50d8ae3SPaolo Bonzini }
2392c50d8ae3SPaolo Bonzini 
23932ff9039aSDavid Matlack static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
23942ff9039aSDavid Matlack 			     struct kvm_mmu_page *sp)
23952ff9039aSDavid Matlack {
239603787394SPaolo Bonzini 	__link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
23972ff9039aSDavid Matlack }
23982ff9039aSDavid Matlack 
2399c50d8ae3SPaolo Bonzini static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2400c50d8ae3SPaolo Bonzini 				   unsigned direct_access)
2401c50d8ae3SPaolo Bonzini {
2402c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2403c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
2404c50d8ae3SPaolo Bonzini 
2405c50d8ae3SPaolo Bonzini 		/*
2406c50d8ae3SPaolo Bonzini 		 * For the direct sp, if the guest pte's dirty bit
2407c50d8ae3SPaolo Bonzini 		 * changed form clean to dirty, it will corrupt the
2408c50d8ae3SPaolo Bonzini 		 * sp's access: allow writable in the read-only sp,
2409c50d8ae3SPaolo Bonzini 		 * so we should update the spte at this point to get
2410c50d8ae3SPaolo Bonzini 		 * a new sp with the correct access.
2411c50d8ae3SPaolo Bonzini 		 */
24125e3edd7eSSean Christopherson 		child = spte_to_child_sp(*sptep);
2413c50d8ae3SPaolo Bonzini 		if (child->role.access == direct_access)
2414c50d8ae3SPaolo Bonzini 			return;
2415c50d8ae3SPaolo Bonzini 
2416c50d8ae3SPaolo Bonzini 		drop_parent_pte(child, sptep);
2417*3cdf9374SHou Wenlong 		kvm_flush_remote_tlbs_sptep(vcpu->kvm, sptep);
2418c50d8ae3SPaolo Bonzini 	}
2419c50d8ae3SPaolo Bonzini }
2420c50d8ae3SPaolo Bonzini 
24212de4085cSBen Gardon /* Returns the number of zapped non-leaf child shadow pages. */
24222de4085cSBen Gardon static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
24232de4085cSBen Gardon 			    u64 *spte, struct list_head *invalid_list)
2424c50d8ae3SPaolo Bonzini {
2425c50d8ae3SPaolo Bonzini 	u64 pte;
2426c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *child;
2427c50d8ae3SPaolo Bonzini 
2428c50d8ae3SPaolo Bonzini 	pte = *spte;
2429c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(pte)) {
2430c50d8ae3SPaolo Bonzini 		if (is_last_spte(pte, sp->role.level)) {
2431c50d8ae3SPaolo Bonzini 			drop_spte(kvm, spte);
2432c50d8ae3SPaolo Bonzini 		} else {
24335e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2434c50d8ae3SPaolo Bonzini 			drop_parent_pte(child, spte);
24352de4085cSBen Gardon 
24362de4085cSBen Gardon 			/*
24372de4085cSBen Gardon 			 * Recursively zap nested TDP SPs, parentless SPs are
24382de4085cSBen Gardon 			 * unlikely to be used again in the near future.  This
24392de4085cSBen Gardon 			 * avoids retaining a large number of stale nested SPs.
24402de4085cSBen Gardon 			 */
24412de4085cSBen Gardon 			if (tdp_enabled && invalid_list &&
24422de4085cSBen Gardon 			    child->role.guest_mode && !child->parent_ptes.val)
24432de4085cSBen Gardon 				return kvm_mmu_prepare_zap_page(kvm, child,
24442de4085cSBen Gardon 								invalid_list);
2445c50d8ae3SPaolo Bonzini 		}
2446ace569e0SSean Christopherson 	} else if (is_mmio_spte(pte)) {
2447c50d8ae3SPaolo Bonzini 		mmu_spte_clear_no_track(spte);
2448ace569e0SSean Christopherson 	}
24492de4085cSBen Gardon 	return 0;
2450c50d8ae3SPaolo Bonzini }
2451c50d8ae3SPaolo Bonzini 
24522de4085cSBen Gardon static int kvm_mmu_page_unlink_children(struct kvm *kvm,
24532de4085cSBen Gardon 					struct kvm_mmu_page *sp,
24542de4085cSBen Gardon 					struct list_head *invalid_list)
2455c50d8ae3SPaolo Bonzini {
24562de4085cSBen Gardon 	int zapped = 0;
2457c50d8ae3SPaolo Bonzini 	unsigned i;
2458c50d8ae3SPaolo Bonzini 
24592ca3129eSSean Christopherson 	for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
24602de4085cSBen Gardon 		zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
24612de4085cSBen Gardon 
24622de4085cSBen Gardon 	return zapped;
2463c50d8ae3SPaolo Bonzini }
2464c50d8ae3SPaolo Bonzini 
246561827671SJinrong Liang static void kvm_mmu_unlink_parents(struct kvm_mmu_page *sp)
2466c50d8ae3SPaolo Bonzini {
2467c50d8ae3SPaolo Bonzini 	u64 *sptep;
2468c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
2469c50d8ae3SPaolo Bonzini 
2470c50d8ae3SPaolo Bonzini 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2471c50d8ae3SPaolo Bonzini 		drop_parent_pte(sp, sptep);
2472c50d8ae3SPaolo Bonzini }
2473c50d8ae3SPaolo Bonzini 
2474c50d8ae3SPaolo Bonzini static int mmu_zap_unsync_children(struct kvm *kvm,
2475c50d8ae3SPaolo Bonzini 				   struct kvm_mmu_page *parent,
2476c50d8ae3SPaolo Bonzini 				   struct list_head *invalid_list)
2477c50d8ae3SPaolo Bonzini {
2478c50d8ae3SPaolo Bonzini 	int i, zapped = 0;
2479c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2480c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2481c50d8ae3SPaolo Bonzini 
24823bae0459SSean Christopherson 	if (parent->role.level == PG_LEVEL_4K)
2483c50d8ae3SPaolo Bonzini 		return 0;
2484c50d8ae3SPaolo Bonzini 
2485c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2486c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
2487c50d8ae3SPaolo Bonzini 
2488c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2489c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2490c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2491c50d8ae3SPaolo Bonzini 			zapped++;
2492c50d8ae3SPaolo Bonzini 		}
2493c50d8ae3SPaolo Bonzini 	}
2494c50d8ae3SPaolo Bonzini 
2495c50d8ae3SPaolo Bonzini 	return zapped;
2496c50d8ae3SPaolo Bonzini }
2497c50d8ae3SPaolo Bonzini 
2498c50d8ae3SPaolo Bonzini static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2499c50d8ae3SPaolo Bonzini 				       struct kvm_mmu_page *sp,
2500c50d8ae3SPaolo Bonzini 				       struct list_head *invalid_list,
2501c50d8ae3SPaolo Bonzini 				       int *nr_zapped)
2502c50d8ae3SPaolo Bonzini {
2503527d5cd7SSean Christopherson 	bool list_unstable, zapped_root = false;
2504c50d8ae3SPaolo Bonzini 
250547b0c2e4SKazuki Takiguchi 	lockdep_assert_held_write(&kvm->mmu_lock);
2506c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_prepare_zap_page(sp);
2507c50d8ae3SPaolo Bonzini 	++kvm->stat.mmu_shadow_zapped;
2508c50d8ae3SPaolo Bonzini 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
25092de4085cSBen Gardon 	*nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
251061827671SJinrong Liang 	kvm_mmu_unlink_parents(sp);
2511c50d8ae3SPaolo Bonzini 
2512c50d8ae3SPaolo Bonzini 	/* Zapping children means active_mmu_pages has become unstable. */
2513c50d8ae3SPaolo Bonzini 	list_unstable = *nr_zapped;
2514c50d8ae3SPaolo Bonzini 
2515767d8d8dSLai Jiangshan 	if (!sp->role.invalid && sp_has_gptes(sp))
2516c50d8ae3SPaolo Bonzini 		unaccount_shadowed(kvm, sp);
2517c50d8ae3SPaolo Bonzini 
2518c50d8ae3SPaolo Bonzini 	if (sp->unsync)
2519c50d8ae3SPaolo Bonzini 		kvm_unlink_unsync_page(kvm, sp);
2520c50d8ae3SPaolo Bonzini 	if (!sp->root_count) {
2521c50d8ae3SPaolo Bonzini 		/* Count self */
2522c50d8ae3SPaolo Bonzini 		(*nr_zapped)++;
2523f95eec9bSSean Christopherson 
2524f95eec9bSSean Christopherson 		/*
2525f95eec9bSSean Christopherson 		 * Already invalid pages (previously active roots) are not on
2526f95eec9bSSean Christopherson 		 * the active page list.  See list_del() in the "else" case of
2527f95eec9bSSean Christopherson 		 * !sp->root_count.
2528f95eec9bSSean Christopherson 		 */
2529f95eec9bSSean Christopherson 		if (sp->role.invalid)
2530f95eec9bSSean Christopherson 			list_add(&sp->link, invalid_list);
2531f95eec9bSSean Christopherson 		else
2532c50d8ae3SPaolo Bonzini 			list_move(&sp->link, invalid_list);
253343a063caSYosry Ahmed 		kvm_unaccount_mmu_page(kvm, sp);
2534c50d8ae3SPaolo Bonzini 	} else {
2535f95eec9bSSean Christopherson 		/*
2536f95eec9bSSean Christopherson 		 * Remove the active root from the active page list, the root
2537f95eec9bSSean Christopherson 		 * will be explicitly freed when the root_count hits zero.
2538f95eec9bSSean Christopherson 		 */
2539f95eec9bSSean Christopherson 		list_del(&sp->link);
2540c50d8ae3SPaolo Bonzini 
2541c50d8ae3SPaolo Bonzini 		/*
2542c50d8ae3SPaolo Bonzini 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2543c50d8ae3SPaolo Bonzini 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2544c50d8ae3SPaolo Bonzini 		 * treats invalid shadow pages as being obsolete.
2545c50d8ae3SPaolo Bonzini 		 */
2546527d5cd7SSean Christopherson 		zapped_root = !is_obsolete_sp(kvm, sp);
2547c50d8ae3SPaolo Bonzini 	}
2548c50d8ae3SPaolo Bonzini 
254955c510e2SSean Christopherson 	if (sp->nx_huge_page_disallowed)
255055c510e2SSean Christopherson 		unaccount_nx_huge_page(kvm, sp);
2551c50d8ae3SPaolo Bonzini 
2552c50d8ae3SPaolo Bonzini 	sp->role.invalid = 1;
2553527d5cd7SSean Christopherson 
2554527d5cd7SSean Christopherson 	/*
2555527d5cd7SSean Christopherson 	 * Make the request to free obsolete roots after marking the root
2556527d5cd7SSean Christopherson 	 * invalid, otherwise other vCPUs may not see it as invalid.
2557527d5cd7SSean Christopherson 	 */
2558527d5cd7SSean Christopherson 	if (zapped_root)
2559527d5cd7SSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2560c50d8ae3SPaolo Bonzini 	return list_unstable;
2561c50d8ae3SPaolo Bonzini }
2562c50d8ae3SPaolo Bonzini 
2563c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2564c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list)
2565c50d8ae3SPaolo Bonzini {
2566c50d8ae3SPaolo Bonzini 	int nr_zapped;
2567c50d8ae3SPaolo Bonzini 
2568c50d8ae3SPaolo Bonzini 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2569c50d8ae3SPaolo Bonzini 	return nr_zapped;
2570c50d8ae3SPaolo Bonzini }
2571c50d8ae3SPaolo Bonzini 
2572c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2573c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list)
2574c50d8ae3SPaolo Bonzini {
2575c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *nsp;
2576c50d8ae3SPaolo Bonzini 
2577c50d8ae3SPaolo Bonzini 	if (list_empty(invalid_list))
2578c50d8ae3SPaolo Bonzini 		return;
2579c50d8ae3SPaolo Bonzini 
2580c50d8ae3SPaolo Bonzini 	/*
2581c50d8ae3SPaolo Bonzini 	 * We need to make sure everyone sees our modifications to
2582c50d8ae3SPaolo Bonzini 	 * the page tables and see changes to vcpu->mode here. The barrier
2583c50d8ae3SPaolo Bonzini 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2584c50d8ae3SPaolo Bonzini 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2585c50d8ae3SPaolo Bonzini 	 *
2586c50d8ae3SPaolo Bonzini 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2587c50d8ae3SPaolo Bonzini 	 * guest mode and/or lockless shadow page table walks.
2588c50d8ae3SPaolo Bonzini 	 */
2589c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs(kvm);
2590c50d8ae3SPaolo Bonzini 
2591c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2592c50d8ae3SPaolo Bonzini 		WARN_ON(!sp->role.invalid || sp->root_count);
259387654643SDavid Matlack 		kvm_mmu_free_shadow_page(sp);
2594c50d8ae3SPaolo Bonzini 	}
2595c50d8ae3SPaolo Bonzini }
2596c50d8ae3SPaolo Bonzini 
25976b82ef2cSSean Christopherson static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
25986b82ef2cSSean Christopherson 						  unsigned long nr_to_zap)
2599c50d8ae3SPaolo Bonzini {
26006b82ef2cSSean Christopherson 	unsigned long total_zapped = 0;
26016b82ef2cSSean Christopherson 	struct kvm_mmu_page *sp, *tmp;
2602ba7888ddSSean Christopherson 	LIST_HEAD(invalid_list);
26036b82ef2cSSean Christopherson 	bool unstable;
26046b82ef2cSSean Christopherson 	int nr_zapped;
2605c50d8ae3SPaolo Bonzini 
2606c50d8ae3SPaolo Bonzini 	if (list_empty(&kvm->arch.active_mmu_pages))
2607ba7888ddSSean Christopherson 		return 0;
2608c50d8ae3SPaolo Bonzini 
26096b82ef2cSSean Christopherson restart:
26108fc51726SSean Christopherson 	list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
26116b82ef2cSSean Christopherson 		/*
26126b82ef2cSSean Christopherson 		 * Don't zap active root pages, the page itself can't be freed
26136b82ef2cSSean Christopherson 		 * and zapping it will just force vCPUs to realloc and reload.
26146b82ef2cSSean Christopherson 		 */
26156b82ef2cSSean Christopherson 		if (sp->root_count)
26166b82ef2cSSean Christopherson 			continue;
26176b82ef2cSSean Christopherson 
26186b82ef2cSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
26196b82ef2cSSean Christopherson 						      &nr_zapped);
26206b82ef2cSSean Christopherson 		total_zapped += nr_zapped;
26216b82ef2cSSean Christopherson 		if (total_zapped >= nr_to_zap)
2622ba7888ddSSean Christopherson 			break;
2623ba7888ddSSean Christopherson 
26246b82ef2cSSean Christopherson 		if (unstable)
26256b82ef2cSSean Christopherson 			goto restart;
2626ba7888ddSSean Christopherson 	}
26276b82ef2cSSean Christopherson 
26286b82ef2cSSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
26296b82ef2cSSean Christopherson 
26306b82ef2cSSean Christopherson 	kvm->stat.mmu_recycled += total_zapped;
26316b82ef2cSSean Christopherson 	return total_zapped;
26326b82ef2cSSean Christopherson }
26336b82ef2cSSean Christopherson 
2634afe8d7e6SSean Christopherson static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2635afe8d7e6SSean Christopherson {
2636afe8d7e6SSean Christopherson 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2637afe8d7e6SSean Christopherson 		return kvm->arch.n_max_mmu_pages -
2638afe8d7e6SSean Christopherson 			kvm->arch.n_used_mmu_pages;
2639afe8d7e6SSean Christopherson 
2640afe8d7e6SSean Christopherson 	return 0;
2641c50d8ae3SPaolo Bonzini }
2642c50d8ae3SPaolo Bonzini 
2643ba7888ddSSean Christopherson static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2644ba7888ddSSean Christopherson {
26456b82ef2cSSean Christopherson 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2646ba7888ddSSean Christopherson 
26476b82ef2cSSean Christopherson 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2648ba7888ddSSean Christopherson 		return 0;
2649ba7888ddSSean Christopherson 
26506b82ef2cSSean Christopherson 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2651ba7888ddSSean Christopherson 
26526e6ec584SSean Christopherson 	/*
26536e6ec584SSean Christopherson 	 * Note, this check is intentionally soft, it only guarantees that one
26546e6ec584SSean Christopherson 	 * page is available, while the caller may end up allocating as many as
26556e6ec584SSean Christopherson 	 * four pages, e.g. for PAE roots or for 5-level paging.  Temporarily
26566e6ec584SSean Christopherson 	 * exceeding the (arbitrary by default) limit will not harm the host,
2657c4342633SIngo Molnar 	 * being too aggressive may unnecessarily kill the guest, and getting an
26586e6ec584SSean Christopherson 	 * exact count is far more trouble than it's worth, especially in the
26596e6ec584SSean Christopherson 	 * page fault paths.
26606e6ec584SSean Christopherson 	 */
2661ba7888ddSSean Christopherson 	if (!kvm_mmu_available_pages(vcpu->kvm))
2662ba7888ddSSean Christopherson 		return -ENOSPC;
2663ba7888ddSSean Christopherson 	return 0;
2664ba7888ddSSean Christopherson }
2665ba7888ddSSean Christopherson 
2666c50d8ae3SPaolo Bonzini /*
2667c50d8ae3SPaolo Bonzini  * Changing the number of mmu pages allocated to the vm
2668c50d8ae3SPaolo Bonzini  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2669c50d8ae3SPaolo Bonzini  */
2670c50d8ae3SPaolo Bonzini void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2671c50d8ae3SPaolo Bonzini {
2672531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2673c50d8ae3SPaolo Bonzini 
2674c50d8ae3SPaolo Bonzini 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
26756b82ef2cSSean Christopherson 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
26766b82ef2cSSean Christopherson 						  goal_nr_mmu_pages);
2677c50d8ae3SPaolo Bonzini 
2678c50d8ae3SPaolo Bonzini 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2679c50d8ae3SPaolo Bonzini 	}
2680c50d8ae3SPaolo Bonzini 
2681c50d8ae3SPaolo Bonzini 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2682c50d8ae3SPaolo Bonzini 
2683531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2684c50d8ae3SPaolo Bonzini }
2685c50d8ae3SPaolo Bonzini 
2686c50d8ae3SPaolo Bonzini int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2687c50d8ae3SPaolo Bonzini {
2688c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2689c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2690c50d8ae3SPaolo Bonzini 	int r;
2691c50d8ae3SPaolo Bonzini 
2692c50d8ae3SPaolo Bonzini 	pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2693c50d8ae3SPaolo Bonzini 	r = 0;
2694531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2695767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2696c50d8ae3SPaolo Bonzini 		pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2697c50d8ae3SPaolo Bonzini 			 sp->role.word);
2698c50d8ae3SPaolo Bonzini 		r = 1;
2699c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2700c50d8ae3SPaolo Bonzini 	}
2701c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2702531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2703c50d8ae3SPaolo Bonzini 
2704c50d8ae3SPaolo Bonzini 	return r;
2705c50d8ae3SPaolo Bonzini }
270696ad91aeSSean Christopherson 
270796ad91aeSSean Christopherson static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
270896ad91aeSSean Christopherson {
270996ad91aeSSean Christopherson 	gpa_t gpa;
271096ad91aeSSean Christopherson 	int r;
271196ad91aeSSean Christopherson 
2712347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
271396ad91aeSSean Christopherson 		return 0;
271496ad91aeSSean Christopherson 
271596ad91aeSSean Christopherson 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
271696ad91aeSSean Christopherson 
271796ad91aeSSean Christopherson 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
271896ad91aeSSean Christopherson 
271996ad91aeSSean Christopherson 	return r;
272096ad91aeSSean Christopherson }
2721c50d8ae3SPaolo Bonzini 
27224d78d0b3SBen Gardon static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2723c50d8ae3SPaolo Bonzini {
2724c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_unsync_page(sp);
27254d78d0b3SBen Gardon 	++kvm->stat.mmu_unsync;
2726c50d8ae3SPaolo Bonzini 	sp->unsync = 1;
2727c50d8ae3SPaolo Bonzini 
2728c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
2729c50d8ae3SPaolo Bonzini }
2730c50d8ae3SPaolo Bonzini 
27310337f585SSean Christopherson /*
27320337f585SSean Christopherson  * Attempt to unsync any shadow pages that can be reached by the specified gfn,
27330337f585SSean Christopherson  * KVM is creating a writable mapping for said gfn.  Returns 0 if all pages
27340337f585SSean Christopherson  * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
27350337f585SSean Christopherson  * be write-protected.
27360337f585SSean Christopherson  */
27378283e36aSBen Gardon int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
27382839180cSPaolo Bonzini 			    gfn_t gfn, bool can_unsync, bool prefetch)
2739c50d8ae3SPaolo Bonzini {
2740c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2741ce25681dSSean Christopherson 	bool locked = false;
2742c50d8ae3SPaolo Bonzini 
27430337f585SSean Christopherson 	/*
27440337f585SSean Christopherson 	 * Force write-protection if the page is being tracked.  Note, the page
27450337f585SSean Christopherson 	 * track machinery is used to write-protect upper-level shadow pages,
27460337f585SSean Christopherson 	 * i.e. this guards the role.level == 4K assertion below!
27470337f585SSean Christopherson 	 */
27484d78d0b3SBen Gardon 	if (kvm_slot_page_track_is_active(kvm, slot, gfn, KVM_PAGE_TRACK_WRITE))
27490337f585SSean Christopherson 		return -EPERM;
2750c50d8ae3SPaolo Bonzini 
27510337f585SSean Christopherson 	/*
27520337f585SSean Christopherson 	 * The page is not write-tracked, mark existing shadow pages unsync
27530337f585SSean Christopherson 	 * unless KVM is synchronizing an unsync SP (can_unsync = false).  In
27540337f585SSean Christopherson 	 * that case, KVM must complete emulation of the guest TLB flush before
27550337f585SSean Christopherson 	 * allowing shadow pages to become unsync (writable by the guest).
27560337f585SSean Christopherson 	 */
2757767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2758c50d8ae3SPaolo Bonzini 		if (!can_unsync)
27590337f585SSean Christopherson 			return -EPERM;
2760c50d8ae3SPaolo Bonzini 
2761c50d8ae3SPaolo Bonzini 		if (sp->unsync)
2762c50d8ae3SPaolo Bonzini 			continue;
2763c50d8ae3SPaolo Bonzini 
27642839180cSPaolo Bonzini 		if (prefetch)
2765f1c4a88cSLai Jiangshan 			return -EEXIST;
2766f1c4a88cSLai Jiangshan 
2767ce25681dSSean Christopherson 		/*
2768ce25681dSSean Christopherson 		 * TDP MMU page faults require an additional spinlock as they
2769ce25681dSSean Christopherson 		 * run with mmu_lock held for read, not write, and the unsync
2770ce25681dSSean Christopherson 		 * logic is not thread safe.  Take the spinklock regardless of
2771ce25681dSSean Christopherson 		 * the MMU type to avoid extra conditionals/parameters, there's
2772ce25681dSSean Christopherson 		 * no meaningful penalty if mmu_lock is held for write.
2773ce25681dSSean Christopherson 		 */
2774ce25681dSSean Christopherson 		if (!locked) {
2775ce25681dSSean Christopherson 			locked = true;
27764d78d0b3SBen Gardon 			spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2777ce25681dSSean Christopherson 
2778ce25681dSSean Christopherson 			/*
2779ce25681dSSean Christopherson 			 * Recheck after taking the spinlock, a different vCPU
2780ce25681dSSean Christopherson 			 * may have since marked the page unsync.  A false
2781ce25681dSSean Christopherson 			 * positive on the unprotected check above is not
2782ce25681dSSean Christopherson 			 * possible as clearing sp->unsync _must_ hold mmu_lock
2783ce25681dSSean Christopherson 			 * for write, i.e. unsync cannot transition from 0->1
2784ce25681dSSean Christopherson 			 * while this CPU holds mmu_lock for read (or write).
2785ce25681dSSean Christopherson 			 */
2786ce25681dSSean Christopherson 			if (READ_ONCE(sp->unsync))
2787ce25681dSSean Christopherson 				continue;
2788ce25681dSSean Christopherson 		}
2789ce25681dSSean Christopherson 
27903bae0459SSean Christopherson 		WARN_ON(sp->role.level != PG_LEVEL_4K);
27914d78d0b3SBen Gardon 		kvm_unsync_page(kvm, sp);
2792c50d8ae3SPaolo Bonzini 	}
2793ce25681dSSean Christopherson 	if (locked)
27944d78d0b3SBen Gardon 		spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2795c50d8ae3SPaolo Bonzini 
2796c50d8ae3SPaolo Bonzini 	/*
2797c50d8ae3SPaolo Bonzini 	 * We need to ensure that the marking of unsync pages is visible
2798c50d8ae3SPaolo Bonzini 	 * before the SPTE is updated to allow writes because
2799c50d8ae3SPaolo Bonzini 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2800c50d8ae3SPaolo Bonzini 	 * the MMU lock and so can race with this. If the SPTE was updated
2801c50d8ae3SPaolo Bonzini 	 * before the page had been marked as unsync-ed, something like the
2802c50d8ae3SPaolo Bonzini 	 * following could happen:
2803c50d8ae3SPaolo Bonzini 	 *
2804c50d8ae3SPaolo Bonzini 	 * CPU 1                    CPU 2
2805c50d8ae3SPaolo Bonzini 	 * ---------------------------------------------------------------------
2806c50d8ae3SPaolo Bonzini 	 * 1.2 Host updates SPTE
2807c50d8ae3SPaolo Bonzini 	 *     to be writable
2808c50d8ae3SPaolo Bonzini 	 *                      2.1 Guest writes a GPTE for GVA X.
2809c50d8ae3SPaolo Bonzini 	 *                          (GPTE being in the guest page table shadowed
2810c50d8ae3SPaolo Bonzini 	 *                           by the SP from CPU 1.)
2811c50d8ae3SPaolo Bonzini 	 *                          This reads SPTE during the page table walk.
2812c50d8ae3SPaolo Bonzini 	 *                          Since SPTE.W is read as 1, there is no
2813c50d8ae3SPaolo Bonzini 	 *                          fault.
2814c50d8ae3SPaolo Bonzini 	 *
2815c50d8ae3SPaolo Bonzini 	 *                      2.2 Guest issues TLB flush.
2816c50d8ae3SPaolo Bonzini 	 *                          That causes a VM Exit.
2817c50d8ae3SPaolo Bonzini 	 *
28180337f585SSean Christopherson 	 *                      2.3 Walking of unsync pages sees sp->unsync is
28190337f585SSean Christopherson 	 *                          false and skips the page.
2820c50d8ae3SPaolo Bonzini 	 *
2821c50d8ae3SPaolo Bonzini 	 *                      2.4 Guest accesses GVA X.
2822c50d8ae3SPaolo Bonzini 	 *                          Since the mapping in the SP was not updated,
2823c50d8ae3SPaolo Bonzini 	 *                          so the old mapping for GVA X incorrectly
2824c50d8ae3SPaolo Bonzini 	 *                          gets used.
2825c50d8ae3SPaolo Bonzini 	 * 1.1 Host marks SP
2826c50d8ae3SPaolo Bonzini 	 *     as unsync
2827c50d8ae3SPaolo Bonzini 	 *     (sp->unsync = true)
2828c50d8ae3SPaolo Bonzini 	 *
2829c50d8ae3SPaolo Bonzini 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2830264d3dc1SLai Jiangshan 	 * the situation in 2.4 does not arise.  It pairs with the read barrier
2831264d3dc1SLai Jiangshan 	 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2832c50d8ae3SPaolo Bonzini 	 */
2833c50d8ae3SPaolo Bonzini 	smp_wmb();
2834c50d8ae3SPaolo Bonzini 
28350337f585SSean Christopherson 	return 0;
2836c50d8ae3SPaolo Bonzini }
2837c50d8ae3SPaolo Bonzini 
28388a9f566aSDavid Matlack static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
28398a9f566aSDavid Matlack 			u64 *sptep, unsigned int pte_access, gfn_t gfn,
2840a12f4381SPaolo Bonzini 			kvm_pfn_t pfn, struct kvm_page_fault *fault)
2841799a4190SBen Gardon {
2842d786c778SPaolo Bonzini 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2843eb5cd7ffSPaolo Bonzini 	int level = sp->role.level;
2844c50d8ae3SPaolo Bonzini 	int was_rmapped = 0;
2845c4371c2aSSean Christopherson 	int ret = RET_PF_FIXED;
2846c50d8ae3SPaolo Bonzini 	bool flush = false;
2847ad67e480SPaolo Bonzini 	bool wrprot;
2848d786c778SPaolo Bonzini 	u64 spte;
2849c50d8ae3SPaolo Bonzini 
2850a12f4381SPaolo Bonzini 	/* Prefetching always gets a writable pfn.  */
2851a12f4381SPaolo Bonzini 	bool host_writable = !fault || fault->map_writable;
28522839180cSPaolo Bonzini 	bool prefetch = !fault || fault->prefetch;
2853a12f4381SPaolo Bonzini 	bool write_fault = fault && fault->write;
2854c50d8ae3SPaolo Bonzini 
2855c50d8ae3SPaolo Bonzini 	pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2856c50d8ae3SPaolo Bonzini 		 *sptep, write_fault, gfn);
2857c50d8ae3SPaolo Bonzini 
2858a54aa15cSSean Christopherson 	if (unlikely(is_noslot_pfn(pfn))) {
28591075d41eSSean Christopherson 		vcpu->stat.pf_mmio_spte_created++;
2860a54aa15cSSean Christopherson 		mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2861a54aa15cSSean Christopherson 		return RET_PF_EMULATE;
2862a54aa15cSSean Christopherson 	}
2863a54aa15cSSean Christopherson 
2864c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep)) {
2865c50d8ae3SPaolo Bonzini 		/*
2866c50d8ae3SPaolo Bonzini 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2867c50d8ae3SPaolo Bonzini 		 * the parent of the now unreachable PTE.
2868c50d8ae3SPaolo Bonzini 		 */
28693bae0459SSean Christopherson 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2870c50d8ae3SPaolo Bonzini 			struct kvm_mmu_page *child;
2871c50d8ae3SPaolo Bonzini 			u64 pte = *sptep;
2872c50d8ae3SPaolo Bonzini 
28735e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2874c50d8ae3SPaolo Bonzini 			drop_parent_pte(child, sptep);
2875c50d8ae3SPaolo Bonzini 			flush = true;
2876c50d8ae3SPaolo Bonzini 		} else if (pfn != spte_to_pfn(*sptep)) {
2877c50d8ae3SPaolo Bonzini 			pgprintk("hfn old %llx new %llx\n",
2878c50d8ae3SPaolo Bonzini 				 spte_to_pfn(*sptep), pfn);
2879c50d8ae3SPaolo Bonzini 			drop_spte(vcpu->kvm, sptep);
2880c50d8ae3SPaolo Bonzini 			flush = true;
2881c50d8ae3SPaolo Bonzini 		} else
2882c50d8ae3SPaolo Bonzini 			was_rmapped = 1;
2883c50d8ae3SPaolo Bonzini 	}
2884c50d8ae3SPaolo Bonzini 
28852839180cSPaolo Bonzini 	wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
28867158bee4SPaolo Bonzini 			   true, host_writable, &spte);
2887d786c778SPaolo Bonzini 
2888d786c778SPaolo Bonzini 	if (*sptep == spte) {
2889d786c778SPaolo Bonzini 		ret = RET_PF_SPURIOUS;
2890d786c778SPaolo Bonzini 	} else {
2891d786c778SPaolo Bonzini 		flush |= mmu_spte_update(sptep, spte);
28925959ff4aSMaxim Levitsky 		trace_kvm_mmu_set_spte(level, gfn, sptep);
2893c50d8ae3SPaolo Bonzini 	}
2894c50d8ae3SPaolo Bonzini 
2895ad67e480SPaolo Bonzini 	if (wrprot) {
2896c50d8ae3SPaolo Bonzini 		if (write_fault)
2897c50d8ae3SPaolo Bonzini 			ret = RET_PF_EMULATE;
2898c50d8ae3SPaolo Bonzini 	}
2899c50d8ae3SPaolo Bonzini 
2900d786c778SPaolo Bonzini 	if (flush)
2901c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
2902c50d8ae3SPaolo Bonzini 				KVM_PAGES_PER_HPAGE(level));
2903c50d8ae3SPaolo Bonzini 
2904c50d8ae3SPaolo Bonzini 	pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2905c50d8ae3SPaolo Bonzini 
2906c50d8ae3SPaolo Bonzini 	if (!was_rmapped) {
2907d786c778SPaolo Bonzini 		WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
29086a97575dSDavid Matlack 		rmap_add(vcpu, slot, sptep, gfn, pte_access);
29096a97575dSDavid Matlack 	} else {
29106a97575dSDavid Matlack 		/* Already rmapped but the pte_access bits may have changed. */
291179e48cecSSean Christopherson 		kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
2912c50d8ae3SPaolo Bonzini 	}
2913c50d8ae3SPaolo Bonzini 
2914c50d8ae3SPaolo Bonzini 	return ret;
2915c50d8ae3SPaolo Bonzini }
2916c50d8ae3SPaolo Bonzini 
2917c50d8ae3SPaolo Bonzini static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2918c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp,
2919c50d8ae3SPaolo Bonzini 				    u64 *start, u64 *end)
2920c50d8ae3SPaolo Bonzini {
2921c50d8ae3SPaolo Bonzini 	struct page *pages[PTE_PREFETCH_NUM];
2922c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
29230a2b64c5SBen Gardon 	unsigned int access = sp->role.access;
2924c50d8ae3SPaolo Bonzini 	int i, ret;
2925c50d8ae3SPaolo Bonzini 	gfn_t gfn;
2926c50d8ae3SPaolo Bonzini 
292779e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
2928c50d8ae3SPaolo Bonzini 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2929c50d8ae3SPaolo Bonzini 	if (!slot)
2930c50d8ae3SPaolo Bonzini 		return -1;
2931c50d8ae3SPaolo Bonzini 
2932c50d8ae3SPaolo Bonzini 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2933c50d8ae3SPaolo Bonzini 	if (ret <= 0)
2934c50d8ae3SPaolo Bonzini 		return -1;
2935c50d8ae3SPaolo Bonzini 
2936c50d8ae3SPaolo Bonzini 	for (i = 0; i < ret; i++, gfn++, start++) {
29378a9f566aSDavid Matlack 		mmu_set_spte(vcpu, slot, start, access, gfn,
2938a12f4381SPaolo Bonzini 			     page_to_pfn(pages[i]), NULL);
2939c50d8ae3SPaolo Bonzini 		put_page(pages[i]);
2940c50d8ae3SPaolo Bonzini 	}
2941c50d8ae3SPaolo Bonzini 
2942c50d8ae3SPaolo Bonzini 	return 0;
2943c50d8ae3SPaolo Bonzini }
2944c50d8ae3SPaolo Bonzini 
2945c50d8ae3SPaolo Bonzini static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2946c50d8ae3SPaolo Bonzini 				  struct kvm_mmu_page *sp, u64 *sptep)
2947c50d8ae3SPaolo Bonzini {
2948c50d8ae3SPaolo Bonzini 	u64 *spte, *start = NULL;
2949c50d8ae3SPaolo Bonzini 	int i;
2950c50d8ae3SPaolo Bonzini 
2951c50d8ae3SPaolo Bonzini 	WARN_ON(!sp->role.direct);
2952c50d8ae3SPaolo Bonzini 
295379e48cecSSean Christopherson 	i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
2954c50d8ae3SPaolo Bonzini 	spte = sp->spt + i;
2955c50d8ae3SPaolo Bonzini 
2956c50d8ae3SPaolo Bonzini 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
2957c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*spte) || spte == sptep) {
2958c50d8ae3SPaolo Bonzini 			if (!start)
2959c50d8ae3SPaolo Bonzini 				continue;
2960c50d8ae3SPaolo Bonzini 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2961c6cecc4bSSean Christopherson 				return;
2962c50d8ae3SPaolo Bonzini 			start = NULL;
2963c50d8ae3SPaolo Bonzini 		} else if (!start)
2964c50d8ae3SPaolo Bonzini 			start = spte;
2965c50d8ae3SPaolo Bonzini 	}
2966c6cecc4bSSean Christopherson 	if (start)
2967c6cecc4bSSean Christopherson 		direct_pte_prefetch_many(vcpu, sp, start, spte);
2968c50d8ae3SPaolo Bonzini }
2969c50d8ae3SPaolo Bonzini 
2970c50d8ae3SPaolo Bonzini static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2971c50d8ae3SPaolo Bonzini {
2972c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2973c50d8ae3SPaolo Bonzini 
297457354682SSean Christopherson 	sp = sptep_to_sp(sptep);
2975c50d8ae3SPaolo Bonzini 
2976c50d8ae3SPaolo Bonzini 	/*
2977c50d8ae3SPaolo Bonzini 	 * Without accessed bits, there's no way to distinguish between
2978c50d8ae3SPaolo Bonzini 	 * actually accessed translations and prefetched, so disable pte
2979c50d8ae3SPaolo Bonzini 	 * prefetch if accessed bits aren't available.
2980c50d8ae3SPaolo Bonzini 	 */
2981c50d8ae3SPaolo Bonzini 	if (sp_ad_disabled(sp))
2982c50d8ae3SPaolo Bonzini 		return;
2983c50d8ae3SPaolo Bonzini 
29843bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
2985c50d8ae3SPaolo Bonzini 		return;
2986c50d8ae3SPaolo Bonzini 
29874a42d848SDavid Stevens 	/*
29884a42d848SDavid Stevens 	 * If addresses are being invalidated, skip prefetching to avoid
29894a42d848SDavid Stevens 	 * accidentally prefetching those addresses.
29904a42d848SDavid Stevens 	 */
299120ec3ebdSChao Peng 	if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
29924a42d848SDavid Stevens 		return;
29934a42d848SDavid Stevens 
2994c50d8ae3SPaolo Bonzini 	__direct_pte_prefetch(vcpu, sp, sptep);
2995c50d8ae3SPaolo Bonzini }
2996c50d8ae3SPaolo Bonzini 
299765e3b446SSean Christopherson /*
299865e3b446SSean Christopherson  * Lookup the mapping level for @gfn in the current mm.
299965e3b446SSean Christopherson  *
300065e3b446SSean Christopherson  * WARNING!  Use of host_pfn_mapping_level() requires the caller and the end
300165e3b446SSean Christopherson  * consumer to be tied into KVM's handlers for MMU notifier events!
300265e3b446SSean Christopherson  *
300365e3b446SSean Christopherson  * There are several ways to safely use this helper:
300465e3b446SSean Christopherson  *
300520ec3ebdSChao Peng  * - Check mmu_invalidate_retry_hva() after grabbing the mapping level, before
300665e3b446SSean Christopherson  *   consuming it.  In this case, mmu_lock doesn't need to be held during the
300765e3b446SSean Christopherson  *   lookup, but it does need to be held while checking the MMU notifier.
300865e3b446SSean Christopherson  *
300965e3b446SSean Christopherson  * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
301065e3b446SSean Christopherson  *   event for the hva.  This can be done by explicit checking the MMU notifier
301165e3b446SSean Christopherson  *   or by ensuring that KVM already has a valid mapping that covers the hva.
301265e3b446SSean Christopherson  *
301365e3b446SSean Christopherson  * - Do not use the result to install new mappings, e.g. use the host mapping
301465e3b446SSean Christopherson  *   level only to decide whether or not to zap an entry.  In this case, it's
301565e3b446SSean Christopherson  *   not required to hold mmu_lock (though it's highly likely the caller will
301665e3b446SSean Christopherson  *   want to hold mmu_lock anyways, e.g. to modify SPTEs).
301765e3b446SSean Christopherson  *
301865e3b446SSean Christopherson  * Note!  The lookup can still race with modifications to host page tables, but
301965e3b446SSean Christopherson  * the above "rules" ensure KVM will not _consume_ the result of the walk if a
302065e3b446SSean Christopherson  * race with the primary MMU occurs.
302165e3b446SSean Christopherson  */
3022a8ac499bSSean Christopherson static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
30238ca6f063SBen Gardon 				  const struct kvm_memory_slot *slot)
3024db543216SSean Christopherson {
3025284dc493SSean Christopherson 	int level = PG_LEVEL_4K;
3026db543216SSean Christopherson 	unsigned long hva;
302744187235SMingwei Zhang 	unsigned long flags;
302844187235SMingwei Zhang 	pgd_t pgd;
302944187235SMingwei Zhang 	p4d_t p4d;
303044187235SMingwei Zhang 	pud_t pud;
303144187235SMingwei Zhang 	pmd_t pmd;
3032db543216SSean Christopherson 
30335d49f08cSSean Christopherson 	/*
3034293e306eSSean Christopherson 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3035293e306eSSean Christopherson 	 * is not solely for performance, it's also necessary to avoid the
3036293e306eSSean Christopherson 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
3037293e306eSSean Christopherson 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
3038293e306eSSean Christopherson 	 * page fault steps have already verified the guest isn't writing a
3039293e306eSSean Christopherson 	 * read-only memslot.
3040293e306eSSean Christopherson 	 */
3041db543216SSean Christopherson 	hva = __gfn_to_hva_memslot(slot, gfn);
3042db543216SSean Christopherson 
304344187235SMingwei Zhang 	/*
304465e3b446SSean Christopherson 	 * Disable IRQs to prevent concurrent tear down of host page tables,
304565e3b446SSean Christopherson 	 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
304665e3b446SSean Christopherson 	 * the original page table.
304744187235SMingwei Zhang 	 */
304844187235SMingwei Zhang 	local_irq_save(flags);
3049db543216SSean Christopherson 
305065e3b446SSean Christopherson 	/*
305165e3b446SSean Christopherson 	 * Read each entry once.  As above, a non-leaf entry can be promoted to
305265e3b446SSean Christopherson 	 * a huge page _during_ this walk.  Re-reading the entry could send the
305365e3b446SSean Christopherson 	 * walk into the weeks, e.g. p*d_large() returns false (sees the old
305465e3b446SSean Christopherson 	 * value) and then p*d_offset() walks into the target huge page instead
305565e3b446SSean Christopherson 	 * of the old page table (sees the new value).
305665e3b446SSean Christopherson 	 */
305744187235SMingwei Zhang 	pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
305844187235SMingwei Zhang 	if (pgd_none(pgd))
305944187235SMingwei Zhang 		goto out;
306044187235SMingwei Zhang 
306144187235SMingwei Zhang 	p4d = READ_ONCE(*p4d_offset(&pgd, hva));
306244187235SMingwei Zhang 	if (p4d_none(p4d) || !p4d_present(p4d))
306344187235SMingwei Zhang 		goto out;
306444187235SMingwei Zhang 
306544187235SMingwei Zhang 	pud = READ_ONCE(*pud_offset(&p4d, hva));
306644187235SMingwei Zhang 	if (pud_none(pud) || !pud_present(pud))
306744187235SMingwei Zhang 		goto out;
306844187235SMingwei Zhang 
306944187235SMingwei Zhang 	if (pud_large(pud)) {
307044187235SMingwei Zhang 		level = PG_LEVEL_1G;
307144187235SMingwei Zhang 		goto out;
307244187235SMingwei Zhang 	}
307344187235SMingwei Zhang 
307444187235SMingwei Zhang 	pmd = READ_ONCE(*pmd_offset(&pud, hva));
307544187235SMingwei Zhang 	if (pmd_none(pmd) || !pmd_present(pmd))
307644187235SMingwei Zhang 		goto out;
307744187235SMingwei Zhang 
307844187235SMingwei Zhang 	if (pmd_large(pmd))
307944187235SMingwei Zhang 		level = PG_LEVEL_2M;
308044187235SMingwei Zhang 
308144187235SMingwei Zhang out:
308244187235SMingwei Zhang 	local_irq_restore(flags);
3083db543216SSean Christopherson 	return level;
3084db543216SSean Christopherson }
3085db543216SSean Christopherson 
30868ca6f063SBen Gardon int kvm_mmu_max_mapping_level(struct kvm *kvm,
30878ca6f063SBen Gardon 			      const struct kvm_memory_slot *slot, gfn_t gfn,
3088a8ac499bSSean Christopherson 			      int max_level)
30891b6d9d9eSSean Christopherson {
30901b6d9d9eSSean Christopherson 	struct kvm_lpage_info *linfo;
3091ec607a56SPaolo Bonzini 	int host_level;
30921b6d9d9eSSean Christopherson 
30931b6d9d9eSSean Christopherson 	max_level = min(max_level, max_huge_page_level);
30941b6d9d9eSSean Christopherson 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
30951b6d9d9eSSean Christopherson 		linfo = lpage_info_slot(gfn, slot, max_level);
30961b6d9d9eSSean Christopherson 		if (!linfo->disallow_lpage)
30971b6d9d9eSSean Christopherson 			break;
30981b6d9d9eSSean Christopherson 	}
30991b6d9d9eSSean Christopherson 
31001b6d9d9eSSean Christopherson 	if (max_level == PG_LEVEL_4K)
31011b6d9d9eSSean Christopherson 		return PG_LEVEL_4K;
31021b6d9d9eSSean Christopherson 
3103a8ac499bSSean Christopherson 	host_level = host_pfn_mapping_level(kvm, gfn, slot);
3104ec607a56SPaolo Bonzini 	return min(host_level, max_level);
31051b6d9d9eSSean Christopherson }
31061b6d9d9eSSean Christopherson 
310773a3c659SPaolo Bonzini void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
31080885904dSSean Christopherson {
3109e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
311017eff019SSean Christopherson 	kvm_pfn_t mask;
31110885904dSSean Christopherson 
311273a3c659SPaolo Bonzini 	fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
31133cf06612SSean Christopherson 
311473a3c659SPaolo Bonzini 	if (unlikely(fault->max_level == PG_LEVEL_4K))
311573a3c659SPaolo Bonzini 		return;
311617eff019SSean Christopherson 
31175d49f08cSSean Christopherson 	if (is_error_noslot_pfn(fault->pfn))
311873a3c659SPaolo Bonzini 		return;
311917eff019SSean Christopherson 
3120e710c5f6SDavid Matlack 	if (kvm_slot_dirty_track_enabled(slot))
312173a3c659SPaolo Bonzini 		return;
3122293e306eSSean Christopherson 
31233cf06612SSean Christopherson 	/*
31243cf06612SSean Christopherson 	 * Enforce the iTLB multihit workaround after capturing the requested
31253cf06612SSean Christopherson 	 * level, which will be used to do precise, accurate accounting.
31263cf06612SSean Christopherson 	 */
312773a3c659SPaolo Bonzini 	fault->req_level = kvm_mmu_max_mapping_level(vcpu->kvm, slot,
3128a8ac499bSSean Christopherson 						     fault->gfn, fault->max_level);
312973a3c659SPaolo Bonzini 	if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
313073a3c659SPaolo Bonzini 		return;
31314cd071d1SSean Christopherson 
31320885904dSSean Christopherson 	/*
313320ec3ebdSChao Peng 	 * mmu_invalidate_retry() was successful and mmu_lock is held, so
31344cd071d1SSean Christopherson 	 * the pmd can't be split from under us.
31350885904dSSean Christopherson 	 */
313673a3c659SPaolo Bonzini 	fault->goal_level = fault->req_level;
313773a3c659SPaolo Bonzini 	mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
313873a3c659SPaolo Bonzini 	VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
313973a3c659SPaolo Bonzini 	fault->pfn &= ~mask;
31400885904dSSean Christopherson }
31410885904dSSean Christopherson 
3142536f0e6aSPaolo Bonzini void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3143c50d8ae3SPaolo Bonzini {
3144536f0e6aSPaolo Bonzini 	if (cur_level > PG_LEVEL_4K &&
3145536f0e6aSPaolo Bonzini 	    cur_level == fault->goal_level &&
3146c50d8ae3SPaolo Bonzini 	    is_shadow_present_pte(spte) &&
314776901e56SMingwei Zhang 	    !is_large_pte(spte) &&
314876901e56SMingwei Zhang 	    spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3149c50d8ae3SPaolo Bonzini 		/*
31506c882ef4SDavid Matlack 		 * A small SPTE exists for this pfn, but FNAME(fetch),
31516c882ef4SDavid Matlack 		 * direct_map(), or kvm_tdp_mmu_map() would like to create a
31526c882ef4SDavid Matlack 		 * large PTE instead: just force them to go down another level,
31536c882ef4SDavid Matlack 		 * patching back for them into pfn the next 9 bits of the
31546c882ef4SDavid Matlack 		 * address.
3155c50d8ae3SPaolo Bonzini 		 */
3156536f0e6aSPaolo Bonzini 		u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3157536f0e6aSPaolo Bonzini 				KVM_PAGES_PER_HPAGE(cur_level - 1);
3158536f0e6aSPaolo Bonzini 		fault->pfn |= fault->gfn & page_mask;
3159536f0e6aSPaolo Bonzini 		fault->goal_level--;
3160c50d8ae3SPaolo Bonzini 	}
3161c50d8ae3SPaolo Bonzini }
3162c50d8ae3SPaolo Bonzini 
31636c882ef4SDavid Matlack static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3164c50d8ae3SPaolo Bonzini {
3165c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator it;
3166c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
316773a3c659SPaolo Bonzini 	int ret;
316843b74355SPaolo Bonzini 	gfn_t base_gfn = fault->gfn;
3169c50d8ae3SPaolo Bonzini 
317073a3c659SPaolo Bonzini 	kvm_mmu_hugepage_adjust(vcpu, fault);
31714cd071d1SSean Christopherson 
3172f0066d94SPaolo Bonzini 	trace_kvm_mmu_spte_requested(fault);
317343b74355SPaolo Bonzini 	for_each_shadow_entry(vcpu, fault->addr, it) {
3174c50d8ae3SPaolo Bonzini 		/*
3175c50d8ae3SPaolo Bonzini 		 * We cannot overwrite existing page tables with an NX
3176c50d8ae3SPaolo Bonzini 		 * large page, as the leaf could be executable.
3177c50d8ae3SPaolo Bonzini 		 */
317873a3c659SPaolo Bonzini 		if (fault->nx_huge_page_workaround_enabled)
3179536f0e6aSPaolo Bonzini 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3180c50d8ae3SPaolo Bonzini 
3181c667a3baSHou Wenlong 		base_gfn = gfn_round_for_level(fault->gfn, it.level);
318273a3c659SPaolo Bonzini 		if (it.level == fault->goal_level)
3183c50d8ae3SPaolo Bonzini 			break;
3184c50d8ae3SPaolo Bonzini 
31852e65e842SDavid Matlack 		sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
31860cd8dc73SPaolo Bonzini 		if (sp == ERR_PTR(-EEXIST))
31870cd8dc73SPaolo Bonzini 			continue;
3188c50d8ae3SPaolo Bonzini 
3189c50d8ae3SPaolo Bonzini 		link_shadow_page(vcpu, it.sptep, sp);
3190b5b0977fSSean Christopherson 		if (fault->huge_page_disallowed)
319155c510e2SSean Christopherson 			account_nx_huge_page(vcpu->kvm, sp,
3192428e9216SSean Christopherson 					     fault->req_level >= it.level);
3193c50d8ae3SPaolo Bonzini 	}
3194c50d8ae3SPaolo Bonzini 
3195b1a429fbSSean Christopherson 	if (WARN_ON_ONCE(it.level != fault->goal_level))
3196b1a429fbSSean Christopherson 		return -EFAULT;
3197b1a429fbSSean Christopherson 
31988a9f566aSDavid Matlack 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3199a12f4381SPaolo Bonzini 			   base_gfn, fault->pfn, fault);
320012703759SSean Christopherson 	if (ret == RET_PF_SPURIOUS)
320112703759SSean Christopherson 		return ret;
320212703759SSean Christopherson 
3203c50d8ae3SPaolo Bonzini 	direct_pte_prefetch(vcpu, it.sptep);
3204c50d8ae3SPaolo Bonzini 	return ret;
3205c50d8ae3SPaolo Bonzini }
3206c50d8ae3SPaolo Bonzini 
3207cd08d178SDavid Matlack static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3208c50d8ae3SPaolo Bonzini {
3209cd08d178SDavid Matlack 	unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3210cd08d178SDavid Matlack 
3211cd08d178SDavid Matlack 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3212c50d8ae3SPaolo Bonzini }
3213c50d8ae3SPaolo Bonzini 
3214cd08d178SDavid Matlack static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3215c50d8ae3SPaolo Bonzini {
3216cd08d178SDavid Matlack 	if (is_sigpending_pfn(fault->pfn)) {
321776657687SPeter Xu 		kvm_handle_signal_exit(vcpu);
321876657687SPeter Xu 		return -EINTR;
321976657687SPeter Xu 	}
322076657687SPeter Xu 
3221c50d8ae3SPaolo Bonzini 	/*
3222c50d8ae3SPaolo Bonzini 	 * Do not cache the mmio info caused by writing the readonly gfn
3223c50d8ae3SPaolo Bonzini 	 * into the spte otherwise read access on readonly gfn also can
3224c50d8ae3SPaolo Bonzini 	 * caused mmio page fault and treat it as mmio access.
3225c50d8ae3SPaolo Bonzini 	 */
3226cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3227c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3228c50d8ae3SPaolo Bonzini 
3229cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3230cd08d178SDavid Matlack 		kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3231c50d8ae3SPaolo Bonzini 		return RET_PF_RETRY;
3232c50d8ae3SPaolo Bonzini 	}
3233c50d8ae3SPaolo Bonzini 
3234c50d8ae3SPaolo Bonzini 	return -EFAULT;
3235c50d8ae3SPaolo Bonzini }
3236c50d8ae3SPaolo Bonzini 
3237354c908cSDavid Matlack static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3238354c908cSDavid Matlack 				   struct kvm_page_fault *fault,
32395276c616SSean Christopherson 				   unsigned int access)
3240c50d8ae3SPaolo Bonzini {
32413a13f4feSPaolo Bonzini 	gva_t gva = fault->is_tdp ? 0 : fault->addr;
32423a13f4feSPaolo Bonzini 
32433a13f4feSPaolo Bonzini 	vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3244c50d8ae3SPaolo Bonzini 			     access & shadow_mmio_access_mask);
3245354c908cSDavid Matlack 
324630ab5901SSean Christopherson 	/*
324730ab5901SSean Christopherson 	 * If MMIO caching is disabled, emulate immediately without
324830ab5901SSean Christopherson 	 * touching the shadow page tables as attempting to install an
3249354c908cSDavid Matlack 	 * MMIO SPTE will just be an expensive nop.
325030ab5901SSean Christopherson 	 */
3251354c908cSDavid Matlack 	if (unlikely(!enable_mmio_caching))
32525276c616SSean Christopherson 		return RET_PF_EMULATE;
3253354c908cSDavid Matlack 
3254354c908cSDavid Matlack 	/*
3255354c908cSDavid Matlack 	 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3256354c908cSDavid Matlack 	 * any guest that generates such gfns is running nested and is being
3257354c908cSDavid Matlack 	 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3258354c908cSDavid Matlack 	 * only if L1's MAXPHYADDR is inaccurate with respect to the
3259354c908cSDavid Matlack 	 * hardware's).
3260354c908cSDavid Matlack 	 */
3261354c908cSDavid Matlack 	if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3262354c908cSDavid Matlack 		return RET_PF_EMULATE;
3263c50d8ae3SPaolo Bonzini 
32645276c616SSean Christopherson 	return RET_PF_CONTINUE;
3265c50d8ae3SPaolo Bonzini }
3266c50d8ae3SPaolo Bonzini 
32673c8ad5a6SPaolo Bonzini static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
3268c50d8ae3SPaolo Bonzini {
3269c50d8ae3SPaolo Bonzini 	/*
32705c64aba5SSean Christopherson 	 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
32715c64aba5SSean Christopherson 	 * reach the common page fault handler if the SPTE has an invalid MMIO
32725c64aba5SSean Christopherson 	 * generation number.  Refreshing the MMIO generation needs to go down
32735c64aba5SSean Christopherson 	 * the slow path.  Note, EPT Misconfigs do NOT set the PRESENT flag!
3274c50d8ae3SPaolo Bonzini 	 */
32753c8ad5a6SPaolo Bonzini 	if (fault->rsvd)
3276c50d8ae3SPaolo Bonzini 		return false;
3277c50d8ae3SPaolo Bonzini 
3278c50d8ae3SPaolo Bonzini 	/*
3279c50d8ae3SPaolo Bonzini 	 * #PF can be fast if:
3280c50d8ae3SPaolo Bonzini 	 *
328154275f74SSean Christopherson 	 * 1. The shadow page table entry is not present and A/D bits are
328254275f74SSean Christopherson 	 *    disabled _by KVM_, which could mean that the fault is potentially
328354275f74SSean Christopherson 	 *    caused by access tracking (if enabled).  If A/D bits are enabled
328454275f74SSean Christopherson 	 *    by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
328554275f74SSean Christopherson 	 *    bits for L2 and employ access tracking, but the fast page fault
328654275f74SSean Christopherson 	 *    mechanism only supports direct MMUs.
328754275f74SSean Christopherson 	 * 2. The shadow page table entry is present, the access is a write,
328854275f74SSean Christopherson 	 *    and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
328954275f74SSean Christopherson 	 *    the fault was caused by a write-protection violation.  If the
329054275f74SSean Christopherson 	 *    SPTE is MMU-writable (determined later), the fault can be fixed
329154275f74SSean Christopherson 	 *    by setting the Writable bit, which can be done out of mmu_lock.
3292c50d8ae3SPaolo Bonzini 	 */
32935c64aba5SSean Christopherson 	if (!fault->present)
32945c64aba5SSean Christopherson 		return !kvm_ad_enabled();
32955c64aba5SSean Christopherson 
32965c64aba5SSean Christopherson 	/*
32975c64aba5SSean Christopherson 	 * Note, instruction fetches and writes are mutually exclusive, ignore
32985c64aba5SSean Christopherson 	 * the "exec" flag.
32995c64aba5SSean Christopherson 	 */
33005c64aba5SSean Christopherson 	return fault->write;
3301c50d8ae3SPaolo Bonzini }
3302c50d8ae3SPaolo Bonzini 
3303c50d8ae3SPaolo Bonzini /*
3304c50d8ae3SPaolo Bonzini  * Returns true if the SPTE was fixed successfully. Otherwise,
3305c50d8ae3SPaolo Bonzini  * someone else modified the SPTE from its original value.
3306c50d8ae3SPaolo Bonzini  */
3307c50d8ae3SPaolo Bonzini static bool
3308e710c5f6SDavid Matlack fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
3309c50d8ae3SPaolo Bonzini 			u64 *sptep, u64 old_spte, u64 new_spte)
3310c50d8ae3SPaolo Bonzini {
3311c50d8ae3SPaolo Bonzini 	/*
3312c50d8ae3SPaolo Bonzini 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3313c50d8ae3SPaolo Bonzini 	 * order to eliminate unnecessary PML logging. See comments in
3314c50d8ae3SPaolo Bonzini 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3315c50d8ae3SPaolo Bonzini 	 * enabled, so we do not do this. This might result in the same GPA
3316c50d8ae3SPaolo Bonzini 	 * to be logged in PML buffer again when the write really happens, and
3317c50d8ae3SPaolo Bonzini 	 * eventually to be called by mark_page_dirty twice. But it's also no
3318c50d8ae3SPaolo Bonzini 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3319c50d8ae3SPaolo Bonzini 	 * so non-PML cases won't be impacted.
3320c50d8ae3SPaolo Bonzini 	 *
3321c50d8ae3SPaolo Bonzini 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3322c50d8ae3SPaolo Bonzini 	 */
33232db2f46fSUros Bizjak 	if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3324c50d8ae3SPaolo Bonzini 		return false;
3325c50d8ae3SPaolo Bonzini 
3326e710c5f6SDavid Matlack 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3327e710c5f6SDavid Matlack 		mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3328c50d8ae3SPaolo Bonzini 
3329c50d8ae3SPaolo Bonzini 	return true;
3330c50d8ae3SPaolo Bonzini }
3331c50d8ae3SPaolo Bonzini 
33323c8ad5a6SPaolo Bonzini static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3333c50d8ae3SPaolo Bonzini {
33343c8ad5a6SPaolo Bonzini 	if (fault->exec)
3335c50d8ae3SPaolo Bonzini 		return is_executable_pte(spte);
3336c50d8ae3SPaolo Bonzini 
33373c8ad5a6SPaolo Bonzini 	if (fault->write)
3338c50d8ae3SPaolo Bonzini 		return is_writable_pte(spte);
3339c50d8ae3SPaolo Bonzini 
3340c50d8ae3SPaolo Bonzini 	/* Fault was on Read access */
3341c50d8ae3SPaolo Bonzini 	return spte & PT_PRESENT_MASK;
3342c50d8ae3SPaolo Bonzini }
3343c50d8ae3SPaolo Bonzini 
3344c50d8ae3SPaolo Bonzini /*
33456e8eb206SDavid Matlack  * Returns the last level spte pointer of the shadow page walk for the given
33466e8eb206SDavid Matlack  * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
33476e8eb206SDavid Matlack  * walk could be performed, returns NULL and *spte does not contain valid data.
33486e8eb206SDavid Matlack  *
33496e8eb206SDavid Matlack  * Contract:
33506e8eb206SDavid Matlack  *  - Must be called between walk_shadow_page_lockless_{begin,end}.
33516e8eb206SDavid Matlack  *  - The returned sptep must not be used after walk_shadow_page_lockless_end.
33526e8eb206SDavid Matlack  */
33536e8eb206SDavid Matlack static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
33546e8eb206SDavid Matlack {
33556e8eb206SDavid Matlack 	struct kvm_shadow_walk_iterator iterator;
33566e8eb206SDavid Matlack 	u64 old_spte;
33576e8eb206SDavid Matlack 	u64 *sptep = NULL;
33586e8eb206SDavid Matlack 
33596e8eb206SDavid Matlack 	for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
33606e8eb206SDavid Matlack 		sptep = iterator.sptep;
33616e8eb206SDavid Matlack 		*spte = old_spte;
33626e8eb206SDavid Matlack 	}
33636e8eb206SDavid Matlack 
33646e8eb206SDavid Matlack 	return sptep;
33656e8eb206SDavid Matlack }
33666e8eb206SDavid Matlack 
33676e8eb206SDavid Matlack /*
3368c4371c2aSSean Christopherson  * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3369c50d8ae3SPaolo Bonzini  */
33703c8ad5a6SPaolo Bonzini static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3371c50d8ae3SPaolo Bonzini {
3372c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3373c4371c2aSSean Christopherson 	int ret = RET_PF_INVALID;
3374c50d8ae3SPaolo Bonzini 	u64 spte = 0ull;
33756e8eb206SDavid Matlack 	u64 *sptep = NULL;
3376c50d8ae3SPaolo Bonzini 	uint retry_count = 0;
3377c50d8ae3SPaolo Bonzini 
33783c8ad5a6SPaolo Bonzini 	if (!page_fault_can_be_fast(fault))
3379c4371c2aSSean Christopherson 		return ret;
3380c50d8ae3SPaolo Bonzini 
3381c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
3382c50d8ae3SPaolo Bonzini 
3383c50d8ae3SPaolo Bonzini 	do {
3384c50d8ae3SPaolo Bonzini 		u64 new_spte;
3385c50d8ae3SPaolo Bonzini 
3386dfe0ecc6SSean Christopherson 		if (tdp_mmu_enabled)
33873c8ad5a6SPaolo Bonzini 			sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
33886e8eb206SDavid Matlack 		else
33893c8ad5a6SPaolo Bonzini 			sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3390c50d8ae3SPaolo Bonzini 
3391ec89e643SSean Christopherson 		if (!is_shadow_present_pte(spte))
3392ec89e643SSean Christopherson 			break;
3393ec89e643SSean Christopherson 
33946e8eb206SDavid Matlack 		sp = sptep_to_sp(sptep);
3395c50d8ae3SPaolo Bonzini 		if (!is_last_spte(spte, sp->role.level))
3396c50d8ae3SPaolo Bonzini 			break;
3397c50d8ae3SPaolo Bonzini 
3398c50d8ae3SPaolo Bonzini 		/*
3399c50d8ae3SPaolo Bonzini 		 * Check whether the memory access that caused the fault would
3400c50d8ae3SPaolo Bonzini 		 * still cause it if it were to be performed right now. If not,
3401c50d8ae3SPaolo Bonzini 		 * then this is a spurious fault caused by TLB lazily flushed,
3402c50d8ae3SPaolo Bonzini 		 * or some other CPU has already fixed the PTE after the
3403c50d8ae3SPaolo Bonzini 		 * current CPU took the fault.
3404c50d8ae3SPaolo Bonzini 		 *
3405c50d8ae3SPaolo Bonzini 		 * Need not check the access of upper level table entries since
3406c50d8ae3SPaolo Bonzini 		 * they are always ACC_ALL.
3407c50d8ae3SPaolo Bonzini 		 */
34083c8ad5a6SPaolo Bonzini 		if (is_access_allowed(fault, spte)) {
3409c4371c2aSSean Christopherson 			ret = RET_PF_SPURIOUS;
3410c50d8ae3SPaolo Bonzini 			break;
3411c50d8ae3SPaolo Bonzini 		}
3412c50d8ae3SPaolo Bonzini 
3413c50d8ae3SPaolo Bonzini 		new_spte = spte;
3414c50d8ae3SPaolo Bonzini 
341554275f74SSean Christopherson 		/*
341654275f74SSean Christopherson 		 * KVM only supports fixing page faults outside of MMU lock for
341754275f74SSean Christopherson 		 * direct MMUs, nested MMUs are always indirect, and KVM always
341854275f74SSean Christopherson 		 * uses A/D bits for non-nested MMUs.  Thus, if A/D bits are
341954275f74SSean Christopherson 		 * enabled, the SPTE can't be an access-tracked SPTE.
342054275f74SSean Christopherson 		 */
342154275f74SSean Christopherson 		if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3422c50d8ae3SPaolo Bonzini 			new_spte = restore_acc_track_spte(new_spte);
3423c50d8ae3SPaolo Bonzini 
3424c50d8ae3SPaolo Bonzini 		/*
342554275f74SSean Christopherson 		 * To keep things simple, only SPTEs that are MMU-writable can
342654275f74SSean Christopherson 		 * be made fully writable outside of mmu_lock, e.g. only SPTEs
342754275f74SSean Christopherson 		 * that were write-protected for dirty-logging or access
342854275f74SSean Christopherson 		 * tracking are handled here.  Don't bother checking if the
342954275f74SSean Christopherson 		 * SPTE is writable to prioritize running with A/D bits enabled.
343054275f74SSean Christopherson 		 * The is_access_allowed() check above handles the common case
343154275f74SSean Christopherson 		 * of the fault being spurious, and the SPTE is known to be
343254275f74SSean Christopherson 		 * shadow-present, i.e. except for access tracking restoration
343354275f74SSean Christopherson 		 * making the new SPTE writable, the check is wasteful.
3434c50d8ae3SPaolo Bonzini 		 */
3435706c9c55SSean Christopherson 		if (fault->write && is_mmu_writable_spte(spte)) {
3436c50d8ae3SPaolo Bonzini 			new_spte |= PT_WRITABLE_MASK;
3437c50d8ae3SPaolo Bonzini 
3438c50d8ae3SPaolo Bonzini 			/*
343910c30de0SJunaid Shahid 			 * Do not fix write-permission on the large spte when
344010c30de0SJunaid Shahid 			 * dirty logging is enabled. Since we only dirty the
344110c30de0SJunaid Shahid 			 * first page into the dirty-bitmap in
3442c50d8ae3SPaolo Bonzini 			 * fast_pf_fix_direct_spte(), other pages are missed
3443c50d8ae3SPaolo Bonzini 			 * if its slot has dirty logging enabled.
3444c50d8ae3SPaolo Bonzini 			 *
3445c50d8ae3SPaolo Bonzini 			 * Instead, we let the slow page fault path create a
3446c50d8ae3SPaolo Bonzini 			 * normal spte to fix the access.
3447c50d8ae3SPaolo Bonzini 			 */
344810c30de0SJunaid Shahid 			if (sp->role.level > PG_LEVEL_4K &&
344910c30de0SJunaid Shahid 			    kvm_slot_dirty_track_enabled(fault->slot))
3450c50d8ae3SPaolo Bonzini 				break;
3451c50d8ae3SPaolo Bonzini 		}
3452c50d8ae3SPaolo Bonzini 
3453c50d8ae3SPaolo Bonzini 		/* Verify that the fault can be handled in the fast path */
3454c50d8ae3SPaolo Bonzini 		if (new_spte == spte ||
34553c8ad5a6SPaolo Bonzini 		    !is_access_allowed(fault, new_spte))
3456c50d8ae3SPaolo Bonzini 			break;
3457c50d8ae3SPaolo Bonzini 
3458c50d8ae3SPaolo Bonzini 		/*
3459c50d8ae3SPaolo Bonzini 		 * Currently, fast page fault only works for direct mapping
3460c50d8ae3SPaolo Bonzini 		 * since the gfn is not stable for indirect shadow page. See
34613ecad8c2SMauro Carvalho Chehab 		 * Documentation/virt/kvm/locking.rst to get more detail.
3462c50d8ae3SPaolo Bonzini 		 */
3463e710c5f6SDavid Matlack 		if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3464c4371c2aSSean Christopherson 			ret = RET_PF_FIXED;
3465c50d8ae3SPaolo Bonzini 			break;
3466c4371c2aSSean Christopherson 		}
3467c50d8ae3SPaolo Bonzini 
3468c50d8ae3SPaolo Bonzini 		if (++retry_count > 4) {
34698d20bd63SSean Christopherson 			pr_warn_once("Fast #PF retrying more than 4 times.\n");
3470c50d8ae3SPaolo Bonzini 			break;
3471c50d8ae3SPaolo Bonzini 		}
3472c50d8ae3SPaolo Bonzini 
3473c50d8ae3SPaolo Bonzini 	} while (true);
3474c50d8ae3SPaolo Bonzini 
3475f0066d94SPaolo Bonzini 	trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3476c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3477c50d8ae3SPaolo Bonzini 
34781075d41eSSean Christopherson 	if (ret != RET_PF_INVALID)
34791075d41eSSean Christopherson 		vcpu->stat.pf_fast++;
34801075d41eSSean Christopherson 
3481c4371c2aSSean Christopherson 	return ret;
3482c50d8ae3SPaolo Bonzini }
3483c50d8ae3SPaolo Bonzini 
3484c50d8ae3SPaolo Bonzini static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3485c50d8ae3SPaolo Bonzini 			       struct list_head *invalid_list)
3486c50d8ae3SPaolo Bonzini {
3487c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3488c50d8ae3SPaolo Bonzini 
3489c50d8ae3SPaolo Bonzini 	if (!VALID_PAGE(*root_hpa))
3490c50d8ae3SPaolo Bonzini 		return;
3491c50d8ae3SPaolo Bonzini 
34925e3edd7eSSean Christopherson 	/*
34935e3edd7eSSean Christopherson 	 * The "root" may be a special root, e.g. a PAE entry, treat it as a
34945e3edd7eSSean Christopherson 	 * SPTE to ensure any non-PA bits are dropped.
34955e3edd7eSSean Christopherson 	 */
34965e3edd7eSSean Christopherson 	sp = spte_to_child_sp(*root_hpa);
34979191b8f0SPaolo Bonzini 	if (WARN_ON(!sp))
34989191b8f0SPaolo Bonzini 		return;
349902c00b3aSBen Gardon 
3500897218ffSPaolo Bonzini 	if (is_tdp_mmu_page(sp))
35016103bc07SBen Gardon 		kvm_tdp_mmu_put_root(kvm, sp, false);
350276eb54e7SBen Gardon 	else if (!--sp->root_count && sp->role.invalid)
3503c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3504c50d8ae3SPaolo Bonzini 
3505c50d8ae3SPaolo Bonzini 	*root_hpa = INVALID_PAGE;
3506c50d8ae3SPaolo Bonzini }
3507c50d8ae3SPaolo Bonzini 
3508c50d8ae3SPaolo Bonzini /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
35090c1c92f1SPaolo Bonzini void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3510c50d8ae3SPaolo Bonzini 			ulong roots_to_free)
3511c50d8ae3SPaolo Bonzini {
3512c50d8ae3SPaolo Bonzini 	int i;
3513c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
3514594bef79SPaolo Bonzini 	bool free_active_root;
3515c50d8ae3SPaolo Bonzini 
3516c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3517c50d8ae3SPaolo Bonzini 
3518c50d8ae3SPaolo Bonzini 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3519594bef79SPaolo Bonzini 	free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3520594bef79SPaolo Bonzini 		&& VALID_PAGE(mmu->root.hpa);
3521594bef79SPaolo Bonzini 
3522594bef79SPaolo Bonzini 	if (!free_active_root) {
3523c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3524c50d8ae3SPaolo Bonzini 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3525c50d8ae3SPaolo Bonzini 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3526c50d8ae3SPaolo Bonzini 				break;
3527c50d8ae3SPaolo Bonzini 
3528c50d8ae3SPaolo Bonzini 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3529c50d8ae3SPaolo Bonzini 			return;
3530c50d8ae3SPaolo Bonzini 	}
3531c50d8ae3SPaolo Bonzini 
3532531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
3533c50d8ae3SPaolo Bonzini 
3534c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3535c50d8ae3SPaolo Bonzini 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
35364d710de9SSean Christopherson 			mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3537c50d8ae3SPaolo Bonzini 					   &invalid_list);
3538c50d8ae3SPaolo Bonzini 
3539c50d8ae3SPaolo Bonzini 	if (free_active_root) {
3540594bef79SPaolo Bonzini 		if (to_shadow_page(mmu->root.hpa)) {
3541b9e5603cSPaolo Bonzini 			mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
354204d45551SSean Christopherson 		} else if (mmu->pae_root) {
3543c834e5e4SSean Christopherson 			for (i = 0; i < 4; ++i) {
3544c834e5e4SSean Christopherson 				if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3545c834e5e4SSean Christopherson 					continue;
3546c834e5e4SSean Christopherson 
3547c834e5e4SSean Christopherson 				mmu_free_root_page(kvm, &mmu->pae_root[i],
3548c50d8ae3SPaolo Bonzini 						   &invalid_list);
3549c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3550c50d8ae3SPaolo Bonzini 			}
3551c50d8ae3SPaolo Bonzini 		}
3552b9e5603cSPaolo Bonzini 		mmu->root.hpa = INVALID_PAGE;
3553b9e5603cSPaolo Bonzini 		mmu->root.pgd = 0;
3554c50d8ae3SPaolo Bonzini 	}
3555c50d8ae3SPaolo Bonzini 
35564d710de9SSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
3557531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
3558c50d8ae3SPaolo Bonzini }
3559c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3560c50d8ae3SPaolo Bonzini 
35610c1c92f1SPaolo Bonzini void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
356225b62c62SSean Christopherson {
356325b62c62SSean Christopherson 	unsigned long roots_to_free = 0;
356425b62c62SSean Christopherson 	hpa_t root_hpa;
356525b62c62SSean Christopherson 	int i;
356625b62c62SSean Christopherson 
356725b62c62SSean Christopherson 	/*
356825b62c62SSean Christopherson 	 * This should not be called while L2 is active, L2 can't invalidate
356925b62c62SSean Christopherson 	 * _only_ its own roots, e.g. INVVPID unconditionally exits.
357025b62c62SSean Christopherson 	 */
35717a458f0eSPaolo Bonzini 	WARN_ON_ONCE(mmu->root_role.guest_mode);
357225b62c62SSean Christopherson 
357325b62c62SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
357425b62c62SSean Christopherson 		root_hpa = mmu->prev_roots[i].hpa;
357525b62c62SSean Christopherson 		if (!VALID_PAGE(root_hpa))
357625b62c62SSean Christopherson 			continue;
357725b62c62SSean Christopherson 
357825b62c62SSean Christopherson 		if (!to_shadow_page(root_hpa) ||
357925b62c62SSean Christopherson 			to_shadow_page(root_hpa)->role.guest_mode)
358025b62c62SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
358125b62c62SSean Christopherson 	}
358225b62c62SSean Christopherson 
35830c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, roots_to_free);
358425b62c62SSean Christopherson }
358525b62c62SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
358625b62c62SSean Christopherson 
358725b62c62SSean Christopherson 
3588c50d8ae3SPaolo Bonzini static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3589c50d8ae3SPaolo Bonzini {
3590c50d8ae3SPaolo Bonzini 	int ret = 0;
3591c50d8ae3SPaolo Bonzini 
3592995decb6SVitaly Kuznetsov 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3593c50d8ae3SPaolo Bonzini 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3594c50d8ae3SPaolo Bonzini 		ret = 1;
3595c50d8ae3SPaolo Bonzini 	}
3596c50d8ae3SPaolo Bonzini 
3597c50d8ae3SPaolo Bonzini 	return ret;
3598c50d8ae3SPaolo Bonzini }
3599c50d8ae3SPaolo Bonzini 
36002e65e842SDavid Matlack static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
360186938ab6SDavid Matlack 			    u8 level)
3602c50d8ae3SPaolo Bonzini {
36032e65e842SDavid Matlack 	union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3604c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
36058123f265SSean Christopherson 
36062e65e842SDavid Matlack 	role.level = level;
36072e65e842SDavid Matlack 	role.quadrant = quadrant;
36082e65e842SDavid Matlack 
36097f497775SDavid Matlack 	WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
36107f497775SDavid Matlack 	WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
36117f497775SDavid Matlack 
361287654643SDavid Matlack 	sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
36138123f265SSean Christopherson 	++sp->root_count;
36148123f265SSean Christopherson 
36158123f265SSean Christopherson 	return __pa(sp->spt);
36168123f265SSean Christopherson }
36178123f265SSean Christopherson 
36188123f265SSean Christopherson static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
36198123f265SSean Christopherson {
3620b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3621a972e29cSPaolo Bonzini 	u8 shadow_root_level = mmu->root_role.level;
36228123f265SSean Christopherson 	hpa_t root;
3623c50d8ae3SPaolo Bonzini 	unsigned i;
36244a38162eSPaolo Bonzini 	int r;
36254a38162eSPaolo Bonzini 
36264a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
36274a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
36284a38162eSPaolo Bonzini 	if (r < 0)
36294a38162eSPaolo Bonzini 		goto out_unlock;
3630c50d8ae3SPaolo Bonzini 
36311f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
363202c00b3aSBen Gardon 		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
3633b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
363402c00b3aSBen Gardon 	} else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
363586938ab6SDavid Matlack 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3636b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
36378123f265SSean Christopherson 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
36384a38162eSPaolo Bonzini 		if (WARN_ON_ONCE(!mmu->pae_root)) {
36394a38162eSPaolo Bonzini 			r = -EIO;
36404a38162eSPaolo Bonzini 			goto out_unlock;
36414a38162eSPaolo Bonzini 		}
364273ad1606SSean Christopherson 
3643c50d8ae3SPaolo Bonzini 		for (i = 0; i < 4; ++i) {
3644c834e5e4SSean Christopherson 			WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3645c50d8ae3SPaolo Bonzini 
36467f497775SDavid Matlack 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
36472e65e842SDavid Matlack 					      PT32_ROOT_LEVEL);
364817e368d9SSean Christopherson 			mmu->pae_root[i] = root | PT_PRESENT_MASK |
3649d2263de1SYuan Yao 					   shadow_me_value;
3650c50d8ae3SPaolo Bonzini 		}
3651b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
365273ad1606SSean Christopherson 	} else {
365373ad1606SSean Christopherson 		WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
36544a38162eSPaolo Bonzini 		r = -EIO;
36554a38162eSPaolo Bonzini 		goto out_unlock;
365673ad1606SSean Christopherson 	}
36573651c7fcSSean Christopherson 
3658b9e5603cSPaolo Bonzini 	/* root.pgd is ignored for direct MMUs. */
3659b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
36604a38162eSPaolo Bonzini out_unlock:
36614a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
36624a38162eSPaolo Bonzini 	return r;
3663c50d8ae3SPaolo Bonzini }
3664c50d8ae3SPaolo Bonzini 
36651e76a3ceSDavid Stevens static int mmu_first_shadow_root_alloc(struct kvm *kvm)
36661e76a3ceSDavid Stevens {
36671e76a3ceSDavid Stevens 	struct kvm_memslots *slots;
36681e76a3ceSDavid Stevens 	struct kvm_memory_slot *slot;
3669a54d8066SMaciej S. Szmigiero 	int r = 0, i, bkt;
36701e76a3ceSDavid Stevens 
36711e76a3ceSDavid Stevens 	/*
36721e76a3ceSDavid Stevens 	 * Check if this is the first shadow root being allocated before
36731e76a3ceSDavid Stevens 	 * taking the lock.
36741e76a3ceSDavid Stevens 	 */
36751e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
36761e76a3ceSDavid Stevens 		return 0;
36771e76a3ceSDavid Stevens 
36781e76a3ceSDavid Stevens 	mutex_lock(&kvm->slots_arch_lock);
36791e76a3ceSDavid Stevens 
36801e76a3ceSDavid Stevens 	/* Recheck, under the lock, whether this is the first shadow root. */
36811e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
36821e76a3ceSDavid Stevens 		goto out_unlock;
36831e76a3ceSDavid Stevens 
36841e76a3ceSDavid Stevens 	/*
36851e76a3ceSDavid Stevens 	 * Check if anything actually needs to be allocated, e.g. all metadata
36861e76a3ceSDavid Stevens 	 * will be allocated upfront if TDP is disabled.
36871e76a3ceSDavid Stevens 	 */
36881e76a3ceSDavid Stevens 	if (kvm_memslots_have_rmaps(kvm) &&
36891e76a3ceSDavid Stevens 	    kvm_page_track_write_tracking_enabled(kvm))
36901e76a3ceSDavid Stevens 		goto out_success;
36911e76a3ceSDavid Stevens 
36921e76a3ceSDavid Stevens 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
36931e76a3ceSDavid Stevens 		slots = __kvm_memslots(kvm, i);
3694a54d8066SMaciej S. Szmigiero 		kvm_for_each_memslot(slot, bkt, slots) {
36951e76a3ceSDavid Stevens 			/*
36961e76a3ceSDavid Stevens 			 * Both of these functions are no-ops if the target is
36971e76a3ceSDavid Stevens 			 * already allocated, so unconditionally calling both
36981e76a3ceSDavid Stevens 			 * is safe.  Intentionally do NOT free allocations on
36991e76a3ceSDavid Stevens 			 * failure to avoid having to track which allocations
37001e76a3ceSDavid Stevens 			 * were made now versus when the memslot was created.
37011e76a3ceSDavid Stevens 			 * The metadata is guaranteed to be freed when the slot
37021e76a3ceSDavid Stevens 			 * is freed, and will be kept/used if userspace retries
37031e76a3ceSDavid Stevens 			 * KVM_RUN instead of killing the VM.
37041e76a3ceSDavid Stevens 			 */
37051e76a3ceSDavid Stevens 			r = memslot_rmap_alloc(slot, slot->npages);
37061e76a3ceSDavid Stevens 			if (r)
37071e76a3ceSDavid Stevens 				goto out_unlock;
37081e76a3ceSDavid Stevens 			r = kvm_page_track_write_tracking_alloc(slot);
37091e76a3ceSDavid Stevens 			if (r)
37101e76a3ceSDavid Stevens 				goto out_unlock;
37111e76a3ceSDavid Stevens 		}
37121e76a3ceSDavid Stevens 	}
37131e76a3ceSDavid Stevens 
37141e76a3ceSDavid Stevens 	/*
37151e76a3ceSDavid Stevens 	 * Ensure that shadow_root_allocated becomes true strictly after
37161e76a3ceSDavid Stevens 	 * all the related pointers are set.
37171e76a3ceSDavid Stevens 	 */
37181e76a3ceSDavid Stevens out_success:
37191e76a3ceSDavid Stevens 	smp_store_release(&kvm->arch.shadow_root_allocated, true);
37201e76a3ceSDavid Stevens 
37211e76a3ceSDavid Stevens out_unlock:
37221e76a3ceSDavid Stevens 	mutex_unlock(&kvm->slots_arch_lock);
37231e76a3ceSDavid Stevens 	return r;
37241e76a3ceSDavid Stevens }
37251e76a3ceSDavid Stevens 
3726c50d8ae3SPaolo Bonzini static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3727c50d8ae3SPaolo Bonzini {
3728b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
37296e0918aeSSean Christopherson 	u64 pdptrs[4], pm_mask;
3730be01e8e2SSean Christopherson 	gfn_t root_gfn, root_pgd;
37317f497775SDavid Matlack 	int quadrant, i, r;
37328123f265SSean Christopherson 	hpa_t root;
3733c50d8ae3SPaolo Bonzini 
3734b37233c9SSean Christopherson 	root_pgd = mmu->get_guest_pgd(vcpu);
3735be01e8e2SSean Christopherson 	root_gfn = root_pgd >> PAGE_SHIFT;
3736c50d8ae3SPaolo Bonzini 
3737c50d8ae3SPaolo Bonzini 	if (mmu_check_root(vcpu, root_gfn))
3738c50d8ae3SPaolo Bonzini 		return 1;
3739c50d8ae3SPaolo Bonzini 
3740c50d8ae3SPaolo Bonzini 	/*
37414a38162eSPaolo Bonzini 	 * On SVM, reading PDPTRs might access guest memory, which might fault
37424a38162eSPaolo Bonzini 	 * and thus might sleep.  Grab the PDPTRs before acquiring mmu_lock.
37434a38162eSPaolo Bonzini 	 */
37444d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
37456e0918aeSSean Christopherson 		for (i = 0; i < 4; ++i) {
37466e0918aeSSean Christopherson 			pdptrs[i] = mmu->get_pdptr(vcpu, i);
37476e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK))
37486e0918aeSSean Christopherson 				continue;
37496e0918aeSSean Christopherson 
37506e0918aeSSean Christopherson 			if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
37516e0918aeSSean Christopherson 				return 1;
37526e0918aeSSean Christopherson 		}
37536e0918aeSSean Christopherson 	}
37546e0918aeSSean Christopherson 
37551e76a3ceSDavid Stevens 	r = mmu_first_shadow_root_alloc(vcpu->kvm);
3756d501f747SBen Gardon 	if (r)
3757d501f747SBen Gardon 		return r;
3758d501f747SBen Gardon 
37594a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
37604a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
37614a38162eSPaolo Bonzini 	if (r < 0)
37624a38162eSPaolo Bonzini 		goto out_unlock;
37634a38162eSPaolo Bonzini 
3764c50d8ae3SPaolo Bonzini 	/*
3765c50d8ae3SPaolo Bonzini 	 * Do we shadow a long mode page table? If so we need to
3766c50d8ae3SPaolo Bonzini 	 * write-protect the guests page table root.
3767c50d8ae3SPaolo Bonzini 	 */
37684d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
37698123f265SSean Christopherson 		root = mmu_alloc_root(vcpu, root_gfn, 0,
377086938ab6SDavid Matlack 				      mmu->root_role.level);
3771b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
3772be01e8e2SSean Christopherson 		goto set_root_pgd;
3773c50d8ae3SPaolo Bonzini 	}
3774c50d8ae3SPaolo Bonzini 
37754a38162eSPaolo Bonzini 	if (WARN_ON_ONCE(!mmu->pae_root)) {
37764a38162eSPaolo Bonzini 		r = -EIO;
37774a38162eSPaolo Bonzini 		goto out_unlock;
37784a38162eSPaolo Bonzini 	}
377973ad1606SSean Christopherson 
3780c50d8ae3SPaolo Bonzini 	/*
3781c50d8ae3SPaolo Bonzini 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3782c50d8ae3SPaolo Bonzini 	 * or a PAE 3-level page table. In either case we need to be aware that
3783c50d8ae3SPaolo Bonzini 	 * the shadow page table may be a PAE or a long mode page table.
3784c50d8ae3SPaolo Bonzini 	 */
3785e54f1ff2SKai Huang 	pm_mask = PT_PRESENT_MASK | shadow_me_value;
3786a972e29cSPaolo Bonzini 	if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3787c50d8ae3SPaolo Bonzini 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3788c50d8ae3SPaolo Bonzini 
378903ca4589SSean Christopherson 		if (WARN_ON_ONCE(!mmu->pml4_root)) {
37904a38162eSPaolo Bonzini 			r = -EIO;
37914a38162eSPaolo Bonzini 			goto out_unlock;
37924a38162eSPaolo Bonzini 		}
379303ca4589SSean Christopherson 		mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3794cb0f722aSWei Huang 
3795a972e29cSPaolo Bonzini 		if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3796cb0f722aSWei Huang 			if (WARN_ON_ONCE(!mmu->pml5_root)) {
3797cb0f722aSWei Huang 				r = -EIO;
3798cb0f722aSWei Huang 				goto out_unlock;
3799cb0f722aSWei Huang 			}
3800cb0f722aSWei Huang 			mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3801cb0f722aSWei Huang 		}
380204d45551SSean Christopherson 	}
380304d45551SSean Christopherson 
3804c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3805c834e5e4SSean Christopherson 		WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
38066e6ec584SSean Christopherson 
38074d25502aSPaolo Bonzini 		if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
38086e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3809c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3810c50d8ae3SPaolo Bonzini 				continue;
3811c50d8ae3SPaolo Bonzini 			}
38126e0918aeSSean Christopherson 			root_gfn = pdptrs[i] >> PAGE_SHIFT;
3813c50d8ae3SPaolo Bonzini 		}
3814c50d8ae3SPaolo Bonzini 
38157f497775SDavid Matlack 		/*
38167f497775SDavid Matlack 		 * If shadowing 32-bit non-PAE page tables, each PAE page
38177f497775SDavid Matlack 		 * directory maps one quarter of the guest's non-PAE page
38187f497775SDavid Matlack 		 * directory. Othwerise each PAE page direct shadows one guest
38197f497775SDavid Matlack 		 * PAE page directory so that quadrant should be 0.
38207f497775SDavid Matlack 		 */
38217f497775SDavid Matlack 		quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
38227f497775SDavid Matlack 
38237f497775SDavid Matlack 		root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3824b37233c9SSean Christopherson 		mmu->pae_root[i] = root | pm_mask;
3825c50d8ae3SPaolo Bonzini 	}
3826c50d8ae3SPaolo Bonzini 
3827a972e29cSPaolo Bonzini 	if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3828b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml5_root);
3829a972e29cSPaolo Bonzini 	else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3830b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml4_root);
3831ba0a194fSSean Christopherson 	else
3832b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
3833c50d8ae3SPaolo Bonzini 
3834be01e8e2SSean Christopherson set_root_pgd:
3835b9e5603cSPaolo Bonzini 	mmu->root.pgd = root_pgd;
38364a38162eSPaolo Bonzini out_unlock:
38374a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
3838c50d8ae3SPaolo Bonzini 
3839c6c937d6SLike Xu 	return r;
3840c50d8ae3SPaolo Bonzini }
3841c50d8ae3SPaolo Bonzini 
3842748e52b9SSean Christopherson static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3843c50d8ae3SPaolo Bonzini {
3844748e52b9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3845a972e29cSPaolo Bonzini 	bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3846cb0f722aSWei Huang 	u64 *pml5_root = NULL;
3847cb0f722aSWei Huang 	u64 *pml4_root = NULL;
3848cb0f722aSWei Huang 	u64 *pae_root;
3849748e52b9SSean Christopherson 
3850748e52b9SSean Christopherson 	/*
3851748e52b9SSean Christopherson 	 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3852748e52b9SSean Christopherson 	 * tables are allocated and initialized at root creation as there is no
3853748e52b9SSean Christopherson 	 * equivalent level in the guest's NPT to shadow.  Allocate the tables
3854748e52b9SSean Christopherson 	 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3855748e52b9SSean Christopherson 	 */
3856347a0d0dSPaolo Bonzini 	if (mmu->root_role.direct ||
3857347a0d0dSPaolo Bonzini 	    mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3858a972e29cSPaolo Bonzini 	    mmu->root_role.level < PT64_ROOT_4LEVEL)
3859748e52b9SSean Christopherson 		return 0;
3860748e52b9SSean Christopherson 
3861a717a780SSean Christopherson 	/*
3862a717a780SSean Christopherson 	 * NPT, the only paging mode that uses this horror, uses a fixed number
3863a717a780SSean Christopherson 	 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3864a717a780SSean Christopherson 	 * all MMus are 5-level.  Thus, this can safely require that pml5_root
3865a717a780SSean Christopherson 	 * is allocated if the other roots are valid and pml5 is needed, as any
3866a717a780SSean Christopherson 	 * prior MMU would also have required pml5.
3867a717a780SSean Christopherson 	 */
3868a717a780SSean Christopherson 	if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3869748e52b9SSean Christopherson 		return 0;
3870748e52b9SSean Christopherson 
3871748e52b9SSean Christopherson 	/*
3872748e52b9SSean Christopherson 	 * The special roots should always be allocated in concert.  Yell and
3873748e52b9SSean Christopherson 	 * bail if KVM ends up in a state where only one of the roots is valid.
3874748e52b9SSean Christopherson 	 */
3875cb0f722aSWei Huang 	if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3876a717a780SSean Christopherson 			 (need_pml5 && mmu->pml5_root)))
3877748e52b9SSean Christopherson 		return -EIO;
3878748e52b9SSean Christopherson 
38794a98623dSSean Christopherson 	/*
38804a98623dSSean Christopherson 	 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
38814a98623dSSean Christopherson 	 * doesn't need to be decrypted.
38824a98623dSSean Christopherson 	 */
3883748e52b9SSean Christopherson 	pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3884748e52b9SSean Christopherson 	if (!pae_root)
3885748e52b9SSean Christopherson 		return -ENOMEM;
3886748e52b9SSean Christopherson 
3887cb0f722aSWei Huang #ifdef CONFIG_X86_64
388803ca4589SSean Christopherson 	pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3889cb0f722aSWei Huang 	if (!pml4_root)
3890cb0f722aSWei Huang 		goto err_pml4;
3891cb0f722aSWei Huang 
3892a717a780SSean Christopherson 	if (need_pml5) {
3893cb0f722aSWei Huang 		pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3894cb0f722aSWei Huang 		if (!pml5_root)
3895cb0f722aSWei Huang 			goto err_pml5;
3896748e52b9SSean Christopherson 	}
3897cb0f722aSWei Huang #endif
3898748e52b9SSean Christopherson 
3899748e52b9SSean Christopherson 	mmu->pae_root = pae_root;
390003ca4589SSean Christopherson 	mmu->pml4_root = pml4_root;
3901cb0f722aSWei Huang 	mmu->pml5_root = pml5_root;
3902748e52b9SSean Christopherson 
3903748e52b9SSean Christopherson 	return 0;
3904cb0f722aSWei Huang 
3905cb0f722aSWei Huang #ifdef CONFIG_X86_64
3906cb0f722aSWei Huang err_pml5:
3907cb0f722aSWei Huang 	free_page((unsigned long)pml4_root);
3908cb0f722aSWei Huang err_pml4:
3909cb0f722aSWei Huang 	free_page((unsigned long)pae_root);
3910cb0f722aSWei Huang 	return -ENOMEM;
3911cb0f722aSWei Huang #endif
3912c50d8ae3SPaolo Bonzini }
3913c50d8ae3SPaolo Bonzini 
3914264d3dc1SLai Jiangshan static bool is_unsync_root(hpa_t root)
3915264d3dc1SLai Jiangshan {
3916264d3dc1SLai Jiangshan 	struct kvm_mmu_page *sp;
3917264d3dc1SLai Jiangshan 
391861b05a9fSLai Jiangshan 	if (!VALID_PAGE(root))
391961b05a9fSLai Jiangshan 		return false;
392061b05a9fSLai Jiangshan 
3921264d3dc1SLai Jiangshan 	/*
3922264d3dc1SLai Jiangshan 	 * The read barrier orders the CPU's read of SPTE.W during the page table
3923264d3dc1SLai Jiangshan 	 * walk before the reads of sp->unsync/sp->unsync_children here.
3924264d3dc1SLai Jiangshan 	 *
3925264d3dc1SLai Jiangshan 	 * Even if another CPU was marking the SP as unsync-ed simultaneously,
3926264d3dc1SLai Jiangshan 	 * any guest page table changes are not guaranteed to be visible anyway
3927264d3dc1SLai Jiangshan 	 * until this VCPU issues a TLB flush strictly after those changes are
3928264d3dc1SLai Jiangshan 	 * made.  We only need to ensure that the other CPU sets these flags
3929264d3dc1SLai Jiangshan 	 * before any actual changes to the page tables are made.  The comments
3930264d3dc1SLai Jiangshan 	 * in mmu_try_to_unsync_pages() describe what could go wrong if this
3931264d3dc1SLai Jiangshan 	 * requirement isn't satisfied.
3932264d3dc1SLai Jiangshan 	 */
3933264d3dc1SLai Jiangshan 	smp_rmb();
3934264d3dc1SLai Jiangshan 	sp = to_shadow_page(root);
39355d6a3221SSean Christopherson 
39365d6a3221SSean Christopherson 	/*
39375d6a3221SSean Christopherson 	 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
39385d6a3221SSean Christopherson 	 * PDPTEs for a given PAE root need to be synchronized individually.
39395d6a3221SSean Christopherson 	 */
39405d6a3221SSean Christopherson 	if (WARN_ON_ONCE(!sp))
39415d6a3221SSean Christopherson 		return false;
39425d6a3221SSean Christopherson 
3943264d3dc1SLai Jiangshan 	if (sp->unsync || sp->unsync_children)
3944264d3dc1SLai Jiangshan 		return true;
3945264d3dc1SLai Jiangshan 
3946264d3dc1SLai Jiangshan 	return false;
3947264d3dc1SLai Jiangshan }
3948264d3dc1SLai Jiangshan 
3949c50d8ae3SPaolo Bonzini void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3950c50d8ae3SPaolo Bonzini {
3951c50d8ae3SPaolo Bonzini 	int i;
3952c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3953c50d8ae3SPaolo Bonzini 
3954347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
3955c50d8ae3SPaolo Bonzini 		return;
3956c50d8ae3SPaolo Bonzini 
3957b9e5603cSPaolo Bonzini 	if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
3958c50d8ae3SPaolo Bonzini 		return;
3959c50d8ae3SPaolo Bonzini 
3960c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3961c50d8ae3SPaolo Bonzini 
39624d25502aSPaolo Bonzini 	if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
3963b9e5603cSPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->root.hpa;
3964e47c4aeeSSean Christopherson 		sp = to_shadow_page(root);
3965c50d8ae3SPaolo Bonzini 
3966264d3dc1SLai Jiangshan 		if (!is_unsync_root(root))
3967c50d8ae3SPaolo Bonzini 			return;
3968c50d8ae3SPaolo Bonzini 
3969531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
397065855ed8SLai Jiangshan 		mmu_sync_children(vcpu, sp, true);
3971531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
3972c50d8ae3SPaolo Bonzini 		return;
3973c50d8ae3SPaolo Bonzini 	}
3974c50d8ae3SPaolo Bonzini 
3975531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
3976c50d8ae3SPaolo Bonzini 
3977c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3978c50d8ae3SPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->pae_root[i];
3979c50d8ae3SPaolo Bonzini 
3980c834e5e4SSean Christopherson 		if (IS_VALID_PAE_ROOT(root)) {
39815e3edd7eSSean Christopherson 			sp = spte_to_child_sp(root);
398265855ed8SLai Jiangshan 			mmu_sync_children(vcpu, sp, true);
3983c50d8ae3SPaolo Bonzini 		}
3984c50d8ae3SPaolo Bonzini 	}
3985c50d8ae3SPaolo Bonzini 
3986531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
3987c50d8ae3SPaolo Bonzini }
3988c50d8ae3SPaolo Bonzini 
398961b05a9fSLai Jiangshan void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
399061b05a9fSLai Jiangshan {
399161b05a9fSLai Jiangshan 	unsigned long roots_to_free = 0;
399261b05a9fSLai Jiangshan 	int i;
399361b05a9fSLai Jiangshan 
399461b05a9fSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
399561b05a9fSLai Jiangshan 		if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
399661b05a9fSLai Jiangshan 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
399761b05a9fSLai Jiangshan 
399861b05a9fSLai Jiangshan 	/* sync prev_roots by simply freeing them */
39990c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
400061b05a9fSLai Jiangshan }
400161b05a9fSLai Jiangshan 
40021f5a21eeSLai Jiangshan static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
40035b22bbe7SLai Jiangshan 				  gpa_t vaddr, u64 access,
4004c50d8ae3SPaolo Bonzini 				  struct x86_exception *exception)
4005c50d8ae3SPaolo Bonzini {
4006c50d8ae3SPaolo Bonzini 	if (exception)
4007c50d8ae3SPaolo Bonzini 		exception->error_code = 0;
4008c59a0f57SLai Jiangshan 	return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
4009c50d8ae3SPaolo Bonzini }
4010c50d8ae3SPaolo Bonzini 
4011c50d8ae3SPaolo Bonzini static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4012c50d8ae3SPaolo Bonzini {
4013c50d8ae3SPaolo Bonzini 	/*
4014c50d8ae3SPaolo Bonzini 	 * A nested guest cannot use the MMIO cache if it is using nested
4015c50d8ae3SPaolo Bonzini 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4016c50d8ae3SPaolo Bonzini 	 */
4017c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
4018c50d8ae3SPaolo Bonzini 		return false;
4019c50d8ae3SPaolo Bonzini 
4020c50d8ae3SPaolo Bonzini 	if (direct)
4021c50d8ae3SPaolo Bonzini 		return vcpu_match_mmio_gpa(vcpu, addr);
4022c50d8ae3SPaolo Bonzini 
4023c50d8ae3SPaolo Bonzini 	return vcpu_match_mmio_gva(vcpu, addr);
4024c50d8ae3SPaolo Bonzini }
4025c50d8ae3SPaolo Bonzini 
402695fb5b02SBen Gardon /*
402795fb5b02SBen Gardon  * Return the level of the lowest level SPTE added to sptes.
402895fb5b02SBen Gardon  * That SPTE may be non-present.
4029c5c8c7c5SDavid Matlack  *
4030c5c8c7c5SDavid Matlack  * Must be called between walk_shadow_page_lockless_{begin,end}.
403195fb5b02SBen Gardon  */
403239b4d43eSSean Christopherson static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4033c50d8ae3SPaolo Bonzini {
4034c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
40352aa07893SSean Christopherson 	int leaf = -1;
403695fb5b02SBen Gardon 	u64 spte;
4037c50d8ae3SPaolo Bonzini 
403839b4d43eSSean Christopherson 	for (shadow_walk_init(&iterator, vcpu, addr),
403939b4d43eSSean Christopherson 	     *root_level = iterator.level;
4040c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&iterator);
4041c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&iterator, spte)) {
404295fb5b02SBen Gardon 		leaf = iterator.level;
4043c50d8ae3SPaolo Bonzini 		spte = mmu_spte_get_lockless(iterator.sptep);
4044c50d8ae3SPaolo Bonzini 
4045dde81f94SSean Christopherson 		sptes[leaf] = spte;
404695fb5b02SBen Gardon 	}
404795fb5b02SBen Gardon 
404895fb5b02SBen Gardon 	return leaf;
404995fb5b02SBen Gardon }
405095fb5b02SBen Gardon 
40519aa41879SSean Christopherson /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
405295fb5b02SBen Gardon static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
405395fb5b02SBen Gardon {
4054dde81f94SSean Christopherson 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
405595fb5b02SBen Gardon 	struct rsvd_bits_validate *rsvd_check;
405639b4d43eSSean Christopherson 	int root, leaf, level;
405795fb5b02SBen Gardon 	bool reserved = false;
405895fb5b02SBen Gardon 
4059c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_begin(vcpu);
4060c5c8c7c5SDavid Matlack 
406178fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu))
406239b4d43eSSean Christopherson 		leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
406395fb5b02SBen Gardon 	else
406439b4d43eSSean Christopherson 		leaf = get_walk(vcpu, addr, sptes, &root);
406595fb5b02SBen Gardon 
4066c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_end(vcpu);
4067c5c8c7c5SDavid Matlack 
40682aa07893SSean Christopherson 	if (unlikely(leaf < 0)) {
40692aa07893SSean Christopherson 		*sptep = 0ull;
40702aa07893SSean Christopherson 		return reserved;
40712aa07893SSean Christopherson 	}
40722aa07893SSean Christopherson 
40739aa41879SSean Christopherson 	*sptep = sptes[leaf];
40749aa41879SSean Christopherson 
40759aa41879SSean Christopherson 	/*
40769aa41879SSean Christopherson 	 * Skip reserved bits checks on the terminal leaf if it's not a valid
40779aa41879SSean Christopherson 	 * SPTE.  Note, this also (intentionally) skips MMIO SPTEs, which, by
40789aa41879SSean Christopherson 	 * design, always have reserved bits set.  The purpose of the checks is
40799aa41879SSean Christopherson 	 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
40809aa41879SSean Christopherson 	 */
40819aa41879SSean Christopherson 	if (!is_shadow_present_pte(sptes[leaf]))
40829aa41879SSean Christopherson 		leaf++;
408395fb5b02SBen Gardon 
408495fb5b02SBen Gardon 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
408595fb5b02SBen Gardon 
40869aa41879SSean Christopherson 	for (level = root; level >= leaf; level--)
4087961f8445SSean Christopherson 		reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4088c50d8ae3SPaolo Bonzini 
4089c50d8ae3SPaolo Bonzini 	if (reserved) {
4090bb4cdf3aSSean Christopherson 		pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4091c50d8ae3SPaolo Bonzini 		       __func__, addr);
409295fb5b02SBen Gardon 		for (level = root; level >= leaf; level--)
4093bb4cdf3aSSean Christopherson 			pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4094bb4cdf3aSSean Christopherson 			       sptes[level], level,
4095961f8445SSean Christopherson 			       get_rsvd_bits(rsvd_check, sptes[level], level));
4096c50d8ae3SPaolo Bonzini 	}
4097ddce6208SSean Christopherson 
4098c50d8ae3SPaolo Bonzini 	return reserved;
4099c50d8ae3SPaolo Bonzini }
4100c50d8ae3SPaolo Bonzini 
4101c50d8ae3SPaolo Bonzini static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4102c50d8ae3SPaolo Bonzini {
4103c50d8ae3SPaolo Bonzini 	u64 spte;
4104c50d8ae3SPaolo Bonzini 	bool reserved;
4105c50d8ae3SPaolo Bonzini 
4106c50d8ae3SPaolo Bonzini 	if (mmio_info_in_cache(vcpu, addr, direct))
4107c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4108c50d8ae3SPaolo Bonzini 
410995fb5b02SBen Gardon 	reserved = get_mmio_spte(vcpu, addr, &spte);
4110c50d8ae3SPaolo Bonzini 	if (WARN_ON(reserved))
4111c50d8ae3SPaolo Bonzini 		return -EINVAL;
4112c50d8ae3SPaolo Bonzini 
4113c50d8ae3SPaolo Bonzini 	if (is_mmio_spte(spte)) {
4114c50d8ae3SPaolo Bonzini 		gfn_t gfn = get_mmio_spte_gfn(spte);
41150a2b64c5SBen Gardon 		unsigned int access = get_mmio_spte_access(spte);
4116c50d8ae3SPaolo Bonzini 
4117c50d8ae3SPaolo Bonzini 		if (!check_mmio_spte(vcpu, spte))
4118c50d8ae3SPaolo Bonzini 			return RET_PF_INVALID;
4119c50d8ae3SPaolo Bonzini 
4120c50d8ae3SPaolo Bonzini 		if (direct)
4121c50d8ae3SPaolo Bonzini 			addr = 0;
4122c50d8ae3SPaolo Bonzini 
4123c50d8ae3SPaolo Bonzini 		trace_handle_mmio_page_fault(addr, gfn, access);
4124c50d8ae3SPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4125c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4126c50d8ae3SPaolo Bonzini 	}
4127c50d8ae3SPaolo Bonzini 
4128c50d8ae3SPaolo Bonzini 	/*
4129c50d8ae3SPaolo Bonzini 	 * If the page table is zapped by other cpus, let CPU fault again on
4130c50d8ae3SPaolo Bonzini 	 * the address.
4131c50d8ae3SPaolo Bonzini 	 */
4132c50d8ae3SPaolo Bonzini 	return RET_PF_RETRY;
4133c50d8ae3SPaolo Bonzini }
4134c50d8ae3SPaolo Bonzini 
4135c50d8ae3SPaolo Bonzini static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4136b8a5d551SPaolo Bonzini 					 struct kvm_page_fault *fault)
4137c50d8ae3SPaolo Bonzini {
4138b8a5d551SPaolo Bonzini 	if (unlikely(fault->rsvd))
4139c50d8ae3SPaolo Bonzini 		return false;
4140c50d8ae3SPaolo Bonzini 
4141b8a5d551SPaolo Bonzini 	if (!fault->present || !fault->write)
4142c50d8ae3SPaolo Bonzini 		return false;
4143c50d8ae3SPaolo Bonzini 
4144c50d8ae3SPaolo Bonzini 	/*
4145c50d8ae3SPaolo Bonzini 	 * guest is writing the page which is write tracked which can
4146c50d8ae3SPaolo Bonzini 	 * not be fixed by page fault handler.
4147c50d8ae3SPaolo Bonzini 	 */
41489d395a0aSBen Gardon 	if (kvm_slot_page_track_is_active(vcpu->kvm, fault->slot, fault->gfn, KVM_PAGE_TRACK_WRITE))
4149c50d8ae3SPaolo Bonzini 		return true;
4150c50d8ae3SPaolo Bonzini 
4151c50d8ae3SPaolo Bonzini 	return false;
4152c50d8ae3SPaolo Bonzini }
4153c50d8ae3SPaolo Bonzini 
4154c50d8ae3SPaolo Bonzini static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4155c50d8ae3SPaolo Bonzini {
4156c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
4157c50d8ae3SPaolo Bonzini 	u64 spte;
4158c50d8ae3SPaolo Bonzini 
4159c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
41603e44dce4SLai Jiangshan 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4161c50d8ae3SPaolo Bonzini 		clear_sp_write_flooding_count(iterator.sptep);
4162c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
4163c50d8ae3SPaolo Bonzini }
4164c50d8ae3SPaolo Bonzini 
41656f3c1fc5SLiang Zhang static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
41666f3c1fc5SLiang Zhang {
41676f3c1fc5SLiang Zhang 	/* make sure the token value is not 0 */
41686f3c1fc5SLiang Zhang 	u32 id = vcpu->arch.apf.id;
41696f3c1fc5SLiang Zhang 
41706f3c1fc5SLiang Zhang 	if (id << 12 == 0)
41716f3c1fc5SLiang Zhang 		vcpu->arch.apf.id = 1;
41726f3c1fc5SLiang Zhang 
41736f3c1fc5SLiang Zhang 	return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
41746f3c1fc5SLiang Zhang }
41756f3c1fc5SLiang Zhang 
4176e8c22266SVitaly Kuznetsov static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
41779f1a8526SSean Christopherson 				    gfn_t gfn)
4178c50d8ae3SPaolo Bonzini {
4179c50d8ae3SPaolo Bonzini 	struct kvm_arch_async_pf arch;
4180c50d8ae3SPaolo Bonzini 
41816f3c1fc5SLiang Zhang 	arch.token = alloc_apf_token(vcpu);
4182c50d8ae3SPaolo Bonzini 	arch.gfn = gfn;
4183347a0d0dSPaolo Bonzini 	arch.direct_map = vcpu->arch.mmu->root_role.direct;
4184d8dd54e0SSean Christopherson 	arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
4185c50d8ae3SPaolo Bonzini 
41869f1a8526SSean Christopherson 	return kvm_setup_async_pf(vcpu, cr2_or_gpa,
41879f1a8526SSean Christopherson 				  kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4188c50d8ae3SPaolo Bonzini }
4189c50d8ae3SPaolo Bonzini 
41908a009d5bSSean Christopherson void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
41918a009d5bSSean Christopherson {
41928a009d5bSSean Christopherson 	int r;
41938a009d5bSSean Christopherson 
41948a009d5bSSean Christopherson 	if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
41958a009d5bSSean Christopherson 	      work->wakeup_all)
41968a009d5bSSean Christopherson 		return;
41978a009d5bSSean Christopherson 
41988a009d5bSSean Christopherson 	r = kvm_mmu_reload(vcpu);
41998a009d5bSSean Christopherson 	if (unlikely(r))
42008a009d5bSSean Christopherson 		return;
42018a009d5bSSean Christopherson 
42028a009d5bSSean Christopherson 	if (!vcpu->arch.mmu->root_role.direct &&
42038a009d5bSSean Christopherson 	      work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
42048a009d5bSSean Christopherson 		return;
42058a009d5bSSean Christopherson 
42068a009d5bSSean Christopherson 	kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
42078a009d5bSSean Christopherson }
42088a009d5bSSean Christopherson 
4209ba6e3fe2SDavid Matlack static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4210c50d8ae3SPaolo Bonzini {
4211e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
4212c50d8ae3SPaolo Bonzini 	bool async;
4213c50d8ae3SPaolo Bonzini 
4214e0c37868SSean Christopherson 	/*
4215e0c37868SSean Christopherson 	 * Retry the page fault if the gfn hit a memslot that is being deleted
4216e0c37868SSean Christopherson 	 * or moved.  This ensures any existing SPTEs for the old memslot will
4217e0c37868SSean Christopherson 	 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4218e0c37868SSean Christopherson 	 */
4219e0c37868SSean Christopherson 	if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
42205276c616SSean Christopherson 		return RET_PF_RETRY;
4221e0c37868SSean Christopherson 
42229cc13d60SMaxim Levitsky 	if (!kvm_is_visible_memslot(slot)) {
4223c36b7150SPaolo Bonzini 		/* Don't expose private memslots to L2. */
42249cc13d60SMaxim Levitsky 		if (is_guest_mode(vcpu)) {
4225e710c5f6SDavid Matlack 			fault->slot = NULL;
42263647cd04SPaolo Bonzini 			fault->pfn = KVM_PFN_NOSLOT;
42273647cd04SPaolo Bonzini 			fault->map_writable = false;
42285276c616SSean Christopherson 			return RET_PF_CONTINUE;
4229c50d8ae3SPaolo Bonzini 		}
42309cc13d60SMaxim Levitsky 		/*
42319cc13d60SMaxim Levitsky 		 * If the APIC access page exists but is disabled, go directly
42329cc13d60SMaxim Levitsky 		 * to emulation without caching the MMIO access or creating a
42339cc13d60SMaxim Levitsky 		 * MMIO SPTE.  That way the cache doesn't need to be purged
42349cc13d60SMaxim Levitsky 		 * when the AVIC is re-enabled.
42359cc13d60SMaxim Levitsky 		 */
42369cc13d60SMaxim Levitsky 		if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
42375276c616SSean Christopherson 		    !kvm_apicv_activated(vcpu->kvm))
42385276c616SSean Christopherson 			return RET_PF_EMULATE;
42399cc13d60SMaxim Levitsky 	}
4240c50d8ae3SPaolo Bonzini 
4241c50d8ae3SPaolo Bonzini 	async = false;
4242c8b88b33SPeter Xu 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, false, &async,
42433647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
42443647cd04SPaolo Bonzini 					  &fault->hva);
4245c50d8ae3SPaolo Bonzini 	if (!async)
42465276c616SSean Christopherson 		return RET_PF_CONTINUE; /* *pfn has correct page already */
4247c50d8ae3SPaolo Bonzini 
42482839180cSPaolo Bonzini 	if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
42493647cd04SPaolo Bonzini 		trace_kvm_try_async_get_page(fault->addr, fault->gfn);
42503647cd04SPaolo Bonzini 		if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
42511685c0f3SMingwei Zhang 			trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4252c50d8ae3SPaolo Bonzini 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
42535276c616SSean Christopherson 			return RET_PF_RETRY;
42545276c616SSean Christopherson 		} else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn)) {
42555276c616SSean Christopherson 			return RET_PF_RETRY;
42565276c616SSean Christopherson 		}
4257c50d8ae3SPaolo Bonzini 	}
4258c50d8ae3SPaolo Bonzini 
425976657687SPeter Xu 	/*
426076657687SPeter Xu 	 * Allow gup to bail on pending non-fatal signals when it's also allowed
426176657687SPeter Xu 	 * to wait for IO.  Note, gup always bails if it is unable to quickly
426276657687SPeter Xu 	 * get a page and a fatal signal, i.e. SIGKILL, is pending.
426376657687SPeter Xu 	 */
426476657687SPeter Xu 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, true, NULL,
42653647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
42663647cd04SPaolo Bonzini 					  &fault->hva);
42675276c616SSean Christopherson 	return RET_PF_CONTINUE;
4268c50d8ae3SPaolo Bonzini }
4269c50d8ae3SPaolo Bonzini 
4270354c908cSDavid Matlack static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
4271354c908cSDavid Matlack 			   unsigned int access)
4272ba6e3fe2SDavid Matlack {
427356c3a4e4SDavid Matlack 	int ret;
427456c3a4e4SDavid Matlack 
4275ba6e3fe2SDavid Matlack 	fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4276ba6e3fe2SDavid Matlack 	smp_rmb();
4277ba6e3fe2SDavid Matlack 
427856c3a4e4SDavid Matlack 	ret = __kvm_faultin_pfn(vcpu, fault);
427956c3a4e4SDavid Matlack 	if (ret != RET_PF_CONTINUE)
428056c3a4e4SDavid Matlack 		return ret;
428156c3a4e4SDavid Matlack 
428256c3a4e4SDavid Matlack 	if (unlikely(is_error_pfn(fault->pfn)))
4283cd08d178SDavid Matlack 		return kvm_handle_error_pfn(vcpu, fault);
428456c3a4e4SDavid Matlack 
4285354c908cSDavid Matlack 	if (unlikely(!fault->slot))
4286354c908cSDavid Matlack 		return kvm_handle_noslot_fault(vcpu, fault, access);
4287354c908cSDavid Matlack 
428856c3a4e4SDavid Matlack 	return RET_PF_CONTINUE;
4289ba6e3fe2SDavid Matlack }
4290ba6e3fe2SDavid Matlack 
4291a955cad8SSean Christopherson /*
4292a955cad8SSean Christopherson  * Returns true if the page fault is stale and needs to be retried, i.e. if the
4293a955cad8SSean Christopherson  * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4294a955cad8SSean Christopherson  */
4295a955cad8SSean Christopherson static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4296ba6e3fe2SDavid Matlack 				struct kvm_page_fault *fault)
4297a955cad8SSean Christopherson {
4298b9e5603cSPaolo Bonzini 	struct kvm_mmu_page *sp = to_shadow_page(vcpu->arch.mmu->root.hpa);
429918c841e1SSean Christopherson 
430018c841e1SSean Christopherson 	/* Special roots, e.g. pae_root, are not backed by shadow pages. */
430118c841e1SSean Christopherson 	if (sp && is_obsolete_sp(vcpu->kvm, sp))
430218c841e1SSean Christopherson 		return true;
430318c841e1SSean Christopherson 
430418c841e1SSean Christopherson 	/*
430518c841e1SSean Christopherson 	 * Roots without an associated shadow page are considered invalid if
430618c841e1SSean Christopherson 	 * there is a pending request to free obsolete roots.  The request is
430718c841e1SSean Christopherson 	 * only a hint that the current root _may_ be obsolete and needs to be
430818c841e1SSean Christopherson 	 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
430918c841e1SSean Christopherson 	 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
431018c841e1SSean Christopherson 	 * to reload even if no vCPU is actively using the root.
431118c841e1SSean Christopherson 	 */
4312527d5cd7SSean Christopherson 	if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4313a955cad8SSean Christopherson 		return true;
4314a955cad8SSean Christopherson 
4315a955cad8SSean Christopherson 	return fault->slot &&
4316ba6e3fe2SDavid Matlack 	       mmu_invalidate_retry_hva(vcpu->kvm, fault->mmu_seq, fault->hva);
4317a955cad8SSean Christopherson }
4318a955cad8SSean Christopherson 
43194326e57eSPaolo Bonzini static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4320c50d8ae3SPaolo Bonzini {
432183f06fa7SSean Christopherson 	int r;
4322c50d8ae3SPaolo Bonzini 
4323b8a5d551SPaolo Bonzini 	if (page_fault_handle_page_track(vcpu, fault))
4324c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4325c50d8ae3SPaolo Bonzini 
43263c8ad5a6SPaolo Bonzini 	r = fast_page_fault(vcpu, fault);
4327c4371c2aSSean Christopherson 	if (r != RET_PF_INVALID)
4328c4371c2aSSean Christopherson 		return r;
432983291445SSean Christopherson 
4330378f5cd6SSean Christopherson 	r = mmu_topup_memory_caches(vcpu, false);
4331c50d8ae3SPaolo Bonzini 	if (r)
4332c50d8ae3SPaolo Bonzini 		return r;
4333c50d8ae3SPaolo Bonzini 
4334354c908cSDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
43355276c616SSean Christopherson 	if (r != RET_PF_CONTINUE)
4336367fd790SSean Christopherson 		return r;
4337367fd790SSean Christopherson 
4338367fd790SSean Christopherson 	r = RET_PF_RETRY;
4339531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
4340a2855afcSBen Gardon 
4341ba6e3fe2SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
4342367fd790SSean Christopherson 		goto out_unlock;
4343a955cad8SSean Christopherson 
43447bd7ded6SSean Christopherson 	r = make_mmu_pages_available(vcpu);
43457bd7ded6SSean Christopherson 	if (r)
4346367fd790SSean Christopherson 		goto out_unlock;
4347bb18842eSBen Gardon 
43486c882ef4SDavid Matlack 	r = direct_map(vcpu, fault);
43490f90e1c1SSean Christopherson 
4350367fd790SSean Christopherson out_unlock:
4351531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
43523647cd04SPaolo Bonzini 	kvm_release_pfn_clean(fault->pfn);
4353367fd790SSean Christopherson 	return r;
4354c50d8ae3SPaolo Bonzini }
4355c50d8ae3SPaolo Bonzini 
4356c501040aSPaolo Bonzini static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4357c501040aSPaolo Bonzini 				struct kvm_page_fault *fault)
43580f90e1c1SSean Christopherson {
43594326e57eSPaolo Bonzini 	pgprintk("%s: gva %lx error %x\n", __func__, fault->addr, fault->error_code);
43600f90e1c1SSean Christopherson 
43610f90e1c1SSean Christopherson 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
43624326e57eSPaolo Bonzini 	fault->max_level = PG_LEVEL_2M;
43634326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
43640f90e1c1SSean Christopherson }
43650f90e1c1SSean Christopherson 
4366c50d8ae3SPaolo Bonzini int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4367c50d8ae3SPaolo Bonzini 				u64 fault_address, char *insn, int insn_len)
4368c50d8ae3SPaolo Bonzini {
4369c50d8ae3SPaolo Bonzini 	int r = 1;
43709ce372b3SVitaly Kuznetsov 	u32 flags = vcpu->arch.apf.host_apf_flags;
4371c50d8ae3SPaolo Bonzini 
4372736c291cSSean Christopherson #ifndef CONFIG_X86_64
4373736c291cSSean Christopherson 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4374736c291cSSean Christopherson 	if (WARN_ON_ONCE(fault_address >> 32))
4375736c291cSSean Christopherson 		return -EFAULT;
4376736c291cSSean Christopherson #endif
4377736c291cSSean Christopherson 
4378c50d8ae3SPaolo Bonzini 	vcpu->arch.l1tf_flush_l1d = true;
43799ce372b3SVitaly Kuznetsov 	if (!flags) {
4380faa03b39SWonhyuk Yang 		trace_kvm_page_fault(vcpu, fault_address, error_code);
4381c50d8ae3SPaolo Bonzini 
4382c50d8ae3SPaolo Bonzini 		if (kvm_event_needs_reinjection(vcpu))
4383c50d8ae3SPaolo Bonzini 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4384c50d8ae3SPaolo Bonzini 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4385c50d8ae3SPaolo Bonzini 				insn_len);
43869ce372b3SVitaly Kuznetsov 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
438768fd66f1SVitaly Kuznetsov 		vcpu->arch.apf.host_apf_flags = 0;
4388c50d8ae3SPaolo Bonzini 		local_irq_disable();
43896bca69adSThomas Gleixner 		kvm_async_pf_task_wait_schedule(fault_address);
4390c50d8ae3SPaolo Bonzini 		local_irq_enable();
43919ce372b3SVitaly Kuznetsov 	} else {
43929ce372b3SVitaly Kuznetsov 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4393c50d8ae3SPaolo Bonzini 	}
43949ce372b3SVitaly Kuznetsov 
4395c50d8ae3SPaolo Bonzini 	return r;
4396c50d8ae3SPaolo Bonzini }
4397c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4398c50d8ae3SPaolo Bonzini 
43999aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
44009aa8ab43SDavid Matlack static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
44019aa8ab43SDavid Matlack 				  struct kvm_page_fault *fault)
44029aa8ab43SDavid Matlack {
44039aa8ab43SDavid Matlack 	int r;
44049aa8ab43SDavid Matlack 
44059aa8ab43SDavid Matlack 	if (page_fault_handle_page_track(vcpu, fault))
44069aa8ab43SDavid Matlack 		return RET_PF_EMULATE;
44079aa8ab43SDavid Matlack 
44089aa8ab43SDavid Matlack 	r = fast_page_fault(vcpu, fault);
44099aa8ab43SDavid Matlack 	if (r != RET_PF_INVALID)
44109aa8ab43SDavid Matlack 		return r;
44119aa8ab43SDavid Matlack 
44129aa8ab43SDavid Matlack 	r = mmu_topup_memory_caches(vcpu, false);
44139aa8ab43SDavid Matlack 	if (r)
44149aa8ab43SDavid Matlack 		return r;
44159aa8ab43SDavid Matlack 
44169aa8ab43SDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
44179aa8ab43SDavid Matlack 	if (r != RET_PF_CONTINUE)
44189aa8ab43SDavid Matlack 		return r;
44199aa8ab43SDavid Matlack 
44209aa8ab43SDavid Matlack 	r = RET_PF_RETRY;
44219aa8ab43SDavid Matlack 	read_lock(&vcpu->kvm->mmu_lock);
44229aa8ab43SDavid Matlack 
44239aa8ab43SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
44249aa8ab43SDavid Matlack 		goto out_unlock;
44259aa8ab43SDavid Matlack 
44269aa8ab43SDavid Matlack 	r = kvm_tdp_mmu_map(vcpu, fault);
44279aa8ab43SDavid Matlack 
44289aa8ab43SDavid Matlack out_unlock:
44299aa8ab43SDavid Matlack 	read_unlock(&vcpu->kvm->mmu_lock);
44309aa8ab43SDavid Matlack 	kvm_release_pfn_clean(fault->pfn);
44319aa8ab43SDavid Matlack 	return r;
44329aa8ab43SDavid Matlack }
44339aa8ab43SDavid Matlack #endif
44349aa8ab43SDavid Matlack 
4435c501040aSPaolo Bonzini int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4436c50d8ae3SPaolo Bonzini {
4437d5e90a69SSean Christopherson 	/*
4438d5e90a69SSean Christopherson 	 * If the guest's MTRRs may be used to compute the "real" memtype,
4439d5e90a69SSean Christopherson 	 * restrict the mapping level to ensure KVM uses a consistent memtype
4440d5e90a69SSean Christopherson 	 * across the entire mapping.  If the host MTRRs are ignored by TDP
4441d5e90a69SSean Christopherson 	 * (shadow_memtype_mask is non-zero), and the VM has non-coherent DMA
4442d5e90a69SSean Christopherson 	 * (DMA doesn't snoop CPU caches), KVM's ABI is to honor the memtype
4443d5e90a69SSean Christopherson 	 * from the guest's MTRRs so that guest accesses to memory that is
4444d5e90a69SSean Christopherson 	 * DMA'd aren't cached against the guest's wishes.
4445d5e90a69SSean Christopherson 	 *
4446d5e90a69SSean Christopherson 	 * Note, KVM may still ultimately ignore guest MTRRs for certain PFNs,
4447d5e90a69SSean Christopherson 	 * e.g. KVM will force UC memtype for host MMIO.
4448d5e90a69SSean Christopherson 	 */
4449d5e90a69SSean Christopherson 	if (shadow_memtype_mask && kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
4450d5e90a69SSean Christopherson 		for ( ; fault->max_level > PG_LEVEL_4K; --fault->max_level) {
44514326e57eSPaolo Bonzini 			int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
4452c667a3baSHou Wenlong 			gfn_t base = gfn_round_for_level(fault->gfn,
4453c667a3baSHou Wenlong 							 fault->max_level);
4454c50d8ae3SPaolo Bonzini 
4455cb9b88c6SSean Christopherson 			if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4456cb9b88c6SSean Christopherson 				break;
4457d5e90a69SSean Christopherson 		}
4458c50d8ae3SPaolo Bonzini 	}
4459c50d8ae3SPaolo Bonzini 
44609aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
44619aa8ab43SDavid Matlack 	if (tdp_mmu_enabled)
44629aa8ab43SDavid Matlack 		return kvm_tdp_mmu_page_fault(vcpu, fault);
44639aa8ab43SDavid Matlack #endif
44649aa8ab43SDavid Matlack 
44654326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
4466c50d8ae3SPaolo Bonzini }
4467c50d8ae3SPaolo Bonzini 
446884a16226SSean Christopherson static void nonpaging_init_context(struct kvm_mmu *context)
4469c50d8ae3SPaolo Bonzini {
4470c50d8ae3SPaolo Bonzini 	context->page_fault = nonpaging_page_fault;
4471c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4472c50d8ae3SPaolo Bonzini 	context->sync_page = nonpaging_sync_page;
44735efac074SPaolo Bonzini 	context->invlpg = NULL;
4474c50d8ae3SPaolo Bonzini }
4475c50d8ae3SPaolo Bonzini 
4476be01e8e2SSean Christopherson static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
44770be44352SSean Christopherson 				  union kvm_mmu_page_role role)
44780be44352SSean Christopherson {
4479be01e8e2SSean Christopherson 	return (role.direct || pgd == root->pgd) &&
44805499ea73SPaolo Bonzini 	       VALID_PAGE(root->hpa) &&
4481e47c4aeeSSean Christopherson 	       role.word == to_shadow_page(root->hpa)->role.word;
44820be44352SSean Christopherson }
44830be44352SSean Christopherson 
4484c50d8ae3SPaolo Bonzini /*
44855499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available,
44865499ea73SPaolo Bonzini  * and insert the current root as the MRU in the cache.
44875499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root and
44885499ea73SPaolo Bonzini  * true is returned.
44895499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid, the LRU root is
44905499ea73SPaolo Bonzini  * evicted to make room for the current root, and false is returned.
4491c50d8ae3SPaolo Bonzini  */
44925499ea73SPaolo Bonzini static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
44935499ea73SPaolo Bonzini 					      gpa_t new_pgd,
4494c50d8ae3SPaolo Bonzini 					      union kvm_mmu_page_role new_role)
4495c50d8ae3SPaolo Bonzini {
4496c50d8ae3SPaolo Bonzini 	uint i;
4497c50d8ae3SPaolo Bonzini 
4498b9e5603cSPaolo Bonzini 	if (is_root_usable(&mmu->root, new_pgd, new_role))
44990be44352SSean Christopherson 		return true;
45000be44352SSean Christopherson 
4501c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
45025499ea73SPaolo Bonzini 		/*
45035499ea73SPaolo Bonzini 		 * The swaps end up rotating the cache like this:
45045499ea73SPaolo Bonzini 		 *   C   0 1 2 3   (on entry to the function)
45055499ea73SPaolo Bonzini 		 *   0   C 1 2 3
45065499ea73SPaolo Bonzini 		 *   1   C 0 2 3
45075499ea73SPaolo Bonzini 		 *   2   C 0 1 3
45085499ea73SPaolo Bonzini 		 *   3   C 0 1 2   (on exit from the loop)
45095499ea73SPaolo Bonzini 		 */
4510b9e5603cSPaolo Bonzini 		swap(mmu->root, mmu->prev_roots[i]);
4511b9e5603cSPaolo Bonzini 		if (is_root_usable(&mmu->root, new_pgd, new_role))
45125499ea73SPaolo Bonzini 			return true;
4513c50d8ae3SPaolo Bonzini 	}
4514c50d8ae3SPaolo Bonzini 
45155499ea73SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
45165499ea73SPaolo Bonzini 	return false;
4517c50d8ae3SPaolo Bonzini }
4518c50d8ae3SPaolo Bonzini 
4519c50d8ae3SPaolo Bonzini /*
45205499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available.
45215499ea73SPaolo Bonzini  * On entry, mmu->root is invalid.
45225499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
45235499ea73SPaolo Bonzini  * of the cache becomes invalid, and true is returned.
45245499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid and false is returned.
45255499ea73SPaolo Bonzini  */
45265499ea73SPaolo Bonzini static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
45275499ea73SPaolo Bonzini 					     gpa_t new_pgd,
45285499ea73SPaolo Bonzini 					     union kvm_mmu_page_role new_role)
45295499ea73SPaolo Bonzini {
45305499ea73SPaolo Bonzini 	uint i;
45315499ea73SPaolo Bonzini 
45325499ea73SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
45335499ea73SPaolo Bonzini 		if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
45345499ea73SPaolo Bonzini 			goto hit;
45355499ea73SPaolo Bonzini 
45365499ea73SPaolo Bonzini 	return false;
45375499ea73SPaolo Bonzini 
45385499ea73SPaolo Bonzini hit:
45395499ea73SPaolo Bonzini 	swap(mmu->root, mmu->prev_roots[i]);
45405499ea73SPaolo Bonzini 	/* Bubble up the remaining roots.  */
45415499ea73SPaolo Bonzini 	for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
45425499ea73SPaolo Bonzini 		mmu->prev_roots[i] = mmu->prev_roots[i + 1];
45435499ea73SPaolo Bonzini 	mmu->prev_roots[i].hpa = INVALID_PAGE;
45445499ea73SPaolo Bonzini 	return true;
45455499ea73SPaolo Bonzini }
45465499ea73SPaolo Bonzini 
45475499ea73SPaolo Bonzini static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
45485499ea73SPaolo Bonzini 			    gpa_t new_pgd, union kvm_mmu_page_role new_role)
45495499ea73SPaolo Bonzini {
45505499ea73SPaolo Bonzini 	/*
45515499ea73SPaolo Bonzini 	 * For now, limit the caching to 64-bit hosts+VMs in order to avoid
4552c50d8ae3SPaolo Bonzini 	 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4553c50d8ae3SPaolo Bonzini 	 * later if necessary.
4554c50d8ae3SPaolo Bonzini 	 */
45555499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa) && !to_shadow_page(mmu->root.hpa))
45565499ea73SPaolo Bonzini 		kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4557c50d8ae3SPaolo Bonzini 
45585499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa))
45595499ea73SPaolo Bonzini 		return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
45605499ea73SPaolo Bonzini 	else
45615499ea73SPaolo Bonzini 		return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4562c50d8ae3SPaolo Bonzini }
4563c50d8ae3SPaolo Bonzini 
4564d2e5f333SPaolo Bonzini void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4565c50d8ae3SPaolo Bonzini {
45660c1c92f1SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
45677a458f0eSPaolo Bonzini 	union kvm_mmu_page_role new_role = mmu->root_role;
45680c1c92f1SPaolo Bonzini 
4569a7e48ef7SWei Liu 	/*
4570a7e48ef7SWei Liu 	 * Return immediately if no usable root was found, kvm_mmu_reload()
4571a7e48ef7SWei Liu 	 * will establish a valid root prior to the next VM-Enter.
4572a7e48ef7SWei Liu 	 */
4573a7e48ef7SWei Liu 	if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role))
4574b869855bSSean Christopherson 		return;
4575c50d8ae3SPaolo Bonzini 
4576c50d8ae3SPaolo Bonzini 	/*
4577b869855bSSean Christopherson 	 * It's possible that the cached previous root page is obsolete because
4578b869855bSSean Christopherson 	 * of a change in the MMU generation number. However, changing the
4579527d5cd7SSean Christopherson 	 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4580527d5cd7SSean Christopherson 	 * which will free the root set here and allocate a new one.
4581b869855bSSean Christopherson 	 */
4582b869855bSSean Christopherson 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4583b869855bSSean Christopherson 
4584b5129100SSean Christopherson 	if (force_flush_and_sync_on_reuse) {
4585b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4586b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4587b5129100SSean Christopherson 	}
4588b869855bSSean Christopherson 
4589b869855bSSean Christopherson 	/*
4590b869855bSSean Christopherson 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4591b869855bSSean Christopherson 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
4592b869855bSSean Christopherson 	 * valid. So clear any cached MMIO info even when we don't need to sync
4593b869855bSSean Christopherson 	 * the shadow page tables.
4594c50d8ae3SPaolo Bonzini 	 */
4595c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4596c50d8ae3SPaolo Bonzini 
4597daa5b6c1SBen Gardon 	/*
4598daa5b6c1SBen Gardon 	 * If this is a direct root page, it doesn't have a write flooding
4599daa5b6c1SBen Gardon 	 * count. Otherwise, clear the write flooding count.
4600daa5b6c1SBen Gardon 	 */
4601daa5b6c1SBen Gardon 	if (!new_role.direct)
4602daa5b6c1SBen Gardon 		__clear_sp_write_flooding_count(
4603b9e5603cSPaolo Bonzini 				to_shadow_page(vcpu->arch.mmu->root.hpa));
4604c50d8ae3SPaolo Bonzini }
4605be01e8e2SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4606c50d8ae3SPaolo Bonzini 
4607c50d8ae3SPaolo Bonzini static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4608c50d8ae3SPaolo Bonzini {
4609c50d8ae3SPaolo Bonzini 	return kvm_read_cr3(vcpu);
4610c50d8ae3SPaolo Bonzini }
4611c50d8ae3SPaolo Bonzini 
4612c50d8ae3SPaolo Bonzini static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4613c3e5e415SLai Jiangshan 			   unsigned int access)
4614c50d8ae3SPaolo Bonzini {
4615c50d8ae3SPaolo Bonzini 	if (unlikely(is_mmio_spte(*sptep))) {
4616c50d8ae3SPaolo Bonzini 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4617c50d8ae3SPaolo Bonzini 			mmu_spte_clear_no_track(sptep);
4618c50d8ae3SPaolo Bonzini 			return true;
4619c50d8ae3SPaolo Bonzini 		}
4620c50d8ae3SPaolo Bonzini 
4621c50d8ae3SPaolo Bonzini 		mark_mmio_spte(vcpu, sptep, gfn, access);
4622c50d8ae3SPaolo Bonzini 		return true;
4623c50d8ae3SPaolo Bonzini 	}
4624c50d8ae3SPaolo Bonzini 
4625c50d8ae3SPaolo Bonzini 	return false;
4626c50d8ae3SPaolo Bonzini }
4627c50d8ae3SPaolo Bonzini 
4628c50d8ae3SPaolo Bonzini #define PTTYPE_EPT 18 /* arbitrary */
4629c50d8ae3SPaolo Bonzini #define PTTYPE PTTYPE_EPT
4630c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4631c50d8ae3SPaolo Bonzini #undef PTTYPE
4632c50d8ae3SPaolo Bonzini 
4633c50d8ae3SPaolo Bonzini #define PTTYPE 64
4634c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4635c50d8ae3SPaolo Bonzini #undef PTTYPE
4636c50d8ae3SPaolo Bonzini 
4637c50d8ae3SPaolo Bonzini #define PTTYPE 32
4638c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4639c50d8ae3SPaolo Bonzini #undef PTTYPE
4640c50d8ae3SPaolo Bonzini 
4641c50d8ae3SPaolo Bonzini static void
4642b705a277SSean Christopherson __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
46435b7f575cSSean Christopherson 			u64 pa_bits_rsvd, int level, bool nx, bool gbpages,
4644c50d8ae3SPaolo Bonzini 			bool pse, bool amd)
4645c50d8ae3SPaolo Bonzini {
4646c50d8ae3SPaolo Bonzini 	u64 gbpages_bit_rsvd = 0;
4647c50d8ae3SPaolo Bonzini 	u64 nonleaf_bit8_rsvd = 0;
46485b7f575cSSean Christopherson 	u64 high_bits_rsvd;
4649c50d8ae3SPaolo Bonzini 
4650c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = 0;
4651c50d8ae3SPaolo Bonzini 
4652c50d8ae3SPaolo Bonzini 	if (!gbpages)
4653c50d8ae3SPaolo Bonzini 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4654c50d8ae3SPaolo Bonzini 
46555b7f575cSSean Christopherson 	if (level == PT32E_ROOT_LEVEL)
46565b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
46575b7f575cSSean Christopherson 	else
46585b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
46595b7f575cSSean Christopherson 
46605b7f575cSSean Christopherson 	/* Note, NX doesn't exist in PDPTEs, this is handled below. */
46615b7f575cSSean Christopherson 	if (!nx)
46625b7f575cSSean Christopherson 		high_bits_rsvd |= rsvd_bits(63, 63);
46635b7f575cSSean Christopherson 
4664c50d8ae3SPaolo Bonzini 	/*
4665c50d8ae3SPaolo Bonzini 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4666c50d8ae3SPaolo Bonzini 	 * leaf entries) on AMD CPUs only.
4667c50d8ae3SPaolo Bonzini 	 */
4668c50d8ae3SPaolo Bonzini 	if (amd)
4669c50d8ae3SPaolo Bonzini 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4670c50d8ae3SPaolo Bonzini 
4671c50d8ae3SPaolo Bonzini 	switch (level) {
4672c50d8ae3SPaolo Bonzini 	case PT32_ROOT_LEVEL:
4673c50d8ae3SPaolo Bonzini 		/* no rsvd bits for 2 level 4K page table entries */
4674c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4675c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4676c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4677c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4678c50d8ae3SPaolo Bonzini 
4679c50d8ae3SPaolo Bonzini 		if (!pse) {
4680c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4681c50d8ae3SPaolo Bonzini 			break;
4682c50d8ae3SPaolo Bonzini 		}
4683c50d8ae3SPaolo Bonzini 
4684c50d8ae3SPaolo Bonzini 		if (is_cpuid_PSE36())
4685c50d8ae3SPaolo Bonzini 			/* 36bits PSE 4MB page */
4686c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4687c50d8ae3SPaolo Bonzini 		else
4688c50d8ae3SPaolo Bonzini 			/* 32 bits PSE 4MB page */
4689c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4690c50d8ae3SPaolo Bonzini 		break;
4691c50d8ae3SPaolo Bonzini 	case PT32E_ROOT_LEVEL:
46925b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
46935b7f575cSSean Christopherson 						   high_bits_rsvd |
46945b7f575cSSean Christopherson 						   rsvd_bits(5, 8) |
46955b7f575cSSean Christopherson 						   rsvd_bits(1, 2);	/* PDPTE */
46965b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;	/* PDE */
46975b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;	/* PTE */
46985b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4699c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20);	/* large page */
4700c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4701c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4702c50d8ae3SPaolo Bonzini 		break;
4703c50d8ae3SPaolo Bonzini 	case PT64_ROOT_5LEVEL:
47045b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
47055b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
47065b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
4707c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][4] =
4708c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][4];
4709df561f66SGustavo A. R. Silva 		fallthrough;
4710c50d8ae3SPaolo Bonzini 	case PT64_ROOT_4LEVEL:
47115b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
47125b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
47135b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
47145b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
47155b7f575cSSean Christopherson 						   gbpages_bit_rsvd;
47165b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
47175b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4718c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][3] =
4719c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][3];
47205b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
47215b7f575cSSean Christopherson 						   gbpages_bit_rsvd |
4722c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 29);
47235b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4724c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20); /* large page */
4725c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4726c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4727c50d8ae3SPaolo Bonzini 		break;
4728c50d8ae3SPaolo Bonzini 	}
4729c50d8ae3SPaolo Bonzini }
4730c50d8ae3SPaolo Bonzini 
473127de9250SSean Christopherson static bool guest_can_use_gbpages(struct kvm_vcpu *vcpu)
473227de9250SSean Christopherson {
473327de9250SSean Christopherson 	/*
473427de9250SSean Christopherson 	 * If TDP is enabled, let the guest use GBPAGES if they're supported in
473527de9250SSean Christopherson 	 * hardware.  The hardware page walker doesn't let KVM disable GBPAGES,
473627de9250SSean Christopherson 	 * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
473727de9250SSean Christopherson 	 * walk for performance and complexity reasons.  Not to mention KVM
473827de9250SSean Christopherson 	 * _can't_ solve the problem because GVA->GPA walks aren't visible to
473927de9250SSean Christopherson 	 * KVM once a TDP translation is installed.  Mimic hardware behavior so
474027de9250SSean Christopherson 	 * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
474127de9250SSean Christopherson 	 */
474227de9250SSean Christopherson 	return tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
474327de9250SSean Christopherson 			     guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES);
474427de9250SSean Christopherson }
474527de9250SSean Christopherson 
4746c919e881SKai Huang static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4747c50d8ae3SPaolo Bonzini 					struct kvm_mmu *context)
4748c50d8ae3SPaolo Bonzini {
4749b705a277SSean Christopherson 	__reset_rsvds_bits_mask(&context->guest_rsvd_check,
47505b7f575cSSean Christopherson 				vcpu->arch.reserved_gpa_bits,
47514d25502aSPaolo Bonzini 				context->cpu_role.base.level, is_efer_nx(context),
475227de9250SSean Christopherson 				guest_can_use_gbpages(vcpu),
47534e9c0d80SSean Christopherson 				is_cr4_pse(context),
475423493d0aSSean Christopherson 				guest_cpuid_is_amd_or_hygon(vcpu));
4755c50d8ae3SPaolo Bonzini }
4756c50d8ae3SPaolo Bonzini 
4757c50d8ae3SPaolo Bonzini static void
4758c50d8ae3SPaolo Bonzini __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
475984ea5c09SLai Jiangshan 			    u64 pa_bits_rsvd, bool execonly, int huge_page_level)
4760c50d8ae3SPaolo Bonzini {
47615b7f575cSSean Christopherson 	u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
476284ea5c09SLai Jiangshan 	u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
4763c50d8ae3SPaolo Bonzini 	u64 bad_mt_xwr;
4764c50d8ae3SPaolo Bonzini 
476584ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_1G)
476684ea5c09SLai Jiangshan 		large_1g_rsvd = rsvd_bits(7, 7);
476784ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_2M)
476884ea5c09SLai Jiangshan 		large_2m_rsvd = rsvd_bits(7, 7);
476984ea5c09SLai Jiangshan 
47705b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
47715b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
477284ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
477384ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
47745b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4775c50d8ae3SPaolo Bonzini 
4776c50d8ae3SPaolo Bonzini 	/* large page */
4777c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4778c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
477984ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
478084ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
4781c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4782c50d8ae3SPaolo Bonzini 
4783c50d8ae3SPaolo Bonzini 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
4784c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
4785c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
4786c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
4787c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
4788c50d8ae3SPaolo Bonzini 	if (!execonly) {
4789c50d8ae3SPaolo Bonzini 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
4790c50d8ae3SPaolo Bonzini 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4791c50d8ae3SPaolo Bonzini 	}
4792c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
4793c50d8ae3SPaolo Bonzini }
4794c50d8ae3SPaolo Bonzini 
4795c50d8ae3SPaolo Bonzini static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
479684ea5c09SLai Jiangshan 		struct kvm_mmu *context, bool execonly, int huge_page_level)
4797c50d8ae3SPaolo Bonzini {
4798c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
479984ea5c09SLai Jiangshan 				    vcpu->arch.reserved_gpa_bits, execonly,
480084ea5c09SLai Jiangshan 				    huge_page_level);
4801c50d8ae3SPaolo Bonzini }
4802c50d8ae3SPaolo Bonzini 
48036f8e65a6SSean Christopherson static inline u64 reserved_hpa_bits(void)
48046f8e65a6SSean Christopherson {
48056f8e65a6SSean Christopherson 	return rsvd_bits(shadow_phys_bits, 63);
48066f8e65a6SSean Christopherson }
48076f8e65a6SSean Christopherson 
4808c50d8ae3SPaolo Bonzini /*
4809c50d8ae3SPaolo Bonzini  * the page table on host is the shadow page table for the page
4810c50d8ae3SPaolo Bonzini  * table in guest or amd nested guest, its mmu features completely
4811c50d8ae3SPaolo Bonzini  * follow the features in guest.
4812c50d8ae3SPaolo Bonzini  */
481316be1d12SSean Christopherson static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
481416be1d12SSean Christopherson 					struct kvm_mmu *context)
4815c50d8ae3SPaolo Bonzini {
48168c985b2dSSean Christopherson 	/* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
48178c985b2dSSean Christopherson 	bool is_amd = true;
48188c985b2dSSean Christopherson 	/* KVM doesn't use 2-level page tables for the shadow MMU. */
48198c985b2dSSean Christopherson 	bool is_pse = false;
4820c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4821c50d8ae3SPaolo Bonzini 	int i;
4822c50d8ae3SPaolo Bonzini 
4823a972e29cSPaolo Bonzini 	WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
48248c985b2dSSean Christopherson 
4825c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4826b705a277SSean Christopherson 	__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4827a972e29cSPaolo Bonzini 				context->root_role.level,
48287a458f0eSPaolo Bonzini 				context->root_role.efer_nx,
482927de9250SSean Christopherson 				guest_can_use_gbpages(vcpu), is_pse, is_amd);
4830c50d8ae3SPaolo Bonzini 
4831c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4832c50d8ae3SPaolo Bonzini 		return;
4833c50d8ae3SPaolo Bonzini 
4834a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
4835e54f1ff2SKai Huang 		/*
4836e54f1ff2SKai Huang 		 * So far shadow_me_value is a constant during KVM's life
4837e54f1ff2SKai Huang 		 * time.  Bits in shadow_me_value are allowed to be set.
4838e54f1ff2SKai Huang 		 * Bits in shadow_me_mask but not in shadow_me_value are
4839e54f1ff2SKai Huang 		 * not allowed to be set.
4840e54f1ff2SKai Huang 		 */
4841e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
4842e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
4843e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
4844e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
4845c50d8ae3SPaolo Bonzini 	}
4846c50d8ae3SPaolo Bonzini 
4847c50d8ae3SPaolo Bonzini }
4848c50d8ae3SPaolo Bonzini 
4849c50d8ae3SPaolo Bonzini static inline bool boot_cpu_is_amd(void)
4850c50d8ae3SPaolo Bonzini {
4851c50d8ae3SPaolo Bonzini 	WARN_ON_ONCE(!tdp_enabled);
4852c50d8ae3SPaolo Bonzini 	return shadow_x_mask == 0;
4853c50d8ae3SPaolo Bonzini }
4854c50d8ae3SPaolo Bonzini 
4855c50d8ae3SPaolo Bonzini /*
4856c50d8ae3SPaolo Bonzini  * the direct page table on host, use as much mmu features as
4857c50d8ae3SPaolo Bonzini  * possible, however, kvm currently does not do execution-protection.
4858c50d8ae3SPaolo Bonzini  */
4859c50d8ae3SPaolo Bonzini static void
4860e8f6e738SJinrong Liang reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
4861c50d8ae3SPaolo Bonzini {
4862c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4863c50d8ae3SPaolo Bonzini 	int i;
4864c50d8ae3SPaolo Bonzini 
4865c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4866c50d8ae3SPaolo Bonzini 
4867c50d8ae3SPaolo Bonzini 	if (boot_cpu_is_amd())
4868b705a277SSean Christopherson 		__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
48696c6ab524SSean Christopherson 					context->root_role.level, true,
4870c50d8ae3SPaolo Bonzini 					boot_cpu_has(X86_FEATURE_GBPAGES),
48718c985b2dSSean Christopherson 					false, true);
4872c50d8ae3SPaolo Bonzini 	else
4873c50d8ae3SPaolo Bonzini 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
487484ea5c09SLai Jiangshan 					    reserved_hpa_bits(), false,
487584ea5c09SLai Jiangshan 					    max_huge_page_level);
4876c50d8ae3SPaolo Bonzini 
4877c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4878c50d8ae3SPaolo Bonzini 		return;
4879c50d8ae3SPaolo Bonzini 
4880a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
4881c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4882c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4883c50d8ae3SPaolo Bonzini 	}
4884c50d8ae3SPaolo Bonzini }
4885c50d8ae3SPaolo Bonzini 
4886c50d8ae3SPaolo Bonzini /*
4887c50d8ae3SPaolo Bonzini  * as the comments in reset_shadow_zero_bits_mask() except it
4888c50d8ae3SPaolo Bonzini  * is the shadow page table for intel nested guest.
4889c50d8ae3SPaolo Bonzini  */
4890c50d8ae3SPaolo Bonzini static void
4891e8f6e738SJinrong Liang reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
4892c50d8ae3SPaolo Bonzini {
4893c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
489484ea5c09SLai Jiangshan 				    reserved_hpa_bits(), execonly,
489584ea5c09SLai Jiangshan 				    max_huge_page_level);
4896c50d8ae3SPaolo Bonzini }
4897c50d8ae3SPaolo Bonzini 
4898c50d8ae3SPaolo Bonzini #define BYTE_MASK(access) \
4899c50d8ae3SPaolo Bonzini 	((1 & (access) ? 2 : 0) | \
4900c50d8ae3SPaolo Bonzini 	 (2 & (access) ? 4 : 0) | \
4901c50d8ae3SPaolo Bonzini 	 (3 & (access) ? 8 : 0) | \
4902c50d8ae3SPaolo Bonzini 	 (4 & (access) ? 16 : 0) | \
4903c50d8ae3SPaolo Bonzini 	 (5 & (access) ? 32 : 0) | \
4904c50d8ae3SPaolo Bonzini 	 (6 & (access) ? 64 : 0) | \
4905c50d8ae3SPaolo Bonzini 	 (7 & (access) ? 128 : 0))
4906c50d8ae3SPaolo Bonzini 
4907c50d8ae3SPaolo Bonzini 
4908c596f147SSean Christopherson static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
4909c50d8ae3SPaolo Bonzini {
4910c50d8ae3SPaolo Bonzini 	unsigned byte;
4911c50d8ae3SPaolo Bonzini 
4912c50d8ae3SPaolo Bonzini 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4913c50d8ae3SPaolo Bonzini 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4914c50d8ae3SPaolo Bonzini 	const u8 u = BYTE_MASK(ACC_USER_MASK);
4915c50d8ae3SPaolo Bonzini 
4916c596f147SSean Christopherson 	bool cr4_smep = is_cr4_smep(mmu);
4917c596f147SSean Christopherson 	bool cr4_smap = is_cr4_smap(mmu);
4918c596f147SSean Christopherson 	bool cr0_wp = is_cr0_wp(mmu);
491990599c28SSean Christopherson 	bool efer_nx = is_efer_nx(mmu);
4920c50d8ae3SPaolo Bonzini 
4921c50d8ae3SPaolo Bonzini 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4922c50d8ae3SPaolo Bonzini 		unsigned pfec = byte << 1;
4923c50d8ae3SPaolo Bonzini 
4924c50d8ae3SPaolo Bonzini 		/*
4925c50d8ae3SPaolo Bonzini 		 * Each "*f" variable has a 1 bit for each UWX value
4926c50d8ae3SPaolo Bonzini 		 * that causes a fault with the given PFEC.
4927c50d8ae3SPaolo Bonzini 		 */
4928c50d8ae3SPaolo Bonzini 
4929c50d8ae3SPaolo Bonzini 		/* Faults from writes to non-writable pages */
4930c50d8ae3SPaolo Bonzini 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4931c50d8ae3SPaolo Bonzini 		/* Faults from user mode accesses to supervisor pages */
4932c50d8ae3SPaolo Bonzini 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4933c50d8ae3SPaolo Bonzini 		/* Faults from fetches of non-executable pages*/
4934c50d8ae3SPaolo Bonzini 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4935c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode fetches of user pages */
4936c50d8ae3SPaolo Bonzini 		u8 smepf = 0;
4937c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode accesses of user pages */
4938c50d8ae3SPaolo Bonzini 		u8 smapf = 0;
4939c50d8ae3SPaolo Bonzini 
4940c50d8ae3SPaolo Bonzini 		if (!ept) {
4941c50d8ae3SPaolo Bonzini 			/* Faults from kernel mode accesses to user pages */
4942c50d8ae3SPaolo Bonzini 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4943c50d8ae3SPaolo Bonzini 
4944c50d8ae3SPaolo Bonzini 			/* Not really needed: !nx will cause pte.nx to fault */
494590599c28SSean Christopherson 			if (!efer_nx)
4946c50d8ae3SPaolo Bonzini 				ff = 0;
4947c50d8ae3SPaolo Bonzini 
4948c50d8ae3SPaolo Bonzini 			/* Allow supervisor writes if !cr0.wp */
4949c50d8ae3SPaolo Bonzini 			if (!cr0_wp)
4950c50d8ae3SPaolo Bonzini 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4951c50d8ae3SPaolo Bonzini 
4952c50d8ae3SPaolo Bonzini 			/* Disallow supervisor fetches of user code if cr4.smep */
4953c50d8ae3SPaolo Bonzini 			if (cr4_smep)
4954c50d8ae3SPaolo Bonzini 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4955c50d8ae3SPaolo Bonzini 
4956c50d8ae3SPaolo Bonzini 			/*
4957c50d8ae3SPaolo Bonzini 			 * SMAP:kernel-mode data accesses from user-mode
4958c50d8ae3SPaolo Bonzini 			 * mappings should fault. A fault is considered
4959c50d8ae3SPaolo Bonzini 			 * as a SMAP violation if all of the following
4960c50d8ae3SPaolo Bonzini 			 * conditions are true:
4961c50d8ae3SPaolo Bonzini 			 *   - X86_CR4_SMAP is set in CR4
4962c50d8ae3SPaolo Bonzini 			 *   - A user page is accessed
4963c50d8ae3SPaolo Bonzini 			 *   - The access is not a fetch
49644f4aa80eSLai Jiangshan 			 *   - The access is supervisor mode
49654f4aa80eSLai Jiangshan 			 *   - If implicit supervisor access or X86_EFLAGS_AC is clear
4966c50d8ae3SPaolo Bonzini 			 *
496794b4a2f1SLai Jiangshan 			 * Here, we cover the first four conditions.
496894b4a2f1SLai Jiangshan 			 * The fifth is computed dynamically in permission_fault();
4969c50d8ae3SPaolo Bonzini 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4970c50d8ae3SPaolo Bonzini 			 * *not* subject to SMAP restrictions.
4971c50d8ae3SPaolo Bonzini 			 */
4972c50d8ae3SPaolo Bonzini 			if (cr4_smap)
4973c50d8ae3SPaolo Bonzini 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4974c50d8ae3SPaolo Bonzini 		}
4975c50d8ae3SPaolo Bonzini 
4976c50d8ae3SPaolo Bonzini 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4977c50d8ae3SPaolo Bonzini 	}
4978c50d8ae3SPaolo Bonzini }
4979c50d8ae3SPaolo Bonzini 
4980c50d8ae3SPaolo Bonzini /*
4981c50d8ae3SPaolo Bonzini * PKU is an additional mechanism by which the paging controls access to
4982c50d8ae3SPaolo Bonzini * user-mode addresses based on the value in the PKRU register.  Protection
4983c50d8ae3SPaolo Bonzini * key violations are reported through a bit in the page fault error code.
4984c50d8ae3SPaolo Bonzini * Unlike other bits of the error code, the PK bit is not known at the
4985c50d8ae3SPaolo Bonzini * call site of e.g. gva_to_gpa; it must be computed directly in
4986c50d8ae3SPaolo Bonzini * permission_fault based on two bits of PKRU, on some machine state (CR4,
4987c50d8ae3SPaolo Bonzini * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4988c50d8ae3SPaolo Bonzini *
4989c50d8ae3SPaolo Bonzini * In particular the following conditions come from the error code, the
4990c50d8ae3SPaolo Bonzini * page tables and the machine state:
4991c50d8ae3SPaolo Bonzini * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4992c50d8ae3SPaolo Bonzini * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4993c50d8ae3SPaolo Bonzini * - PK is always zero if U=0 in the page tables
4994c50d8ae3SPaolo Bonzini * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4995c50d8ae3SPaolo Bonzini *
4996c50d8ae3SPaolo Bonzini * The PKRU bitmask caches the result of these four conditions.  The error
4997c50d8ae3SPaolo Bonzini * code (minus the P bit) and the page table's U bit form an index into the
4998c50d8ae3SPaolo Bonzini * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
4999c50d8ae3SPaolo Bonzini * with the two bits of the PKRU register corresponding to the protection key.
5000c50d8ae3SPaolo Bonzini * For the first three conditions above the bits will be 00, thus masking
5001c50d8ae3SPaolo Bonzini * away both AD and WD.  For all reads or if the last condition holds, WD
5002c50d8ae3SPaolo Bonzini * only will be masked away.
5003c50d8ae3SPaolo Bonzini */
50042e4c0661SSean Christopherson static void update_pkru_bitmask(struct kvm_mmu *mmu)
5005c50d8ae3SPaolo Bonzini {
5006c50d8ae3SPaolo Bonzini 	unsigned bit;
5007c50d8ae3SPaolo Bonzini 	bool wp;
5008c50d8ae3SPaolo Bonzini 
5009c50d8ae3SPaolo Bonzini 	mmu->pkru_mask = 0;
5010a3ca5281SChenyi Qiang 
5011a3ca5281SChenyi Qiang 	if (!is_cr4_pke(mmu))
5012c50d8ae3SPaolo Bonzini 		return;
5013c50d8ae3SPaolo Bonzini 
50142e4c0661SSean Christopherson 	wp = is_cr0_wp(mmu);
5015c50d8ae3SPaolo Bonzini 
5016c50d8ae3SPaolo Bonzini 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5017c50d8ae3SPaolo Bonzini 		unsigned pfec, pkey_bits;
5018c50d8ae3SPaolo Bonzini 		bool check_pkey, check_write, ff, uf, wf, pte_user;
5019c50d8ae3SPaolo Bonzini 
5020c50d8ae3SPaolo Bonzini 		pfec = bit << 1;
5021c50d8ae3SPaolo Bonzini 		ff = pfec & PFERR_FETCH_MASK;
5022c50d8ae3SPaolo Bonzini 		uf = pfec & PFERR_USER_MASK;
5023c50d8ae3SPaolo Bonzini 		wf = pfec & PFERR_WRITE_MASK;
5024c50d8ae3SPaolo Bonzini 
5025c50d8ae3SPaolo Bonzini 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
5026c50d8ae3SPaolo Bonzini 		pte_user = pfec & PFERR_RSVD_MASK;
5027c50d8ae3SPaolo Bonzini 
5028c50d8ae3SPaolo Bonzini 		/*
5029c50d8ae3SPaolo Bonzini 		 * Only need to check the access which is not an
5030c50d8ae3SPaolo Bonzini 		 * instruction fetch and is to a user page.
5031c50d8ae3SPaolo Bonzini 		 */
5032c50d8ae3SPaolo Bonzini 		check_pkey = (!ff && pte_user);
5033c50d8ae3SPaolo Bonzini 		/*
5034c50d8ae3SPaolo Bonzini 		 * write access is controlled by PKRU if it is a
5035c50d8ae3SPaolo Bonzini 		 * user access or CR0.WP = 1.
5036c50d8ae3SPaolo Bonzini 		 */
5037c50d8ae3SPaolo Bonzini 		check_write = check_pkey && wf && (uf || wp);
5038c50d8ae3SPaolo Bonzini 
5039c50d8ae3SPaolo Bonzini 		/* PKRU.AD stops both read and write access. */
5040c50d8ae3SPaolo Bonzini 		pkey_bits = !!check_pkey;
5041c50d8ae3SPaolo Bonzini 		/* PKRU.WD stops write access. */
5042c50d8ae3SPaolo Bonzini 		pkey_bits |= (!!check_write) << 1;
5043c50d8ae3SPaolo Bonzini 
5044c50d8ae3SPaolo Bonzini 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5045c50d8ae3SPaolo Bonzini 	}
5046c50d8ae3SPaolo Bonzini }
5047c50d8ae3SPaolo Bonzini 
5048533f9a4bSSean Christopherson static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5049533f9a4bSSean Christopherson 					struct kvm_mmu *mmu)
5050c50d8ae3SPaolo Bonzini {
5051533f9a4bSSean Christopherson 	if (!is_cr0_pg(mmu))
5052533f9a4bSSean Christopherson 		return;
5053c50d8ae3SPaolo Bonzini 
5054c919e881SKai Huang 	reset_guest_rsvds_bits_mask(vcpu, mmu);
5055533f9a4bSSean Christopherson 	update_permission_bitmask(mmu, false);
5056533f9a4bSSean Christopherson 	update_pkru_bitmask(mmu);
5057c50d8ae3SPaolo Bonzini }
5058c50d8ae3SPaolo Bonzini 
5059fe660f72SSean Christopherson static void paging64_init_context(struct kvm_mmu *context)
5060c50d8ae3SPaolo Bonzini {
5061c50d8ae3SPaolo Bonzini 	context->page_fault = paging64_page_fault;
5062c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging64_gva_to_gpa;
5063c50d8ae3SPaolo Bonzini 	context->sync_page = paging64_sync_page;
5064c50d8ae3SPaolo Bonzini 	context->invlpg = paging64_invlpg;
5065c50d8ae3SPaolo Bonzini }
5066c50d8ae3SPaolo Bonzini 
506784a16226SSean Christopherson static void paging32_init_context(struct kvm_mmu *context)
5068c50d8ae3SPaolo Bonzini {
5069c50d8ae3SPaolo Bonzini 	context->page_fault = paging32_page_fault;
5070c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging32_gva_to_gpa;
5071c50d8ae3SPaolo Bonzini 	context->sync_page = paging32_sync_page;
5072c50d8ae3SPaolo Bonzini 	context->invlpg = paging32_invlpg;
5073c50d8ae3SPaolo Bonzini }
5074c50d8ae3SPaolo Bonzini 
50757a7ae829SPaolo Bonzini static union kvm_cpu_role
5076e5ed0fb0SPaolo Bonzini kvm_calc_cpu_role(struct kvm_vcpu *vcpu, const struct kvm_mmu_role_regs *regs)
5077e5ed0fb0SPaolo Bonzini {
50787a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5079e5ed0fb0SPaolo Bonzini 
5080e5ed0fb0SPaolo Bonzini 	role.base.access = ACC_ALL;
5081e5ed0fb0SPaolo Bonzini 	role.base.smm = is_smm(vcpu);
5082e5ed0fb0SPaolo Bonzini 	role.base.guest_mode = is_guest_mode(vcpu);
5083e5ed0fb0SPaolo Bonzini 	role.ext.valid = 1;
5084e5ed0fb0SPaolo Bonzini 
5085e5ed0fb0SPaolo Bonzini 	if (!____is_cr0_pg(regs)) {
5086e5ed0fb0SPaolo Bonzini 		role.base.direct = 1;
5087e5ed0fb0SPaolo Bonzini 		return role;
5088e5ed0fb0SPaolo Bonzini 	}
5089e5ed0fb0SPaolo Bonzini 
5090e5ed0fb0SPaolo Bonzini 	role.base.efer_nx = ____is_efer_nx(regs);
5091e5ed0fb0SPaolo Bonzini 	role.base.cr0_wp = ____is_cr0_wp(regs);
5092e5ed0fb0SPaolo Bonzini 	role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5093e5ed0fb0SPaolo Bonzini 	role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5094e5ed0fb0SPaolo Bonzini 	role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
509560f3cb60SPaolo Bonzini 
509660f3cb60SPaolo Bonzini 	if (____is_efer_lma(regs))
509760f3cb60SPaolo Bonzini 		role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
509860f3cb60SPaolo Bonzini 							: PT64_ROOT_4LEVEL;
509960f3cb60SPaolo Bonzini 	else if (____is_cr4_pae(regs))
510060f3cb60SPaolo Bonzini 		role.base.level = PT32E_ROOT_LEVEL;
510160f3cb60SPaolo Bonzini 	else
510260f3cb60SPaolo Bonzini 		role.base.level = PT32_ROOT_LEVEL;
5103e5ed0fb0SPaolo Bonzini 
5104e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smep = ____is_cr4_smep(regs);
5105e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smap = ____is_cr4_smap(regs);
5106e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pse = ____is_cr4_pse(regs);
5107e5ed0fb0SPaolo Bonzini 
5108e5ed0fb0SPaolo Bonzini 	/* PKEY and LA57 are active iff long mode is active. */
5109e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5110e5ed0fb0SPaolo Bonzini 	role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5111e5ed0fb0SPaolo Bonzini 	role.ext.efer_lma = ____is_efer_lma(regs);
5112e5ed0fb0SPaolo Bonzini 	return role;
5113e5ed0fb0SPaolo Bonzini }
5114e5ed0fb0SPaolo Bonzini 
5115d468d94bSSean Christopherson static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5116d468d94bSSean Christopherson {
5117746700d2SWei Huang 	/* tdp_root_level is architecture forced level, use it if nonzero */
5118746700d2SWei Huang 	if (tdp_root_level)
5119746700d2SWei Huang 		return tdp_root_level;
5120746700d2SWei Huang 
5121d468d94bSSean Christopherson 	/* Use 5-level TDP if and only if it's useful/necessary. */
512283013059SSean Christopherson 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5123d468d94bSSean Christopherson 		return 4;
5124d468d94bSSean Christopherson 
512583013059SSean Christopherson 	return max_tdp_level;
5126d468d94bSSean Christopherson }
5127d468d94bSSean Christopherson 
51287a458f0eSPaolo Bonzini static union kvm_mmu_page_role
51298626c120SSean Christopherson kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
51307a7ae829SPaolo Bonzini 				union kvm_cpu_role cpu_role)
5131c50d8ae3SPaolo Bonzini {
51327a458f0eSPaolo Bonzini 	union kvm_mmu_page_role role = {0};
5133c50d8ae3SPaolo Bonzini 
51347a458f0eSPaolo Bonzini 	role.access = ACC_ALL;
51357a458f0eSPaolo Bonzini 	role.cr0_wp = true;
51367a458f0eSPaolo Bonzini 	role.efer_nx = true;
51377a458f0eSPaolo Bonzini 	role.smm = cpu_role.base.smm;
51387a458f0eSPaolo Bonzini 	role.guest_mode = cpu_role.base.guest_mode;
513954275f74SSean Christopherson 	role.ad_disabled = !kvm_ad_enabled();
51407a458f0eSPaolo Bonzini 	role.level = kvm_mmu_get_tdp_level(vcpu);
51417a458f0eSPaolo Bonzini 	role.direct = true;
51427a458f0eSPaolo Bonzini 	role.has_4_byte_gpte = false;
5143c50d8ae3SPaolo Bonzini 
5144c50d8ae3SPaolo Bonzini 	return role;
5145c50d8ae3SPaolo Bonzini }
5146c50d8ae3SPaolo Bonzini 
514739e7e2bfSPaolo Bonzini static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5148a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5149c50d8ae3SPaolo Bonzini {
51508c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
51517a458f0eSPaolo Bonzini 	union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5152c50d8ae3SPaolo Bonzini 
5153e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
51547a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
5155c50d8ae3SPaolo Bonzini 		return;
5156c50d8ae3SPaolo Bonzini 
5157e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
51587a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
51597a02674dSSean Christopherson 	context->page_fault = kvm_tdp_page_fault;
5160c50d8ae3SPaolo Bonzini 	context->sync_page = nonpaging_sync_page;
51615efac074SPaolo Bonzini 	context->invlpg = NULL;
5162d8dd54e0SSean Christopherson 	context->get_guest_pgd = get_cr3;
5163c50d8ae3SPaolo Bonzini 	context->get_pdptr = kvm_pdptr_read;
5164c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5165c50d8ae3SPaolo Bonzini 
516636f26787SSean Christopherson 	if (!is_cr0_pg(context))
5167c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = nonpaging_gva_to_gpa;
516836f26787SSean Christopherson 	else if (is_cr4_pae(context))
5169c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging64_gva_to_gpa;
5170f4bd6f73SSean Christopherson 	else
5171c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging32_gva_to_gpa;
5172c50d8ae3SPaolo Bonzini 
5173533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5174e8f6e738SJinrong Liang 	reset_tdp_shadow_zero_bits_mask(context);
5175c50d8ae3SPaolo Bonzini }
5176c50d8ae3SPaolo Bonzini 
51778c008659SPaolo Bonzini static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
51787a7ae829SPaolo Bonzini 				    union kvm_cpu_role cpu_role,
51797a458f0eSPaolo Bonzini 				    union kvm_mmu_page_role root_role)
5180c50d8ae3SPaolo Bonzini {
5181e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
51827a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
518318db1b17SSean Christopherson 		return;
5184c50d8ae3SPaolo Bonzini 
5185e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
51867a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
518718db1b17SSean Christopherson 
518836f26787SSean Christopherson 	if (!is_cr0_pg(context))
518984a16226SSean Christopherson 		nonpaging_init_context(context);
519036f26787SSean Christopherson 	else if (is_cr4_pae(context))
5191fe660f72SSean Christopherson 		paging64_init_context(context);
5192c50d8ae3SPaolo Bonzini 	else
519384a16226SSean Christopherson 		paging32_init_context(context);
5194c50d8ae3SPaolo Bonzini 
5195533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5196c50d8ae3SPaolo Bonzini 	reset_shadow_zero_bits_mask(vcpu, context);
5197c50d8ae3SPaolo Bonzini }
51980f04a2acSVitaly Kuznetsov 
5199594e91a1SSean Christopherson static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5200a7f1de9bSPaolo Bonzini 				union kvm_cpu_role cpu_role)
52010f04a2acSVitaly Kuznetsov {
52028c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
520356b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
520456b321f9SPaolo Bonzini 
520556b321f9SPaolo Bonzini 	root_role = cpu_role.base;
520656b321f9SPaolo Bonzini 
520756b321f9SPaolo Bonzini 	/* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
520856b321f9SPaolo Bonzini 	root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
520956b321f9SPaolo Bonzini 
521056b321f9SPaolo Bonzini 	/*
521156b321f9SPaolo Bonzini 	 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
521256b321f9SPaolo Bonzini 	 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
521356b321f9SPaolo Bonzini 	 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
521456b321f9SPaolo Bonzini 	 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
521556b321f9SPaolo Bonzini 	 * The iTLB multi-hit workaround can be toggled at any time, so assume
521656b321f9SPaolo Bonzini 	 * NX can be used by any non-nested shadow MMU to avoid having to reset
521756b321f9SPaolo Bonzini 	 * MMU contexts.
521856b321f9SPaolo Bonzini 	 */
521956b321f9SPaolo Bonzini 	root_role.efer_nx = true;
52200f04a2acSVitaly Kuznetsov 
52217a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
52220f04a2acSVitaly Kuznetsov }
52230f04a2acSVitaly Kuznetsov 
5224dbc4739bSSean Christopherson void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5225dbc4739bSSean Christopherson 			     unsigned long cr4, u64 efer, gpa_t nested_cr3)
52260f04a2acSVitaly Kuznetsov {
52278c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5228594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
5229594e91a1SSean Christopherson 		.cr0 = cr0,
523028f091bcSPaolo Bonzini 		.cr4 = cr4 & ~X86_CR4_PKE,
5231594e91a1SSean Christopherson 		.efer = efer,
5232594e91a1SSean Christopherson 	};
52337a7ae829SPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
523456b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
523556b321f9SPaolo Bonzini 
523656b321f9SPaolo Bonzini 	/* NPT requires CR0.PG=1. */
523756b321f9SPaolo Bonzini 	WARN_ON_ONCE(cpu_role.base.direct);
523856b321f9SPaolo Bonzini 
523956b321f9SPaolo Bonzini 	root_role = cpu_role.base;
524056b321f9SPaolo Bonzini 	root_role.level = kvm_mmu_get_tdp_level(vcpu);
524184e5ffd0SLai Jiangshan 	if (root_role.level == PT64_ROOT_5LEVEL &&
524284e5ffd0SLai Jiangshan 	    cpu_role.base.level == PT64_ROOT_4LEVEL)
524384e5ffd0SLai Jiangshan 		root_role.passthrough = 1;
52440f04a2acSVitaly Kuznetsov 
52457a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5246d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, nested_cr3);
52470f04a2acSVitaly Kuznetsov }
52480f04a2acSVitaly Kuznetsov EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5249c50d8ae3SPaolo Bonzini 
52507a7ae829SPaolo Bonzini static union kvm_cpu_role
5251c50d8ae3SPaolo Bonzini kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5252bb1fcc70SSean Christopherson 				   bool execonly, u8 level)
5253c50d8ae3SPaolo Bonzini {
52547a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5255c50d8ae3SPaolo Bonzini 
5256daed87b8SPaolo Bonzini 	/*
5257daed87b8SPaolo Bonzini 	 * KVM does not support SMM transfer monitors, and consequently does not
5258daed87b8SPaolo Bonzini 	 * support the "entry to SMM" control either.  role.base.smm is always 0.
5259daed87b8SPaolo Bonzini 	 */
5260daed87b8SPaolo Bonzini 	WARN_ON_ONCE(is_smm(vcpu));
5261bb1fcc70SSean Christopherson 	role.base.level = level;
5262bb3b394dSLai Jiangshan 	role.base.has_4_byte_gpte = false;
5263c50d8ae3SPaolo Bonzini 	role.base.direct = false;
5264c50d8ae3SPaolo Bonzini 	role.base.ad_disabled = !accessed_dirty;
5265c50d8ae3SPaolo Bonzini 	role.base.guest_mode = true;
5266c50d8ae3SPaolo Bonzini 	role.base.access = ACC_ALL;
5267c50d8ae3SPaolo Bonzini 
5268cd6767c3SSean Christopherson 	role.ext.word = 0;
5269c50d8ae3SPaolo Bonzini 	role.ext.execonly = execonly;
5270cd6767c3SSean Christopherson 	role.ext.valid = 1;
5271c50d8ae3SPaolo Bonzini 
5272c50d8ae3SPaolo Bonzini 	return role;
5273c50d8ae3SPaolo Bonzini }
5274c50d8ae3SPaolo Bonzini 
5275c50d8ae3SPaolo Bonzini void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5276cc022ae1SLai Jiangshan 			     int huge_page_level, bool accessed_dirty,
5277cc022ae1SLai Jiangshan 			     gpa_t new_eptp)
5278c50d8ae3SPaolo Bonzini {
52798c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5280bb1fcc70SSean Christopherson 	u8 level = vmx_eptp_page_walk_level(new_eptp);
52817a7ae829SPaolo Bonzini 	union kvm_cpu_role new_mode =
5282c50d8ae3SPaolo Bonzini 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5283bb1fcc70SSean Christopherson 						   execonly, level);
5284c50d8ae3SPaolo Bonzini 
5285e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 != context->cpu_role.as_u64) {
5286e5ed0fb0SPaolo Bonzini 		/* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5287e5ed0fb0SPaolo Bonzini 		context->cpu_role.as_u64 = new_mode.as_u64;
52887a458f0eSPaolo Bonzini 		context->root_role.word = new_mode.base.word;
528918db1b17SSean Christopherson 
5290c50d8ae3SPaolo Bonzini 		context->page_fault = ept_page_fault;
5291c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = ept_gva_to_gpa;
5292c50d8ae3SPaolo Bonzini 		context->sync_page = ept_sync_page;
5293c50d8ae3SPaolo Bonzini 		context->invlpg = ept_invlpg;
5294347a0d0dSPaolo Bonzini 
5295c596f147SSean Christopherson 		update_permission_bitmask(context, true);
529628f091bcSPaolo Bonzini 		context->pkru_mask = 0;
5297cc022ae1SLai Jiangshan 		reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5298e8f6e738SJinrong Liang 		reset_ept_shadow_zero_bits_mask(context, execonly);
5299c50d8ae3SPaolo Bonzini 	}
53003cffc89dSPaolo Bonzini 
5301d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, new_eptp);
53023cffc89dSPaolo Bonzini }
5303c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5304c50d8ae3SPaolo Bonzini 
530539e7e2bfSPaolo Bonzini static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5306a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5307c50d8ae3SPaolo Bonzini {
53088c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5309c50d8ae3SPaolo Bonzini 
5310a7f1de9bSPaolo Bonzini 	kvm_init_shadow_mmu(vcpu, cpu_role);
5311929d1cfaSPaolo Bonzini 
5312d8dd54e0SSean Christopherson 	context->get_guest_pgd     = get_cr3;
5313c50d8ae3SPaolo Bonzini 	context->get_pdptr         = kvm_pdptr_read;
5314c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5315c50d8ae3SPaolo Bonzini }
5316c50d8ae3SPaolo Bonzini 
531739e7e2bfSPaolo Bonzini static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5318a7f1de9bSPaolo Bonzini 				union kvm_cpu_role new_mode)
5319c50d8ae3SPaolo Bonzini {
5320c50d8ae3SPaolo Bonzini 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5321c50d8ae3SPaolo Bonzini 
5322e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5323c50d8ae3SPaolo Bonzini 		return;
5324c50d8ae3SPaolo Bonzini 
5325e5ed0fb0SPaolo Bonzini 	g_context->cpu_role.as_u64   = new_mode.as_u64;
5326d8dd54e0SSean Christopherson 	g_context->get_guest_pgd     = get_cr3;
5327c50d8ae3SPaolo Bonzini 	g_context->get_pdptr         = kvm_pdptr_read;
5328c50d8ae3SPaolo Bonzini 	g_context->inject_page_fault = kvm_inject_page_fault;
5329c50d8ae3SPaolo Bonzini 
5330c50d8ae3SPaolo Bonzini 	/*
53315efac074SPaolo Bonzini 	 * L2 page tables are never shadowed, so there is no need to sync
53325efac074SPaolo Bonzini 	 * SPTEs.
53335efac074SPaolo Bonzini 	 */
53345efac074SPaolo Bonzini 	g_context->invlpg            = NULL;
53355efac074SPaolo Bonzini 
53365efac074SPaolo Bonzini 	/*
5337c50d8ae3SPaolo Bonzini 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5338c50d8ae3SPaolo Bonzini 	 * L1's nested page tables (e.g. EPT12). The nested translation
5339c50d8ae3SPaolo Bonzini 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5340c50d8ae3SPaolo Bonzini 	 * L2's page tables as the first level of translation and L1's
5341c50d8ae3SPaolo Bonzini 	 * nested page tables as the second level of translation. Basically
5342c50d8ae3SPaolo Bonzini 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5343c50d8ae3SPaolo Bonzini 	 */
5344fa4b5588SSean Christopherson 	if (!is_paging(vcpu))
53451f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5346fa4b5588SSean Christopherson 	else if (is_long_mode(vcpu))
53471f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5348fa4b5588SSean Christopherson 	else if (is_pae(vcpu))
53491f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5350fa4b5588SSean Christopherson 	else
53511f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging32_gva_to_gpa;
5352fa4b5588SSean Christopherson 
5353533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, g_context);
5354c50d8ae3SPaolo Bonzini }
5355c50d8ae3SPaolo Bonzini 
5356c9060662SSean Christopherson void kvm_init_mmu(struct kvm_vcpu *vcpu)
5357c50d8ae3SPaolo Bonzini {
535839e7e2bfSPaolo Bonzini 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5359a7f1de9bSPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
536039e7e2bfSPaolo Bonzini 
5361c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
5362a7f1de9bSPaolo Bonzini 		init_kvm_nested_mmu(vcpu, cpu_role);
5363c50d8ae3SPaolo Bonzini 	else if (tdp_enabled)
5364a7f1de9bSPaolo Bonzini 		init_kvm_tdp_mmu(vcpu, cpu_role);
5365c50d8ae3SPaolo Bonzini 	else
5366a7f1de9bSPaolo Bonzini 		init_kvm_softmmu(vcpu, cpu_role);
5367c50d8ae3SPaolo Bonzini }
5368c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_mmu);
5369c50d8ae3SPaolo Bonzini 
537049c6f875SSean Christopherson void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
537149c6f875SSean Christopherson {
537249c6f875SSean Christopherson 	/*
537349c6f875SSean Christopherson 	 * Invalidate all MMU roles to force them to reinitialize as CPUID
537449c6f875SSean Christopherson 	 * information is factored into reserved bit calculations.
5375feb627e8SVitaly Kuznetsov 	 *
5376feb627e8SVitaly Kuznetsov 	 * Correctly handling multiple vCPU models with respect to paging and
5377feb627e8SVitaly Kuznetsov 	 * physical address properties) in a single VM would require tracking
5378feb627e8SVitaly Kuznetsov 	 * all relevant CPUID information in kvm_mmu_page_role. That is very
5379feb627e8SVitaly Kuznetsov 	 * undesirable as it would increase the memory requirements for
5380feb627e8SVitaly Kuznetsov 	 * gfn_track (see struct kvm_mmu_page_role comments).  For now that
5381feb627e8SVitaly Kuznetsov 	 * problem is swept under the rug; KVM's CPUID API is horrific and
5382feb627e8SVitaly Kuznetsov 	 * it's all but impossible to solve it without introducing a new API.
538349c6f875SSean Christopherson 	 */
53847a458f0eSPaolo Bonzini 	vcpu->arch.root_mmu.root_role.word = 0;
53857a458f0eSPaolo Bonzini 	vcpu->arch.guest_mmu.root_role.word = 0;
53867a458f0eSPaolo Bonzini 	vcpu->arch.nested_mmu.root_role.word = 0;
5387e5ed0fb0SPaolo Bonzini 	vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5388e5ed0fb0SPaolo Bonzini 	vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5389e5ed0fb0SPaolo Bonzini 	vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
539049c6f875SSean Christopherson 	kvm_mmu_reset_context(vcpu);
539163f5a190SSean Christopherson 
539263f5a190SSean Christopherson 	/*
5393feb627e8SVitaly Kuznetsov 	 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5394feb627e8SVitaly Kuznetsov 	 * kvm_arch_vcpu_ioctl().
539563f5a190SSean Christopherson 	 */
5396feb627e8SVitaly Kuznetsov 	KVM_BUG_ON(vcpu->arch.last_vmentry_cpu != -1, vcpu->kvm);
539749c6f875SSean Christopherson }
539849c6f875SSean Christopherson 
5399c50d8ae3SPaolo Bonzini void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5400c50d8ae3SPaolo Bonzini {
5401c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
5402c9060662SSean Christopherson 	kvm_init_mmu(vcpu);
5403c50d8ae3SPaolo Bonzini }
5404c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5405c50d8ae3SPaolo Bonzini 
5406c50d8ae3SPaolo Bonzini int kvm_mmu_load(struct kvm_vcpu *vcpu)
5407c50d8ae3SPaolo Bonzini {
5408c50d8ae3SPaolo Bonzini 	int r;
5409c50d8ae3SPaolo Bonzini 
5410347a0d0dSPaolo Bonzini 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5411c50d8ae3SPaolo Bonzini 	if (r)
5412c50d8ae3SPaolo Bonzini 		goto out;
5413748e52b9SSean Christopherson 	r = mmu_alloc_special_roots(vcpu);
5414c50d8ae3SPaolo Bonzini 	if (r)
5415c50d8ae3SPaolo Bonzini 		goto out;
5416347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
54176e6ec584SSean Christopherson 		r = mmu_alloc_direct_roots(vcpu);
54186e6ec584SSean Christopherson 	else
54196e6ec584SSean Christopherson 		r = mmu_alloc_shadow_roots(vcpu);
5420c50d8ae3SPaolo Bonzini 	if (r)
5421c50d8ae3SPaolo Bonzini 		goto out;
5422a91f387bSSean Christopherson 
5423a91f387bSSean Christopherson 	kvm_mmu_sync_roots(vcpu);
5424a91f387bSSean Christopherson 
5425727a7e27SPaolo Bonzini 	kvm_mmu_load_pgd(vcpu);
5426db01416bSSean Christopherson 
5427db01416bSSean Christopherson 	/*
5428db01416bSSean Christopherson 	 * Flush any TLB entries for the new root, the provenance of the root
5429db01416bSSean Christopherson 	 * is unknown.  Even if KVM ensures there are no stale TLB entries
5430db01416bSSean Christopherson 	 * for a freed root, in theory another hypervisor could have left
5431db01416bSSean Christopherson 	 * stale entries.  Flushing on alloc also allows KVM to skip the TLB
5432db01416bSSean Christopherson 	 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5433db01416bSSean Christopherson 	 */
5434e27bc044SSean Christopherson 	static_call(kvm_x86_flush_tlb_current)(vcpu);
5435c50d8ae3SPaolo Bonzini out:
5436c50d8ae3SPaolo Bonzini 	return r;
5437c50d8ae3SPaolo Bonzini }
5438c50d8ae3SPaolo Bonzini 
5439c50d8ae3SPaolo Bonzini void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5440c50d8ae3SPaolo Bonzini {
54410c1c92f1SPaolo Bonzini 	struct kvm *kvm = vcpu->kvm;
54420c1c92f1SPaolo Bonzini 
54430c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5444b9e5603cSPaolo Bonzini 	WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
54450c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5446b9e5603cSPaolo Bonzini 	WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
54476d58f275SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5448c50d8ae3SPaolo Bonzini }
5449c50d8ae3SPaolo Bonzini 
5450527d5cd7SSean Christopherson static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5451527d5cd7SSean Christopherson {
5452527d5cd7SSean Christopherson 	struct kvm_mmu_page *sp;
5453527d5cd7SSean Christopherson 
5454527d5cd7SSean Christopherson 	if (!VALID_PAGE(root_hpa))
5455527d5cd7SSean Christopherson 		return false;
5456527d5cd7SSean Christopherson 
5457527d5cd7SSean Christopherson 	/*
5458527d5cd7SSean Christopherson 	 * When freeing obsolete roots, treat roots as obsolete if they don't
5459527d5cd7SSean Christopherson 	 * have an associated shadow page.  This does mean KVM will get false
5460527d5cd7SSean Christopherson 	 * positives and free roots that don't strictly need to be freed, but
5461527d5cd7SSean Christopherson 	 * such false positives are relatively rare:
5462527d5cd7SSean Christopherson 	 *
5463527d5cd7SSean Christopherson 	 *  (a) only PAE paging and nested NPT has roots without shadow pages
5464527d5cd7SSean Christopherson 	 *  (b) remote reloads due to a memslot update obsoletes _all_ roots
5465527d5cd7SSean Christopherson 	 *  (c) KVM doesn't track previous roots for PAE paging, and the guest
5466527d5cd7SSean Christopherson 	 *      is unlikely to zap an in-use PGD.
5467527d5cd7SSean Christopherson 	 */
5468527d5cd7SSean Christopherson 	sp = to_shadow_page(root_hpa);
5469527d5cd7SSean Christopherson 	return !sp || is_obsolete_sp(kvm, sp);
5470527d5cd7SSean Christopherson }
5471527d5cd7SSean Christopherson 
5472527d5cd7SSean Christopherson static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5473527d5cd7SSean Christopherson {
5474527d5cd7SSean Christopherson 	unsigned long roots_to_free = 0;
5475527d5cd7SSean Christopherson 	int i;
5476527d5cd7SSean Christopherson 
5477527d5cd7SSean Christopherson 	if (is_obsolete_root(kvm, mmu->root.hpa))
5478527d5cd7SSean Christopherson 		roots_to_free |= KVM_MMU_ROOT_CURRENT;
5479527d5cd7SSean Christopherson 
5480527d5cd7SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5481cf4a8693SShaoqin Huang 		if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5482527d5cd7SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5483527d5cd7SSean Christopherson 	}
5484527d5cd7SSean Christopherson 
5485527d5cd7SSean Christopherson 	if (roots_to_free)
5486527d5cd7SSean Christopherson 		kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5487527d5cd7SSean Christopherson }
5488527d5cd7SSean Christopherson 
5489527d5cd7SSean Christopherson void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5490527d5cd7SSean Christopherson {
5491527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5492527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5493527d5cd7SSean Christopherson }
5494527d5cd7SSean Christopherson 
5495c50d8ae3SPaolo Bonzini static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5496c50d8ae3SPaolo Bonzini 				    int *bytes)
5497c50d8ae3SPaolo Bonzini {
5498c50d8ae3SPaolo Bonzini 	u64 gentry = 0;
5499c50d8ae3SPaolo Bonzini 	int r;
5500c50d8ae3SPaolo Bonzini 
5501c50d8ae3SPaolo Bonzini 	/*
5502c50d8ae3SPaolo Bonzini 	 * Assume that the pte write on a page table of the same type
5503c50d8ae3SPaolo Bonzini 	 * as the current vcpu paging mode since we update the sptes only
5504c50d8ae3SPaolo Bonzini 	 * when they have the same mode.
5505c50d8ae3SPaolo Bonzini 	 */
5506c50d8ae3SPaolo Bonzini 	if (is_pae(vcpu) && *bytes == 4) {
5507c50d8ae3SPaolo Bonzini 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5508c50d8ae3SPaolo Bonzini 		*gpa &= ~(gpa_t)7;
5509c50d8ae3SPaolo Bonzini 		*bytes = 8;
5510c50d8ae3SPaolo Bonzini 	}
5511c50d8ae3SPaolo Bonzini 
5512c50d8ae3SPaolo Bonzini 	if (*bytes == 4 || *bytes == 8) {
5513c50d8ae3SPaolo Bonzini 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5514c50d8ae3SPaolo Bonzini 		if (r)
5515c50d8ae3SPaolo Bonzini 			gentry = 0;
5516c50d8ae3SPaolo Bonzini 	}
5517c50d8ae3SPaolo Bonzini 
5518c50d8ae3SPaolo Bonzini 	return gentry;
5519c50d8ae3SPaolo Bonzini }
5520c50d8ae3SPaolo Bonzini 
5521c50d8ae3SPaolo Bonzini /*
5522c50d8ae3SPaolo Bonzini  * If we're seeing too many writes to a page, it may no longer be a page table,
5523c50d8ae3SPaolo Bonzini  * or we may be forking, in which case it is better to unmap the page.
5524c50d8ae3SPaolo Bonzini  */
5525c50d8ae3SPaolo Bonzini static bool detect_write_flooding(struct kvm_mmu_page *sp)
5526c50d8ae3SPaolo Bonzini {
5527c50d8ae3SPaolo Bonzini 	/*
5528c50d8ae3SPaolo Bonzini 	 * Skip write-flooding detected for the sp whose level is 1, because
5529c50d8ae3SPaolo Bonzini 	 * it can become unsync, then the guest page is not write-protected.
5530c50d8ae3SPaolo Bonzini 	 */
55313bae0459SSean Christopherson 	if (sp->role.level == PG_LEVEL_4K)
5532c50d8ae3SPaolo Bonzini 		return false;
5533c50d8ae3SPaolo Bonzini 
5534c50d8ae3SPaolo Bonzini 	atomic_inc(&sp->write_flooding_count);
5535c50d8ae3SPaolo Bonzini 	return atomic_read(&sp->write_flooding_count) >= 3;
5536c50d8ae3SPaolo Bonzini }
5537c50d8ae3SPaolo Bonzini 
5538c50d8ae3SPaolo Bonzini /*
5539c50d8ae3SPaolo Bonzini  * Misaligned accesses are too much trouble to fix up; also, they usually
5540c50d8ae3SPaolo Bonzini  * indicate a page is not used as a page table.
5541c50d8ae3SPaolo Bonzini  */
5542c50d8ae3SPaolo Bonzini static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5543c50d8ae3SPaolo Bonzini 				    int bytes)
5544c50d8ae3SPaolo Bonzini {
5545c50d8ae3SPaolo Bonzini 	unsigned offset, pte_size, misaligned;
5546c50d8ae3SPaolo Bonzini 
5547c50d8ae3SPaolo Bonzini 	pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5548c50d8ae3SPaolo Bonzini 		 gpa, bytes, sp->role.word);
5549c50d8ae3SPaolo Bonzini 
5550c50d8ae3SPaolo Bonzini 	offset = offset_in_page(gpa);
5551bb3b394dSLai Jiangshan 	pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5552c50d8ae3SPaolo Bonzini 
5553c50d8ae3SPaolo Bonzini 	/*
5554c50d8ae3SPaolo Bonzini 	 * Sometimes, the OS only writes the last one bytes to update status
5555c50d8ae3SPaolo Bonzini 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5556c50d8ae3SPaolo Bonzini 	 */
5557c50d8ae3SPaolo Bonzini 	if (!(offset & (pte_size - 1)) && bytes == 1)
5558c50d8ae3SPaolo Bonzini 		return false;
5559c50d8ae3SPaolo Bonzini 
5560c50d8ae3SPaolo Bonzini 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5561c50d8ae3SPaolo Bonzini 	misaligned |= bytes < 4;
5562c50d8ae3SPaolo Bonzini 
5563c50d8ae3SPaolo Bonzini 	return misaligned;
5564c50d8ae3SPaolo Bonzini }
5565c50d8ae3SPaolo Bonzini 
5566c50d8ae3SPaolo Bonzini static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5567c50d8ae3SPaolo Bonzini {
5568c50d8ae3SPaolo Bonzini 	unsigned page_offset, quadrant;
5569c50d8ae3SPaolo Bonzini 	u64 *spte;
5570c50d8ae3SPaolo Bonzini 	int level;
5571c50d8ae3SPaolo Bonzini 
5572c50d8ae3SPaolo Bonzini 	page_offset = offset_in_page(gpa);
5573c50d8ae3SPaolo Bonzini 	level = sp->role.level;
5574c50d8ae3SPaolo Bonzini 	*nspte = 1;
5575bb3b394dSLai Jiangshan 	if (sp->role.has_4_byte_gpte) {
5576c50d8ae3SPaolo Bonzini 		page_offset <<= 1;	/* 32->64 */
5577c50d8ae3SPaolo Bonzini 		/*
5578c50d8ae3SPaolo Bonzini 		 * A 32-bit pde maps 4MB while the shadow pdes map
5579c50d8ae3SPaolo Bonzini 		 * only 2MB.  So we need to double the offset again
5580c50d8ae3SPaolo Bonzini 		 * and zap two pdes instead of one.
5581c50d8ae3SPaolo Bonzini 		 */
5582c50d8ae3SPaolo Bonzini 		if (level == PT32_ROOT_LEVEL) {
5583c50d8ae3SPaolo Bonzini 			page_offset &= ~7; /* kill rounding error */
5584c50d8ae3SPaolo Bonzini 			page_offset <<= 1;
5585c50d8ae3SPaolo Bonzini 			*nspte = 2;
5586c50d8ae3SPaolo Bonzini 		}
5587c50d8ae3SPaolo Bonzini 		quadrant = page_offset >> PAGE_SHIFT;
5588c50d8ae3SPaolo Bonzini 		page_offset &= ~PAGE_MASK;
5589c50d8ae3SPaolo Bonzini 		if (quadrant != sp->role.quadrant)
5590c50d8ae3SPaolo Bonzini 			return NULL;
5591c50d8ae3SPaolo Bonzini 	}
5592c50d8ae3SPaolo Bonzini 
5593c50d8ae3SPaolo Bonzini 	spte = &sp->spt[page_offset / sizeof(*spte)];
5594c50d8ae3SPaolo Bonzini 	return spte;
5595c50d8ae3SPaolo Bonzini }
5596c50d8ae3SPaolo Bonzini 
5597c50d8ae3SPaolo Bonzini static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5598c50d8ae3SPaolo Bonzini 			      const u8 *new, int bytes,
5599c50d8ae3SPaolo Bonzini 			      struct kvm_page_track_notifier_node *node)
5600c50d8ae3SPaolo Bonzini {
5601c50d8ae3SPaolo Bonzini 	gfn_t gfn = gpa >> PAGE_SHIFT;
5602c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
5603c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
5604c50d8ae3SPaolo Bonzini 	u64 entry, gentry, *spte;
5605c50d8ae3SPaolo Bonzini 	int npte;
560606152b2dSLai Jiangshan 	bool flush = false;
5607c50d8ae3SPaolo Bonzini 
5608c50d8ae3SPaolo Bonzini 	/*
5609c50d8ae3SPaolo Bonzini 	 * If we don't have indirect shadow pages, it means no page is
5610c50d8ae3SPaolo Bonzini 	 * write-protected, so we can exit simply.
5611c50d8ae3SPaolo Bonzini 	 */
5612c50d8ae3SPaolo Bonzini 	if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5613c50d8ae3SPaolo Bonzini 		return;
5614c50d8ae3SPaolo Bonzini 
5615c50d8ae3SPaolo Bonzini 	pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5616c50d8ae3SPaolo Bonzini 
5617531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
5618c50d8ae3SPaolo Bonzini 
5619c50d8ae3SPaolo Bonzini 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5620c50d8ae3SPaolo Bonzini 
5621c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_pte_write;
5622c50d8ae3SPaolo Bonzini 
5623767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5624c50d8ae3SPaolo Bonzini 		if (detect_write_misaligned(sp, gpa, bytes) ||
5625c50d8ae3SPaolo Bonzini 		      detect_write_flooding(sp)) {
5626c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5627c50d8ae3SPaolo Bonzini 			++vcpu->kvm->stat.mmu_flooded;
5628c50d8ae3SPaolo Bonzini 			continue;
5629c50d8ae3SPaolo Bonzini 		}
5630c50d8ae3SPaolo Bonzini 
5631c50d8ae3SPaolo Bonzini 		spte = get_written_sptes(sp, gpa, &npte);
5632c50d8ae3SPaolo Bonzini 		if (!spte)
5633c50d8ae3SPaolo Bonzini 			continue;
5634c50d8ae3SPaolo Bonzini 
5635c50d8ae3SPaolo Bonzini 		while (npte--) {
5636c50d8ae3SPaolo Bonzini 			entry = *spte;
56372de4085cSBen Gardon 			mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5638c5e2184dSSean Christopherson 			if (gentry && sp->role.level != PG_LEVEL_4K)
5639c5e2184dSSean Christopherson 				++vcpu->kvm->stat.mmu_pde_zapped;
56401441ca14SJunaid Shahid 			if (is_shadow_present_pte(entry))
564106152b2dSLai Jiangshan 				flush = true;
5642c50d8ae3SPaolo Bonzini 			++spte;
5643c50d8ae3SPaolo Bonzini 		}
5644c50d8ae3SPaolo Bonzini 	}
564506152b2dSLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5646531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
5647c50d8ae3SPaolo Bonzini }
5648c50d8ae3SPaolo Bonzini 
56491075d41eSSean Christopherson int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5650c50d8ae3SPaolo Bonzini 		       void *insn, int insn_len)
5651c50d8ae3SPaolo Bonzini {
565292daa48bSSean Christopherson 	int r, emulation_type = EMULTYPE_PF;
5653347a0d0dSPaolo Bonzini 	bool direct = vcpu->arch.mmu->root_role.direct;
5654c50d8ae3SPaolo Bonzini 
5655b9e5603cSPaolo Bonzini 	if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5656ddce6208SSean Christopherson 		return RET_PF_RETRY;
5657ddce6208SSean Christopherson 
5658c50d8ae3SPaolo Bonzini 	r = RET_PF_INVALID;
5659c50d8ae3SPaolo Bonzini 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
5660736c291cSSean Christopherson 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5661c50d8ae3SPaolo Bonzini 		if (r == RET_PF_EMULATE)
5662c50d8ae3SPaolo Bonzini 			goto emulate;
5663c50d8ae3SPaolo Bonzini 	}
5664c50d8ae3SPaolo Bonzini 
5665c50d8ae3SPaolo Bonzini 	if (r == RET_PF_INVALID) {
56667a02674dSSean Christopherson 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
56677a02674dSSean Christopherson 					  lower_32_bits(error_code), false);
566819025e7bSSean Christopherson 		if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
56697b367bc9SSean Christopherson 			return -EIO;
5670c50d8ae3SPaolo Bonzini 	}
5671c50d8ae3SPaolo Bonzini 
5672c50d8ae3SPaolo Bonzini 	if (r < 0)
5673c50d8ae3SPaolo Bonzini 		return r;
567483a2ba4cSSean Christopherson 	if (r != RET_PF_EMULATE)
567583a2ba4cSSean Christopherson 		return 1;
5676c50d8ae3SPaolo Bonzini 
5677c50d8ae3SPaolo Bonzini 	/*
5678c50d8ae3SPaolo Bonzini 	 * Before emulating the instruction, check if the error code
5679c50d8ae3SPaolo Bonzini 	 * was due to a RO violation while translating the guest page.
5680c50d8ae3SPaolo Bonzini 	 * This can occur when using nested virtualization with nested
5681c50d8ae3SPaolo Bonzini 	 * paging in both guests. If true, we simply unprotect the page
5682c50d8ae3SPaolo Bonzini 	 * and resume the guest.
5683c50d8ae3SPaolo Bonzini 	 */
5684347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct &&
5685c50d8ae3SPaolo Bonzini 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5686736c291cSSean Christopherson 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5687c50d8ae3SPaolo Bonzini 		return 1;
5688c50d8ae3SPaolo Bonzini 	}
5689c50d8ae3SPaolo Bonzini 
5690c50d8ae3SPaolo Bonzini 	/*
5691c50d8ae3SPaolo Bonzini 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5692c50d8ae3SPaolo Bonzini 	 * optimistically try to just unprotect the page and let the processor
5693c50d8ae3SPaolo Bonzini 	 * re-execute the instruction that caused the page fault.  Do not allow
5694c50d8ae3SPaolo Bonzini 	 * retrying MMIO emulation, as it's not only pointless but could also
5695c50d8ae3SPaolo Bonzini 	 * cause us to enter an infinite loop because the processor will keep
5696c50d8ae3SPaolo Bonzini 	 * faulting on the non-existent MMIO address.  Retrying an instruction
5697c50d8ae3SPaolo Bonzini 	 * from a nested guest is also pointless and dangerous as we are only
5698c50d8ae3SPaolo Bonzini 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
5699c50d8ae3SPaolo Bonzini 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5700c50d8ae3SPaolo Bonzini 	 */
5701736c291cSSean Christopherson 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
570292daa48bSSean Christopherson 		emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5703c50d8ae3SPaolo Bonzini emulate:
5704736c291cSSean Christopherson 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5705c50d8ae3SPaolo Bonzini 				       insn_len);
5706c50d8ae3SPaolo Bonzini }
5707c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5708c50d8ae3SPaolo Bonzini 
57095efac074SPaolo Bonzini void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
57105efac074SPaolo Bonzini 			    gva_t gva, hpa_t root_hpa)
5711c50d8ae3SPaolo Bonzini {
5712c50d8ae3SPaolo Bonzini 	int i;
5713c50d8ae3SPaolo Bonzini 
57145efac074SPaolo Bonzini 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
57155efac074SPaolo Bonzini 	if (mmu != &vcpu->arch.guest_mmu) {
57165efac074SPaolo Bonzini 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
5717c50d8ae3SPaolo Bonzini 		if (is_noncanonical_address(gva, vcpu))
5718c50d8ae3SPaolo Bonzini 			return;
5719c50d8ae3SPaolo Bonzini 
5720e27bc044SSean Christopherson 		static_call(kvm_x86_flush_tlb_gva)(vcpu, gva);
57215efac074SPaolo Bonzini 	}
57225efac074SPaolo Bonzini 
57235efac074SPaolo Bonzini 	if (!mmu->invlpg)
57245efac074SPaolo Bonzini 		return;
57255efac074SPaolo Bonzini 
57265efac074SPaolo Bonzini 	if (root_hpa == INVALID_PAGE) {
5727b9e5603cSPaolo Bonzini 		mmu->invlpg(vcpu, gva, mmu->root.hpa);
5728c50d8ae3SPaolo Bonzini 
5729c50d8ae3SPaolo Bonzini 		/*
5730c50d8ae3SPaolo Bonzini 		 * INVLPG is required to invalidate any global mappings for the VA,
5731c50d8ae3SPaolo Bonzini 		 * irrespective of PCID. Since it would take us roughly similar amount
5732c50d8ae3SPaolo Bonzini 		 * of work to determine whether any of the prev_root mappings of the VA
5733c50d8ae3SPaolo Bonzini 		 * is marked global, or to just sync it blindly, so we might as well
5734c50d8ae3SPaolo Bonzini 		 * just always sync it.
5735c50d8ae3SPaolo Bonzini 		 *
5736c50d8ae3SPaolo Bonzini 		 * Mappings not reachable via the current cr3 or the prev_roots will be
5737c50d8ae3SPaolo Bonzini 		 * synced when switching to that cr3, so nothing needs to be done here
5738c50d8ae3SPaolo Bonzini 		 * for them.
5739c50d8ae3SPaolo Bonzini 		 */
5740c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5741c50d8ae3SPaolo Bonzini 			if (VALID_PAGE(mmu->prev_roots[i].hpa))
5742c50d8ae3SPaolo Bonzini 				mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
57435efac074SPaolo Bonzini 	} else {
57445efac074SPaolo Bonzini 		mmu->invlpg(vcpu, gva, root_hpa);
57455efac074SPaolo Bonzini 	}
57465efac074SPaolo Bonzini }
5747c50d8ae3SPaolo Bonzini 
57485efac074SPaolo Bonzini void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
57495efac074SPaolo Bonzini {
575005b29633SLai Jiangshan 	kvm_mmu_invalidate_gva(vcpu, vcpu->arch.walk_mmu, gva, INVALID_PAGE);
5751c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5752c50d8ae3SPaolo Bonzini }
5753c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5754c50d8ae3SPaolo Bonzini 
57555efac074SPaolo Bonzini 
5756c50d8ae3SPaolo Bonzini void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5757c50d8ae3SPaolo Bonzini {
5758c50d8ae3SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
5759c50d8ae3SPaolo Bonzini 	bool tlb_flush = false;
5760c50d8ae3SPaolo Bonzini 	uint i;
5761c50d8ae3SPaolo Bonzini 
5762c50d8ae3SPaolo Bonzini 	if (pcid == kvm_get_active_pcid(vcpu)) {
57639f46c187SPaolo Bonzini 		if (mmu->invlpg)
5764b9e5603cSPaolo Bonzini 			mmu->invlpg(vcpu, gva, mmu->root.hpa);
5765c50d8ae3SPaolo Bonzini 		tlb_flush = true;
5766c50d8ae3SPaolo Bonzini 	}
5767c50d8ae3SPaolo Bonzini 
5768c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5769c50d8ae3SPaolo Bonzini 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5770be01e8e2SSean Christopherson 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
57719f46c187SPaolo Bonzini 			if (mmu->invlpg)
5772c50d8ae3SPaolo Bonzini 				mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5773c50d8ae3SPaolo Bonzini 			tlb_flush = true;
5774c50d8ae3SPaolo Bonzini 		}
5775c50d8ae3SPaolo Bonzini 	}
5776c50d8ae3SPaolo Bonzini 
5777c50d8ae3SPaolo Bonzini 	if (tlb_flush)
5778e27bc044SSean Christopherson 		static_call(kvm_x86_flush_tlb_gva)(vcpu, gva);
5779c50d8ae3SPaolo Bonzini 
5780c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5781c50d8ae3SPaolo Bonzini 
5782c50d8ae3SPaolo Bonzini 	/*
5783c50d8ae3SPaolo Bonzini 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5784c50d8ae3SPaolo Bonzini 	 * synced when switching to that cr3, so nothing needs to be done here
5785c50d8ae3SPaolo Bonzini 	 * for them.
5786c50d8ae3SPaolo Bonzini 	 */
5787c50d8ae3SPaolo Bonzini }
5788c50d8ae3SPaolo Bonzini 
5789746700d2SWei Huang void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
5790746700d2SWei Huang 		       int tdp_max_root_level, int tdp_huge_page_level)
5791c50d8ae3SPaolo Bonzini {
5792bde77235SSean Christopherson 	tdp_enabled = enable_tdp;
5793746700d2SWei Huang 	tdp_root_level = tdp_forced_root_level;
579483013059SSean Christopherson 	max_tdp_level = tdp_max_root_level;
5795703c335dSSean Christopherson 
57961f98f2bdSDavid Matlack #ifdef CONFIG_X86_64
57971f98f2bdSDavid Matlack 	tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
57981f98f2bdSDavid Matlack #endif
5799703c335dSSean Christopherson 	/*
58001d92d2e8SSean Christopherson 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5801703c335dSSean Christopherson 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5802703c335dSSean Christopherson 	 * the kernel is not.  But, KVM never creates a page size greater than
5803703c335dSSean Christopherson 	 * what is used by the kernel for any given HVA, i.e. the kernel's
5804703c335dSSean Christopherson 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5805703c335dSSean Christopherson 	 */
5806703c335dSSean Christopherson 	if (tdp_enabled)
58071d92d2e8SSean Christopherson 		max_huge_page_level = tdp_huge_page_level;
5808703c335dSSean Christopherson 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
58091d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_1G;
5810703c335dSSean Christopherson 	else
58111d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_2M;
5812c50d8ae3SPaolo Bonzini }
5813bde77235SSean Christopherson EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5814c50d8ae3SPaolo Bonzini 
5815c50d8ae3SPaolo Bonzini /* The return value indicates if tlb flush on all vcpus is needed. */
5816269e9552SHamza Mahfooz typedef bool (*slot_level_handler) (struct kvm *kvm,
5817269e9552SHamza Mahfooz 				    struct kvm_rmap_head *rmap_head,
5818269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot);
5819c50d8ae3SPaolo Bonzini 
5820c50d8ae3SPaolo Bonzini /* The caller should hold mmu-lock before calling this function. */
5821c50d8ae3SPaolo Bonzini static __always_inline bool
5822269e9552SHamza Mahfooz slot_handle_level_range(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5823c50d8ae3SPaolo Bonzini 			slot_level_handler fn, int start_level, int end_level,
58241a61b7dbSSean Christopherson 			gfn_t start_gfn, gfn_t end_gfn, bool flush_on_yield,
58251a61b7dbSSean Christopherson 			bool flush)
5826c50d8ae3SPaolo Bonzini {
5827c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
5828c50d8ae3SPaolo Bonzini 
5829c50d8ae3SPaolo Bonzini 	for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5830c50d8ae3SPaolo Bonzini 			end_gfn, &iterator) {
5831c50d8ae3SPaolo Bonzini 		if (iterator.rmap)
58320a234f5dSSean Christopherson 			flush |= fn(kvm, iterator.rmap, memslot);
5833c50d8ae3SPaolo Bonzini 
5834531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
5835302695a5SSean Christopherson 			if (flush && flush_on_yield) {
5836c50d8ae3SPaolo Bonzini 				kvm_flush_remote_tlbs_with_address(kvm,
5837c50d8ae3SPaolo Bonzini 						start_gfn,
5838c50d8ae3SPaolo Bonzini 						iterator.gfn - start_gfn + 1);
5839c50d8ae3SPaolo Bonzini 				flush = false;
5840c50d8ae3SPaolo Bonzini 			}
5841531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
5842c50d8ae3SPaolo Bonzini 		}
5843c50d8ae3SPaolo Bonzini 	}
5844c50d8ae3SPaolo Bonzini 
5845c50d8ae3SPaolo Bonzini 	return flush;
5846c50d8ae3SPaolo Bonzini }
5847c50d8ae3SPaolo Bonzini 
5848c50d8ae3SPaolo Bonzini static __always_inline bool
5849269e9552SHamza Mahfooz slot_handle_level(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5850c50d8ae3SPaolo Bonzini 		  slot_level_handler fn, int start_level, int end_level,
5851302695a5SSean Christopherson 		  bool flush_on_yield)
5852c50d8ae3SPaolo Bonzini {
5853c50d8ae3SPaolo Bonzini 	return slot_handle_level_range(kvm, memslot, fn, start_level,
5854c50d8ae3SPaolo Bonzini 			end_level, memslot->base_gfn,
5855c50d8ae3SPaolo Bonzini 			memslot->base_gfn + memslot->npages - 1,
58561a61b7dbSSean Christopherson 			flush_on_yield, false);
5857c50d8ae3SPaolo Bonzini }
5858c50d8ae3SPaolo Bonzini 
5859c50d8ae3SPaolo Bonzini static __always_inline bool
5860610265eaSDavid Matlack slot_handle_level_4k(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5861302695a5SSean Christopherson 		     slot_level_handler fn, bool flush_on_yield)
5862c50d8ae3SPaolo Bonzini {
58633bae0459SSean Christopherson 	return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5864302695a5SSean Christopherson 				 PG_LEVEL_4K, flush_on_yield);
5865c50d8ae3SPaolo Bonzini }
5866c50d8ae3SPaolo Bonzini 
5867c50d8ae3SPaolo Bonzini static void free_mmu_pages(struct kvm_mmu *mmu)
5868c50d8ae3SPaolo Bonzini {
58694a98623dSSean Christopherson 	if (!tdp_enabled && mmu->pae_root)
58704a98623dSSean Christopherson 		set_memory_encrypted((unsigned long)mmu->pae_root, 1);
5871c50d8ae3SPaolo Bonzini 	free_page((unsigned long)mmu->pae_root);
587203ca4589SSean Christopherson 	free_page((unsigned long)mmu->pml4_root);
5873cb0f722aSWei Huang 	free_page((unsigned long)mmu->pml5_root);
5874c50d8ae3SPaolo Bonzini }
5875c50d8ae3SPaolo Bonzini 
587604d28e37SSean Christopherson static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5877c50d8ae3SPaolo Bonzini {
5878c50d8ae3SPaolo Bonzini 	struct page *page;
5879c50d8ae3SPaolo Bonzini 	int i;
5880c50d8ae3SPaolo Bonzini 
5881b9e5603cSPaolo Bonzini 	mmu->root.hpa = INVALID_PAGE;
5882b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
588304d28e37SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
588404d28e37SSean Christopherson 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
588504d28e37SSean Christopherson 
588627f4fca2SLai Jiangshan 	/* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
588727f4fca2SLai Jiangshan 	if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
588827f4fca2SLai Jiangshan 		return 0;
588927f4fca2SLai Jiangshan 
5890c50d8ae3SPaolo Bonzini 	/*
5891c50d8ae3SPaolo Bonzini 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5892c50d8ae3SPaolo Bonzini 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
5893c50d8ae3SPaolo Bonzini 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
5894c50d8ae3SPaolo Bonzini 	 * x86_64.  Therefore we need to allocate the PDP table in the first
589504d45551SSean Christopherson 	 * 4GB of memory, which happens to fit the DMA32 zone.  TDP paging
589604d45551SSean Christopherson 	 * generally doesn't use PAE paging and can skip allocating the PDP
589704d45551SSean Christopherson 	 * table.  The main exception, handled here, is SVM's 32-bit NPT.  The
589804d45551SSean Christopherson 	 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
589984432316SLai Jiangshan 	 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
5900c50d8ae3SPaolo Bonzini 	 */
5901d468d94bSSean Christopherson 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5902c50d8ae3SPaolo Bonzini 		return 0;
5903c50d8ae3SPaolo Bonzini 
5904c50d8ae3SPaolo Bonzini 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5905c50d8ae3SPaolo Bonzini 	if (!page)
5906c50d8ae3SPaolo Bonzini 		return -ENOMEM;
5907c50d8ae3SPaolo Bonzini 
5908c50d8ae3SPaolo Bonzini 	mmu->pae_root = page_address(page);
59094a98623dSSean Christopherson 
59104a98623dSSean Christopherson 	/*
59114a98623dSSean Christopherson 	 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
59124a98623dSSean Christopherson 	 * get the CPU to treat the PDPTEs as encrypted.  Decrypt the page so
59134a98623dSSean Christopherson 	 * that KVM's writes and the CPU's reads get along.  Note, this is
59144a98623dSSean Christopherson 	 * only necessary when using shadow paging, as 64-bit NPT can get at
59154a98623dSSean Christopherson 	 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
59164a98623dSSean Christopherson 	 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
59174a98623dSSean Christopherson 	 */
59184a98623dSSean Christopherson 	if (!tdp_enabled)
59194a98623dSSean Christopherson 		set_memory_decrypted((unsigned long)mmu->pae_root, 1);
59204a98623dSSean Christopherson 	else
5921e54f1ff2SKai Huang 		WARN_ON_ONCE(shadow_me_value);
59224a98623dSSean Christopherson 
5923c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i)
5924c834e5e4SSean Christopherson 		mmu->pae_root[i] = INVALID_PAE_ROOT;
5925c50d8ae3SPaolo Bonzini 
5926c50d8ae3SPaolo Bonzini 	return 0;
5927c50d8ae3SPaolo Bonzini }
5928c50d8ae3SPaolo Bonzini 
5929c50d8ae3SPaolo Bonzini int kvm_mmu_create(struct kvm_vcpu *vcpu)
5930c50d8ae3SPaolo Bonzini {
5931c50d8ae3SPaolo Bonzini 	int ret;
5932c50d8ae3SPaolo Bonzini 
59335962bfb7SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
59345f6078f9SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
59355f6078f9SSean Christopherson 
59365962bfb7SSean Christopherson 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
59375f6078f9SSean Christopherson 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
59385962bfb7SSean Christopherson 
593996880883SSean Christopherson 	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
594096880883SSean Christopherson 
5941c50d8ae3SPaolo Bonzini 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
5942c50d8ae3SPaolo Bonzini 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5943c50d8ae3SPaolo Bonzini 
594404d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
5945c50d8ae3SPaolo Bonzini 	if (ret)
5946c50d8ae3SPaolo Bonzini 		return ret;
5947c50d8ae3SPaolo Bonzini 
594804d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
5949c50d8ae3SPaolo Bonzini 	if (ret)
5950c50d8ae3SPaolo Bonzini 		goto fail_allocate_root;
5951c50d8ae3SPaolo Bonzini 
5952c50d8ae3SPaolo Bonzini 	return ret;
5953c50d8ae3SPaolo Bonzini  fail_allocate_root:
5954c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
5955c50d8ae3SPaolo Bonzini 	return ret;
5956c50d8ae3SPaolo Bonzini }
5957c50d8ae3SPaolo Bonzini 
5958c50d8ae3SPaolo Bonzini #define BATCH_ZAP_PAGES	10
5959c50d8ae3SPaolo Bonzini static void kvm_zap_obsolete_pages(struct kvm *kvm)
5960c50d8ae3SPaolo Bonzini {
5961c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
5962c50d8ae3SPaolo Bonzini 	int nr_zapped, batch = 0;
5963b28cb0cdSSean Christopherson 	bool unstable;
5964c50d8ae3SPaolo Bonzini 
5965c50d8ae3SPaolo Bonzini restart:
5966c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe_reverse(sp, node,
5967c50d8ae3SPaolo Bonzini 	      &kvm->arch.active_mmu_pages, link) {
5968c50d8ae3SPaolo Bonzini 		/*
5969c50d8ae3SPaolo Bonzini 		 * No obsolete valid page exists before a newly created page
5970c50d8ae3SPaolo Bonzini 		 * since active_mmu_pages is a FIFO list.
5971c50d8ae3SPaolo Bonzini 		 */
5972c50d8ae3SPaolo Bonzini 		if (!is_obsolete_sp(kvm, sp))
5973c50d8ae3SPaolo Bonzini 			break;
5974c50d8ae3SPaolo Bonzini 
5975c50d8ae3SPaolo Bonzini 		/*
5976f95eec9bSSean Christopherson 		 * Invalid pages should never land back on the list of active
5977f95eec9bSSean Christopherson 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
5978f95eec9bSSean Christopherson 		 * infinite loop if the page gets put back on the list (again).
5979c50d8ae3SPaolo Bonzini 		 */
5980f95eec9bSSean Christopherson 		if (WARN_ON(sp->role.invalid))
5981c50d8ae3SPaolo Bonzini 			continue;
5982c50d8ae3SPaolo Bonzini 
5983c50d8ae3SPaolo Bonzini 		/*
5984c50d8ae3SPaolo Bonzini 		 * No need to flush the TLB since we're only zapping shadow
5985c50d8ae3SPaolo Bonzini 		 * pages with an obsolete generation number and all vCPUS have
5986c50d8ae3SPaolo Bonzini 		 * loaded a new root, i.e. the shadow pages being zapped cannot
5987c50d8ae3SPaolo Bonzini 		 * be in active use by the guest.
5988c50d8ae3SPaolo Bonzini 		 */
5989c50d8ae3SPaolo Bonzini 		if (batch >= BATCH_ZAP_PAGES &&
5990531810caSBen Gardon 		    cond_resched_rwlock_write(&kvm->mmu_lock)) {
5991c50d8ae3SPaolo Bonzini 			batch = 0;
5992c50d8ae3SPaolo Bonzini 			goto restart;
5993c50d8ae3SPaolo Bonzini 		}
5994c50d8ae3SPaolo Bonzini 
5995b28cb0cdSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
5996b28cb0cdSSean Christopherson 				&kvm->arch.zapped_obsolete_pages, &nr_zapped);
5997c50d8ae3SPaolo Bonzini 		batch += nr_zapped;
5998b28cb0cdSSean Christopherson 
5999b28cb0cdSSean Christopherson 		if (unstable)
6000c50d8ae3SPaolo Bonzini 			goto restart;
6001c50d8ae3SPaolo Bonzini 	}
6002c50d8ae3SPaolo Bonzini 
6003c50d8ae3SPaolo Bonzini 	/*
60047ae5840eSSean Christopherson 	 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
60057ae5840eSSean Christopherson 	 * to ensure KVM is not in the middle of a lockless shadow page table
60067ae5840eSSean Christopherson 	 * walk, which may reference the pages.  The remote TLB flush itself is
60077ae5840eSSean Christopherson 	 * not required and is simply a convenient way to kick vCPUs as needed.
60087ae5840eSSean Christopherson 	 * KVM performs a local TLB flush when allocating a new root (see
60097ae5840eSSean Christopherson 	 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
60107ae5840eSSean Christopherson 	 * running with an obsolete MMU.
6011c50d8ae3SPaolo Bonzini 	 */
6012c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
6013c50d8ae3SPaolo Bonzini }
6014c50d8ae3SPaolo Bonzini 
6015c50d8ae3SPaolo Bonzini /*
6016c50d8ae3SPaolo Bonzini  * Fast invalidate all shadow pages and use lock-break technique
6017c50d8ae3SPaolo Bonzini  * to zap obsolete pages.
6018c50d8ae3SPaolo Bonzini  *
6019c50d8ae3SPaolo Bonzini  * It's required when memslot is being deleted or VM is being
6020c50d8ae3SPaolo Bonzini  * destroyed, in these cases, we should ensure that KVM MMU does
6021c50d8ae3SPaolo Bonzini  * not use any resource of the being-deleted slot or all slots
6022c50d8ae3SPaolo Bonzini  * after calling the function.
6023c50d8ae3SPaolo Bonzini  */
6024c50d8ae3SPaolo Bonzini static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6025c50d8ae3SPaolo Bonzini {
6026c50d8ae3SPaolo Bonzini 	lockdep_assert_held(&kvm->slots_lock);
6027c50d8ae3SPaolo Bonzini 
6028531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6029c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_zap_all_fast(kvm);
6030c50d8ae3SPaolo Bonzini 
6031c50d8ae3SPaolo Bonzini 	/*
6032c50d8ae3SPaolo Bonzini 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
6033c50d8ae3SPaolo Bonzini 	 * held for the entire duration of zapping obsolete pages, it's
6034c50d8ae3SPaolo Bonzini 	 * impossible for there to be multiple invalid generations associated
6035c50d8ae3SPaolo Bonzini 	 * with *valid* shadow pages at any given time, i.e. there is exactly
6036c50d8ae3SPaolo Bonzini 	 * one valid generation and (at most) one invalid generation.
6037c50d8ae3SPaolo Bonzini 	 */
6038c50d8ae3SPaolo Bonzini 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6039c50d8ae3SPaolo Bonzini 
60402f6f66ccSSean Christopherson 	/*
60412f6f66ccSSean Christopherson 	 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
60422f6f66ccSSean Christopherson 	 * invalidating TDP MMU roots must be done while holding mmu_lock for
60432f6f66ccSSean Christopherson 	 * write and in the same critical section as making the reload request,
60442f6f66ccSSean Christopherson 	 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6045b7cccd39SBen Gardon 	 */
60461f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6047b7cccd39SBen Gardon 		kvm_tdp_mmu_invalidate_all_roots(kvm);
6048b7cccd39SBen Gardon 
6049c50d8ae3SPaolo Bonzini 	/*
6050c50d8ae3SPaolo Bonzini 	 * Notify all vcpus to reload its shadow page table and flush TLB.
6051c50d8ae3SPaolo Bonzini 	 * Then all vcpus will switch to new shadow page table with the new
6052c50d8ae3SPaolo Bonzini 	 * mmu_valid_gen.
6053c50d8ae3SPaolo Bonzini 	 *
6054c50d8ae3SPaolo Bonzini 	 * Note: we need to do this under the protection of mmu_lock,
6055c50d8ae3SPaolo Bonzini 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
6056c50d8ae3SPaolo Bonzini 	 */
6057527d5cd7SSean Christopherson 	kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6058c50d8ae3SPaolo Bonzini 
6059c50d8ae3SPaolo Bonzini 	kvm_zap_obsolete_pages(kvm);
6060faaf05b0SBen Gardon 
6061531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
60624c6654bdSBen Gardon 
6063f28e9c7fSSean Christopherson 	/*
6064f28e9c7fSSean Christopherson 	 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6065f28e9c7fSSean Christopherson 	 * returning to the caller, e.g. if the zap is in response to a memslot
6066f28e9c7fSSean Christopherson 	 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6067f28e9c7fSSean Christopherson 	 * associated with the deleted memslot once the update completes, and
6068f28e9c7fSSean Christopherson 	 * Deferring the zap until the final reference to the root is put would
6069f28e9c7fSSean Christopherson 	 * lead to use-after-free.
6070f28e9c7fSSean Christopherson 	 */
60711f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
60724c6654bdSBen Gardon 		kvm_tdp_mmu_zap_invalidated_roots(kvm);
6073c50d8ae3SPaolo Bonzini }
6074c50d8ae3SPaolo Bonzini 
6075c50d8ae3SPaolo Bonzini static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
6076c50d8ae3SPaolo Bonzini {
6077c50d8ae3SPaolo Bonzini 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
6078c50d8ae3SPaolo Bonzini }
6079c50d8ae3SPaolo Bonzini 
6080c50d8ae3SPaolo Bonzini static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
6081c50d8ae3SPaolo Bonzini 			struct kvm_memory_slot *slot,
6082c50d8ae3SPaolo Bonzini 			struct kvm_page_track_notifier_node *node)
6083c50d8ae3SPaolo Bonzini {
6084c50d8ae3SPaolo Bonzini 	kvm_mmu_zap_all_fast(kvm);
6085c50d8ae3SPaolo Bonzini }
6086c50d8ae3SPaolo Bonzini 
6087a1a39128SPaolo Bonzini int kvm_mmu_init_vm(struct kvm *kvm)
6088c50d8ae3SPaolo Bonzini {
6089c50d8ae3SPaolo Bonzini 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6090a1a39128SPaolo Bonzini 	int r;
6091c50d8ae3SPaolo Bonzini 
6092a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6093a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
609455c510e2SSean Christopherson 	INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6095ce25681dSSean Christopherson 	spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6096ce25681dSSean Christopherson 
609709732d2bSDavid Matlack 	if (tdp_mmu_enabled) {
6098a1a39128SPaolo Bonzini 		r = kvm_mmu_init_tdp_mmu(kvm);
6099a1a39128SPaolo Bonzini 		if (r < 0)
6100a1a39128SPaolo Bonzini 			return r;
610109732d2bSDavid Matlack 	}
6102fe5db27dSBen Gardon 
6103c50d8ae3SPaolo Bonzini 	node->track_write = kvm_mmu_pte_write;
6104c50d8ae3SPaolo Bonzini 	node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
6105c50d8ae3SPaolo Bonzini 	kvm_page_track_register_notifier(kvm, node);
6106ada51a9dSDavid Matlack 
6107ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6108ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6109ada51a9dSDavid Matlack 
6110ada51a9dSDavid Matlack 	kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6111ada51a9dSDavid Matlack 
6112ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6113ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6114ada51a9dSDavid Matlack 
6115a1a39128SPaolo Bonzini 	return 0;
6116c50d8ae3SPaolo Bonzini }
6117c50d8ae3SPaolo Bonzini 
6118ada51a9dSDavid Matlack static void mmu_free_vm_memory_caches(struct kvm *kvm)
6119ada51a9dSDavid Matlack {
6120ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6121ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6122ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6123ada51a9dSDavid Matlack }
6124ada51a9dSDavid Matlack 
6125c50d8ae3SPaolo Bonzini void kvm_mmu_uninit_vm(struct kvm *kvm)
6126c50d8ae3SPaolo Bonzini {
6127c50d8ae3SPaolo Bonzini 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6128c50d8ae3SPaolo Bonzini 
6129c50d8ae3SPaolo Bonzini 	kvm_page_track_unregister_notifier(kvm, node);
6130fe5db27dSBen Gardon 
613109732d2bSDavid Matlack 	if (tdp_mmu_enabled)
6132fe5db27dSBen Gardon 		kvm_mmu_uninit_tdp_mmu(kvm);
6133ada51a9dSDavid Matlack 
6134ada51a9dSDavid Matlack 	mmu_free_vm_memory_caches(kvm);
6135c50d8ae3SPaolo Bonzini }
6136c50d8ae3SPaolo Bonzini 
61372833eda0SSean Christopherson static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
613821fa3246SSean Christopherson {
613921fa3246SSean Christopherson 	const struct kvm_memory_slot *memslot;
614021fa3246SSean Christopherson 	struct kvm_memslots *slots;
6141f4209439SMaciej S. Szmigiero 	struct kvm_memslot_iter iter;
614221fa3246SSean Christopherson 	bool flush = false;
614321fa3246SSean Christopherson 	gfn_t start, end;
6144f4209439SMaciej S. Szmigiero 	int i;
614521fa3246SSean Christopherson 
614621fa3246SSean Christopherson 	if (!kvm_memslots_have_rmaps(kvm))
614721fa3246SSean Christopherson 		return flush;
614821fa3246SSean Christopherson 
614921fa3246SSean Christopherson 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
615021fa3246SSean Christopherson 		slots = __kvm_memslots(kvm, i);
6151f4209439SMaciej S. Szmigiero 
6152f4209439SMaciej S. Szmigiero 		kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6153f4209439SMaciej S. Szmigiero 			memslot = iter.slot;
615421fa3246SSean Christopherson 			start = max(gfn_start, memslot->base_gfn);
615521fa3246SSean Christopherson 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
6156f4209439SMaciej S. Szmigiero 			if (WARN_ON_ONCE(start >= end))
615721fa3246SSean Christopherson 				continue;
615821fa3246SSean Christopherson 
6159f8480721SSean Christopherson 			flush = slot_handle_level_range(kvm, memslot, __kvm_zap_rmap,
616021fa3246SSean Christopherson 							PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
616121fa3246SSean Christopherson 							start, end - 1, true, flush);
616221fa3246SSean Christopherson 		}
616321fa3246SSean Christopherson 	}
616421fa3246SSean Christopherson 
616521fa3246SSean Christopherson 	return flush;
616621fa3246SSean Christopherson }
616721fa3246SSean Christopherson 
616888f58535SMaxim Levitsky /*
616988f58535SMaxim Levitsky  * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
617088f58535SMaxim Levitsky  * (not including it)
617188f58535SMaxim Levitsky  */
6172c50d8ae3SPaolo Bonzini void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6173c50d8ae3SPaolo Bonzini {
617421fa3246SSean Christopherson 	bool flush;
6175c50d8ae3SPaolo Bonzini 	int i;
6176c50d8ae3SPaolo Bonzini 
6177f4209439SMaciej S. Szmigiero 	if (WARN_ON_ONCE(gfn_end <= gfn_start))
6178f4209439SMaciej S. Szmigiero 		return;
6179f4209439SMaciej S. Szmigiero 
6180531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
61815a324c24SSean Christopherson 
61826d3085e4SSean Christopherson 	kvm_mmu_invalidate_begin(kvm, 0, -1ul);
6183edb298c6SMaxim Levitsky 
61842833eda0SSean Christopherson 	flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
61856103bc07SBen Gardon 
61861f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
61876103bc07SBen Gardon 		for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
6188f47e5bbbSSean Christopherson 			flush = kvm_tdp_mmu_zap_leafs(kvm, i, gfn_start,
6189f47e5bbbSSean Christopherson 						      gfn_end, true, flush);
61906103bc07SBen Gardon 	}
61915a324c24SSean Christopherson 
61925a324c24SSean Christopherson 	if (flush)
6193bc3b3c10SSean Christopherson 		kvm_flush_remote_tlbs_with_address(kvm, gfn_start,
6194bc3b3c10SSean Christopherson 						   gfn_end - gfn_start);
61955a324c24SSean Christopherson 
61966d3085e4SSean Christopherson 	kvm_mmu_invalidate_end(kvm, 0, -1ul);
6197edb298c6SMaxim Levitsky 
61985a324c24SSean Christopherson 	write_unlock(&kvm->mmu_lock);
6199c50d8ae3SPaolo Bonzini }
6200c50d8ae3SPaolo Bonzini 
6201c50d8ae3SPaolo Bonzini static bool slot_rmap_write_protect(struct kvm *kvm,
62020a234f5dSSean Christopherson 				    struct kvm_rmap_head *rmap_head,
6203269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot)
6204c50d8ae3SPaolo Bonzini {
62051346bbb6SDavid Matlack 	return rmap_write_protect(rmap_head, false);
6206c50d8ae3SPaolo Bonzini }
6207c50d8ae3SPaolo Bonzini 
6208c50d8ae3SPaolo Bonzini void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6209269e9552SHamza Mahfooz 				      const struct kvm_memory_slot *memslot,
62103c9bd400SJay Zhou 				      int start_level)
6211c50d8ae3SPaolo Bonzini {
6212e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6213531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6214b64d740eSJunaid Shahid 		slot_handle_level(kvm, memslot, slot_rmap_write_protect,
6215b64d740eSJunaid Shahid 				  start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6216531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6217e2209710SBen Gardon 	}
6218c50d8ae3SPaolo Bonzini 
62191f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
622024ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6221b64d740eSJunaid Shahid 		kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
622224ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
622324ae4cfaSBen Gardon 	}
6224c50d8ae3SPaolo Bonzini }
6225c50d8ae3SPaolo Bonzini 
6226ada51a9dSDavid Matlack static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6227ada51a9dSDavid Matlack {
6228ada51a9dSDavid Matlack 	return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6229ada51a9dSDavid Matlack }
6230ada51a9dSDavid Matlack 
6231ada51a9dSDavid Matlack static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6232ada51a9dSDavid Matlack {
6233ada51a9dSDavid Matlack 	if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6234ada51a9dSDavid Matlack 		return true;
6235ada51a9dSDavid Matlack 
6236ada51a9dSDavid Matlack 	/*
6237ada51a9dSDavid Matlack 	 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6238ada51a9dSDavid Matlack 	 * to split a single huge page. Calculating how many are actually needed
6239ada51a9dSDavid Matlack 	 * is possible but not worth the complexity.
6240ada51a9dSDavid Matlack 	 */
6241ada51a9dSDavid Matlack 	return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6242ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_page_header_cache, 1) ||
6243ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_shadow_page_cache, 1);
6244ada51a9dSDavid Matlack }
6245ada51a9dSDavid Matlack 
6246ada51a9dSDavid Matlack static int topup_split_caches(struct kvm *kvm)
6247ada51a9dSDavid Matlack {
6248b9b71f43SSean Christopherson 	/*
6249b9b71f43SSean Christopherson 	 * Allocating rmap list entries when splitting huge pages for nested
6250dfd4eb44SSean Christopherson 	 * MMUs is uncommon as KVM needs to use a list if and only if there is
6251b9b71f43SSean Christopherson 	 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6252dfd4eb44SSean Christopherson 	 * aliased by multiple L2 gfns and/or from multiple nested roots with
6253dfd4eb44SSean Christopherson 	 * different roles.  Aliasing gfns when using TDP is atypical for VMMs;
6254dfd4eb44SSean Christopherson 	 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6255dfd4eb44SSean Christopherson 	 * but aliasing rarely occurs post-boot or for many gfns.  If there is
6256dfd4eb44SSean Christopherson 	 * only one rmap entry, rmap->val points directly at that one entry and
6257dfd4eb44SSean Christopherson 	 * doesn't need to allocate a list.  Buffer the cache by the default
6258dfd4eb44SSean Christopherson 	 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6259b9b71f43SSean Christopherson 	 * encounters an aliased gfn or two.
6260b9b71f43SSean Christopherson 	 */
6261b9b71f43SSean Christopherson 	const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6262b9b71f43SSean Christopherson 			     KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6263ada51a9dSDavid Matlack 	int r;
6264ada51a9dSDavid Matlack 
6265ada51a9dSDavid Matlack 	lockdep_assert_held(&kvm->slots_lock);
6266ada51a9dSDavid Matlack 
6267b9b71f43SSean Christopherson 	r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6268ada51a9dSDavid Matlack 					 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6269ada51a9dSDavid Matlack 	if (r)
6270ada51a9dSDavid Matlack 		return r;
6271ada51a9dSDavid Matlack 
6272ada51a9dSDavid Matlack 	r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6273ada51a9dSDavid Matlack 	if (r)
6274ada51a9dSDavid Matlack 		return r;
6275ada51a9dSDavid Matlack 
6276ada51a9dSDavid Matlack 	return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6277ada51a9dSDavid Matlack }
6278ada51a9dSDavid Matlack 
6279ada51a9dSDavid Matlack static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6280ada51a9dSDavid Matlack {
6281ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6282ada51a9dSDavid Matlack 	struct shadow_page_caches caches = {};
6283ada51a9dSDavid Matlack 	union kvm_mmu_page_role role;
6284ada51a9dSDavid Matlack 	unsigned int access;
6285ada51a9dSDavid Matlack 	gfn_t gfn;
6286ada51a9dSDavid Matlack 
628779e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
628879e48cecSSean Christopherson 	access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6289ada51a9dSDavid Matlack 
6290ada51a9dSDavid Matlack 	/*
6291ada51a9dSDavid Matlack 	 * Note, huge page splitting always uses direct shadow pages, regardless
6292ada51a9dSDavid Matlack 	 * of whether the huge page itself is mapped by a direct or indirect
6293ada51a9dSDavid Matlack 	 * shadow page, since the huge page region itself is being directly
6294ada51a9dSDavid Matlack 	 * mapped with smaller pages.
6295ada51a9dSDavid Matlack 	 */
6296ada51a9dSDavid Matlack 	role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6297ada51a9dSDavid Matlack 
6298ada51a9dSDavid Matlack 	/* Direct SPs do not require a shadowed_info_cache. */
6299ada51a9dSDavid Matlack 	caches.page_header_cache = &kvm->arch.split_page_header_cache;
6300ada51a9dSDavid Matlack 	caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6301ada51a9dSDavid Matlack 
6302ada51a9dSDavid Matlack 	/* Safe to pass NULL for vCPU since requesting a direct SP. */
6303ada51a9dSDavid Matlack 	return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6304ada51a9dSDavid Matlack }
6305ada51a9dSDavid Matlack 
6306ada51a9dSDavid Matlack static void shadow_mmu_split_huge_page(struct kvm *kvm,
6307ada51a9dSDavid Matlack 				       const struct kvm_memory_slot *slot,
6308ada51a9dSDavid Matlack 				       u64 *huge_sptep)
6309ada51a9dSDavid Matlack 
6310ada51a9dSDavid Matlack {
6311ada51a9dSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6312ada51a9dSDavid Matlack 	u64 huge_spte = READ_ONCE(*huge_sptep);
6313ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
631403787394SPaolo Bonzini 	bool flush = false;
6315ada51a9dSDavid Matlack 	u64 *sptep, spte;
6316ada51a9dSDavid Matlack 	gfn_t gfn;
6317ada51a9dSDavid Matlack 	int index;
6318ada51a9dSDavid Matlack 
6319ada51a9dSDavid Matlack 	sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6320ada51a9dSDavid Matlack 
6321ada51a9dSDavid Matlack 	for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6322ada51a9dSDavid Matlack 		sptep = &sp->spt[index];
6323ada51a9dSDavid Matlack 		gfn = kvm_mmu_page_get_gfn(sp, index);
6324ada51a9dSDavid Matlack 
6325ada51a9dSDavid Matlack 		/*
6326ada51a9dSDavid Matlack 		 * The SP may already have populated SPTEs, e.g. if this huge
6327ada51a9dSDavid Matlack 		 * page is aliased by multiple sptes with the same access
6328ada51a9dSDavid Matlack 		 * permissions. These entries are guaranteed to map the same
6329ada51a9dSDavid Matlack 		 * gfn-to-pfn translation since the SP is direct, so no need to
6330ada51a9dSDavid Matlack 		 * modify them.
6331ada51a9dSDavid Matlack 		 *
633203787394SPaolo Bonzini 		 * However, if a given SPTE points to a lower level page table,
633303787394SPaolo Bonzini 		 * that lower level page table may only be partially populated.
633403787394SPaolo Bonzini 		 * Installing such SPTEs would effectively unmap a potion of the
633503787394SPaolo Bonzini 		 * huge page. Unmapping guest memory always requires a TLB flush
633603787394SPaolo Bonzini 		 * since a subsequent operation on the unmapped regions would
633703787394SPaolo Bonzini 		 * fail to detect the need to flush.
6338ada51a9dSDavid Matlack 		 */
633903787394SPaolo Bonzini 		if (is_shadow_present_pte(*sptep)) {
634003787394SPaolo Bonzini 			flush |= !is_last_spte(*sptep, sp->role.level);
6341ada51a9dSDavid Matlack 			continue;
634203787394SPaolo Bonzini 		}
6343ada51a9dSDavid Matlack 
6344ada51a9dSDavid Matlack 		spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
6345ada51a9dSDavid Matlack 		mmu_spte_set(sptep, spte);
6346ada51a9dSDavid Matlack 		__rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6347ada51a9dSDavid Matlack 	}
6348ada51a9dSDavid Matlack 
634903787394SPaolo Bonzini 	__link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6350ada51a9dSDavid Matlack }
6351ada51a9dSDavid Matlack 
6352ada51a9dSDavid Matlack static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6353ada51a9dSDavid Matlack 					  const struct kvm_memory_slot *slot,
6354ada51a9dSDavid Matlack 					  u64 *huge_sptep)
6355ada51a9dSDavid Matlack {
6356ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6357ada51a9dSDavid Matlack 	int level, r = 0;
6358ada51a9dSDavid Matlack 	gfn_t gfn;
6359ada51a9dSDavid Matlack 	u64 spte;
6360ada51a9dSDavid Matlack 
6361ada51a9dSDavid Matlack 	/* Grab information for the tracepoint before dropping the MMU lock. */
636279e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6363ada51a9dSDavid Matlack 	level = huge_sp->role.level;
6364ada51a9dSDavid Matlack 	spte = *huge_sptep;
6365ada51a9dSDavid Matlack 
6366ada51a9dSDavid Matlack 	if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6367ada51a9dSDavid Matlack 		r = -ENOSPC;
6368ada51a9dSDavid Matlack 		goto out;
6369ada51a9dSDavid Matlack 	}
6370ada51a9dSDavid Matlack 
6371ada51a9dSDavid Matlack 	if (need_topup_split_caches_or_resched(kvm)) {
6372ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6373ada51a9dSDavid Matlack 		cond_resched();
6374ada51a9dSDavid Matlack 		/*
6375ada51a9dSDavid Matlack 		 * If the topup succeeds, return -EAGAIN to indicate that the
6376ada51a9dSDavid Matlack 		 * rmap iterator should be restarted because the MMU lock was
6377ada51a9dSDavid Matlack 		 * dropped.
6378ada51a9dSDavid Matlack 		 */
6379ada51a9dSDavid Matlack 		r = topup_split_caches(kvm) ?: -EAGAIN;
6380ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6381ada51a9dSDavid Matlack 		goto out;
6382ada51a9dSDavid Matlack 	}
6383ada51a9dSDavid Matlack 
6384ada51a9dSDavid Matlack 	shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6385ada51a9dSDavid Matlack 
6386ada51a9dSDavid Matlack out:
6387ada51a9dSDavid Matlack 	trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6388ada51a9dSDavid Matlack 	return r;
6389ada51a9dSDavid Matlack }
6390ada51a9dSDavid Matlack 
6391ada51a9dSDavid Matlack static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6392ada51a9dSDavid Matlack 					    struct kvm_rmap_head *rmap_head,
6393ada51a9dSDavid Matlack 					    const struct kvm_memory_slot *slot)
6394ada51a9dSDavid Matlack {
6395ada51a9dSDavid Matlack 	struct rmap_iterator iter;
6396ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
6397ada51a9dSDavid Matlack 	u64 *huge_sptep;
6398ada51a9dSDavid Matlack 	int r;
6399ada51a9dSDavid Matlack 
6400ada51a9dSDavid Matlack restart:
6401ada51a9dSDavid Matlack 	for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6402ada51a9dSDavid Matlack 		sp = sptep_to_sp(huge_sptep);
6403ada51a9dSDavid Matlack 
6404ada51a9dSDavid Matlack 		/* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6405ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!sp->role.guest_mode))
6406ada51a9dSDavid Matlack 			continue;
6407ada51a9dSDavid Matlack 
6408ada51a9dSDavid Matlack 		/* The rmaps should never contain non-leaf SPTEs. */
6409ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6410ada51a9dSDavid Matlack 			continue;
6411ada51a9dSDavid Matlack 
6412ada51a9dSDavid Matlack 		/* SPs with level >PG_LEVEL_4K should never by unsync. */
6413ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(sp->unsync))
6414ada51a9dSDavid Matlack 			continue;
6415ada51a9dSDavid Matlack 
6416ada51a9dSDavid Matlack 		/* Don't bother splitting huge pages on invalid SPs. */
6417ada51a9dSDavid Matlack 		if (sp->role.invalid)
6418ada51a9dSDavid Matlack 			continue;
6419ada51a9dSDavid Matlack 
6420ada51a9dSDavid Matlack 		r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6421ada51a9dSDavid Matlack 
6422ada51a9dSDavid Matlack 		/*
6423ada51a9dSDavid Matlack 		 * The split succeeded or needs to be retried because the MMU
6424ada51a9dSDavid Matlack 		 * lock was dropped. Either way, restart the iterator to get it
6425ada51a9dSDavid Matlack 		 * back into a consistent state.
6426ada51a9dSDavid Matlack 		 */
6427ada51a9dSDavid Matlack 		if (!r || r == -EAGAIN)
6428ada51a9dSDavid Matlack 			goto restart;
6429ada51a9dSDavid Matlack 
6430ada51a9dSDavid Matlack 		/* The split failed and shouldn't be retried (e.g. -ENOMEM). */
6431ada51a9dSDavid Matlack 		break;
6432ada51a9dSDavid Matlack 	}
6433ada51a9dSDavid Matlack 
6434ada51a9dSDavid Matlack 	return false;
6435ada51a9dSDavid Matlack }
6436ada51a9dSDavid Matlack 
6437ada51a9dSDavid Matlack static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6438ada51a9dSDavid Matlack 						const struct kvm_memory_slot *slot,
6439ada51a9dSDavid Matlack 						gfn_t start, gfn_t end,
6440ada51a9dSDavid Matlack 						int target_level)
6441ada51a9dSDavid Matlack {
6442ada51a9dSDavid Matlack 	int level;
6443ada51a9dSDavid Matlack 
6444ada51a9dSDavid Matlack 	/*
6445ada51a9dSDavid Matlack 	 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
6446ada51a9dSDavid Matlack 	 * down to the target level. This ensures pages are recursively split
6447ada51a9dSDavid Matlack 	 * all the way to the target level. There's no need to split pages
6448ada51a9dSDavid Matlack 	 * already at the target level.
6449ada51a9dSDavid Matlack 	 */
6450ada51a9dSDavid Matlack 	for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--) {
6451ada51a9dSDavid Matlack 		slot_handle_level_range(kvm, slot, shadow_mmu_try_split_huge_pages,
6452ada51a9dSDavid Matlack 					level, level, start, end - 1, true, false);
6453ada51a9dSDavid Matlack 	}
6454ada51a9dSDavid Matlack }
6455ada51a9dSDavid Matlack 
6456cb00a70bSDavid Matlack /* Must be called with the mmu_lock held in write-mode. */
6457cb00a70bSDavid Matlack void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6458cb00a70bSDavid Matlack 				   const struct kvm_memory_slot *memslot,
6459cb00a70bSDavid Matlack 				   u64 start, u64 end,
6460cb00a70bSDavid Matlack 				   int target_level)
6461cb00a70bSDavid Matlack {
64621f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6463ada51a9dSDavid Matlack 		return;
6464ada51a9dSDavid Matlack 
6465ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm))
6466ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6467ada51a9dSDavid Matlack 
6468ada51a9dSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
6469cb00a70bSDavid Matlack 
6470cb00a70bSDavid Matlack 	/*
6471cb00a70bSDavid Matlack 	 * A TLB flush is unnecessary at this point for the same resons as in
6472cb00a70bSDavid Matlack 	 * kvm_mmu_slot_try_split_huge_pages().
6473cb00a70bSDavid Matlack 	 */
6474cb00a70bSDavid Matlack }
6475cb00a70bSDavid Matlack 
6476a3fe5dbdSDavid Matlack void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6477a3fe5dbdSDavid Matlack 					const struct kvm_memory_slot *memslot,
6478a3fe5dbdSDavid Matlack 					int target_level)
6479a3fe5dbdSDavid Matlack {
6480a3fe5dbdSDavid Matlack 	u64 start = memslot->base_gfn;
6481a3fe5dbdSDavid Matlack 	u64 end = start + memslot->npages;
6482a3fe5dbdSDavid Matlack 
64831f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6484ada51a9dSDavid Matlack 		return;
6485ada51a9dSDavid Matlack 
6486ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm)) {
6487ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6488ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6489ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6490ada51a9dSDavid Matlack 	}
6491ada51a9dSDavid Matlack 
6492a3fe5dbdSDavid Matlack 	read_lock(&kvm->mmu_lock);
6493cb00a70bSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6494a3fe5dbdSDavid Matlack 	read_unlock(&kvm->mmu_lock);
6495a3fe5dbdSDavid Matlack 
6496a3fe5dbdSDavid Matlack 	/*
6497a3fe5dbdSDavid Matlack 	 * No TLB flush is necessary here. KVM will flush TLBs after
6498a3fe5dbdSDavid Matlack 	 * write-protecting and/or clearing dirty on the newly split SPTEs to
6499a3fe5dbdSDavid Matlack 	 * ensure that guest writes are reflected in the dirty log before the
6500a3fe5dbdSDavid Matlack 	 * ioctl to enable dirty logging on this memslot completes. Since the
6501a3fe5dbdSDavid Matlack 	 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6502a3fe5dbdSDavid Matlack 	 * safe for KVM to decide if a TLB flush is necessary based on the split
6503a3fe5dbdSDavid Matlack 	 * SPTEs.
6504a3fe5dbdSDavid Matlack 	 */
6505a3fe5dbdSDavid Matlack }
6506a3fe5dbdSDavid Matlack 
6507c50d8ae3SPaolo Bonzini static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
65080a234f5dSSean Christopherson 					 struct kvm_rmap_head *rmap_head,
6509269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
6510c50d8ae3SPaolo Bonzini {
6511c50d8ae3SPaolo Bonzini 	u64 *sptep;
6512c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
6513c50d8ae3SPaolo Bonzini 	int need_tlb_flush = 0;
6514c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6515c50d8ae3SPaolo Bonzini 
6516c50d8ae3SPaolo Bonzini restart:
6517c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
651857354682SSean Christopherson 		sp = sptep_to_sp(sptep);
6519c50d8ae3SPaolo Bonzini 
6520c50d8ae3SPaolo Bonzini 		/*
6521c50d8ae3SPaolo Bonzini 		 * We cannot do huge page mapping for indirect shadow pages,
6522c50d8ae3SPaolo Bonzini 		 * which are found on the last rmap (level = 1) when not using
6523c50d8ae3SPaolo Bonzini 		 * tdp; such shadow pages are synced with the page table in
6524c50d8ae3SPaolo Bonzini 		 * the guest, and the guest page table is using 4K page size
6525c50d8ae3SPaolo Bonzini 		 * mapping if the indirect sp has level = 1.
6526c50d8ae3SPaolo Bonzini 		 */
65275d49f08cSSean Christopherson 		if (sp->role.direct &&
65289eba50f8SSean Christopherson 		    sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
6529a8ac499bSSean Christopherson 							       PG_LEVEL_NUM)) {
65309202aee8SSean Christopherson 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
6531c50d8ae3SPaolo Bonzini 
6532c50d8ae3SPaolo Bonzini 			if (kvm_available_flush_tlb_with_range())
65331b2dc736SHou Wenlong 				kvm_flush_remote_tlbs_sptep(kvm, sptep);
6534c50d8ae3SPaolo Bonzini 			else
6535c50d8ae3SPaolo Bonzini 				need_tlb_flush = 1;
6536c50d8ae3SPaolo Bonzini 
6537c50d8ae3SPaolo Bonzini 			goto restart;
6538c50d8ae3SPaolo Bonzini 		}
6539c50d8ae3SPaolo Bonzini 	}
6540c50d8ae3SPaolo Bonzini 
6541c50d8ae3SPaolo Bonzini 	return need_tlb_flush;
6542c50d8ae3SPaolo Bonzini }
6543c50d8ae3SPaolo Bonzini 
654420d49186SDavid Matlack static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
654520d49186SDavid Matlack 					   const struct kvm_memory_slot *slot)
654620d49186SDavid Matlack {
654720d49186SDavid Matlack 	/*
654820d49186SDavid Matlack 	 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
654920d49186SDavid Matlack 	 * pages that are already mapped at the maximum hugepage level.
655020d49186SDavid Matlack 	 */
655120d49186SDavid Matlack 	if (slot_handle_level(kvm, slot, kvm_mmu_zap_collapsible_spte,
655220d49186SDavid Matlack 			      PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
655320d49186SDavid Matlack 		kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
655420d49186SDavid Matlack }
655520d49186SDavid Matlack 
6556c50d8ae3SPaolo Bonzini void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6557269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *slot)
6558c50d8ae3SPaolo Bonzini {
6559e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6560531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
656120d49186SDavid Matlack 		kvm_rmap_zap_collapsible_sptes(kvm, slot);
6562531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6563e2209710SBen Gardon 	}
65642db6f772SBen Gardon 
65651f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
65662db6f772SBen Gardon 		read_lock(&kvm->mmu_lock);
65674b85c921SSean Christopherson 		kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
65682db6f772SBen Gardon 		read_unlock(&kvm->mmu_lock);
65692db6f772SBen Gardon 	}
6570c50d8ae3SPaolo Bonzini }
6571c50d8ae3SPaolo Bonzini 
6572b3594ffbSSean Christopherson void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
65736c9dd6d2SPaolo Bonzini 					const struct kvm_memory_slot *memslot)
6574b3594ffbSSean Christopherson {
6575b3594ffbSSean Christopherson 	/*
65767f42aa76SSean Christopherson 	 * All current use cases for flushing the TLBs for a specific memslot
6577302695a5SSean Christopherson 	 * related to dirty logging, and many do the TLB flush out of mmu_lock.
65787f42aa76SSean Christopherson 	 * The interaction between the various operations on memslot must be
65797f42aa76SSean Christopherson 	 * serialized by slots_locks to ensure the TLB flush from one operation
65807f42aa76SSean Christopherson 	 * is observed by any other operation on the same memslot.
6581b3594ffbSSean Christopherson 	 */
6582b3594ffbSSean Christopherson 	lockdep_assert_held(&kvm->slots_lock);
6583cec37648SSean Christopherson 	kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6584cec37648SSean Christopherson 					   memslot->npages);
6585b3594ffbSSean Christopherson }
6586b3594ffbSSean Christopherson 
6587c50d8ae3SPaolo Bonzini void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6588269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *memslot)
6589c50d8ae3SPaolo Bonzini {
6590e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6591531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6592610265eaSDavid Matlack 		/*
6593610265eaSDavid Matlack 		 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6594610265eaSDavid Matlack 		 * support dirty logging at a 4k granularity.
6595610265eaSDavid Matlack 		 */
6596b64d740eSJunaid Shahid 		slot_handle_level_4k(kvm, memslot, __rmap_clear_dirty, false);
6597531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6598e2209710SBen Gardon 	}
6599c50d8ae3SPaolo Bonzini 
66001f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
660124ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6602b64d740eSJunaid Shahid 		kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
660324ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
660424ae4cfaSBen Gardon 	}
660524ae4cfaSBen Gardon 
6606c50d8ae3SPaolo Bonzini 	/*
6607b64d740eSJunaid Shahid 	 * The caller will flush the TLBs after this function returns.
6608b64d740eSJunaid Shahid 	 *
6609c50d8ae3SPaolo Bonzini 	 * It's also safe to flush TLBs out of mmu lock here as currently this
6610c50d8ae3SPaolo Bonzini 	 * function is only used for dirty logging, in which case flushing TLB
6611c50d8ae3SPaolo Bonzini 	 * out of mmu lock also guarantees no dirty pages will be lost in
6612c50d8ae3SPaolo Bonzini 	 * dirty_bitmap.
6613c50d8ae3SPaolo Bonzini 	 */
6614c50d8ae3SPaolo Bonzini }
6615c50d8ae3SPaolo Bonzini 
6616c50d8ae3SPaolo Bonzini void kvm_mmu_zap_all(struct kvm *kvm)
6617c50d8ae3SPaolo Bonzini {
6618c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6619c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6620c50d8ae3SPaolo Bonzini 	int ign;
6621c50d8ae3SPaolo Bonzini 
6622531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6623c50d8ae3SPaolo Bonzini restart:
6624c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6625f95eec9bSSean Christopherson 		if (WARN_ON(sp->role.invalid))
6626c50d8ae3SPaolo Bonzini 			continue;
6627c50d8ae3SPaolo Bonzini 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6628c50d8ae3SPaolo Bonzini 			goto restart;
6629531810caSBen Gardon 		if (cond_resched_rwlock_write(&kvm->mmu_lock))
6630c50d8ae3SPaolo Bonzini 			goto restart;
6631c50d8ae3SPaolo Bonzini 	}
6632c50d8ae3SPaolo Bonzini 
6633c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6634faaf05b0SBen Gardon 
66351f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6636faaf05b0SBen Gardon 		kvm_tdp_mmu_zap_all(kvm);
6637faaf05b0SBen Gardon 
6638531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
6639c50d8ae3SPaolo Bonzini }
6640c50d8ae3SPaolo Bonzini 
6641c50d8ae3SPaolo Bonzini void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6642c50d8ae3SPaolo Bonzini {
6643c50d8ae3SPaolo Bonzini 	WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6644c50d8ae3SPaolo Bonzini 
6645c50d8ae3SPaolo Bonzini 	gen &= MMIO_SPTE_GEN_MASK;
6646c50d8ae3SPaolo Bonzini 
6647c50d8ae3SPaolo Bonzini 	/*
6648c50d8ae3SPaolo Bonzini 	 * Generation numbers are incremented in multiples of the number of
6649c50d8ae3SPaolo Bonzini 	 * address spaces in order to provide unique generations across all
6650c50d8ae3SPaolo Bonzini 	 * address spaces.  Strip what is effectively the address space
6651c50d8ae3SPaolo Bonzini 	 * modifier prior to checking for a wrap of the MMIO generation so
6652c50d8ae3SPaolo Bonzini 	 * that a wrap in any address space is detected.
6653c50d8ae3SPaolo Bonzini 	 */
6654c50d8ae3SPaolo Bonzini 	gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6655c50d8ae3SPaolo Bonzini 
6656c50d8ae3SPaolo Bonzini 	/*
6657c50d8ae3SPaolo Bonzini 	 * The very rare case: if the MMIO generation number has wrapped,
6658c50d8ae3SPaolo Bonzini 	 * zap all shadow pages.
6659c50d8ae3SPaolo Bonzini 	 */
6660c50d8ae3SPaolo Bonzini 	if (unlikely(gen == 0)) {
66618d20bd63SSean Christopherson 		kvm_debug_ratelimited("zapping shadow pages for mmio generation wraparound\n");
6662c50d8ae3SPaolo Bonzini 		kvm_mmu_zap_all_fast(kvm);
6663c50d8ae3SPaolo Bonzini 	}
6664c50d8ae3SPaolo Bonzini }
6665c50d8ae3SPaolo Bonzini 
6666c50d8ae3SPaolo Bonzini static unsigned long
6667c50d8ae3SPaolo Bonzini mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6668c50d8ae3SPaolo Bonzini {
6669c50d8ae3SPaolo Bonzini 	struct kvm *kvm;
6670c50d8ae3SPaolo Bonzini 	int nr_to_scan = sc->nr_to_scan;
6671c50d8ae3SPaolo Bonzini 	unsigned long freed = 0;
6672c50d8ae3SPaolo Bonzini 
6673c50d8ae3SPaolo Bonzini 	mutex_lock(&kvm_lock);
6674c50d8ae3SPaolo Bonzini 
6675c50d8ae3SPaolo Bonzini 	list_for_each_entry(kvm, &vm_list, vm_list) {
6676c50d8ae3SPaolo Bonzini 		int idx;
6677c50d8ae3SPaolo Bonzini 		LIST_HEAD(invalid_list);
6678c50d8ae3SPaolo Bonzini 
6679c50d8ae3SPaolo Bonzini 		/*
6680c50d8ae3SPaolo Bonzini 		 * Never scan more than sc->nr_to_scan VM instances.
6681c50d8ae3SPaolo Bonzini 		 * Will not hit this condition practically since we do not try
6682c50d8ae3SPaolo Bonzini 		 * to shrink more than one VM and it is very unlikely to see
6683c50d8ae3SPaolo Bonzini 		 * !n_used_mmu_pages so many times.
6684c50d8ae3SPaolo Bonzini 		 */
6685c50d8ae3SPaolo Bonzini 		if (!nr_to_scan--)
6686c50d8ae3SPaolo Bonzini 			break;
6687c50d8ae3SPaolo Bonzini 		/*
6688c50d8ae3SPaolo Bonzini 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6689c50d8ae3SPaolo Bonzini 		 * here. We may skip a VM instance errorneosly, but we do not
6690c50d8ae3SPaolo Bonzini 		 * want to shrink a VM that only started to populate its MMU
6691c50d8ae3SPaolo Bonzini 		 * anyway.
6692c50d8ae3SPaolo Bonzini 		 */
6693c50d8ae3SPaolo Bonzini 		if (!kvm->arch.n_used_mmu_pages &&
6694c50d8ae3SPaolo Bonzini 		    !kvm_has_zapped_obsolete_pages(kvm))
6695c50d8ae3SPaolo Bonzini 			continue;
6696c50d8ae3SPaolo Bonzini 
6697c50d8ae3SPaolo Bonzini 		idx = srcu_read_lock(&kvm->srcu);
6698531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6699c50d8ae3SPaolo Bonzini 
6700c50d8ae3SPaolo Bonzini 		if (kvm_has_zapped_obsolete_pages(kvm)) {
6701c50d8ae3SPaolo Bonzini 			kvm_mmu_commit_zap_page(kvm,
6702c50d8ae3SPaolo Bonzini 			      &kvm->arch.zapped_obsolete_pages);
6703c50d8ae3SPaolo Bonzini 			goto unlock;
6704c50d8ae3SPaolo Bonzini 		}
6705c50d8ae3SPaolo Bonzini 
6706ebdb292dSSean Christopherson 		freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6707c50d8ae3SPaolo Bonzini 
6708c50d8ae3SPaolo Bonzini unlock:
6709531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6710c50d8ae3SPaolo Bonzini 		srcu_read_unlock(&kvm->srcu, idx);
6711c50d8ae3SPaolo Bonzini 
6712c50d8ae3SPaolo Bonzini 		/*
6713c50d8ae3SPaolo Bonzini 		 * unfair on small ones
6714c50d8ae3SPaolo Bonzini 		 * per-vm shrinkers cry out
6715c50d8ae3SPaolo Bonzini 		 * sadness comes quickly
6716c50d8ae3SPaolo Bonzini 		 */
6717c50d8ae3SPaolo Bonzini 		list_move_tail(&kvm->vm_list, &vm_list);
6718c50d8ae3SPaolo Bonzini 		break;
6719c50d8ae3SPaolo Bonzini 	}
6720c50d8ae3SPaolo Bonzini 
6721c50d8ae3SPaolo Bonzini 	mutex_unlock(&kvm_lock);
6722c50d8ae3SPaolo Bonzini 	return freed;
6723c50d8ae3SPaolo Bonzini }
6724c50d8ae3SPaolo Bonzini 
6725c50d8ae3SPaolo Bonzini static unsigned long
6726c50d8ae3SPaolo Bonzini mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6727c50d8ae3SPaolo Bonzini {
6728c50d8ae3SPaolo Bonzini 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6729c50d8ae3SPaolo Bonzini }
6730c50d8ae3SPaolo Bonzini 
6731c50d8ae3SPaolo Bonzini static struct shrinker mmu_shrinker = {
6732c50d8ae3SPaolo Bonzini 	.count_objects = mmu_shrink_count,
6733c50d8ae3SPaolo Bonzini 	.scan_objects = mmu_shrink_scan,
6734c50d8ae3SPaolo Bonzini 	.seeks = DEFAULT_SEEKS * 10,
6735c50d8ae3SPaolo Bonzini };
6736c50d8ae3SPaolo Bonzini 
6737c50d8ae3SPaolo Bonzini static void mmu_destroy_caches(void)
6738c50d8ae3SPaolo Bonzini {
6739c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(pte_list_desc_cache);
6740c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(mmu_page_header_cache);
6741c50d8ae3SPaolo Bonzini }
6742c50d8ae3SPaolo Bonzini 
6743c50d8ae3SPaolo Bonzini static bool get_nx_auto_mode(void)
6744c50d8ae3SPaolo Bonzini {
6745c50d8ae3SPaolo Bonzini 	/* Return true when CPU has the bug, and mitigations are ON */
6746c50d8ae3SPaolo Bonzini 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6747c50d8ae3SPaolo Bonzini }
6748c50d8ae3SPaolo Bonzini 
6749c50d8ae3SPaolo Bonzini static void __set_nx_huge_pages(bool val)
6750c50d8ae3SPaolo Bonzini {
6751c50d8ae3SPaolo Bonzini 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6752c50d8ae3SPaolo Bonzini }
6753c50d8ae3SPaolo Bonzini 
6754c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6755c50d8ae3SPaolo Bonzini {
6756c50d8ae3SPaolo Bonzini 	bool old_val = nx_huge_pages;
6757c50d8ae3SPaolo Bonzini 	bool new_val;
6758c50d8ae3SPaolo Bonzini 
6759c50d8ae3SPaolo Bonzini 	/* In "auto" mode deploy workaround only if CPU has the bug. */
6760c50d8ae3SPaolo Bonzini 	if (sysfs_streq(val, "off"))
6761c50d8ae3SPaolo Bonzini 		new_val = 0;
6762c50d8ae3SPaolo Bonzini 	else if (sysfs_streq(val, "force"))
6763c50d8ae3SPaolo Bonzini 		new_val = 1;
6764c50d8ae3SPaolo Bonzini 	else if (sysfs_streq(val, "auto"))
6765c50d8ae3SPaolo Bonzini 		new_val = get_nx_auto_mode();
6766c50d8ae3SPaolo Bonzini 	else if (strtobool(val, &new_val) < 0)
6767c50d8ae3SPaolo Bonzini 		return -EINVAL;
6768c50d8ae3SPaolo Bonzini 
6769c50d8ae3SPaolo Bonzini 	__set_nx_huge_pages(new_val);
6770c50d8ae3SPaolo Bonzini 
6771c50d8ae3SPaolo Bonzini 	if (new_val != old_val) {
6772c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6773c50d8ae3SPaolo Bonzini 
6774c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6775c50d8ae3SPaolo Bonzini 
6776c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list) {
6777c50d8ae3SPaolo Bonzini 			mutex_lock(&kvm->slots_lock);
6778c50d8ae3SPaolo Bonzini 			kvm_mmu_zap_all_fast(kvm);
6779c50d8ae3SPaolo Bonzini 			mutex_unlock(&kvm->slots_lock);
6780c50d8ae3SPaolo Bonzini 
678155c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
6782c50d8ae3SPaolo Bonzini 		}
6783c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6784c50d8ae3SPaolo Bonzini 	}
6785c50d8ae3SPaolo Bonzini 
6786c50d8ae3SPaolo Bonzini 	return 0;
6787c50d8ae3SPaolo Bonzini }
6788c50d8ae3SPaolo Bonzini 
67891d0e8480SSean Christopherson /*
67901d0e8480SSean Christopherson  * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
67911d0e8480SSean Christopherson  * its default value of -1 is technically undefined behavior for a boolean.
6792c3e0c8c2SSean Christopherson  * Forward the module init call to SPTE code so that it too can handle module
6793c3e0c8c2SSean Christopherson  * params that need to be resolved/snapshot.
67941d0e8480SSean Christopherson  */
6795982bae43SSean Christopherson void __init kvm_mmu_x86_module_init(void)
6796c50d8ae3SPaolo Bonzini {
6797c50d8ae3SPaolo Bonzini 	if (nx_huge_pages == -1)
6798c50d8ae3SPaolo Bonzini 		__set_nx_huge_pages(get_nx_auto_mode());
6799c3e0c8c2SSean Christopherson 
68001f98f2bdSDavid Matlack 	/*
68011f98f2bdSDavid Matlack 	 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
68021f98f2bdSDavid Matlack 	 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
68031f98f2bdSDavid Matlack 	 * when the vendor module is loaded.
68041f98f2bdSDavid Matlack 	 */
68051f98f2bdSDavid Matlack 	tdp_mmu_allowed = tdp_mmu_enabled;
68061f98f2bdSDavid Matlack 
6807c3e0c8c2SSean Christopherson 	kvm_mmu_spte_module_init();
68081d0e8480SSean Christopherson }
68091d0e8480SSean Christopherson 
68101d0e8480SSean Christopherson /*
68111d0e8480SSean Christopherson  * The bulk of the MMU initialization is deferred until the vendor module is
68121d0e8480SSean Christopherson  * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
68131d0e8480SSean Christopherson  * to be reset when a potentially different vendor module is loaded.
68141d0e8480SSean Christopherson  */
68151d0e8480SSean Christopherson int kvm_mmu_vendor_module_init(void)
68161d0e8480SSean Christopherson {
68171d0e8480SSean Christopherson 	int ret = -ENOMEM;
6818c50d8ae3SPaolo Bonzini 
6819c50d8ae3SPaolo Bonzini 	/*
6820c50d8ae3SPaolo Bonzini 	 * MMU roles use union aliasing which is, generally speaking, an
6821c50d8ae3SPaolo Bonzini 	 * undefined behavior. However, we supposedly know how compilers behave
6822c50d8ae3SPaolo Bonzini 	 * and the current status quo is unlikely to change. Guardians below are
6823c50d8ae3SPaolo Bonzini 	 * supposed to let us know if the assumption becomes false.
6824c50d8ae3SPaolo Bonzini 	 */
6825c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6826c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
68277a7ae829SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
6828c50d8ae3SPaolo Bonzini 
6829c50d8ae3SPaolo Bonzini 	kvm_mmu_reset_all_pte_masks();
6830c50d8ae3SPaolo Bonzini 
6831c50d8ae3SPaolo Bonzini 	pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6832c50d8ae3SPaolo Bonzini 					    sizeof(struct pte_list_desc),
6833c50d8ae3SPaolo Bonzini 					    0, SLAB_ACCOUNT, NULL);
6834c50d8ae3SPaolo Bonzini 	if (!pte_list_desc_cache)
6835c50d8ae3SPaolo Bonzini 		goto out;
6836c50d8ae3SPaolo Bonzini 
6837c50d8ae3SPaolo Bonzini 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6838c50d8ae3SPaolo Bonzini 						  sizeof(struct kvm_mmu_page),
6839c50d8ae3SPaolo Bonzini 						  0, SLAB_ACCOUNT, NULL);
6840c50d8ae3SPaolo Bonzini 	if (!mmu_page_header_cache)
6841c50d8ae3SPaolo Bonzini 		goto out;
6842c50d8ae3SPaolo Bonzini 
6843c50d8ae3SPaolo Bonzini 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6844c50d8ae3SPaolo Bonzini 		goto out;
6845c50d8ae3SPaolo Bonzini 
6846e33c267aSRoman Gushchin 	ret = register_shrinker(&mmu_shrinker, "x86-mmu");
6847c50d8ae3SPaolo Bonzini 	if (ret)
6848d7c9bfb9SMiaohe Lin 		goto out_shrinker;
6849c50d8ae3SPaolo Bonzini 
6850c50d8ae3SPaolo Bonzini 	return 0;
6851c50d8ae3SPaolo Bonzini 
6852d7c9bfb9SMiaohe Lin out_shrinker:
6853d7c9bfb9SMiaohe Lin 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6854c50d8ae3SPaolo Bonzini out:
6855c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6856c50d8ae3SPaolo Bonzini 	return ret;
6857c50d8ae3SPaolo Bonzini }
6858c50d8ae3SPaolo Bonzini 
6859c50d8ae3SPaolo Bonzini void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6860c50d8ae3SPaolo Bonzini {
6861c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
6862c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.root_mmu);
6863c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
6864c50d8ae3SPaolo Bonzini 	mmu_free_memory_caches(vcpu);
6865c50d8ae3SPaolo Bonzini }
6866c50d8ae3SPaolo Bonzini 
68671d0e8480SSean Christopherson void kvm_mmu_vendor_module_exit(void)
6868c50d8ae3SPaolo Bonzini {
6869c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6870c50d8ae3SPaolo Bonzini 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6871c50d8ae3SPaolo Bonzini 	unregister_shrinker(&mmu_shrinker);
6872c50d8ae3SPaolo Bonzini }
6873c50d8ae3SPaolo Bonzini 
6874f47491d7SSean Christopherson /*
6875f47491d7SSean Christopherson  * Calculate the effective recovery period, accounting for '0' meaning "let KVM
6876f47491d7SSean Christopherson  * select a halving time of 1 hour".  Returns true if recovery is enabled.
6877f47491d7SSean Christopherson  */
6878f47491d7SSean Christopherson static bool calc_nx_huge_pages_recovery_period(uint *period)
6879f47491d7SSean Christopherson {
6880f47491d7SSean Christopherson 	/*
6881f47491d7SSean Christopherson 	 * Use READ_ONCE to get the params, this may be called outside of the
6882f47491d7SSean Christopherson 	 * param setters, e.g. by the kthread to compute its next timeout.
6883f47491d7SSean Christopherson 	 */
6884f47491d7SSean Christopherson 	bool enabled = READ_ONCE(nx_huge_pages);
6885f47491d7SSean Christopherson 	uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6886f47491d7SSean Christopherson 
6887f47491d7SSean Christopherson 	if (!enabled || !ratio)
6888f47491d7SSean Christopherson 		return false;
6889f47491d7SSean Christopherson 
6890f47491d7SSean Christopherson 	*period = READ_ONCE(nx_huge_pages_recovery_period_ms);
6891f47491d7SSean Christopherson 	if (!*period) {
6892f47491d7SSean Christopherson 		/* Make sure the period is not less than one second.  */
6893f47491d7SSean Christopherson 		ratio = min(ratio, 3600u);
6894f47491d7SSean Christopherson 		*period = 60 * 60 * 1000 / ratio;
6895f47491d7SSean Christopherson 	}
6896f47491d7SSean Christopherson 	return true;
6897f47491d7SSean Christopherson }
6898f47491d7SSean Christopherson 
68994dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
6900c50d8ae3SPaolo Bonzini {
69014dfe4f40SJunaid Shahid 	bool was_recovery_enabled, is_recovery_enabled;
69024dfe4f40SJunaid Shahid 	uint old_period, new_period;
6903c50d8ae3SPaolo Bonzini 	int err;
6904c50d8ae3SPaolo Bonzini 
6905f47491d7SSean Christopherson 	was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
69064dfe4f40SJunaid Shahid 
6907c50d8ae3SPaolo Bonzini 	err = param_set_uint(val, kp);
6908c50d8ae3SPaolo Bonzini 	if (err)
6909c50d8ae3SPaolo Bonzini 		return err;
6910c50d8ae3SPaolo Bonzini 
6911f47491d7SSean Christopherson 	is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
69124dfe4f40SJunaid Shahid 
6913f47491d7SSean Christopherson 	if (is_recovery_enabled &&
69144dfe4f40SJunaid Shahid 	    (!was_recovery_enabled || old_period > new_period)) {
6915c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6916c50d8ae3SPaolo Bonzini 
6917c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6918c50d8ae3SPaolo Bonzini 
6919c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list)
692055c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
6921c50d8ae3SPaolo Bonzini 
6922c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6923c50d8ae3SPaolo Bonzini 	}
6924c50d8ae3SPaolo Bonzini 
6925c50d8ae3SPaolo Bonzini 	return err;
6926c50d8ae3SPaolo Bonzini }
6927c50d8ae3SPaolo Bonzini 
692855c510e2SSean Christopherson static void kvm_recover_nx_huge_pages(struct kvm *kvm)
6929c50d8ae3SPaolo Bonzini {
6930ade74e14SSean Christopherson 	unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
6931eb298605SDavid Matlack 	struct kvm_memory_slot *slot;
6932c50d8ae3SPaolo Bonzini 	int rcu_idx;
6933c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6934c50d8ae3SPaolo Bonzini 	unsigned int ratio;
6935c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6936048f4980SSean Christopherson 	bool flush = false;
6937c50d8ae3SPaolo Bonzini 	ulong to_zap;
6938c50d8ae3SPaolo Bonzini 
6939c50d8ae3SPaolo Bonzini 	rcu_idx = srcu_read_lock(&kvm->srcu);
6940531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6941c50d8ae3SPaolo Bonzini 
6942bb95dfb9SSean Christopherson 	/*
6943bb95dfb9SSean Christopherson 	 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
6944bb95dfb9SSean Christopherson 	 * be done under RCU protection, because the pages are freed via RCU
6945bb95dfb9SSean Christopherson 	 * callback.
6946bb95dfb9SSean Christopherson 	 */
6947bb95dfb9SSean Christopherson 	rcu_read_lock();
6948bb95dfb9SSean Christopherson 
6949c50d8ae3SPaolo Bonzini 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6950ade74e14SSean Christopherson 	to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
69517d919c7aSSean Christopherson 	for ( ; to_zap; --to_zap) {
695255c510e2SSean Christopherson 		if (list_empty(&kvm->arch.possible_nx_huge_pages))
69537d919c7aSSean Christopherson 			break;
69547d919c7aSSean Christopherson 
6955c50d8ae3SPaolo Bonzini 		/*
6956c50d8ae3SPaolo Bonzini 		 * We use a separate list instead of just using active_mmu_pages
695755c510e2SSean Christopherson 		 * because the number of shadow pages that be replaced with an
695855c510e2SSean Christopherson 		 * NX huge page is expected to be relatively small compared to
695955c510e2SSean Christopherson 		 * the total number of shadow pages.  And because the TDP MMU
696055c510e2SSean Christopherson 		 * doesn't use active_mmu_pages.
6961c50d8ae3SPaolo Bonzini 		 */
696255c510e2SSean Christopherson 		sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
6963c50d8ae3SPaolo Bonzini 				      struct kvm_mmu_page,
696455c510e2SSean Christopherson 				      possible_nx_huge_page_link);
696555c510e2SSean Christopherson 		WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
6966eb298605SDavid Matlack 		WARN_ON_ONCE(!sp->role.direct);
6967eb298605SDavid Matlack 
6968eb298605SDavid Matlack 		/*
6969eb298605SDavid Matlack 		 * Unaccount and do not attempt to recover any NX Huge Pages
6970eb298605SDavid Matlack 		 * that are being dirty tracked, as they would just be faulted
6971eb298605SDavid Matlack 		 * back in as 4KiB pages. The NX Huge Pages in this slot will be
6972eb298605SDavid Matlack 		 * recovered, along with all the other huge pages in the slot,
6973eb298605SDavid Matlack 		 * when dirty logging is disabled.
69746c7b2202SPaolo Bonzini 		 *
69756c7b2202SPaolo Bonzini 		 * Since gfn_to_memslot() is relatively expensive, it helps to
69766c7b2202SPaolo Bonzini 		 * skip it if it the test cannot possibly return true.  On the
69776c7b2202SPaolo Bonzini 		 * other hand, if any memslot has logging enabled, chances are
69786c7b2202SPaolo Bonzini 		 * good that all of them do, in which case unaccount_nx_huge_page()
69796c7b2202SPaolo Bonzini 		 * is much cheaper than zapping the page.
69806c7b2202SPaolo Bonzini 		 *
69816c7b2202SPaolo Bonzini 		 * If a memslot update is in progress, reading an incorrect value
69826c7b2202SPaolo Bonzini 		 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
69836c7b2202SPaolo Bonzini 		 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
69846c7b2202SPaolo Bonzini 		 * it is becoming nonzero, the page will be zapped unnecessarily.
69856c7b2202SPaolo Bonzini 		 * Either way, this only affects efficiency in racy situations,
69866c7b2202SPaolo Bonzini 		 * and not correctness.
6987eb298605SDavid Matlack 		 */
69886c7b2202SPaolo Bonzini 		slot = NULL;
69896c7b2202SPaolo Bonzini 		if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
69906c7b2202SPaolo Bonzini 			slot = gfn_to_memslot(kvm, sp->gfn);
69916c7b2202SPaolo Bonzini 			WARN_ON_ONCE(!slot);
699229cf0f50SBen Gardon 		}
6993c50d8ae3SPaolo Bonzini 
6994eb298605SDavid Matlack 		if (slot && kvm_slot_dirty_track_enabled(slot))
6995eb298605SDavid Matlack 			unaccount_nx_huge_page(kvm, sp);
6996eb298605SDavid Matlack 		else if (is_tdp_mmu_page(sp))
6997c50d8ae3SPaolo Bonzini 			flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
69983a056757SSean Christopherson 		else
6999c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
700055c510e2SSean Christopherson 		WARN_ON_ONCE(sp->nx_huge_page_disallowed);
7001c50d8ae3SPaolo Bonzini 
7002531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7003048f4980SSean Christopherson 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7004bb95dfb9SSean Christopherson 			rcu_read_unlock();
7005bb95dfb9SSean Christopherson 
7006531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
7007048f4980SSean Christopherson 			flush = false;
7008bb95dfb9SSean Christopherson 
7009bb95dfb9SSean Christopherson 			rcu_read_lock();
7010c50d8ae3SPaolo Bonzini 		}
7011c50d8ae3SPaolo Bonzini 	}
7012048f4980SSean Christopherson 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7013c50d8ae3SPaolo Bonzini 
7014bb95dfb9SSean Christopherson 	rcu_read_unlock();
7015bb95dfb9SSean Christopherson 
7016531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
7017c50d8ae3SPaolo Bonzini 	srcu_read_unlock(&kvm->srcu, rcu_idx);
7018c50d8ae3SPaolo Bonzini }
7019c50d8ae3SPaolo Bonzini 
702055c510e2SSean Christopherson static long get_nx_huge_page_recovery_timeout(u64 start_time)
7021c50d8ae3SPaolo Bonzini {
7022f47491d7SSean Christopherson 	bool enabled;
7023f47491d7SSean Christopherson 	uint period;
70244dfe4f40SJunaid Shahid 
7025f47491d7SSean Christopherson 	enabled = calc_nx_huge_pages_recovery_period(&period);
70264dfe4f40SJunaid Shahid 
7027f47491d7SSean Christopherson 	return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
7028c50d8ae3SPaolo Bonzini 		       : MAX_SCHEDULE_TIMEOUT;
7029c50d8ae3SPaolo Bonzini }
7030c50d8ae3SPaolo Bonzini 
703155c510e2SSean Christopherson static int kvm_nx_huge_page_recovery_worker(struct kvm *kvm, uintptr_t data)
7032c50d8ae3SPaolo Bonzini {
7033c50d8ae3SPaolo Bonzini 	u64 start_time;
7034c50d8ae3SPaolo Bonzini 	long remaining_time;
7035c50d8ae3SPaolo Bonzini 
7036c50d8ae3SPaolo Bonzini 	while (true) {
7037c50d8ae3SPaolo Bonzini 		start_time = get_jiffies_64();
703855c510e2SSean Christopherson 		remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7039c50d8ae3SPaolo Bonzini 
7040c50d8ae3SPaolo Bonzini 		set_current_state(TASK_INTERRUPTIBLE);
7041c50d8ae3SPaolo Bonzini 		while (!kthread_should_stop() && remaining_time > 0) {
7042c50d8ae3SPaolo Bonzini 			schedule_timeout(remaining_time);
704355c510e2SSean Christopherson 			remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7044c50d8ae3SPaolo Bonzini 			set_current_state(TASK_INTERRUPTIBLE);
7045c50d8ae3SPaolo Bonzini 		}
7046c50d8ae3SPaolo Bonzini 
7047c50d8ae3SPaolo Bonzini 		set_current_state(TASK_RUNNING);
7048c50d8ae3SPaolo Bonzini 
7049c50d8ae3SPaolo Bonzini 		if (kthread_should_stop())
7050c50d8ae3SPaolo Bonzini 			return 0;
7051c50d8ae3SPaolo Bonzini 
705255c510e2SSean Christopherson 		kvm_recover_nx_huge_pages(kvm);
7053c50d8ae3SPaolo Bonzini 	}
7054c50d8ae3SPaolo Bonzini }
7055c50d8ae3SPaolo Bonzini 
7056c50d8ae3SPaolo Bonzini int kvm_mmu_post_init_vm(struct kvm *kvm)
7057c50d8ae3SPaolo Bonzini {
7058c50d8ae3SPaolo Bonzini 	int err;
7059c50d8ae3SPaolo Bonzini 
706055c510e2SSean Christopherson 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_huge_page_recovery_worker, 0,
7061c50d8ae3SPaolo Bonzini 					  "kvm-nx-lpage-recovery",
706255c510e2SSean Christopherson 					  &kvm->arch.nx_huge_page_recovery_thread);
7063c50d8ae3SPaolo Bonzini 	if (!err)
706455c510e2SSean Christopherson 		kthread_unpark(kvm->arch.nx_huge_page_recovery_thread);
7065c50d8ae3SPaolo Bonzini 
7066c50d8ae3SPaolo Bonzini 	return err;
7067c50d8ae3SPaolo Bonzini }
7068c50d8ae3SPaolo Bonzini 
7069c50d8ae3SPaolo Bonzini void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7070c50d8ae3SPaolo Bonzini {
707155c510e2SSean Christopherson 	if (kvm->arch.nx_huge_page_recovery_thread)
707255c510e2SSean Christopherson 		kthread_stop(kvm->arch.nx_huge_page_recovery_thread);
7073c50d8ae3SPaolo Bonzini }
7074