xref: /linux/arch/x86/kvm/mmu/mmu.c (revision 7a458f0e1ba150a6ea012171a43c4b947f1d825d)
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  */
17c50d8ae3SPaolo Bonzini 
18c50d8ae3SPaolo Bonzini #include "irq.h"
1988197e6aS彭浩(Richard) #include "ioapic.h"
20c50d8ae3SPaolo Bonzini #include "mmu.h"
216ca9a6f3SSean Christopherson #include "mmu_internal.h"
22fe5db27dSBen Gardon #include "tdp_mmu.h"
23c50d8ae3SPaolo Bonzini #include "x86.h"
24c50d8ae3SPaolo Bonzini #include "kvm_cache_regs.h"
252f728d66SSean Christopherson #include "kvm_emulate.h"
26c50d8ae3SPaolo Bonzini #include "cpuid.h"
275a9624afSPaolo Bonzini #include "spte.h"
28c50d8ae3SPaolo Bonzini 
29c50d8ae3SPaolo Bonzini #include <linux/kvm_host.h>
30c50d8ae3SPaolo Bonzini #include <linux/types.h>
31c50d8ae3SPaolo Bonzini #include <linux/string.h>
32c50d8ae3SPaolo Bonzini #include <linux/mm.h>
33c50d8ae3SPaolo Bonzini #include <linux/highmem.h>
34c50d8ae3SPaolo Bonzini #include <linux/moduleparam.h>
35c50d8ae3SPaolo Bonzini #include <linux/export.h>
36c50d8ae3SPaolo Bonzini #include <linux/swap.h>
37c50d8ae3SPaolo Bonzini #include <linux/hugetlb.h>
38c50d8ae3SPaolo Bonzini #include <linux/compiler.h>
39c50d8ae3SPaolo Bonzini #include <linux/srcu.h>
40c50d8ae3SPaolo Bonzini #include <linux/slab.h>
41c50d8ae3SPaolo Bonzini #include <linux/sched/signal.h>
42c50d8ae3SPaolo Bonzini #include <linux/uaccess.h>
43c50d8ae3SPaolo Bonzini #include <linux/hash.h>
44c50d8ae3SPaolo Bonzini #include <linux/kern_levels.h>
45c50d8ae3SPaolo Bonzini #include <linux/kthread.h>
46c50d8ae3SPaolo Bonzini 
47c50d8ae3SPaolo Bonzini #include <asm/page.h>
48eb243d1dSIngo Molnar #include <asm/memtype.h>
49c50d8ae3SPaolo Bonzini #include <asm/cmpxchg.h>
50c50d8ae3SPaolo Bonzini #include <asm/io.h>
514a98623dSSean Christopherson #include <asm/set_memory.h>
52c50d8ae3SPaolo Bonzini #include <asm/vmx.h>
53c50d8ae3SPaolo Bonzini #include <asm/kvm_page_track.h>
54c50d8ae3SPaolo Bonzini #include "trace.h"
55c50d8ae3SPaolo Bonzini 
56fc9bf2e0SSean Christopherson #include "paging.h"
57fc9bf2e0SSean Christopherson 
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 
1031d92d2e8SSean Christopherson static int max_huge_page_level __read_mostly;
104746700d2SWei Huang static int tdp_root_level __read_mostly;
10583013059SSean Christopherson static int max_tdp_level __read_mostly;
106703c335dSSean Christopherson 
107c50d8ae3SPaolo Bonzini #ifdef MMU_DEBUG
1085a9624afSPaolo Bonzini bool dbg = 0;
109c50d8ae3SPaolo Bonzini module_param(dbg, bool, 0644);
110c50d8ae3SPaolo Bonzini #endif
111c50d8ae3SPaolo Bonzini 
112c50d8ae3SPaolo Bonzini #define PTE_PREFETCH_NUM		8
113c50d8ae3SPaolo Bonzini 
114c50d8ae3SPaolo Bonzini #define PT32_LEVEL_BITS 10
115c50d8ae3SPaolo Bonzini 
116c50d8ae3SPaolo Bonzini #define PT32_LEVEL_SHIFT(level) \
117c50d8ae3SPaolo Bonzini 		(PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
118c50d8ae3SPaolo Bonzini 
119c50d8ae3SPaolo Bonzini #define PT32_LVL_OFFSET_MASK(level) \
120c50d8ae3SPaolo Bonzini 	(PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
121c50d8ae3SPaolo Bonzini 						* PT32_LEVEL_BITS))) - 1))
122c50d8ae3SPaolo Bonzini 
123c50d8ae3SPaolo Bonzini #define PT32_INDEX(address, level)\
124c50d8ae3SPaolo Bonzini 	(((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
125c50d8ae3SPaolo Bonzini 
126c50d8ae3SPaolo Bonzini 
127c50d8ae3SPaolo Bonzini #define PT32_BASE_ADDR_MASK PAGE_MASK
128c50d8ae3SPaolo Bonzini #define PT32_DIR_BASE_ADDR_MASK \
129c50d8ae3SPaolo Bonzini 	(PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
130c50d8ae3SPaolo Bonzini #define PT32_LVL_ADDR_MASK(level) \
131c50d8ae3SPaolo Bonzini 	(PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
132c50d8ae3SPaolo Bonzini 					    * PT32_LEVEL_BITS))) - 1))
133c50d8ae3SPaolo Bonzini 
134c50d8ae3SPaolo Bonzini #include <trace/events/kvm.h>
135c50d8ae3SPaolo Bonzini 
136dc1cff96SPeter Xu /* make pte_list_desc fit well in cache lines */
13713236e25SPeter Xu #define PTE_LIST_EXT 14
138c50d8ae3SPaolo Bonzini 
13913236e25SPeter Xu /*
14013236e25SPeter Xu  * Slight optimization of cacheline layout, by putting `more' and `spte_count'
14113236e25SPeter Xu  * at the start; then accessing it will only use one single cacheline for
14213236e25SPeter Xu  * either full (entries==PTE_LIST_EXT) case or entries<=6.
14313236e25SPeter Xu  */
144c50d8ae3SPaolo Bonzini struct pte_list_desc {
145c50d8ae3SPaolo Bonzini 	struct pte_list_desc *more;
14613236e25SPeter Xu 	/*
14713236e25SPeter Xu 	 * Stores number of entries stored in the pte_list_desc.  No need to be
14813236e25SPeter Xu 	 * u64 but just for easier alignment.  When PTE_LIST_EXT, means full.
14913236e25SPeter Xu 	 */
15013236e25SPeter Xu 	u64 spte_count;
15113236e25SPeter Xu 	u64 *sptes[PTE_LIST_EXT];
152c50d8ae3SPaolo Bonzini };
153c50d8ae3SPaolo Bonzini 
154c50d8ae3SPaolo Bonzini struct kvm_shadow_walk_iterator {
155c50d8ae3SPaolo Bonzini 	u64 addr;
156c50d8ae3SPaolo Bonzini 	hpa_t shadow_addr;
157c50d8ae3SPaolo Bonzini 	u64 *sptep;
158c50d8ae3SPaolo Bonzini 	int level;
159c50d8ae3SPaolo Bonzini 	unsigned index;
160c50d8ae3SPaolo Bonzini };
161c50d8ae3SPaolo Bonzini 
162c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
163c50d8ae3SPaolo Bonzini 	for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
164c50d8ae3SPaolo Bonzini 					 (_root), (_addr));                \
165c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			           \
166c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
167c50d8ae3SPaolo Bonzini 
168c50d8ae3SPaolo Bonzini #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
169c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);	\
170c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			\
171c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
172c50d8ae3SPaolo Bonzini 
173c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)	\
174c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);		\
175c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker)) &&				\
176c50d8ae3SPaolo Bonzini 		({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });	\
177c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&(_walker), spte))
178c50d8ae3SPaolo Bonzini 
179c50d8ae3SPaolo Bonzini static struct kmem_cache *pte_list_desc_cache;
18002c00b3aSBen Gardon struct kmem_cache *mmu_page_header_cache;
181c50d8ae3SPaolo Bonzini static struct percpu_counter kvm_total_used_mmu_pages;
182c50d8ae3SPaolo Bonzini 
183c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 spte);
184c50d8ae3SPaolo Bonzini 
185594e91a1SSean Christopherson struct kvm_mmu_role_regs {
186594e91a1SSean Christopherson 	const unsigned long cr0;
187594e91a1SSean Christopherson 	const unsigned long cr4;
188594e91a1SSean Christopherson 	const u64 efer;
189594e91a1SSean Christopherson };
190594e91a1SSean Christopherson 
191c50d8ae3SPaolo Bonzini #define CREATE_TRACE_POINTS
192c50d8ae3SPaolo Bonzini #include "mmutrace.h"
193c50d8ae3SPaolo Bonzini 
194594e91a1SSean Christopherson /*
195594e91a1SSean Christopherson  * Yes, lot's of underscores.  They're a hint that you probably shouldn't be
196*7a458f0eSPaolo Bonzini  * reading from the role_regs.  Once the root_role is constructed, it becomes
197594e91a1SSean Christopherson  * the single source of truth for the MMU's state.
198594e91a1SSean Christopherson  */
199594e91a1SSean Christopherson #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag)			\
20082ffa13fSPaolo Bonzini static inline bool __maybe_unused					\
20182ffa13fSPaolo Bonzini ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs)		\
202594e91a1SSean Christopherson {									\
203594e91a1SSean Christopherson 	return !!(regs->reg & flag);					\
204594e91a1SSean Christopherson }
205594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
206594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
207594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
208594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
209594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
210594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
211594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
212594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
213594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
214594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
215594e91a1SSean Christopherson 
21660667724SSean Christopherson /*
21760667724SSean Christopherson  * The MMU itself (with a valid role) is the single source of truth for the
21860667724SSean Christopherson  * MMU.  Do not use the regs used to build the MMU/role, nor the vCPU.  The
21960667724SSean Christopherson  * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
22060667724SSean Christopherson  * and the vCPU may be incorrect/irrelevant.
22160667724SSean Christopherson  */
22260667724SSean Christopherson #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name)		\
2234ac21457SPaolo Bonzini static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu)	\
22460667724SSean Christopherson {								\
225e5ed0fb0SPaolo Bonzini 	return !!(mmu->cpu_role. base_or_ext . reg##_##name);	\
22660667724SSean Christopherson }
22760667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr0, pg);
22860667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
22960667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pse);
23060667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pae);
23160667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smep);
23260667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smap);
23360667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pke);
23460667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, la57);
23560667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
23660667724SSean Christopherson 
237594e91a1SSean Christopherson static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
238594e91a1SSean Christopherson {
239594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
240594e91a1SSean Christopherson 		.cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
241594e91a1SSean Christopherson 		.cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
242594e91a1SSean Christopherson 		.efer = vcpu->arch.efer,
243594e91a1SSean Christopherson 	};
244594e91a1SSean Christopherson 
245594e91a1SSean Christopherson 	return regs;
246594e91a1SSean Christopherson }
247c50d8ae3SPaolo Bonzini 
248c50d8ae3SPaolo Bonzini static inline bool kvm_available_flush_tlb_with_range(void)
249c50d8ae3SPaolo Bonzini {
250afaf0b2fSSean Christopherson 	return kvm_x86_ops.tlb_remote_flush_with_range;
251c50d8ae3SPaolo Bonzini }
252c50d8ae3SPaolo Bonzini 
253c50d8ae3SPaolo Bonzini static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
254c50d8ae3SPaolo Bonzini 		struct kvm_tlb_range *range)
255c50d8ae3SPaolo Bonzini {
256c50d8ae3SPaolo Bonzini 	int ret = -ENOTSUPP;
257c50d8ae3SPaolo Bonzini 
258afaf0b2fSSean Christopherson 	if (range && kvm_x86_ops.tlb_remote_flush_with_range)
259b3646477SJason Baron 		ret = static_call(kvm_x86_tlb_remote_flush_with_range)(kvm, range);
260c50d8ae3SPaolo Bonzini 
261c50d8ae3SPaolo Bonzini 	if (ret)
262c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
263c50d8ae3SPaolo Bonzini }
264c50d8ae3SPaolo Bonzini 
2652f2fad08SBen Gardon void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
266c50d8ae3SPaolo Bonzini 		u64 start_gfn, u64 pages)
267c50d8ae3SPaolo Bonzini {
268c50d8ae3SPaolo Bonzini 	struct kvm_tlb_range range;
269c50d8ae3SPaolo Bonzini 
270c50d8ae3SPaolo Bonzini 	range.start_gfn = start_gfn;
271c50d8ae3SPaolo Bonzini 	range.pages = pages;
272c50d8ae3SPaolo Bonzini 
273c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs_with_range(kvm, &range);
274c50d8ae3SPaolo Bonzini }
275c50d8ae3SPaolo Bonzini 
2768f79b064SBen Gardon static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
2778f79b064SBen Gardon 			   unsigned int access)
2788f79b064SBen Gardon {
279c236d962SSean Christopherson 	u64 spte = make_mmio_spte(vcpu, gfn, access);
2808f79b064SBen Gardon 
281c236d962SSean Christopherson 	trace_mark_mmio_spte(sptep, gfn, spte);
282c236d962SSean Christopherson 	mmu_spte_set(sptep, spte);
283c50d8ae3SPaolo Bonzini }
284c50d8ae3SPaolo Bonzini 
285c50d8ae3SPaolo Bonzini static gfn_t get_mmio_spte_gfn(u64 spte)
286c50d8ae3SPaolo Bonzini {
287c50d8ae3SPaolo Bonzini 	u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
288c50d8ae3SPaolo Bonzini 
2898a967d65SPaolo Bonzini 	gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
290c50d8ae3SPaolo Bonzini 	       & shadow_nonpresent_or_rsvd_mask;
291c50d8ae3SPaolo Bonzini 
292c50d8ae3SPaolo Bonzini 	return gpa >> PAGE_SHIFT;
293c50d8ae3SPaolo Bonzini }
294c50d8ae3SPaolo Bonzini 
295c50d8ae3SPaolo Bonzini static unsigned get_mmio_spte_access(u64 spte)
296c50d8ae3SPaolo Bonzini {
297c50d8ae3SPaolo Bonzini 	return spte & shadow_mmio_access_mask;
298c50d8ae3SPaolo Bonzini }
299c50d8ae3SPaolo Bonzini 
300c50d8ae3SPaolo Bonzini static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
301c50d8ae3SPaolo Bonzini {
302c50d8ae3SPaolo Bonzini 	u64 kvm_gen, spte_gen, gen;
303c50d8ae3SPaolo Bonzini 
304c50d8ae3SPaolo Bonzini 	gen = kvm_vcpu_memslots(vcpu)->generation;
305c50d8ae3SPaolo Bonzini 	if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
306c50d8ae3SPaolo Bonzini 		return false;
307c50d8ae3SPaolo Bonzini 
308c50d8ae3SPaolo Bonzini 	kvm_gen = gen & MMIO_SPTE_GEN_MASK;
309c50d8ae3SPaolo Bonzini 	spte_gen = get_mmio_spte_generation(spte);
310c50d8ae3SPaolo Bonzini 
311c50d8ae3SPaolo Bonzini 	trace_check_mmio_spte(spte, kvm_gen, spte_gen);
312c50d8ae3SPaolo Bonzini 	return likely(kvm_gen == spte_gen);
313c50d8ae3SPaolo Bonzini }
314c50d8ae3SPaolo Bonzini 
315c50d8ae3SPaolo Bonzini static int is_cpuid_PSE36(void)
316c50d8ae3SPaolo Bonzini {
317c50d8ae3SPaolo Bonzini 	return 1;
318c50d8ae3SPaolo Bonzini }
319c50d8ae3SPaolo Bonzini 
320c50d8ae3SPaolo Bonzini static gfn_t pse36_gfn_delta(u32 gpte)
321c50d8ae3SPaolo Bonzini {
322c50d8ae3SPaolo Bonzini 	int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
323c50d8ae3SPaolo Bonzini 
324c50d8ae3SPaolo Bonzini 	return (gpte & PT32_DIR_PSE36_MASK) << shift;
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  *
426c50d8ae3SPaolo Bonzini  * An spte tlb flush may be pending, because kvm_set_pte_rmapp
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 static bool spte_has_volatile_bits(u64 spte)
465c50d8ae3SPaolo Bonzini {
466c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(spte))
467c50d8ae3SPaolo Bonzini 		return false;
468c50d8ae3SPaolo Bonzini 
469c50d8ae3SPaolo Bonzini 	/*
470c50d8ae3SPaolo Bonzini 	 * Always atomically update spte if it can be updated
471c50d8ae3SPaolo Bonzini 	 * out of mmu-lock, it can ensure dirty bit is not lost,
472c50d8ae3SPaolo Bonzini 	 * also, it can help us to get a stable is_writable_pte()
473c50d8ae3SPaolo Bonzini 	 * to ensure tlb flush is not missed.
474c50d8ae3SPaolo Bonzini 	 */
475c50d8ae3SPaolo Bonzini 	if (spte_can_locklessly_be_made_writable(spte) ||
476c50d8ae3SPaolo Bonzini 	    is_access_track_spte(spte))
477c50d8ae3SPaolo Bonzini 		return true;
478c50d8ae3SPaolo Bonzini 
479c50d8ae3SPaolo Bonzini 	if (spte_ad_enabled(spte)) {
480c50d8ae3SPaolo Bonzini 		if ((spte & shadow_accessed_mask) == 0 ||
481c50d8ae3SPaolo Bonzini 	    	    (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
482c50d8ae3SPaolo Bonzini 			return true;
483c50d8ae3SPaolo Bonzini 	}
484c50d8ae3SPaolo Bonzini 
485c50d8ae3SPaolo Bonzini 	return false;
486c50d8ae3SPaolo Bonzini }
487c50d8ae3SPaolo Bonzini 
488c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_set:
489c50d8ae3SPaolo Bonzini  * Set the sptep from nonpresent to present.
490c50d8ae3SPaolo Bonzini  * Note: the sptep being assigned *must* be either not present
491c50d8ae3SPaolo Bonzini  * or in a state where the hardware will not attempt to update
492c50d8ae3SPaolo Bonzini  * the spte.
493c50d8ae3SPaolo Bonzini  */
494c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 new_spte)
495c50d8ae3SPaolo Bonzini {
496c50d8ae3SPaolo Bonzini 	WARN_ON(is_shadow_present_pte(*sptep));
497c50d8ae3SPaolo Bonzini 	__set_spte(sptep, new_spte);
498c50d8ae3SPaolo Bonzini }
499c50d8ae3SPaolo Bonzini 
500c50d8ae3SPaolo Bonzini /*
501c50d8ae3SPaolo Bonzini  * Update the SPTE (excluding the PFN), but do not track changes in its
502c50d8ae3SPaolo Bonzini  * accessed/dirty status.
503c50d8ae3SPaolo Bonzini  */
504c50d8ae3SPaolo Bonzini static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
505c50d8ae3SPaolo Bonzini {
506c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
507c50d8ae3SPaolo Bonzini 
508c50d8ae3SPaolo Bonzini 	WARN_ON(!is_shadow_present_pte(new_spte));
509115111efSDavid Matlack 	check_spte_writable_invariants(new_spte);
510c50d8ae3SPaolo Bonzini 
511c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte)) {
512c50d8ae3SPaolo Bonzini 		mmu_spte_set(sptep, new_spte);
513c50d8ae3SPaolo Bonzini 		return old_spte;
514c50d8ae3SPaolo Bonzini 	}
515c50d8ae3SPaolo Bonzini 
516c50d8ae3SPaolo Bonzini 	if (!spte_has_volatile_bits(old_spte))
517c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, new_spte);
518c50d8ae3SPaolo Bonzini 	else
519c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, new_spte);
520c50d8ae3SPaolo Bonzini 
521c50d8ae3SPaolo Bonzini 	WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
522c50d8ae3SPaolo Bonzini 
523c50d8ae3SPaolo Bonzini 	return old_spte;
524c50d8ae3SPaolo Bonzini }
525c50d8ae3SPaolo Bonzini 
526c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_update:
527c50d8ae3SPaolo Bonzini  * Update the state bits, it means the mapped pfn is not changed.
528c50d8ae3SPaolo Bonzini  *
52902844ac1SDavid Matlack  * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
53002844ac1SDavid Matlack  * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
53102844ac1SDavid Matlack  * spte, even though the writable spte might be cached on a CPU's TLB.
532c50d8ae3SPaolo Bonzini  *
533c50d8ae3SPaolo Bonzini  * Returns true if the TLB needs to be flushed
534c50d8ae3SPaolo Bonzini  */
535c50d8ae3SPaolo Bonzini static bool mmu_spte_update(u64 *sptep, u64 new_spte)
536c50d8ae3SPaolo Bonzini {
537c50d8ae3SPaolo Bonzini 	bool flush = false;
538c50d8ae3SPaolo Bonzini 	u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
539c50d8ae3SPaolo Bonzini 
540c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
541c50d8ae3SPaolo Bonzini 		return false;
542c50d8ae3SPaolo Bonzini 
543c50d8ae3SPaolo Bonzini 	/*
544c50d8ae3SPaolo Bonzini 	 * For the spte updated out of mmu-lock is safe, since
545c50d8ae3SPaolo Bonzini 	 * we always atomically update it, see the comments in
546c50d8ae3SPaolo Bonzini 	 * spte_has_volatile_bits().
547c50d8ae3SPaolo Bonzini 	 */
548c50d8ae3SPaolo Bonzini 	if (spte_can_locklessly_be_made_writable(old_spte) &&
549c50d8ae3SPaolo Bonzini 	      !is_writable_pte(new_spte))
550c50d8ae3SPaolo Bonzini 		flush = true;
551c50d8ae3SPaolo Bonzini 
552c50d8ae3SPaolo Bonzini 	/*
553c50d8ae3SPaolo Bonzini 	 * Flush TLB when accessed/dirty states are changed in the page tables,
554c50d8ae3SPaolo Bonzini 	 * to guarantee consistency between TLB and page tables.
555c50d8ae3SPaolo Bonzini 	 */
556c50d8ae3SPaolo Bonzini 
557c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
558c50d8ae3SPaolo Bonzini 		flush = true;
559c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(spte_to_pfn(old_spte));
560c50d8ae3SPaolo Bonzini 	}
561c50d8ae3SPaolo Bonzini 
562c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
563c50d8ae3SPaolo Bonzini 		flush = true;
564c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(old_spte));
565c50d8ae3SPaolo Bonzini 	}
566c50d8ae3SPaolo Bonzini 
567c50d8ae3SPaolo Bonzini 	return flush;
568c50d8ae3SPaolo Bonzini }
569c50d8ae3SPaolo Bonzini 
570c50d8ae3SPaolo Bonzini /*
571c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_track_bits:
572c50d8ae3SPaolo Bonzini  * It sets the sptep from present to nonpresent, and track the
573c50d8ae3SPaolo Bonzini  * state bits, it is used to clear the last level sptep.
5747fa2a347SSean Christopherson  * Returns the old PTE.
575c50d8ae3SPaolo Bonzini  */
57671f51d2cSMingwei Zhang static int mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
577c50d8ae3SPaolo Bonzini {
578c50d8ae3SPaolo Bonzini 	kvm_pfn_t pfn;
579c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
58071f51d2cSMingwei Zhang 	int level = sptep_to_sp(sptep)->role.level;
581c50d8ae3SPaolo Bonzini 
582c50d8ae3SPaolo Bonzini 	if (!spte_has_volatile_bits(old_spte))
583c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, 0ull);
584c50d8ae3SPaolo Bonzini 	else
585c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, 0ull);
586c50d8ae3SPaolo Bonzini 
587c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
5887fa2a347SSean Christopherson 		return old_spte;
589c50d8ae3SPaolo Bonzini 
59071f51d2cSMingwei Zhang 	kvm_update_page_stats(kvm, level, -1);
59171f51d2cSMingwei Zhang 
592c50d8ae3SPaolo Bonzini 	pfn = spte_to_pfn(old_spte);
593c50d8ae3SPaolo Bonzini 
594c50d8ae3SPaolo Bonzini 	/*
595c50d8ae3SPaolo Bonzini 	 * KVM does not hold the refcount of the page used by
596c50d8ae3SPaolo Bonzini 	 * kvm mmu, before reclaiming the page, we should
597c50d8ae3SPaolo Bonzini 	 * unmap it from mmu first.
598c50d8ae3SPaolo Bonzini 	 */
599c50d8ae3SPaolo Bonzini 	WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
600c50d8ae3SPaolo Bonzini 
601c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte))
602c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(pfn);
603c50d8ae3SPaolo Bonzini 
604c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte))
605c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(pfn);
606c50d8ae3SPaolo Bonzini 
6077fa2a347SSean Christopherson 	return old_spte;
608c50d8ae3SPaolo Bonzini }
609c50d8ae3SPaolo Bonzini 
610c50d8ae3SPaolo Bonzini /*
611c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_no_track:
612c50d8ae3SPaolo Bonzini  * Directly clear spte without caring the state bits of sptep,
613c50d8ae3SPaolo Bonzini  * it is used to set the upper level spte.
614c50d8ae3SPaolo Bonzini  */
615c50d8ae3SPaolo Bonzini static void mmu_spte_clear_no_track(u64 *sptep)
616c50d8ae3SPaolo Bonzini {
617c50d8ae3SPaolo Bonzini 	__update_clear_spte_fast(sptep, 0ull);
618c50d8ae3SPaolo Bonzini }
619c50d8ae3SPaolo Bonzini 
620c50d8ae3SPaolo Bonzini static u64 mmu_spte_get_lockless(u64 *sptep)
621c50d8ae3SPaolo Bonzini {
622c50d8ae3SPaolo Bonzini 	return __get_spte_lockless(sptep);
623c50d8ae3SPaolo Bonzini }
624c50d8ae3SPaolo Bonzini 
625c50d8ae3SPaolo Bonzini /* Returns the Accessed status of the PTE and resets it at the same time. */
626c50d8ae3SPaolo Bonzini static bool mmu_spte_age(u64 *sptep)
627c50d8ae3SPaolo Bonzini {
628c50d8ae3SPaolo Bonzini 	u64 spte = mmu_spte_get_lockless(sptep);
629c50d8ae3SPaolo Bonzini 
630c50d8ae3SPaolo Bonzini 	if (!is_accessed_spte(spte))
631c50d8ae3SPaolo Bonzini 		return false;
632c50d8ae3SPaolo Bonzini 
633c50d8ae3SPaolo Bonzini 	if (spte_ad_enabled(spte)) {
634c50d8ae3SPaolo Bonzini 		clear_bit((ffs(shadow_accessed_mask) - 1),
635c50d8ae3SPaolo Bonzini 			  (unsigned long *)sptep);
636c50d8ae3SPaolo Bonzini 	} else {
637c50d8ae3SPaolo Bonzini 		/*
638c50d8ae3SPaolo Bonzini 		 * Capture the dirty status of the page, so that it doesn't get
639c50d8ae3SPaolo Bonzini 		 * lost when the SPTE is marked for access tracking.
640c50d8ae3SPaolo Bonzini 		 */
641c50d8ae3SPaolo Bonzini 		if (is_writable_pte(spte))
642c50d8ae3SPaolo Bonzini 			kvm_set_pfn_dirty(spte_to_pfn(spte));
643c50d8ae3SPaolo Bonzini 
644c50d8ae3SPaolo Bonzini 		spte = mark_spte_for_access_track(spte);
645c50d8ae3SPaolo Bonzini 		mmu_spte_update_no_track(sptep, spte);
646c50d8ae3SPaolo Bonzini 	}
647c50d8ae3SPaolo Bonzini 
648c50d8ae3SPaolo Bonzini 	return true;
649c50d8ae3SPaolo Bonzini }
650c50d8ae3SPaolo Bonzini 
651c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
652c50d8ae3SPaolo Bonzini {
653c5c8c7c5SDavid Matlack 	if (is_tdp_mmu(vcpu->arch.mmu)) {
654c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_begin();
655c5c8c7c5SDavid Matlack 	} else {
656c50d8ae3SPaolo Bonzini 		/*
657c50d8ae3SPaolo Bonzini 		 * Prevent page table teardown by making any free-er wait during
658c50d8ae3SPaolo Bonzini 		 * kvm_flush_remote_tlbs() IPI to all active vcpus.
659c50d8ae3SPaolo Bonzini 		 */
660c50d8ae3SPaolo Bonzini 		local_irq_disable();
661c50d8ae3SPaolo Bonzini 
662c50d8ae3SPaolo Bonzini 		/*
663c50d8ae3SPaolo Bonzini 		 * Make sure a following spte read is not reordered ahead of the write
664c50d8ae3SPaolo Bonzini 		 * to vcpu->mode.
665c50d8ae3SPaolo Bonzini 		 */
666c50d8ae3SPaolo Bonzini 		smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
667c50d8ae3SPaolo Bonzini 	}
668c5c8c7c5SDavid Matlack }
669c50d8ae3SPaolo Bonzini 
670c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
671c50d8ae3SPaolo Bonzini {
672c5c8c7c5SDavid Matlack 	if (is_tdp_mmu(vcpu->arch.mmu)) {
673c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_end();
674c5c8c7c5SDavid Matlack 	} else {
675c50d8ae3SPaolo Bonzini 		/*
676c50d8ae3SPaolo Bonzini 		 * Make sure the write to vcpu->mode is not reordered in front of
677c50d8ae3SPaolo Bonzini 		 * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
678c50d8ae3SPaolo Bonzini 		 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
679c50d8ae3SPaolo Bonzini 		 */
680c50d8ae3SPaolo Bonzini 		smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
681c50d8ae3SPaolo Bonzini 		local_irq_enable();
682c50d8ae3SPaolo Bonzini 	}
683c5c8c7c5SDavid Matlack }
684c50d8ae3SPaolo Bonzini 
685378f5cd6SSean Christopherson static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
686c50d8ae3SPaolo Bonzini {
687c50d8ae3SPaolo Bonzini 	int r;
688c50d8ae3SPaolo Bonzini 
689531281adSSean Christopherson 	/* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
69094ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
691531281adSSean Christopherson 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
692c50d8ae3SPaolo Bonzini 	if (r)
693c50d8ae3SPaolo Bonzini 		return r;
69494ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
695171a90d7SSean Christopherson 				       PT64_ROOT_MAX_LEVEL);
696171a90d7SSean Christopherson 	if (r)
697171a90d7SSean Christopherson 		return r;
698378f5cd6SSean Christopherson 	if (maybe_indirect) {
69994ce87efSSean Christopherson 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_gfn_array_cache,
700171a90d7SSean Christopherson 					       PT64_ROOT_MAX_LEVEL);
701c50d8ae3SPaolo Bonzini 		if (r)
702c50d8ae3SPaolo Bonzini 			return r;
703378f5cd6SSean Christopherson 	}
70494ce87efSSean Christopherson 	return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
705531281adSSean Christopherson 					  PT64_ROOT_MAX_LEVEL);
706c50d8ae3SPaolo Bonzini }
707c50d8ae3SPaolo Bonzini 
708c50d8ae3SPaolo Bonzini static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
709c50d8ae3SPaolo Bonzini {
71094ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
71194ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
71294ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_gfn_array_cache);
71394ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
714c50d8ae3SPaolo Bonzini }
715c50d8ae3SPaolo Bonzini 
716c50d8ae3SPaolo Bonzini static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
717c50d8ae3SPaolo Bonzini {
71894ce87efSSean Christopherson 	return kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
719c50d8ae3SPaolo Bonzini }
720c50d8ae3SPaolo Bonzini 
721c50d8ae3SPaolo Bonzini static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
722c50d8ae3SPaolo Bonzini {
723c50d8ae3SPaolo Bonzini 	kmem_cache_free(pte_list_desc_cache, pte_list_desc);
724c50d8ae3SPaolo Bonzini }
725c50d8ae3SPaolo Bonzini 
726c50d8ae3SPaolo Bonzini static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
727c50d8ae3SPaolo Bonzini {
728c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
729c50d8ae3SPaolo Bonzini 		return sp->gfns[index];
730c50d8ae3SPaolo Bonzini 
731c50d8ae3SPaolo Bonzini 	return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
732c50d8ae3SPaolo Bonzini }
733c50d8ae3SPaolo Bonzini 
734c50d8ae3SPaolo Bonzini static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
735c50d8ae3SPaolo Bonzini {
736c50d8ae3SPaolo Bonzini 	if (!sp->role.direct) {
737c50d8ae3SPaolo Bonzini 		sp->gfns[index] = gfn;
738c50d8ae3SPaolo Bonzini 		return;
739c50d8ae3SPaolo Bonzini 	}
740c50d8ae3SPaolo Bonzini 
741c50d8ae3SPaolo Bonzini 	if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
742c50d8ae3SPaolo Bonzini 		pr_err_ratelimited("gfn mismatch under direct page %llx "
743c50d8ae3SPaolo Bonzini 				   "(expected %llx, got %llx)\n",
744c50d8ae3SPaolo Bonzini 				   sp->gfn,
745c50d8ae3SPaolo Bonzini 				   kvm_mmu_page_get_gfn(sp, index), gfn);
746c50d8ae3SPaolo Bonzini }
747c50d8ae3SPaolo Bonzini 
748c50d8ae3SPaolo Bonzini /*
749c50d8ae3SPaolo Bonzini  * Return the pointer to the large page information for a given gfn,
750c50d8ae3SPaolo Bonzini  * handling slots that are not large page aligned.
751c50d8ae3SPaolo Bonzini  */
752c50d8ae3SPaolo Bonzini static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
7538ca6f063SBen Gardon 		const struct kvm_memory_slot *slot, int level)
754c50d8ae3SPaolo Bonzini {
755c50d8ae3SPaolo Bonzini 	unsigned long idx;
756c50d8ae3SPaolo Bonzini 
757c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
758c50d8ae3SPaolo Bonzini 	return &slot->arch.lpage_info[level - 2][idx];
759c50d8ae3SPaolo Bonzini }
760c50d8ae3SPaolo Bonzini 
761269e9552SHamza Mahfooz static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
762c50d8ae3SPaolo Bonzini 					    gfn_t gfn, int count)
763c50d8ae3SPaolo Bonzini {
764c50d8ae3SPaolo Bonzini 	struct kvm_lpage_info *linfo;
765c50d8ae3SPaolo Bonzini 	int i;
766c50d8ae3SPaolo Bonzini 
7673bae0459SSean Christopherson 	for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
768c50d8ae3SPaolo Bonzini 		linfo = lpage_info_slot(gfn, slot, i);
769c50d8ae3SPaolo Bonzini 		linfo->disallow_lpage += count;
770c50d8ae3SPaolo Bonzini 		WARN_ON(linfo->disallow_lpage < 0);
771c50d8ae3SPaolo Bonzini 	}
772c50d8ae3SPaolo Bonzini }
773c50d8ae3SPaolo Bonzini 
774269e9552SHamza Mahfooz void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
775c50d8ae3SPaolo Bonzini {
776c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, 1);
777c50d8ae3SPaolo Bonzini }
778c50d8ae3SPaolo Bonzini 
779269e9552SHamza Mahfooz void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
780c50d8ae3SPaolo Bonzini {
781c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, -1);
782c50d8ae3SPaolo Bonzini }
783c50d8ae3SPaolo Bonzini 
784c50d8ae3SPaolo Bonzini static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
785c50d8ae3SPaolo Bonzini {
786c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
787c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
788c50d8ae3SPaolo Bonzini 	gfn_t gfn;
789c50d8ae3SPaolo Bonzini 
790c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages++;
791c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
792c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
793c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
794c50d8ae3SPaolo Bonzini 
795c50d8ae3SPaolo Bonzini 	/* the non-leaf shadow pages are keeping readonly. */
7963bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
797c50d8ae3SPaolo Bonzini 		return kvm_slot_page_track_add_page(kvm, slot, gfn,
798c50d8ae3SPaolo Bonzini 						    KVM_PAGE_TRACK_WRITE);
799c50d8ae3SPaolo Bonzini 
800c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
801c50d8ae3SPaolo Bonzini }
802c50d8ae3SPaolo Bonzini 
80329cf0f50SBen Gardon void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
804c50d8ae3SPaolo Bonzini {
805c50d8ae3SPaolo Bonzini 	if (sp->lpage_disallowed)
806c50d8ae3SPaolo Bonzini 		return;
807c50d8ae3SPaolo Bonzini 
808c50d8ae3SPaolo Bonzini 	++kvm->stat.nx_lpage_splits;
809c50d8ae3SPaolo Bonzini 	list_add_tail(&sp->lpage_disallowed_link,
810c50d8ae3SPaolo Bonzini 		      &kvm->arch.lpage_disallowed_mmu_pages);
811c50d8ae3SPaolo Bonzini 	sp->lpage_disallowed = true;
812c50d8ae3SPaolo Bonzini }
813c50d8ae3SPaolo Bonzini 
814c50d8ae3SPaolo Bonzini static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
815c50d8ae3SPaolo Bonzini {
816c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
817c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
818c50d8ae3SPaolo Bonzini 	gfn_t gfn;
819c50d8ae3SPaolo Bonzini 
820c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages--;
821c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
822c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
823c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
8243bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
825c50d8ae3SPaolo Bonzini 		return kvm_slot_page_track_remove_page(kvm, slot, gfn,
826c50d8ae3SPaolo Bonzini 						       KVM_PAGE_TRACK_WRITE);
827c50d8ae3SPaolo Bonzini 
828c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_allow_lpage(slot, gfn);
829c50d8ae3SPaolo Bonzini }
830c50d8ae3SPaolo Bonzini 
83129cf0f50SBen Gardon void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
832c50d8ae3SPaolo Bonzini {
833c50d8ae3SPaolo Bonzini 	--kvm->stat.nx_lpage_splits;
834c50d8ae3SPaolo Bonzini 	sp->lpage_disallowed = false;
835c50d8ae3SPaolo Bonzini 	list_del(&sp->lpage_disallowed_link);
836c50d8ae3SPaolo Bonzini }
837c50d8ae3SPaolo Bonzini 
838c50d8ae3SPaolo Bonzini static struct kvm_memory_slot *
839c50d8ae3SPaolo Bonzini gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
840c50d8ae3SPaolo Bonzini 			    bool no_dirty_log)
841c50d8ae3SPaolo Bonzini {
842c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
843c50d8ae3SPaolo Bonzini 
844c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
84591b0d268SPaolo Bonzini 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
84691b0d268SPaolo Bonzini 		return NULL;
847044c59c4SPeter Xu 	if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
84891b0d268SPaolo Bonzini 		return NULL;
849c50d8ae3SPaolo Bonzini 
850c50d8ae3SPaolo Bonzini 	return slot;
851c50d8ae3SPaolo Bonzini }
852c50d8ae3SPaolo Bonzini 
853c50d8ae3SPaolo Bonzini /*
854c50d8ae3SPaolo Bonzini  * About rmap_head encoding:
855c50d8ae3SPaolo Bonzini  *
856c50d8ae3SPaolo Bonzini  * If the bit zero of rmap_head->val is clear, then it points to the only spte
857c50d8ae3SPaolo Bonzini  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
858c50d8ae3SPaolo Bonzini  * pte_list_desc containing more mappings.
859c50d8ae3SPaolo Bonzini  */
860c50d8ae3SPaolo Bonzini 
861c50d8ae3SPaolo Bonzini /*
862c50d8ae3SPaolo Bonzini  * Returns the number of pointers in the rmap chain, not counting the new one.
863c50d8ae3SPaolo Bonzini  */
864c50d8ae3SPaolo Bonzini static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
865c50d8ae3SPaolo Bonzini 			struct kvm_rmap_head *rmap_head)
866c50d8ae3SPaolo Bonzini {
867c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
86813236e25SPeter Xu 	int count = 0;
869c50d8ae3SPaolo Bonzini 
870c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
871805a0f83SStephen Zhang 		rmap_printk("%p %llx 0->1\n", spte, *spte);
872c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)spte;
873c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
874805a0f83SStephen Zhang 		rmap_printk("%p %llx 1->many\n", spte, *spte);
875c50d8ae3SPaolo Bonzini 		desc = mmu_alloc_pte_list_desc(vcpu);
876c50d8ae3SPaolo Bonzini 		desc->sptes[0] = (u64 *)rmap_head->val;
877c50d8ae3SPaolo Bonzini 		desc->sptes[1] = spte;
87813236e25SPeter Xu 		desc->spte_count = 2;
879c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)desc | 1;
880c50d8ae3SPaolo Bonzini 		++count;
881c50d8ae3SPaolo Bonzini 	} else {
882805a0f83SStephen Zhang 		rmap_printk("%p %llx many->many\n", spte, *spte);
883c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
88413236e25SPeter Xu 		while (desc->spte_count == PTE_LIST_EXT) {
885c50d8ae3SPaolo Bonzini 			count += PTE_LIST_EXT;
886c6c4f961SLi RongQing 			if (!desc->more) {
887c50d8ae3SPaolo Bonzini 				desc->more = mmu_alloc_pte_list_desc(vcpu);
888c50d8ae3SPaolo Bonzini 				desc = desc->more;
88913236e25SPeter Xu 				desc->spte_count = 0;
890c6c4f961SLi RongQing 				break;
891c6c4f961SLi RongQing 			}
892c6c4f961SLi RongQing 			desc = desc->more;
893c50d8ae3SPaolo Bonzini 		}
89413236e25SPeter Xu 		count += desc->spte_count;
89513236e25SPeter Xu 		desc->sptes[desc->spte_count++] = spte;
896c50d8ae3SPaolo Bonzini 	}
897c50d8ae3SPaolo Bonzini 	return count;
898c50d8ae3SPaolo Bonzini }
899c50d8ae3SPaolo Bonzini 
900c50d8ae3SPaolo Bonzini static void
901c50d8ae3SPaolo Bonzini pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
902c50d8ae3SPaolo Bonzini 			   struct pte_list_desc *desc, int i,
903c50d8ae3SPaolo Bonzini 			   struct pte_list_desc *prev_desc)
904c50d8ae3SPaolo Bonzini {
90513236e25SPeter Xu 	int j = desc->spte_count - 1;
906c50d8ae3SPaolo Bonzini 
907c50d8ae3SPaolo Bonzini 	desc->sptes[i] = desc->sptes[j];
908c50d8ae3SPaolo Bonzini 	desc->sptes[j] = NULL;
90913236e25SPeter Xu 	desc->spte_count--;
91013236e25SPeter Xu 	if (desc->spte_count)
911c50d8ae3SPaolo Bonzini 		return;
912c50d8ae3SPaolo Bonzini 	if (!prev_desc && !desc->more)
913fe3c2b4cSMiaohe Lin 		rmap_head->val = 0;
914c50d8ae3SPaolo Bonzini 	else
915c50d8ae3SPaolo Bonzini 		if (prev_desc)
916c50d8ae3SPaolo Bonzini 			prev_desc->more = desc->more;
917c50d8ae3SPaolo Bonzini 		else
918c50d8ae3SPaolo Bonzini 			rmap_head->val = (unsigned long)desc->more | 1;
919c50d8ae3SPaolo Bonzini 	mmu_free_pte_list_desc(desc);
920c50d8ae3SPaolo Bonzini }
921c50d8ae3SPaolo Bonzini 
922c50d8ae3SPaolo Bonzini static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
923c50d8ae3SPaolo Bonzini {
924c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
925c50d8ae3SPaolo Bonzini 	struct pte_list_desc *prev_desc;
926c50d8ae3SPaolo Bonzini 	int i;
927c50d8ae3SPaolo Bonzini 
928c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
929c50d8ae3SPaolo Bonzini 		pr_err("%s: %p 0->BUG\n", __func__, spte);
930c50d8ae3SPaolo Bonzini 		BUG();
931c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
932805a0f83SStephen Zhang 		rmap_printk("%p 1->0\n", spte);
933c50d8ae3SPaolo Bonzini 		if ((u64 *)rmap_head->val != spte) {
934c50d8ae3SPaolo Bonzini 			pr_err("%s:  %p 1->BUG\n", __func__, spte);
935c50d8ae3SPaolo Bonzini 			BUG();
936c50d8ae3SPaolo Bonzini 		}
937c50d8ae3SPaolo Bonzini 		rmap_head->val = 0;
938c50d8ae3SPaolo Bonzini 	} else {
939805a0f83SStephen Zhang 		rmap_printk("%p many->many\n", spte);
940c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
941c50d8ae3SPaolo Bonzini 		prev_desc = NULL;
942c50d8ae3SPaolo Bonzini 		while (desc) {
94313236e25SPeter Xu 			for (i = 0; i < desc->spte_count; ++i) {
944c50d8ae3SPaolo Bonzini 				if (desc->sptes[i] == spte) {
945c50d8ae3SPaolo Bonzini 					pte_list_desc_remove_entry(rmap_head,
946c50d8ae3SPaolo Bonzini 							desc, i, prev_desc);
947c50d8ae3SPaolo Bonzini 					return;
948c50d8ae3SPaolo Bonzini 				}
949c50d8ae3SPaolo Bonzini 			}
950c50d8ae3SPaolo Bonzini 			prev_desc = desc;
951c50d8ae3SPaolo Bonzini 			desc = desc->more;
952c50d8ae3SPaolo Bonzini 		}
953c50d8ae3SPaolo Bonzini 		pr_err("%s: %p many->many\n", __func__, spte);
954c50d8ae3SPaolo Bonzini 		BUG();
955c50d8ae3SPaolo Bonzini 	}
956c50d8ae3SPaolo Bonzini }
957c50d8ae3SPaolo Bonzini 
95871f51d2cSMingwei Zhang static void pte_list_remove(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
95971f51d2cSMingwei Zhang 			    u64 *sptep)
960c50d8ae3SPaolo Bonzini {
96171f51d2cSMingwei Zhang 	mmu_spte_clear_track_bits(kvm, sptep);
962c50d8ae3SPaolo Bonzini 	__pte_list_remove(sptep, rmap_head);
963c50d8ae3SPaolo Bonzini }
964c50d8ae3SPaolo Bonzini 
965a75b5404SPeter Xu /* Return true if rmap existed, false otherwise */
96671f51d2cSMingwei Zhang static bool pte_list_destroy(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
967a75b5404SPeter Xu {
968a75b5404SPeter Xu 	struct pte_list_desc *desc, *next;
969a75b5404SPeter Xu 	int i;
970a75b5404SPeter Xu 
971a75b5404SPeter Xu 	if (!rmap_head->val)
972a75b5404SPeter Xu 		return false;
973a75b5404SPeter Xu 
974a75b5404SPeter Xu 	if (!(rmap_head->val & 1)) {
97571f51d2cSMingwei Zhang 		mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
976a75b5404SPeter Xu 		goto out;
977a75b5404SPeter Xu 	}
978a75b5404SPeter Xu 
979a75b5404SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
980a75b5404SPeter Xu 
981a75b5404SPeter Xu 	for (; desc; desc = next) {
982a75b5404SPeter Xu 		for (i = 0; i < desc->spte_count; i++)
98371f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
984a75b5404SPeter Xu 		next = desc->more;
985a75b5404SPeter Xu 		mmu_free_pte_list_desc(desc);
986a75b5404SPeter Xu 	}
987a75b5404SPeter Xu out:
988a75b5404SPeter Xu 	/* rmap_head is meaningless now, remember to reset it */
989a75b5404SPeter Xu 	rmap_head->val = 0;
990a75b5404SPeter Xu 	return true;
991a75b5404SPeter Xu }
992a75b5404SPeter Xu 
9933bcd0662SPeter Xu unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
9943bcd0662SPeter Xu {
9953bcd0662SPeter Xu 	struct pte_list_desc *desc;
9963bcd0662SPeter Xu 	unsigned int count = 0;
9973bcd0662SPeter Xu 
9983bcd0662SPeter Xu 	if (!rmap_head->val)
9993bcd0662SPeter Xu 		return 0;
10003bcd0662SPeter Xu 	else if (!(rmap_head->val & 1))
10013bcd0662SPeter Xu 		return 1;
10023bcd0662SPeter Xu 
10033bcd0662SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
10043bcd0662SPeter Xu 
10053bcd0662SPeter Xu 	while (desc) {
10063bcd0662SPeter Xu 		count += desc->spte_count;
10073bcd0662SPeter Xu 		desc = desc->more;
10083bcd0662SPeter Xu 	}
10093bcd0662SPeter Xu 
10103bcd0662SPeter Xu 	return count;
10113bcd0662SPeter Xu }
10123bcd0662SPeter Xu 
101393e083d4SDavid Matlack static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1014269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
1015c50d8ae3SPaolo Bonzini {
1016c50d8ae3SPaolo Bonzini 	unsigned long idx;
1017c50d8ae3SPaolo Bonzini 
1018c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
10193bae0459SSean Christopherson 	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1020c50d8ae3SPaolo Bonzini }
1021c50d8ae3SPaolo Bonzini 
1022c50d8ae3SPaolo Bonzini static bool rmap_can_add(struct kvm_vcpu *vcpu)
1023c50d8ae3SPaolo Bonzini {
1024356ec69aSSean Christopherson 	struct kvm_mmu_memory_cache *mc;
1025c50d8ae3SPaolo Bonzini 
1026356ec69aSSean Christopherson 	mc = &vcpu->arch.mmu_pte_list_desc_cache;
102794ce87efSSean Christopherson 	return kvm_mmu_memory_cache_nr_free_objects(mc);
1028c50d8ae3SPaolo Bonzini }
1029c50d8ae3SPaolo Bonzini 
1030c50d8ae3SPaolo Bonzini static void rmap_remove(struct kvm *kvm, u64 *spte)
1031c50d8ae3SPaolo Bonzini {
1032601f8af0SDavid Matlack 	struct kvm_memslots *slots;
1033601f8af0SDavid Matlack 	struct kvm_memory_slot *slot;
1034c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1035c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1036c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1037c50d8ae3SPaolo Bonzini 
103857354682SSean Christopherson 	sp = sptep_to_sp(spte);
1039c50d8ae3SPaolo Bonzini 	gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1040601f8af0SDavid Matlack 
1041601f8af0SDavid Matlack 	/*
104268be1306SDavid Matlack 	 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
104368be1306SDavid Matlack 	 * so we have to determine which memslots to use based on context
104468be1306SDavid Matlack 	 * information in sp->role.
1045601f8af0SDavid Matlack 	 */
1046601f8af0SDavid Matlack 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1047601f8af0SDavid Matlack 
1048601f8af0SDavid Matlack 	slot = __gfn_to_memslot(slots, gfn);
104993e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1050601f8af0SDavid Matlack 
1051c50d8ae3SPaolo Bonzini 	__pte_list_remove(spte, rmap_head);
1052c50d8ae3SPaolo Bonzini }
1053c50d8ae3SPaolo Bonzini 
1054c50d8ae3SPaolo Bonzini /*
1055c50d8ae3SPaolo Bonzini  * Used by the following functions to iterate through the sptes linked by a
1056c50d8ae3SPaolo Bonzini  * rmap.  All fields are private and not assumed to be used outside.
1057c50d8ae3SPaolo Bonzini  */
1058c50d8ae3SPaolo Bonzini struct rmap_iterator {
1059c50d8ae3SPaolo Bonzini 	/* private fields */
1060c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1061c50d8ae3SPaolo Bonzini 	int pos;			/* index of the sptep */
1062c50d8ae3SPaolo Bonzini };
1063c50d8ae3SPaolo Bonzini 
1064c50d8ae3SPaolo Bonzini /*
1065c50d8ae3SPaolo Bonzini  * Iteration must be started by this function.  This should also be used after
1066c50d8ae3SPaolo Bonzini  * removing/dropping sptes from the rmap link because in such cases the
10670a03cbdaSMiaohe Lin  * information in the iterator may not be valid.
1068c50d8ae3SPaolo Bonzini  *
1069c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1070c50d8ae3SPaolo Bonzini  */
1071c50d8ae3SPaolo Bonzini static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1072c50d8ae3SPaolo Bonzini 			   struct rmap_iterator *iter)
1073c50d8ae3SPaolo Bonzini {
1074c50d8ae3SPaolo Bonzini 	u64 *sptep;
1075c50d8ae3SPaolo Bonzini 
1076c50d8ae3SPaolo Bonzini 	if (!rmap_head->val)
1077c50d8ae3SPaolo Bonzini 		return NULL;
1078c50d8ae3SPaolo Bonzini 
1079c50d8ae3SPaolo Bonzini 	if (!(rmap_head->val & 1)) {
1080c50d8ae3SPaolo Bonzini 		iter->desc = NULL;
1081c50d8ae3SPaolo Bonzini 		sptep = (u64 *)rmap_head->val;
1082c50d8ae3SPaolo Bonzini 		goto out;
1083c50d8ae3SPaolo Bonzini 	}
1084c50d8ae3SPaolo Bonzini 
1085c50d8ae3SPaolo Bonzini 	iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1086c50d8ae3SPaolo Bonzini 	iter->pos = 0;
1087c50d8ae3SPaolo Bonzini 	sptep = iter->desc->sptes[iter->pos];
1088c50d8ae3SPaolo Bonzini out:
1089c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1090c50d8ae3SPaolo Bonzini 	return sptep;
1091c50d8ae3SPaolo Bonzini }
1092c50d8ae3SPaolo Bonzini 
1093c50d8ae3SPaolo Bonzini /*
1094c50d8ae3SPaolo Bonzini  * Must be used with a valid iterator: e.g. after rmap_get_first().
1095c50d8ae3SPaolo Bonzini  *
1096c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1097c50d8ae3SPaolo Bonzini  */
1098c50d8ae3SPaolo Bonzini static u64 *rmap_get_next(struct rmap_iterator *iter)
1099c50d8ae3SPaolo Bonzini {
1100c50d8ae3SPaolo Bonzini 	u64 *sptep;
1101c50d8ae3SPaolo Bonzini 
1102c50d8ae3SPaolo Bonzini 	if (iter->desc) {
1103c50d8ae3SPaolo Bonzini 		if (iter->pos < PTE_LIST_EXT - 1) {
1104c50d8ae3SPaolo Bonzini 			++iter->pos;
1105c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1106c50d8ae3SPaolo Bonzini 			if (sptep)
1107c50d8ae3SPaolo Bonzini 				goto out;
1108c50d8ae3SPaolo Bonzini 		}
1109c50d8ae3SPaolo Bonzini 
1110c50d8ae3SPaolo Bonzini 		iter->desc = iter->desc->more;
1111c50d8ae3SPaolo Bonzini 
1112c50d8ae3SPaolo Bonzini 		if (iter->desc) {
1113c50d8ae3SPaolo Bonzini 			iter->pos = 0;
1114c50d8ae3SPaolo Bonzini 			/* desc->sptes[0] cannot be NULL */
1115c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1116c50d8ae3SPaolo Bonzini 			goto out;
1117c50d8ae3SPaolo Bonzini 		}
1118c50d8ae3SPaolo Bonzini 	}
1119c50d8ae3SPaolo Bonzini 
1120c50d8ae3SPaolo Bonzini 	return NULL;
1121c50d8ae3SPaolo Bonzini out:
1122c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1123c50d8ae3SPaolo Bonzini 	return sptep;
1124c50d8ae3SPaolo Bonzini }
1125c50d8ae3SPaolo Bonzini 
1126c50d8ae3SPaolo Bonzini #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)			\
1127c50d8ae3SPaolo Bonzini 	for (_spte_ = rmap_get_first(_rmap_head_, _iter_);		\
1128c50d8ae3SPaolo Bonzini 	     _spte_; _spte_ = rmap_get_next(_iter_))
1129c50d8ae3SPaolo Bonzini 
1130c50d8ae3SPaolo Bonzini static void drop_spte(struct kvm *kvm, u64 *sptep)
1131c50d8ae3SPaolo Bonzini {
113271f51d2cSMingwei Zhang 	u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
11337fa2a347SSean Christopherson 
11347fa2a347SSean Christopherson 	if (is_shadow_present_pte(old_spte))
1135c50d8ae3SPaolo Bonzini 		rmap_remove(kvm, sptep);
1136c50d8ae3SPaolo Bonzini }
1137c50d8ae3SPaolo Bonzini 
1138c50d8ae3SPaolo Bonzini 
1139c50d8ae3SPaolo Bonzini static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1140c50d8ae3SPaolo Bonzini {
1141c50d8ae3SPaolo Bonzini 	if (is_large_pte(*sptep)) {
114257354682SSean Christopherson 		WARN_ON(sptep_to_sp(sptep)->role.level == PG_LEVEL_4K);
1143c50d8ae3SPaolo Bonzini 		drop_spte(kvm, sptep);
1144c50d8ae3SPaolo Bonzini 		return true;
1145c50d8ae3SPaolo Bonzini 	}
1146c50d8ae3SPaolo Bonzini 
1147c50d8ae3SPaolo Bonzini 	return false;
1148c50d8ae3SPaolo Bonzini }
1149c50d8ae3SPaolo Bonzini 
1150c50d8ae3SPaolo Bonzini static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1151c50d8ae3SPaolo Bonzini {
1152c50d8ae3SPaolo Bonzini 	if (__drop_large_spte(vcpu->kvm, sptep)) {
115357354682SSean Christopherson 		struct kvm_mmu_page *sp = sptep_to_sp(sptep);
1154c50d8ae3SPaolo Bonzini 
1155c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1156c50d8ae3SPaolo Bonzini 			KVM_PAGES_PER_HPAGE(sp->role.level));
1157c50d8ae3SPaolo Bonzini 	}
1158c50d8ae3SPaolo Bonzini }
1159c50d8ae3SPaolo Bonzini 
1160c50d8ae3SPaolo Bonzini /*
1161c50d8ae3SPaolo Bonzini  * Write-protect on the specified @sptep, @pt_protect indicates whether
1162c50d8ae3SPaolo Bonzini  * spte write-protection is caused by protecting shadow page table.
1163c50d8ae3SPaolo Bonzini  *
1164c50d8ae3SPaolo Bonzini  * Note: write protection is difference between dirty logging and spte
1165c50d8ae3SPaolo Bonzini  * protection:
1166c50d8ae3SPaolo Bonzini  * - for dirty logging, the spte can be set to writable at anytime if
1167c50d8ae3SPaolo Bonzini  *   its dirty bitmap is properly set.
1168c50d8ae3SPaolo Bonzini  * - for spte protection, the spte can be writable only after unsync-ing
1169c50d8ae3SPaolo Bonzini  *   shadow page.
1170c50d8ae3SPaolo Bonzini  *
1171c50d8ae3SPaolo Bonzini  * Return true if tlb need be flushed.
1172c50d8ae3SPaolo Bonzini  */
1173c50d8ae3SPaolo Bonzini static bool spte_write_protect(u64 *sptep, bool pt_protect)
1174c50d8ae3SPaolo Bonzini {
1175c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1176c50d8ae3SPaolo Bonzini 
1177c50d8ae3SPaolo Bonzini 	if (!is_writable_pte(spte) &&
1178c50d8ae3SPaolo Bonzini 	      !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1179c50d8ae3SPaolo Bonzini 		return false;
1180c50d8ae3SPaolo Bonzini 
1181805a0f83SStephen Zhang 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1182c50d8ae3SPaolo Bonzini 
1183c50d8ae3SPaolo Bonzini 	if (pt_protect)
11845fc3424fSSean Christopherson 		spte &= ~shadow_mmu_writable_mask;
1185c50d8ae3SPaolo Bonzini 	spte = spte & ~PT_WRITABLE_MASK;
1186c50d8ae3SPaolo Bonzini 
1187c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1188c50d8ae3SPaolo Bonzini }
1189c50d8ae3SPaolo Bonzini 
11901346bbb6SDavid Matlack static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1191c50d8ae3SPaolo Bonzini 			       bool pt_protect)
1192c50d8ae3SPaolo Bonzini {
1193c50d8ae3SPaolo Bonzini 	u64 *sptep;
1194c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1195c50d8ae3SPaolo Bonzini 	bool flush = false;
1196c50d8ae3SPaolo Bonzini 
1197c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1198c50d8ae3SPaolo Bonzini 		flush |= spte_write_protect(sptep, pt_protect);
1199c50d8ae3SPaolo Bonzini 
1200c50d8ae3SPaolo Bonzini 	return flush;
1201c50d8ae3SPaolo Bonzini }
1202c50d8ae3SPaolo Bonzini 
1203c50d8ae3SPaolo Bonzini static bool spte_clear_dirty(u64 *sptep)
1204c50d8ae3SPaolo Bonzini {
1205c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1206c50d8ae3SPaolo Bonzini 
1207805a0f83SStephen Zhang 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1208c50d8ae3SPaolo Bonzini 
1209c50d8ae3SPaolo Bonzini 	MMU_WARN_ON(!spte_ad_enabled(spte));
1210c50d8ae3SPaolo Bonzini 	spte &= ~shadow_dirty_mask;
1211c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1212c50d8ae3SPaolo Bonzini }
1213c50d8ae3SPaolo Bonzini 
1214c50d8ae3SPaolo Bonzini static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1215c50d8ae3SPaolo Bonzini {
1216c50d8ae3SPaolo Bonzini 	bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1217c50d8ae3SPaolo Bonzini 					       (unsigned long *)sptep);
1218c50d8ae3SPaolo Bonzini 	if (was_writable && !spte_ad_enabled(*sptep))
1219c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1220c50d8ae3SPaolo Bonzini 
1221c50d8ae3SPaolo Bonzini 	return was_writable;
1222c50d8ae3SPaolo Bonzini }
1223c50d8ae3SPaolo Bonzini 
1224c50d8ae3SPaolo Bonzini /*
1225c50d8ae3SPaolo Bonzini  * Gets the GFN ready for another round of dirty logging by clearing the
1226c50d8ae3SPaolo Bonzini  *	- D bit on ad-enabled SPTEs, and
1227c50d8ae3SPaolo Bonzini  *	- W bit on ad-disabled SPTEs.
1228c50d8ae3SPaolo Bonzini  * Returns true iff any D or W bits were cleared.
1229c50d8ae3SPaolo Bonzini  */
12300a234f5dSSean Christopherson static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1231269e9552SHamza Mahfooz 			       const struct kvm_memory_slot *slot)
1232c50d8ae3SPaolo Bonzini {
1233c50d8ae3SPaolo Bonzini 	u64 *sptep;
1234c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1235c50d8ae3SPaolo Bonzini 	bool flush = false;
1236c50d8ae3SPaolo Bonzini 
1237c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1238c50d8ae3SPaolo Bonzini 		if (spte_ad_need_write_protect(*sptep))
1239c50d8ae3SPaolo Bonzini 			flush |= spte_wrprot_for_clear_dirty(sptep);
1240c50d8ae3SPaolo Bonzini 		else
1241c50d8ae3SPaolo Bonzini 			flush |= spte_clear_dirty(sptep);
1242c50d8ae3SPaolo Bonzini 
1243c50d8ae3SPaolo Bonzini 	return flush;
1244c50d8ae3SPaolo Bonzini }
1245c50d8ae3SPaolo Bonzini 
1246c50d8ae3SPaolo Bonzini /**
1247c50d8ae3SPaolo Bonzini  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1248c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1249c50d8ae3SPaolo Bonzini  * @slot: slot to protect
1250c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1251c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should protect
1252c50d8ae3SPaolo Bonzini  *
125389212919SKeqian Zhu  * Used when we do not need to care about huge page mappings.
1254c50d8ae3SPaolo Bonzini  */
1255c50d8ae3SPaolo Bonzini static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1256c50d8ae3SPaolo Bonzini 				     struct kvm_memory_slot *slot,
1257c50d8ae3SPaolo Bonzini 				     gfn_t gfn_offset, unsigned long mask)
1258c50d8ae3SPaolo Bonzini {
1259c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1260c50d8ae3SPaolo Bonzini 
1261897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
1262a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1263a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, true);
1264e2209710SBen Gardon 
1265e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1266e2209710SBen Gardon 		return;
1267e2209710SBen Gardon 
1268c50d8ae3SPaolo Bonzini 	while (mask) {
126993e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
12703bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
12711346bbb6SDavid Matlack 		rmap_write_protect(rmap_head, false);
1272c50d8ae3SPaolo Bonzini 
1273c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1274c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1275c50d8ae3SPaolo Bonzini 	}
1276c50d8ae3SPaolo Bonzini }
1277c50d8ae3SPaolo Bonzini 
1278c50d8ae3SPaolo Bonzini /**
1279c50d8ae3SPaolo Bonzini  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1280c50d8ae3SPaolo Bonzini  * protect the page if the D-bit isn't supported.
1281c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1282c50d8ae3SPaolo Bonzini  * @slot: slot to clear D-bit
1283c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1284c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should clear D-bit
1285c50d8ae3SPaolo Bonzini  *
1286c50d8ae3SPaolo Bonzini  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1287c50d8ae3SPaolo Bonzini  */
1288a018eba5SSean Christopherson static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1289c50d8ae3SPaolo Bonzini 					 struct kvm_memory_slot *slot,
1290c50d8ae3SPaolo Bonzini 					 gfn_t gfn_offset, unsigned long mask)
1291c50d8ae3SPaolo Bonzini {
1292c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1293c50d8ae3SPaolo Bonzini 
1294897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
1295a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1296a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, false);
1297e2209710SBen Gardon 
1298e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1299e2209710SBen Gardon 		return;
1300e2209710SBen Gardon 
1301c50d8ae3SPaolo Bonzini 	while (mask) {
130293e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13033bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13040a234f5dSSean Christopherson 		__rmap_clear_dirty(kvm, rmap_head, slot);
1305c50d8ae3SPaolo Bonzini 
1306c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1307c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1308c50d8ae3SPaolo Bonzini 	}
1309c50d8ae3SPaolo Bonzini }
1310c50d8ae3SPaolo Bonzini 
1311c50d8ae3SPaolo Bonzini /**
1312c50d8ae3SPaolo Bonzini  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1313c50d8ae3SPaolo Bonzini  * PT level pages.
1314c50d8ae3SPaolo Bonzini  *
1315c50d8ae3SPaolo Bonzini  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1316c50d8ae3SPaolo Bonzini  * enable dirty logging for them.
1317c50d8ae3SPaolo Bonzini  *
131889212919SKeqian Zhu  * We need to care about huge page mappings: e.g. during dirty logging we may
131989212919SKeqian Zhu  * have such mappings.
1320c50d8ae3SPaolo Bonzini  */
1321c50d8ae3SPaolo Bonzini void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1322c50d8ae3SPaolo Bonzini 				struct kvm_memory_slot *slot,
1323c50d8ae3SPaolo Bonzini 				gfn_t gfn_offset, unsigned long mask)
1324c50d8ae3SPaolo Bonzini {
132589212919SKeqian Zhu 	/*
132689212919SKeqian Zhu 	 * Huge pages are NOT write protected when we start dirty logging in
132789212919SKeqian Zhu 	 * initially-all-set mode; must write protect them here so that they
132889212919SKeqian Zhu 	 * are split to 4K on the first write.
132989212919SKeqian Zhu 	 *
133089212919SKeqian Zhu 	 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
133189212919SKeqian Zhu 	 * of memslot has no such restriction, so the range can cross two large
133289212919SKeqian Zhu 	 * pages.
133389212919SKeqian Zhu 	 */
133489212919SKeqian Zhu 	if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
133589212919SKeqian Zhu 		gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
133689212919SKeqian Zhu 		gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
133789212919SKeqian Zhu 
1338cb00a70bSDavid Matlack 		if (READ_ONCE(eager_page_split))
1339cb00a70bSDavid Matlack 			kvm_mmu_try_split_huge_pages(kvm, slot, start, end, PG_LEVEL_4K);
1340cb00a70bSDavid Matlack 
134189212919SKeqian Zhu 		kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
134289212919SKeqian Zhu 
134389212919SKeqian Zhu 		/* Cross two large pages? */
134489212919SKeqian Zhu 		if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
134589212919SKeqian Zhu 		    ALIGN(end << PAGE_SHIFT, PMD_SIZE))
134689212919SKeqian Zhu 			kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
134789212919SKeqian Zhu 						       PG_LEVEL_2M);
134889212919SKeqian Zhu 	}
134989212919SKeqian Zhu 
135089212919SKeqian Zhu 	/* Now handle 4K PTEs.  */
1351a018eba5SSean Christopherson 	if (kvm_x86_ops.cpu_dirty_log_size)
1352a018eba5SSean Christopherson 		kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1353c50d8ae3SPaolo Bonzini 	else
1354c50d8ae3SPaolo Bonzini 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1355c50d8ae3SPaolo Bonzini }
1356c50d8ae3SPaolo Bonzini 
1357fb04a1edSPeter Xu int kvm_cpu_dirty_log_size(void)
1358fb04a1edSPeter Xu {
13596dd03800SSean Christopherson 	return kvm_x86_ops.cpu_dirty_log_size;
1360fb04a1edSPeter Xu }
1361fb04a1edSPeter Xu 
1362c50d8ae3SPaolo Bonzini bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
13633ad93562SKeqian Zhu 				    struct kvm_memory_slot *slot, u64 gfn,
13643ad93562SKeqian Zhu 				    int min_level)
1365c50d8ae3SPaolo Bonzini {
1366c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1367c50d8ae3SPaolo Bonzini 	int i;
1368c50d8ae3SPaolo Bonzini 	bool write_protected = false;
1369c50d8ae3SPaolo Bonzini 
1370e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
13713ad93562SKeqian Zhu 		for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
137293e083d4SDavid Matlack 			rmap_head = gfn_to_rmap(gfn, i, slot);
13731346bbb6SDavid Matlack 			write_protected |= rmap_write_protect(rmap_head, true);
1374c50d8ae3SPaolo Bonzini 		}
1375e2209710SBen Gardon 	}
1376c50d8ae3SPaolo Bonzini 
1377897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
137846044f72SBen Gardon 		write_protected |=
13793ad93562SKeqian Zhu 			kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
138046044f72SBen Gardon 
1381c50d8ae3SPaolo Bonzini 	return write_protected;
1382c50d8ae3SPaolo Bonzini }
1383c50d8ae3SPaolo Bonzini 
1384cf48f9e2SDavid Matlack static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1385c50d8ae3SPaolo Bonzini {
1386c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
1387c50d8ae3SPaolo Bonzini 
1388c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
13893ad93562SKeqian Zhu 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1390c50d8ae3SPaolo Bonzini }
1391c50d8ae3SPaolo Bonzini 
13920a234f5dSSean Christopherson static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1393269e9552SHamza Mahfooz 			  const struct kvm_memory_slot *slot)
1394c50d8ae3SPaolo Bonzini {
139571f51d2cSMingwei Zhang 	return pte_list_destroy(kvm, rmap_head);
1396c50d8ae3SPaolo Bonzini }
1397c50d8ae3SPaolo Bonzini 
13983039bcc7SSean Christopherson static bool kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1399c50d8ae3SPaolo Bonzini 			    struct kvm_memory_slot *slot, gfn_t gfn, int level,
14003039bcc7SSean Christopherson 			    pte_t unused)
1401c50d8ae3SPaolo Bonzini {
14020a234f5dSSean Christopherson 	return kvm_zap_rmapp(kvm, rmap_head, slot);
1403c50d8ae3SPaolo Bonzini }
1404c50d8ae3SPaolo Bonzini 
14053039bcc7SSean Christopherson static bool kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1406c50d8ae3SPaolo Bonzini 			      struct kvm_memory_slot *slot, gfn_t gfn, int level,
14073039bcc7SSean Christopherson 			      pte_t pte)
1408c50d8ae3SPaolo Bonzini {
1409c50d8ae3SPaolo Bonzini 	u64 *sptep;
1410c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
141198a26b69SVihas Mak 	bool need_flush = false;
1412c50d8ae3SPaolo Bonzini 	u64 new_spte;
1413c50d8ae3SPaolo Bonzini 	kvm_pfn_t new_pfn;
1414c50d8ae3SPaolo Bonzini 
14153039bcc7SSean Christopherson 	WARN_ON(pte_huge(pte));
14163039bcc7SSean Christopherson 	new_pfn = pte_pfn(pte);
1417c50d8ae3SPaolo Bonzini 
1418c50d8ae3SPaolo Bonzini restart:
1419c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
1420805a0f83SStephen Zhang 		rmap_printk("spte %p %llx gfn %llx (%d)\n",
1421c50d8ae3SPaolo Bonzini 			    sptep, *sptep, gfn, level);
1422c50d8ae3SPaolo Bonzini 
142398a26b69SVihas Mak 		need_flush = true;
1424c50d8ae3SPaolo Bonzini 
14253039bcc7SSean Christopherson 		if (pte_write(pte)) {
142671f51d2cSMingwei Zhang 			pte_list_remove(kvm, rmap_head, sptep);
1427c50d8ae3SPaolo Bonzini 			goto restart;
1428c50d8ae3SPaolo Bonzini 		} else {
1429cb3eedabSPaolo Bonzini 			new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1430cb3eedabSPaolo Bonzini 					*sptep, new_pfn);
1431c50d8ae3SPaolo Bonzini 
143271f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, sptep);
1433c50d8ae3SPaolo Bonzini 			mmu_spte_set(sptep, new_spte);
1434c50d8ae3SPaolo Bonzini 		}
1435c50d8ae3SPaolo Bonzini 	}
1436c50d8ae3SPaolo Bonzini 
1437c50d8ae3SPaolo Bonzini 	if (need_flush && kvm_available_flush_tlb_with_range()) {
1438c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
143998a26b69SVihas Mak 		return false;
1440c50d8ae3SPaolo Bonzini 	}
1441c50d8ae3SPaolo Bonzini 
1442c50d8ae3SPaolo Bonzini 	return need_flush;
1443c50d8ae3SPaolo Bonzini }
1444c50d8ae3SPaolo Bonzini 
1445c50d8ae3SPaolo Bonzini struct slot_rmap_walk_iterator {
1446c50d8ae3SPaolo Bonzini 	/* input fields. */
1447269e9552SHamza Mahfooz 	const struct kvm_memory_slot *slot;
1448c50d8ae3SPaolo Bonzini 	gfn_t start_gfn;
1449c50d8ae3SPaolo Bonzini 	gfn_t end_gfn;
1450c50d8ae3SPaolo Bonzini 	int start_level;
1451c50d8ae3SPaolo Bonzini 	int end_level;
1452c50d8ae3SPaolo Bonzini 
1453c50d8ae3SPaolo Bonzini 	/* output fields. */
1454c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1455c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap;
1456c50d8ae3SPaolo Bonzini 	int level;
1457c50d8ae3SPaolo Bonzini 
1458c50d8ae3SPaolo Bonzini 	/* private field. */
1459c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *end_rmap;
1460c50d8ae3SPaolo Bonzini };
1461c50d8ae3SPaolo Bonzini 
1462c50d8ae3SPaolo Bonzini static void
1463c50d8ae3SPaolo Bonzini rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1464c50d8ae3SPaolo Bonzini {
1465c50d8ae3SPaolo Bonzini 	iterator->level = level;
1466c50d8ae3SPaolo Bonzini 	iterator->gfn = iterator->start_gfn;
146793e083d4SDavid Matlack 	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
146893e083d4SDavid Matlack 	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1469c50d8ae3SPaolo Bonzini }
1470c50d8ae3SPaolo Bonzini 
1471c50d8ae3SPaolo Bonzini static void
1472c50d8ae3SPaolo Bonzini slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1473269e9552SHamza Mahfooz 		    const struct kvm_memory_slot *slot, int start_level,
1474c50d8ae3SPaolo Bonzini 		    int end_level, gfn_t start_gfn, gfn_t end_gfn)
1475c50d8ae3SPaolo Bonzini {
1476c50d8ae3SPaolo Bonzini 	iterator->slot = slot;
1477c50d8ae3SPaolo Bonzini 	iterator->start_level = start_level;
1478c50d8ae3SPaolo Bonzini 	iterator->end_level = end_level;
1479c50d8ae3SPaolo Bonzini 	iterator->start_gfn = start_gfn;
1480c50d8ae3SPaolo Bonzini 	iterator->end_gfn = end_gfn;
1481c50d8ae3SPaolo Bonzini 
1482c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->start_level);
1483c50d8ae3SPaolo Bonzini }
1484c50d8ae3SPaolo Bonzini 
1485c50d8ae3SPaolo Bonzini static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1486c50d8ae3SPaolo Bonzini {
1487c50d8ae3SPaolo Bonzini 	return !!iterator->rmap;
1488c50d8ae3SPaolo Bonzini }
1489c50d8ae3SPaolo Bonzini 
1490c50d8ae3SPaolo Bonzini static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1491c50d8ae3SPaolo Bonzini {
1492c50d8ae3SPaolo Bonzini 	if (++iterator->rmap <= iterator->end_rmap) {
1493c50d8ae3SPaolo Bonzini 		iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1494c50d8ae3SPaolo Bonzini 		return;
1495c50d8ae3SPaolo Bonzini 	}
1496c50d8ae3SPaolo Bonzini 
1497c50d8ae3SPaolo Bonzini 	if (++iterator->level > iterator->end_level) {
1498c50d8ae3SPaolo Bonzini 		iterator->rmap = NULL;
1499c50d8ae3SPaolo Bonzini 		return;
1500c50d8ae3SPaolo Bonzini 	}
1501c50d8ae3SPaolo Bonzini 
1502c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->level);
1503c50d8ae3SPaolo Bonzini }
1504c50d8ae3SPaolo Bonzini 
1505c50d8ae3SPaolo Bonzini #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1506c50d8ae3SPaolo Bonzini 	   _start_gfn, _end_gfn, _iter_)				\
1507c50d8ae3SPaolo Bonzini 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1508c50d8ae3SPaolo Bonzini 				 _end_level_, _start_gfn, _end_gfn);	\
1509c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_okay(_iter_);				\
1510c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_next(_iter_))
1511c50d8ae3SPaolo Bonzini 
15123039bcc7SSean Christopherson typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1513c1b91493SSean Christopherson 			       struct kvm_memory_slot *slot, gfn_t gfn,
15143039bcc7SSean Christopherson 			       int level, pte_t pte);
1515c1b91493SSean Christopherson 
15163039bcc7SSean Christopherson static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
15173039bcc7SSean Christopherson 						 struct kvm_gfn_range *range,
1518c1b91493SSean Christopherson 						 rmap_handler_t handler)
1519c50d8ae3SPaolo Bonzini {
1520c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
15213039bcc7SSean Christopherson 	bool ret = false;
1522c50d8ae3SPaolo Bonzini 
15233039bcc7SSean Christopherson 	for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
15243039bcc7SSean Christopherson 				 range->start, range->end - 1, &iterator)
15253039bcc7SSean Christopherson 		ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
15263039bcc7SSean Christopherson 			       iterator.level, range->pte);
1527c50d8ae3SPaolo Bonzini 
1528c50d8ae3SPaolo Bonzini 	return ret;
1529c50d8ae3SPaolo Bonzini }
1530c50d8ae3SPaolo Bonzini 
15313039bcc7SSean Christopherson bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1532c50d8ae3SPaolo Bonzini {
1533e2209710SBen Gardon 	bool flush = false;
1534c50d8ae3SPaolo Bonzini 
1535e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
15363039bcc7SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_unmap_rmapp);
1537063afacdSBen Gardon 
1538897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
1539c7785d85SHou Wenlong 		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1540063afacdSBen Gardon 
15413039bcc7SSean Christopherson 	return flush;
1542c50d8ae3SPaolo Bonzini }
1543c50d8ae3SPaolo Bonzini 
15443039bcc7SSean Christopherson bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1545c50d8ae3SPaolo Bonzini {
1546e2209710SBen Gardon 	bool flush = false;
15471d8dd6b3SBen Gardon 
1548e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
15493039bcc7SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmapp);
15501d8dd6b3SBen Gardon 
1551897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
15523039bcc7SSean Christopherson 		flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
15531d8dd6b3SBen Gardon 
15543039bcc7SSean Christopherson 	return flush;
1555c50d8ae3SPaolo Bonzini }
1556c50d8ae3SPaolo Bonzini 
15573039bcc7SSean Christopherson static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1558c50d8ae3SPaolo Bonzini 			  struct kvm_memory_slot *slot, gfn_t gfn, int level,
15593039bcc7SSean Christopherson 			  pte_t unused)
1560c50d8ae3SPaolo Bonzini {
1561c50d8ae3SPaolo Bonzini 	u64 *sptep;
15623f649ab7SKees Cook 	struct rmap_iterator iter;
1563c50d8ae3SPaolo Bonzini 	int young = 0;
1564c50d8ae3SPaolo Bonzini 
1565c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1566c50d8ae3SPaolo Bonzini 		young |= mmu_spte_age(sptep);
1567c50d8ae3SPaolo Bonzini 
1568c50d8ae3SPaolo Bonzini 	return young;
1569c50d8ae3SPaolo Bonzini }
1570c50d8ae3SPaolo Bonzini 
15713039bcc7SSean Christopherson static bool kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1572c50d8ae3SPaolo Bonzini 			       struct kvm_memory_slot *slot, gfn_t gfn,
15733039bcc7SSean Christopherson 			       int level, pte_t unused)
1574c50d8ae3SPaolo Bonzini {
1575c50d8ae3SPaolo Bonzini 	u64 *sptep;
1576c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1577c50d8ae3SPaolo Bonzini 
1578c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1579c50d8ae3SPaolo Bonzini 		if (is_accessed_spte(*sptep))
158098a26b69SVihas Mak 			return true;
158198a26b69SVihas Mak 	return false;
1582c50d8ae3SPaolo Bonzini }
1583c50d8ae3SPaolo Bonzini 
1584c50d8ae3SPaolo Bonzini #define RMAP_RECYCLE_THRESHOLD 1000
1585c50d8ae3SPaolo Bonzini 
15868a9f566aSDavid Matlack static void rmap_add(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
15878a9f566aSDavid Matlack 		     u64 *spte, gfn_t gfn)
1588c50d8ae3SPaolo Bonzini {
1589c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
159068be1306SDavid Matlack 	struct kvm_rmap_head *rmap_head;
159168be1306SDavid Matlack 	int rmap_count;
1592c50d8ae3SPaolo Bonzini 
159357354682SSean Christopherson 	sp = sptep_to_sp(spte);
159468be1306SDavid Matlack 	kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
159593e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
159668be1306SDavid Matlack 	rmap_count = pte_list_add(vcpu, spte, rmap_head);
1597c50d8ae3SPaolo Bonzini 
159868be1306SDavid Matlack 	if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
15993039bcc7SSean Christopherson 		kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, __pte(0));
160068be1306SDavid Matlack 		kvm_flush_remote_tlbs_with_address(
160168be1306SDavid Matlack 				vcpu->kvm, sp->gfn, KVM_PAGES_PER_HPAGE(sp->role.level));
160268be1306SDavid Matlack 	}
1603c50d8ae3SPaolo Bonzini }
1604c50d8ae3SPaolo Bonzini 
16053039bcc7SSean Christopherson bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1606c50d8ae3SPaolo Bonzini {
1607e2209710SBen Gardon 	bool young = false;
1608f8e14497SBen Gardon 
1609e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
16103039bcc7SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_age_rmapp);
16113039bcc7SSean Christopherson 
1612897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
16133039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1614f8e14497SBen Gardon 
1615f8e14497SBen Gardon 	return young;
1616c50d8ae3SPaolo Bonzini }
1617c50d8ae3SPaolo Bonzini 
16183039bcc7SSean Christopherson bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1619c50d8ae3SPaolo Bonzini {
1620e2209710SBen Gardon 	bool young = false;
1621f8e14497SBen Gardon 
1622e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
16233039bcc7SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmapp);
16243039bcc7SSean Christopherson 
1625897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
16263039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1627f8e14497SBen Gardon 
1628f8e14497SBen Gardon 	return young;
1629c50d8ae3SPaolo Bonzini }
1630c50d8ae3SPaolo Bonzini 
1631c50d8ae3SPaolo Bonzini #ifdef MMU_DEBUG
1632c50d8ae3SPaolo Bonzini static int is_empty_shadow_page(u64 *spt)
1633c50d8ae3SPaolo Bonzini {
1634c50d8ae3SPaolo Bonzini 	u64 *pos;
1635c50d8ae3SPaolo Bonzini 	u64 *end;
1636c50d8ae3SPaolo Bonzini 
1637c50d8ae3SPaolo Bonzini 	for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1638c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*pos)) {
1639c50d8ae3SPaolo Bonzini 			printk(KERN_ERR "%s: %p %llx\n", __func__,
1640c50d8ae3SPaolo Bonzini 			       pos, *pos);
1641c50d8ae3SPaolo Bonzini 			return 0;
1642c50d8ae3SPaolo Bonzini 		}
1643c50d8ae3SPaolo Bonzini 	return 1;
1644c50d8ae3SPaolo Bonzini }
1645c50d8ae3SPaolo Bonzini #endif
1646c50d8ae3SPaolo Bonzini 
1647c50d8ae3SPaolo Bonzini /*
1648c50d8ae3SPaolo Bonzini  * This value is the sum of all of the kvm instances's
1649c50d8ae3SPaolo Bonzini  * kvm->arch.n_used_mmu_pages values.  We need a global,
1650c50d8ae3SPaolo Bonzini  * aggregate version in order to make the slab shrinker
1651c50d8ae3SPaolo Bonzini  * faster
1652c50d8ae3SPaolo Bonzini  */
1653d5aaad6fSSean Christopherson static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1654c50d8ae3SPaolo Bonzini {
1655c50d8ae3SPaolo Bonzini 	kvm->arch.n_used_mmu_pages += nr;
1656c50d8ae3SPaolo Bonzini 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1657c50d8ae3SPaolo Bonzini }
1658c50d8ae3SPaolo Bonzini 
1659c50d8ae3SPaolo Bonzini static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
1660c50d8ae3SPaolo Bonzini {
1661c50d8ae3SPaolo Bonzini 	MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1662c50d8ae3SPaolo Bonzini 	hlist_del(&sp->hash_link);
1663c50d8ae3SPaolo Bonzini 	list_del(&sp->link);
1664c50d8ae3SPaolo Bonzini 	free_page((unsigned long)sp->spt);
1665c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
1666c50d8ae3SPaolo Bonzini 		free_page((unsigned long)sp->gfns);
1667c50d8ae3SPaolo Bonzini 	kmem_cache_free(mmu_page_header_cache, sp);
1668c50d8ae3SPaolo Bonzini }
1669c50d8ae3SPaolo Bonzini 
1670c50d8ae3SPaolo Bonzini static unsigned kvm_page_table_hashfn(gfn_t gfn)
1671c50d8ae3SPaolo Bonzini {
1672c50d8ae3SPaolo Bonzini 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1673c50d8ae3SPaolo Bonzini }
1674c50d8ae3SPaolo Bonzini 
1675c50d8ae3SPaolo Bonzini static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
1676c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp, u64 *parent_pte)
1677c50d8ae3SPaolo Bonzini {
1678c50d8ae3SPaolo Bonzini 	if (!parent_pte)
1679c50d8ae3SPaolo Bonzini 		return;
1680c50d8ae3SPaolo Bonzini 
1681c50d8ae3SPaolo Bonzini 	pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
1682c50d8ae3SPaolo Bonzini }
1683c50d8ae3SPaolo Bonzini 
1684c50d8ae3SPaolo Bonzini static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1685c50d8ae3SPaolo Bonzini 				       u64 *parent_pte)
1686c50d8ae3SPaolo Bonzini {
1687c50d8ae3SPaolo Bonzini 	__pte_list_remove(parent_pte, &sp->parent_ptes);
1688c50d8ae3SPaolo Bonzini }
1689c50d8ae3SPaolo Bonzini 
1690c50d8ae3SPaolo Bonzini static void drop_parent_pte(struct kvm_mmu_page *sp,
1691c50d8ae3SPaolo Bonzini 			    u64 *parent_pte)
1692c50d8ae3SPaolo Bonzini {
1693c50d8ae3SPaolo Bonzini 	mmu_page_remove_parent_pte(sp, parent_pte);
1694c50d8ae3SPaolo Bonzini 	mmu_spte_clear_no_track(parent_pte);
1695c50d8ae3SPaolo Bonzini }
1696c50d8ae3SPaolo Bonzini 
1697c50d8ae3SPaolo Bonzini static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
1698c50d8ae3SPaolo Bonzini {
1699c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1700c50d8ae3SPaolo Bonzini 
170194ce87efSSean Christopherson 	sp = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
170294ce87efSSean Christopherson 	sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
1703c50d8ae3SPaolo Bonzini 	if (!direct)
170494ce87efSSean Christopherson 		sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
1705c50d8ae3SPaolo Bonzini 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
1706c50d8ae3SPaolo Bonzini 
1707c50d8ae3SPaolo Bonzini 	/*
1708c50d8ae3SPaolo Bonzini 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
1709c50d8ae3SPaolo Bonzini 	 * depends on valid pages being added to the head of the list.  See
1710c50d8ae3SPaolo Bonzini 	 * comments in kvm_zap_obsolete_pages().
1711c50d8ae3SPaolo Bonzini 	 */
1712c50d8ae3SPaolo Bonzini 	sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
1713c50d8ae3SPaolo Bonzini 	list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
1714c50d8ae3SPaolo Bonzini 	kvm_mod_used_mmu_pages(vcpu->kvm, +1);
1715c50d8ae3SPaolo Bonzini 	return sp;
1716c50d8ae3SPaolo Bonzini }
1717c50d8ae3SPaolo Bonzini 
1718c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte);
1719c50d8ae3SPaolo Bonzini static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1720c50d8ae3SPaolo Bonzini {
1721c50d8ae3SPaolo Bonzini 	u64 *sptep;
1722c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1723c50d8ae3SPaolo Bonzini 
1724c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1725c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
1726c50d8ae3SPaolo Bonzini 	}
1727c50d8ae3SPaolo Bonzini }
1728c50d8ae3SPaolo Bonzini 
1729c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte)
1730c50d8ae3SPaolo Bonzini {
1731c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1732c50d8ae3SPaolo Bonzini 	unsigned int index;
1733c50d8ae3SPaolo Bonzini 
173457354682SSean Christopherson 	sp = sptep_to_sp(spte);
1735c50d8ae3SPaolo Bonzini 	index = spte - sp->spt;
1736c50d8ae3SPaolo Bonzini 	if (__test_and_set_bit(index, sp->unsync_child_bitmap))
1737c50d8ae3SPaolo Bonzini 		return;
1738c50d8ae3SPaolo Bonzini 	if (sp->unsync_children++)
1739c50d8ae3SPaolo Bonzini 		return;
1740c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
1741c50d8ae3SPaolo Bonzini }
1742c50d8ae3SPaolo Bonzini 
1743c50d8ae3SPaolo Bonzini static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
1744c50d8ae3SPaolo Bonzini 			       struct kvm_mmu_page *sp)
1745c50d8ae3SPaolo Bonzini {
1746c3e5e415SLai Jiangshan 	return -1;
1747c50d8ae3SPaolo Bonzini }
1748c50d8ae3SPaolo Bonzini 
1749c50d8ae3SPaolo Bonzini #define KVM_PAGE_ARRAY_NR 16
1750c50d8ae3SPaolo Bonzini 
1751c50d8ae3SPaolo Bonzini struct kvm_mmu_pages {
1752c50d8ae3SPaolo Bonzini 	struct mmu_page_and_offset {
1753c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
1754c50d8ae3SPaolo Bonzini 		unsigned int idx;
1755c50d8ae3SPaolo Bonzini 	} page[KVM_PAGE_ARRAY_NR];
1756c50d8ae3SPaolo Bonzini 	unsigned int nr;
1757c50d8ae3SPaolo Bonzini };
1758c50d8ae3SPaolo Bonzini 
1759c50d8ae3SPaolo Bonzini static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1760c50d8ae3SPaolo Bonzini 			 int idx)
1761c50d8ae3SPaolo Bonzini {
1762c50d8ae3SPaolo Bonzini 	int i;
1763c50d8ae3SPaolo Bonzini 
1764c50d8ae3SPaolo Bonzini 	if (sp->unsync)
1765c50d8ae3SPaolo Bonzini 		for (i=0; i < pvec->nr; i++)
1766c50d8ae3SPaolo Bonzini 			if (pvec->page[i].sp == sp)
1767c50d8ae3SPaolo Bonzini 				return 0;
1768c50d8ae3SPaolo Bonzini 
1769c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].sp = sp;
1770c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].idx = idx;
1771c50d8ae3SPaolo Bonzini 	pvec->nr++;
1772c50d8ae3SPaolo Bonzini 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
1773c50d8ae3SPaolo Bonzini }
1774c50d8ae3SPaolo Bonzini 
1775c50d8ae3SPaolo Bonzini static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1776c50d8ae3SPaolo Bonzini {
1777c50d8ae3SPaolo Bonzini 	--sp->unsync_children;
1778c50d8ae3SPaolo Bonzini 	WARN_ON((int)sp->unsync_children < 0);
1779c50d8ae3SPaolo Bonzini 	__clear_bit(idx, sp->unsync_child_bitmap);
1780c50d8ae3SPaolo Bonzini }
1781c50d8ae3SPaolo Bonzini 
1782c50d8ae3SPaolo Bonzini static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1783c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1784c50d8ae3SPaolo Bonzini {
1785c50d8ae3SPaolo Bonzini 	int i, ret, nr_unsync_leaf = 0;
1786c50d8ae3SPaolo Bonzini 
1787c50d8ae3SPaolo Bonzini 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1788c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
1789c50d8ae3SPaolo Bonzini 		u64 ent = sp->spt[i];
1790c50d8ae3SPaolo Bonzini 
1791c50d8ae3SPaolo Bonzini 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1792c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1793c50d8ae3SPaolo Bonzini 			continue;
1794c50d8ae3SPaolo Bonzini 		}
1795c50d8ae3SPaolo Bonzini 
1796e47c4aeeSSean Christopherson 		child = to_shadow_page(ent & PT64_BASE_ADDR_MASK);
1797c50d8ae3SPaolo Bonzini 
1798c50d8ae3SPaolo Bonzini 		if (child->unsync_children) {
1799c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1800c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1801c50d8ae3SPaolo Bonzini 
1802c50d8ae3SPaolo Bonzini 			ret = __mmu_unsync_walk(child, pvec);
1803c50d8ae3SPaolo Bonzini 			if (!ret) {
1804c50d8ae3SPaolo Bonzini 				clear_unsync_child_bit(sp, i);
1805c50d8ae3SPaolo Bonzini 				continue;
1806c50d8ae3SPaolo Bonzini 			} else if (ret > 0) {
1807c50d8ae3SPaolo Bonzini 				nr_unsync_leaf += ret;
1808c50d8ae3SPaolo Bonzini 			} else
1809c50d8ae3SPaolo Bonzini 				return ret;
1810c50d8ae3SPaolo Bonzini 		} else if (child->unsync) {
1811c50d8ae3SPaolo Bonzini 			nr_unsync_leaf++;
1812c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1813c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1814c50d8ae3SPaolo Bonzini 		} else
1815c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1816c50d8ae3SPaolo Bonzini 	}
1817c50d8ae3SPaolo Bonzini 
1818c50d8ae3SPaolo Bonzini 	return nr_unsync_leaf;
1819c50d8ae3SPaolo Bonzini }
1820c50d8ae3SPaolo Bonzini 
1821c50d8ae3SPaolo Bonzini #define INVALID_INDEX (-1)
1822c50d8ae3SPaolo Bonzini 
1823c50d8ae3SPaolo Bonzini static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1824c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1825c50d8ae3SPaolo Bonzini {
1826c50d8ae3SPaolo Bonzini 	pvec->nr = 0;
1827c50d8ae3SPaolo Bonzini 	if (!sp->unsync_children)
1828c50d8ae3SPaolo Bonzini 		return 0;
1829c50d8ae3SPaolo Bonzini 
1830c50d8ae3SPaolo Bonzini 	mmu_pages_add(pvec, sp, INVALID_INDEX);
1831c50d8ae3SPaolo Bonzini 	return __mmu_unsync_walk(sp, pvec);
1832c50d8ae3SPaolo Bonzini }
1833c50d8ae3SPaolo Bonzini 
1834c50d8ae3SPaolo Bonzini static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1835c50d8ae3SPaolo Bonzini {
1836c50d8ae3SPaolo Bonzini 	WARN_ON(!sp->unsync);
1837c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_sync_page(sp);
1838c50d8ae3SPaolo Bonzini 	sp->unsync = 0;
1839c50d8ae3SPaolo Bonzini 	--kvm->stat.mmu_unsync;
1840c50d8ae3SPaolo Bonzini }
1841c50d8ae3SPaolo Bonzini 
1842c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1843c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list);
1844c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1845c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list);
1846c50d8ae3SPaolo Bonzini 
1847ac101b7cSSean Christopherson #define for_each_valid_sp(_kvm, _sp, _list)				\
1848ac101b7cSSean Christopherson 	hlist_for_each_entry(_sp, _list, hash_link)			\
1849c50d8ae3SPaolo Bonzini 		if (is_obsolete_sp((_kvm), (_sp))) {			\
1850c50d8ae3SPaolo Bonzini 		} else
1851c50d8ae3SPaolo Bonzini 
1852c50d8ae3SPaolo Bonzini #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn)			\
1853ac101b7cSSean Christopherson 	for_each_valid_sp(_kvm, _sp,					\
1854ac101b7cSSean Christopherson 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
1855c50d8ae3SPaolo Bonzini 		if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
1856c50d8ae3SPaolo Bonzini 
18578d5678a7SHou Wenlong static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1858c50d8ae3SPaolo Bonzini 			 struct list_head *invalid_list)
1859c50d8ae3SPaolo Bonzini {
1860c3e5e415SLai Jiangshan 	int ret = vcpu->arch.mmu->sync_page(vcpu, sp);
1861c3e5e415SLai Jiangshan 
18628d5678a7SHou Wenlong 	if (ret < 0)
1863c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
18648d5678a7SHou Wenlong 	return ret;
1865c50d8ae3SPaolo Bonzini }
1866c50d8ae3SPaolo Bonzini 
1867c50d8ae3SPaolo Bonzini static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1868c50d8ae3SPaolo Bonzini 					struct list_head *invalid_list,
1869c50d8ae3SPaolo Bonzini 					bool remote_flush)
1870c50d8ae3SPaolo Bonzini {
1871c50d8ae3SPaolo Bonzini 	if (!remote_flush && list_empty(invalid_list))
1872c50d8ae3SPaolo Bonzini 		return false;
1873c50d8ae3SPaolo Bonzini 
1874c50d8ae3SPaolo Bonzini 	if (!list_empty(invalid_list))
1875c50d8ae3SPaolo Bonzini 		kvm_mmu_commit_zap_page(kvm, invalid_list);
1876c50d8ae3SPaolo Bonzini 	else
1877c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
1878c50d8ae3SPaolo Bonzini 	return true;
1879c50d8ae3SPaolo Bonzini }
1880c50d8ae3SPaolo Bonzini 
1881c50d8ae3SPaolo Bonzini static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
1882c50d8ae3SPaolo Bonzini {
1883a955cad8SSean Christopherson 	if (sp->role.invalid)
1884a955cad8SSean Christopherson 		return true;
1885a955cad8SSean Christopherson 
1886a955cad8SSean Christopherson 	/* TDP MMU pages due not use the MMU generation. */
1887a955cad8SSean Christopherson 	return !sp->tdp_mmu_page &&
1888c50d8ae3SPaolo Bonzini 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
1889c50d8ae3SPaolo Bonzini }
1890c50d8ae3SPaolo Bonzini 
1891c50d8ae3SPaolo Bonzini struct mmu_page_path {
1892c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
1893c50d8ae3SPaolo Bonzini 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
1894c50d8ae3SPaolo Bonzini };
1895c50d8ae3SPaolo Bonzini 
1896c50d8ae3SPaolo Bonzini #define for_each_sp(pvec, sp, parents, i)			\
1897c50d8ae3SPaolo Bonzini 		for (i = mmu_pages_first(&pvec, &parents);	\
1898c50d8ae3SPaolo Bonzini 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
1899c50d8ae3SPaolo Bonzini 			i = mmu_pages_next(&pvec, &parents, i))
1900c50d8ae3SPaolo Bonzini 
1901c50d8ae3SPaolo Bonzini static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1902c50d8ae3SPaolo Bonzini 			  struct mmu_page_path *parents,
1903c50d8ae3SPaolo Bonzini 			  int i)
1904c50d8ae3SPaolo Bonzini {
1905c50d8ae3SPaolo Bonzini 	int n;
1906c50d8ae3SPaolo Bonzini 
1907c50d8ae3SPaolo Bonzini 	for (n = i+1; n < pvec->nr; n++) {
1908c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp = pvec->page[n].sp;
1909c50d8ae3SPaolo Bonzini 		unsigned idx = pvec->page[n].idx;
1910c50d8ae3SPaolo Bonzini 		int level = sp->role.level;
1911c50d8ae3SPaolo Bonzini 
1912c50d8ae3SPaolo Bonzini 		parents->idx[level-1] = idx;
19133bae0459SSean Christopherson 		if (level == PG_LEVEL_4K)
1914c50d8ae3SPaolo Bonzini 			break;
1915c50d8ae3SPaolo Bonzini 
1916c50d8ae3SPaolo Bonzini 		parents->parent[level-2] = sp;
1917c50d8ae3SPaolo Bonzini 	}
1918c50d8ae3SPaolo Bonzini 
1919c50d8ae3SPaolo Bonzini 	return n;
1920c50d8ae3SPaolo Bonzini }
1921c50d8ae3SPaolo Bonzini 
1922c50d8ae3SPaolo Bonzini static int mmu_pages_first(struct kvm_mmu_pages *pvec,
1923c50d8ae3SPaolo Bonzini 			   struct mmu_page_path *parents)
1924c50d8ae3SPaolo Bonzini {
1925c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1926c50d8ae3SPaolo Bonzini 	int level;
1927c50d8ae3SPaolo Bonzini 
1928c50d8ae3SPaolo Bonzini 	if (pvec->nr == 0)
1929c50d8ae3SPaolo Bonzini 		return 0;
1930c50d8ae3SPaolo Bonzini 
1931c50d8ae3SPaolo Bonzini 	WARN_ON(pvec->page[0].idx != INVALID_INDEX);
1932c50d8ae3SPaolo Bonzini 
1933c50d8ae3SPaolo Bonzini 	sp = pvec->page[0].sp;
1934c50d8ae3SPaolo Bonzini 	level = sp->role.level;
19353bae0459SSean Christopherson 	WARN_ON(level == PG_LEVEL_4K);
1936c50d8ae3SPaolo Bonzini 
1937c50d8ae3SPaolo Bonzini 	parents->parent[level-2] = sp;
1938c50d8ae3SPaolo Bonzini 
1939c50d8ae3SPaolo Bonzini 	/* Also set up a sentinel.  Further entries in pvec are all
1940c50d8ae3SPaolo Bonzini 	 * children of sp, so this element is never overwritten.
1941c50d8ae3SPaolo Bonzini 	 */
1942c50d8ae3SPaolo Bonzini 	parents->parent[level-1] = NULL;
1943c50d8ae3SPaolo Bonzini 	return mmu_pages_next(pvec, parents, 0);
1944c50d8ae3SPaolo Bonzini }
1945c50d8ae3SPaolo Bonzini 
1946c50d8ae3SPaolo Bonzini static void mmu_pages_clear_parents(struct mmu_page_path *parents)
1947c50d8ae3SPaolo Bonzini {
1948c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1949c50d8ae3SPaolo Bonzini 	unsigned int level = 0;
1950c50d8ae3SPaolo Bonzini 
1951c50d8ae3SPaolo Bonzini 	do {
1952c50d8ae3SPaolo Bonzini 		unsigned int idx = parents->idx[level];
1953c50d8ae3SPaolo Bonzini 		sp = parents->parent[level];
1954c50d8ae3SPaolo Bonzini 		if (!sp)
1955c50d8ae3SPaolo Bonzini 			return;
1956c50d8ae3SPaolo Bonzini 
1957c50d8ae3SPaolo Bonzini 		WARN_ON(idx == INVALID_INDEX);
1958c50d8ae3SPaolo Bonzini 		clear_unsync_child_bit(sp, idx);
1959c50d8ae3SPaolo Bonzini 		level++;
1960c50d8ae3SPaolo Bonzini 	} while (!sp->unsync_children);
1961c50d8ae3SPaolo Bonzini }
1962c50d8ae3SPaolo Bonzini 
196365855ed8SLai Jiangshan static int mmu_sync_children(struct kvm_vcpu *vcpu,
196465855ed8SLai Jiangshan 			     struct kvm_mmu_page *parent, bool can_yield)
1965c50d8ae3SPaolo Bonzini {
1966c50d8ae3SPaolo Bonzini 	int i;
1967c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1968c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
1969c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
1970c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
1971c50d8ae3SPaolo Bonzini 	bool flush = false;
1972c50d8ae3SPaolo Bonzini 
1973c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
1974c50d8ae3SPaolo Bonzini 		bool protected = false;
1975c50d8ae3SPaolo Bonzini 
1976c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i)
1977cf48f9e2SDavid Matlack 			protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
1978c50d8ae3SPaolo Bonzini 
1979c50d8ae3SPaolo Bonzini 		if (protected) {
19805591c069SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
1981c50d8ae3SPaolo Bonzini 			flush = false;
1982c50d8ae3SPaolo Bonzini 		}
1983c50d8ae3SPaolo Bonzini 
1984c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
1985479a1efcSSean Christopherson 			kvm_unlink_unsync_page(vcpu->kvm, sp);
19868d5678a7SHou Wenlong 			flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
1987c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
1988c50d8ae3SPaolo Bonzini 		}
1989531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
1990c3e5e415SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
199165855ed8SLai Jiangshan 			if (!can_yield) {
199265855ed8SLai Jiangshan 				kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
199365855ed8SLai Jiangshan 				return -EINTR;
199465855ed8SLai Jiangshan 			}
199565855ed8SLai Jiangshan 
1996531810caSBen Gardon 			cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
1997c50d8ae3SPaolo Bonzini 			flush = false;
1998c50d8ae3SPaolo Bonzini 		}
1999c50d8ae3SPaolo Bonzini 	}
2000c50d8ae3SPaolo Bonzini 
2001c3e5e415SLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
200265855ed8SLai Jiangshan 	return 0;
2003c50d8ae3SPaolo Bonzini }
2004c50d8ae3SPaolo Bonzini 
2005c50d8ae3SPaolo Bonzini static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2006c50d8ae3SPaolo Bonzini {
2007c50d8ae3SPaolo Bonzini 	atomic_set(&sp->write_flooding_count,  0);
2008c50d8ae3SPaolo Bonzini }
2009c50d8ae3SPaolo Bonzini 
2010c50d8ae3SPaolo Bonzini static void clear_sp_write_flooding_count(u64 *spte)
2011c50d8ae3SPaolo Bonzini {
201257354682SSean Christopherson 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
2013c50d8ae3SPaolo Bonzini }
2014c50d8ae3SPaolo Bonzini 
2015c50d8ae3SPaolo Bonzini static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2016c50d8ae3SPaolo Bonzini 					     gfn_t gfn,
2017c50d8ae3SPaolo Bonzini 					     gva_t gaddr,
2018c50d8ae3SPaolo Bonzini 					     unsigned level,
2019c50d8ae3SPaolo Bonzini 					     int direct,
20200a2b64c5SBen Gardon 					     unsigned int access)
2021c50d8ae3SPaolo Bonzini {
2022fb58a9c3SSean Christopherson 	bool direct_mmu = vcpu->arch.mmu->direct_map;
2023c50d8ae3SPaolo Bonzini 	union kvm_mmu_page_role role;
2024ac101b7cSSean Christopherson 	struct hlist_head *sp_list;
2025c50d8ae3SPaolo Bonzini 	unsigned quadrant;
2026c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
20278d5678a7SHou Wenlong 	int ret;
2028c50d8ae3SPaolo Bonzini 	int collisions = 0;
2029c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2030c50d8ae3SPaolo Bonzini 
2031*7a458f0eSPaolo Bonzini 	role = vcpu->arch.mmu->root_role;
2032c50d8ae3SPaolo Bonzini 	role.level = level;
2033c50d8ae3SPaolo Bonzini 	role.direct = direct;
2034c50d8ae3SPaolo Bonzini 	role.access = access;
2035bb3b394dSLai Jiangshan 	if (role.has_4_byte_gpte) {
2036c50d8ae3SPaolo Bonzini 		quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2037c50d8ae3SPaolo Bonzini 		quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2038c50d8ae3SPaolo Bonzini 		role.quadrant = quadrant;
2039c50d8ae3SPaolo Bonzini 	}
2040ac101b7cSSean Christopherson 
2041ac101b7cSSean Christopherson 	sp_list = &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2042ac101b7cSSean Christopherson 	for_each_valid_sp(vcpu->kvm, sp, sp_list) {
2043c50d8ae3SPaolo Bonzini 		if (sp->gfn != gfn) {
2044c50d8ae3SPaolo Bonzini 			collisions++;
2045c50d8ae3SPaolo Bonzini 			continue;
2046c50d8ae3SPaolo Bonzini 		}
2047c50d8ae3SPaolo Bonzini 
2048ddc16abbSSean Christopherson 		if (sp->role.word != role.word) {
2049ddc16abbSSean Christopherson 			/*
2050ddc16abbSSean Christopherson 			 * If the guest is creating an upper-level page, zap
2051ddc16abbSSean Christopherson 			 * unsync pages for the same gfn.  While it's possible
2052ddc16abbSSean Christopherson 			 * the guest is using recursive page tables, in all
2053ddc16abbSSean Christopherson 			 * likelihood the guest has stopped using the unsync
2054ddc16abbSSean Christopherson 			 * page and is installing a completely unrelated page.
2055ddc16abbSSean Christopherson 			 * Unsync pages must not be left as is, because the new
2056ddc16abbSSean Christopherson 			 * upper-level page will be write-protected.
2057ddc16abbSSean Christopherson 			 */
2058ddc16abbSSean Christopherson 			if (level > PG_LEVEL_4K && sp->unsync)
2059ddc16abbSSean Christopherson 				kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
2060ddc16abbSSean Christopherson 							 &invalid_list);
2061c50d8ae3SPaolo Bonzini 			continue;
2062ddc16abbSSean Christopherson 		}
2063c50d8ae3SPaolo Bonzini 
2064fb58a9c3SSean Christopherson 		if (direct_mmu)
2065fb58a9c3SSean Christopherson 			goto trace_get_page;
2066fb58a9c3SSean Christopherson 
2067c50d8ae3SPaolo Bonzini 		if (sp->unsync) {
206807dc4f35SSean Christopherson 			/*
2069479a1efcSSean Christopherson 			 * The page is good, but is stale.  kvm_sync_page does
207007dc4f35SSean Christopherson 			 * get the latest guest state, but (unlike mmu_unsync_children)
207107dc4f35SSean Christopherson 			 * it doesn't write-protect the page or mark it synchronized!
207207dc4f35SSean Christopherson 			 * This way the validity of the mapping is ensured, but the
207307dc4f35SSean Christopherson 			 * overhead of write protection is not incurred until the
207407dc4f35SSean Christopherson 			 * guest invalidates the TLB mapping.  This allows multiple
207507dc4f35SSean Christopherson 			 * SPs for a single gfn to be unsync.
207607dc4f35SSean Christopherson 			 *
207707dc4f35SSean Christopherson 			 * If the sync fails, the page is zapped.  If so, break
207807dc4f35SSean Christopherson 			 * in order to rebuild it.
2079c50d8ae3SPaolo Bonzini 			 */
20808d5678a7SHou Wenlong 			ret = kvm_sync_page(vcpu, sp, &invalid_list);
20818d5678a7SHou Wenlong 			if (ret < 0)
2082c50d8ae3SPaolo Bonzini 				break;
2083c50d8ae3SPaolo Bonzini 
2084c50d8ae3SPaolo Bonzini 			WARN_ON(!list_empty(&invalid_list));
20858d5678a7SHou Wenlong 			if (ret > 0)
2086c3e5e415SLai Jiangshan 				kvm_flush_remote_tlbs(vcpu->kvm);
2087c50d8ae3SPaolo Bonzini 		}
2088c50d8ae3SPaolo Bonzini 
2089c50d8ae3SPaolo Bonzini 		__clear_sp_write_flooding_count(sp);
2090fb58a9c3SSean Christopherson 
2091fb58a9c3SSean Christopherson trace_get_page:
2092c50d8ae3SPaolo Bonzini 		trace_kvm_mmu_get_page(sp, false);
2093c50d8ae3SPaolo Bonzini 		goto out;
2094c50d8ae3SPaolo Bonzini 	}
2095c50d8ae3SPaolo Bonzini 
2096c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_cache_miss;
2097c50d8ae3SPaolo Bonzini 
2098c50d8ae3SPaolo Bonzini 	sp = kvm_mmu_alloc_page(vcpu, direct);
2099c50d8ae3SPaolo Bonzini 
2100c50d8ae3SPaolo Bonzini 	sp->gfn = gfn;
2101c50d8ae3SPaolo Bonzini 	sp->role = role;
2102ac101b7cSSean Christopherson 	hlist_add_head(&sp->hash_link, sp_list);
2103c50d8ae3SPaolo Bonzini 	if (!direct) {
2104c50d8ae3SPaolo Bonzini 		account_shadowed(vcpu->kvm, sp);
2105cf48f9e2SDavid Matlack 		if (level == PG_LEVEL_4K && kvm_vcpu_write_protect_gfn(vcpu, gfn))
2106c50d8ae3SPaolo Bonzini 			kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2107c50d8ae3SPaolo Bonzini 	}
2108c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_get_page(sp, true);
2109c50d8ae3SPaolo Bonzini out:
2110ddc16abbSSean Christopherson 	kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
2111ddc16abbSSean Christopherson 
2112c50d8ae3SPaolo Bonzini 	if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2113c50d8ae3SPaolo Bonzini 		vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2114c50d8ae3SPaolo Bonzini 	return sp;
2115c50d8ae3SPaolo Bonzini }
2116c50d8ae3SPaolo Bonzini 
2117c50d8ae3SPaolo Bonzini static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2118c50d8ae3SPaolo Bonzini 					struct kvm_vcpu *vcpu, hpa_t root,
2119c50d8ae3SPaolo Bonzini 					u64 addr)
2120c50d8ae3SPaolo Bonzini {
2121c50d8ae3SPaolo Bonzini 	iterator->addr = addr;
2122c50d8ae3SPaolo Bonzini 	iterator->shadow_addr = root;
2123c50d8ae3SPaolo Bonzini 	iterator->level = vcpu->arch.mmu->shadow_root_level;
2124c50d8ae3SPaolo Bonzini 
212512ec33a7SLai Jiangshan 	if (iterator->level >= PT64_ROOT_4LEVEL &&
2126c50d8ae3SPaolo Bonzini 	    vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2127c50d8ae3SPaolo Bonzini 	    !vcpu->arch.mmu->direct_map)
212812ec33a7SLai Jiangshan 		iterator->level = PT32E_ROOT_LEVEL;
2129c50d8ae3SPaolo Bonzini 
2130c50d8ae3SPaolo Bonzini 	if (iterator->level == PT32E_ROOT_LEVEL) {
2131c50d8ae3SPaolo Bonzini 		/*
2132c50d8ae3SPaolo Bonzini 		 * prev_root is currently only used for 64-bit hosts. So only
2133c50d8ae3SPaolo Bonzini 		 * the active root_hpa is valid here.
2134c50d8ae3SPaolo Bonzini 		 */
2135b9e5603cSPaolo Bonzini 		BUG_ON(root != vcpu->arch.mmu->root.hpa);
2136c50d8ae3SPaolo Bonzini 
2137c50d8ae3SPaolo Bonzini 		iterator->shadow_addr
2138c50d8ae3SPaolo Bonzini 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2139c50d8ae3SPaolo Bonzini 		iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2140c50d8ae3SPaolo Bonzini 		--iterator->level;
2141c50d8ae3SPaolo Bonzini 		if (!iterator->shadow_addr)
2142c50d8ae3SPaolo Bonzini 			iterator->level = 0;
2143c50d8ae3SPaolo Bonzini 	}
2144c50d8ae3SPaolo Bonzini }
2145c50d8ae3SPaolo Bonzini 
2146c50d8ae3SPaolo Bonzini static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2147c50d8ae3SPaolo Bonzini 			     struct kvm_vcpu *vcpu, u64 addr)
2148c50d8ae3SPaolo Bonzini {
2149b9e5603cSPaolo Bonzini 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2150c50d8ae3SPaolo Bonzini 				    addr);
2151c50d8ae3SPaolo Bonzini }
2152c50d8ae3SPaolo Bonzini 
2153c50d8ae3SPaolo Bonzini static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2154c50d8ae3SPaolo Bonzini {
21553bae0459SSean Christopherson 	if (iterator->level < PG_LEVEL_4K)
2156c50d8ae3SPaolo Bonzini 		return false;
2157c50d8ae3SPaolo Bonzini 
2158c50d8ae3SPaolo Bonzini 	iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2159c50d8ae3SPaolo Bonzini 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2160c50d8ae3SPaolo Bonzini 	return true;
2161c50d8ae3SPaolo Bonzini }
2162c50d8ae3SPaolo Bonzini 
2163c50d8ae3SPaolo Bonzini static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2164c50d8ae3SPaolo Bonzini 			       u64 spte)
2165c50d8ae3SPaolo Bonzini {
21663e44dce4SLai Jiangshan 	if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2167c50d8ae3SPaolo Bonzini 		iterator->level = 0;
2168c50d8ae3SPaolo Bonzini 		return;
2169c50d8ae3SPaolo Bonzini 	}
2170c50d8ae3SPaolo Bonzini 
2171c50d8ae3SPaolo Bonzini 	iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2172c50d8ae3SPaolo Bonzini 	--iterator->level;
2173c50d8ae3SPaolo Bonzini }
2174c50d8ae3SPaolo Bonzini 
2175c50d8ae3SPaolo Bonzini static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2176c50d8ae3SPaolo Bonzini {
2177c50d8ae3SPaolo Bonzini 	__shadow_walk_next(iterator, *iterator->sptep);
2178c50d8ae3SPaolo Bonzini }
2179c50d8ae3SPaolo Bonzini 
2180c50d8ae3SPaolo Bonzini static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2181c50d8ae3SPaolo Bonzini 			     struct kvm_mmu_page *sp)
2182c50d8ae3SPaolo Bonzini {
2183c50d8ae3SPaolo Bonzini 	u64 spte;
2184c50d8ae3SPaolo Bonzini 
2185c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2186c50d8ae3SPaolo Bonzini 
2187cc4674d0SBen Gardon 	spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2188c50d8ae3SPaolo Bonzini 
2189c50d8ae3SPaolo Bonzini 	mmu_spte_set(sptep, spte);
2190c50d8ae3SPaolo Bonzini 
2191c50d8ae3SPaolo Bonzini 	mmu_page_add_parent_pte(vcpu, sp, sptep);
2192c50d8ae3SPaolo Bonzini 
2193c50d8ae3SPaolo Bonzini 	if (sp->unsync_children || sp->unsync)
2194c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
2195c50d8ae3SPaolo Bonzini }
2196c50d8ae3SPaolo Bonzini 
2197c50d8ae3SPaolo Bonzini static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2198c50d8ae3SPaolo Bonzini 				   unsigned direct_access)
2199c50d8ae3SPaolo Bonzini {
2200c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2201c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
2202c50d8ae3SPaolo Bonzini 
2203c50d8ae3SPaolo Bonzini 		/*
2204c50d8ae3SPaolo Bonzini 		 * For the direct sp, if the guest pte's dirty bit
2205c50d8ae3SPaolo Bonzini 		 * changed form clean to dirty, it will corrupt the
2206c50d8ae3SPaolo Bonzini 		 * sp's access: allow writable in the read-only sp,
2207c50d8ae3SPaolo Bonzini 		 * so we should update the spte at this point to get
2208c50d8ae3SPaolo Bonzini 		 * a new sp with the correct access.
2209c50d8ae3SPaolo Bonzini 		 */
2210e47c4aeeSSean Christopherson 		child = to_shadow_page(*sptep & PT64_BASE_ADDR_MASK);
2211c50d8ae3SPaolo Bonzini 		if (child->role.access == direct_access)
2212c50d8ae3SPaolo Bonzini 			return;
2213c50d8ae3SPaolo Bonzini 
2214c50d8ae3SPaolo Bonzini 		drop_parent_pte(child, sptep);
2215c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2216c50d8ae3SPaolo Bonzini 	}
2217c50d8ae3SPaolo Bonzini }
2218c50d8ae3SPaolo Bonzini 
22192de4085cSBen Gardon /* Returns the number of zapped non-leaf child shadow pages. */
22202de4085cSBen Gardon static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
22212de4085cSBen Gardon 			    u64 *spte, struct list_head *invalid_list)
2222c50d8ae3SPaolo Bonzini {
2223c50d8ae3SPaolo Bonzini 	u64 pte;
2224c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *child;
2225c50d8ae3SPaolo Bonzini 
2226c50d8ae3SPaolo Bonzini 	pte = *spte;
2227c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(pte)) {
2228c50d8ae3SPaolo Bonzini 		if (is_last_spte(pte, sp->role.level)) {
2229c50d8ae3SPaolo Bonzini 			drop_spte(kvm, spte);
2230c50d8ae3SPaolo Bonzini 		} else {
2231e47c4aeeSSean Christopherson 			child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
2232c50d8ae3SPaolo Bonzini 			drop_parent_pte(child, spte);
22332de4085cSBen Gardon 
22342de4085cSBen Gardon 			/*
22352de4085cSBen Gardon 			 * Recursively zap nested TDP SPs, parentless SPs are
22362de4085cSBen Gardon 			 * unlikely to be used again in the near future.  This
22372de4085cSBen Gardon 			 * avoids retaining a large number of stale nested SPs.
22382de4085cSBen Gardon 			 */
22392de4085cSBen Gardon 			if (tdp_enabled && invalid_list &&
22402de4085cSBen Gardon 			    child->role.guest_mode && !child->parent_ptes.val)
22412de4085cSBen Gardon 				return kvm_mmu_prepare_zap_page(kvm, child,
22422de4085cSBen Gardon 								invalid_list);
2243c50d8ae3SPaolo Bonzini 		}
2244ace569e0SSean Christopherson 	} else if (is_mmio_spte(pte)) {
2245c50d8ae3SPaolo Bonzini 		mmu_spte_clear_no_track(spte);
2246ace569e0SSean Christopherson 	}
22472de4085cSBen Gardon 	return 0;
2248c50d8ae3SPaolo Bonzini }
2249c50d8ae3SPaolo Bonzini 
22502de4085cSBen Gardon static int kvm_mmu_page_unlink_children(struct kvm *kvm,
22512de4085cSBen Gardon 					struct kvm_mmu_page *sp,
22522de4085cSBen Gardon 					struct list_head *invalid_list)
2253c50d8ae3SPaolo Bonzini {
22542de4085cSBen Gardon 	int zapped = 0;
2255c50d8ae3SPaolo Bonzini 	unsigned i;
2256c50d8ae3SPaolo Bonzini 
2257c50d8ae3SPaolo Bonzini 	for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
22582de4085cSBen Gardon 		zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
22592de4085cSBen Gardon 
22602de4085cSBen Gardon 	return zapped;
2261c50d8ae3SPaolo Bonzini }
2262c50d8ae3SPaolo Bonzini 
226361827671SJinrong Liang static void kvm_mmu_unlink_parents(struct kvm_mmu_page *sp)
2264c50d8ae3SPaolo Bonzini {
2265c50d8ae3SPaolo Bonzini 	u64 *sptep;
2266c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
2267c50d8ae3SPaolo Bonzini 
2268c50d8ae3SPaolo Bonzini 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2269c50d8ae3SPaolo Bonzini 		drop_parent_pte(sp, sptep);
2270c50d8ae3SPaolo Bonzini }
2271c50d8ae3SPaolo Bonzini 
2272c50d8ae3SPaolo Bonzini static int mmu_zap_unsync_children(struct kvm *kvm,
2273c50d8ae3SPaolo Bonzini 				   struct kvm_mmu_page *parent,
2274c50d8ae3SPaolo Bonzini 				   struct list_head *invalid_list)
2275c50d8ae3SPaolo Bonzini {
2276c50d8ae3SPaolo Bonzini 	int i, zapped = 0;
2277c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2278c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2279c50d8ae3SPaolo Bonzini 
22803bae0459SSean Christopherson 	if (parent->role.level == PG_LEVEL_4K)
2281c50d8ae3SPaolo Bonzini 		return 0;
2282c50d8ae3SPaolo Bonzini 
2283c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2284c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
2285c50d8ae3SPaolo Bonzini 
2286c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2287c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2288c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2289c50d8ae3SPaolo Bonzini 			zapped++;
2290c50d8ae3SPaolo Bonzini 		}
2291c50d8ae3SPaolo Bonzini 	}
2292c50d8ae3SPaolo Bonzini 
2293c50d8ae3SPaolo Bonzini 	return zapped;
2294c50d8ae3SPaolo Bonzini }
2295c50d8ae3SPaolo Bonzini 
2296c50d8ae3SPaolo Bonzini static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2297c50d8ae3SPaolo Bonzini 				       struct kvm_mmu_page *sp,
2298c50d8ae3SPaolo Bonzini 				       struct list_head *invalid_list,
2299c50d8ae3SPaolo Bonzini 				       int *nr_zapped)
2300c50d8ae3SPaolo Bonzini {
2301527d5cd7SSean Christopherson 	bool list_unstable, zapped_root = false;
2302c50d8ae3SPaolo Bonzini 
2303c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_prepare_zap_page(sp);
2304c50d8ae3SPaolo Bonzini 	++kvm->stat.mmu_shadow_zapped;
2305c50d8ae3SPaolo Bonzini 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
23062de4085cSBen Gardon 	*nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
230761827671SJinrong Liang 	kvm_mmu_unlink_parents(sp);
2308c50d8ae3SPaolo Bonzini 
2309c50d8ae3SPaolo Bonzini 	/* Zapping children means active_mmu_pages has become unstable. */
2310c50d8ae3SPaolo Bonzini 	list_unstable = *nr_zapped;
2311c50d8ae3SPaolo Bonzini 
2312c50d8ae3SPaolo Bonzini 	if (!sp->role.invalid && !sp->role.direct)
2313c50d8ae3SPaolo Bonzini 		unaccount_shadowed(kvm, sp);
2314c50d8ae3SPaolo Bonzini 
2315c50d8ae3SPaolo Bonzini 	if (sp->unsync)
2316c50d8ae3SPaolo Bonzini 		kvm_unlink_unsync_page(kvm, sp);
2317c50d8ae3SPaolo Bonzini 	if (!sp->root_count) {
2318c50d8ae3SPaolo Bonzini 		/* Count self */
2319c50d8ae3SPaolo Bonzini 		(*nr_zapped)++;
2320f95eec9bSSean Christopherson 
2321f95eec9bSSean Christopherson 		/*
2322f95eec9bSSean Christopherson 		 * Already invalid pages (previously active roots) are not on
2323f95eec9bSSean Christopherson 		 * the active page list.  See list_del() in the "else" case of
2324f95eec9bSSean Christopherson 		 * !sp->root_count.
2325f95eec9bSSean Christopherson 		 */
2326f95eec9bSSean Christopherson 		if (sp->role.invalid)
2327f95eec9bSSean Christopherson 			list_add(&sp->link, invalid_list);
2328f95eec9bSSean Christopherson 		else
2329c50d8ae3SPaolo Bonzini 			list_move(&sp->link, invalid_list);
2330c50d8ae3SPaolo Bonzini 		kvm_mod_used_mmu_pages(kvm, -1);
2331c50d8ae3SPaolo Bonzini 	} else {
2332f95eec9bSSean Christopherson 		/*
2333f95eec9bSSean Christopherson 		 * Remove the active root from the active page list, the root
2334f95eec9bSSean Christopherson 		 * will be explicitly freed when the root_count hits zero.
2335f95eec9bSSean Christopherson 		 */
2336f95eec9bSSean Christopherson 		list_del(&sp->link);
2337c50d8ae3SPaolo Bonzini 
2338c50d8ae3SPaolo Bonzini 		/*
2339c50d8ae3SPaolo Bonzini 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2340c50d8ae3SPaolo Bonzini 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2341c50d8ae3SPaolo Bonzini 		 * treats invalid shadow pages as being obsolete.
2342c50d8ae3SPaolo Bonzini 		 */
2343527d5cd7SSean Christopherson 		zapped_root = !is_obsolete_sp(kvm, sp);
2344c50d8ae3SPaolo Bonzini 	}
2345c50d8ae3SPaolo Bonzini 
2346c50d8ae3SPaolo Bonzini 	if (sp->lpage_disallowed)
2347c50d8ae3SPaolo Bonzini 		unaccount_huge_nx_page(kvm, sp);
2348c50d8ae3SPaolo Bonzini 
2349c50d8ae3SPaolo Bonzini 	sp->role.invalid = 1;
2350527d5cd7SSean Christopherson 
2351527d5cd7SSean Christopherson 	/*
2352527d5cd7SSean Christopherson 	 * Make the request to free obsolete roots after marking the root
2353527d5cd7SSean Christopherson 	 * invalid, otherwise other vCPUs may not see it as invalid.
2354527d5cd7SSean Christopherson 	 */
2355527d5cd7SSean Christopherson 	if (zapped_root)
2356527d5cd7SSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2357c50d8ae3SPaolo Bonzini 	return list_unstable;
2358c50d8ae3SPaolo Bonzini }
2359c50d8ae3SPaolo Bonzini 
2360c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2361c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list)
2362c50d8ae3SPaolo Bonzini {
2363c50d8ae3SPaolo Bonzini 	int nr_zapped;
2364c50d8ae3SPaolo Bonzini 
2365c50d8ae3SPaolo Bonzini 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2366c50d8ae3SPaolo Bonzini 	return nr_zapped;
2367c50d8ae3SPaolo Bonzini }
2368c50d8ae3SPaolo Bonzini 
2369c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2370c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list)
2371c50d8ae3SPaolo Bonzini {
2372c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *nsp;
2373c50d8ae3SPaolo Bonzini 
2374c50d8ae3SPaolo Bonzini 	if (list_empty(invalid_list))
2375c50d8ae3SPaolo Bonzini 		return;
2376c50d8ae3SPaolo Bonzini 
2377c50d8ae3SPaolo Bonzini 	/*
2378c50d8ae3SPaolo Bonzini 	 * We need to make sure everyone sees our modifications to
2379c50d8ae3SPaolo Bonzini 	 * the page tables and see changes to vcpu->mode here. The barrier
2380c50d8ae3SPaolo Bonzini 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2381c50d8ae3SPaolo Bonzini 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2382c50d8ae3SPaolo Bonzini 	 *
2383c50d8ae3SPaolo Bonzini 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2384c50d8ae3SPaolo Bonzini 	 * guest mode and/or lockless shadow page table walks.
2385c50d8ae3SPaolo Bonzini 	 */
2386c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs(kvm);
2387c50d8ae3SPaolo Bonzini 
2388c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2389c50d8ae3SPaolo Bonzini 		WARN_ON(!sp->role.invalid || sp->root_count);
2390c50d8ae3SPaolo Bonzini 		kvm_mmu_free_page(sp);
2391c50d8ae3SPaolo Bonzini 	}
2392c50d8ae3SPaolo Bonzini }
2393c50d8ae3SPaolo Bonzini 
23946b82ef2cSSean Christopherson static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
23956b82ef2cSSean Christopherson 						  unsigned long nr_to_zap)
2396c50d8ae3SPaolo Bonzini {
23976b82ef2cSSean Christopherson 	unsigned long total_zapped = 0;
23986b82ef2cSSean Christopherson 	struct kvm_mmu_page *sp, *tmp;
2399ba7888ddSSean Christopherson 	LIST_HEAD(invalid_list);
24006b82ef2cSSean Christopherson 	bool unstable;
24016b82ef2cSSean Christopherson 	int nr_zapped;
2402c50d8ae3SPaolo Bonzini 
2403c50d8ae3SPaolo Bonzini 	if (list_empty(&kvm->arch.active_mmu_pages))
2404ba7888ddSSean Christopherson 		return 0;
2405c50d8ae3SPaolo Bonzini 
24066b82ef2cSSean Christopherson restart:
24078fc51726SSean Christopherson 	list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
24086b82ef2cSSean Christopherson 		/*
24096b82ef2cSSean Christopherson 		 * Don't zap active root pages, the page itself can't be freed
24106b82ef2cSSean Christopherson 		 * and zapping it will just force vCPUs to realloc and reload.
24116b82ef2cSSean Christopherson 		 */
24126b82ef2cSSean Christopherson 		if (sp->root_count)
24136b82ef2cSSean Christopherson 			continue;
24146b82ef2cSSean Christopherson 
24156b82ef2cSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
24166b82ef2cSSean Christopherson 						      &nr_zapped);
24176b82ef2cSSean Christopherson 		total_zapped += nr_zapped;
24186b82ef2cSSean Christopherson 		if (total_zapped >= nr_to_zap)
2419ba7888ddSSean Christopherson 			break;
2420ba7888ddSSean Christopherson 
24216b82ef2cSSean Christopherson 		if (unstable)
24226b82ef2cSSean Christopherson 			goto restart;
2423ba7888ddSSean Christopherson 	}
24246b82ef2cSSean Christopherson 
24256b82ef2cSSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
24266b82ef2cSSean Christopherson 
24276b82ef2cSSean Christopherson 	kvm->stat.mmu_recycled += total_zapped;
24286b82ef2cSSean Christopherson 	return total_zapped;
24296b82ef2cSSean Christopherson }
24306b82ef2cSSean Christopherson 
2431afe8d7e6SSean Christopherson static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2432afe8d7e6SSean Christopherson {
2433afe8d7e6SSean Christopherson 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2434afe8d7e6SSean Christopherson 		return kvm->arch.n_max_mmu_pages -
2435afe8d7e6SSean Christopherson 			kvm->arch.n_used_mmu_pages;
2436afe8d7e6SSean Christopherson 
2437afe8d7e6SSean Christopherson 	return 0;
2438c50d8ae3SPaolo Bonzini }
2439c50d8ae3SPaolo Bonzini 
2440ba7888ddSSean Christopherson static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2441ba7888ddSSean Christopherson {
24426b82ef2cSSean Christopherson 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2443ba7888ddSSean Christopherson 
24446b82ef2cSSean Christopherson 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2445ba7888ddSSean Christopherson 		return 0;
2446ba7888ddSSean Christopherson 
24476b82ef2cSSean Christopherson 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2448ba7888ddSSean Christopherson 
24496e6ec584SSean Christopherson 	/*
24506e6ec584SSean Christopherson 	 * Note, this check is intentionally soft, it only guarantees that one
24516e6ec584SSean Christopherson 	 * page is available, while the caller may end up allocating as many as
24526e6ec584SSean Christopherson 	 * four pages, e.g. for PAE roots or for 5-level paging.  Temporarily
24536e6ec584SSean Christopherson 	 * exceeding the (arbitrary by default) limit will not harm the host,
2454c4342633SIngo Molnar 	 * being too aggressive may unnecessarily kill the guest, and getting an
24556e6ec584SSean Christopherson 	 * exact count is far more trouble than it's worth, especially in the
24566e6ec584SSean Christopherson 	 * page fault paths.
24576e6ec584SSean Christopherson 	 */
2458ba7888ddSSean Christopherson 	if (!kvm_mmu_available_pages(vcpu->kvm))
2459ba7888ddSSean Christopherson 		return -ENOSPC;
2460ba7888ddSSean Christopherson 	return 0;
2461ba7888ddSSean Christopherson }
2462ba7888ddSSean Christopherson 
2463c50d8ae3SPaolo Bonzini /*
2464c50d8ae3SPaolo Bonzini  * Changing the number of mmu pages allocated to the vm
2465c50d8ae3SPaolo Bonzini  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2466c50d8ae3SPaolo Bonzini  */
2467c50d8ae3SPaolo Bonzini void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2468c50d8ae3SPaolo Bonzini {
2469531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2470c50d8ae3SPaolo Bonzini 
2471c50d8ae3SPaolo Bonzini 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
24726b82ef2cSSean Christopherson 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
24736b82ef2cSSean Christopherson 						  goal_nr_mmu_pages);
2474c50d8ae3SPaolo Bonzini 
2475c50d8ae3SPaolo Bonzini 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2476c50d8ae3SPaolo Bonzini 	}
2477c50d8ae3SPaolo Bonzini 
2478c50d8ae3SPaolo Bonzini 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2479c50d8ae3SPaolo Bonzini 
2480531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2481c50d8ae3SPaolo Bonzini }
2482c50d8ae3SPaolo Bonzini 
2483c50d8ae3SPaolo Bonzini int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2484c50d8ae3SPaolo Bonzini {
2485c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2486c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2487c50d8ae3SPaolo Bonzini 	int r;
2488c50d8ae3SPaolo Bonzini 
2489c50d8ae3SPaolo Bonzini 	pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2490c50d8ae3SPaolo Bonzini 	r = 0;
2491531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2492c50d8ae3SPaolo Bonzini 	for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2493c50d8ae3SPaolo Bonzini 		pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2494c50d8ae3SPaolo Bonzini 			 sp->role.word);
2495c50d8ae3SPaolo Bonzini 		r = 1;
2496c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2497c50d8ae3SPaolo Bonzini 	}
2498c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2499531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2500c50d8ae3SPaolo Bonzini 
2501c50d8ae3SPaolo Bonzini 	return r;
2502c50d8ae3SPaolo Bonzini }
250396ad91aeSSean Christopherson 
250496ad91aeSSean Christopherson static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
250596ad91aeSSean Christopherson {
250696ad91aeSSean Christopherson 	gpa_t gpa;
250796ad91aeSSean Christopherson 	int r;
250896ad91aeSSean Christopherson 
250996ad91aeSSean Christopherson 	if (vcpu->arch.mmu->direct_map)
251096ad91aeSSean Christopherson 		return 0;
251196ad91aeSSean Christopherson 
251296ad91aeSSean Christopherson 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
251396ad91aeSSean Christopherson 
251496ad91aeSSean Christopherson 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
251596ad91aeSSean Christopherson 
251696ad91aeSSean Christopherson 	return r;
251796ad91aeSSean Christopherson }
2518c50d8ae3SPaolo Bonzini 
25194d78d0b3SBen Gardon static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2520c50d8ae3SPaolo Bonzini {
2521c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_unsync_page(sp);
25224d78d0b3SBen Gardon 	++kvm->stat.mmu_unsync;
2523c50d8ae3SPaolo Bonzini 	sp->unsync = 1;
2524c50d8ae3SPaolo Bonzini 
2525c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
2526c50d8ae3SPaolo Bonzini }
2527c50d8ae3SPaolo Bonzini 
25280337f585SSean Christopherson /*
25290337f585SSean Christopherson  * Attempt to unsync any shadow pages that can be reached by the specified gfn,
25300337f585SSean Christopherson  * KVM is creating a writable mapping for said gfn.  Returns 0 if all pages
25310337f585SSean Christopherson  * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
25320337f585SSean Christopherson  * be write-protected.
25330337f585SSean Christopherson  */
25348283e36aSBen Gardon int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
25352839180cSPaolo Bonzini 			    gfn_t gfn, bool can_unsync, bool prefetch)
2536c50d8ae3SPaolo Bonzini {
2537c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2538ce25681dSSean Christopherson 	bool locked = false;
2539c50d8ae3SPaolo Bonzini 
25400337f585SSean Christopherson 	/*
25410337f585SSean Christopherson 	 * Force write-protection if the page is being tracked.  Note, the page
25420337f585SSean Christopherson 	 * track machinery is used to write-protect upper-level shadow pages,
25430337f585SSean Christopherson 	 * i.e. this guards the role.level == 4K assertion below!
25440337f585SSean Christopherson 	 */
25454d78d0b3SBen Gardon 	if (kvm_slot_page_track_is_active(kvm, slot, gfn, KVM_PAGE_TRACK_WRITE))
25460337f585SSean Christopherson 		return -EPERM;
2547c50d8ae3SPaolo Bonzini 
25480337f585SSean Christopherson 	/*
25490337f585SSean Christopherson 	 * The page is not write-tracked, mark existing shadow pages unsync
25500337f585SSean Christopherson 	 * unless KVM is synchronizing an unsync SP (can_unsync = false).  In
25510337f585SSean Christopherson 	 * that case, KVM must complete emulation of the guest TLB flush before
25520337f585SSean Christopherson 	 * allowing shadow pages to become unsync (writable by the guest).
25530337f585SSean Christopherson 	 */
25544d78d0b3SBen Gardon 	for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2555c50d8ae3SPaolo Bonzini 		if (!can_unsync)
25560337f585SSean Christopherson 			return -EPERM;
2557c50d8ae3SPaolo Bonzini 
2558c50d8ae3SPaolo Bonzini 		if (sp->unsync)
2559c50d8ae3SPaolo Bonzini 			continue;
2560c50d8ae3SPaolo Bonzini 
25612839180cSPaolo Bonzini 		if (prefetch)
2562f1c4a88cSLai Jiangshan 			return -EEXIST;
2563f1c4a88cSLai Jiangshan 
2564ce25681dSSean Christopherson 		/*
2565ce25681dSSean Christopherson 		 * TDP MMU page faults require an additional spinlock as they
2566ce25681dSSean Christopherson 		 * run with mmu_lock held for read, not write, and the unsync
2567ce25681dSSean Christopherson 		 * logic is not thread safe.  Take the spinklock regardless of
2568ce25681dSSean Christopherson 		 * the MMU type to avoid extra conditionals/parameters, there's
2569ce25681dSSean Christopherson 		 * no meaningful penalty if mmu_lock is held for write.
2570ce25681dSSean Christopherson 		 */
2571ce25681dSSean Christopherson 		if (!locked) {
2572ce25681dSSean Christopherson 			locked = true;
25734d78d0b3SBen Gardon 			spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2574ce25681dSSean Christopherson 
2575ce25681dSSean Christopherson 			/*
2576ce25681dSSean Christopherson 			 * Recheck after taking the spinlock, a different vCPU
2577ce25681dSSean Christopherson 			 * may have since marked the page unsync.  A false
2578ce25681dSSean Christopherson 			 * positive on the unprotected check above is not
2579ce25681dSSean Christopherson 			 * possible as clearing sp->unsync _must_ hold mmu_lock
2580ce25681dSSean Christopherson 			 * for write, i.e. unsync cannot transition from 0->1
2581ce25681dSSean Christopherson 			 * while this CPU holds mmu_lock for read (or write).
2582ce25681dSSean Christopherson 			 */
2583ce25681dSSean Christopherson 			if (READ_ONCE(sp->unsync))
2584ce25681dSSean Christopherson 				continue;
2585ce25681dSSean Christopherson 		}
2586ce25681dSSean Christopherson 
25873bae0459SSean Christopherson 		WARN_ON(sp->role.level != PG_LEVEL_4K);
25884d78d0b3SBen Gardon 		kvm_unsync_page(kvm, sp);
2589c50d8ae3SPaolo Bonzini 	}
2590ce25681dSSean Christopherson 	if (locked)
25914d78d0b3SBen Gardon 		spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2592c50d8ae3SPaolo Bonzini 
2593c50d8ae3SPaolo Bonzini 	/*
2594c50d8ae3SPaolo Bonzini 	 * We need to ensure that the marking of unsync pages is visible
2595c50d8ae3SPaolo Bonzini 	 * before the SPTE is updated to allow writes because
2596c50d8ae3SPaolo Bonzini 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2597c50d8ae3SPaolo Bonzini 	 * the MMU lock and so can race with this. If the SPTE was updated
2598c50d8ae3SPaolo Bonzini 	 * before the page had been marked as unsync-ed, something like the
2599c50d8ae3SPaolo Bonzini 	 * following could happen:
2600c50d8ae3SPaolo Bonzini 	 *
2601c50d8ae3SPaolo Bonzini 	 * CPU 1                    CPU 2
2602c50d8ae3SPaolo Bonzini 	 * ---------------------------------------------------------------------
2603c50d8ae3SPaolo Bonzini 	 * 1.2 Host updates SPTE
2604c50d8ae3SPaolo Bonzini 	 *     to be writable
2605c50d8ae3SPaolo Bonzini 	 *                      2.1 Guest writes a GPTE for GVA X.
2606c50d8ae3SPaolo Bonzini 	 *                          (GPTE being in the guest page table shadowed
2607c50d8ae3SPaolo Bonzini 	 *                           by the SP from CPU 1.)
2608c50d8ae3SPaolo Bonzini 	 *                          This reads SPTE during the page table walk.
2609c50d8ae3SPaolo Bonzini 	 *                          Since SPTE.W is read as 1, there is no
2610c50d8ae3SPaolo Bonzini 	 *                          fault.
2611c50d8ae3SPaolo Bonzini 	 *
2612c50d8ae3SPaolo Bonzini 	 *                      2.2 Guest issues TLB flush.
2613c50d8ae3SPaolo Bonzini 	 *                          That causes a VM Exit.
2614c50d8ae3SPaolo Bonzini 	 *
26150337f585SSean Christopherson 	 *                      2.3 Walking of unsync pages sees sp->unsync is
26160337f585SSean Christopherson 	 *                          false and skips the page.
2617c50d8ae3SPaolo Bonzini 	 *
2618c50d8ae3SPaolo Bonzini 	 *                      2.4 Guest accesses GVA X.
2619c50d8ae3SPaolo Bonzini 	 *                          Since the mapping in the SP was not updated,
2620c50d8ae3SPaolo Bonzini 	 *                          so the old mapping for GVA X incorrectly
2621c50d8ae3SPaolo Bonzini 	 *                          gets used.
2622c50d8ae3SPaolo Bonzini 	 * 1.1 Host marks SP
2623c50d8ae3SPaolo Bonzini 	 *     as unsync
2624c50d8ae3SPaolo Bonzini 	 *     (sp->unsync = true)
2625c50d8ae3SPaolo Bonzini 	 *
2626c50d8ae3SPaolo Bonzini 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2627264d3dc1SLai Jiangshan 	 * the situation in 2.4 does not arise.  It pairs with the read barrier
2628264d3dc1SLai Jiangshan 	 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2629c50d8ae3SPaolo Bonzini 	 */
2630c50d8ae3SPaolo Bonzini 	smp_wmb();
2631c50d8ae3SPaolo Bonzini 
26320337f585SSean Christopherson 	return 0;
2633c50d8ae3SPaolo Bonzini }
2634c50d8ae3SPaolo Bonzini 
26358a9f566aSDavid Matlack static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
26368a9f566aSDavid Matlack 			u64 *sptep, unsigned int pte_access, gfn_t gfn,
2637a12f4381SPaolo Bonzini 			kvm_pfn_t pfn, struct kvm_page_fault *fault)
2638799a4190SBen Gardon {
2639d786c778SPaolo Bonzini 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2640eb5cd7ffSPaolo Bonzini 	int level = sp->role.level;
2641c50d8ae3SPaolo Bonzini 	int was_rmapped = 0;
2642c4371c2aSSean Christopherson 	int ret = RET_PF_FIXED;
2643c50d8ae3SPaolo Bonzini 	bool flush = false;
2644ad67e480SPaolo Bonzini 	bool wrprot;
2645d786c778SPaolo Bonzini 	u64 spte;
2646c50d8ae3SPaolo Bonzini 
2647a12f4381SPaolo Bonzini 	/* Prefetching always gets a writable pfn.  */
2648a12f4381SPaolo Bonzini 	bool host_writable = !fault || fault->map_writable;
26492839180cSPaolo Bonzini 	bool prefetch = !fault || fault->prefetch;
2650a12f4381SPaolo Bonzini 	bool write_fault = fault && fault->write;
2651c50d8ae3SPaolo Bonzini 
2652c50d8ae3SPaolo Bonzini 	pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2653c50d8ae3SPaolo Bonzini 		 *sptep, write_fault, gfn);
2654c50d8ae3SPaolo Bonzini 
2655a54aa15cSSean Christopherson 	if (unlikely(is_noslot_pfn(pfn))) {
2656a54aa15cSSean Christopherson 		mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2657a54aa15cSSean Christopherson 		return RET_PF_EMULATE;
2658a54aa15cSSean Christopherson 	}
2659a54aa15cSSean Christopherson 
2660c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep)) {
2661c50d8ae3SPaolo Bonzini 		/*
2662c50d8ae3SPaolo Bonzini 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2663c50d8ae3SPaolo Bonzini 		 * the parent of the now unreachable PTE.
2664c50d8ae3SPaolo Bonzini 		 */
26653bae0459SSean Christopherson 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2666c50d8ae3SPaolo Bonzini 			struct kvm_mmu_page *child;
2667c50d8ae3SPaolo Bonzini 			u64 pte = *sptep;
2668c50d8ae3SPaolo Bonzini 
2669e47c4aeeSSean Christopherson 			child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
2670c50d8ae3SPaolo Bonzini 			drop_parent_pte(child, sptep);
2671c50d8ae3SPaolo Bonzini 			flush = true;
2672c50d8ae3SPaolo Bonzini 		} else if (pfn != spte_to_pfn(*sptep)) {
2673c50d8ae3SPaolo Bonzini 			pgprintk("hfn old %llx new %llx\n",
2674c50d8ae3SPaolo Bonzini 				 spte_to_pfn(*sptep), pfn);
2675c50d8ae3SPaolo Bonzini 			drop_spte(vcpu->kvm, sptep);
2676c50d8ae3SPaolo Bonzini 			flush = true;
2677c50d8ae3SPaolo Bonzini 		} else
2678c50d8ae3SPaolo Bonzini 			was_rmapped = 1;
2679c50d8ae3SPaolo Bonzini 	}
2680c50d8ae3SPaolo Bonzini 
26812839180cSPaolo Bonzini 	wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
26827158bee4SPaolo Bonzini 			   true, host_writable, &spte);
2683d786c778SPaolo Bonzini 
2684d786c778SPaolo Bonzini 	if (*sptep == spte) {
2685d786c778SPaolo Bonzini 		ret = RET_PF_SPURIOUS;
2686d786c778SPaolo Bonzini 	} else {
2687d786c778SPaolo Bonzini 		flush |= mmu_spte_update(sptep, spte);
26885959ff4aSMaxim Levitsky 		trace_kvm_mmu_set_spte(level, gfn, sptep);
2689c50d8ae3SPaolo Bonzini 	}
2690c50d8ae3SPaolo Bonzini 
2691ad67e480SPaolo Bonzini 	if (wrprot) {
2692c50d8ae3SPaolo Bonzini 		if (write_fault)
2693c50d8ae3SPaolo Bonzini 			ret = RET_PF_EMULATE;
2694c50d8ae3SPaolo Bonzini 	}
2695c50d8ae3SPaolo Bonzini 
2696d786c778SPaolo Bonzini 	if (flush)
2697c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
2698c50d8ae3SPaolo Bonzini 				KVM_PAGES_PER_HPAGE(level));
2699c50d8ae3SPaolo Bonzini 
2700c50d8ae3SPaolo Bonzini 	pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2701c50d8ae3SPaolo Bonzini 
2702c50d8ae3SPaolo Bonzini 	if (!was_rmapped) {
2703d786c778SPaolo Bonzini 		WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
270471f51d2cSMingwei Zhang 		kvm_update_page_stats(vcpu->kvm, level, 1);
27058a9f566aSDavid Matlack 		rmap_add(vcpu, slot, sptep, gfn);
2706c50d8ae3SPaolo Bonzini 	}
2707c50d8ae3SPaolo Bonzini 
2708c50d8ae3SPaolo Bonzini 	return ret;
2709c50d8ae3SPaolo Bonzini }
2710c50d8ae3SPaolo Bonzini 
2711c50d8ae3SPaolo Bonzini static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2712c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp,
2713c50d8ae3SPaolo Bonzini 				    u64 *start, u64 *end)
2714c50d8ae3SPaolo Bonzini {
2715c50d8ae3SPaolo Bonzini 	struct page *pages[PTE_PREFETCH_NUM];
2716c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
27170a2b64c5SBen Gardon 	unsigned int access = sp->role.access;
2718c50d8ae3SPaolo Bonzini 	int i, ret;
2719c50d8ae3SPaolo Bonzini 	gfn_t gfn;
2720c50d8ae3SPaolo Bonzini 
2721c50d8ae3SPaolo Bonzini 	gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
2722c50d8ae3SPaolo Bonzini 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2723c50d8ae3SPaolo Bonzini 	if (!slot)
2724c50d8ae3SPaolo Bonzini 		return -1;
2725c50d8ae3SPaolo Bonzini 
2726c50d8ae3SPaolo Bonzini 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2727c50d8ae3SPaolo Bonzini 	if (ret <= 0)
2728c50d8ae3SPaolo Bonzini 		return -1;
2729c50d8ae3SPaolo Bonzini 
2730c50d8ae3SPaolo Bonzini 	for (i = 0; i < ret; i++, gfn++, start++) {
27318a9f566aSDavid Matlack 		mmu_set_spte(vcpu, slot, start, access, gfn,
2732a12f4381SPaolo Bonzini 			     page_to_pfn(pages[i]), NULL);
2733c50d8ae3SPaolo Bonzini 		put_page(pages[i]);
2734c50d8ae3SPaolo Bonzini 	}
2735c50d8ae3SPaolo Bonzini 
2736c50d8ae3SPaolo Bonzini 	return 0;
2737c50d8ae3SPaolo Bonzini }
2738c50d8ae3SPaolo Bonzini 
2739c50d8ae3SPaolo Bonzini static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2740c50d8ae3SPaolo Bonzini 				  struct kvm_mmu_page *sp, u64 *sptep)
2741c50d8ae3SPaolo Bonzini {
2742c50d8ae3SPaolo Bonzini 	u64 *spte, *start = NULL;
2743c50d8ae3SPaolo Bonzini 	int i;
2744c50d8ae3SPaolo Bonzini 
2745c50d8ae3SPaolo Bonzini 	WARN_ON(!sp->role.direct);
2746c50d8ae3SPaolo Bonzini 
2747c50d8ae3SPaolo Bonzini 	i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
2748c50d8ae3SPaolo Bonzini 	spte = sp->spt + i;
2749c50d8ae3SPaolo Bonzini 
2750c50d8ae3SPaolo Bonzini 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
2751c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*spte) || spte == sptep) {
2752c50d8ae3SPaolo Bonzini 			if (!start)
2753c50d8ae3SPaolo Bonzini 				continue;
2754c50d8ae3SPaolo Bonzini 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2755c6cecc4bSSean Christopherson 				return;
2756c50d8ae3SPaolo Bonzini 			start = NULL;
2757c50d8ae3SPaolo Bonzini 		} else if (!start)
2758c50d8ae3SPaolo Bonzini 			start = spte;
2759c50d8ae3SPaolo Bonzini 	}
2760c6cecc4bSSean Christopherson 	if (start)
2761c6cecc4bSSean Christopherson 		direct_pte_prefetch_many(vcpu, sp, start, spte);
2762c50d8ae3SPaolo Bonzini }
2763c50d8ae3SPaolo Bonzini 
2764c50d8ae3SPaolo Bonzini static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2765c50d8ae3SPaolo Bonzini {
2766c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2767c50d8ae3SPaolo Bonzini 
276857354682SSean Christopherson 	sp = sptep_to_sp(sptep);
2769c50d8ae3SPaolo Bonzini 
2770c50d8ae3SPaolo Bonzini 	/*
2771c50d8ae3SPaolo Bonzini 	 * Without accessed bits, there's no way to distinguish between
2772c50d8ae3SPaolo Bonzini 	 * actually accessed translations and prefetched, so disable pte
2773c50d8ae3SPaolo Bonzini 	 * prefetch if accessed bits aren't available.
2774c50d8ae3SPaolo Bonzini 	 */
2775c50d8ae3SPaolo Bonzini 	if (sp_ad_disabled(sp))
2776c50d8ae3SPaolo Bonzini 		return;
2777c50d8ae3SPaolo Bonzini 
27783bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
2779c50d8ae3SPaolo Bonzini 		return;
2780c50d8ae3SPaolo Bonzini 
27814a42d848SDavid Stevens 	/*
27824a42d848SDavid Stevens 	 * If addresses are being invalidated, skip prefetching to avoid
27834a42d848SDavid Stevens 	 * accidentally prefetching those addresses.
27844a42d848SDavid Stevens 	 */
27854a42d848SDavid Stevens 	if (unlikely(vcpu->kvm->mmu_notifier_count))
27864a42d848SDavid Stevens 		return;
27874a42d848SDavid Stevens 
2788c50d8ae3SPaolo Bonzini 	__direct_pte_prefetch(vcpu, sp, sptep);
2789c50d8ae3SPaolo Bonzini }
2790c50d8ae3SPaolo Bonzini 
27911b6d9d9eSSean Christopherson static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
27928ca6f063SBen Gardon 				  const struct kvm_memory_slot *slot)
2793db543216SSean Christopherson {
2794db543216SSean Christopherson 	unsigned long hva;
279544187235SMingwei Zhang 	unsigned long flags;
279644187235SMingwei Zhang 	int level = PG_LEVEL_4K;
279744187235SMingwei Zhang 	pgd_t pgd;
279844187235SMingwei Zhang 	p4d_t p4d;
279944187235SMingwei Zhang 	pud_t pud;
280044187235SMingwei Zhang 	pmd_t pmd;
2801db543216SSean Christopherson 
2802e851265aSSean Christopherson 	if (!PageCompound(pfn_to_page(pfn)) && !kvm_is_zone_device_pfn(pfn))
28033bae0459SSean Christopherson 		return PG_LEVEL_4K;
2804db543216SSean Christopherson 
2805293e306eSSean Christopherson 	/*
2806293e306eSSean Christopherson 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
2807293e306eSSean Christopherson 	 * is not solely for performance, it's also necessary to avoid the
2808293e306eSSean Christopherson 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
2809293e306eSSean Christopherson 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
2810293e306eSSean Christopherson 	 * page fault steps have already verified the guest isn't writing a
2811293e306eSSean Christopherson 	 * read-only memslot.
2812293e306eSSean Christopherson 	 */
2813db543216SSean Christopherson 	hva = __gfn_to_hva_memslot(slot, gfn);
2814db543216SSean Christopherson 
281544187235SMingwei Zhang 	/*
281644187235SMingwei Zhang 	 * Lookup the mapping level in the current mm.  The information
281744187235SMingwei Zhang 	 * may become stale soon, but it is safe to use as long as
281844187235SMingwei Zhang 	 * 1) mmu_notifier_retry was checked after taking mmu_lock, and
281944187235SMingwei Zhang 	 * 2) mmu_lock is taken now.
282044187235SMingwei Zhang 	 *
282144187235SMingwei Zhang 	 * We still need to disable IRQs to prevent concurrent tear down
282244187235SMingwei Zhang 	 * of page tables.
282344187235SMingwei Zhang 	 */
282444187235SMingwei Zhang 	local_irq_save(flags);
2825db543216SSean Christopherson 
282644187235SMingwei Zhang 	pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
282744187235SMingwei Zhang 	if (pgd_none(pgd))
282844187235SMingwei Zhang 		goto out;
282944187235SMingwei Zhang 
283044187235SMingwei Zhang 	p4d = READ_ONCE(*p4d_offset(&pgd, hva));
283144187235SMingwei Zhang 	if (p4d_none(p4d) || !p4d_present(p4d))
283244187235SMingwei Zhang 		goto out;
283344187235SMingwei Zhang 
283444187235SMingwei Zhang 	pud = READ_ONCE(*pud_offset(&p4d, hva));
283544187235SMingwei Zhang 	if (pud_none(pud) || !pud_present(pud))
283644187235SMingwei Zhang 		goto out;
283744187235SMingwei Zhang 
283844187235SMingwei Zhang 	if (pud_large(pud)) {
283944187235SMingwei Zhang 		level = PG_LEVEL_1G;
284044187235SMingwei Zhang 		goto out;
284144187235SMingwei Zhang 	}
284244187235SMingwei Zhang 
284344187235SMingwei Zhang 	pmd = READ_ONCE(*pmd_offset(&pud, hva));
284444187235SMingwei Zhang 	if (pmd_none(pmd) || !pmd_present(pmd))
284544187235SMingwei Zhang 		goto out;
284644187235SMingwei Zhang 
284744187235SMingwei Zhang 	if (pmd_large(pmd))
284844187235SMingwei Zhang 		level = PG_LEVEL_2M;
284944187235SMingwei Zhang 
285044187235SMingwei Zhang out:
285144187235SMingwei Zhang 	local_irq_restore(flags);
2852db543216SSean Christopherson 	return level;
2853db543216SSean Christopherson }
2854db543216SSean Christopherson 
28558ca6f063SBen Gardon int kvm_mmu_max_mapping_level(struct kvm *kvm,
28568ca6f063SBen Gardon 			      const struct kvm_memory_slot *slot, gfn_t gfn,
28578ca6f063SBen Gardon 			      kvm_pfn_t pfn, int max_level)
28581b6d9d9eSSean Christopherson {
28591b6d9d9eSSean Christopherson 	struct kvm_lpage_info *linfo;
2860ec607a56SPaolo Bonzini 	int host_level;
28611b6d9d9eSSean Christopherson 
28621b6d9d9eSSean Christopherson 	max_level = min(max_level, max_huge_page_level);
28631b6d9d9eSSean Christopherson 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
28641b6d9d9eSSean Christopherson 		linfo = lpage_info_slot(gfn, slot, max_level);
28651b6d9d9eSSean Christopherson 		if (!linfo->disallow_lpage)
28661b6d9d9eSSean Christopherson 			break;
28671b6d9d9eSSean Christopherson 	}
28681b6d9d9eSSean Christopherson 
28691b6d9d9eSSean Christopherson 	if (max_level == PG_LEVEL_4K)
28701b6d9d9eSSean Christopherson 		return PG_LEVEL_4K;
28711b6d9d9eSSean Christopherson 
2872ec607a56SPaolo Bonzini 	host_level = host_pfn_mapping_level(kvm, gfn, pfn, slot);
2873ec607a56SPaolo Bonzini 	return min(host_level, max_level);
28741b6d9d9eSSean Christopherson }
28751b6d9d9eSSean Christopherson 
287673a3c659SPaolo Bonzini void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
28770885904dSSean Christopherson {
2878e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
287917eff019SSean Christopherson 	kvm_pfn_t mask;
28800885904dSSean Christopherson 
288173a3c659SPaolo Bonzini 	fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
28823cf06612SSean Christopherson 
288373a3c659SPaolo Bonzini 	if (unlikely(fault->max_level == PG_LEVEL_4K))
288473a3c659SPaolo Bonzini 		return;
288517eff019SSean Christopherson 
288673a3c659SPaolo Bonzini 	if (is_error_noslot_pfn(fault->pfn) || kvm_is_reserved_pfn(fault->pfn))
288773a3c659SPaolo Bonzini 		return;
288817eff019SSean Christopherson 
2889e710c5f6SDavid Matlack 	if (kvm_slot_dirty_track_enabled(slot))
289073a3c659SPaolo Bonzini 		return;
2891293e306eSSean Christopherson 
28923cf06612SSean Christopherson 	/*
28933cf06612SSean Christopherson 	 * Enforce the iTLB multihit workaround after capturing the requested
28943cf06612SSean Christopherson 	 * level, which will be used to do precise, accurate accounting.
28953cf06612SSean Christopherson 	 */
289673a3c659SPaolo Bonzini 	fault->req_level = kvm_mmu_max_mapping_level(vcpu->kvm, slot,
289773a3c659SPaolo Bonzini 						     fault->gfn, fault->pfn,
289873a3c659SPaolo Bonzini 						     fault->max_level);
289973a3c659SPaolo Bonzini 	if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
290073a3c659SPaolo Bonzini 		return;
29014cd071d1SSean Christopherson 
29020885904dSSean Christopherson 	/*
29034cd071d1SSean Christopherson 	 * mmu_notifier_retry() was successful and mmu_lock is held, so
29044cd071d1SSean Christopherson 	 * the pmd can't be split from under us.
29050885904dSSean Christopherson 	 */
290673a3c659SPaolo Bonzini 	fault->goal_level = fault->req_level;
290773a3c659SPaolo Bonzini 	mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
290873a3c659SPaolo Bonzini 	VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
290973a3c659SPaolo Bonzini 	fault->pfn &= ~mask;
29100885904dSSean Christopherson }
29110885904dSSean Christopherson 
2912536f0e6aSPaolo Bonzini void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
2913c50d8ae3SPaolo Bonzini {
2914536f0e6aSPaolo Bonzini 	if (cur_level > PG_LEVEL_4K &&
2915536f0e6aSPaolo Bonzini 	    cur_level == fault->goal_level &&
2916c50d8ae3SPaolo Bonzini 	    is_shadow_present_pte(spte) &&
2917c50d8ae3SPaolo Bonzini 	    !is_large_pte(spte)) {
2918c50d8ae3SPaolo Bonzini 		/*
2919c50d8ae3SPaolo Bonzini 		 * A small SPTE exists for this pfn, but FNAME(fetch)
2920c50d8ae3SPaolo Bonzini 		 * and __direct_map would like to create a large PTE
2921c50d8ae3SPaolo Bonzini 		 * instead: just force them to go down another level,
2922c50d8ae3SPaolo Bonzini 		 * patching back for them into pfn the next 9 bits of
2923c50d8ae3SPaolo Bonzini 		 * the address.
2924c50d8ae3SPaolo Bonzini 		 */
2925536f0e6aSPaolo Bonzini 		u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
2926536f0e6aSPaolo Bonzini 				KVM_PAGES_PER_HPAGE(cur_level - 1);
2927536f0e6aSPaolo Bonzini 		fault->pfn |= fault->gfn & page_mask;
2928536f0e6aSPaolo Bonzini 		fault->goal_level--;
2929c50d8ae3SPaolo Bonzini 	}
2930c50d8ae3SPaolo Bonzini }
2931c50d8ae3SPaolo Bonzini 
293243b74355SPaolo Bonzini static int __direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
2933c50d8ae3SPaolo Bonzini {
2934c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator it;
2935c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
293673a3c659SPaolo Bonzini 	int ret;
293743b74355SPaolo Bonzini 	gfn_t base_gfn = fault->gfn;
2938c50d8ae3SPaolo Bonzini 
293973a3c659SPaolo Bonzini 	kvm_mmu_hugepage_adjust(vcpu, fault);
29404cd071d1SSean Christopherson 
2941f0066d94SPaolo Bonzini 	trace_kvm_mmu_spte_requested(fault);
294243b74355SPaolo Bonzini 	for_each_shadow_entry(vcpu, fault->addr, it) {
2943c50d8ae3SPaolo Bonzini 		/*
2944c50d8ae3SPaolo Bonzini 		 * We cannot overwrite existing page tables with an NX
2945c50d8ae3SPaolo Bonzini 		 * large page, as the leaf could be executable.
2946c50d8ae3SPaolo Bonzini 		 */
294773a3c659SPaolo Bonzini 		if (fault->nx_huge_page_workaround_enabled)
2948536f0e6aSPaolo Bonzini 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
2949c50d8ae3SPaolo Bonzini 
295043b74355SPaolo Bonzini 		base_gfn = fault->gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
295173a3c659SPaolo Bonzini 		if (it.level == fault->goal_level)
2952c50d8ae3SPaolo Bonzini 			break;
2953c50d8ae3SPaolo Bonzini 
2954c50d8ae3SPaolo Bonzini 		drop_large_spte(vcpu, it.sptep);
295503fffc54SSean Christopherson 		if (is_shadow_present_pte(*it.sptep))
295603fffc54SSean Christopherson 			continue;
295703fffc54SSean Christopherson 
2958c50d8ae3SPaolo Bonzini 		sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
2959c50d8ae3SPaolo Bonzini 				      it.level - 1, true, ACC_ALL);
2960c50d8ae3SPaolo Bonzini 
2961c50d8ae3SPaolo Bonzini 		link_shadow_page(vcpu, it.sptep, sp);
296273a3c659SPaolo Bonzini 		if (fault->is_tdp && fault->huge_page_disallowed &&
296373a3c659SPaolo Bonzini 		    fault->req_level >= it.level)
2964c50d8ae3SPaolo Bonzini 			account_huge_nx_page(vcpu->kvm, sp);
2965c50d8ae3SPaolo Bonzini 	}
2966c50d8ae3SPaolo Bonzini 
2967b1a429fbSSean Christopherson 	if (WARN_ON_ONCE(it.level != fault->goal_level))
2968b1a429fbSSean Christopherson 		return -EFAULT;
2969b1a429fbSSean Christopherson 
29708a9f566aSDavid Matlack 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
2971a12f4381SPaolo Bonzini 			   base_gfn, fault->pfn, fault);
297212703759SSean Christopherson 	if (ret == RET_PF_SPURIOUS)
297312703759SSean Christopherson 		return ret;
297412703759SSean Christopherson 
2975c50d8ae3SPaolo Bonzini 	direct_pte_prefetch(vcpu, it.sptep);
2976c50d8ae3SPaolo Bonzini 	++vcpu->stat.pf_fixed;
2977c50d8ae3SPaolo Bonzini 	return ret;
2978c50d8ae3SPaolo Bonzini }
2979c50d8ae3SPaolo Bonzini 
2980c50d8ae3SPaolo Bonzini static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
2981c50d8ae3SPaolo Bonzini {
2982c50d8ae3SPaolo Bonzini 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
2983c50d8ae3SPaolo Bonzini }
2984c50d8ae3SPaolo Bonzini 
2985c50d8ae3SPaolo Bonzini static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
2986c50d8ae3SPaolo Bonzini {
2987c50d8ae3SPaolo Bonzini 	/*
2988c50d8ae3SPaolo Bonzini 	 * Do not cache the mmio info caused by writing the readonly gfn
2989c50d8ae3SPaolo Bonzini 	 * into the spte otherwise read access on readonly gfn also can
2990c50d8ae3SPaolo Bonzini 	 * caused mmio page fault and treat it as mmio access.
2991c50d8ae3SPaolo Bonzini 	 */
2992c50d8ae3SPaolo Bonzini 	if (pfn == KVM_PFN_ERR_RO_FAULT)
2993c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
2994c50d8ae3SPaolo Bonzini 
2995c50d8ae3SPaolo Bonzini 	if (pfn == KVM_PFN_ERR_HWPOISON) {
2996c50d8ae3SPaolo Bonzini 		kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
2997c50d8ae3SPaolo Bonzini 		return RET_PF_RETRY;
2998c50d8ae3SPaolo Bonzini 	}
2999c50d8ae3SPaolo Bonzini 
3000c50d8ae3SPaolo Bonzini 	return -EFAULT;
3001c50d8ae3SPaolo Bonzini }
3002c50d8ae3SPaolo Bonzini 
30033a13f4feSPaolo Bonzini static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
30043a13f4feSPaolo Bonzini 				unsigned int access, int *ret_val)
3005c50d8ae3SPaolo Bonzini {
3006c50d8ae3SPaolo Bonzini 	/* The pfn is invalid, report the error! */
30073a13f4feSPaolo Bonzini 	if (unlikely(is_error_pfn(fault->pfn))) {
30083a13f4feSPaolo Bonzini 		*ret_val = kvm_handle_bad_page(vcpu, fault->gfn, fault->pfn);
3009c50d8ae3SPaolo Bonzini 		return true;
3010c50d8ae3SPaolo Bonzini 	}
3011c50d8ae3SPaolo Bonzini 
3012e710c5f6SDavid Matlack 	if (unlikely(!fault->slot)) {
30133a13f4feSPaolo Bonzini 		gva_t gva = fault->is_tdp ? 0 : fault->addr;
30143a13f4feSPaolo Bonzini 
30153a13f4feSPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3016c50d8ae3SPaolo Bonzini 				     access & shadow_mmio_access_mask);
301730ab5901SSean Christopherson 		/*
301830ab5901SSean Christopherson 		 * If MMIO caching is disabled, emulate immediately without
301930ab5901SSean Christopherson 		 * touching the shadow page tables as attempting to install an
302086931ff7SSean Christopherson 		 * MMIO SPTE will just be an expensive nop.  Do not cache MMIO
302186931ff7SSean Christopherson 		 * whose gfn is greater than host.MAXPHYADDR, any guest that
302286931ff7SSean Christopherson 		 * generates such gfns is running nested and is being tricked
302386931ff7SSean Christopherson 		 * by L0 userspace (you can observe gfn > L1.MAXPHYADDR if
302486931ff7SSean Christopherson 		 * and only if L1's MAXPHYADDR is inaccurate with respect to
302586931ff7SSean Christopherson 		 * the hardware's).
302630ab5901SSean Christopherson 		 */
30278b9e74bfSSean Christopherson 		if (unlikely(!enable_mmio_caching) ||
302886931ff7SSean Christopherson 		    unlikely(fault->gfn > kvm_mmu_max_gfn())) {
302930ab5901SSean Christopherson 			*ret_val = RET_PF_EMULATE;
303030ab5901SSean Christopherson 			return true;
303130ab5901SSean Christopherson 		}
303230ab5901SSean Christopherson 	}
3033c50d8ae3SPaolo Bonzini 
3034c50d8ae3SPaolo Bonzini 	return false;
3035c50d8ae3SPaolo Bonzini }
3036c50d8ae3SPaolo Bonzini 
30373c8ad5a6SPaolo Bonzini static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
3038c50d8ae3SPaolo Bonzini {
3039c50d8ae3SPaolo Bonzini 	/*
3040c50d8ae3SPaolo Bonzini 	 * Do not fix the mmio spte with invalid generation number which
3041c50d8ae3SPaolo Bonzini 	 * need to be updated by slow page fault path.
3042c50d8ae3SPaolo Bonzini 	 */
30433c8ad5a6SPaolo Bonzini 	if (fault->rsvd)
3044c50d8ae3SPaolo Bonzini 		return false;
3045c50d8ae3SPaolo Bonzini 
3046c50d8ae3SPaolo Bonzini 	/* See if the page fault is due to an NX violation */
30473c8ad5a6SPaolo Bonzini 	if (unlikely(fault->exec && fault->present))
3048c50d8ae3SPaolo Bonzini 		return false;
3049c50d8ae3SPaolo Bonzini 
3050c50d8ae3SPaolo Bonzini 	/*
3051c50d8ae3SPaolo Bonzini 	 * #PF can be fast if:
3052c50d8ae3SPaolo Bonzini 	 * 1. The shadow page table entry is not present, which could mean that
3053c50d8ae3SPaolo Bonzini 	 *    the fault is potentially caused by access tracking (if enabled).
3054c50d8ae3SPaolo Bonzini 	 * 2. The shadow page table entry is present and the fault
3055c50d8ae3SPaolo Bonzini 	 *    is caused by write-protect, that means we just need change the W
3056c50d8ae3SPaolo Bonzini 	 *    bit of the spte which can be done out of mmu-lock.
3057c50d8ae3SPaolo Bonzini 	 *
3058c50d8ae3SPaolo Bonzini 	 * However, if access tracking is disabled we know that a non-present
3059c50d8ae3SPaolo Bonzini 	 * page must be a genuine page fault where we have to create a new SPTE.
3060c50d8ae3SPaolo Bonzini 	 * So, if access tracking is disabled, we return true only for write
3061c50d8ae3SPaolo Bonzini 	 * accesses to a present page.
3062c50d8ae3SPaolo Bonzini 	 */
3063c50d8ae3SPaolo Bonzini 
30643c8ad5a6SPaolo Bonzini 	return shadow_acc_track_mask != 0 || (fault->write && fault->present);
3065c50d8ae3SPaolo Bonzini }
3066c50d8ae3SPaolo Bonzini 
3067c50d8ae3SPaolo Bonzini /*
3068c50d8ae3SPaolo Bonzini  * Returns true if the SPTE was fixed successfully. Otherwise,
3069c50d8ae3SPaolo Bonzini  * someone else modified the SPTE from its original value.
3070c50d8ae3SPaolo Bonzini  */
3071c50d8ae3SPaolo Bonzini static bool
3072e710c5f6SDavid Matlack fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
3073c50d8ae3SPaolo Bonzini 			u64 *sptep, u64 old_spte, u64 new_spte)
3074c50d8ae3SPaolo Bonzini {
3075c50d8ae3SPaolo Bonzini 	/*
3076c50d8ae3SPaolo Bonzini 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3077c50d8ae3SPaolo Bonzini 	 * order to eliminate unnecessary PML logging. See comments in
3078c50d8ae3SPaolo Bonzini 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3079c50d8ae3SPaolo Bonzini 	 * enabled, so we do not do this. This might result in the same GPA
3080c50d8ae3SPaolo Bonzini 	 * to be logged in PML buffer again when the write really happens, and
3081c50d8ae3SPaolo Bonzini 	 * eventually to be called by mark_page_dirty twice. But it's also no
3082c50d8ae3SPaolo Bonzini 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3083c50d8ae3SPaolo Bonzini 	 * so non-PML cases won't be impacted.
3084c50d8ae3SPaolo Bonzini 	 *
3085c50d8ae3SPaolo Bonzini 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3086c50d8ae3SPaolo Bonzini 	 */
3087c50d8ae3SPaolo Bonzini 	if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3088c50d8ae3SPaolo Bonzini 		return false;
3089c50d8ae3SPaolo Bonzini 
3090e710c5f6SDavid Matlack 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3091e710c5f6SDavid Matlack 		mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3092c50d8ae3SPaolo Bonzini 
3093c50d8ae3SPaolo Bonzini 	return true;
3094c50d8ae3SPaolo Bonzini }
3095c50d8ae3SPaolo Bonzini 
30963c8ad5a6SPaolo Bonzini static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3097c50d8ae3SPaolo Bonzini {
30983c8ad5a6SPaolo Bonzini 	if (fault->exec)
3099c50d8ae3SPaolo Bonzini 		return is_executable_pte(spte);
3100c50d8ae3SPaolo Bonzini 
31013c8ad5a6SPaolo Bonzini 	if (fault->write)
3102c50d8ae3SPaolo Bonzini 		return is_writable_pte(spte);
3103c50d8ae3SPaolo Bonzini 
3104c50d8ae3SPaolo Bonzini 	/* Fault was on Read access */
3105c50d8ae3SPaolo Bonzini 	return spte & PT_PRESENT_MASK;
3106c50d8ae3SPaolo Bonzini }
3107c50d8ae3SPaolo Bonzini 
3108c50d8ae3SPaolo Bonzini /*
31096e8eb206SDavid Matlack  * Returns the last level spte pointer of the shadow page walk for the given
31106e8eb206SDavid Matlack  * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
31116e8eb206SDavid Matlack  * walk could be performed, returns NULL and *spte does not contain valid data.
31126e8eb206SDavid Matlack  *
31136e8eb206SDavid Matlack  * Contract:
31146e8eb206SDavid Matlack  *  - Must be called between walk_shadow_page_lockless_{begin,end}.
31156e8eb206SDavid Matlack  *  - The returned sptep must not be used after walk_shadow_page_lockless_end.
31166e8eb206SDavid Matlack  */
31176e8eb206SDavid Matlack static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
31186e8eb206SDavid Matlack {
31196e8eb206SDavid Matlack 	struct kvm_shadow_walk_iterator iterator;
31206e8eb206SDavid Matlack 	u64 old_spte;
31216e8eb206SDavid Matlack 	u64 *sptep = NULL;
31226e8eb206SDavid Matlack 
31236e8eb206SDavid Matlack 	for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
31246e8eb206SDavid Matlack 		sptep = iterator.sptep;
31256e8eb206SDavid Matlack 		*spte = old_spte;
31266e8eb206SDavid Matlack 	}
31276e8eb206SDavid Matlack 
31286e8eb206SDavid Matlack 	return sptep;
31296e8eb206SDavid Matlack }
31306e8eb206SDavid Matlack 
31316e8eb206SDavid Matlack /*
3132c4371c2aSSean Christopherson  * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3133c50d8ae3SPaolo Bonzini  */
31343c8ad5a6SPaolo Bonzini static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3135c50d8ae3SPaolo Bonzini {
3136c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3137c4371c2aSSean Christopherson 	int ret = RET_PF_INVALID;
3138c50d8ae3SPaolo Bonzini 	u64 spte = 0ull;
31396e8eb206SDavid Matlack 	u64 *sptep = NULL;
3140c50d8ae3SPaolo Bonzini 	uint retry_count = 0;
3141c50d8ae3SPaolo Bonzini 
31423c8ad5a6SPaolo Bonzini 	if (!page_fault_can_be_fast(fault))
3143c4371c2aSSean Christopherson 		return ret;
3144c50d8ae3SPaolo Bonzini 
3145c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
3146c50d8ae3SPaolo Bonzini 
3147c50d8ae3SPaolo Bonzini 	do {
3148c50d8ae3SPaolo Bonzini 		u64 new_spte;
3149c50d8ae3SPaolo Bonzini 
31506e8eb206SDavid Matlack 		if (is_tdp_mmu(vcpu->arch.mmu))
31513c8ad5a6SPaolo Bonzini 			sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
31526e8eb206SDavid Matlack 		else
31533c8ad5a6SPaolo Bonzini 			sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3154c50d8ae3SPaolo Bonzini 
3155ec89e643SSean Christopherson 		if (!is_shadow_present_pte(spte))
3156ec89e643SSean Christopherson 			break;
3157ec89e643SSean Christopherson 
31586e8eb206SDavid Matlack 		sp = sptep_to_sp(sptep);
3159c50d8ae3SPaolo Bonzini 		if (!is_last_spte(spte, sp->role.level))
3160c50d8ae3SPaolo Bonzini 			break;
3161c50d8ae3SPaolo Bonzini 
3162c50d8ae3SPaolo Bonzini 		/*
3163c50d8ae3SPaolo Bonzini 		 * Check whether the memory access that caused the fault would
3164c50d8ae3SPaolo Bonzini 		 * still cause it if it were to be performed right now. If not,
3165c50d8ae3SPaolo Bonzini 		 * then this is a spurious fault caused by TLB lazily flushed,
3166c50d8ae3SPaolo Bonzini 		 * or some other CPU has already fixed the PTE after the
3167c50d8ae3SPaolo Bonzini 		 * current CPU took the fault.
3168c50d8ae3SPaolo Bonzini 		 *
3169c50d8ae3SPaolo Bonzini 		 * Need not check the access of upper level table entries since
3170c50d8ae3SPaolo Bonzini 		 * they are always ACC_ALL.
3171c50d8ae3SPaolo Bonzini 		 */
31723c8ad5a6SPaolo Bonzini 		if (is_access_allowed(fault, spte)) {
3173c4371c2aSSean Christopherson 			ret = RET_PF_SPURIOUS;
3174c50d8ae3SPaolo Bonzini 			break;
3175c50d8ae3SPaolo Bonzini 		}
3176c50d8ae3SPaolo Bonzini 
3177c50d8ae3SPaolo Bonzini 		new_spte = spte;
3178c50d8ae3SPaolo Bonzini 
3179c50d8ae3SPaolo Bonzini 		if (is_access_track_spte(spte))
3180c50d8ae3SPaolo Bonzini 			new_spte = restore_acc_track_spte(new_spte);
3181c50d8ae3SPaolo Bonzini 
3182c50d8ae3SPaolo Bonzini 		/*
3183c50d8ae3SPaolo Bonzini 		 * Currently, to simplify the code, write-protection can
3184c50d8ae3SPaolo Bonzini 		 * be removed in the fast path only if the SPTE was
3185c50d8ae3SPaolo Bonzini 		 * write-protected for dirty-logging or access tracking.
3186c50d8ae3SPaolo Bonzini 		 */
31873c8ad5a6SPaolo Bonzini 		if (fault->write &&
3188e6302698SMiaohe Lin 		    spte_can_locklessly_be_made_writable(spte)) {
3189c50d8ae3SPaolo Bonzini 			new_spte |= PT_WRITABLE_MASK;
3190c50d8ae3SPaolo Bonzini 
3191c50d8ae3SPaolo Bonzini 			/*
319210c30de0SJunaid Shahid 			 * Do not fix write-permission on the large spte when
319310c30de0SJunaid Shahid 			 * dirty logging is enabled. Since we only dirty the
319410c30de0SJunaid Shahid 			 * first page into the dirty-bitmap in
3195c50d8ae3SPaolo Bonzini 			 * fast_pf_fix_direct_spte(), other pages are missed
3196c50d8ae3SPaolo Bonzini 			 * if its slot has dirty logging enabled.
3197c50d8ae3SPaolo Bonzini 			 *
3198c50d8ae3SPaolo Bonzini 			 * Instead, we let the slow page fault path create a
3199c50d8ae3SPaolo Bonzini 			 * normal spte to fix the access.
3200c50d8ae3SPaolo Bonzini 			 */
320110c30de0SJunaid Shahid 			if (sp->role.level > PG_LEVEL_4K &&
320210c30de0SJunaid Shahid 			    kvm_slot_dirty_track_enabled(fault->slot))
3203c50d8ae3SPaolo Bonzini 				break;
3204c50d8ae3SPaolo Bonzini 		}
3205c50d8ae3SPaolo Bonzini 
3206c50d8ae3SPaolo Bonzini 		/* Verify that the fault can be handled in the fast path */
3207c50d8ae3SPaolo Bonzini 		if (new_spte == spte ||
32083c8ad5a6SPaolo Bonzini 		    !is_access_allowed(fault, new_spte))
3209c50d8ae3SPaolo Bonzini 			break;
3210c50d8ae3SPaolo Bonzini 
3211c50d8ae3SPaolo Bonzini 		/*
3212c50d8ae3SPaolo Bonzini 		 * Currently, fast page fault only works for direct mapping
3213c50d8ae3SPaolo Bonzini 		 * since the gfn is not stable for indirect shadow page. See
32143ecad8c2SMauro Carvalho Chehab 		 * Documentation/virt/kvm/locking.rst to get more detail.
3215c50d8ae3SPaolo Bonzini 		 */
3216e710c5f6SDavid Matlack 		if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3217c4371c2aSSean Christopherson 			ret = RET_PF_FIXED;
3218c50d8ae3SPaolo Bonzini 			break;
3219c4371c2aSSean Christopherson 		}
3220c50d8ae3SPaolo Bonzini 
3221c50d8ae3SPaolo Bonzini 		if (++retry_count > 4) {
3222c50d8ae3SPaolo Bonzini 			printk_once(KERN_WARNING
3223c50d8ae3SPaolo Bonzini 				"kvm: Fast #PF retrying more than 4 times.\n");
3224c50d8ae3SPaolo Bonzini 			break;
3225c50d8ae3SPaolo Bonzini 		}
3226c50d8ae3SPaolo Bonzini 
3227c50d8ae3SPaolo Bonzini 	} while (true);
3228c50d8ae3SPaolo Bonzini 
3229f0066d94SPaolo Bonzini 	trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3230c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3231c50d8ae3SPaolo Bonzini 
3232c4371c2aSSean Christopherson 	return ret;
3233c50d8ae3SPaolo Bonzini }
3234c50d8ae3SPaolo Bonzini 
3235c50d8ae3SPaolo Bonzini static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3236c50d8ae3SPaolo Bonzini 			       struct list_head *invalid_list)
3237c50d8ae3SPaolo Bonzini {
3238c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3239c50d8ae3SPaolo Bonzini 
3240c50d8ae3SPaolo Bonzini 	if (!VALID_PAGE(*root_hpa))
3241c50d8ae3SPaolo Bonzini 		return;
3242c50d8ae3SPaolo Bonzini 
3243e47c4aeeSSean Christopherson 	sp = to_shadow_page(*root_hpa & PT64_BASE_ADDR_MASK);
32449191b8f0SPaolo Bonzini 	if (WARN_ON(!sp))
32459191b8f0SPaolo Bonzini 		return;
324602c00b3aSBen Gardon 
3247897218ffSPaolo Bonzini 	if (is_tdp_mmu_page(sp))
32486103bc07SBen Gardon 		kvm_tdp_mmu_put_root(kvm, sp, false);
324976eb54e7SBen Gardon 	else if (!--sp->root_count && sp->role.invalid)
3250c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3251c50d8ae3SPaolo Bonzini 
3252c50d8ae3SPaolo Bonzini 	*root_hpa = INVALID_PAGE;
3253c50d8ae3SPaolo Bonzini }
3254c50d8ae3SPaolo Bonzini 
3255c50d8ae3SPaolo Bonzini /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
32560c1c92f1SPaolo Bonzini void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3257c50d8ae3SPaolo Bonzini 			ulong roots_to_free)
3258c50d8ae3SPaolo Bonzini {
3259c50d8ae3SPaolo Bonzini 	int i;
3260c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
3261594bef79SPaolo Bonzini 	bool free_active_root;
3262c50d8ae3SPaolo Bonzini 
3263c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3264c50d8ae3SPaolo Bonzini 
3265c50d8ae3SPaolo Bonzini 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3266594bef79SPaolo Bonzini 	free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3267594bef79SPaolo Bonzini 		&& VALID_PAGE(mmu->root.hpa);
3268594bef79SPaolo Bonzini 
3269594bef79SPaolo Bonzini 	if (!free_active_root) {
3270c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3271c50d8ae3SPaolo Bonzini 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3272c50d8ae3SPaolo Bonzini 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3273c50d8ae3SPaolo Bonzini 				break;
3274c50d8ae3SPaolo Bonzini 
3275c50d8ae3SPaolo Bonzini 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3276c50d8ae3SPaolo Bonzini 			return;
3277c50d8ae3SPaolo Bonzini 	}
3278c50d8ae3SPaolo Bonzini 
3279531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
3280c50d8ae3SPaolo Bonzini 
3281c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3282c50d8ae3SPaolo Bonzini 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
32834d710de9SSean Christopherson 			mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3284c50d8ae3SPaolo Bonzini 					   &invalid_list);
3285c50d8ae3SPaolo Bonzini 
3286c50d8ae3SPaolo Bonzini 	if (free_active_root) {
3287594bef79SPaolo Bonzini 		if (to_shadow_page(mmu->root.hpa)) {
3288b9e5603cSPaolo Bonzini 			mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
328904d45551SSean Christopherson 		} else if (mmu->pae_root) {
3290c834e5e4SSean Christopherson 			for (i = 0; i < 4; ++i) {
3291c834e5e4SSean Christopherson 				if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3292c834e5e4SSean Christopherson 					continue;
3293c834e5e4SSean Christopherson 
3294c834e5e4SSean Christopherson 				mmu_free_root_page(kvm, &mmu->pae_root[i],
3295c50d8ae3SPaolo Bonzini 						   &invalid_list);
3296c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3297c50d8ae3SPaolo Bonzini 			}
3298c50d8ae3SPaolo Bonzini 		}
3299b9e5603cSPaolo Bonzini 		mmu->root.hpa = INVALID_PAGE;
3300b9e5603cSPaolo Bonzini 		mmu->root.pgd = 0;
3301c50d8ae3SPaolo Bonzini 	}
3302c50d8ae3SPaolo Bonzini 
33034d710de9SSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
3304531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
3305c50d8ae3SPaolo Bonzini }
3306c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3307c50d8ae3SPaolo Bonzini 
33080c1c92f1SPaolo Bonzini void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
330925b62c62SSean Christopherson {
331025b62c62SSean Christopherson 	unsigned long roots_to_free = 0;
331125b62c62SSean Christopherson 	hpa_t root_hpa;
331225b62c62SSean Christopherson 	int i;
331325b62c62SSean Christopherson 
331425b62c62SSean Christopherson 	/*
331525b62c62SSean Christopherson 	 * This should not be called while L2 is active, L2 can't invalidate
331625b62c62SSean Christopherson 	 * _only_ its own roots, e.g. INVVPID unconditionally exits.
331725b62c62SSean Christopherson 	 */
3318*7a458f0eSPaolo Bonzini 	WARN_ON_ONCE(mmu->root_role.guest_mode);
331925b62c62SSean Christopherson 
332025b62c62SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
332125b62c62SSean Christopherson 		root_hpa = mmu->prev_roots[i].hpa;
332225b62c62SSean Christopherson 		if (!VALID_PAGE(root_hpa))
332325b62c62SSean Christopherson 			continue;
332425b62c62SSean Christopherson 
332525b62c62SSean Christopherson 		if (!to_shadow_page(root_hpa) ||
332625b62c62SSean Christopherson 			to_shadow_page(root_hpa)->role.guest_mode)
332725b62c62SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
332825b62c62SSean Christopherson 	}
332925b62c62SSean Christopherson 
33300c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, roots_to_free);
333125b62c62SSean Christopherson }
333225b62c62SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
333325b62c62SSean Christopherson 
333425b62c62SSean Christopherson 
3335c50d8ae3SPaolo Bonzini static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3336c50d8ae3SPaolo Bonzini {
3337c50d8ae3SPaolo Bonzini 	int ret = 0;
3338c50d8ae3SPaolo Bonzini 
3339995decb6SVitaly Kuznetsov 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3340c50d8ae3SPaolo Bonzini 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3341c50d8ae3SPaolo Bonzini 		ret = 1;
3342c50d8ae3SPaolo Bonzini 	}
3343c50d8ae3SPaolo Bonzini 
3344c50d8ae3SPaolo Bonzini 	return ret;
3345c50d8ae3SPaolo Bonzini }
3346c50d8ae3SPaolo Bonzini 
33478123f265SSean Christopherson static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
33488123f265SSean Christopherson 			    u8 level, bool direct)
3349c50d8ae3SPaolo Bonzini {
3350c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
33518123f265SSean Christopherson 
33528123f265SSean Christopherson 	sp = kvm_mmu_get_page(vcpu, gfn, gva, level, direct, ACC_ALL);
33538123f265SSean Christopherson 	++sp->root_count;
33548123f265SSean Christopherson 
33558123f265SSean Christopherson 	return __pa(sp->spt);
33568123f265SSean Christopherson }
33578123f265SSean Christopherson 
33588123f265SSean Christopherson static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
33598123f265SSean Christopherson {
3360b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3361b37233c9SSean Christopherson 	u8 shadow_root_level = mmu->shadow_root_level;
33628123f265SSean Christopherson 	hpa_t root;
3363c50d8ae3SPaolo Bonzini 	unsigned i;
33644a38162eSPaolo Bonzini 	int r;
33654a38162eSPaolo Bonzini 
33664a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
33674a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
33684a38162eSPaolo Bonzini 	if (r < 0)
33694a38162eSPaolo Bonzini 		goto out_unlock;
3370c50d8ae3SPaolo Bonzini 
3371897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(vcpu->kvm)) {
337202c00b3aSBen Gardon 		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
3373b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
337402c00b3aSBen Gardon 	} else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
33756e6ec584SSean Christopherson 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level, true);
3376b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
33778123f265SSean Christopherson 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
33784a38162eSPaolo Bonzini 		if (WARN_ON_ONCE(!mmu->pae_root)) {
33794a38162eSPaolo Bonzini 			r = -EIO;
33804a38162eSPaolo Bonzini 			goto out_unlock;
33814a38162eSPaolo Bonzini 		}
338273ad1606SSean Christopherson 
3383c50d8ae3SPaolo Bonzini 		for (i = 0; i < 4; ++i) {
3384c834e5e4SSean Christopherson 			WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3385c50d8ae3SPaolo Bonzini 
33868123f265SSean Christopherson 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT),
33878123f265SSean Christopherson 					      i << 30, PT32_ROOT_LEVEL, true);
338817e368d9SSean Christopherson 			mmu->pae_root[i] = root | PT_PRESENT_MASK |
338917e368d9SSean Christopherson 					   shadow_me_mask;
3390c50d8ae3SPaolo Bonzini 		}
3391b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
339273ad1606SSean Christopherson 	} else {
339373ad1606SSean Christopherson 		WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
33944a38162eSPaolo Bonzini 		r = -EIO;
33954a38162eSPaolo Bonzini 		goto out_unlock;
339673ad1606SSean Christopherson 	}
33973651c7fcSSean Christopherson 
3398b9e5603cSPaolo Bonzini 	/* root.pgd is ignored for direct MMUs. */
3399b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
34004a38162eSPaolo Bonzini out_unlock:
34014a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
34024a38162eSPaolo Bonzini 	return r;
3403c50d8ae3SPaolo Bonzini }
3404c50d8ae3SPaolo Bonzini 
34051e76a3ceSDavid Stevens static int mmu_first_shadow_root_alloc(struct kvm *kvm)
34061e76a3ceSDavid Stevens {
34071e76a3ceSDavid Stevens 	struct kvm_memslots *slots;
34081e76a3ceSDavid Stevens 	struct kvm_memory_slot *slot;
3409a54d8066SMaciej S. Szmigiero 	int r = 0, i, bkt;
34101e76a3ceSDavid Stevens 
34111e76a3ceSDavid Stevens 	/*
34121e76a3ceSDavid Stevens 	 * Check if this is the first shadow root being allocated before
34131e76a3ceSDavid Stevens 	 * taking the lock.
34141e76a3ceSDavid Stevens 	 */
34151e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
34161e76a3ceSDavid Stevens 		return 0;
34171e76a3ceSDavid Stevens 
34181e76a3ceSDavid Stevens 	mutex_lock(&kvm->slots_arch_lock);
34191e76a3ceSDavid Stevens 
34201e76a3ceSDavid Stevens 	/* Recheck, under the lock, whether this is the first shadow root. */
34211e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
34221e76a3ceSDavid Stevens 		goto out_unlock;
34231e76a3ceSDavid Stevens 
34241e76a3ceSDavid Stevens 	/*
34251e76a3ceSDavid Stevens 	 * Check if anything actually needs to be allocated, e.g. all metadata
34261e76a3ceSDavid Stevens 	 * will be allocated upfront if TDP is disabled.
34271e76a3ceSDavid Stevens 	 */
34281e76a3ceSDavid Stevens 	if (kvm_memslots_have_rmaps(kvm) &&
34291e76a3ceSDavid Stevens 	    kvm_page_track_write_tracking_enabled(kvm))
34301e76a3ceSDavid Stevens 		goto out_success;
34311e76a3ceSDavid Stevens 
34321e76a3ceSDavid Stevens 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
34331e76a3ceSDavid Stevens 		slots = __kvm_memslots(kvm, i);
3434a54d8066SMaciej S. Szmigiero 		kvm_for_each_memslot(slot, bkt, slots) {
34351e76a3ceSDavid Stevens 			/*
34361e76a3ceSDavid Stevens 			 * Both of these functions are no-ops if the target is
34371e76a3ceSDavid Stevens 			 * already allocated, so unconditionally calling both
34381e76a3ceSDavid Stevens 			 * is safe.  Intentionally do NOT free allocations on
34391e76a3ceSDavid Stevens 			 * failure to avoid having to track which allocations
34401e76a3ceSDavid Stevens 			 * were made now versus when the memslot was created.
34411e76a3ceSDavid Stevens 			 * The metadata is guaranteed to be freed when the slot
34421e76a3ceSDavid Stevens 			 * is freed, and will be kept/used if userspace retries
34431e76a3ceSDavid Stevens 			 * KVM_RUN instead of killing the VM.
34441e76a3ceSDavid Stevens 			 */
34451e76a3ceSDavid Stevens 			r = memslot_rmap_alloc(slot, slot->npages);
34461e76a3ceSDavid Stevens 			if (r)
34471e76a3ceSDavid Stevens 				goto out_unlock;
34481e76a3ceSDavid Stevens 			r = kvm_page_track_write_tracking_alloc(slot);
34491e76a3ceSDavid Stevens 			if (r)
34501e76a3ceSDavid Stevens 				goto out_unlock;
34511e76a3ceSDavid Stevens 		}
34521e76a3ceSDavid Stevens 	}
34531e76a3ceSDavid Stevens 
34541e76a3ceSDavid Stevens 	/*
34551e76a3ceSDavid Stevens 	 * Ensure that shadow_root_allocated becomes true strictly after
34561e76a3ceSDavid Stevens 	 * all the related pointers are set.
34571e76a3ceSDavid Stevens 	 */
34581e76a3ceSDavid Stevens out_success:
34591e76a3ceSDavid Stevens 	smp_store_release(&kvm->arch.shadow_root_allocated, true);
34601e76a3ceSDavid Stevens 
34611e76a3ceSDavid Stevens out_unlock:
34621e76a3ceSDavid Stevens 	mutex_unlock(&kvm->slots_arch_lock);
34631e76a3ceSDavid Stevens 	return r;
34641e76a3ceSDavid Stevens }
34651e76a3ceSDavid Stevens 
3466c50d8ae3SPaolo Bonzini static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3467c50d8ae3SPaolo Bonzini {
3468b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
34696e0918aeSSean Christopherson 	u64 pdptrs[4], pm_mask;
3470be01e8e2SSean Christopherson 	gfn_t root_gfn, root_pgd;
34718123f265SSean Christopherson 	hpa_t root;
34724a38162eSPaolo Bonzini 	unsigned i;
34734a38162eSPaolo Bonzini 	int r;
3474c50d8ae3SPaolo Bonzini 
3475b37233c9SSean Christopherson 	root_pgd = mmu->get_guest_pgd(vcpu);
3476be01e8e2SSean Christopherson 	root_gfn = root_pgd >> PAGE_SHIFT;
3477c50d8ae3SPaolo Bonzini 
3478c50d8ae3SPaolo Bonzini 	if (mmu_check_root(vcpu, root_gfn))
3479c50d8ae3SPaolo Bonzini 		return 1;
3480c50d8ae3SPaolo Bonzini 
3481c50d8ae3SPaolo Bonzini 	/*
34824a38162eSPaolo Bonzini 	 * On SVM, reading PDPTRs might access guest memory, which might fault
34834a38162eSPaolo Bonzini 	 * and thus might sleep.  Grab the PDPTRs before acquiring mmu_lock.
34844a38162eSPaolo Bonzini 	 */
34856e0918aeSSean Christopherson 	if (mmu->root_level == PT32E_ROOT_LEVEL) {
34866e0918aeSSean Christopherson 		for (i = 0; i < 4; ++i) {
34876e0918aeSSean Christopherson 			pdptrs[i] = mmu->get_pdptr(vcpu, i);
34886e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK))
34896e0918aeSSean Christopherson 				continue;
34906e0918aeSSean Christopherson 
34916e0918aeSSean Christopherson 			if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
34926e0918aeSSean Christopherson 				return 1;
34936e0918aeSSean Christopherson 		}
34946e0918aeSSean Christopherson 	}
34956e0918aeSSean Christopherson 
34961e76a3ceSDavid Stevens 	r = mmu_first_shadow_root_alloc(vcpu->kvm);
3497d501f747SBen Gardon 	if (r)
3498d501f747SBen Gardon 		return r;
3499d501f747SBen Gardon 
35004a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
35014a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
35024a38162eSPaolo Bonzini 	if (r < 0)
35034a38162eSPaolo Bonzini 		goto out_unlock;
35044a38162eSPaolo Bonzini 
3505c50d8ae3SPaolo Bonzini 	/*
3506c50d8ae3SPaolo Bonzini 	 * Do we shadow a long mode page table? If so we need to
3507c50d8ae3SPaolo Bonzini 	 * write-protect the guests page table root.
3508c50d8ae3SPaolo Bonzini 	 */
3509b37233c9SSean Christopherson 	if (mmu->root_level >= PT64_ROOT_4LEVEL) {
35108123f265SSean Christopherson 		root = mmu_alloc_root(vcpu, root_gfn, 0,
3511b37233c9SSean Christopherson 				      mmu->shadow_root_level, false);
3512b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
3513be01e8e2SSean Christopherson 		goto set_root_pgd;
3514c50d8ae3SPaolo Bonzini 	}
3515c50d8ae3SPaolo Bonzini 
35164a38162eSPaolo Bonzini 	if (WARN_ON_ONCE(!mmu->pae_root)) {
35174a38162eSPaolo Bonzini 		r = -EIO;
35184a38162eSPaolo Bonzini 		goto out_unlock;
35194a38162eSPaolo Bonzini 	}
352073ad1606SSean Christopherson 
3521c50d8ae3SPaolo Bonzini 	/*
3522c50d8ae3SPaolo Bonzini 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3523c50d8ae3SPaolo Bonzini 	 * or a PAE 3-level page table. In either case we need to be aware that
3524c50d8ae3SPaolo Bonzini 	 * the shadow page table may be a PAE or a long mode page table.
3525c50d8ae3SPaolo Bonzini 	 */
352617e368d9SSean Christopherson 	pm_mask = PT_PRESENT_MASK | shadow_me_mask;
3527cb0f722aSWei Huang 	if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3528c50d8ae3SPaolo Bonzini 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3529c50d8ae3SPaolo Bonzini 
353003ca4589SSean Christopherson 		if (WARN_ON_ONCE(!mmu->pml4_root)) {
35314a38162eSPaolo Bonzini 			r = -EIO;
35324a38162eSPaolo Bonzini 			goto out_unlock;
35334a38162eSPaolo Bonzini 		}
353403ca4589SSean Christopherson 		mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3535cb0f722aSWei Huang 
3536cb0f722aSWei Huang 		if (mmu->shadow_root_level == PT64_ROOT_5LEVEL) {
3537cb0f722aSWei Huang 			if (WARN_ON_ONCE(!mmu->pml5_root)) {
3538cb0f722aSWei Huang 				r = -EIO;
3539cb0f722aSWei Huang 				goto out_unlock;
3540cb0f722aSWei Huang 			}
3541cb0f722aSWei Huang 			mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3542cb0f722aSWei Huang 		}
354304d45551SSean Christopherson 	}
354404d45551SSean Christopherson 
3545c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3546c834e5e4SSean Christopherson 		WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
35476e6ec584SSean Christopherson 
3548b37233c9SSean Christopherson 		if (mmu->root_level == PT32E_ROOT_LEVEL) {
35496e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3550c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3551c50d8ae3SPaolo Bonzini 				continue;
3552c50d8ae3SPaolo Bonzini 			}
35536e0918aeSSean Christopherson 			root_gfn = pdptrs[i] >> PAGE_SHIFT;
3554c50d8ae3SPaolo Bonzini 		}
3555c50d8ae3SPaolo Bonzini 
35568123f265SSean Christopherson 		root = mmu_alloc_root(vcpu, root_gfn, i << 30,
35578123f265SSean Christopherson 				      PT32_ROOT_LEVEL, false);
3558b37233c9SSean Christopherson 		mmu->pae_root[i] = root | pm_mask;
3559c50d8ae3SPaolo Bonzini 	}
3560c50d8ae3SPaolo Bonzini 
3561cb0f722aSWei Huang 	if (mmu->shadow_root_level == PT64_ROOT_5LEVEL)
3562b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml5_root);
3563cb0f722aSWei Huang 	else if (mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3564b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml4_root);
3565ba0a194fSSean Christopherson 	else
3566b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
3567c50d8ae3SPaolo Bonzini 
3568be01e8e2SSean Christopherson set_root_pgd:
3569b9e5603cSPaolo Bonzini 	mmu->root.pgd = root_pgd;
35704a38162eSPaolo Bonzini out_unlock:
35714a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
3572c50d8ae3SPaolo Bonzini 
3573c6c937d6SLike Xu 	return r;
3574c50d8ae3SPaolo Bonzini }
3575c50d8ae3SPaolo Bonzini 
3576748e52b9SSean Christopherson static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3577c50d8ae3SPaolo Bonzini {
3578748e52b9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3579a717a780SSean Christopherson 	bool need_pml5 = mmu->shadow_root_level > PT64_ROOT_4LEVEL;
3580cb0f722aSWei Huang 	u64 *pml5_root = NULL;
3581cb0f722aSWei Huang 	u64 *pml4_root = NULL;
3582cb0f722aSWei Huang 	u64 *pae_root;
3583748e52b9SSean Christopherson 
3584748e52b9SSean Christopherson 	/*
3585748e52b9SSean Christopherson 	 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3586748e52b9SSean Christopherson 	 * tables are allocated and initialized at root creation as there is no
3587748e52b9SSean Christopherson 	 * equivalent level in the guest's NPT to shadow.  Allocate the tables
3588748e52b9SSean Christopherson 	 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3589748e52b9SSean Christopherson 	 */
3590748e52b9SSean Christopherson 	if (mmu->direct_map || mmu->root_level >= PT64_ROOT_4LEVEL ||
3591748e52b9SSean Christopherson 	    mmu->shadow_root_level < PT64_ROOT_4LEVEL)
3592748e52b9SSean Christopherson 		return 0;
3593748e52b9SSean Christopherson 
3594a717a780SSean Christopherson 	/*
3595a717a780SSean Christopherson 	 * NPT, the only paging mode that uses this horror, uses a fixed number
3596a717a780SSean Christopherson 	 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3597a717a780SSean Christopherson 	 * all MMus are 5-level.  Thus, this can safely require that pml5_root
3598a717a780SSean Christopherson 	 * is allocated if the other roots are valid and pml5 is needed, as any
3599a717a780SSean Christopherson 	 * prior MMU would also have required pml5.
3600a717a780SSean Christopherson 	 */
3601a717a780SSean Christopherson 	if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3602748e52b9SSean Christopherson 		return 0;
3603748e52b9SSean Christopherson 
3604748e52b9SSean Christopherson 	/*
3605748e52b9SSean Christopherson 	 * The special roots should always be allocated in concert.  Yell and
3606748e52b9SSean Christopherson 	 * bail if KVM ends up in a state where only one of the roots is valid.
3607748e52b9SSean Christopherson 	 */
3608cb0f722aSWei Huang 	if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3609a717a780SSean Christopherson 			 (need_pml5 && mmu->pml5_root)))
3610748e52b9SSean Christopherson 		return -EIO;
3611748e52b9SSean Christopherson 
36124a98623dSSean Christopherson 	/*
36134a98623dSSean Christopherson 	 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
36144a98623dSSean Christopherson 	 * doesn't need to be decrypted.
36154a98623dSSean Christopherson 	 */
3616748e52b9SSean Christopherson 	pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3617748e52b9SSean Christopherson 	if (!pae_root)
3618748e52b9SSean Christopherson 		return -ENOMEM;
3619748e52b9SSean Christopherson 
3620cb0f722aSWei Huang #ifdef CONFIG_X86_64
362103ca4589SSean Christopherson 	pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3622cb0f722aSWei Huang 	if (!pml4_root)
3623cb0f722aSWei Huang 		goto err_pml4;
3624cb0f722aSWei Huang 
3625a717a780SSean Christopherson 	if (need_pml5) {
3626cb0f722aSWei Huang 		pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3627cb0f722aSWei Huang 		if (!pml5_root)
3628cb0f722aSWei Huang 			goto err_pml5;
3629748e52b9SSean Christopherson 	}
3630cb0f722aSWei Huang #endif
3631748e52b9SSean Christopherson 
3632748e52b9SSean Christopherson 	mmu->pae_root = pae_root;
363303ca4589SSean Christopherson 	mmu->pml4_root = pml4_root;
3634cb0f722aSWei Huang 	mmu->pml5_root = pml5_root;
3635748e52b9SSean Christopherson 
3636748e52b9SSean Christopherson 	return 0;
3637cb0f722aSWei Huang 
3638cb0f722aSWei Huang #ifdef CONFIG_X86_64
3639cb0f722aSWei Huang err_pml5:
3640cb0f722aSWei Huang 	free_page((unsigned long)pml4_root);
3641cb0f722aSWei Huang err_pml4:
3642cb0f722aSWei Huang 	free_page((unsigned long)pae_root);
3643cb0f722aSWei Huang 	return -ENOMEM;
3644cb0f722aSWei Huang #endif
3645c50d8ae3SPaolo Bonzini }
3646c50d8ae3SPaolo Bonzini 
3647264d3dc1SLai Jiangshan static bool is_unsync_root(hpa_t root)
3648264d3dc1SLai Jiangshan {
3649264d3dc1SLai Jiangshan 	struct kvm_mmu_page *sp;
3650264d3dc1SLai Jiangshan 
365161b05a9fSLai Jiangshan 	if (!VALID_PAGE(root))
365261b05a9fSLai Jiangshan 		return false;
365361b05a9fSLai Jiangshan 
3654264d3dc1SLai Jiangshan 	/*
3655264d3dc1SLai Jiangshan 	 * The read barrier orders the CPU's read of SPTE.W during the page table
3656264d3dc1SLai Jiangshan 	 * walk before the reads of sp->unsync/sp->unsync_children here.
3657264d3dc1SLai Jiangshan 	 *
3658264d3dc1SLai Jiangshan 	 * Even if another CPU was marking the SP as unsync-ed simultaneously,
3659264d3dc1SLai Jiangshan 	 * any guest page table changes are not guaranteed to be visible anyway
3660264d3dc1SLai Jiangshan 	 * until this VCPU issues a TLB flush strictly after those changes are
3661264d3dc1SLai Jiangshan 	 * made.  We only need to ensure that the other CPU sets these flags
3662264d3dc1SLai Jiangshan 	 * before any actual changes to the page tables are made.  The comments
3663264d3dc1SLai Jiangshan 	 * in mmu_try_to_unsync_pages() describe what could go wrong if this
3664264d3dc1SLai Jiangshan 	 * requirement isn't satisfied.
3665264d3dc1SLai Jiangshan 	 */
3666264d3dc1SLai Jiangshan 	smp_rmb();
3667264d3dc1SLai Jiangshan 	sp = to_shadow_page(root);
36685d6a3221SSean Christopherson 
36695d6a3221SSean Christopherson 	/*
36705d6a3221SSean Christopherson 	 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
36715d6a3221SSean Christopherson 	 * PDPTEs for a given PAE root need to be synchronized individually.
36725d6a3221SSean Christopherson 	 */
36735d6a3221SSean Christopherson 	if (WARN_ON_ONCE(!sp))
36745d6a3221SSean Christopherson 		return false;
36755d6a3221SSean Christopherson 
3676264d3dc1SLai Jiangshan 	if (sp->unsync || sp->unsync_children)
3677264d3dc1SLai Jiangshan 		return true;
3678264d3dc1SLai Jiangshan 
3679264d3dc1SLai Jiangshan 	return false;
3680264d3dc1SLai Jiangshan }
3681264d3dc1SLai Jiangshan 
3682c50d8ae3SPaolo Bonzini void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3683c50d8ae3SPaolo Bonzini {
3684c50d8ae3SPaolo Bonzini 	int i;
3685c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3686c50d8ae3SPaolo Bonzini 
3687c50d8ae3SPaolo Bonzini 	if (vcpu->arch.mmu->direct_map)
3688c50d8ae3SPaolo Bonzini 		return;
3689c50d8ae3SPaolo Bonzini 
3690b9e5603cSPaolo Bonzini 	if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
3691c50d8ae3SPaolo Bonzini 		return;
3692c50d8ae3SPaolo Bonzini 
3693c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3694c50d8ae3SPaolo Bonzini 
3695c50d8ae3SPaolo Bonzini 	if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3696b9e5603cSPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->root.hpa;
3697e47c4aeeSSean Christopherson 		sp = to_shadow_page(root);
3698c50d8ae3SPaolo Bonzini 
3699264d3dc1SLai Jiangshan 		if (!is_unsync_root(root))
3700c50d8ae3SPaolo Bonzini 			return;
3701c50d8ae3SPaolo Bonzini 
3702531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
370365855ed8SLai Jiangshan 		mmu_sync_children(vcpu, sp, true);
3704531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
3705c50d8ae3SPaolo Bonzini 		return;
3706c50d8ae3SPaolo Bonzini 	}
3707c50d8ae3SPaolo Bonzini 
3708531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
3709c50d8ae3SPaolo Bonzini 
3710c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3711c50d8ae3SPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->pae_root[i];
3712c50d8ae3SPaolo Bonzini 
3713c834e5e4SSean Christopherson 		if (IS_VALID_PAE_ROOT(root)) {
3714c50d8ae3SPaolo Bonzini 			root &= PT64_BASE_ADDR_MASK;
3715e47c4aeeSSean Christopherson 			sp = to_shadow_page(root);
371665855ed8SLai Jiangshan 			mmu_sync_children(vcpu, sp, true);
3717c50d8ae3SPaolo Bonzini 		}
3718c50d8ae3SPaolo Bonzini 	}
3719c50d8ae3SPaolo Bonzini 
3720531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
3721c50d8ae3SPaolo Bonzini }
3722c50d8ae3SPaolo Bonzini 
372361b05a9fSLai Jiangshan void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
372461b05a9fSLai Jiangshan {
372561b05a9fSLai Jiangshan 	unsigned long roots_to_free = 0;
372661b05a9fSLai Jiangshan 	int i;
372761b05a9fSLai Jiangshan 
372861b05a9fSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
372961b05a9fSLai Jiangshan 		if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
373061b05a9fSLai Jiangshan 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
373161b05a9fSLai Jiangshan 
373261b05a9fSLai Jiangshan 	/* sync prev_roots by simply freeing them */
37330c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
373461b05a9fSLai Jiangshan }
373561b05a9fSLai Jiangshan 
37361f5a21eeSLai Jiangshan static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
37375b22bbe7SLai Jiangshan 				  gpa_t vaddr, u64 access,
3738c50d8ae3SPaolo Bonzini 				  struct x86_exception *exception)
3739c50d8ae3SPaolo Bonzini {
3740c50d8ae3SPaolo Bonzini 	if (exception)
3741c50d8ae3SPaolo Bonzini 		exception->error_code = 0;
3742c59a0f57SLai Jiangshan 	return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
3743c50d8ae3SPaolo Bonzini }
3744c50d8ae3SPaolo Bonzini 
3745c50d8ae3SPaolo Bonzini static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3746c50d8ae3SPaolo Bonzini {
3747c50d8ae3SPaolo Bonzini 	/*
3748c50d8ae3SPaolo Bonzini 	 * A nested guest cannot use the MMIO cache if it is using nested
3749c50d8ae3SPaolo Bonzini 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3750c50d8ae3SPaolo Bonzini 	 */
3751c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
3752c50d8ae3SPaolo Bonzini 		return false;
3753c50d8ae3SPaolo Bonzini 
3754c50d8ae3SPaolo Bonzini 	if (direct)
3755c50d8ae3SPaolo Bonzini 		return vcpu_match_mmio_gpa(vcpu, addr);
3756c50d8ae3SPaolo Bonzini 
3757c50d8ae3SPaolo Bonzini 	return vcpu_match_mmio_gva(vcpu, addr);
3758c50d8ae3SPaolo Bonzini }
3759c50d8ae3SPaolo Bonzini 
376095fb5b02SBen Gardon /*
376195fb5b02SBen Gardon  * Return the level of the lowest level SPTE added to sptes.
376295fb5b02SBen Gardon  * That SPTE may be non-present.
3763c5c8c7c5SDavid Matlack  *
3764c5c8c7c5SDavid Matlack  * Must be called between walk_shadow_page_lockless_{begin,end}.
376595fb5b02SBen Gardon  */
376639b4d43eSSean Christopherson static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
3767c50d8ae3SPaolo Bonzini {
3768c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
37692aa07893SSean Christopherson 	int leaf = -1;
377095fb5b02SBen Gardon 	u64 spte;
3771c50d8ae3SPaolo Bonzini 
377239b4d43eSSean Christopherson 	for (shadow_walk_init(&iterator, vcpu, addr),
377339b4d43eSSean Christopherson 	     *root_level = iterator.level;
3774c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&iterator);
3775c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&iterator, spte)) {
377695fb5b02SBen Gardon 		leaf = iterator.level;
3777c50d8ae3SPaolo Bonzini 		spte = mmu_spte_get_lockless(iterator.sptep);
3778c50d8ae3SPaolo Bonzini 
3779dde81f94SSean Christopherson 		sptes[leaf] = spte;
378095fb5b02SBen Gardon 	}
378195fb5b02SBen Gardon 
378295fb5b02SBen Gardon 	return leaf;
378395fb5b02SBen Gardon }
378495fb5b02SBen Gardon 
37859aa41879SSean Christopherson /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
378695fb5b02SBen Gardon static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
378795fb5b02SBen Gardon {
3788dde81f94SSean Christopherson 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
378995fb5b02SBen Gardon 	struct rsvd_bits_validate *rsvd_check;
379039b4d43eSSean Christopherson 	int root, leaf, level;
379195fb5b02SBen Gardon 	bool reserved = false;
379295fb5b02SBen Gardon 
3793c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_begin(vcpu);
3794c5c8c7c5SDavid Matlack 
379563c0cac9SDavid Matlack 	if (is_tdp_mmu(vcpu->arch.mmu))
379639b4d43eSSean Christopherson 		leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
379795fb5b02SBen Gardon 	else
379839b4d43eSSean Christopherson 		leaf = get_walk(vcpu, addr, sptes, &root);
379995fb5b02SBen Gardon 
3800c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_end(vcpu);
3801c5c8c7c5SDavid Matlack 
38022aa07893SSean Christopherson 	if (unlikely(leaf < 0)) {
38032aa07893SSean Christopherson 		*sptep = 0ull;
38042aa07893SSean Christopherson 		return reserved;
38052aa07893SSean Christopherson 	}
38062aa07893SSean Christopherson 
38079aa41879SSean Christopherson 	*sptep = sptes[leaf];
38089aa41879SSean Christopherson 
38099aa41879SSean Christopherson 	/*
38109aa41879SSean Christopherson 	 * Skip reserved bits checks on the terminal leaf if it's not a valid
38119aa41879SSean Christopherson 	 * SPTE.  Note, this also (intentionally) skips MMIO SPTEs, which, by
38129aa41879SSean Christopherson 	 * design, always have reserved bits set.  The purpose of the checks is
38139aa41879SSean Christopherson 	 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
38149aa41879SSean Christopherson 	 */
38159aa41879SSean Christopherson 	if (!is_shadow_present_pte(sptes[leaf]))
38169aa41879SSean Christopherson 		leaf++;
381795fb5b02SBen Gardon 
381895fb5b02SBen Gardon 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
381995fb5b02SBen Gardon 
38209aa41879SSean Christopherson 	for (level = root; level >= leaf; level--)
3821961f8445SSean Christopherson 		reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
3822c50d8ae3SPaolo Bonzini 
3823c50d8ae3SPaolo Bonzini 	if (reserved) {
3824bb4cdf3aSSean Christopherson 		pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
3825c50d8ae3SPaolo Bonzini 		       __func__, addr);
382695fb5b02SBen Gardon 		for (level = root; level >= leaf; level--)
3827bb4cdf3aSSean Christopherson 			pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
3828bb4cdf3aSSean Christopherson 			       sptes[level], level,
3829961f8445SSean Christopherson 			       get_rsvd_bits(rsvd_check, sptes[level], level));
3830c50d8ae3SPaolo Bonzini 	}
3831ddce6208SSean Christopherson 
3832c50d8ae3SPaolo Bonzini 	return reserved;
3833c50d8ae3SPaolo Bonzini }
3834c50d8ae3SPaolo Bonzini 
3835c50d8ae3SPaolo Bonzini static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3836c50d8ae3SPaolo Bonzini {
3837c50d8ae3SPaolo Bonzini 	u64 spte;
3838c50d8ae3SPaolo Bonzini 	bool reserved;
3839c50d8ae3SPaolo Bonzini 
3840c50d8ae3SPaolo Bonzini 	if (mmio_info_in_cache(vcpu, addr, direct))
3841c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3842c50d8ae3SPaolo Bonzini 
384395fb5b02SBen Gardon 	reserved = get_mmio_spte(vcpu, addr, &spte);
3844c50d8ae3SPaolo Bonzini 	if (WARN_ON(reserved))
3845c50d8ae3SPaolo Bonzini 		return -EINVAL;
3846c50d8ae3SPaolo Bonzini 
3847c50d8ae3SPaolo Bonzini 	if (is_mmio_spte(spte)) {
3848c50d8ae3SPaolo Bonzini 		gfn_t gfn = get_mmio_spte_gfn(spte);
38490a2b64c5SBen Gardon 		unsigned int access = get_mmio_spte_access(spte);
3850c50d8ae3SPaolo Bonzini 
3851c50d8ae3SPaolo Bonzini 		if (!check_mmio_spte(vcpu, spte))
3852c50d8ae3SPaolo Bonzini 			return RET_PF_INVALID;
3853c50d8ae3SPaolo Bonzini 
3854c50d8ae3SPaolo Bonzini 		if (direct)
3855c50d8ae3SPaolo Bonzini 			addr = 0;
3856c50d8ae3SPaolo Bonzini 
3857c50d8ae3SPaolo Bonzini 		trace_handle_mmio_page_fault(addr, gfn, access);
3858c50d8ae3SPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3859c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3860c50d8ae3SPaolo Bonzini 	}
3861c50d8ae3SPaolo Bonzini 
3862c50d8ae3SPaolo Bonzini 	/*
3863c50d8ae3SPaolo Bonzini 	 * If the page table is zapped by other cpus, let CPU fault again on
3864c50d8ae3SPaolo Bonzini 	 * the address.
3865c50d8ae3SPaolo Bonzini 	 */
3866c50d8ae3SPaolo Bonzini 	return RET_PF_RETRY;
3867c50d8ae3SPaolo Bonzini }
3868c50d8ae3SPaolo Bonzini 
3869c50d8ae3SPaolo Bonzini static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3870b8a5d551SPaolo Bonzini 					 struct kvm_page_fault *fault)
3871c50d8ae3SPaolo Bonzini {
3872b8a5d551SPaolo Bonzini 	if (unlikely(fault->rsvd))
3873c50d8ae3SPaolo Bonzini 		return false;
3874c50d8ae3SPaolo Bonzini 
3875b8a5d551SPaolo Bonzini 	if (!fault->present || !fault->write)
3876c50d8ae3SPaolo Bonzini 		return false;
3877c50d8ae3SPaolo Bonzini 
3878c50d8ae3SPaolo Bonzini 	/*
3879c50d8ae3SPaolo Bonzini 	 * guest is writing the page which is write tracked which can
3880c50d8ae3SPaolo Bonzini 	 * not be fixed by page fault handler.
3881c50d8ae3SPaolo Bonzini 	 */
38829d395a0aSBen Gardon 	if (kvm_slot_page_track_is_active(vcpu->kvm, fault->slot, fault->gfn, KVM_PAGE_TRACK_WRITE))
3883c50d8ae3SPaolo Bonzini 		return true;
3884c50d8ae3SPaolo Bonzini 
3885c50d8ae3SPaolo Bonzini 	return false;
3886c50d8ae3SPaolo Bonzini }
3887c50d8ae3SPaolo Bonzini 
3888c50d8ae3SPaolo Bonzini static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3889c50d8ae3SPaolo Bonzini {
3890c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
3891c50d8ae3SPaolo Bonzini 	u64 spte;
3892c50d8ae3SPaolo Bonzini 
3893c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
38943e44dce4SLai Jiangshan 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
3895c50d8ae3SPaolo Bonzini 		clear_sp_write_flooding_count(iterator.sptep);
3896c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3897c50d8ae3SPaolo Bonzini }
3898c50d8ae3SPaolo Bonzini 
38996f3c1fc5SLiang Zhang static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
39006f3c1fc5SLiang Zhang {
39016f3c1fc5SLiang Zhang 	/* make sure the token value is not 0 */
39026f3c1fc5SLiang Zhang 	u32 id = vcpu->arch.apf.id;
39036f3c1fc5SLiang Zhang 
39046f3c1fc5SLiang Zhang 	if (id << 12 == 0)
39056f3c1fc5SLiang Zhang 		vcpu->arch.apf.id = 1;
39066f3c1fc5SLiang Zhang 
39076f3c1fc5SLiang Zhang 	return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
39086f3c1fc5SLiang Zhang }
39096f3c1fc5SLiang Zhang 
3910e8c22266SVitaly Kuznetsov static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
39119f1a8526SSean Christopherson 				    gfn_t gfn)
3912c50d8ae3SPaolo Bonzini {
3913c50d8ae3SPaolo Bonzini 	struct kvm_arch_async_pf arch;
3914c50d8ae3SPaolo Bonzini 
39156f3c1fc5SLiang Zhang 	arch.token = alloc_apf_token(vcpu);
3916c50d8ae3SPaolo Bonzini 	arch.gfn = gfn;
3917c50d8ae3SPaolo Bonzini 	arch.direct_map = vcpu->arch.mmu->direct_map;
3918d8dd54e0SSean Christopherson 	arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
3919c50d8ae3SPaolo Bonzini 
39209f1a8526SSean Christopherson 	return kvm_setup_async_pf(vcpu, cr2_or_gpa,
39219f1a8526SSean Christopherson 				  kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
3922c50d8ae3SPaolo Bonzini }
3923c50d8ae3SPaolo Bonzini 
39243647cd04SPaolo Bonzini static bool kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault, int *r)
3925c50d8ae3SPaolo Bonzini {
3926e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
3927c50d8ae3SPaolo Bonzini 	bool async;
3928c50d8ae3SPaolo Bonzini 
3929e0c37868SSean Christopherson 	/*
3930e0c37868SSean Christopherson 	 * Retry the page fault if the gfn hit a memslot that is being deleted
3931e0c37868SSean Christopherson 	 * or moved.  This ensures any existing SPTEs for the old memslot will
3932e0c37868SSean Christopherson 	 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
3933e0c37868SSean Christopherson 	 */
3934e0c37868SSean Christopherson 	if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
39358f32d5e5SMaxim Levitsky 		goto out_retry;
3936e0c37868SSean Christopherson 
39379cc13d60SMaxim Levitsky 	if (!kvm_is_visible_memslot(slot)) {
3938c36b7150SPaolo Bonzini 		/* Don't expose private memslots to L2. */
39399cc13d60SMaxim Levitsky 		if (is_guest_mode(vcpu)) {
3940e710c5f6SDavid Matlack 			fault->slot = NULL;
39413647cd04SPaolo Bonzini 			fault->pfn = KVM_PFN_NOSLOT;
39423647cd04SPaolo Bonzini 			fault->map_writable = false;
3943c50d8ae3SPaolo Bonzini 			return false;
3944c50d8ae3SPaolo Bonzini 		}
39459cc13d60SMaxim Levitsky 		/*
39469cc13d60SMaxim Levitsky 		 * If the APIC access page exists but is disabled, go directly
39479cc13d60SMaxim Levitsky 		 * to emulation without caching the MMIO access or creating a
39489cc13d60SMaxim Levitsky 		 * MMIO SPTE.  That way the cache doesn't need to be purged
39499cc13d60SMaxim Levitsky 		 * when the AVIC is re-enabled.
39509cc13d60SMaxim Levitsky 		 */
39519cc13d60SMaxim Levitsky 		if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
39529cc13d60SMaxim Levitsky 		    !kvm_apicv_activated(vcpu->kvm)) {
39539cc13d60SMaxim Levitsky 			*r = RET_PF_EMULATE;
39549cc13d60SMaxim Levitsky 			return true;
39559cc13d60SMaxim Levitsky 		}
39569cc13d60SMaxim Levitsky 	}
3957c50d8ae3SPaolo Bonzini 
3958c50d8ae3SPaolo Bonzini 	async = false;
39593647cd04SPaolo Bonzini 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, &async,
39603647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
39613647cd04SPaolo Bonzini 					  &fault->hva);
3962c50d8ae3SPaolo Bonzini 	if (!async)
3963c50d8ae3SPaolo Bonzini 		return false; /* *pfn has correct page already */
3964c50d8ae3SPaolo Bonzini 
39652839180cSPaolo Bonzini 	if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
39663647cd04SPaolo Bonzini 		trace_kvm_try_async_get_page(fault->addr, fault->gfn);
39673647cd04SPaolo Bonzini 		if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
39683647cd04SPaolo Bonzini 			trace_kvm_async_pf_doublefault(fault->addr, fault->gfn);
3969c50d8ae3SPaolo Bonzini 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
39708f32d5e5SMaxim Levitsky 			goto out_retry;
39713647cd04SPaolo Bonzini 		} else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn))
39728f32d5e5SMaxim Levitsky 			goto out_retry;
3973c50d8ae3SPaolo Bonzini 	}
3974c50d8ae3SPaolo Bonzini 
39753647cd04SPaolo Bonzini 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, NULL,
39763647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
39773647cd04SPaolo Bonzini 					  &fault->hva);
3978a7cc099fSAndrei Vagin 	return false;
39798f32d5e5SMaxim Levitsky 
39808f32d5e5SMaxim Levitsky out_retry:
39818f32d5e5SMaxim Levitsky 	*r = RET_PF_RETRY;
39828f32d5e5SMaxim Levitsky 	return true;
3983c50d8ae3SPaolo Bonzini }
3984c50d8ae3SPaolo Bonzini 
3985a955cad8SSean Christopherson /*
3986a955cad8SSean Christopherson  * Returns true if the page fault is stale and needs to be retried, i.e. if the
3987a955cad8SSean Christopherson  * root was invalidated by a memslot update or a relevant mmu_notifier fired.
3988a955cad8SSean Christopherson  */
3989a955cad8SSean Christopherson static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
3990a955cad8SSean Christopherson 				struct kvm_page_fault *fault, int mmu_seq)
3991a955cad8SSean Christopherson {
3992b9e5603cSPaolo Bonzini 	struct kvm_mmu_page *sp = to_shadow_page(vcpu->arch.mmu->root.hpa);
399318c841e1SSean Christopherson 
399418c841e1SSean Christopherson 	/* Special roots, e.g. pae_root, are not backed by shadow pages. */
399518c841e1SSean Christopherson 	if (sp && is_obsolete_sp(vcpu->kvm, sp))
399618c841e1SSean Christopherson 		return true;
399718c841e1SSean Christopherson 
399818c841e1SSean Christopherson 	/*
399918c841e1SSean Christopherson 	 * Roots without an associated shadow page are considered invalid if
400018c841e1SSean Christopherson 	 * there is a pending request to free obsolete roots.  The request is
400118c841e1SSean Christopherson 	 * only a hint that the current root _may_ be obsolete and needs to be
400218c841e1SSean Christopherson 	 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
400318c841e1SSean Christopherson 	 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
400418c841e1SSean Christopherson 	 * to reload even if no vCPU is actively using the root.
400518c841e1SSean Christopherson 	 */
4006527d5cd7SSean Christopherson 	if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4007a955cad8SSean Christopherson 		return true;
4008a955cad8SSean Christopherson 
4009a955cad8SSean Christopherson 	return fault->slot &&
4010a955cad8SSean Christopherson 	       mmu_notifier_retry_hva(vcpu->kvm, mmu_seq, fault->hva);
4011a955cad8SSean Christopherson }
4012a955cad8SSean Christopherson 
40134326e57eSPaolo Bonzini static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4014c50d8ae3SPaolo Bonzini {
401563c0cac9SDavid Matlack 	bool is_tdp_mmu_fault = is_tdp_mmu(vcpu->arch.mmu);
4016c50d8ae3SPaolo Bonzini 
40170f90e1c1SSean Christopherson 	unsigned long mmu_seq;
401883f06fa7SSean Christopherson 	int r;
4019c50d8ae3SPaolo Bonzini 
40203c8ad5a6SPaolo Bonzini 	fault->gfn = fault->addr >> PAGE_SHIFT;
4021e710c5f6SDavid Matlack 	fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);
4022e710c5f6SDavid Matlack 
4023b8a5d551SPaolo Bonzini 	if (page_fault_handle_page_track(vcpu, fault))
4024c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4025c50d8ae3SPaolo Bonzini 
40263c8ad5a6SPaolo Bonzini 	r = fast_page_fault(vcpu, fault);
4027c4371c2aSSean Christopherson 	if (r != RET_PF_INVALID)
4028c4371c2aSSean Christopherson 		return r;
402983291445SSean Christopherson 
4030378f5cd6SSean Christopherson 	r = mmu_topup_memory_caches(vcpu, false);
4031c50d8ae3SPaolo Bonzini 	if (r)
4032c50d8ae3SPaolo Bonzini 		return r;
4033c50d8ae3SPaolo Bonzini 
4034367fd790SSean Christopherson 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
4035367fd790SSean Christopherson 	smp_rmb();
4036367fd790SSean Christopherson 
40373647cd04SPaolo Bonzini 	if (kvm_faultin_pfn(vcpu, fault, &r))
40388f32d5e5SMaxim Levitsky 		return r;
4039367fd790SSean Christopherson 
40403a13f4feSPaolo Bonzini 	if (handle_abnormal_pfn(vcpu, fault, ACC_ALL, &r))
4041367fd790SSean Christopherson 		return r;
4042367fd790SSean Christopherson 
4043367fd790SSean Christopherson 	r = RET_PF_RETRY;
4044a2855afcSBen Gardon 
40450b873fd7SDavid Matlack 	if (is_tdp_mmu_fault)
4046a2855afcSBen Gardon 		read_lock(&vcpu->kvm->mmu_lock);
4047a2855afcSBen Gardon 	else
4048531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
4049a2855afcSBen Gardon 
4050a955cad8SSean Christopherson 	if (is_page_fault_stale(vcpu, fault, mmu_seq))
4051367fd790SSean Christopherson 		goto out_unlock;
4052a955cad8SSean Christopherson 
40537bd7ded6SSean Christopherson 	r = make_mmu_pages_available(vcpu);
40547bd7ded6SSean Christopherson 	if (r)
4055367fd790SSean Christopherson 		goto out_unlock;
4056bb18842eSBen Gardon 
40570b873fd7SDavid Matlack 	if (is_tdp_mmu_fault)
40582f6305ddSPaolo Bonzini 		r = kvm_tdp_mmu_map(vcpu, fault);
4059bb18842eSBen Gardon 	else
406043b74355SPaolo Bonzini 		r = __direct_map(vcpu, fault);
40610f90e1c1SSean Christopherson 
4062367fd790SSean Christopherson out_unlock:
40630b873fd7SDavid Matlack 	if (is_tdp_mmu_fault)
4064a2855afcSBen Gardon 		read_unlock(&vcpu->kvm->mmu_lock);
4065a2855afcSBen Gardon 	else
4066531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
40673647cd04SPaolo Bonzini 	kvm_release_pfn_clean(fault->pfn);
4068367fd790SSean Christopherson 	return r;
4069c50d8ae3SPaolo Bonzini }
4070c50d8ae3SPaolo Bonzini 
4071c501040aSPaolo Bonzini static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4072c501040aSPaolo Bonzini 				struct kvm_page_fault *fault)
40730f90e1c1SSean Christopherson {
40744326e57eSPaolo Bonzini 	pgprintk("%s: gva %lx error %x\n", __func__, fault->addr, fault->error_code);
40750f90e1c1SSean Christopherson 
40760f90e1c1SSean Christopherson 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
40774326e57eSPaolo Bonzini 	fault->max_level = PG_LEVEL_2M;
40784326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
40790f90e1c1SSean Christopherson }
40800f90e1c1SSean Christopherson 
4081c50d8ae3SPaolo Bonzini int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4082c50d8ae3SPaolo Bonzini 				u64 fault_address, char *insn, int insn_len)
4083c50d8ae3SPaolo Bonzini {
4084c50d8ae3SPaolo Bonzini 	int r = 1;
40859ce372b3SVitaly Kuznetsov 	u32 flags = vcpu->arch.apf.host_apf_flags;
4086c50d8ae3SPaolo Bonzini 
4087736c291cSSean Christopherson #ifndef CONFIG_X86_64
4088736c291cSSean Christopherson 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4089736c291cSSean Christopherson 	if (WARN_ON_ONCE(fault_address >> 32))
4090736c291cSSean Christopherson 		return -EFAULT;
4091736c291cSSean Christopherson #endif
4092736c291cSSean Christopherson 
4093c50d8ae3SPaolo Bonzini 	vcpu->arch.l1tf_flush_l1d = true;
40949ce372b3SVitaly Kuznetsov 	if (!flags) {
4095c50d8ae3SPaolo Bonzini 		trace_kvm_page_fault(fault_address, error_code);
4096c50d8ae3SPaolo Bonzini 
4097c50d8ae3SPaolo Bonzini 		if (kvm_event_needs_reinjection(vcpu))
4098c50d8ae3SPaolo Bonzini 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4099c50d8ae3SPaolo Bonzini 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4100c50d8ae3SPaolo Bonzini 				insn_len);
41019ce372b3SVitaly Kuznetsov 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
410268fd66f1SVitaly Kuznetsov 		vcpu->arch.apf.host_apf_flags = 0;
4103c50d8ae3SPaolo Bonzini 		local_irq_disable();
41046bca69adSThomas Gleixner 		kvm_async_pf_task_wait_schedule(fault_address);
4105c50d8ae3SPaolo Bonzini 		local_irq_enable();
41069ce372b3SVitaly Kuznetsov 	} else {
41079ce372b3SVitaly Kuznetsov 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4108c50d8ae3SPaolo Bonzini 	}
41099ce372b3SVitaly Kuznetsov 
4110c50d8ae3SPaolo Bonzini 	return r;
4111c50d8ae3SPaolo Bonzini }
4112c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4113c50d8ae3SPaolo Bonzini 
4114c501040aSPaolo Bonzini int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4115c50d8ae3SPaolo Bonzini {
41164326e57eSPaolo Bonzini 	while (fault->max_level > PG_LEVEL_4K) {
41174326e57eSPaolo Bonzini 		int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
41184326e57eSPaolo Bonzini 		gfn_t base = (fault->addr >> PAGE_SHIFT) & ~(page_num - 1);
4119c50d8ae3SPaolo Bonzini 
4120cb9b88c6SSean Christopherson 		if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4121cb9b88c6SSean Christopherson 			break;
41224326e57eSPaolo Bonzini 
41234326e57eSPaolo Bonzini 		--fault->max_level;
4124c50d8ae3SPaolo Bonzini 	}
4125c50d8ae3SPaolo Bonzini 
41264326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
4127c50d8ae3SPaolo Bonzini }
4128c50d8ae3SPaolo Bonzini 
412984a16226SSean Christopherson static void nonpaging_init_context(struct kvm_mmu *context)
4130c50d8ae3SPaolo Bonzini {
4131c50d8ae3SPaolo Bonzini 	context->page_fault = nonpaging_page_fault;
4132c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4133c50d8ae3SPaolo Bonzini 	context->sync_page = nonpaging_sync_page;
41345efac074SPaolo Bonzini 	context->invlpg = NULL;
4135c50d8ae3SPaolo Bonzini 	context->direct_map = true;
4136c50d8ae3SPaolo Bonzini }
4137c50d8ae3SPaolo Bonzini 
4138be01e8e2SSean Christopherson static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
41390be44352SSean Christopherson 				  union kvm_mmu_page_role role)
41400be44352SSean Christopherson {
4141be01e8e2SSean Christopherson 	return (role.direct || pgd == root->pgd) &&
41425499ea73SPaolo Bonzini 	       VALID_PAGE(root->hpa) &&
4143e47c4aeeSSean Christopherson 	       role.word == to_shadow_page(root->hpa)->role.word;
41440be44352SSean Christopherson }
41450be44352SSean Christopherson 
4146c50d8ae3SPaolo Bonzini /*
41475499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available,
41485499ea73SPaolo Bonzini  * and insert the current root as the MRU in the cache.
41495499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root and
41505499ea73SPaolo Bonzini  * true is returned.
41515499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid, the LRU root is
41525499ea73SPaolo Bonzini  * evicted to make room for the current root, and false is returned.
4153c50d8ae3SPaolo Bonzini  */
41545499ea73SPaolo Bonzini static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
41555499ea73SPaolo Bonzini 					      gpa_t new_pgd,
4156c50d8ae3SPaolo Bonzini 					      union kvm_mmu_page_role new_role)
4157c50d8ae3SPaolo Bonzini {
4158c50d8ae3SPaolo Bonzini 	uint i;
4159c50d8ae3SPaolo Bonzini 
4160b9e5603cSPaolo Bonzini 	if (is_root_usable(&mmu->root, new_pgd, new_role))
41610be44352SSean Christopherson 		return true;
41620be44352SSean Christopherson 
4163c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
41645499ea73SPaolo Bonzini 		/*
41655499ea73SPaolo Bonzini 		 * The swaps end up rotating the cache like this:
41665499ea73SPaolo Bonzini 		 *   C   0 1 2 3   (on entry to the function)
41675499ea73SPaolo Bonzini 		 *   0   C 1 2 3
41685499ea73SPaolo Bonzini 		 *   1   C 0 2 3
41695499ea73SPaolo Bonzini 		 *   2   C 0 1 3
41705499ea73SPaolo Bonzini 		 *   3   C 0 1 2   (on exit from the loop)
41715499ea73SPaolo Bonzini 		 */
4172b9e5603cSPaolo Bonzini 		swap(mmu->root, mmu->prev_roots[i]);
4173b9e5603cSPaolo Bonzini 		if (is_root_usable(&mmu->root, new_pgd, new_role))
41745499ea73SPaolo Bonzini 			return true;
4175c50d8ae3SPaolo Bonzini 	}
4176c50d8ae3SPaolo Bonzini 
41775499ea73SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
41785499ea73SPaolo Bonzini 	return false;
4179c50d8ae3SPaolo Bonzini }
4180c50d8ae3SPaolo Bonzini 
4181c50d8ae3SPaolo Bonzini /*
41825499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available.
41835499ea73SPaolo Bonzini  * On entry, mmu->root is invalid.
41845499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
41855499ea73SPaolo Bonzini  * of the cache becomes invalid, and true is returned.
41865499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid and false is returned.
41875499ea73SPaolo Bonzini  */
41885499ea73SPaolo Bonzini static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
41895499ea73SPaolo Bonzini 					     gpa_t new_pgd,
41905499ea73SPaolo Bonzini 					     union kvm_mmu_page_role new_role)
41915499ea73SPaolo Bonzini {
41925499ea73SPaolo Bonzini 	uint i;
41935499ea73SPaolo Bonzini 
41945499ea73SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
41955499ea73SPaolo Bonzini 		if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
41965499ea73SPaolo Bonzini 			goto hit;
41975499ea73SPaolo Bonzini 
41985499ea73SPaolo Bonzini 	return false;
41995499ea73SPaolo Bonzini 
42005499ea73SPaolo Bonzini hit:
42015499ea73SPaolo Bonzini 	swap(mmu->root, mmu->prev_roots[i]);
42025499ea73SPaolo Bonzini 	/* Bubble up the remaining roots.  */
42035499ea73SPaolo Bonzini 	for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
42045499ea73SPaolo Bonzini 		mmu->prev_roots[i] = mmu->prev_roots[i + 1];
42055499ea73SPaolo Bonzini 	mmu->prev_roots[i].hpa = INVALID_PAGE;
42065499ea73SPaolo Bonzini 	return true;
42075499ea73SPaolo Bonzini }
42085499ea73SPaolo Bonzini 
42095499ea73SPaolo Bonzini static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
42105499ea73SPaolo Bonzini 			    gpa_t new_pgd, union kvm_mmu_page_role new_role)
42115499ea73SPaolo Bonzini {
42125499ea73SPaolo Bonzini 	/*
42135499ea73SPaolo Bonzini 	 * For now, limit the caching to 64-bit hosts+VMs in order to avoid
4214c50d8ae3SPaolo Bonzini 	 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4215c50d8ae3SPaolo Bonzini 	 * later if necessary.
4216c50d8ae3SPaolo Bonzini 	 */
42175499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa) && !to_shadow_page(mmu->root.hpa))
42185499ea73SPaolo Bonzini 		kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4219c50d8ae3SPaolo Bonzini 
42205499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa))
42215499ea73SPaolo Bonzini 		return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
42225499ea73SPaolo Bonzini 	else
42235499ea73SPaolo Bonzini 		return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4224c50d8ae3SPaolo Bonzini }
4225c50d8ae3SPaolo Bonzini 
4226d2e5f333SPaolo Bonzini void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4227c50d8ae3SPaolo Bonzini {
42280c1c92f1SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
4229*7a458f0eSPaolo Bonzini 	union kvm_mmu_page_role new_role = mmu->root_role;
42300c1c92f1SPaolo Bonzini 
42315499ea73SPaolo Bonzini 	if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role)) {
42325499ea73SPaolo Bonzini 		/* kvm_mmu_ensure_valid_pgd will set up a new root.  */
4233b869855bSSean Christopherson 		return;
4234c50d8ae3SPaolo Bonzini 	}
4235c50d8ae3SPaolo Bonzini 
4236c50d8ae3SPaolo Bonzini 	/*
4237b869855bSSean Christopherson 	 * It's possible that the cached previous root page is obsolete because
4238b869855bSSean Christopherson 	 * of a change in the MMU generation number. However, changing the
4239527d5cd7SSean Christopherson 	 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4240527d5cd7SSean Christopherson 	 * which will free the root set here and allocate a new one.
4241b869855bSSean Christopherson 	 */
4242b869855bSSean Christopherson 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4243b869855bSSean Christopherson 
4244b5129100SSean Christopherson 	if (force_flush_and_sync_on_reuse) {
4245b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4246b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4247b5129100SSean Christopherson 	}
4248b869855bSSean Christopherson 
4249b869855bSSean Christopherson 	/*
4250b869855bSSean Christopherson 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4251b869855bSSean Christopherson 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
4252b869855bSSean Christopherson 	 * valid. So clear any cached MMIO info even when we don't need to sync
4253b869855bSSean Christopherson 	 * the shadow page tables.
4254c50d8ae3SPaolo Bonzini 	 */
4255c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4256c50d8ae3SPaolo Bonzini 
4257daa5b6c1SBen Gardon 	/*
4258daa5b6c1SBen Gardon 	 * If this is a direct root page, it doesn't have a write flooding
4259daa5b6c1SBen Gardon 	 * count. Otherwise, clear the write flooding count.
4260daa5b6c1SBen Gardon 	 */
4261daa5b6c1SBen Gardon 	if (!new_role.direct)
4262daa5b6c1SBen Gardon 		__clear_sp_write_flooding_count(
4263b9e5603cSPaolo Bonzini 				to_shadow_page(vcpu->arch.mmu->root.hpa));
4264c50d8ae3SPaolo Bonzini }
4265be01e8e2SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4266c50d8ae3SPaolo Bonzini 
4267c50d8ae3SPaolo Bonzini static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4268c50d8ae3SPaolo Bonzini {
4269c50d8ae3SPaolo Bonzini 	return kvm_read_cr3(vcpu);
4270c50d8ae3SPaolo Bonzini }
4271c50d8ae3SPaolo Bonzini 
4272c50d8ae3SPaolo Bonzini static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4273c3e5e415SLai Jiangshan 			   unsigned int access)
4274c50d8ae3SPaolo Bonzini {
4275c50d8ae3SPaolo Bonzini 	if (unlikely(is_mmio_spte(*sptep))) {
4276c50d8ae3SPaolo Bonzini 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4277c50d8ae3SPaolo Bonzini 			mmu_spte_clear_no_track(sptep);
4278c50d8ae3SPaolo Bonzini 			return true;
4279c50d8ae3SPaolo Bonzini 		}
4280c50d8ae3SPaolo Bonzini 
4281c50d8ae3SPaolo Bonzini 		mark_mmio_spte(vcpu, sptep, gfn, access);
4282c50d8ae3SPaolo Bonzini 		return true;
4283c50d8ae3SPaolo Bonzini 	}
4284c50d8ae3SPaolo Bonzini 
4285c50d8ae3SPaolo Bonzini 	return false;
4286c50d8ae3SPaolo Bonzini }
4287c50d8ae3SPaolo Bonzini 
4288c50d8ae3SPaolo Bonzini #define PTTYPE_EPT 18 /* arbitrary */
4289c50d8ae3SPaolo Bonzini #define PTTYPE PTTYPE_EPT
4290c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4291c50d8ae3SPaolo Bonzini #undef PTTYPE
4292c50d8ae3SPaolo Bonzini 
4293c50d8ae3SPaolo Bonzini #define PTTYPE 64
4294c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4295c50d8ae3SPaolo Bonzini #undef PTTYPE
4296c50d8ae3SPaolo Bonzini 
4297c50d8ae3SPaolo Bonzini #define PTTYPE 32
4298c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4299c50d8ae3SPaolo Bonzini #undef PTTYPE
4300c50d8ae3SPaolo Bonzini 
4301c50d8ae3SPaolo Bonzini static void
4302b705a277SSean Christopherson __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
43035b7f575cSSean Christopherson 			u64 pa_bits_rsvd, int level, bool nx, bool gbpages,
4304c50d8ae3SPaolo Bonzini 			bool pse, bool amd)
4305c50d8ae3SPaolo Bonzini {
4306c50d8ae3SPaolo Bonzini 	u64 gbpages_bit_rsvd = 0;
4307c50d8ae3SPaolo Bonzini 	u64 nonleaf_bit8_rsvd = 0;
43085b7f575cSSean Christopherson 	u64 high_bits_rsvd;
4309c50d8ae3SPaolo Bonzini 
4310c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = 0;
4311c50d8ae3SPaolo Bonzini 
4312c50d8ae3SPaolo Bonzini 	if (!gbpages)
4313c50d8ae3SPaolo Bonzini 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4314c50d8ae3SPaolo Bonzini 
43155b7f575cSSean Christopherson 	if (level == PT32E_ROOT_LEVEL)
43165b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
43175b7f575cSSean Christopherson 	else
43185b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
43195b7f575cSSean Christopherson 
43205b7f575cSSean Christopherson 	/* Note, NX doesn't exist in PDPTEs, this is handled below. */
43215b7f575cSSean Christopherson 	if (!nx)
43225b7f575cSSean Christopherson 		high_bits_rsvd |= rsvd_bits(63, 63);
43235b7f575cSSean Christopherson 
4324c50d8ae3SPaolo Bonzini 	/*
4325c50d8ae3SPaolo Bonzini 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4326c50d8ae3SPaolo Bonzini 	 * leaf entries) on AMD CPUs only.
4327c50d8ae3SPaolo Bonzini 	 */
4328c50d8ae3SPaolo Bonzini 	if (amd)
4329c50d8ae3SPaolo Bonzini 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4330c50d8ae3SPaolo Bonzini 
4331c50d8ae3SPaolo Bonzini 	switch (level) {
4332c50d8ae3SPaolo Bonzini 	case PT32_ROOT_LEVEL:
4333c50d8ae3SPaolo Bonzini 		/* no rsvd bits for 2 level 4K page table entries */
4334c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4335c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4336c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4337c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4338c50d8ae3SPaolo Bonzini 
4339c50d8ae3SPaolo Bonzini 		if (!pse) {
4340c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4341c50d8ae3SPaolo Bonzini 			break;
4342c50d8ae3SPaolo Bonzini 		}
4343c50d8ae3SPaolo Bonzini 
4344c50d8ae3SPaolo Bonzini 		if (is_cpuid_PSE36())
4345c50d8ae3SPaolo Bonzini 			/* 36bits PSE 4MB page */
4346c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4347c50d8ae3SPaolo Bonzini 		else
4348c50d8ae3SPaolo Bonzini 			/* 32 bits PSE 4MB page */
4349c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4350c50d8ae3SPaolo Bonzini 		break;
4351c50d8ae3SPaolo Bonzini 	case PT32E_ROOT_LEVEL:
43525b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
43535b7f575cSSean Christopherson 						   high_bits_rsvd |
43545b7f575cSSean Christopherson 						   rsvd_bits(5, 8) |
43555b7f575cSSean Christopherson 						   rsvd_bits(1, 2);	/* PDPTE */
43565b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;	/* PDE */
43575b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;	/* PTE */
43585b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4359c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20);	/* large page */
4360c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4361c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4362c50d8ae3SPaolo Bonzini 		break;
4363c50d8ae3SPaolo Bonzini 	case PT64_ROOT_5LEVEL:
43645b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
43655b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
43665b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
4367c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][4] =
4368c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][4];
4369df561f66SGustavo A. R. Silva 		fallthrough;
4370c50d8ae3SPaolo Bonzini 	case PT64_ROOT_4LEVEL:
43715b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
43725b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
43735b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
43745b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
43755b7f575cSSean Christopherson 						   gbpages_bit_rsvd;
43765b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
43775b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4378c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][3] =
4379c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][3];
43805b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
43815b7f575cSSean Christopherson 						   gbpages_bit_rsvd |
4382c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 29);
43835b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4384c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20); /* large page */
4385c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4386c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4387c50d8ae3SPaolo Bonzini 		break;
4388c50d8ae3SPaolo Bonzini 	}
4389c50d8ae3SPaolo Bonzini }
4390c50d8ae3SPaolo Bonzini 
439127de9250SSean Christopherson static bool guest_can_use_gbpages(struct kvm_vcpu *vcpu)
439227de9250SSean Christopherson {
439327de9250SSean Christopherson 	/*
439427de9250SSean Christopherson 	 * If TDP is enabled, let the guest use GBPAGES if they're supported in
439527de9250SSean Christopherson 	 * hardware.  The hardware page walker doesn't let KVM disable GBPAGES,
439627de9250SSean Christopherson 	 * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
439727de9250SSean Christopherson 	 * walk for performance and complexity reasons.  Not to mention KVM
439827de9250SSean Christopherson 	 * _can't_ solve the problem because GVA->GPA walks aren't visible to
439927de9250SSean Christopherson 	 * KVM once a TDP translation is installed.  Mimic hardware behavior so
440027de9250SSean Christopherson 	 * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
440127de9250SSean Christopherson 	 */
440227de9250SSean Christopherson 	return tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
440327de9250SSean Christopherson 			     guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES);
440427de9250SSean Christopherson }
440527de9250SSean Christopherson 
4406c50d8ae3SPaolo Bonzini static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4407c50d8ae3SPaolo Bonzini 				  struct kvm_mmu *context)
4408c50d8ae3SPaolo Bonzini {
4409b705a277SSean Christopherson 	__reset_rsvds_bits_mask(&context->guest_rsvd_check,
44105b7f575cSSean Christopherson 				vcpu->arch.reserved_gpa_bits,
441190599c28SSean Christopherson 				context->root_level, is_efer_nx(context),
441227de9250SSean Christopherson 				guest_can_use_gbpages(vcpu),
44134e9c0d80SSean Christopherson 				is_cr4_pse(context),
441423493d0aSSean Christopherson 				guest_cpuid_is_amd_or_hygon(vcpu));
4415c50d8ae3SPaolo Bonzini }
4416c50d8ae3SPaolo Bonzini 
4417c50d8ae3SPaolo Bonzini static void
4418c50d8ae3SPaolo Bonzini __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
441984ea5c09SLai Jiangshan 			    u64 pa_bits_rsvd, bool execonly, int huge_page_level)
4420c50d8ae3SPaolo Bonzini {
44215b7f575cSSean Christopherson 	u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
442284ea5c09SLai Jiangshan 	u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
4423c50d8ae3SPaolo Bonzini 	u64 bad_mt_xwr;
4424c50d8ae3SPaolo Bonzini 
442584ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_1G)
442684ea5c09SLai Jiangshan 		large_1g_rsvd = rsvd_bits(7, 7);
442784ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_2M)
442884ea5c09SLai Jiangshan 		large_2m_rsvd = rsvd_bits(7, 7);
442984ea5c09SLai Jiangshan 
44305b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
44315b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
443284ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
443384ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
44345b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4435c50d8ae3SPaolo Bonzini 
4436c50d8ae3SPaolo Bonzini 	/* large page */
4437c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4438c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
443984ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
444084ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
4441c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4442c50d8ae3SPaolo Bonzini 
4443c50d8ae3SPaolo Bonzini 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
4444c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
4445c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
4446c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
4447c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
4448c50d8ae3SPaolo Bonzini 	if (!execonly) {
4449c50d8ae3SPaolo Bonzini 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
4450c50d8ae3SPaolo Bonzini 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4451c50d8ae3SPaolo Bonzini 	}
4452c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
4453c50d8ae3SPaolo Bonzini }
4454c50d8ae3SPaolo Bonzini 
4455c50d8ae3SPaolo Bonzini static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
445684ea5c09SLai Jiangshan 		struct kvm_mmu *context, bool execonly, int huge_page_level)
4457c50d8ae3SPaolo Bonzini {
4458c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
445984ea5c09SLai Jiangshan 				    vcpu->arch.reserved_gpa_bits, execonly,
446084ea5c09SLai Jiangshan 				    huge_page_level);
4461c50d8ae3SPaolo Bonzini }
4462c50d8ae3SPaolo Bonzini 
44636f8e65a6SSean Christopherson static inline u64 reserved_hpa_bits(void)
44646f8e65a6SSean Christopherson {
44656f8e65a6SSean Christopherson 	return rsvd_bits(shadow_phys_bits, 63);
44666f8e65a6SSean Christopherson }
44676f8e65a6SSean Christopherson 
4468c50d8ae3SPaolo Bonzini /*
4469c50d8ae3SPaolo Bonzini  * the page table on host is the shadow page table for the page
4470c50d8ae3SPaolo Bonzini  * table in guest or amd nested guest, its mmu features completely
4471c50d8ae3SPaolo Bonzini  * follow the features in guest.
4472c50d8ae3SPaolo Bonzini  */
447316be1d12SSean Christopherson static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
447416be1d12SSean Christopherson 					struct kvm_mmu *context)
4475c50d8ae3SPaolo Bonzini {
44768c985b2dSSean Christopherson 	/* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
44778c985b2dSSean Christopherson 	bool is_amd = true;
44788c985b2dSSean Christopherson 	/* KVM doesn't use 2-level page tables for the shadow MMU. */
44798c985b2dSSean Christopherson 	bool is_pse = false;
4480c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4481c50d8ae3SPaolo Bonzini 	int i;
4482c50d8ae3SPaolo Bonzini 
44838c985b2dSSean Christopherson 	WARN_ON_ONCE(context->shadow_root_level < PT32E_ROOT_LEVEL);
44848c985b2dSSean Christopherson 
4485c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4486b705a277SSean Christopherson 	__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4487362505deSPaolo Bonzini 				context->shadow_root_level,
4488*7a458f0eSPaolo Bonzini 				context->root_role.efer_nx,
448927de9250SSean Christopherson 				guest_can_use_gbpages(vcpu), is_pse, is_amd);
4490c50d8ae3SPaolo Bonzini 
4491c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4492c50d8ae3SPaolo Bonzini 		return;
4493c50d8ae3SPaolo Bonzini 
4494c50d8ae3SPaolo Bonzini 	for (i = context->shadow_root_level; --i >= 0;) {
4495c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4496c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4497c50d8ae3SPaolo Bonzini 	}
4498c50d8ae3SPaolo Bonzini 
4499c50d8ae3SPaolo Bonzini }
4500c50d8ae3SPaolo Bonzini 
4501c50d8ae3SPaolo Bonzini static inline bool boot_cpu_is_amd(void)
4502c50d8ae3SPaolo Bonzini {
4503c50d8ae3SPaolo Bonzini 	WARN_ON_ONCE(!tdp_enabled);
4504c50d8ae3SPaolo Bonzini 	return shadow_x_mask == 0;
4505c50d8ae3SPaolo Bonzini }
4506c50d8ae3SPaolo Bonzini 
4507c50d8ae3SPaolo Bonzini /*
4508c50d8ae3SPaolo Bonzini  * the direct page table on host, use as much mmu features as
4509c50d8ae3SPaolo Bonzini  * possible, however, kvm currently does not do execution-protection.
4510c50d8ae3SPaolo Bonzini  */
4511c50d8ae3SPaolo Bonzini static void
4512e8f6e738SJinrong Liang reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
4513c50d8ae3SPaolo Bonzini {
4514c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4515c50d8ae3SPaolo Bonzini 	int i;
4516c50d8ae3SPaolo Bonzini 
4517c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4518c50d8ae3SPaolo Bonzini 
4519c50d8ae3SPaolo Bonzini 	if (boot_cpu_is_amd())
4520b705a277SSean Christopherson 		__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4521c50d8ae3SPaolo Bonzini 					context->shadow_root_level, false,
4522c50d8ae3SPaolo Bonzini 					boot_cpu_has(X86_FEATURE_GBPAGES),
45238c985b2dSSean Christopherson 					false, true);
4524c50d8ae3SPaolo Bonzini 	else
4525c50d8ae3SPaolo Bonzini 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
452684ea5c09SLai Jiangshan 					    reserved_hpa_bits(), false,
452784ea5c09SLai Jiangshan 					    max_huge_page_level);
4528c50d8ae3SPaolo Bonzini 
4529c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4530c50d8ae3SPaolo Bonzini 		return;
4531c50d8ae3SPaolo Bonzini 
4532c50d8ae3SPaolo Bonzini 	for (i = context->shadow_root_level; --i >= 0;) {
4533c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4534c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4535c50d8ae3SPaolo Bonzini 	}
4536c50d8ae3SPaolo Bonzini }
4537c50d8ae3SPaolo Bonzini 
4538c50d8ae3SPaolo Bonzini /*
4539c50d8ae3SPaolo Bonzini  * as the comments in reset_shadow_zero_bits_mask() except it
4540c50d8ae3SPaolo Bonzini  * is the shadow page table for intel nested guest.
4541c50d8ae3SPaolo Bonzini  */
4542c50d8ae3SPaolo Bonzini static void
4543e8f6e738SJinrong Liang reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
4544c50d8ae3SPaolo Bonzini {
4545c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
454684ea5c09SLai Jiangshan 				    reserved_hpa_bits(), execonly,
454784ea5c09SLai Jiangshan 				    max_huge_page_level);
4548c50d8ae3SPaolo Bonzini }
4549c50d8ae3SPaolo Bonzini 
4550c50d8ae3SPaolo Bonzini #define BYTE_MASK(access) \
4551c50d8ae3SPaolo Bonzini 	((1 & (access) ? 2 : 0) | \
4552c50d8ae3SPaolo Bonzini 	 (2 & (access) ? 4 : 0) | \
4553c50d8ae3SPaolo Bonzini 	 (3 & (access) ? 8 : 0) | \
4554c50d8ae3SPaolo Bonzini 	 (4 & (access) ? 16 : 0) | \
4555c50d8ae3SPaolo Bonzini 	 (5 & (access) ? 32 : 0) | \
4556c50d8ae3SPaolo Bonzini 	 (6 & (access) ? 64 : 0) | \
4557c50d8ae3SPaolo Bonzini 	 (7 & (access) ? 128 : 0))
4558c50d8ae3SPaolo Bonzini 
4559c50d8ae3SPaolo Bonzini 
4560c596f147SSean Christopherson static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
4561c50d8ae3SPaolo Bonzini {
4562c50d8ae3SPaolo Bonzini 	unsigned byte;
4563c50d8ae3SPaolo Bonzini 
4564c50d8ae3SPaolo Bonzini 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4565c50d8ae3SPaolo Bonzini 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4566c50d8ae3SPaolo Bonzini 	const u8 u = BYTE_MASK(ACC_USER_MASK);
4567c50d8ae3SPaolo Bonzini 
4568c596f147SSean Christopherson 	bool cr4_smep = is_cr4_smep(mmu);
4569c596f147SSean Christopherson 	bool cr4_smap = is_cr4_smap(mmu);
4570c596f147SSean Christopherson 	bool cr0_wp = is_cr0_wp(mmu);
457190599c28SSean Christopherson 	bool efer_nx = is_efer_nx(mmu);
4572c50d8ae3SPaolo Bonzini 
4573c50d8ae3SPaolo Bonzini 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4574c50d8ae3SPaolo Bonzini 		unsigned pfec = byte << 1;
4575c50d8ae3SPaolo Bonzini 
4576c50d8ae3SPaolo Bonzini 		/*
4577c50d8ae3SPaolo Bonzini 		 * Each "*f" variable has a 1 bit for each UWX value
4578c50d8ae3SPaolo Bonzini 		 * that causes a fault with the given PFEC.
4579c50d8ae3SPaolo Bonzini 		 */
4580c50d8ae3SPaolo Bonzini 
4581c50d8ae3SPaolo Bonzini 		/* Faults from writes to non-writable pages */
4582c50d8ae3SPaolo Bonzini 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4583c50d8ae3SPaolo Bonzini 		/* Faults from user mode accesses to supervisor pages */
4584c50d8ae3SPaolo Bonzini 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4585c50d8ae3SPaolo Bonzini 		/* Faults from fetches of non-executable pages*/
4586c50d8ae3SPaolo Bonzini 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4587c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode fetches of user pages */
4588c50d8ae3SPaolo Bonzini 		u8 smepf = 0;
4589c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode accesses of user pages */
4590c50d8ae3SPaolo Bonzini 		u8 smapf = 0;
4591c50d8ae3SPaolo Bonzini 
4592c50d8ae3SPaolo Bonzini 		if (!ept) {
4593c50d8ae3SPaolo Bonzini 			/* Faults from kernel mode accesses to user pages */
4594c50d8ae3SPaolo Bonzini 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4595c50d8ae3SPaolo Bonzini 
4596c50d8ae3SPaolo Bonzini 			/* Not really needed: !nx will cause pte.nx to fault */
459790599c28SSean Christopherson 			if (!efer_nx)
4598c50d8ae3SPaolo Bonzini 				ff = 0;
4599c50d8ae3SPaolo Bonzini 
4600c50d8ae3SPaolo Bonzini 			/* Allow supervisor writes if !cr0.wp */
4601c50d8ae3SPaolo Bonzini 			if (!cr0_wp)
4602c50d8ae3SPaolo Bonzini 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4603c50d8ae3SPaolo Bonzini 
4604c50d8ae3SPaolo Bonzini 			/* Disallow supervisor fetches of user code if cr4.smep */
4605c50d8ae3SPaolo Bonzini 			if (cr4_smep)
4606c50d8ae3SPaolo Bonzini 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4607c50d8ae3SPaolo Bonzini 
4608c50d8ae3SPaolo Bonzini 			/*
4609c50d8ae3SPaolo Bonzini 			 * SMAP:kernel-mode data accesses from user-mode
4610c50d8ae3SPaolo Bonzini 			 * mappings should fault. A fault is considered
4611c50d8ae3SPaolo Bonzini 			 * as a SMAP violation if all of the following
4612c50d8ae3SPaolo Bonzini 			 * conditions are true:
4613c50d8ae3SPaolo Bonzini 			 *   - X86_CR4_SMAP is set in CR4
4614c50d8ae3SPaolo Bonzini 			 *   - A user page is accessed
4615c50d8ae3SPaolo Bonzini 			 *   - The access is not a fetch
46164f4aa80eSLai Jiangshan 			 *   - The access is supervisor mode
46174f4aa80eSLai Jiangshan 			 *   - If implicit supervisor access or X86_EFLAGS_AC is clear
4618c50d8ae3SPaolo Bonzini 			 *
461994b4a2f1SLai Jiangshan 			 * Here, we cover the first four conditions.
462094b4a2f1SLai Jiangshan 			 * The fifth is computed dynamically in permission_fault();
4621c50d8ae3SPaolo Bonzini 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4622c50d8ae3SPaolo Bonzini 			 * *not* subject to SMAP restrictions.
4623c50d8ae3SPaolo Bonzini 			 */
4624c50d8ae3SPaolo Bonzini 			if (cr4_smap)
4625c50d8ae3SPaolo Bonzini 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4626c50d8ae3SPaolo Bonzini 		}
4627c50d8ae3SPaolo Bonzini 
4628c50d8ae3SPaolo Bonzini 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4629c50d8ae3SPaolo Bonzini 	}
4630c50d8ae3SPaolo Bonzini }
4631c50d8ae3SPaolo Bonzini 
4632c50d8ae3SPaolo Bonzini /*
4633c50d8ae3SPaolo Bonzini * PKU is an additional mechanism by which the paging controls access to
4634c50d8ae3SPaolo Bonzini * user-mode addresses based on the value in the PKRU register.  Protection
4635c50d8ae3SPaolo Bonzini * key violations are reported through a bit in the page fault error code.
4636c50d8ae3SPaolo Bonzini * Unlike other bits of the error code, the PK bit is not known at the
4637c50d8ae3SPaolo Bonzini * call site of e.g. gva_to_gpa; it must be computed directly in
4638c50d8ae3SPaolo Bonzini * permission_fault based on two bits of PKRU, on some machine state (CR4,
4639c50d8ae3SPaolo Bonzini * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4640c50d8ae3SPaolo Bonzini *
4641c50d8ae3SPaolo Bonzini * In particular the following conditions come from the error code, the
4642c50d8ae3SPaolo Bonzini * page tables and the machine state:
4643c50d8ae3SPaolo Bonzini * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4644c50d8ae3SPaolo Bonzini * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4645c50d8ae3SPaolo Bonzini * - PK is always zero if U=0 in the page tables
4646c50d8ae3SPaolo Bonzini * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4647c50d8ae3SPaolo Bonzini *
4648c50d8ae3SPaolo Bonzini * The PKRU bitmask caches the result of these four conditions.  The error
4649c50d8ae3SPaolo Bonzini * code (minus the P bit) and the page table's U bit form an index into the
4650c50d8ae3SPaolo Bonzini * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
4651c50d8ae3SPaolo Bonzini * with the two bits of the PKRU register corresponding to the protection key.
4652c50d8ae3SPaolo Bonzini * For the first three conditions above the bits will be 00, thus masking
4653c50d8ae3SPaolo Bonzini * away both AD and WD.  For all reads or if the last condition holds, WD
4654c50d8ae3SPaolo Bonzini * only will be masked away.
4655c50d8ae3SPaolo Bonzini */
46562e4c0661SSean Christopherson static void update_pkru_bitmask(struct kvm_mmu *mmu)
4657c50d8ae3SPaolo Bonzini {
4658c50d8ae3SPaolo Bonzini 	unsigned bit;
4659c50d8ae3SPaolo Bonzini 	bool wp;
4660c50d8ae3SPaolo Bonzini 
4661c50d8ae3SPaolo Bonzini 	mmu->pkru_mask = 0;
4662a3ca5281SChenyi Qiang 
4663a3ca5281SChenyi Qiang 	if (!is_cr4_pke(mmu))
4664c50d8ae3SPaolo Bonzini 		return;
4665c50d8ae3SPaolo Bonzini 
46662e4c0661SSean Christopherson 	wp = is_cr0_wp(mmu);
4667c50d8ae3SPaolo Bonzini 
4668c50d8ae3SPaolo Bonzini 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4669c50d8ae3SPaolo Bonzini 		unsigned pfec, pkey_bits;
4670c50d8ae3SPaolo Bonzini 		bool check_pkey, check_write, ff, uf, wf, pte_user;
4671c50d8ae3SPaolo Bonzini 
4672c50d8ae3SPaolo Bonzini 		pfec = bit << 1;
4673c50d8ae3SPaolo Bonzini 		ff = pfec & PFERR_FETCH_MASK;
4674c50d8ae3SPaolo Bonzini 		uf = pfec & PFERR_USER_MASK;
4675c50d8ae3SPaolo Bonzini 		wf = pfec & PFERR_WRITE_MASK;
4676c50d8ae3SPaolo Bonzini 
4677c50d8ae3SPaolo Bonzini 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
4678c50d8ae3SPaolo Bonzini 		pte_user = pfec & PFERR_RSVD_MASK;
4679c50d8ae3SPaolo Bonzini 
4680c50d8ae3SPaolo Bonzini 		/*
4681c50d8ae3SPaolo Bonzini 		 * Only need to check the access which is not an
4682c50d8ae3SPaolo Bonzini 		 * instruction fetch and is to a user page.
4683c50d8ae3SPaolo Bonzini 		 */
4684c50d8ae3SPaolo Bonzini 		check_pkey = (!ff && pte_user);
4685c50d8ae3SPaolo Bonzini 		/*
4686c50d8ae3SPaolo Bonzini 		 * write access is controlled by PKRU if it is a
4687c50d8ae3SPaolo Bonzini 		 * user access or CR0.WP = 1.
4688c50d8ae3SPaolo Bonzini 		 */
4689c50d8ae3SPaolo Bonzini 		check_write = check_pkey && wf && (uf || wp);
4690c50d8ae3SPaolo Bonzini 
4691c50d8ae3SPaolo Bonzini 		/* PKRU.AD stops both read and write access. */
4692c50d8ae3SPaolo Bonzini 		pkey_bits = !!check_pkey;
4693c50d8ae3SPaolo Bonzini 		/* PKRU.WD stops write access. */
4694c50d8ae3SPaolo Bonzini 		pkey_bits |= (!!check_write) << 1;
4695c50d8ae3SPaolo Bonzini 
4696c50d8ae3SPaolo Bonzini 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4697c50d8ae3SPaolo Bonzini 	}
4698c50d8ae3SPaolo Bonzini }
4699c50d8ae3SPaolo Bonzini 
4700533f9a4bSSean Christopherson static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
4701533f9a4bSSean Christopherson 					struct kvm_mmu *mmu)
4702c50d8ae3SPaolo Bonzini {
4703533f9a4bSSean Christopherson 	if (!is_cr0_pg(mmu))
4704533f9a4bSSean Christopherson 		return;
4705c50d8ae3SPaolo Bonzini 
4706533f9a4bSSean Christopherson 	reset_rsvds_bits_mask(vcpu, mmu);
4707533f9a4bSSean Christopherson 	update_permission_bitmask(mmu, false);
4708533f9a4bSSean Christopherson 	update_pkru_bitmask(mmu);
4709c50d8ae3SPaolo Bonzini }
4710c50d8ae3SPaolo Bonzini 
4711fe660f72SSean Christopherson static void paging64_init_context(struct kvm_mmu *context)
4712c50d8ae3SPaolo Bonzini {
4713c50d8ae3SPaolo Bonzini 	context->page_fault = paging64_page_fault;
4714c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging64_gva_to_gpa;
4715c50d8ae3SPaolo Bonzini 	context->sync_page = paging64_sync_page;
4716c50d8ae3SPaolo Bonzini 	context->invlpg = paging64_invlpg;
4717c50d8ae3SPaolo Bonzini 	context->direct_map = false;
4718c50d8ae3SPaolo Bonzini }
4719c50d8ae3SPaolo Bonzini 
472084a16226SSean Christopherson static void paging32_init_context(struct kvm_mmu *context)
4721c50d8ae3SPaolo Bonzini {
4722c50d8ae3SPaolo Bonzini 	context->page_fault = paging32_page_fault;
4723c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging32_gva_to_gpa;
4724c50d8ae3SPaolo Bonzini 	context->sync_page = paging32_sync_page;
4725c50d8ae3SPaolo Bonzini 	context->invlpg = paging32_invlpg;
4726c50d8ae3SPaolo Bonzini 	context->direct_map = false;
4727c50d8ae3SPaolo Bonzini }
4728c50d8ae3SPaolo Bonzini 
4729e5ed0fb0SPaolo Bonzini static union kvm_mmu_role
4730e5ed0fb0SPaolo Bonzini kvm_calc_cpu_role(struct kvm_vcpu *vcpu, const struct kvm_mmu_role_regs *regs)
4731e5ed0fb0SPaolo Bonzini {
4732e5ed0fb0SPaolo Bonzini 	union kvm_mmu_role role = {0};
4733e5ed0fb0SPaolo Bonzini 
4734e5ed0fb0SPaolo Bonzini 	role.base.access = ACC_ALL;
4735e5ed0fb0SPaolo Bonzini 	role.base.smm = is_smm(vcpu);
4736e5ed0fb0SPaolo Bonzini 	role.base.guest_mode = is_guest_mode(vcpu);
4737e5ed0fb0SPaolo Bonzini 	role.ext.valid = 1;
4738e5ed0fb0SPaolo Bonzini 
4739e5ed0fb0SPaolo Bonzini 	if (!____is_cr0_pg(regs)) {
4740e5ed0fb0SPaolo Bonzini 		role.base.direct = 1;
4741e5ed0fb0SPaolo Bonzini 		return role;
4742e5ed0fb0SPaolo Bonzini 	}
4743e5ed0fb0SPaolo Bonzini 
4744e5ed0fb0SPaolo Bonzini 	role.base.efer_nx = ____is_efer_nx(regs);
4745e5ed0fb0SPaolo Bonzini 	role.base.cr0_wp = ____is_cr0_wp(regs);
4746e5ed0fb0SPaolo Bonzini 	role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
4747e5ed0fb0SPaolo Bonzini 	role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
4748e5ed0fb0SPaolo Bonzini 	role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
474960f3cb60SPaolo Bonzini 
475060f3cb60SPaolo Bonzini 	if (____is_efer_lma(regs))
475160f3cb60SPaolo Bonzini 		role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
475260f3cb60SPaolo Bonzini 							: PT64_ROOT_4LEVEL;
475360f3cb60SPaolo Bonzini 	else if (____is_cr4_pae(regs))
475460f3cb60SPaolo Bonzini 		role.base.level = PT32E_ROOT_LEVEL;
475560f3cb60SPaolo Bonzini 	else
475660f3cb60SPaolo Bonzini 		role.base.level = PT32_ROOT_LEVEL;
4757e5ed0fb0SPaolo Bonzini 
4758e5ed0fb0SPaolo Bonzini 	role.ext.cr0_pg = 1;
4759e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pae = ____is_cr4_pae(regs);
4760e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smep = ____is_cr4_smep(regs);
4761e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smap = ____is_cr4_smap(regs);
4762e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pse = ____is_cr4_pse(regs);
4763e5ed0fb0SPaolo Bonzini 
4764e5ed0fb0SPaolo Bonzini 	/* PKEY and LA57 are active iff long mode is active. */
4765e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
4766e5ed0fb0SPaolo Bonzini 	role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
4767e5ed0fb0SPaolo Bonzini 	role.ext.efer_lma = ____is_efer_lma(regs);
4768e5ed0fb0SPaolo Bonzini 	return role;
4769e5ed0fb0SPaolo Bonzini }
4770e5ed0fb0SPaolo Bonzini 
4771d468d94bSSean Christopherson static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
4772d468d94bSSean Christopherson {
4773746700d2SWei Huang 	/* tdp_root_level is architecture forced level, use it if nonzero */
4774746700d2SWei Huang 	if (tdp_root_level)
4775746700d2SWei Huang 		return tdp_root_level;
4776746700d2SWei Huang 
4777d468d94bSSean Christopherson 	/* Use 5-level TDP if and only if it's useful/necessary. */
477883013059SSean Christopherson 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
4779d468d94bSSean Christopherson 		return 4;
4780d468d94bSSean Christopherson 
478183013059SSean Christopherson 	return max_tdp_level;
4782d468d94bSSean Christopherson }
4783d468d94bSSean Christopherson 
4784*7a458f0eSPaolo Bonzini static union kvm_mmu_page_role
47858626c120SSean Christopherson kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
47862ba67677SPaolo Bonzini 				union kvm_mmu_role cpu_role)
4787c50d8ae3SPaolo Bonzini {
4788*7a458f0eSPaolo Bonzini 	union kvm_mmu_page_role role = {0};
4789c50d8ae3SPaolo Bonzini 
4790*7a458f0eSPaolo Bonzini 	role.access = ACC_ALL;
4791*7a458f0eSPaolo Bonzini 	role.cr0_wp = true;
4792*7a458f0eSPaolo Bonzini 	role.efer_nx = true;
4793*7a458f0eSPaolo Bonzini 	role.smm = cpu_role.base.smm;
4794*7a458f0eSPaolo Bonzini 	role.guest_mode = cpu_role.base.guest_mode;
4795*7a458f0eSPaolo Bonzini 	role.ad_disabled = (shadow_accessed_mask == 0);
4796*7a458f0eSPaolo Bonzini 	role.level = kvm_mmu_get_tdp_level(vcpu);
4797*7a458f0eSPaolo Bonzini 	role.direct = true;
4798*7a458f0eSPaolo Bonzini 	role.has_4_byte_gpte = false;
4799c50d8ae3SPaolo Bonzini 
4800c50d8ae3SPaolo Bonzini 	return role;
4801c50d8ae3SPaolo Bonzini }
4802c50d8ae3SPaolo Bonzini 
480339e7e2bfSPaolo Bonzini static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
480439e7e2bfSPaolo Bonzini 			     const struct kvm_mmu_role_regs *regs)
4805c50d8ae3SPaolo Bonzini {
48068c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
4807e5ed0fb0SPaolo Bonzini 	union kvm_mmu_role cpu_role = kvm_calc_cpu_role(vcpu, regs);
4808*7a458f0eSPaolo Bonzini 	union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
4809c50d8ae3SPaolo Bonzini 
4810e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
4811*7a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
4812c50d8ae3SPaolo Bonzini 		return;
4813c50d8ae3SPaolo Bonzini 
4814e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
4815*7a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
48167a02674dSSean Christopherson 	context->page_fault = kvm_tdp_page_fault;
4817c50d8ae3SPaolo Bonzini 	context->sync_page = nonpaging_sync_page;
48185efac074SPaolo Bonzini 	context->invlpg = NULL;
4819d468d94bSSean Christopherson 	context->shadow_root_level = kvm_mmu_get_tdp_level(vcpu);
4820c50d8ae3SPaolo Bonzini 	context->direct_map = true;
4821d8dd54e0SSean Christopherson 	context->get_guest_pgd = get_cr3;
4822c50d8ae3SPaolo Bonzini 	context->get_pdptr = kvm_pdptr_read;
4823c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
482460f3cb60SPaolo Bonzini 	context->root_level = cpu_role.base.level;
4825c50d8ae3SPaolo Bonzini 
482636f26787SSean Christopherson 	if (!is_cr0_pg(context))
4827c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = nonpaging_gva_to_gpa;
482836f26787SSean Christopherson 	else if (is_cr4_pae(context))
4829c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging64_gva_to_gpa;
4830f4bd6f73SSean Christopherson 	else
4831c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging32_gva_to_gpa;
4832c50d8ae3SPaolo Bonzini 
4833533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
4834e8f6e738SJinrong Liang 	reset_tdp_shadow_zero_bits_mask(context);
4835c50d8ae3SPaolo Bonzini }
4836c50d8ae3SPaolo Bonzini 
4837*7a458f0eSPaolo Bonzini static union kvm_mmu_page_role
48388626c120SSean Christopherson kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu,
4839f417e145SPaolo Bonzini 				   union kvm_mmu_role cpu_role)
484059505b55SSean Christopherson {
4841*7a458f0eSPaolo Bonzini 	union kvm_mmu_page_role role;
484259505b55SSean Christopherson 
4843*7a458f0eSPaolo Bonzini 	role = cpu_role.base;
4844f417e145SPaolo Bonzini 	if (!cpu_role.ext.efer_lma)
4845*7a458f0eSPaolo Bonzini 		role.level = PT32E_ROOT_LEVEL;
4846f417e145SPaolo Bonzini 	else if (cpu_role.ext.cr4_la57)
4847*7a458f0eSPaolo Bonzini 		role.level = PT64_ROOT_5LEVEL;
4848c50d8ae3SPaolo Bonzini 	else
4849*7a458f0eSPaolo Bonzini 		role.level = PT64_ROOT_4LEVEL;
4850c50d8ae3SPaolo Bonzini 
4851362505deSPaolo Bonzini 	/*
4852362505deSPaolo Bonzini 	 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
4853362505deSPaolo Bonzini 	 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
4854362505deSPaolo Bonzini 	 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
4855362505deSPaolo Bonzini 	 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
4856362505deSPaolo Bonzini 	 * The iTLB multi-hit workaround can be toggled at any time, so assume
4857362505deSPaolo Bonzini 	 * NX can be used by any non-nested shadow MMU to avoid having to reset
4858362505deSPaolo Bonzini 	 * MMU contexts.
4859362505deSPaolo Bonzini 	 */
4860*7a458f0eSPaolo Bonzini 	role.efer_nx = true;
4861c50d8ae3SPaolo Bonzini 	return role;
4862c50d8ae3SPaolo Bonzini }
4863c50d8ae3SPaolo Bonzini 
48648c008659SPaolo Bonzini static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
4865e5ed0fb0SPaolo Bonzini 				    union kvm_mmu_role cpu_role,
4866*7a458f0eSPaolo Bonzini 				    union kvm_mmu_page_role root_role)
4867c50d8ae3SPaolo Bonzini {
4868e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
4869*7a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
487018db1b17SSean Christopherson 		return;
4871c50d8ae3SPaolo Bonzini 
4872e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
4873*7a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
487418db1b17SSean Christopherson 
487536f26787SSean Christopherson 	if (!is_cr0_pg(context))
487684a16226SSean Christopherson 		nonpaging_init_context(context);
487736f26787SSean Christopherson 	else if (is_cr4_pae(context))
4878fe660f72SSean Christopherson 		paging64_init_context(context);
4879c50d8ae3SPaolo Bonzini 	else
488084a16226SSean Christopherson 		paging32_init_context(context);
4881e5ed0fb0SPaolo Bonzini 	context->root_level = cpu_role.base.level;
4882c50d8ae3SPaolo Bonzini 
4883533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
4884*7a458f0eSPaolo Bonzini 	context->shadow_root_level = root_role.level;
4885d555f705SSean Christopherson 
4886c50d8ae3SPaolo Bonzini 	reset_shadow_zero_bits_mask(vcpu, context);
4887c50d8ae3SPaolo Bonzini }
48880f04a2acSVitaly Kuznetsov 
4889594e91a1SSean Christopherson static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
489082ffa13fSPaolo Bonzini 				const struct kvm_mmu_role_regs *regs)
48910f04a2acSVitaly Kuznetsov {
48928c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
4893e5ed0fb0SPaolo Bonzini 	union kvm_mmu_role cpu_role = kvm_calc_cpu_role(vcpu, regs);
4894*7a458f0eSPaolo Bonzini 	union kvm_mmu_page_role root_role =
4895f417e145SPaolo Bonzini 		kvm_calc_shadow_mmu_root_page_role(vcpu, cpu_role);
48960f04a2acSVitaly Kuznetsov 
4897*7a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
48980f04a2acSVitaly Kuznetsov }
48990f04a2acSVitaly Kuznetsov 
4900*7a458f0eSPaolo Bonzini static union kvm_mmu_page_role
49018626c120SSean Christopherson kvm_calc_shadow_npt_root_page_role(struct kvm_vcpu *vcpu,
4902f417e145SPaolo Bonzini 				   union kvm_mmu_role cpu_role)
490359505b55SSean Christopherson {
4904*7a458f0eSPaolo Bonzini 	union kvm_mmu_page_role role;
490559505b55SSean Christopherson 
490619b5dcc3SPaolo Bonzini 	WARN_ON_ONCE(cpu_role.base.direct);
4907*7a458f0eSPaolo Bonzini 	role = cpu_role.base;
4908*7a458f0eSPaolo Bonzini 	role.level = kvm_mmu_get_tdp_level(vcpu);
490959505b55SSean Christopherson 	return role;
491059505b55SSean Christopherson }
491159505b55SSean Christopherson 
4912dbc4739bSSean Christopherson void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
4913dbc4739bSSean Christopherson 			     unsigned long cr4, u64 efer, gpa_t nested_cr3)
49140f04a2acSVitaly Kuznetsov {
49158c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
4916594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
4917594e91a1SSean Christopherson 		.cr0 = cr0,
491828f091bcSPaolo Bonzini 		.cr4 = cr4 & ~X86_CR4_PKE,
4919594e91a1SSean Christopherson 		.efer = efer,
4920594e91a1SSean Christopherson 	};
4921e5ed0fb0SPaolo Bonzini 	union kvm_mmu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
4922*7a458f0eSPaolo Bonzini 	union kvm_mmu_page_role root_role = kvm_calc_shadow_npt_root_page_role(vcpu, cpu_role);
49230f04a2acSVitaly Kuznetsov 
4924*7a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
4925d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, nested_cr3);
49260f04a2acSVitaly Kuznetsov }
49270f04a2acSVitaly Kuznetsov EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
4928c50d8ae3SPaolo Bonzini 
4929c50d8ae3SPaolo Bonzini static union kvm_mmu_role
4930c50d8ae3SPaolo Bonzini kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4931bb1fcc70SSean Christopherson 				   bool execonly, u8 level)
4932c50d8ae3SPaolo Bonzini {
4933c50d8ae3SPaolo Bonzini 	union kvm_mmu_role role = {0};
4934c50d8ae3SPaolo Bonzini 
4935daed87b8SPaolo Bonzini 	/*
4936daed87b8SPaolo Bonzini 	 * KVM does not support SMM transfer monitors, and consequently does not
4937daed87b8SPaolo Bonzini 	 * support the "entry to SMM" control either.  role.base.smm is always 0.
4938daed87b8SPaolo Bonzini 	 */
4939daed87b8SPaolo Bonzini 	WARN_ON_ONCE(is_smm(vcpu));
4940bb1fcc70SSean Christopherson 	role.base.level = level;
4941bb3b394dSLai Jiangshan 	role.base.has_4_byte_gpte = false;
4942c50d8ae3SPaolo Bonzini 	role.base.direct = false;
4943c50d8ae3SPaolo Bonzini 	role.base.ad_disabled = !accessed_dirty;
4944c50d8ae3SPaolo Bonzini 	role.base.guest_mode = true;
4945c50d8ae3SPaolo Bonzini 	role.base.access = ACC_ALL;
4946c50d8ae3SPaolo Bonzini 
4947cd6767c3SSean Christopherson 	role.ext.word = 0;
4948c50d8ae3SPaolo Bonzini 	role.ext.execonly = execonly;
4949cd6767c3SSean Christopherson 	role.ext.valid = 1;
4950c50d8ae3SPaolo Bonzini 
4951c50d8ae3SPaolo Bonzini 	return role;
4952c50d8ae3SPaolo Bonzini }
4953c50d8ae3SPaolo Bonzini 
4954c50d8ae3SPaolo Bonzini void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4955cc022ae1SLai Jiangshan 			     int huge_page_level, bool accessed_dirty,
4956cc022ae1SLai Jiangshan 			     gpa_t new_eptp)
4957c50d8ae3SPaolo Bonzini {
49588c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
4959bb1fcc70SSean Christopherson 	u8 level = vmx_eptp_page_walk_level(new_eptp);
4960e5ed0fb0SPaolo Bonzini 	union kvm_mmu_role new_mode =
4961c50d8ae3SPaolo Bonzini 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4962bb1fcc70SSean Christopherson 						   execonly, level);
4963c50d8ae3SPaolo Bonzini 
4964e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 != context->cpu_role.as_u64) {
4965e5ed0fb0SPaolo Bonzini 		/* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
4966e5ed0fb0SPaolo Bonzini 		context->cpu_role.as_u64 = new_mode.as_u64;
4967*7a458f0eSPaolo Bonzini 		context->root_role.word = new_mode.base.word;
496818db1b17SSean Christopherson 
4969bb1fcc70SSean Christopherson 		context->shadow_root_level = level;
4970c50d8ae3SPaolo Bonzini 
4971c50d8ae3SPaolo Bonzini 		context->page_fault = ept_page_fault;
4972c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = ept_gva_to_gpa;
4973c50d8ae3SPaolo Bonzini 		context->sync_page = ept_sync_page;
4974c50d8ae3SPaolo Bonzini 		context->invlpg = ept_invlpg;
4975bb1fcc70SSean Christopherson 		context->root_level = level;
4976c50d8ae3SPaolo Bonzini 		context->direct_map = false;
4977c596f147SSean Christopherson 		update_permission_bitmask(context, true);
497828f091bcSPaolo Bonzini 		context->pkru_mask = 0;
4979cc022ae1SLai Jiangshan 		reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
4980e8f6e738SJinrong Liang 		reset_ept_shadow_zero_bits_mask(context, execonly);
4981c50d8ae3SPaolo Bonzini 	}
49823cffc89dSPaolo Bonzini 
4983d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, new_eptp);
49843cffc89dSPaolo Bonzini }
4985c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4986c50d8ae3SPaolo Bonzini 
498739e7e2bfSPaolo Bonzini static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
498839e7e2bfSPaolo Bonzini 			     const struct kvm_mmu_role_regs *regs)
4989c50d8ae3SPaolo Bonzini {
49908c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
4991c50d8ae3SPaolo Bonzini 
499239e7e2bfSPaolo Bonzini 	kvm_init_shadow_mmu(vcpu, regs);
4993929d1cfaSPaolo Bonzini 
4994d8dd54e0SSean Christopherson 	context->get_guest_pgd     = get_cr3;
4995c50d8ae3SPaolo Bonzini 	context->get_pdptr         = kvm_pdptr_read;
4996c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
4997c50d8ae3SPaolo Bonzini }
4998c50d8ae3SPaolo Bonzini 
499939e7e2bfSPaolo Bonzini static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
500039e7e2bfSPaolo Bonzini 				const struct kvm_mmu_role_regs *regs)
5001c50d8ae3SPaolo Bonzini {
5002e5ed0fb0SPaolo Bonzini 	union kvm_mmu_role new_mode = kvm_calc_cpu_role(vcpu, regs);
5003c50d8ae3SPaolo Bonzini 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5004c50d8ae3SPaolo Bonzini 
5005e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5006c50d8ae3SPaolo Bonzini 		return;
5007c50d8ae3SPaolo Bonzini 
5008e5ed0fb0SPaolo Bonzini 	g_context->cpu_role.as_u64   = new_mode.as_u64;
5009d8dd54e0SSean Christopherson 	g_context->get_guest_pgd     = get_cr3;
5010c50d8ae3SPaolo Bonzini 	g_context->get_pdptr         = kvm_pdptr_read;
5011c50d8ae3SPaolo Bonzini 	g_context->inject_page_fault = kvm_inject_page_fault;
5012e5ed0fb0SPaolo Bonzini 	g_context->root_level        = new_mode.base.level;
5013c50d8ae3SPaolo Bonzini 
5014c50d8ae3SPaolo Bonzini 	/*
50155efac074SPaolo Bonzini 	 * L2 page tables are never shadowed, so there is no need to sync
50165efac074SPaolo Bonzini 	 * SPTEs.
50175efac074SPaolo Bonzini 	 */
50185efac074SPaolo Bonzini 	g_context->invlpg            = NULL;
50195efac074SPaolo Bonzini 
50205efac074SPaolo Bonzini 	/*
5021c50d8ae3SPaolo Bonzini 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5022c50d8ae3SPaolo Bonzini 	 * L1's nested page tables (e.g. EPT12). The nested translation
5023c50d8ae3SPaolo Bonzini 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5024c50d8ae3SPaolo Bonzini 	 * L2's page tables as the first level of translation and L1's
5025c50d8ae3SPaolo Bonzini 	 * nested page tables as the second level of translation. Basically
5026c50d8ae3SPaolo Bonzini 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5027c50d8ae3SPaolo Bonzini 	 */
5028fa4b5588SSean Christopherson 	if (!is_paging(vcpu))
50291f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5030fa4b5588SSean Christopherson 	else if (is_long_mode(vcpu))
50311f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5032fa4b5588SSean Christopherson 	else if (is_pae(vcpu))
50331f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5034fa4b5588SSean Christopherson 	else
50351f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging32_gva_to_gpa;
5036fa4b5588SSean Christopherson 
5037533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, g_context);
5038c50d8ae3SPaolo Bonzini }
5039c50d8ae3SPaolo Bonzini 
5040c9060662SSean Christopherson void kvm_init_mmu(struct kvm_vcpu *vcpu)
5041c50d8ae3SPaolo Bonzini {
504239e7e2bfSPaolo Bonzini 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
504339e7e2bfSPaolo Bonzini 
5044c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
504539e7e2bfSPaolo Bonzini 		init_kvm_nested_mmu(vcpu, &regs);
5046c50d8ae3SPaolo Bonzini 	else if (tdp_enabled)
504739e7e2bfSPaolo Bonzini 		init_kvm_tdp_mmu(vcpu, &regs);
5048c50d8ae3SPaolo Bonzini 	else
504939e7e2bfSPaolo Bonzini 		init_kvm_softmmu(vcpu, &regs);
5050c50d8ae3SPaolo Bonzini }
5051c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_mmu);
5052c50d8ae3SPaolo Bonzini 
505349c6f875SSean Christopherson void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
505449c6f875SSean Christopherson {
505549c6f875SSean Christopherson 	/*
505649c6f875SSean Christopherson 	 * Invalidate all MMU roles to force them to reinitialize as CPUID
505749c6f875SSean Christopherson 	 * information is factored into reserved bit calculations.
5058feb627e8SVitaly Kuznetsov 	 *
5059feb627e8SVitaly Kuznetsov 	 * Correctly handling multiple vCPU models with respect to paging and
5060feb627e8SVitaly Kuznetsov 	 * physical address properties) in a single VM would require tracking
5061feb627e8SVitaly Kuznetsov 	 * all relevant CPUID information in kvm_mmu_page_role. That is very
5062feb627e8SVitaly Kuznetsov 	 * undesirable as it would increase the memory requirements for
5063feb627e8SVitaly Kuznetsov 	 * gfn_track (see struct kvm_mmu_page_role comments).  For now that
5064feb627e8SVitaly Kuznetsov 	 * problem is swept under the rug; KVM's CPUID API is horrific and
5065feb627e8SVitaly Kuznetsov 	 * it's all but impossible to solve it without introducing a new API.
506649c6f875SSean Christopherson 	 */
5067*7a458f0eSPaolo Bonzini 	vcpu->arch.root_mmu.root_role.word = 0;
5068*7a458f0eSPaolo Bonzini 	vcpu->arch.guest_mmu.root_role.word = 0;
5069*7a458f0eSPaolo Bonzini 	vcpu->arch.nested_mmu.root_role.word = 0;
5070e5ed0fb0SPaolo Bonzini 	vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5071e5ed0fb0SPaolo Bonzini 	vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5072e5ed0fb0SPaolo Bonzini 	vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
507349c6f875SSean Christopherson 	kvm_mmu_reset_context(vcpu);
507463f5a190SSean Christopherson 
507563f5a190SSean Christopherson 	/*
5076feb627e8SVitaly Kuznetsov 	 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5077feb627e8SVitaly Kuznetsov 	 * kvm_arch_vcpu_ioctl().
507863f5a190SSean Christopherson 	 */
5079feb627e8SVitaly Kuznetsov 	KVM_BUG_ON(vcpu->arch.last_vmentry_cpu != -1, vcpu->kvm);
508049c6f875SSean Christopherson }
508149c6f875SSean Christopherson 
5082c50d8ae3SPaolo Bonzini void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5083c50d8ae3SPaolo Bonzini {
5084c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
5085c9060662SSean Christopherson 	kvm_init_mmu(vcpu);
5086c50d8ae3SPaolo Bonzini }
5087c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5088c50d8ae3SPaolo Bonzini 
5089c50d8ae3SPaolo Bonzini int kvm_mmu_load(struct kvm_vcpu *vcpu)
5090c50d8ae3SPaolo Bonzini {
5091c50d8ae3SPaolo Bonzini 	int r;
5092c50d8ae3SPaolo Bonzini 
5093378f5cd6SSean Christopherson 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->direct_map);
5094c50d8ae3SPaolo Bonzini 	if (r)
5095c50d8ae3SPaolo Bonzini 		goto out;
5096748e52b9SSean Christopherson 	r = mmu_alloc_special_roots(vcpu);
5097c50d8ae3SPaolo Bonzini 	if (r)
5098c50d8ae3SPaolo Bonzini 		goto out;
50994a38162eSPaolo Bonzini 	if (vcpu->arch.mmu->direct_map)
51006e6ec584SSean Christopherson 		r = mmu_alloc_direct_roots(vcpu);
51016e6ec584SSean Christopherson 	else
51026e6ec584SSean Christopherson 		r = mmu_alloc_shadow_roots(vcpu);
5103c50d8ae3SPaolo Bonzini 	if (r)
5104c50d8ae3SPaolo Bonzini 		goto out;
5105a91f387bSSean Christopherson 
5106a91f387bSSean Christopherson 	kvm_mmu_sync_roots(vcpu);
5107a91f387bSSean Christopherson 
5108727a7e27SPaolo Bonzini 	kvm_mmu_load_pgd(vcpu);
5109db01416bSSean Christopherson 
5110db01416bSSean Christopherson 	/*
5111db01416bSSean Christopherson 	 * Flush any TLB entries for the new root, the provenance of the root
5112db01416bSSean Christopherson 	 * is unknown.  Even if KVM ensures there are no stale TLB entries
5113db01416bSSean Christopherson 	 * for a freed root, in theory another hypervisor could have left
5114db01416bSSean Christopherson 	 * stale entries.  Flushing on alloc also allows KVM to skip the TLB
5115db01416bSSean Christopherson 	 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5116db01416bSSean Christopherson 	 */
5117e27bc044SSean Christopherson 	static_call(kvm_x86_flush_tlb_current)(vcpu);
5118c50d8ae3SPaolo Bonzini out:
5119c50d8ae3SPaolo Bonzini 	return r;
5120c50d8ae3SPaolo Bonzini }
5121c50d8ae3SPaolo Bonzini 
5122c50d8ae3SPaolo Bonzini void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5123c50d8ae3SPaolo Bonzini {
51240c1c92f1SPaolo Bonzini 	struct kvm *kvm = vcpu->kvm;
51250c1c92f1SPaolo Bonzini 
51260c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5127b9e5603cSPaolo Bonzini 	WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
51280c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5129b9e5603cSPaolo Bonzini 	WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
51306d58f275SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5131c50d8ae3SPaolo Bonzini }
5132c50d8ae3SPaolo Bonzini 
5133527d5cd7SSean Christopherson static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5134527d5cd7SSean Christopherson {
5135527d5cd7SSean Christopherson 	struct kvm_mmu_page *sp;
5136527d5cd7SSean Christopherson 
5137527d5cd7SSean Christopherson 	if (!VALID_PAGE(root_hpa))
5138527d5cd7SSean Christopherson 		return false;
5139527d5cd7SSean Christopherson 
5140527d5cd7SSean Christopherson 	/*
5141527d5cd7SSean Christopherson 	 * When freeing obsolete roots, treat roots as obsolete if they don't
5142527d5cd7SSean Christopherson 	 * have an associated shadow page.  This does mean KVM will get false
5143527d5cd7SSean Christopherson 	 * positives and free roots that don't strictly need to be freed, but
5144527d5cd7SSean Christopherson 	 * such false positives are relatively rare:
5145527d5cd7SSean Christopherson 	 *
5146527d5cd7SSean Christopherson 	 *  (a) only PAE paging and nested NPT has roots without shadow pages
5147527d5cd7SSean Christopherson 	 *  (b) remote reloads due to a memslot update obsoletes _all_ roots
5148527d5cd7SSean Christopherson 	 *  (c) KVM doesn't track previous roots for PAE paging, and the guest
5149527d5cd7SSean Christopherson 	 *      is unlikely to zap an in-use PGD.
5150527d5cd7SSean Christopherson 	 */
5151527d5cd7SSean Christopherson 	sp = to_shadow_page(root_hpa);
5152527d5cd7SSean Christopherson 	return !sp || is_obsolete_sp(kvm, sp);
5153527d5cd7SSean Christopherson }
5154527d5cd7SSean Christopherson 
5155527d5cd7SSean Christopherson static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5156527d5cd7SSean Christopherson {
5157527d5cd7SSean Christopherson 	unsigned long roots_to_free = 0;
5158527d5cd7SSean Christopherson 	int i;
5159527d5cd7SSean Christopherson 
5160527d5cd7SSean Christopherson 	if (is_obsolete_root(kvm, mmu->root.hpa))
5161527d5cd7SSean Christopherson 		roots_to_free |= KVM_MMU_ROOT_CURRENT;
5162527d5cd7SSean Christopherson 
5163527d5cd7SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5164527d5cd7SSean Christopherson 		if (is_obsolete_root(kvm, mmu->root.hpa))
5165527d5cd7SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5166527d5cd7SSean Christopherson 	}
5167527d5cd7SSean Christopherson 
5168527d5cd7SSean Christopherson 	if (roots_to_free)
5169527d5cd7SSean Christopherson 		kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5170527d5cd7SSean Christopherson }
5171527d5cd7SSean Christopherson 
5172527d5cd7SSean Christopherson void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5173527d5cd7SSean Christopherson {
5174527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5175527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5176527d5cd7SSean Christopherson }
5177527d5cd7SSean Christopherson 
5178c50d8ae3SPaolo Bonzini static bool need_remote_flush(u64 old, u64 new)
5179c50d8ae3SPaolo Bonzini {
5180c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old))
5181c50d8ae3SPaolo Bonzini 		return false;
5182c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(new))
5183c50d8ae3SPaolo Bonzini 		return true;
5184c50d8ae3SPaolo Bonzini 	if ((old ^ new) & PT64_BASE_ADDR_MASK)
5185c50d8ae3SPaolo Bonzini 		return true;
5186c50d8ae3SPaolo Bonzini 	old ^= shadow_nx_mask;
5187c50d8ae3SPaolo Bonzini 	new ^= shadow_nx_mask;
5188c50d8ae3SPaolo Bonzini 	return (old & ~new & PT64_PERM_MASK) != 0;
5189c50d8ae3SPaolo Bonzini }
5190c50d8ae3SPaolo Bonzini 
5191c50d8ae3SPaolo Bonzini static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5192c50d8ae3SPaolo Bonzini 				    int *bytes)
5193c50d8ae3SPaolo Bonzini {
5194c50d8ae3SPaolo Bonzini 	u64 gentry = 0;
5195c50d8ae3SPaolo Bonzini 	int r;
5196c50d8ae3SPaolo Bonzini 
5197c50d8ae3SPaolo Bonzini 	/*
5198c50d8ae3SPaolo Bonzini 	 * Assume that the pte write on a page table of the same type
5199c50d8ae3SPaolo Bonzini 	 * as the current vcpu paging mode since we update the sptes only
5200c50d8ae3SPaolo Bonzini 	 * when they have the same mode.
5201c50d8ae3SPaolo Bonzini 	 */
5202c50d8ae3SPaolo Bonzini 	if (is_pae(vcpu) && *bytes == 4) {
5203c50d8ae3SPaolo Bonzini 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5204c50d8ae3SPaolo Bonzini 		*gpa &= ~(gpa_t)7;
5205c50d8ae3SPaolo Bonzini 		*bytes = 8;
5206c50d8ae3SPaolo Bonzini 	}
5207c50d8ae3SPaolo Bonzini 
5208c50d8ae3SPaolo Bonzini 	if (*bytes == 4 || *bytes == 8) {
5209c50d8ae3SPaolo Bonzini 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5210c50d8ae3SPaolo Bonzini 		if (r)
5211c50d8ae3SPaolo Bonzini 			gentry = 0;
5212c50d8ae3SPaolo Bonzini 	}
5213c50d8ae3SPaolo Bonzini 
5214c50d8ae3SPaolo Bonzini 	return gentry;
5215c50d8ae3SPaolo Bonzini }
5216c50d8ae3SPaolo Bonzini 
5217c50d8ae3SPaolo Bonzini /*
5218c50d8ae3SPaolo Bonzini  * If we're seeing too many writes to a page, it may no longer be a page table,
5219c50d8ae3SPaolo Bonzini  * or we may be forking, in which case it is better to unmap the page.
5220c50d8ae3SPaolo Bonzini  */
5221c50d8ae3SPaolo Bonzini static bool detect_write_flooding(struct kvm_mmu_page *sp)
5222c50d8ae3SPaolo Bonzini {
5223c50d8ae3SPaolo Bonzini 	/*
5224c50d8ae3SPaolo Bonzini 	 * Skip write-flooding detected for the sp whose level is 1, because
5225c50d8ae3SPaolo Bonzini 	 * it can become unsync, then the guest page is not write-protected.
5226c50d8ae3SPaolo Bonzini 	 */
52273bae0459SSean Christopherson 	if (sp->role.level == PG_LEVEL_4K)
5228c50d8ae3SPaolo Bonzini 		return false;
5229c50d8ae3SPaolo Bonzini 
5230c50d8ae3SPaolo Bonzini 	atomic_inc(&sp->write_flooding_count);
5231c50d8ae3SPaolo Bonzini 	return atomic_read(&sp->write_flooding_count) >= 3;
5232c50d8ae3SPaolo Bonzini }
5233c50d8ae3SPaolo Bonzini 
5234c50d8ae3SPaolo Bonzini /*
5235c50d8ae3SPaolo Bonzini  * Misaligned accesses are too much trouble to fix up; also, they usually
5236c50d8ae3SPaolo Bonzini  * indicate a page is not used as a page table.
5237c50d8ae3SPaolo Bonzini  */
5238c50d8ae3SPaolo Bonzini static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5239c50d8ae3SPaolo Bonzini 				    int bytes)
5240c50d8ae3SPaolo Bonzini {
5241c50d8ae3SPaolo Bonzini 	unsigned offset, pte_size, misaligned;
5242c50d8ae3SPaolo Bonzini 
5243c50d8ae3SPaolo Bonzini 	pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5244c50d8ae3SPaolo Bonzini 		 gpa, bytes, sp->role.word);
5245c50d8ae3SPaolo Bonzini 
5246c50d8ae3SPaolo Bonzini 	offset = offset_in_page(gpa);
5247bb3b394dSLai Jiangshan 	pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5248c50d8ae3SPaolo Bonzini 
5249c50d8ae3SPaolo Bonzini 	/*
5250c50d8ae3SPaolo Bonzini 	 * Sometimes, the OS only writes the last one bytes to update status
5251c50d8ae3SPaolo Bonzini 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5252c50d8ae3SPaolo Bonzini 	 */
5253c50d8ae3SPaolo Bonzini 	if (!(offset & (pte_size - 1)) && bytes == 1)
5254c50d8ae3SPaolo Bonzini 		return false;
5255c50d8ae3SPaolo Bonzini 
5256c50d8ae3SPaolo Bonzini 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5257c50d8ae3SPaolo Bonzini 	misaligned |= bytes < 4;
5258c50d8ae3SPaolo Bonzini 
5259c50d8ae3SPaolo Bonzini 	return misaligned;
5260c50d8ae3SPaolo Bonzini }
5261c50d8ae3SPaolo Bonzini 
5262c50d8ae3SPaolo Bonzini static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5263c50d8ae3SPaolo Bonzini {
5264c50d8ae3SPaolo Bonzini 	unsigned page_offset, quadrant;
5265c50d8ae3SPaolo Bonzini 	u64 *spte;
5266c50d8ae3SPaolo Bonzini 	int level;
5267c50d8ae3SPaolo Bonzini 
5268c50d8ae3SPaolo Bonzini 	page_offset = offset_in_page(gpa);
5269c50d8ae3SPaolo Bonzini 	level = sp->role.level;
5270c50d8ae3SPaolo Bonzini 	*nspte = 1;
5271bb3b394dSLai Jiangshan 	if (sp->role.has_4_byte_gpte) {
5272c50d8ae3SPaolo Bonzini 		page_offset <<= 1;	/* 32->64 */
5273c50d8ae3SPaolo Bonzini 		/*
5274c50d8ae3SPaolo Bonzini 		 * A 32-bit pde maps 4MB while the shadow pdes map
5275c50d8ae3SPaolo Bonzini 		 * only 2MB.  So we need to double the offset again
5276c50d8ae3SPaolo Bonzini 		 * and zap two pdes instead of one.
5277c50d8ae3SPaolo Bonzini 		 */
5278c50d8ae3SPaolo Bonzini 		if (level == PT32_ROOT_LEVEL) {
5279c50d8ae3SPaolo Bonzini 			page_offset &= ~7; /* kill rounding error */
5280c50d8ae3SPaolo Bonzini 			page_offset <<= 1;
5281c50d8ae3SPaolo Bonzini 			*nspte = 2;
5282c50d8ae3SPaolo Bonzini 		}
5283c50d8ae3SPaolo Bonzini 		quadrant = page_offset >> PAGE_SHIFT;
5284c50d8ae3SPaolo Bonzini 		page_offset &= ~PAGE_MASK;
5285c50d8ae3SPaolo Bonzini 		if (quadrant != sp->role.quadrant)
5286c50d8ae3SPaolo Bonzini 			return NULL;
5287c50d8ae3SPaolo Bonzini 	}
5288c50d8ae3SPaolo Bonzini 
5289c50d8ae3SPaolo Bonzini 	spte = &sp->spt[page_offset / sizeof(*spte)];
5290c50d8ae3SPaolo Bonzini 	return spte;
5291c50d8ae3SPaolo Bonzini }
5292c50d8ae3SPaolo Bonzini 
5293c50d8ae3SPaolo Bonzini static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5294c50d8ae3SPaolo Bonzini 			      const u8 *new, int bytes,
5295c50d8ae3SPaolo Bonzini 			      struct kvm_page_track_notifier_node *node)
5296c50d8ae3SPaolo Bonzini {
5297c50d8ae3SPaolo Bonzini 	gfn_t gfn = gpa >> PAGE_SHIFT;
5298c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
5299c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
5300c50d8ae3SPaolo Bonzini 	u64 entry, gentry, *spte;
5301c50d8ae3SPaolo Bonzini 	int npte;
530206152b2dSLai Jiangshan 	bool flush = false;
5303c50d8ae3SPaolo Bonzini 
5304c50d8ae3SPaolo Bonzini 	/*
5305c50d8ae3SPaolo Bonzini 	 * If we don't have indirect shadow pages, it means no page is
5306c50d8ae3SPaolo Bonzini 	 * write-protected, so we can exit simply.
5307c50d8ae3SPaolo Bonzini 	 */
5308c50d8ae3SPaolo Bonzini 	if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5309c50d8ae3SPaolo Bonzini 		return;
5310c50d8ae3SPaolo Bonzini 
5311c50d8ae3SPaolo Bonzini 	pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5312c50d8ae3SPaolo Bonzini 
5313c50d8ae3SPaolo Bonzini 	/*
5314c50d8ae3SPaolo Bonzini 	 * No need to care whether allocation memory is successful
5315d9f6e12fSIngo Molnar 	 * or not since pte prefetch is skipped if it does not have
5316c50d8ae3SPaolo Bonzini 	 * enough objects in the cache.
5317c50d8ae3SPaolo Bonzini 	 */
5318378f5cd6SSean Christopherson 	mmu_topup_memory_caches(vcpu, true);
5319c50d8ae3SPaolo Bonzini 
5320531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
5321c50d8ae3SPaolo Bonzini 
5322c50d8ae3SPaolo Bonzini 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5323c50d8ae3SPaolo Bonzini 
5324c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_pte_write;
5325c50d8ae3SPaolo Bonzini 
5326c50d8ae3SPaolo Bonzini 	for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5327c50d8ae3SPaolo Bonzini 		if (detect_write_misaligned(sp, gpa, bytes) ||
5328c50d8ae3SPaolo Bonzini 		      detect_write_flooding(sp)) {
5329c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5330c50d8ae3SPaolo Bonzini 			++vcpu->kvm->stat.mmu_flooded;
5331c50d8ae3SPaolo Bonzini 			continue;
5332c50d8ae3SPaolo Bonzini 		}
5333c50d8ae3SPaolo Bonzini 
5334c50d8ae3SPaolo Bonzini 		spte = get_written_sptes(sp, gpa, &npte);
5335c50d8ae3SPaolo Bonzini 		if (!spte)
5336c50d8ae3SPaolo Bonzini 			continue;
5337c50d8ae3SPaolo Bonzini 
5338c50d8ae3SPaolo Bonzini 		while (npte--) {
5339c50d8ae3SPaolo Bonzini 			entry = *spte;
53402de4085cSBen Gardon 			mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5341c5e2184dSSean Christopherson 			if (gentry && sp->role.level != PG_LEVEL_4K)
5342c5e2184dSSean Christopherson 				++vcpu->kvm->stat.mmu_pde_zapped;
5343c50d8ae3SPaolo Bonzini 			if (need_remote_flush(entry, *spte))
534406152b2dSLai Jiangshan 				flush = true;
5345c50d8ae3SPaolo Bonzini 			++spte;
5346c50d8ae3SPaolo Bonzini 		}
5347c50d8ae3SPaolo Bonzini 	}
534806152b2dSLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5349531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
5350c50d8ae3SPaolo Bonzini }
5351c50d8ae3SPaolo Bonzini 
5352736c291cSSean Christopherson int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5353c50d8ae3SPaolo Bonzini 		       void *insn, int insn_len)
5354c50d8ae3SPaolo Bonzini {
535592daa48bSSean Christopherson 	int r, emulation_type = EMULTYPE_PF;
5356c50d8ae3SPaolo Bonzini 	bool direct = vcpu->arch.mmu->direct_map;
5357c50d8ae3SPaolo Bonzini 
5358b9e5603cSPaolo Bonzini 	if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5359ddce6208SSean Christopherson 		return RET_PF_RETRY;
5360ddce6208SSean Christopherson 
5361c50d8ae3SPaolo Bonzini 	r = RET_PF_INVALID;
5362c50d8ae3SPaolo Bonzini 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
5363736c291cSSean Christopherson 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5364c50d8ae3SPaolo Bonzini 		if (r == RET_PF_EMULATE)
5365c50d8ae3SPaolo Bonzini 			goto emulate;
5366c50d8ae3SPaolo Bonzini 	}
5367c50d8ae3SPaolo Bonzini 
5368c50d8ae3SPaolo Bonzini 	if (r == RET_PF_INVALID) {
53697a02674dSSean Christopherson 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
53707a02674dSSean Christopherson 					  lower_32_bits(error_code), false);
537119025e7bSSean Christopherson 		if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
53727b367bc9SSean Christopherson 			return -EIO;
5373c50d8ae3SPaolo Bonzini 	}
5374c50d8ae3SPaolo Bonzini 
5375c50d8ae3SPaolo Bonzini 	if (r < 0)
5376c50d8ae3SPaolo Bonzini 		return r;
537783a2ba4cSSean Christopherson 	if (r != RET_PF_EMULATE)
537883a2ba4cSSean Christopherson 		return 1;
5379c50d8ae3SPaolo Bonzini 
5380c50d8ae3SPaolo Bonzini 	/*
5381c50d8ae3SPaolo Bonzini 	 * Before emulating the instruction, check if the error code
5382c50d8ae3SPaolo Bonzini 	 * was due to a RO violation while translating the guest page.
5383c50d8ae3SPaolo Bonzini 	 * This can occur when using nested virtualization with nested
5384c50d8ae3SPaolo Bonzini 	 * paging in both guests. If true, we simply unprotect the page
5385c50d8ae3SPaolo Bonzini 	 * and resume the guest.
5386c50d8ae3SPaolo Bonzini 	 */
5387c50d8ae3SPaolo Bonzini 	if (vcpu->arch.mmu->direct_map &&
5388c50d8ae3SPaolo Bonzini 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5389736c291cSSean Christopherson 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5390c50d8ae3SPaolo Bonzini 		return 1;
5391c50d8ae3SPaolo Bonzini 	}
5392c50d8ae3SPaolo Bonzini 
5393c50d8ae3SPaolo Bonzini 	/*
5394c50d8ae3SPaolo Bonzini 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5395c50d8ae3SPaolo Bonzini 	 * optimistically try to just unprotect the page and let the processor
5396c50d8ae3SPaolo Bonzini 	 * re-execute the instruction that caused the page fault.  Do not allow
5397c50d8ae3SPaolo Bonzini 	 * retrying MMIO emulation, as it's not only pointless but could also
5398c50d8ae3SPaolo Bonzini 	 * cause us to enter an infinite loop because the processor will keep
5399c50d8ae3SPaolo Bonzini 	 * faulting on the non-existent MMIO address.  Retrying an instruction
5400c50d8ae3SPaolo Bonzini 	 * from a nested guest is also pointless and dangerous as we are only
5401c50d8ae3SPaolo Bonzini 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
5402c50d8ae3SPaolo Bonzini 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5403c50d8ae3SPaolo Bonzini 	 */
5404736c291cSSean Christopherson 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
540592daa48bSSean Christopherson 		emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5406c50d8ae3SPaolo Bonzini emulate:
5407736c291cSSean Christopherson 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5408c50d8ae3SPaolo Bonzini 				       insn_len);
5409c50d8ae3SPaolo Bonzini }
5410c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5411c50d8ae3SPaolo Bonzini 
54125efac074SPaolo Bonzini void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
54135efac074SPaolo Bonzini 			    gva_t gva, hpa_t root_hpa)
5414c50d8ae3SPaolo Bonzini {
5415c50d8ae3SPaolo Bonzini 	int i;
5416c50d8ae3SPaolo Bonzini 
54175efac074SPaolo Bonzini 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
54185efac074SPaolo Bonzini 	if (mmu != &vcpu->arch.guest_mmu) {
54195efac074SPaolo Bonzini 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
5420c50d8ae3SPaolo Bonzini 		if (is_noncanonical_address(gva, vcpu))
5421c50d8ae3SPaolo Bonzini 			return;
5422c50d8ae3SPaolo Bonzini 
5423e27bc044SSean Christopherson 		static_call(kvm_x86_flush_tlb_gva)(vcpu, gva);
54245efac074SPaolo Bonzini 	}
54255efac074SPaolo Bonzini 
54265efac074SPaolo Bonzini 	if (!mmu->invlpg)
54275efac074SPaolo Bonzini 		return;
54285efac074SPaolo Bonzini 
54295efac074SPaolo Bonzini 	if (root_hpa == INVALID_PAGE) {
5430b9e5603cSPaolo Bonzini 		mmu->invlpg(vcpu, gva, mmu->root.hpa);
5431c50d8ae3SPaolo Bonzini 
5432c50d8ae3SPaolo Bonzini 		/*
5433c50d8ae3SPaolo Bonzini 		 * INVLPG is required to invalidate any global mappings for the VA,
5434c50d8ae3SPaolo Bonzini 		 * irrespective of PCID. Since it would take us roughly similar amount
5435c50d8ae3SPaolo Bonzini 		 * of work to determine whether any of the prev_root mappings of the VA
5436c50d8ae3SPaolo Bonzini 		 * is marked global, or to just sync it blindly, so we might as well
5437c50d8ae3SPaolo Bonzini 		 * just always sync it.
5438c50d8ae3SPaolo Bonzini 		 *
5439c50d8ae3SPaolo Bonzini 		 * Mappings not reachable via the current cr3 or the prev_roots will be
5440c50d8ae3SPaolo Bonzini 		 * synced when switching to that cr3, so nothing needs to be done here
5441c50d8ae3SPaolo Bonzini 		 * for them.
5442c50d8ae3SPaolo Bonzini 		 */
5443c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5444c50d8ae3SPaolo Bonzini 			if (VALID_PAGE(mmu->prev_roots[i].hpa))
5445c50d8ae3SPaolo Bonzini 				mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
54465efac074SPaolo Bonzini 	} else {
54475efac074SPaolo Bonzini 		mmu->invlpg(vcpu, gva, root_hpa);
54485efac074SPaolo Bonzini 	}
54495efac074SPaolo Bonzini }
5450c50d8ae3SPaolo Bonzini 
54515efac074SPaolo Bonzini void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
54525efac074SPaolo Bonzini {
545305b29633SLai Jiangshan 	kvm_mmu_invalidate_gva(vcpu, vcpu->arch.walk_mmu, gva, INVALID_PAGE);
5454c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5455c50d8ae3SPaolo Bonzini }
5456c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5457c50d8ae3SPaolo Bonzini 
54585efac074SPaolo Bonzini 
5459c50d8ae3SPaolo Bonzini void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5460c50d8ae3SPaolo Bonzini {
5461c50d8ae3SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
5462c50d8ae3SPaolo Bonzini 	bool tlb_flush = false;
5463c50d8ae3SPaolo Bonzini 	uint i;
5464c50d8ae3SPaolo Bonzini 
5465c50d8ae3SPaolo Bonzini 	if (pcid == kvm_get_active_pcid(vcpu)) {
5466b9e5603cSPaolo Bonzini 		mmu->invlpg(vcpu, gva, mmu->root.hpa);
5467c50d8ae3SPaolo Bonzini 		tlb_flush = true;
5468c50d8ae3SPaolo Bonzini 	}
5469c50d8ae3SPaolo Bonzini 
5470c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5471c50d8ae3SPaolo Bonzini 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5472be01e8e2SSean Christopherson 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
5473c50d8ae3SPaolo Bonzini 			mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5474c50d8ae3SPaolo Bonzini 			tlb_flush = true;
5475c50d8ae3SPaolo Bonzini 		}
5476c50d8ae3SPaolo Bonzini 	}
5477c50d8ae3SPaolo Bonzini 
5478c50d8ae3SPaolo Bonzini 	if (tlb_flush)
5479e27bc044SSean Christopherson 		static_call(kvm_x86_flush_tlb_gva)(vcpu, gva);
5480c50d8ae3SPaolo Bonzini 
5481c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5482c50d8ae3SPaolo Bonzini 
5483c50d8ae3SPaolo Bonzini 	/*
5484c50d8ae3SPaolo Bonzini 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5485c50d8ae3SPaolo Bonzini 	 * synced when switching to that cr3, so nothing needs to be done here
5486c50d8ae3SPaolo Bonzini 	 * for them.
5487c50d8ae3SPaolo Bonzini 	 */
5488c50d8ae3SPaolo Bonzini }
5489c50d8ae3SPaolo Bonzini 
5490746700d2SWei Huang void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
5491746700d2SWei Huang 		       int tdp_max_root_level, int tdp_huge_page_level)
5492c50d8ae3SPaolo Bonzini {
5493bde77235SSean Christopherson 	tdp_enabled = enable_tdp;
5494746700d2SWei Huang 	tdp_root_level = tdp_forced_root_level;
549583013059SSean Christopherson 	max_tdp_level = tdp_max_root_level;
5496703c335dSSean Christopherson 
5497703c335dSSean Christopherson 	/*
54981d92d2e8SSean Christopherson 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5499703c335dSSean Christopherson 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5500703c335dSSean Christopherson 	 * the kernel is not.  But, KVM never creates a page size greater than
5501703c335dSSean Christopherson 	 * what is used by the kernel for any given HVA, i.e. the kernel's
5502703c335dSSean Christopherson 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5503703c335dSSean Christopherson 	 */
5504703c335dSSean Christopherson 	if (tdp_enabled)
55051d92d2e8SSean Christopherson 		max_huge_page_level = tdp_huge_page_level;
5506703c335dSSean Christopherson 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
55071d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_1G;
5508703c335dSSean Christopherson 	else
55091d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_2M;
5510c50d8ae3SPaolo Bonzini }
5511bde77235SSean Christopherson EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5512c50d8ae3SPaolo Bonzini 
5513c50d8ae3SPaolo Bonzini /* The return value indicates if tlb flush on all vcpus is needed. */
5514269e9552SHamza Mahfooz typedef bool (*slot_level_handler) (struct kvm *kvm,
5515269e9552SHamza Mahfooz 				    struct kvm_rmap_head *rmap_head,
5516269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot);
5517c50d8ae3SPaolo Bonzini 
5518c50d8ae3SPaolo Bonzini /* The caller should hold mmu-lock before calling this function. */
5519c50d8ae3SPaolo Bonzini static __always_inline bool
5520269e9552SHamza Mahfooz slot_handle_level_range(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5521c50d8ae3SPaolo Bonzini 			slot_level_handler fn, int start_level, int end_level,
55221a61b7dbSSean Christopherson 			gfn_t start_gfn, gfn_t end_gfn, bool flush_on_yield,
55231a61b7dbSSean Christopherson 			bool flush)
5524c50d8ae3SPaolo Bonzini {
5525c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
5526c50d8ae3SPaolo Bonzini 
5527c50d8ae3SPaolo Bonzini 	for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5528c50d8ae3SPaolo Bonzini 			end_gfn, &iterator) {
5529c50d8ae3SPaolo Bonzini 		if (iterator.rmap)
55300a234f5dSSean Christopherson 			flush |= fn(kvm, iterator.rmap, memslot);
5531c50d8ae3SPaolo Bonzini 
5532531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
5533302695a5SSean Christopherson 			if (flush && flush_on_yield) {
5534c50d8ae3SPaolo Bonzini 				kvm_flush_remote_tlbs_with_address(kvm,
5535c50d8ae3SPaolo Bonzini 						start_gfn,
5536c50d8ae3SPaolo Bonzini 						iterator.gfn - start_gfn + 1);
5537c50d8ae3SPaolo Bonzini 				flush = false;
5538c50d8ae3SPaolo Bonzini 			}
5539531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
5540c50d8ae3SPaolo Bonzini 		}
5541c50d8ae3SPaolo Bonzini 	}
5542c50d8ae3SPaolo Bonzini 
5543c50d8ae3SPaolo Bonzini 	return flush;
5544c50d8ae3SPaolo Bonzini }
5545c50d8ae3SPaolo Bonzini 
5546c50d8ae3SPaolo Bonzini static __always_inline bool
5547269e9552SHamza Mahfooz slot_handle_level(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5548c50d8ae3SPaolo Bonzini 		  slot_level_handler fn, int start_level, int end_level,
5549302695a5SSean Christopherson 		  bool flush_on_yield)
5550c50d8ae3SPaolo Bonzini {
5551c50d8ae3SPaolo Bonzini 	return slot_handle_level_range(kvm, memslot, fn, start_level,
5552c50d8ae3SPaolo Bonzini 			end_level, memslot->base_gfn,
5553c50d8ae3SPaolo Bonzini 			memslot->base_gfn + memslot->npages - 1,
55541a61b7dbSSean Christopherson 			flush_on_yield, false);
5555c50d8ae3SPaolo Bonzini }
5556c50d8ae3SPaolo Bonzini 
5557c50d8ae3SPaolo Bonzini static __always_inline bool
5558610265eaSDavid Matlack slot_handle_level_4k(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5559302695a5SSean Christopherson 		     slot_level_handler fn, bool flush_on_yield)
5560c50d8ae3SPaolo Bonzini {
55613bae0459SSean Christopherson 	return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5562302695a5SSean Christopherson 				 PG_LEVEL_4K, flush_on_yield);
5563c50d8ae3SPaolo Bonzini }
5564c50d8ae3SPaolo Bonzini 
5565c50d8ae3SPaolo Bonzini static void free_mmu_pages(struct kvm_mmu *mmu)
5566c50d8ae3SPaolo Bonzini {
55674a98623dSSean Christopherson 	if (!tdp_enabled && mmu->pae_root)
55684a98623dSSean Christopherson 		set_memory_encrypted((unsigned long)mmu->pae_root, 1);
5569c50d8ae3SPaolo Bonzini 	free_page((unsigned long)mmu->pae_root);
557003ca4589SSean Christopherson 	free_page((unsigned long)mmu->pml4_root);
5571cb0f722aSWei Huang 	free_page((unsigned long)mmu->pml5_root);
5572c50d8ae3SPaolo Bonzini }
5573c50d8ae3SPaolo Bonzini 
557404d28e37SSean Christopherson static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5575c50d8ae3SPaolo Bonzini {
5576c50d8ae3SPaolo Bonzini 	struct page *page;
5577c50d8ae3SPaolo Bonzini 	int i;
5578c50d8ae3SPaolo Bonzini 
5579b9e5603cSPaolo Bonzini 	mmu->root.hpa = INVALID_PAGE;
5580b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
558104d28e37SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
558204d28e37SSean Christopherson 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
558304d28e37SSean Christopherson 
558427f4fca2SLai Jiangshan 	/* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
558527f4fca2SLai Jiangshan 	if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
558627f4fca2SLai Jiangshan 		return 0;
558727f4fca2SLai Jiangshan 
5588c50d8ae3SPaolo Bonzini 	/*
5589c50d8ae3SPaolo Bonzini 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5590c50d8ae3SPaolo Bonzini 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
5591c50d8ae3SPaolo Bonzini 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
5592c50d8ae3SPaolo Bonzini 	 * x86_64.  Therefore we need to allocate the PDP table in the first
559304d45551SSean Christopherson 	 * 4GB of memory, which happens to fit the DMA32 zone.  TDP paging
559404d45551SSean Christopherson 	 * generally doesn't use PAE paging and can skip allocating the PDP
559504d45551SSean Christopherson 	 * table.  The main exception, handled here, is SVM's 32-bit NPT.  The
559604d45551SSean Christopherson 	 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
559784432316SLai Jiangshan 	 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
5598c50d8ae3SPaolo Bonzini 	 */
5599d468d94bSSean Christopherson 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5600c50d8ae3SPaolo Bonzini 		return 0;
5601c50d8ae3SPaolo Bonzini 
5602c50d8ae3SPaolo Bonzini 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5603c50d8ae3SPaolo Bonzini 	if (!page)
5604c50d8ae3SPaolo Bonzini 		return -ENOMEM;
5605c50d8ae3SPaolo Bonzini 
5606c50d8ae3SPaolo Bonzini 	mmu->pae_root = page_address(page);
56074a98623dSSean Christopherson 
56084a98623dSSean Christopherson 	/*
56094a98623dSSean Christopherson 	 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
56104a98623dSSean Christopherson 	 * get the CPU to treat the PDPTEs as encrypted.  Decrypt the page so
56114a98623dSSean Christopherson 	 * that KVM's writes and the CPU's reads get along.  Note, this is
56124a98623dSSean Christopherson 	 * only necessary when using shadow paging, as 64-bit NPT can get at
56134a98623dSSean Christopherson 	 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
56144a98623dSSean Christopherson 	 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
56154a98623dSSean Christopherson 	 */
56164a98623dSSean Christopherson 	if (!tdp_enabled)
56174a98623dSSean Christopherson 		set_memory_decrypted((unsigned long)mmu->pae_root, 1);
56184a98623dSSean Christopherson 	else
56194a98623dSSean Christopherson 		WARN_ON_ONCE(shadow_me_mask);
56204a98623dSSean Christopherson 
5621c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i)
5622c834e5e4SSean Christopherson 		mmu->pae_root[i] = INVALID_PAE_ROOT;
5623c50d8ae3SPaolo Bonzini 
5624c50d8ae3SPaolo Bonzini 	return 0;
5625c50d8ae3SPaolo Bonzini }
5626c50d8ae3SPaolo Bonzini 
5627c50d8ae3SPaolo Bonzini int kvm_mmu_create(struct kvm_vcpu *vcpu)
5628c50d8ae3SPaolo Bonzini {
5629c50d8ae3SPaolo Bonzini 	int ret;
5630c50d8ae3SPaolo Bonzini 
56315962bfb7SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
56325f6078f9SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
56335f6078f9SSean Christopherson 
56345962bfb7SSean Christopherson 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
56355f6078f9SSean Christopherson 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
56365962bfb7SSean Christopherson 
563796880883SSean Christopherson 	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
563896880883SSean Christopherson 
5639c50d8ae3SPaolo Bonzini 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
5640c50d8ae3SPaolo Bonzini 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5641c50d8ae3SPaolo Bonzini 
564204d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
5643c50d8ae3SPaolo Bonzini 	if (ret)
5644c50d8ae3SPaolo Bonzini 		return ret;
5645c50d8ae3SPaolo Bonzini 
564604d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
5647c50d8ae3SPaolo Bonzini 	if (ret)
5648c50d8ae3SPaolo Bonzini 		goto fail_allocate_root;
5649c50d8ae3SPaolo Bonzini 
5650c50d8ae3SPaolo Bonzini 	return ret;
5651c50d8ae3SPaolo Bonzini  fail_allocate_root:
5652c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
5653c50d8ae3SPaolo Bonzini 	return ret;
5654c50d8ae3SPaolo Bonzini }
5655c50d8ae3SPaolo Bonzini 
5656c50d8ae3SPaolo Bonzini #define BATCH_ZAP_PAGES	10
5657c50d8ae3SPaolo Bonzini static void kvm_zap_obsolete_pages(struct kvm *kvm)
5658c50d8ae3SPaolo Bonzini {
5659c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
5660c50d8ae3SPaolo Bonzini 	int nr_zapped, batch = 0;
5661c50d8ae3SPaolo Bonzini 
5662c50d8ae3SPaolo Bonzini restart:
5663c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe_reverse(sp, node,
5664c50d8ae3SPaolo Bonzini 	      &kvm->arch.active_mmu_pages, link) {
5665c50d8ae3SPaolo Bonzini 		/*
5666c50d8ae3SPaolo Bonzini 		 * No obsolete valid page exists before a newly created page
5667c50d8ae3SPaolo Bonzini 		 * since active_mmu_pages is a FIFO list.
5668c50d8ae3SPaolo Bonzini 		 */
5669c50d8ae3SPaolo Bonzini 		if (!is_obsolete_sp(kvm, sp))
5670c50d8ae3SPaolo Bonzini 			break;
5671c50d8ae3SPaolo Bonzini 
5672c50d8ae3SPaolo Bonzini 		/*
5673f95eec9bSSean Christopherson 		 * Invalid pages should never land back on the list of active
5674f95eec9bSSean Christopherson 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
5675f95eec9bSSean Christopherson 		 * infinite loop if the page gets put back on the list (again).
5676c50d8ae3SPaolo Bonzini 		 */
5677f95eec9bSSean Christopherson 		if (WARN_ON(sp->role.invalid))
5678c50d8ae3SPaolo Bonzini 			continue;
5679c50d8ae3SPaolo Bonzini 
5680c50d8ae3SPaolo Bonzini 		/*
5681c50d8ae3SPaolo Bonzini 		 * No need to flush the TLB since we're only zapping shadow
5682c50d8ae3SPaolo Bonzini 		 * pages with an obsolete generation number and all vCPUS have
5683c50d8ae3SPaolo Bonzini 		 * loaded a new root, i.e. the shadow pages being zapped cannot
5684c50d8ae3SPaolo Bonzini 		 * be in active use by the guest.
5685c50d8ae3SPaolo Bonzini 		 */
5686c50d8ae3SPaolo Bonzini 		if (batch >= BATCH_ZAP_PAGES &&
5687531810caSBen Gardon 		    cond_resched_rwlock_write(&kvm->mmu_lock)) {
5688c50d8ae3SPaolo Bonzini 			batch = 0;
5689c50d8ae3SPaolo Bonzini 			goto restart;
5690c50d8ae3SPaolo Bonzini 		}
5691c50d8ae3SPaolo Bonzini 
5692c50d8ae3SPaolo Bonzini 		if (__kvm_mmu_prepare_zap_page(kvm, sp,
5693c50d8ae3SPaolo Bonzini 				&kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
5694c50d8ae3SPaolo Bonzini 			batch += nr_zapped;
5695c50d8ae3SPaolo Bonzini 			goto restart;
5696c50d8ae3SPaolo Bonzini 		}
5697c50d8ae3SPaolo Bonzini 	}
5698c50d8ae3SPaolo Bonzini 
5699c50d8ae3SPaolo Bonzini 	/*
57007ae5840eSSean Christopherson 	 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
57017ae5840eSSean Christopherson 	 * to ensure KVM is not in the middle of a lockless shadow page table
57027ae5840eSSean Christopherson 	 * walk, which may reference the pages.  The remote TLB flush itself is
57037ae5840eSSean Christopherson 	 * not required and is simply a convenient way to kick vCPUs as needed.
57047ae5840eSSean Christopherson 	 * KVM performs a local TLB flush when allocating a new root (see
57057ae5840eSSean Christopherson 	 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
57067ae5840eSSean Christopherson 	 * running with an obsolete MMU.
5707c50d8ae3SPaolo Bonzini 	 */
5708c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5709c50d8ae3SPaolo Bonzini }
5710c50d8ae3SPaolo Bonzini 
5711c50d8ae3SPaolo Bonzini /*
5712c50d8ae3SPaolo Bonzini  * Fast invalidate all shadow pages and use lock-break technique
5713c50d8ae3SPaolo Bonzini  * to zap obsolete pages.
5714c50d8ae3SPaolo Bonzini  *
5715c50d8ae3SPaolo Bonzini  * It's required when memslot is being deleted or VM is being
5716c50d8ae3SPaolo Bonzini  * destroyed, in these cases, we should ensure that KVM MMU does
5717c50d8ae3SPaolo Bonzini  * not use any resource of the being-deleted slot or all slots
5718c50d8ae3SPaolo Bonzini  * after calling the function.
5719c50d8ae3SPaolo Bonzini  */
5720c50d8ae3SPaolo Bonzini static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5721c50d8ae3SPaolo Bonzini {
5722c50d8ae3SPaolo Bonzini 	lockdep_assert_held(&kvm->slots_lock);
5723c50d8ae3SPaolo Bonzini 
5724531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
5725c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_zap_all_fast(kvm);
5726c50d8ae3SPaolo Bonzini 
5727c50d8ae3SPaolo Bonzini 	/*
5728c50d8ae3SPaolo Bonzini 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
5729c50d8ae3SPaolo Bonzini 	 * held for the entire duration of zapping obsolete pages, it's
5730c50d8ae3SPaolo Bonzini 	 * impossible for there to be multiple invalid generations associated
5731c50d8ae3SPaolo Bonzini 	 * with *valid* shadow pages at any given time, i.e. there is exactly
5732c50d8ae3SPaolo Bonzini 	 * one valid generation and (at most) one invalid generation.
5733c50d8ae3SPaolo Bonzini 	 */
5734c50d8ae3SPaolo Bonzini 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5735c50d8ae3SPaolo Bonzini 
57362f6f66ccSSean Christopherson 	/*
57372f6f66ccSSean Christopherson 	 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
57382f6f66ccSSean Christopherson 	 * invalidating TDP MMU roots must be done while holding mmu_lock for
57392f6f66ccSSean Christopherson 	 * write and in the same critical section as making the reload request,
57402f6f66ccSSean Christopherson 	 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
5741b7cccd39SBen Gardon 	 */
5742b7cccd39SBen Gardon 	if (is_tdp_mmu_enabled(kvm))
5743b7cccd39SBen Gardon 		kvm_tdp_mmu_invalidate_all_roots(kvm);
5744b7cccd39SBen Gardon 
5745c50d8ae3SPaolo Bonzini 	/*
5746c50d8ae3SPaolo Bonzini 	 * Notify all vcpus to reload its shadow page table and flush TLB.
5747c50d8ae3SPaolo Bonzini 	 * Then all vcpus will switch to new shadow page table with the new
5748c50d8ae3SPaolo Bonzini 	 * mmu_valid_gen.
5749c50d8ae3SPaolo Bonzini 	 *
5750c50d8ae3SPaolo Bonzini 	 * Note: we need to do this under the protection of mmu_lock,
5751c50d8ae3SPaolo Bonzini 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
5752c50d8ae3SPaolo Bonzini 	 */
5753527d5cd7SSean Christopherson 	kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
5754c50d8ae3SPaolo Bonzini 
5755c50d8ae3SPaolo Bonzini 	kvm_zap_obsolete_pages(kvm);
5756faaf05b0SBen Gardon 
5757531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
57584c6654bdSBen Gardon 
5759f28e9c7fSSean Christopherson 	/*
5760f28e9c7fSSean Christopherson 	 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
5761f28e9c7fSSean Christopherson 	 * returning to the caller, e.g. if the zap is in response to a memslot
5762f28e9c7fSSean Christopherson 	 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
5763f28e9c7fSSean Christopherson 	 * associated with the deleted memslot once the update completes, and
5764f28e9c7fSSean Christopherson 	 * Deferring the zap until the final reference to the root is put would
5765f28e9c7fSSean Christopherson 	 * lead to use-after-free.
5766f28e9c7fSSean Christopherson 	 */
576722b94c4bSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
57684c6654bdSBen Gardon 		kvm_tdp_mmu_zap_invalidated_roots(kvm);
5769c50d8ae3SPaolo Bonzini }
5770c50d8ae3SPaolo Bonzini 
5771c50d8ae3SPaolo Bonzini static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5772c50d8ae3SPaolo Bonzini {
5773c50d8ae3SPaolo Bonzini 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5774c50d8ae3SPaolo Bonzini }
5775c50d8ae3SPaolo Bonzini 
5776c50d8ae3SPaolo Bonzini static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5777c50d8ae3SPaolo Bonzini 			struct kvm_memory_slot *slot,
5778c50d8ae3SPaolo Bonzini 			struct kvm_page_track_notifier_node *node)
5779c50d8ae3SPaolo Bonzini {
5780c50d8ae3SPaolo Bonzini 	kvm_mmu_zap_all_fast(kvm);
5781c50d8ae3SPaolo Bonzini }
5782c50d8ae3SPaolo Bonzini 
5783a1a39128SPaolo Bonzini int kvm_mmu_init_vm(struct kvm *kvm)
5784c50d8ae3SPaolo Bonzini {
5785c50d8ae3SPaolo Bonzini 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5786a1a39128SPaolo Bonzini 	int r;
5787c50d8ae3SPaolo Bonzini 
5788a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
5789a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
5790a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
5791ce25681dSSean Christopherson 	spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
5792ce25681dSSean Christopherson 
5793a1a39128SPaolo Bonzini 	r = kvm_mmu_init_tdp_mmu(kvm);
5794a1a39128SPaolo Bonzini 	if (r < 0)
5795a1a39128SPaolo Bonzini 		return r;
5796fe5db27dSBen Gardon 
5797c50d8ae3SPaolo Bonzini 	node->track_write = kvm_mmu_pte_write;
5798c50d8ae3SPaolo Bonzini 	node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5799c50d8ae3SPaolo Bonzini 	kvm_page_track_register_notifier(kvm, node);
5800a1a39128SPaolo Bonzini 	return 0;
5801c50d8ae3SPaolo Bonzini }
5802c50d8ae3SPaolo Bonzini 
5803c50d8ae3SPaolo Bonzini void kvm_mmu_uninit_vm(struct kvm *kvm)
5804c50d8ae3SPaolo Bonzini {
5805c50d8ae3SPaolo Bonzini 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5806c50d8ae3SPaolo Bonzini 
5807c50d8ae3SPaolo Bonzini 	kvm_page_track_unregister_notifier(kvm, node);
5808fe5db27dSBen Gardon 
5809fe5db27dSBen Gardon 	kvm_mmu_uninit_tdp_mmu(kvm);
5810c50d8ae3SPaolo Bonzini }
5811c50d8ae3SPaolo Bonzini 
581221fa3246SSean Christopherson static bool __kvm_zap_rmaps(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
581321fa3246SSean Christopherson {
581421fa3246SSean Christopherson 	const struct kvm_memory_slot *memslot;
581521fa3246SSean Christopherson 	struct kvm_memslots *slots;
5816f4209439SMaciej S. Szmigiero 	struct kvm_memslot_iter iter;
581721fa3246SSean Christopherson 	bool flush = false;
581821fa3246SSean Christopherson 	gfn_t start, end;
5819f4209439SMaciej S. Szmigiero 	int i;
582021fa3246SSean Christopherson 
582121fa3246SSean Christopherson 	if (!kvm_memslots_have_rmaps(kvm))
582221fa3246SSean Christopherson 		return flush;
582321fa3246SSean Christopherson 
582421fa3246SSean Christopherson 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
582521fa3246SSean Christopherson 		slots = __kvm_memslots(kvm, i);
5826f4209439SMaciej S. Szmigiero 
5827f4209439SMaciej S. Szmigiero 		kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
5828f4209439SMaciej S. Szmigiero 			memslot = iter.slot;
582921fa3246SSean Christopherson 			start = max(gfn_start, memslot->base_gfn);
583021fa3246SSean Christopherson 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
5831f4209439SMaciej S. Szmigiero 			if (WARN_ON_ONCE(start >= end))
583221fa3246SSean Christopherson 				continue;
583321fa3246SSean Christopherson 
583421fa3246SSean Christopherson 			flush = slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
58356ff94f27SDavid Matlack 
583621fa3246SSean Christopherson 							PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
583721fa3246SSean Christopherson 							start, end - 1, true, flush);
583821fa3246SSean Christopherson 		}
583921fa3246SSean Christopherson 	}
584021fa3246SSean Christopherson 
584121fa3246SSean Christopherson 	return flush;
584221fa3246SSean Christopherson }
584321fa3246SSean Christopherson 
584488f58535SMaxim Levitsky /*
584588f58535SMaxim Levitsky  * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
584688f58535SMaxim Levitsky  * (not including it)
584788f58535SMaxim Levitsky  */
5848c50d8ae3SPaolo Bonzini void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5849c50d8ae3SPaolo Bonzini {
585021fa3246SSean Christopherson 	bool flush;
5851c50d8ae3SPaolo Bonzini 	int i;
5852c50d8ae3SPaolo Bonzini 
5853f4209439SMaciej S. Szmigiero 	if (WARN_ON_ONCE(gfn_end <= gfn_start))
5854f4209439SMaciej S. Szmigiero 		return;
5855f4209439SMaciej S. Szmigiero 
5856531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
58575a324c24SSean Christopherson 
5858edb298c6SMaxim Levitsky 	kvm_inc_notifier_count(kvm, gfn_start, gfn_end);
5859edb298c6SMaxim Levitsky 
586021fa3246SSean Christopherson 	flush = __kvm_zap_rmaps(kvm, gfn_start, gfn_end);
58616103bc07SBen Gardon 
58626103bc07SBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
58636103bc07SBen Gardon 		for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
5864f47e5bbbSSean Christopherson 			flush = kvm_tdp_mmu_zap_leafs(kvm, i, gfn_start,
5865f47e5bbbSSean Christopherson 						      gfn_end, true, flush);
58666103bc07SBen Gardon 	}
58675a324c24SSean Christopherson 
58685a324c24SSean Christopherson 	if (flush)
5869bc3b3c10SSean Christopherson 		kvm_flush_remote_tlbs_with_address(kvm, gfn_start,
5870bc3b3c10SSean Christopherson 						   gfn_end - gfn_start);
58715a324c24SSean Christopherson 
5872edb298c6SMaxim Levitsky 	kvm_dec_notifier_count(kvm, gfn_start, gfn_end);
5873edb298c6SMaxim Levitsky 
58745a324c24SSean Christopherson 	write_unlock(&kvm->mmu_lock);
5875c50d8ae3SPaolo Bonzini }
5876c50d8ae3SPaolo Bonzini 
5877c50d8ae3SPaolo Bonzini static bool slot_rmap_write_protect(struct kvm *kvm,
58780a234f5dSSean Christopherson 				    struct kvm_rmap_head *rmap_head,
5879269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot)
5880c50d8ae3SPaolo Bonzini {
58811346bbb6SDavid Matlack 	return rmap_write_protect(rmap_head, false);
5882c50d8ae3SPaolo Bonzini }
5883c50d8ae3SPaolo Bonzini 
5884c50d8ae3SPaolo Bonzini void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5885269e9552SHamza Mahfooz 				      const struct kvm_memory_slot *memslot,
58863c9bd400SJay Zhou 				      int start_level)
5887c50d8ae3SPaolo Bonzini {
5888e2209710SBen Gardon 	bool flush = false;
5889c50d8ae3SPaolo Bonzini 
5890e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
5891531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
58923c9bd400SJay Zhou 		flush = slot_handle_level(kvm, memslot, slot_rmap_write_protect,
5893e2209710SBen Gardon 					  start_level, KVM_MAX_HUGEPAGE_LEVEL,
5894e2209710SBen Gardon 					  false);
5895531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
5896e2209710SBen Gardon 	}
5897c50d8ae3SPaolo Bonzini 
589824ae4cfaSBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
589924ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
590024ae4cfaSBen Gardon 		flush |= kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
590124ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
590224ae4cfaSBen Gardon 	}
590324ae4cfaSBen Gardon 
5904c50d8ae3SPaolo Bonzini 	/*
59056ff94f27SDavid Matlack 	 * Flush TLBs if any SPTEs had to be write-protected to ensure that
59066ff94f27SDavid Matlack 	 * guest writes are reflected in the dirty bitmap before the memslot
59076ff94f27SDavid Matlack 	 * update completes, i.e. before enabling dirty logging is visible to
59086ff94f27SDavid Matlack 	 * userspace.
59096ff94f27SDavid Matlack 	 *
59106ff94f27SDavid Matlack 	 * Perform the TLB flush outside the mmu_lock to reduce the amount of
59116ff94f27SDavid Matlack 	 * time the lock is held. However, this does mean that another CPU can
59126ff94f27SDavid Matlack 	 * now grab mmu_lock and encounter a write-protected SPTE while CPUs
59136ff94f27SDavid Matlack 	 * still have a writable mapping for the associated GFN in their TLB.
59146ff94f27SDavid Matlack 	 *
59156ff94f27SDavid Matlack 	 * This is safe but requires KVM to be careful when making decisions
59166ff94f27SDavid Matlack 	 * based on the write-protection status of an SPTE. Specifically, KVM
59176ff94f27SDavid Matlack 	 * also write-protects SPTEs to monitor changes to guest page tables
59186ff94f27SDavid Matlack 	 * during shadow paging, and must guarantee no CPUs can write to those
59196ff94f27SDavid Matlack 	 * page before the lock is dropped. As mentioned in the previous
59206ff94f27SDavid Matlack 	 * paragraph, a write-protected SPTE is no guarantee that CPU cannot
59216ff94f27SDavid Matlack 	 * perform writes. So to determine if a TLB flush is truly required, KVM
59226ff94f27SDavid Matlack 	 * will clear a separate software-only bit (MMU-writable) and skip the
59236ff94f27SDavid Matlack 	 * flush if-and-only-if this bit was already clear.
59246ff94f27SDavid Matlack 	 *
592502844ac1SDavid Matlack 	 * See is_writable_pte() for more details.
5926c50d8ae3SPaolo Bonzini 	 */
5927c50d8ae3SPaolo Bonzini 	if (flush)
59287f42aa76SSean Christopherson 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
5929c50d8ae3SPaolo Bonzini }
5930c50d8ae3SPaolo Bonzini 
5931cb00a70bSDavid Matlack /* Must be called with the mmu_lock held in write-mode. */
5932cb00a70bSDavid Matlack void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
5933cb00a70bSDavid Matlack 				   const struct kvm_memory_slot *memslot,
5934cb00a70bSDavid Matlack 				   u64 start, u64 end,
5935cb00a70bSDavid Matlack 				   int target_level)
5936cb00a70bSDavid Matlack {
5937cb00a70bSDavid Matlack 	if (is_tdp_mmu_enabled(kvm))
5938cb00a70bSDavid Matlack 		kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end,
5939cb00a70bSDavid Matlack 						 target_level, false);
5940cb00a70bSDavid Matlack 
5941cb00a70bSDavid Matlack 	/*
5942cb00a70bSDavid Matlack 	 * A TLB flush is unnecessary at this point for the same resons as in
5943cb00a70bSDavid Matlack 	 * kvm_mmu_slot_try_split_huge_pages().
5944cb00a70bSDavid Matlack 	 */
5945cb00a70bSDavid Matlack }
5946cb00a70bSDavid Matlack 
5947a3fe5dbdSDavid Matlack void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
5948a3fe5dbdSDavid Matlack 					const struct kvm_memory_slot *memslot,
5949a3fe5dbdSDavid Matlack 					int target_level)
5950a3fe5dbdSDavid Matlack {
5951a3fe5dbdSDavid Matlack 	u64 start = memslot->base_gfn;
5952a3fe5dbdSDavid Matlack 	u64 end = start + memslot->npages;
5953a3fe5dbdSDavid Matlack 
5954a3fe5dbdSDavid Matlack 	if (is_tdp_mmu_enabled(kvm)) {
5955a3fe5dbdSDavid Matlack 		read_lock(&kvm->mmu_lock);
5956cb00a70bSDavid Matlack 		kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
5957a3fe5dbdSDavid Matlack 		read_unlock(&kvm->mmu_lock);
5958a3fe5dbdSDavid Matlack 	}
5959a3fe5dbdSDavid Matlack 
5960a3fe5dbdSDavid Matlack 	/*
5961a3fe5dbdSDavid Matlack 	 * No TLB flush is necessary here. KVM will flush TLBs after
5962a3fe5dbdSDavid Matlack 	 * write-protecting and/or clearing dirty on the newly split SPTEs to
5963a3fe5dbdSDavid Matlack 	 * ensure that guest writes are reflected in the dirty log before the
5964a3fe5dbdSDavid Matlack 	 * ioctl to enable dirty logging on this memslot completes. Since the
5965a3fe5dbdSDavid Matlack 	 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
5966a3fe5dbdSDavid Matlack 	 * safe for KVM to decide if a TLB flush is necessary based on the split
5967a3fe5dbdSDavid Matlack 	 * SPTEs.
5968a3fe5dbdSDavid Matlack 	 */
5969a3fe5dbdSDavid Matlack }
5970a3fe5dbdSDavid Matlack 
5971c50d8ae3SPaolo Bonzini static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
59720a234f5dSSean Christopherson 					 struct kvm_rmap_head *rmap_head,
5973269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
5974c50d8ae3SPaolo Bonzini {
5975c50d8ae3SPaolo Bonzini 	u64 *sptep;
5976c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
5977c50d8ae3SPaolo Bonzini 	int need_tlb_flush = 0;
5978c50d8ae3SPaolo Bonzini 	kvm_pfn_t pfn;
5979c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
5980c50d8ae3SPaolo Bonzini 
5981c50d8ae3SPaolo Bonzini restart:
5982c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
598357354682SSean Christopherson 		sp = sptep_to_sp(sptep);
5984c50d8ae3SPaolo Bonzini 		pfn = spte_to_pfn(*sptep);
5985c50d8ae3SPaolo Bonzini 
5986c50d8ae3SPaolo Bonzini 		/*
5987c50d8ae3SPaolo Bonzini 		 * We cannot do huge page mapping for indirect shadow pages,
5988c50d8ae3SPaolo Bonzini 		 * which are found on the last rmap (level = 1) when not using
5989c50d8ae3SPaolo Bonzini 		 * tdp; such shadow pages are synced with the page table in
5990c50d8ae3SPaolo Bonzini 		 * the guest, and the guest page table is using 4K page size
5991c50d8ae3SPaolo Bonzini 		 * mapping if the indirect sp has level = 1.
5992c50d8ae3SPaolo Bonzini 		 */
5993c50d8ae3SPaolo Bonzini 		if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
59949eba50f8SSean Christopherson 		    sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
59959eba50f8SSean Christopherson 							       pfn, PG_LEVEL_NUM)) {
599671f51d2cSMingwei Zhang 			pte_list_remove(kvm, rmap_head, sptep);
5997c50d8ae3SPaolo Bonzini 
5998c50d8ae3SPaolo Bonzini 			if (kvm_available_flush_tlb_with_range())
5999c50d8ae3SPaolo Bonzini 				kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
6000c50d8ae3SPaolo Bonzini 					KVM_PAGES_PER_HPAGE(sp->role.level));
6001c50d8ae3SPaolo Bonzini 			else
6002c50d8ae3SPaolo Bonzini 				need_tlb_flush = 1;
6003c50d8ae3SPaolo Bonzini 
6004c50d8ae3SPaolo Bonzini 			goto restart;
6005c50d8ae3SPaolo Bonzini 		}
6006c50d8ae3SPaolo Bonzini 	}
6007c50d8ae3SPaolo Bonzini 
6008c50d8ae3SPaolo Bonzini 	return need_tlb_flush;
6009c50d8ae3SPaolo Bonzini }
6010c50d8ae3SPaolo Bonzini 
6011c50d8ae3SPaolo Bonzini void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6012269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *slot)
6013c50d8ae3SPaolo Bonzini {
6014e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6015531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6016610265eaSDavid Matlack 		/*
6017610265eaSDavid Matlack 		 * Zap only 4k SPTEs since the legacy MMU only supports dirty
6018610265eaSDavid Matlack 		 * logging at a 4k granularity and never creates collapsible
6019610265eaSDavid Matlack 		 * 2m SPTEs during dirty logging.
6020610265eaSDavid Matlack 		 */
60214b85c921SSean Christopherson 		if (slot_handle_level_4k(kvm, slot, kvm_mmu_zap_collapsible_spte, true))
6022302695a5SSean Christopherson 			kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
6023531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6024e2209710SBen Gardon 	}
60252db6f772SBen Gardon 
60262db6f772SBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
60272db6f772SBen Gardon 		read_lock(&kvm->mmu_lock);
60284b85c921SSean Christopherson 		kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
60292db6f772SBen Gardon 		read_unlock(&kvm->mmu_lock);
60302db6f772SBen Gardon 	}
6031c50d8ae3SPaolo Bonzini }
6032c50d8ae3SPaolo Bonzini 
6033b3594ffbSSean Christopherson void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
60346c9dd6d2SPaolo Bonzini 					const struct kvm_memory_slot *memslot)
6035b3594ffbSSean Christopherson {
6036b3594ffbSSean Christopherson 	/*
60377f42aa76SSean Christopherson 	 * All current use cases for flushing the TLBs for a specific memslot
6038302695a5SSean Christopherson 	 * related to dirty logging, and many do the TLB flush out of mmu_lock.
60397f42aa76SSean Christopherson 	 * The interaction between the various operations on memslot must be
60407f42aa76SSean Christopherson 	 * serialized by slots_locks to ensure the TLB flush from one operation
60417f42aa76SSean Christopherson 	 * is observed by any other operation on the same memslot.
6042b3594ffbSSean Christopherson 	 */
6043b3594ffbSSean Christopherson 	lockdep_assert_held(&kvm->slots_lock);
6044cec37648SSean Christopherson 	kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6045cec37648SSean Christopherson 					   memslot->npages);
6046b3594ffbSSean Christopherson }
6047b3594ffbSSean Christopherson 
6048c50d8ae3SPaolo Bonzini void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6049269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *memslot)
6050c50d8ae3SPaolo Bonzini {
6051e2209710SBen Gardon 	bool flush = false;
6052c50d8ae3SPaolo Bonzini 
6053e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6054531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6055610265eaSDavid Matlack 		/*
6056610265eaSDavid Matlack 		 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6057610265eaSDavid Matlack 		 * support dirty logging at a 4k granularity.
6058610265eaSDavid Matlack 		 */
6059610265eaSDavid Matlack 		flush = slot_handle_level_4k(kvm, memslot, __rmap_clear_dirty, false);
6060531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6061e2209710SBen Gardon 	}
6062c50d8ae3SPaolo Bonzini 
606324ae4cfaSBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
606424ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
606524ae4cfaSBen Gardon 		flush |= kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
606624ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
606724ae4cfaSBen Gardon 	}
606824ae4cfaSBen Gardon 
6069c50d8ae3SPaolo Bonzini 	/*
6070c50d8ae3SPaolo Bonzini 	 * It's also safe to flush TLBs out of mmu lock here as currently this
6071c50d8ae3SPaolo Bonzini 	 * function is only used for dirty logging, in which case flushing TLB
6072c50d8ae3SPaolo Bonzini 	 * out of mmu lock also guarantees no dirty pages will be lost in
6073c50d8ae3SPaolo Bonzini 	 * dirty_bitmap.
6074c50d8ae3SPaolo Bonzini 	 */
6075c50d8ae3SPaolo Bonzini 	if (flush)
60767f42aa76SSean Christopherson 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6077c50d8ae3SPaolo Bonzini }
6078c50d8ae3SPaolo Bonzini 
6079c50d8ae3SPaolo Bonzini void kvm_mmu_zap_all(struct kvm *kvm)
6080c50d8ae3SPaolo Bonzini {
6081c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6082c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6083c50d8ae3SPaolo Bonzini 	int ign;
6084c50d8ae3SPaolo Bonzini 
6085531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6086c50d8ae3SPaolo Bonzini restart:
6087c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6088f95eec9bSSean Christopherson 		if (WARN_ON(sp->role.invalid))
6089c50d8ae3SPaolo Bonzini 			continue;
6090c50d8ae3SPaolo Bonzini 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6091c50d8ae3SPaolo Bonzini 			goto restart;
6092531810caSBen Gardon 		if (cond_resched_rwlock_write(&kvm->mmu_lock))
6093c50d8ae3SPaolo Bonzini 			goto restart;
6094c50d8ae3SPaolo Bonzini 	}
6095c50d8ae3SPaolo Bonzini 
6096c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6097faaf05b0SBen Gardon 
6098897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
6099faaf05b0SBen Gardon 		kvm_tdp_mmu_zap_all(kvm);
6100faaf05b0SBen Gardon 
6101531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
6102c50d8ae3SPaolo Bonzini }
6103c50d8ae3SPaolo Bonzini 
6104c50d8ae3SPaolo Bonzini void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6105c50d8ae3SPaolo Bonzini {
6106c50d8ae3SPaolo Bonzini 	WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6107c50d8ae3SPaolo Bonzini 
6108c50d8ae3SPaolo Bonzini 	gen &= MMIO_SPTE_GEN_MASK;
6109c50d8ae3SPaolo Bonzini 
6110c50d8ae3SPaolo Bonzini 	/*
6111c50d8ae3SPaolo Bonzini 	 * Generation numbers are incremented in multiples of the number of
6112c50d8ae3SPaolo Bonzini 	 * address spaces in order to provide unique generations across all
6113c50d8ae3SPaolo Bonzini 	 * address spaces.  Strip what is effectively the address space
6114c50d8ae3SPaolo Bonzini 	 * modifier prior to checking for a wrap of the MMIO generation so
6115c50d8ae3SPaolo Bonzini 	 * that a wrap in any address space is detected.
6116c50d8ae3SPaolo Bonzini 	 */
6117c50d8ae3SPaolo Bonzini 	gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6118c50d8ae3SPaolo Bonzini 
6119c50d8ae3SPaolo Bonzini 	/*
6120c50d8ae3SPaolo Bonzini 	 * The very rare case: if the MMIO generation number has wrapped,
6121c50d8ae3SPaolo Bonzini 	 * zap all shadow pages.
6122c50d8ae3SPaolo Bonzini 	 */
6123c50d8ae3SPaolo Bonzini 	if (unlikely(gen == 0)) {
6124c50d8ae3SPaolo Bonzini 		kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6125c50d8ae3SPaolo Bonzini 		kvm_mmu_zap_all_fast(kvm);
6126c50d8ae3SPaolo Bonzini 	}
6127c50d8ae3SPaolo Bonzini }
6128c50d8ae3SPaolo Bonzini 
6129c50d8ae3SPaolo Bonzini static unsigned long
6130c50d8ae3SPaolo Bonzini mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6131c50d8ae3SPaolo Bonzini {
6132c50d8ae3SPaolo Bonzini 	struct kvm *kvm;
6133c50d8ae3SPaolo Bonzini 	int nr_to_scan = sc->nr_to_scan;
6134c50d8ae3SPaolo Bonzini 	unsigned long freed = 0;
6135c50d8ae3SPaolo Bonzini 
6136c50d8ae3SPaolo Bonzini 	mutex_lock(&kvm_lock);
6137c50d8ae3SPaolo Bonzini 
6138c50d8ae3SPaolo Bonzini 	list_for_each_entry(kvm, &vm_list, vm_list) {
6139c50d8ae3SPaolo Bonzini 		int idx;
6140c50d8ae3SPaolo Bonzini 		LIST_HEAD(invalid_list);
6141c50d8ae3SPaolo Bonzini 
6142c50d8ae3SPaolo Bonzini 		/*
6143c50d8ae3SPaolo Bonzini 		 * Never scan more than sc->nr_to_scan VM instances.
6144c50d8ae3SPaolo Bonzini 		 * Will not hit this condition practically since we do not try
6145c50d8ae3SPaolo Bonzini 		 * to shrink more than one VM and it is very unlikely to see
6146c50d8ae3SPaolo Bonzini 		 * !n_used_mmu_pages so many times.
6147c50d8ae3SPaolo Bonzini 		 */
6148c50d8ae3SPaolo Bonzini 		if (!nr_to_scan--)
6149c50d8ae3SPaolo Bonzini 			break;
6150c50d8ae3SPaolo Bonzini 		/*
6151c50d8ae3SPaolo Bonzini 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6152c50d8ae3SPaolo Bonzini 		 * here. We may skip a VM instance errorneosly, but we do not
6153c50d8ae3SPaolo Bonzini 		 * want to shrink a VM that only started to populate its MMU
6154c50d8ae3SPaolo Bonzini 		 * anyway.
6155c50d8ae3SPaolo Bonzini 		 */
6156c50d8ae3SPaolo Bonzini 		if (!kvm->arch.n_used_mmu_pages &&
6157c50d8ae3SPaolo Bonzini 		    !kvm_has_zapped_obsolete_pages(kvm))
6158c50d8ae3SPaolo Bonzini 			continue;
6159c50d8ae3SPaolo Bonzini 
6160c50d8ae3SPaolo Bonzini 		idx = srcu_read_lock(&kvm->srcu);
6161531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6162c50d8ae3SPaolo Bonzini 
6163c50d8ae3SPaolo Bonzini 		if (kvm_has_zapped_obsolete_pages(kvm)) {
6164c50d8ae3SPaolo Bonzini 			kvm_mmu_commit_zap_page(kvm,
6165c50d8ae3SPaolo Bonzini 			      &kvm->arch.zapped_obsolete_pages);
6166c50d8ae3SPaolo Bonzini 			goto unlock;
6167c50d8ae3SPaolo Bonzini 		}
6168c50d8ae3SPaolo Bonzini 
6169ebdb292dSSean Christopherson 		freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6170c50d8ae3SPaolo Bonzini 
6171c50d8ae3SPaolo Bonzini unlock:
6172531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6173c50d8ae3SPaolo Bonzini 		srcu_read_unlock(&kvm->srcu, idx);
6174c50d8ae3SPaolo Bonzini 
6175c50d8ae3SPaolo Bonzini 		/*
6176c50d8ae3SPaolo Bonzini 		 * unfair on small ones
6177c50d8ae3SPaolo Bonzini 		 * per-vm shrinkers cry out
6178c50d8ae3SPaolo Bonzini 		 * sadness comes quickly
6179c50d8ae3SPaolo Bonzini 		 */
6180c50d8ae3SPaolo Bonzini 		list_move_tail(&kvm->vm_list, &vm_list);
6181c50d8ae3SPaolo Bonzini 		break;
6182c50d8ae3SPaolo Bonzini 	}
6183c50d8ae3SPaolo Bonzini 
6184c50d8ae3SPaolo Bonzini 	mutex_unlock(&kvm_lock);
6185c50d8ae3SPaolo Bonzini 	return freed;
6186c50d8ae3SPaolo Bonzini }
6187c50d8ae3SPaolo Bonzini 
6188c50d8ae3SPaolo Bonzini static unsigned long
6189c50d8ae3SPaolo Bonzini mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6190c50d8ae3SPaolo Bonzini {
6191c50d8ae3SPaolo Bonzini 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6192c50d8ae3SPaolo Bonzini }
6193c50d8ae3SPaolo Bonzini 
6194c50d8ae3SPaolo Bonzini static struct shrinker mmu_shrinker = {
6195c50d8ae3SPaolo Bonzini 	.count_objects = mmu_shrink_count,
6196c50d8ae3SPaolo Bonzini 	.scan_objects = mmu_shrink_scan,
6197c50d8ae3SPaolo Bonzini 	.seeks = DEFAULT_SEEKS * 10,
6198c50d8ae3SPaolo Bonzini };
6199c50d8ae3SPaolo Bonzini 
6200c50d8ae3SPaolo Bonzini static void mmu_destroy_caches(void)
6201c50d8ae3SPaolo Bonzini {
6202c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(pte_list_desc_cache);
6203c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(mmu_page_header_cache);
6204c50d8ae3SPaolo Bonzini }
6205c50d8ae3SPaolo Bonzini 
6206c50d8ae3SPaolo Bonzini static bool get_nx_auto_mode(void)
6207c50d8ae3SPaolo Bonzini {
6208c50d8ae3SPaolo Bonzini 	/* Return true when CPU has the bug, and mitigations are ON */
6209c50d8ae3SPaolo Bonzini 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6210c50d8ae3SPaolo Bonzini }
6211c50d8ae3SPaolo Bonzini 
6212c50d8ae3SPaolo Bonzini static void __set_nx_huge_pages(bool val)
6213c50d8ae3SPaolo Bonzini {
6214c50d8ae3SPaolo Bonzini 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6215c50d8ae3SPaolo Bonzini }
6216c50d8ae3SPaolo Bonzini 
6217c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6218c50d8ae3SPaolo Bonzini {
6219c50d8ae3SPaolo Bonzini 	bool old_val = nx_huge_pages;
6220c50d8ae3SPaolo Bonzini 	bool new_val;
6221c50d8ae3SPaolo Bonzini 
6222c50d8ae3SPaolo Bonzini 	/* In "auto" mode deploy workaround only if CPU has the bug. */
6223c50d8ae3SPaolo Bonzini 	if (sysfs_streq(val, "off"))
6224c50d8ae3SPaolo Bonzini 		new_val = 0;
6225c50d8ae3SPaolo Bonzini 	else if (sysfs_streq(val, "force"))
6226c50d8ae3SPaolo Bonzini 		new_val = 1;
6227c50d8ae3SPaolo Bonzini 	else if (sysfs_streq(val, "auto"))
6228c50d8ae3SPaolo Bonzini 		new_val = get_nx_auto_mode();
6229c50d8ae3SPaolo Bonzini 	else if (strtobool(val, &new_val) < 0)
6230c50d8ae3SPaolo Bonzini 		return -EINVAL;
6231c50d8ae3SPaolo Bonzini 
6232c50d8ae3SPaolo Bonzini 	__set_nx_huge_pages(new_val);
6233c50d8ae3SPaolo Bonzini 
6234c50d8ae3SPaolo Bonzini 	if (new_val != old_val) {
6235c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6236c50d8ae3SPaolo Bonzini 
6237c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6238c50d8ae3SPaolo Bonzini 
6239c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list) {
6240c50d8ae3SPaolo Bonzini 			mutex_lock(&kvm->slots_lock);
6241c50d8ae3SPaolo Bonzini 			kvm_mmu_zap_all_fast(kvm);
6242c50d8ae3SPaolo Bonzini 			mutex_unlock(&kvm->slots_lock);
6243c50d8ae3SPaolo Bonzini 
6244c50d8ae3SPaolo Bonzini 			wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6245c50d8ae3SPaolo Bonzini 		}
6246c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6247c50d8ae3SPaolo Bonzini 	}
6248c50d8ae3SPaolo Bonzini 
6249c50d8ae3SPaolo Bonzini 	return 0;
6250c50d8ae3SPaolo Bonzini }
6251c50d8ae3SPaolo Bonzini 
62521d0e8480SSean Christopherson /*
62531d0e8480SSean Christopherson  * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
62541d0e8480SSean Christopherson  * its default value of -1 is technically undefined behavior for a boolean.
62551d0e8480SSean Christopherson  */
62561d0e8480SSean Christopherson void kvm_mmu_x86_module_init(void)
6257c50d8ae3SPaolo Bonzini {
6258c50d8ae3SPaolo Bonzini 	if (nx_huge_pages == -1)
6259c50d8ae3SPaolo Bonzini 		__set_nx_huge_pages(get_nx_auto_mode());
62601d0e8480SSean Christopherson }
62611d0e8480SSean Christopherson 
62621d0e8480SSean Christopherson /*
62631d0e8480SSean Christopherson  * The bulk of the MMU initialization is deferred until the vendor module is
62641d0e8480SSean Christopherson  * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
62651d0e8480SSean Christopherson  * to be reset when a potentially different vendor module is loaded.
62661d0e8480SSean Christopherson  */
62671d0e8480SSean Christopherson int kvm_mmu_vendor_module_init(void)
62681d0e8480SSean Christopherson {
62691d0e8480SSean Christopherson 	int ret = -ENOMEM;
6270c50d8ae3SPaolo Bonzini 
6271c50d8ae3SPaolo Bonzini 	/*
6272c50d8ae3SPaolo Bonzini 	 * MMU roles use union aliasing which is, generally speaking, an
6273c50d8ae3SPaolo Bonzini 	 * undefined behavior. However, we supposedly know how compilers behave
6274c50d8ae3SPaolo Bonzini 	 * and the current status quo is unlikely to change. Guardians below are
6275c50d8ae3SPaolo Bonzini 	 * supposed to let us know if the assumption becomes false.
6276c50d8ae3SPaolo Bonzini 	 */
6277c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6278c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6279c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6280c50d8ae3SPaolo Bonzini 
6281c50d8ae3SPaolo Bonzini 	kvm_mmu_reset_all_pte_masks();
6282c50d8ae3SPaolo Bonzini 
6283c50d8ae3SPaolo Bonzini 	pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6284c50d8ae3SPaolo Bonzini 					    sizeof(struct pte_list_desc),
6285c50d8ae3SPaolo Bonzini 					    0, SLAB_ACCOUNT, NULL);
6286c50d8ae3SPaolo Bonzini 	if (!pte_list_desc_cache)
6287c50d8ae3SPaolo Bonzini 		goto out;
6288c50d8ae3SPaolo Bonzini 
6289c50d8ae3SPaolo Bonzini 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6290c50d8ae3SPaolo Bonzini 						  sizeof(struct kvm_mmu_page),
6291c50d8ae3SPaolo Bonzini 						  0, SLAB_ACCOUNT, NULL);
6292c50d8ae3SPaolo Bonzini 	if (!mmu_page_header_cache)
6293c50d8ae3SPaolo Bonzini 		goto out;
6294c50d8ae3SPaolo Bonzini 
6295c50d8ae3SPaolo Bonzini 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6296c50d8ae3SPaolo Bonzini 		goto out;
6297c50d8ae3SPaolo Bonzini 
6298c50d8ae3SPaolo Bonzini 	ret = register_shrinker(&mmu_shrinker);
6299c50d8ae3SPaolo Bonzini 	if (ret)
6300c50d8ae3SPaolo Bonzini 		goto out;
6301c50d8ae3SPaolo Bonzini 
6302c50d8ae3SPaolo Bonzini 	return 0;
6303c50d8ae3SPaolo Bonzini 
6304c50d8ae3SPaolo Bonzini out:
6305c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6306c50d8ae3SPaolo Bonzini 	return ret;
6307c50d8ae3SPaolo Bonzini }
6308c50d8ae3SPaolo Bonzini 
6309c50d8ae3SPaolo Bonzini void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6310c50d8ae3SPaolo Bonzini {
6311c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
6312c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.root_mmu);
6313c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
6314c50d8ae3SPaolo Bonzini 	mmu_free_memory_caches(vcpu);
6315c50d8ae3SPaolo Bonzini }
6316c50d8ae3SPaolo Bonzini 
63171d0e8480SSean Christopherson void kvm_mmu_vendor_module_exit(void)
6318c50d8ae3SPaolo Bonzini {
6319c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6320c50d8ae3SPaolo Bonzini 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6321c50d8ae3SPaolo Bonzini 	unregister_shrinker(&mmu_shrinker);
6322c50d8ae3SPaolo Bonzini }
6323c50d8ae3SPaolo Bonzini 
6324f47491d7SSean Christopherson /*
6325f47491d7SSean Christopherson  * Calculate the effective recovery period, accounting for '0' meaning "let KVM
6326f47491d7SSean Christopherson  * select a halving time of 1 hour".  Returns true if recovery is enabled.
6327f47491d7SSean Christopherson  */
6328f47491d7SSean Christopherson static bool calc_nx_huge_pages_recovery_period(uint *period)
6329f47491d7SSean Christopherson {
6330f47491d7SSean Christopherson 	/*
6331f47491d7SSean Christopherson 	 * Use READ_ONCE to get the params, this may be called outside of the
6332f47491d7SSean Christopherson 	 * param setters, e.g. by the kthread to compute its next timeout.
6333f47491d7SSean Christopherson 	 */
6334f47491d7SSean Christopherson 	bool enabled = READ_ONCE(nx_huge_pages);
6335f47491d7SSean Christopherson 	uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6336f47491d7SSean Christopherson 
6337f47491d7SSean Christopherson 	if (!enabled || !ratio)
6338f47491d7SSean Christopherson 		return false;
6339f47491d7SSean Christopherson 
6340f47491d7SSean Christopherson 	*period = READ_ONCE(nx_huge_pages_recovery_period_ms);
6341f47491d7SSean Christopherson 	if (!*period) {
6342f47491d7SSean Christopherson 		/* Make sure the period is not less than one second.  */
6343f47491d7SSean Christopherson 		ratio = min(ratio, 3600u);
6344f47491d7SSean Christopherson 		*period = 60 * 60 * 1000 / ratio;
6345f47491d7SSean Christopherson 	}
6346f47491d7SSean Christopherson 	return true;
6347f47491d7SSean Christopherson }
6348f47491d7SSean Christopherson 
63494dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
6350c50d8ae3SPaolo Bonzini {
63514dfe4f40SJunaid Shahid 	bool was_recovery_enabled, is_recovery_enabled;
63524dfe4f40SJunaid Shahid 	uint old_period, new_period;
6353c50d8ae3SPaolo Bonzini 	int err;
6354c50d8ae3SPaolo Bonzini 
6355f47491d7SSean Christopherson 	was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
63564dfe4f40SJunaid Shahid 
6357c50d8ae3SPaolo Bonzini 	err = param_set_uint(val, kp);
6358c50d8ae3SPaolo Bonzini 	if (err)
6359c50d8ae3SPaolo Bonzini 		return err;
6360c50d8ae3SPaolo Bonzini 
6361f47491d7SSean Christopherson 	is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
63624dfe4f40SJunaid Shahid 
6363f47491d7SSean Christopherson 	if (is_recovery_enabled &&
63644dfe4f40SJunaid Shahid 	    (!was_recovery_enabled || old_period > new_period)) {
6365c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6366c50d8ae3SPaolo Bonzini 
6367c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6368c50d8ae3SPaolo Bonzini 
6369c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list)
6370c50d8ae3SPaolo Bonzini 			wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6371c50d8ae3SPaolo Bonzini 
6372c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6373c50d8ae3SPaolo Bonzini 	}
6374c50d8ae3SPaolo Bonzini 
6375c50d8ae3SPaolo Bonzini 	return err;
6376c50d8ae3SPaolo Bonzini }
6377c50d8ae3SPaolo Bonzini 
6378c50d8ae3SPaolo Bonzini static void kvm_recover_nx_lpages(struct kvm *kvm)
6379c50d8ae3SPaolo Bonzini {
6380ade74e14SSean Christopherson 	unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
6381c50d8ae3SPaolo Bonzini 	int rcu_idx;
6382c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6383c50d8ae3SPaolo Bonzini 	unsigned int ratio;
6384c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6385048f4980SSean Christopherson 	bool flush = false;
6386c50d8ae3SPaolo Bonzini 	ulong to_zap;
6387c50d8ae3SPaolo Bonzini 
6388c50d8ae3SPaolo Bonzini 	rcu_idx = srcu_read_lock(&kvm->srcu);
6389531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6390c50d8ae3SPaolo Bonzini 
6391bb95dfb9SSean Christopherson 	/*
6392bb95dfb9SSean Christopherson 	 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
6393bb95dfb9SSean Christopherson 	 * be done under RCU protection, because the pages are freed via RCU
6394bb95dfb9SSean Christopherson 	 * callback.
6395bb95dfb9SSean Christopherson 	 */
6396bb95dfb9SSean Christopherson 	rcu_read_lock();
6397bb95dfb9SSean Christopherson 
6398c50d8ae3SPaolo Bonzini 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6399ade74e14SSean Christopherson 	to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
64007d919c7aSSean Christopherson 	for ( ; to_zap; --to_zap) {
64017d919c7aSSean Christopherson 		if (list_empty(&kvm->arch.lpage_disallowed_mmu_pages))
64027d919c7aSSean Christopherson 			break;
64037d919c7aSSean Christopherson 
6404c50d8ae3SPaolo Bonzini 		/*
6405c50d8ae3SPaolo Bonzini 		 * We use a separate list instead of just using active_mmu_pages
6406c50d8ae3SPaolo Bonzini 		 * because the number of lpage_disallowed pages is expected to
6407c50d8ae3SPaolo Bonzini 		 * be relatively small compared to the total.
6408c50d8ae3SPaolo Bonzini 		 */
6409c50d8ae3SPaolo Bonzini 		sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6410c50d8ae3SPaolo Bonzini 				      struct kvm_mmu_page,
6411c50d8ae3SPaolo Bonzini 				      lpage_disallowed_link);
6412c50d8ae3SPaolo Bonzini 		WARN_ON_ONCE(!sp->lpage_disallowed);
6413897218ffSPaolo Bonzini 		if (is_tdp_mmu_page(sp)) {
6414315f02c6SPaolo Bonzini 			flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
64158d1a182eSBen Gardon 		} else {
6416c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6417c50d8ae3SPaolo Bonzini 			WARN_ON_ONCE(sp->lpage_disallowed);
641829cf0f50SBen Gardon 		}
6419c50d8ae3SPaolo Bonzini 
6420531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
6421048f4980SSean Christopherson 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
6422bb95dfb9SSean Christopherson 			rcu_read_unlock();
6423bb95dfb9SSean Christopherson 
6424531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
6425048f4980SSean Christopherson 			flush = false;
6426bb95dfb9SSean Christopherson 
6427bb95dfb9SSean Christopherson 			rcu_read_lock();
6428c50d8ae3SPaolo Bonzini 		}
6429c50d8ae3SPaolo Bonzini 	}
6430048f4980SSean Christopherson 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
6431c50d8ae3SPaolo Bonzini 
6432bb95dfb9SSean Christopherson 	rcu_read_unlock();
6433bb95dfb9SSean Christopherson 
6434531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
6435c50d8ae3SPaolo Bonzini 	srcu_read_unlock(&kvm->srcu, rcu_idx);
6436c50d8ae3SPaolo Bonzini }
6437c50d8ae3SPaolo Bonzini 
6438c50d8ae3SPaolo Bonzini static long get_nx_lpage_recovery_timeout(u64 start_time)
6439c50d8ae3SPaolo Bonzini {
6440f47491d7SSean Christopherson 	bool enabled;
6441f47491d7SSean Christopherson 	uint period;
64424dfe4f40SJunaid Shahid 
6443f47491d7SSean Christopherson 	enabled = calc_nx_huge_pages_recovery_period(&period);
64444dfe4f40SJunaid Shahid 
6445f47491d7SSean Christopherson 	return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
6446c50d8ae3SPaolo Bonzini 		       : MAX_SCHEDULE_TIMEOUT;
6447c50d8ae3SPaolo Bonzini }
6448c50d8ae3SPaolo Bonzini 
6449c50d8ae3SPaolo Bonzini static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6450c50d8ae3SPaolo Bonzini {
6451c50d8ae3SPaolo Bonzini 	u64 start_time;
6452c50d8ae3SPaolo Bonzini 	long remaining_time;
6453c50d8ae3SPaolo Bonzini 
6454c50d8ae3SPaolo Bonzini 	while (true) {
6455c50d8ae3SPaolo Bonzini 		start_time = get_jiffies_64();
6456c50d8ae3SPaolo Bonzini 		remaining_time = get_nx_lpage_recovery_timeout(start_time);
6457c50d8ae3SPaolo Bonzini 
6458c50d8ae3SPaolo Bonzini 		set_current_state(TASK_INTERRUPTIBLE);
6459c50d8ae3SPaolo Bonzini 		while (!kthread_should_stop() && remaining_time > 0) {
6460c50d8ae3SPaolo Bonzini 			schedule_timeout(remaining_time);
6461c50d8ae3SPaolo Bonzini 			remaining_time = get_nx_lpage_recovery_timeout(start_time);
6462c50d8ae3SPaolo Bonzini 			set_current_state(TASK_INTERRUPTIBLE);
6463c50d8ae3SPaolo Bonzini 		}
6464c50d8ae3SPaolo Bonzini 
6465c50d8ae3SPaolo Bonzini 		set_current_state(TASK_RUNNING);
6466c50d8ae3SPaolo Bonzini 
6467c50d8ae3SPaolo Bonzini 		if (kthread_should_stop())
6468c50d8ae3SPaolo Bonzini 			return 0;
6469c50d8ae3SPaolo Bonzini 
6470c50d8ae3SPaolo Bonzini 		kvm_recover_nx_lpages(kvm);
6471c50d8ae3SPaolo Bonzini 	}
6472c50d8ae3SPaolo Bonzini }
6473c50d8ae3SPaolo Bonzini 
6474c50d8ae3SPaolo Bonzini int kvm_mmu_post_init_vm(struct kvm *kvm)
6475c50d8ae3SPaolo Bonzini {
6476c50d8ae3SPaolo Bonzini 	int err;
6477c50d8ae3SPaolo Bonzini 
6478c50d8ae3SPaolo Bonzini 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6479c50d8ae3SPaolo Bonzini 					  "kvm-nx-lpage-recovery",
6480c50d8ae3SPaolo Bonzini 					  &kvm->arch.nx_lpage_recovery_thread);
6481c50d8ae3SPaolo Bonzini 	if (!err)
6482c50d8ae3SPaolo Bonzini 		kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6483c50d8ae3SPaolo Bonzini 
6484c50d8ae3SPaolo Bonzini 	return err;
6485c50d8ae3SPaolo Bonzini }
6486c50d8ae3SPaolo Bonzini 
6487c50d8ae3SPaolo Bonzini void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6488c50d8ae3SPaolo Bonzini {
6489c50d8ae3SPaolo Bonzini 	if (kvm->arch.nx_lpage_recovery_thread)
6490c50d8ae3SPaolo Bonzini 		kthread_stop(kvm->arch.nx_lpage_recovery_thread);
6491c50d8ae3SPaolo Bonzini }
6492