xref: /linux/arch/x86/kvm/mmu/mmu.c (revision 94c8136448c80496cbfe0922bcb379bcf62cb8ac)
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 
56c50d8ae3SPaolo Bonzini extern bool itlb_multihit_kvm_mitigation;
57c50d8ae3SPaolo Bonzini 
58a9d6496dSShaokun Zhang int __read_mostly nx_huge_pages = -1;
594dfe4f40SJunaid Shahid static uint __read_mostly nx_huge_pages_recovery_period_ms;
60c50d8ae3SPaolo Bonzini #ifdef CONFIG_PREEMPT_RT
61c50d8ae3SPaolo Bonzini /* Recovery can cause latency spikes, disable it for PREEMPT_RT.  */
62c50d8ae3SPaolo Bonzini static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
63c50d8ae3SPaolo Bonzini #else
64c50d8ae3SPaolo Bonzini static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
65c50d8ae3SPaolo Bonzini #endif
66c50d8ae3SPaolo Bonzini 
67c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
684dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp);
69c50d8ae3SPaolo Bonzini 
70d5d6c18dSJoe Perches static const struct kernel_param_ops nx_huge_pages_ops = {
71c50d8ae3SPaolo Bonzini 	.set = set_nx_huge_pages,
72c50d8ae3SPaolo Bonzini 	.get = param_get_bool,
73c50d8ae3SPaolo Bonzini };
74c50d8ae3SPaolo Bonzini 
754dfe4f40SJunaid Shahid static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
764dfe4f40SJunaid Shahid 	.set = set_nx_huge_pages_recovery_param,
77c50d8ae3SPaolo Bonzini 	.get = param_get_uint,
78c50d8ae3SPaolo Bonzini };
79c50d8ae3SPaolo Bonzini 
80c50d8ae3SPaolo Bonzini module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
81c50d8ae3SPaolo Bonzini __MODULE_PARM_TYPE(nx_huge_pages, "bool");
824dfe4f40SJunaid Shahid module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_param_ops,
83c50d8ae3SPaolo Bonzini 		&nx_huge_pages_recovery_ratio, 0644);
84c50d8ae3SPaolo Bonzini __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
854dfe4f40SJunaid Shahid module_param_cb(nx_huge_pages_recovery_period_ms, &nx_huge_pages_recovery_param_ops,
864dfe4f40SJunaid Shahid 		&nx_huge_pages_recovery_period_ms, 0644);
874dfe4f40SJunaid Shahid __MODULE_PARM_TYPE(nx_huge_pages_recovery_period_ms, "uint");
88c50d8ae3SPaolo Bonzini 
8971fe7013SSean Christopherson static bool __read_mostly force_flush_and_sync_on_reuse;
9071fe7013SSean Christopherson module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
9171fe7013SSean Christopherson 
92c50d8ae3SPaolo Bonzini /*
93c50d8ae3SPaolo Bonzini  * When setting this variable to true it enables Two-Dimensional-Paging
94c50d8ae3SPaolo Bonzini  * where the hardware walks 2 page tables:
95c50d8ae3SPaolo Bonzini  * 1. the guest-virtual to guest-physical
96c50d8ae3SPaolo Bonzini  * 2. while doing 1. it walks guest-physical to host-physical
97c50d8ae3SPaolo Bonzini  * If the hardware supports that we don't need to do shadow paging.
98c50d8ae3SPaolo Bonzini  */
99c50d8ae3SPaolo Bonzini bool tdp_enabled = false;
100c50d8ae3SPaolo Bonzini 
1011d92d2e8SSean Christopherson static int max_huge_page_level __read_mostly;
102746700d2SWei Huang static int tdp_root_level __read_mostly;
10383013059SSean Christopherson static int max_tdp_level __read_mostly;
104703c335dSSean Christopherson 
105c50d8ae3SPaolo Bonzini #ifdef MMU_DEBUG
1065a9624afSPaolo Bonzini bool dbg = 0;
107c50d8ae3SPaolo Bonzini module_param(dbg, bool, 0644);
108c50d8ae3SPaolo Bonzini #endif
109c50d8ae3SPaolo Bonzini 
110c50d8ae3SPaolo Bonzini #define PTE_PREFETCH_NUM		8
111c50d8ae3SPaolo Bonzini 
112c50d8ae3SPaolo Bonzini #include <trace/events/kvm.h>
113c50d8ae3SPaolo Bonzini 
114dc1cff96SPeter Xu /* make pte_list_desc fit well in cache lines */
11513236e25SPeter Xu #define PTE_LIST_EXT 14
116c50d8ae3SPaolo Bonzini 
11713236e25SPeter Xu /*
11813236e25SPeter Xu  * Slight optimization of cacheline layout, by putting `more' and `spte_count'
11913236e25SPeter Xu  * at the start; then accessing it will only use one single cacheline for
12013236e25SPeter Xu  * either full (entries==PTE_LIST_EXT) case or entries<=6.
12113236e25SPeter Xu  */
122c50d8ae3SPaolo Bonzini struct pte_list_desc {
123c50d8ae3SPaolo Bonzini 	struct pte_list_desc *more;
12413236e25SPeter Xu 	/*
12513236e25SPeter Xu 	 * Stores number of entries stored in the pte_list_desc.  No need to be
12613236e25SPeter Xu 	 * u64 but just for easier alignment.  When PTE_LIST_EXT, means full.
12713236e25SPeter Xu 	 */
12813236e25SPeter Xu 	u64 spte_count;
12913236e25SPeter Xu 	u64 *sptes[PTE_LIST_EXT];
130c50d8ae3SPaolo Bonzini };
131c50d8ae3SPaolo Bonzini 
132c50d8ae3SPaolo Bonzini struct kvm_shadow_walk_iterator {
133c50d8ae3SPaolo Bonzini 	u64 addr;
134c50d8ae3SPaolo Bonzini 	hpa_t shadow_addr;
135c50d8ae3SPaolo Bonzini 	u64 *sptep;
136c50d8ae3SPaolo Bonzini 	int level;
137c50d8ae3SPaolo Bonzini 	unsigned index;
138c50d8ae3SPaolo Bonzini };
139c50d8ae3SPaolo Bonzini 
140c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
141c50d8ae3SPaolo Bonzini 	for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
142c50d8ae3SPaolo Bonzini 					 (_root), (_addr));                \
143c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			           \
144c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
145c50d8ae3SPaolo Bonzini 
146c50d8ae3SPaolo Bonzini #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
147c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);	\
148c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			\
149c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
150c50d8ae3SPaolo Bonzini 
151c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)	\
152c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);		\
153c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker)) &&				\
154c50d8ae3SPaolo Bonzini 		({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });	\
155c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&(_walker), spte))
156c50d8ae3SPaolo Bonzini 
157c50d8ae3SPaolo Bonzini static struct kmem_cache *pte_list_desc_cache;
15802c00b3aSBen Gardon struct kmem_cache *mmu_page_header_cache;
159c50d8ae3SPaolo Bonzini static struct percpu_counter kvm_total_used_mmu_pages;
160c50d8ae3SPaolo Bonzini 
161c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 spte);
162c50d8ae3SPaolo Bonzini 
163594e91a1SSean Christopherson struct kvm_mmu_role_regs {
164594e91a1SSean Christopherson 	const unsigned long cr0;
165594e91a1SSean Christopherson 	const unsigned long cr4;
166594e91a1SSean Christopherson 	const u64 efer;
167594e91a1SSean Christopherson };
168594e91a1SSean Christopherson 
169c50d8ae3SPaolo Bonzini #define CREATE_TRACE_POINTS
170c50d8ae3SPaolo Bonzini #include "mmutrace.h"
171c50d8ae3SPaolo Bonzini 
172594e91a1SSean Christopherson /*
173594e91a1SSean Christopherson  * Yes, lot's of underscores.  They're a hint that you probably shouldn't be
1747a458f0eSPaolo Bonzini  * reading from the role_regs.  Once the root_role is constructed, it becomes
175594e91a1SSean Christopherson  * the single source of truth for the MMU's state.
176594e91a1SSean Christopherson  */
177594e91a1SSean Christopherson #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag)			\
17882ffa13fSPaolo Bonzini static inline bool __maybe_unused					\
17982ffa13fSPaolo Bonzini ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs)		\
180594e91a1SSean Christopherson {									\
181594e91a1SSean Christopherson 	return !!(regs->reg & flag);					\
182594e91a1SSean Christopherson }
183594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
184594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
185594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
186594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
187594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
188594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
189594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
190594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
191594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
192594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
193594e91a1SSean Christopherson 
19460667724SSean Christopherson /*
19560667724SSean Christopherson  * The MMU itself (with a valid role) is the single source of truth for the
19660667724SSean Christopherson  * MMU.  Do not use the regs used to build the MMU/role, nor the vCPU.  The
19760667724SSean Christopherson  * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
19860667724SSean Christopherson  * and the vCPU may be incorrect/irrelevant.
19960667724SSean Christopherson  */
20060667724SSean Christopherson #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name)		\
2014ac21457SPaolo Bonzini static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu)	\
20260667724SSean Christopherson {								\
203e5ed0fb0SPaolo Bonzini 	return !!(mmu->cpu_role. base_or_ext . reg##_##name);	\
20460667724SSean Christopherson }
20560667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
20660667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pse);
20760667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smep);
20860667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smap);
20960667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pke);
21060667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, la57);
21160667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
21256b321f9SPaolo Bonzini BUILD_MMU_ROLE_ACCESSOR(ext,  efer, lma);
21360667724SSean Christopherson 
214faf72962SPaolo Bonzini static inline bool is_cr0_pg(struct kvm_mmu *mmu)
215faf72962SPaolo Bonzini {
216faf72962SPaolo Bonzini         return mmu->cpu_role.base.level > 0;
217faf72962SPaolo Bonzini }
218faf72962SPaolo Bonzini 
219faf72962SPaolo Bonzini static inline bool is_cr4_pae(struct kvm_mmu *mmu)
220faf72962SPaolo Bonzini {
221faf72962SPaolo Bonzini         return !mmu->cpu_role.base.has_4_byte_gpte;
222faf72962SPaolo Bonzini }
223faf72962SPaolo Bonzini 
224594e91a1SSean Christopherson static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
225594e91a1SSean Christopherson {
226594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
227594e91a1SSean Christopherson 		.cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
228594e91a1SSean Christopherson 		.cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
229594e91a1SSean Christopherson 		.efer = vcpu->arch.efer,
230594e91a1SSean Christopherson 	};
231594e91a1SSean Christopherson 
232594e91a1SSean Christopherson 	return regs;
233594e91a1SSean Christopherson }
234c50d8ae3SPaolo Bonzini 
235c50d8ae3SPaolo Bonzini static inline bool kvm_available_flush_tlb_with_range(void)
236c50d8ae3SPaolo Bonzini {
237afaf0b2fSSean Christopherson 	return kvm_x86_ops.tlb_remote_flush_with_range;
238c50d8ae3SPaolo Bonzini }
239c50d8ae3SPaolo Bonzini 
240c50d8ae3SPaolo Bonzini static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
241c50d8ae3SPaolo Bonzini 		struct kvm_tlb_range *range)
242c50d8ae3SPaolo Bonzini {
243c50d8ae3SPaolo Bonzini 	int ret = -ENOTSUPP;
244c50d8ae3SPaolo Bonzini 
245afaf0b2fSSean Christopherson 	if (range && kvm_x86_ops.tlb_remote_flush_with_range)
246b3646477SJason Baron 		ret = static_call(kvm_x86_tlb_remote_flush_with_range)(kvm, range);
247c50d8ae3SPaolo Bonzini 
248c50d8ae3SPaolo Bonzini 	if (ret)
249c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
250c50d8ae3SPaolo Bonzini }
251c50d8ae3SPaolo Bonzini 
2522f2fad08SBen Gardon void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
253c50d8ae3SPaolo Bonzini 		u64 start_gfn, u64 pages)
254c50d8ae3SPaolo Bonzini {
255c50d8ae3SPaolo Bonzini 	struct kvm_tlb_range range;
256c50d8ae3SPaolo Bonzini 
257c50d8ae3SPaolo Bonzini 	range.start_gfn = start_gfn;
258c50d8ae3SPaolo Bonzini 	range.pages = pages;
259c50d8ae3SPaolo Bonzini 
260c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs_with_range(kvm, &range);
261c50d8ae3SPaolo Bonzini }
262c50d8ae3SPaolo Bonzini 
2638f79b064SBen Gardon static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
2648f79b064SBen Gardon 			   unsigned int access)
2658f79b064SBen Gardon {
266c236d962SSean Christopherson 	u64 spte = make_mmio_spte(vcpu, gfn, access);
2678f79b064SBen Gardon 
268c236d962SSean Christopherson 	trace_mark_mmio_spte(sptep, gfn, spte);
269c236d962SSean Christopherson 	mmu_spte_set(sptep, spte);
270c50d8ae3SPaolo Bonzini }
271c50d8ae3SPaolo Bonzini 
272c50d8ae3SPaolo Bonzini static gfn_t get_mmio_spte_gfn(u64 spte)
273c50d8ae3SPaolo Bonzini {
274c50d8ae3SPaolo Bonzini 	u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
275c50d8ae3SPaolo Bonzini 
2768a967d65SPaolo Bonzini 	gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
277c50d8ae3SPaolo Bonzini 	       & shadow_nonpresent_or_rsvd_mask;
278c50d8ae3SPaolo Bonzini 
279c50d8ae3SPaolo Bonzini 	return gpa >> PAGE_SHIFT;
280c50d8ae3SPaolo Bonzini }
281c50d8ae3SPaolo Bonzini 
282c50d8ae3SPaolo Bonzini static unsigned get_mmio_spte_access(u64 spte)
283c50d8ae3SPaolo Bonzini {
284c50d8ae3SPaolo Bonzini 	return spte & shadow_mmio_access_mask;
285c50d8ae3SPaolo Bonzini }
286c50d8ae3SPaolo Bonzini 
287c50d8ae3SPaolo Bonzini static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
288c50d8ae3SPaolo Bonzini {
289c50d8ae3SPaolo Bonzini 	u64 kvm_gen, spte_gen, gen;
290c50d8ae3SPaolo Bonzini 
291c50d8ae3SPaolo Bonzini 	gen = kvm_vcpu_memslots(vcpu)->generation;
292c50d8ae3SPaolo Bonzini 	if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
293c50d8ae3SPaolo Bonzini 		return false;
294c50d8ae3SPaolo Bonzini 
295c50d8ae3SPaolo Bonzini 	kvm_gen = gen & MMIO_SPTE_GEN_MASK;
296c50d8ae3SPaolo Bonzini 	spte_gen = get_mmio_spte_generation(spte);
297c50d8ae3SPaolo Bonzini 
298c50d8ae3SPaolo Bonzini 	trace_check_mmio_spte(spte, kvm_gen, spte_gen);
299c50d8ae3SPaolo Bonzini 	return likely(kvm_gen == spte_gen);
300c50d8ae3SPaolo Bonzini }
301c50d8ae3SPaolo Bonzini 
302c50d8ae3SPaolo Bonzini static int is_cpuid_PSE36(void)
303c50d8ae3SPaolo Bonzini {
304c50d8ae3SPaolo Bonzini 	return 1;
305c50d8ae3SPaolo Bonzini }
306c50d8ae3SPaolo Bonzini 
307c50d8ae3SPaolo Bonzini #ifdef CONFIG_X86_64
308c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
309c50d8ae3SPaolo Bonzini {
310c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
311c50d8ae3SPaolo Bonzini }
312c50d8ae3SPaolo Bonzini 
313c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
314c50d8ae3SPaolo Bonzini {
315c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
316c50d8ae3SPaolo Bonzini }
317c50d8ae3SPaolo Bonzini 
318c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
319c50d8ae3SPaolo Bonzini {
320c50d8ae3SPaolo Bonzini 	return xchg(sptep, spte);
321c50d8ae3SPaolo Bonzini }
322c50d8ae3SPaolo Bonzini 
323c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
324c50d8ae3SPaolo Bonzini {
325c50d8ae3SPaolo Bonzini 	return READ_ONCE(*sptep);
326c50d8ae3SPaolo Bonzini }
327c50d8ae3SPaolo Bonzini #else
328c50d8ae3SPaolo Bonzini union split_spte {
329c50d8ae3SPaolo Bonzini 	struct {
330c50d8ae3SPaolo Bonzini 		u32 spte_low;
331c50d8ae3SPaolo Bonzini 		u32 spte_high;
332c50d8ae3SPaolo Bonzini 	};
333c50d8ae3SPaolo Bonzini 	u64 spte;
334c50d8ae3SPaolo Bonzini };
335c50d8ae3SPaolo Bonzini 
336c50d8ae3SPaolo Bonzini static void count_spte_clear(u64 *sptep, u64 spte)
337c50d8ae3SPaolo Bonzini {
33857354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
339c50d8ae3SPaolo Bonzini 
340c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(spte))
341c50d8ae3SPaolo Bonzini 		return;
342c50d8ae3SPaolo Bonzini 
343c50d8ae3SPaolo Bonzini 	/* Ensure the spte is completely set before we increase the count */
344c50d8ae3SPaolo Bonzini 	smp_wmb();
345c50d8ae3SPaolo Bonzini 	sp->clear_spte_count++;
346c50d8ae3SPaolo Bonzini }
347c50d8ae3SPaolo Bonzini 
348c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
349c50d8ae3SPaolo Bonzini {
350c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
351c50d8ae3SPaolo Bonzini 
352c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
353c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
354c50d8ae3SPaolo Bonzini 
355c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
356c50d8ae3SPaolo Bonzini 
357c50d8ae3SPaolo Bonzini 	/*
358c50d8ae3SPaolo Bonzini 	 * If we map the spte from nonpresent to present, We should store
359c50d8ae3SPaolo Bonzini 	 * the high bits firstly, then set present bit, so cpu can not
360c50d8ae3SPaolo Bonzini 	 * fetch this spte while we are setting the spte.
361c50d8ae3SPaolo Bonzini 	 */
362c50d8ae3SPaolo Bonzini 	smp_wmb();
363c50d8ae3SPaolo Bonzini 
364c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
365c50d8ae3SPaolo Bonzini }
366c50d8ae3SPaolo Bonzini 
367c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
368c50d8ae3SPaolo Bonzini {
369c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
370c50d8ae3SPaolo Bonzini 
371c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
372c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
373c50d8ae3SPaolo Bonzini 
374c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
375c50d8ae3SPaolo Bonzini 
376c50d8ae3SPaolo Bonzini 	/*
377c50d8ae3SPaolo Bonzini 	 * If we map the spte from present to nonpresent, we should clear
378c50d8ae3SPaolo Bonzini 	 * present bit firstly to avoid vcpu fetch the old high bits.
379c50d8ae3SPaolo Bonzini 	 */
380c50d8ae3SPaolo Bonzini 	smp_wmb();
381c50d8ae3SPaolo Bonzini 
382c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
383c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
384c50d8ae3SPaolo Bonzini }
385c50d8ae3SPaolo Bonzini 
386c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
387c50d8ae3SPaolo Bonzini {
388c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte, orig;
389c50d8ae3SPaolo Bonzini 
390c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
391c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
392c50d8ae3SPaolo Bonzini 
393c50d8ae3SPaolo Bonzini 	/* xchg acts as a barrier before the setting of the high bits */
394c50d8ae3SPaolo Bonzini 	orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
395c50d8ae3SPaolo Bonzini 	orig.spte_high = ssptep->spte_high;
396c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
397c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
398c50d8ae3SPaolo Bonzini 
399c50d8ae3SPaolo Bonzini 	return orig.spte;
400c50d8ae3SPaolo Bonzini }
401c50d8ae3SPaolo Bonzini 
402c50d8ae3SPaolo Bonzini /*
403c50d8ae3SPaolo Bonzini  * The idea using the light way get the spte on x86_32 guest is from
404c50d8ae3SPaolo Bonzini  * gup_get_pte (mm/gup.c).
405c50d8ae3SPaolo Bonzini  *
406c50d8ae3SPaolo Bonzini  * An spte tlb flush may be pending, because kvm_set_pte_rmapp
407c50d8ae3SPaolo Bonzini  * coalesces them and we are running out of the MMU lock.  Therefore
408c50d8ae3SPaolo Bonzini  * we need to protect against in-progress updates of the spte.
409c50d8ae3SPaolo Bonzini  *
410c50d8ae3SPaolo Bonzini  * Reading the spte while an update is in progress may get the old value
411c50d8ae3SPaolo Bonzini  * for the high part of the spte.  The race is fine for a present->non-present
412c50d8ae3SPaolo Bonzini  * change (because the high part of the spte is ignored for non-present spte),
413c50d8ae3SPaolo Bonzini  * but for a present->present change we must reread the spte.
414c50d8ae3SPaolo Bonzini  *
415c50d8ae3SPaolo Bonzini  * All such changes are done in two steps (present->non-present and
416c50d8ae3SPaolo Bonzini  * non-present->present), hence it is enough to count the number of
417c50d8ae3SPaolo Bonzini  * present->non-present updates: if it changed while reading the spte,
418c50d8ae3SPaolo Bonzini  * we might have hit the race.  This is done using clear_spte_count.
419c50d8ae3SPaolo Bonzini  */
420c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
421c50d8ae3SPaolo Bonzini {
42257354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
423c50d8ae3SPaolo Bonzini 	union split_spte spte, *orig = (union split_spte *)sptep;
424c50d8ae3SPaolo Bonzini 	int count;
425c50d8ae3SPaolo Bonzini 
426c50d8ae3SPaolo Bonzini retry:
427c50d8ae3SPaolo Bonzini 	count = sp->clear_spte_count;
428c50d8ae3SPaolo Bonzini 	smp_rmb();
429c50d8ae3SPaolo Bonzini 
430c50d8ae3SPaolo Bonzini 	spte.spte_low = orig->spte_low;
431c50d8ae3SPaolo Bonzini 	smp_rmb();
432c50d8ae3SPaolo Bonzini 
433c50d8ae3SPaolo Bonzini 	spte.spte_high = orig->spte_high;
434c50d8ae3SPaolo Bonzini 	smp_rmb();
435c50d8ae3SPaolo Bonzini 
436c50d8ae3SPaolo Bonzini 	if (unlikely(spte.spte_low != orig->spte_low ||
437c50d8ae3SPaolo Bonzini 	      count != sp->clear_spte_count))
438c50d8ae3SPaolo Bonzini 		goto retry;
439c50d8ae3SPaolo Bonzini 
440c50d8ae3SPaolo Bonzini 	return spte.spte;
441c50d8ae3SPaolo Bonzini }
442c50d8ae3SPaolo Bonzini #endif
443c50d8ae3SPaolo Bonzini 
444c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_set:
445c50d8ae3SPaolo Bonzini  * Set the sptep from nonpresent to present.
446c50d8ae3SPaolo Bonzini  * Note: the sptep being assigned *must* be either not present
447c50d8ae3SPaolo Bonzini  * or in a state where the hardware will not attempt to update
448c50d8ae3SPaolo Bonzini  * the spte.
449c50d8ae3SPaolo Bonzini  */
450c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 new_spte)
451c50d8ae3SPaolo Bonzini {
452c50d8ae3SPaolo Bonzini 	WARN_ON(is_shadow_present_pte(*sptep));
453c50d8ae3SPaolo Bonzini 	__set_spte(sptep, new_spte);
454c50d8ae3SPaolo Bonzini }
455c50d8ae3SPaolo Bonzini 
456c50d8ae3SPaolo Bonzini /*
457c50d8ae3SPaolo Bonzini  * Update the SPTE (excluding the PFN), but do not track changes in its
458c50d8ae3SPaolo Bonzini  * accessed/dirty status.
459c50d8ae3SPaolo Bonzini  */
460c50d8ae3SPaolo Bonzini static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
461c50d8ae3SPaolo Bonzini {
462c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
463c50d8ae3SPaolo Bonzini 
464c50d8ae3SPaolo Bonzini 	WARN_ON(!is_shadow_present_pte(new_spte));
465115111efSDavid Matlack 	check_spte_writable_invariants(new_spte);
466c50d8ae3SPaolo Bonzini 
467c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte)) {
468c50d8ae3SPaolo Bonzini 		mmu_spte_set(sptep, new_spte);
469c50d8ae3SPaolo Bonzini 		return old_spte;
470c50d8ae3SPaolo Bonzini 	}
471c50d8ae3SPaolo Bonzini 
472c50d8ae3SPaolo Bonzini 	if (!spte_has_volatile_bits(old_spte))
473c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, new_spte);
474c50d8ae3SPaolo Bonzini 	else
475c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, new_spte);
476c50d8ae3SPaolo Bonzini 
477c50d8ae3SPaolo Bonzini 	WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
478c50d8ae3SPaolo Bonzini 
479c50d8ae3SPaolo Bonzini 	return old_spte;
480c50d8ae3SPaolo Bonzini }
481c50d8ae3SPaolo Bonzini 
482c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_update:
483c50d8ae3SPaolo Bonzini  * Update the state bits, it means the mapped pfn is not changed.
484c50d8ae3SPaolo Bonzini  *
48502844ac1SDavid Matlack  * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
48602844ac1SDavid Matlack  * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
48702844ac1SDavid Matlack  * spte, even though the writable spte might be cached on a CPU's TLB.
488c50d8ae3SPaolo Bonzini  *
489c50d8ae3SPaolo Bonzini  * Returns true if the TLB needs to be flushed
490c50d8ae3SPaolo Bonzini  */
491c50d8ae3SPaolo Bonzini static bool mmu_spte_update(u64 *sptep, u64 new_spte)
492c50d8ae3SPaolo Bonzini {
493c50d8ae3SPaolo Bonzini 	bool flush = false;
494c50d8ae3SPaolo Bonzini 	u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
495c50d8ae3SPaolo Bonzini 
496c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
497c50d8ae3SPaolo Bonzini 		return false;
498c50d8ae3SPaolo Bonzini 
499c50d8ae3SPaolo Bonzini 	/*
500c50d8ae3SPaolo Bonzini 	 * For the spte updated out of mmu-lock is safe, since
501c50d8ae3SPaolo Bonzini 	 * we always atomically update it, see the comments in
502c50d8ae3SPaolo Bonzini 	 * spte_has_volatile_bits().
503c50d8ae3SPaolo Bonzini 	 */
504706c9c55SSean Christopherson 	if (is_mmu_writable_spte(old_spte) &&
505c50d8ae3SPaolo Bonzini 	      !is_writable_pte(new_spte))
506c50d8ae3SPaolo Bonzini 		flush = true;
507c50d8ae3SPaolo Bonzini 
508c50d8ae3SPaolo Bonzini 	/*
509c50d8ae3SPaolo Bonzini 	 * Flush TLB when accessed/dirty states are changed in the page tables,
510c50d8ae3SPaolo Bonzini 	 * to guarantee consistency between TLB and page tables.
511c50d8ae3SPaolo Bonzini 	 */
512c50d8ae3SPaolo Bonzini 
513c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
514c50d8ae3SPaolo Bonzini 		flush = true;
515c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(spte_to_pfn(old_spte));
516c50d8ae3SPaolo Bonzini 	}
517c50d8ae3SPaolo Bonzini 
518c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
519c50d8ae3SPaolo Bonzini 		flush = true;
520c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(old_spte));
521c50d8ae3SPaolo Bonzini 	}
522c50d8ae3SPaolo Bonzini 
523c50d8ae3SPaolo Bonzini 	return flush;
524c50d8ae3SPaolo Bonzini }
525c50d8ae3SPaolo Bonzini 
526c50d8ae3SPaolo Bonzini /*
527c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_track_bits:
528c50d8ae3SPaolo Bonzini  * It sets the sptep from present to nonpresent, and track the
529c50d8ae3SPaolo Bonzini  * state bits, it is used to clear the last level sptep.
5307fa2a347SSean Christopherson  * Returns the old PTE.
531c50d8ae3SPaolo Bonzini  */
53271f51d2cSMingwei Zhang static int mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
533c50d8ae3SPaolo Bonzini {
534c50d8ae3SPaolo Bonzini 	kvm_pfn_t pfn;
535c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
53671f51d2cSMingwei Zhang 	int level = sptep_to_sp(sptep)->role.level;
537b14b2690SSean Christopherson 	struct page *page;
538c50d8ae3SPaolo Bonzini 
53954eb3ef5SSean Christopherson 	if (!is_shadow_present_pte(old_spte) ||
54054eb3ef5SSean Christopherson 	    !spte_has_volatile_bits(old_spte))
541c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, 0ull);
542c50d8ae3SPaolo Bonzini 	else
543c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, 0ull);
544c50d8ae3SPaolo Bonzini 
545c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
5467fa2a347SSean Christopherson 		return old_spte;
547c50d8ae3SPaolo Bonzini 
54871f51d2cSMingwei Zhang 	kvm_update_page_stats(kvm, level, -1);
54971f51d2cSMingwei Zhang 
550c50d8ae3SPaolo Bonzini 	pfn = spte_to_pfn(old_spte);
551c50d8ae3SPaolo Bonzini 
552c50d8ae3SPaolo Bonzini 	/*
553b14b2690SSean Christopherson 	 * KVM doesn't hold a reference to any pages mapped into the guest, and
554b14b2690SSean Christopherson 	 * instead uses the mmu_notifier to ensure that KVM unmaps any pages
555b14b2690SSean Christopherson 	 * before they are reclaimed.  Sanity check that, if the pfn is backed
556b14b2690SSean Christopherson 	 * by a refcounted page, the refcount is elevated.
557c50d8ae3SPaolo Bonzini 	 */
558b14b2690SSean Christopherson 	page = kvm_pfn_to_refcounted_page(pfn);
559b14b2690SSean Christopherson 	WARN_ON(page && !page_count(page));
560c50d8ae3SPaolo Bonzini 
561c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte))
562c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(pfn);
563c50d8ae3SPaolo Bonzini 
564c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte))
565c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(pfn);
566c50d8ae3SPaolo Bonzini 
5677fa2a347SSean Christopherson 	return old_spte;
568c50d8ae3SPaolo Bonzini }
569c50d8ae3SPaolo Bonzini 
570c50d8ae3SPaolo Bonzini /*
571c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_no_track:
572c50d8ae3SPaolo Bonzini  * Directly clear spte without caring the state bits of sptep,
573c50d8ae3SPaolo Bonzini  * it is used to set the upper level spte.
574c50d8ae3SPaolo Bonzini  */
575c50d8ae3SPaolo Bonzini static void mmu_spte_clear_no_track(u64 *sptep)
576c50d8ae3SPaolo Bonzini {
577c50d8ae3SPaolo Bonzini 	__update_clear_spte_fast(sptep, 0ull);
578c50d8ae3SPaolo Bonzini }
579c50d8ae3SPaolo Bonzini 
580c50d8ae3SPaolo Bonzini static u64 mmu_spte_get_lockless(u64 *sptep)
581c50d8ae3SPaolo Bonzini {
582c50d8ae3SPaolo Bonzini 	return __get_spte_lockless(sptep);
583c50d8ae3SPaolo Bonzini }
584c50d8ae3SPaolo Bonzini 
585c50d8ae3SPaolo Bonzini /* Returns the Accessed status of the PTE and resets it at the same time. */
586c50d8ae3SPaolo Bonzini static bool mmu_spte_age(u64 *sptep)
587c50d8ae3SPaolo Bonzini {
588c50d8ae3SPaolo Bonzini 	u64 spte = mmu_spte_get_lockless(sptep);
589c50d8ae3SPaolo Bonzini 
590c50d8ae3SPaolo Bonzini 	if (!is_accessed_spte(spte))
591c50d8ae3SPaolo Bonzini 		return false;
592c50d8ae3SPaolo Bonzini 
593c50d8ae3SPaolo Bonzini 	if (spte_ad_enabled(spte)) {
594c50d8ae3SPaolo Bonzini 		clear_bit((ffs(shadow_accessed_mask) - 1),
595c50d8ae3SPaolo Bonzini 			  (unsigned long *)sptep);
596c50d8ae3SPaolo Bonzini 	} else {
597c50d8ae3SPaolo Bonzini 		/*
598c50d8ae3SPaolo Bonzini 		 * Capture the dirty status of the page, so that it doesn't get
599c50d8ae3SPaolo Bonzini 		 * lost when the SPTE is marked for access tracking.
600c50d8ae3SPaolo Bonzini 		 */
601c50d8ae3SPaolo Bonzini 		if (is_writable_pte(spte))
602c50d8ae3SPaolo Bonzini 			kvm_set_pfn_dirty(spte_to_pfn(spte));
603c50d8ae3SPaolo Bonzini 
604c50d8ae3SPaolo Bonzini 		spte = mark_spte_for_access_track(spte);
605c50d8ae3SPaolo Bonzini 		mmu_spte_update_no_track(sptep, spte);
606c50d8ae3SPaolo Bonzini 	}
607c50d8ae3SPaolo Bonzini 
608c50d8ae3SPaolo Bonzini 	return true;
609c50d8ae3SPaolo Bonzini }
610c50d8ae3SPaolo Bonzini 
611c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
612c50d8ae3SPaolo Bonzini {
613c5c8c7c5SDavid Matlack 	if (is_tdp_mmu(vcpu->arch.mmu)) {
614c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_begin();
615c5c8c7c5SDavid Matlack 	} else {
616c50d8ae3SPaolo Bonzini 		/*
617c50d8ae3SPaolo Bonzini 		 * Prevent page table teardown by making any free-er wait during
618c50d8ae3SPaolo Bonzini 		 * kvm_flush_remote_tlbs() IPI to all active vcpus.
619c50d8ae3SPaolo Bonzini 		 */
620c50d8ae3SPaolo Bonzini 		local_irq_disable();
621c50d8ae3SPaolo Bonzini 
622c50d8ae3SPaolo Bonzini 		/*
623c50d8ae3SPaolo Bonzini 		 * Make sure a following spte read is not reordered ahead of the write
624c50d8ae3SPaolo Bonzini 		 * to vcpu->mode.
625c50d8ae3SPaolo Bonzini 		 */
626c50d8ae3SPaolo Bonzini 		smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
627c50d8ae3SPaolo Bonzini 	}
628c5c8c7c5SDavid Matlack }
629c50d8ae3SPaolo Bonzini 
630c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
631c50d8ae3SPaolo Bonzini {
632c5c8c7c5SDavid Matlack 	if (is_tdp_mmu(vcpu->arch.mmu)) {
633c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_end();
634c5c8c7c5SDavid Matlack 	} else {
635c50d8ae3SPaolo Bonzini 		/*
636c50d8ae3SPaolo Bonzini 		 * Make sure the write to vcpu->mode is not reordered in front of
637c50d8ae3SPaolo Bonzini 		 * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
638c50d8ae3SPaolo Bonzini 		 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
639c50d8ae3SPaolo Bonzini 		 */
640c50d8ae3SPaolo Bonzini 		smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
641c50d8ae3SPaolo Bonzini 		local_irq_enable();
642c50d8ae3SPaolo Bonzini 	}
643c5c8c7c5SDavid Matlack }
644c50d8ae3SPaolo Bonzini 
645378f5cd6SSean Christopherson static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
646c50d8ae3SPaolo Bonzini {
647c50d8ae3SPaolo Bonzini 	int r;
648c50d8ae3SPaolo Bonzini 
649531281adSSean Christopherson 	/* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
65094ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
651531281adSSean Christopherson 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
652c50d8ae3SPaolo Bonzini 	if (r)
653c50d8ae3SPaolo Bonzini 		return r;
65494ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
655171a90d7SSean Christopherson 				       PT64_ROOT_MAX_LEVEL);
656171a90d7SSean Christopherson 	if (r)
657171a90d7SSean Christopherson 		return r;
658378f5cd6SSean Christopherson 	if (maybe_indirect) {
65994ce87efSSean Christopherson 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_gfn_array_cache,
660171a90d7SSean Christopherson 					       PT64_ROOT_MAX_LEVEL);
661c50d8ae3SPaolo Bonzini 		if (r)
662c50d8ae3SPaolo Bonzini 			return r;
663378f5cd6SSean Christopherson 	}
66494ce87efSSean Christopherson 	return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
665531281adSSean Christopherson 					  PT64_ROOT_MAX_LEVEL);
666c50d8ae3SPaolo Bonzini }
667c50d8ae3SPaolo Bonzini 
668c50d8ae3SPaolo Bonzini static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
669c50d8ae3SPaolo Bonzini {
67094ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
67194ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
67294ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_gfn_array_cache);
67394ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
674c50d8ae3SPaolo Bonzini }
675c50d8ae3SPaolo Bonzini 
676c50d8ae3SPaolo Bonzini static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
677c50d8ae3SPaolo Bonzini {
67894ce87efSSean Christopherson 	return kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
679c50d8ae3SPaolo Bonzini }
680c50d8ae3SPaolo Bonzini 
681c50d8ae3SPaolo Bonzini static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
682c50d8ae3SPaolo Bonzini {
683c50d8ae3SPaolo Bonzini 	kmem_cache_free(pte_list_desc_cache, pte_list_desc);
684c50d8ae3SPaolo Bonzini }
685c50d8ae3SPaolo Bonzini 
686c50d8ae3SPaolo Bonzini static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
687c50d8ae3SPaolo Bonzini {
68884e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
68984e5ffd0SLai Jiangshan 		return sp->gfn;
69084e5ffd0SLai Jiangshan 
691c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
692c50d8ae3SPaolo Bonzini 		return sp->gfns[index];
693c50d8ae3SPaolo Bonzini 
6942ca3129eSSean Christopherson 	return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
695c50d8ae3SPaolo Bonzini }
696c50d8ae3SPaolo Bonzini 
697c50d8ae3SPaolo Bonzini static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
698c50d8ae3SPaolo Bonzini {
69984e5ffd0SLai Jiangshan 	if (sp->role.passthrough) {
70084e5ffd0SLai Jiangshan 		WARN_ON_ONCE(gfn != sp->gfn);
70184e5ffd0SLai Jiangshan 		return;
70284e5ffd0SLai Jiangshan 	}
70384e5ffd0SLai Jiangshan 
704c50d8ae3SPaolo Bonzini 	if (!sp->role.direct) {
705c50d8ae3SPaolo Bonzini 		sp->gfns[index] = gfn;
706c50d8ae3SPaolo Bonzini 		return;
707c50d8ae3SPaolo Bonzini 	}
708c50d8ae3SPaolo Bonzini 
709c50d8ae3SPaolo Bonzini 	if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
710c50d8ae3SPaolo Bonzini 		pr_err_ratelimited("gfn mismatch under direct page %llx "
711c50d8ae3SPaolo Bonzini 				   "(expected %llx, got %llx)\n",
712c50d8ae3SPaolo Bonzini 				   sp->gfn,
713c50d8ae3SPaolo Bonzini 				   kvm_mmu_page_get_gfn(sp, index), gfn);
714c50d8ae3SPaolo Bonzini }
715c50d8ae3SPaolo Bonzini 
716c50d8ae3SPaolo Bonzini /*
717c50d8ae3SPaolo Bonzini  * Return the pointer to the large page information for a given gfn,
718c50d8ae3SPaolo Bonzini  * handling slots that are not large page aligned.
719c50d8ae3SPaolo Bonzini  */
720c50d8ae3SPaolo Bonzini static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
7218ca6f063SBen Gardon 		const struct kvm_memory_slot *slot, int level)
722c50d8ae3SPaolo Bonzini {
723c50d8ae3SPaolo Bonzini 	unsigned long idx;
724c50d8ae3SPaolo Bonzini 
725c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
726c50d8ae3SPaolo Bonzini 	return &slot->arch.lpage_info[level - 2][idx];
727c50d8ae3SPaolo Bonzini }
728c50d8ae3SPaolo Bonzini 
729269e9552SHamza Mahfooz static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
730c50d8ae3SPaolo Bonzini 					    gfn_t gfn, int count)
731c50d8ae3SPaolo Bonzini {
732c50d8ae3SPaolo Bonzini 	struct kvm_lpage_info *linfo;
733c50d8ae3SPaolo Bonzini 	int i;
734c50d8ae3SPaolo Bonzini 
7353bae0459SSean Christopherson 	for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
736c50d8ae3SPaolo Bonzini 		linfo = lpage_info_slot(gfn, slot, i);
737c50d8ae3SPaolo Bonzini 		linfo->disallow_lpage += count;
738c50d8ae3SPaolo Bonzini 		WARN_ON(linfo->disallow_lpage < 0);
739c50d8ae3SPaolo Bonzini 	}
740c50d8ae3SPaolo Bonzini }
741c50d8ae3SPaolo Bonzini 
742269e9552SHamza Mahfooz void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
743c50d8ae3SPaolo Bonzini {
744c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, 1);
745c50d8ae3SPaolo Bonzini }
746c50d8ae3SPaolo Bonzini 
747269e9552SHamza Mahfooz void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
748c50d8ae3SPaolo Bonzini {
749c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, -1);
750c50d8ae3SPaolo Bonzini }
751c50d8ae3SPaolo Bonzini 
752c50d8ae3SPaolo Bonzini static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
753c50d8ae3SPaolo Bonzini {
754c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
755c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
756c50d8ae3SPaolo Bonzini 	gfn_t gfn;
757c50d8ae3SPaolo Bonzini 
758c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages++;
759c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
760c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
761c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
762c50d8ae3SPaolo Bonzini 
763c50d8ae3SPaolo Bonzini 	/* the non-leaf shadow pages are keeping readonly. */
7643bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
765c50d8ae3SPaolo Bonzini 		return kvm_slot_page_track_add_page(kvm, slot, gfn,
766c50d8ae3SPaolo Bonzini 						    KVM_PAGE_TRACK_WRITE);
767c50d8ae3SPaolo Bonzini 
768c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
769c50d8ae3SPaolo Bonzini }
770c50d8ae3SPaolo Bonzini 
77129cf0f50SBen Gardon void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
772c50d8ae3SPaolo Bonzini {
773c50d8ae3SPaolo Bonzini 	if (sp->lpage_disallowed)
774c50d8ae3SPaolo Bonzini 		return;
775c50d8ae3SPaolo Bonzini 
776c50d8ae3SPaolo Bonzini 	++kvm->stat.nx_lpage_splits;
777c50d8ae3SPaolo Bonzini 	list_add_tail(&sp->lpage_disallowed_link,
778c50d8ae3SPaolo Bonzini 		      &kvm->arch.lpage_disallowed_mmu_pages);
779c50d8ae3SPaolo Bonzini 	sp->lpage_disallowed = true;
780c50d8ae3SPaolo Bonzini }
781c50d8ae3SPaolo Bonzini 
782c50d8ae3SPaolo Bonzini static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
783c50d8ae3SPaolo Bonzini {
784c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
785c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
786c50d8ae3SPaolo Bonzini 	gfn_t gfn;
787c50d8ae3SPaolo Bonzini 
788c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages--;
789c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
790c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
791c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
7923bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
793c50d8ae3SPaolo Bonzini 		return kvm_slot_page_track_remove_page(kvm, slot, gfn,
794c50d8ae3SPaolo Bonzini 						       KVM_PAGE_TRACK_WRITE);
795c50d8ae3SPaolo Bonzini 
796c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_allow_lpage(slot, gfn);
797c50d8ae3SPaolo Bonzini }
798c50d8ae3SPaolo Bonzini 
79929cf0f50SBen Gardon void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
800c50d8ae3SPaolo Bonzini {
801c50d8ae3SPaolo Bonzini 	--kvm->stat.nx_lpage_splits;
802c50d8ae3SPaolo Bonzini 	sp->lpage_disallowed = false;
803c50d8ae3SPaolo Bonzini 	list_del(&sp->lpage_disallowed_link);
804c50d8ae3SPaolo Bonzini }
805c50d8ae3SPaolo Bonzini 
806c50d8ae3SPaolo Bonzini static struct kvm_memory_slot *
807c50d8ae3SPaolo Bonzini gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
808c50d8ae3SPaolo Bonzini 			    bool no_dirty_log)
809c50d8ae3SPaolo Bonzini {
810c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
811c50d8ae3SPaolo Bonzini 
812c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
81391b0d268SPaolo Bonzini 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
81491b0d268SPaolo Bonzini 		return NULL;
815044c59c4SPeter Xu 	if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
81691b0d268SPaolo Bonzini 		return NULL;
817c50d8ae3SPaolo Bonzini 
818c50d8ae3SPaolo Bonzini 	return slot;
819c50d8ae3SPaolo Bonzini }
820c50d8ae3SPaolo Bonzini 
821c50d8ae3SPaolo Bonzini /*
822c50d8ae3SPaolo Bonzini  * About rmap_head encoding:
823c50d8ae3SPaolo Bonzini  *
824c50d8ae3SPaolo Bonzini  * If the bit zero of rmap_head->val is clear, then it points to the only spte
825c50d8ae3SPaolo Bonzini  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
826c50d8ae3SPaolo Bonzini  * pte_list_desc containing more mappings.
827c50d8ae3SPaolo Bonzini  */
828c50d8ae3SPaolo Bonzini 
829c50d8ae3SPaolo Bonzini /*
830c50d8ae3SPaolo Bonzini  * Returns the number of pointers in the rmap chain, not counting the new one.
831c50d8ae3SPaolo Bonzini  */
832c50d8ae3SPaolo Bonzini static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
833c50d8ae3SPaolo Bonzini 			struct kvm_rmap_head *rmap_head)
834c50d8ae3SPaolo Bonzini {
835c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
83613236e25SPeter Xu 	int count = 0;
837c50d8ae3SPaolo Bonzini 
838c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
839805a0f83SStephen Zhang 		rmap_printk("%p %llx 0->1\n", spte, *spte);
840c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)spte;
841c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
842805a0f83SStephen Zhang 		rmap_printk("%p %llx 1->many\n", spte, *spte);
843c50d8ae3SPaolo Bonzini 		desc = mmu_alloc_pte_list_desc(vcpu);
844c50d8ae3SPaolo Bonzini 		desc->sptes[0] = (u64 *)rmap_head->val;
845c50d8ae3SPaolo Bonzini 		desc->sptes[1] = spte;
84613236e25SPeter Xu 		desc->spte_count = 2;
847c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)desc | 1;
848c50d8ae3SPaolo Bonzini 		++count;
849c50d8ae3SPaolo Bonzini 	} else {
850805a0f83SStephen Zhang 		rmap_printk("%p %llx many->many\n", spte, *spte);
851c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
85213236e25SPeter Xu 		while (desc->spte_count == PTE_LIST_EXT) {
853c50d8ae3SPaolo Bonzini 			count += PTE_LIST_EXT;
854c6c4f961SLi RongQing 			if (!desc->more) {
855c50d8ae3SPaolo Bonzini 				desc->more = mmu_alloc_pte_list_desc(vcpu);
856c50d8ae3SPaolo Bonzini 				desc = desc->more;
85713236e25SPeter Xu 				desc->spte_count = 0;
858c6c4f961SLi RongQing 				break;
859c6c4f961SLi RongQing 			}
860c6c4f961SLi RongQing 			desc = desc->more;
861c50d8ae3SPaolo Bonzini 		}
86213236e25SPeter Xu 		count += desc->spte_count;
86313236e25SPeter Xu 		desc->sptes[desc->spte_count++] = spte;
864c50d8ae3SPaolo Bonzini 	}
865c50d8ae3SPaolo Bonzini 	return count;
866c50d8ae3SPaolo Bonzini }
867c50d8ae3SPaolo Bonzini 
868c50d8ae3SPaolo Bonzini static void
869c50d8ae3SPaolo Bonzini pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
870c50d8ae3SPaolo Bonzini 			   struct pte_list_desc *desc, int i,
871c50d8ae3SPaolo Bonzini 			   struct pte_list_desc *prev_desc)
872c50d8ae3SPaolo Bonzini {
87313236e25SPeter Xu 	int j = desc->spte_count - 1;
874c50d8ae3SPaolo Bonzini 
875c50d8ae3SPaolo Bonzini 	desc->sptes[i] = desc->sptes[j];
876c50d8ae3SPaolo Bonzini 	desc->sptes[j] = NULL;
87713236e25SPeter Xu 	desc->spte_count--;
87813236e25SPeter Xu 	if (desc->spte_count)
879c50d8ae3SPaolo Bonzini 		return;
880c50d8ae3SPaolo Bonzini 	if (!prev_desc && !desc->more)
881fe3c2b4cSMiaohe Lin 		rmap_head->val = 0;
882c50d8ae3SPaolo Bonzini 	else
883c50d8ae3SPaolo Bonzini 		if (prev_desc)
884c50d8ae3SPaolo Bonzini 			prev_desc->more = desc->more;
885c50d8ae3SPaolo Bonzini 		else
886c50d8ae3SPaolo Bonzini 			rmap_head->val = (unsigned long)desc->more | 1;
887c50d8ae3SPaolo Bonzini 	mmu_free_pte_list_desc(desc);
888c50d8ae3SPaolo Bonzini }
889c50d8ae3SPaolo Bonzini 
890c50d8ae3SPaolo Bonzini static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
891c50d8ae3SPaolo Bonzini {
892c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
893c50d8ae3SPaolo Bonzini 	struct pte_list_desc *prev_desc;
894c50d8ae3SPaolo Bonzini 	int i;
895c50d8ae3SPaolo Bonzini 
896c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
897c50d8ae3SPaolo Bonzini 		pr_err("%s: %p 0->BUG\n", __func__, spte);
898c50d8ae3SPaolo Bonzini 		BUG();
899c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
900805a0f83SStephen Zhang 		rmap_printk("%p 1->0\n", spte);
901c50d8ae3SPaolo Bonzini 		if ((u64 *)rmap_head->val != spte) {
902c50d8ae3SPaolo Bonzini 			pr_err("%s:  %p 1->BUG\n", __func__, spte);
903c50d8ae3SPaolo Bonzini 			BUG();
904c50d8ae3SPaolo Bonzini 		}
905c50d8ae3SPaolo Bonzini 		rmap_head->val = 0;
906c50d8ae3SPaolo Bonzini 	} else {
907805a0f83SStephen Zhang 		rmap_printk("%p many->many\n", spte);
908c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
909c50d8ae3SPaolo Bonzini 		prev_desc = NULL;
910c50d8ae3SPaolo Bonzini 		while (desc) {
91113236e25SPeter Xu 			for (i = 0; i < desc->spte_count; ++i) {
912c50d8ae3SPaolo Bonzini 				if (desc->sptes[i] == spte) {
913c50d8ae3SPaolo Bonzini 					pte_list_desc_remove_entry(rmap_head,
914c50d8ae3SPaolo Bonzini 							desc, i, prev_desc);
915c50d8ae3SPaolo Bonzini 					return;
916c50d8ae3SPaolo Bonzini 				}
917c50d8ae3SPaolo Bonzini 			}
918c50d8ae3SPaolo Bonzini 			prev_desc = desc;
919c50d8ae3SPaolo Bonzini 			desc = desc->more;
920c50d8ae3SPaolo Bonzini 		}
921c50d8ae3SPaolo Bonzini 		pr_err("%s: %p many->many\n", __func__, spte);
922c50d8ae3SPaolo Bonzini 		BUG();
923c50d8ae3SPaolo Bonzini 	}
924c50d8ae3SPaolo Bonzini }
925c50d8ae3SPaolo Bonzini 
92671f51d2cSMingwei Zhang static void pte_list_remove(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
92771f51d2cSMingwei Zhang 			    u64 *sptep)
928c50d8ae3SPaolo Bonzini {
92971f51d2cSMingwei Zhang 	mmu_spte_clear_track_bits(kvm, sptep);
930c50d8ae3SPaolo Bonzini 	__pte_list_remove(sptep, rmap_head);
931c50d8ae3SPaolo Bonzini }
932c50d8ae3SPaolo Bonzini 
933a75b5404SPeter Xu /* Return true if rmap existed, false otherwise */
93471f51d2cSMingwei Zhang static bool pte_list_destroy(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
935a75b5404SPeter Xu {
936a75b5404SPeter Xu 	struct pte_list_desc *desc, *next;
937a75b5404SPeter Xu 	int i;
938a75b5404SPeter Xu 
939a75b5404SPeter Xu 	if (!rmap_head->val)
940a75b5404SPeter Xu 		return false;
941a75b5404SPeter Xu 
942a75b5404SPeter Xu 	if (!(rmap_head->val & 1)) {
94371f51d2cSMingwei Zhang 		mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
944a75b5404SPeter Xu 		goto out;
945a75b5404SPeter Xu 	}
946a75b5404SPeter Xu 
947a75b5404SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
948a75b5404SPeter Xu 
949a75b5404SPeter Xu 	for (; desc; desc = next) {
950a75b5404SPeter Xu 		for (i = 0; i < desc->spte_count; i++)
95171f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
952a75b5404SPeter Xu 		next = desc->more;
953a75b5404SPeter Xu 		mmu_free_pte_list_desc(desc);
954a75b5404SPeter Xu 	}
955a75b5404SPeter Xu out:
956a75b5404SPeter Xu 	/* rmap_head is meaningless now, remember to reset it */
957a75b5404SPeter Xu 	rmap_head->val = 0;
958a75b5404SPeter Xu 	return true;
959a75b5404SPeter Xu }
960a75b5404SPeter Xu 
9613bcd0662SPeter Xu unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
9623bcd0662SPeter Xu {
9633bcd0662SPeter Xu 	struct pte_list_desc *desc;
9643bcd0662SPeter Xu 	unsigned int count = 0;
9653bcd0662SPeter Xu 
9663bcd0662SPeter Xu 	if (!rmap_head->val)
9673bcd0662SPeter Xu 		return 0;
9683bcd0662SPeter Xu 	else if (!(rmap_head->val & 1))
9693bcd0662SPeter Xu 		return 1;
9703bcd0662SPeter Xu 
9713bcd0662SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
9723bcd0662SPeter Xu 
9733bcd0662SPeter Xu 	while (desc) {
9743bcd0662SPeter Xu 		count += desc->spte_count;
9753bcd0662SPeter Xu 		desc = desc->more;
9763bcd0662SPeter Xu 	}
9773bcd0662SPeter Xu 
9783bcd0662SPeter Xu 	return count;
9793bcd0662SPeter Xu }
9803bcd0662SPeter Xu 
98193e083d4SDavid Matlack static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
982269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
983c50d8ae3SPaolo Bonzini {
984c50d8ae3SPaolo Bonzini 	unsigned long idx;
985c50d8ae3SPaolo Bonzini 
986c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
9873bae0459SSean Christopherson 	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
988c50d8ae3SPaolo Bonzini }
989c50d8ae3SPaolo Bonzini 
990c50d8ae3SPaolo Bonzini static bool rmap_can_add(struct kvm_vcpu *vcpu)
991c50d8ae3SPaolo Bonzini {
992356ec69aSSean Christopherson 	struct kvm_mmu_memory_cache *mc;
993c50d8ae3SPaolo Bonzini 
994356ec69aSSean Christopherson 	mc = &vcpu->arch.mmu_pte_list_desc_cache;
99594ce87efSSean Christopherson 	return kvm_mmu_memory_cache_nr_free_objects(mc);
996c50d8ae3SPaolo Bonzini }
997c50d8ae3SPaolo Bonzini 
998c50d8ae3SPaolo Bonzini static void rmap_remove(struct kvm *kvm, u64 *spte)
999c50d8ae3SPaolo Bonzini {
1000601f8af0SDavid Matlack 	struct kvm_memslots *slots;
1001601f8af0SDavid Matlack 	struct kvm_memory_slot *slot;
1002c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1003c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1004c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1005c50d8ae3SPaolo Bonzini 
100657354682SSean Christopherson 	sp = sptep_to_sp(spte);
1007c50d8ae3SPaolo Bonzini 	gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1008601f8af0SDavid Matlack 
1009601f8af0SDavid Matlack 	/*
101068be1306SDavid Matlack 	 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
101168be1306SDavid Matlack 	 * so we have to determine which memslots to use based on context
101268be1306SDavid Matlack 	 * information in sp->role.
1013601f8af0SDavid Matlack 	 */
1014601f8af0SDavid Matlack 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1015601f8af0SDavid Matlack 
1016601f8af0SDavid Matlack 	slot = __gfn_to_memslot(slots, gfn);
101793e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1018601f8af0SDavid Matlack 
1019c50d8ae3SPaolo Bonzini 	__pte_list_remove(spte, rmap_head);
1020c50d8ae3SPaolo Bonzini }
1021c50d8ae3SPaolo Bonzini 
1022c50d8ae3SPaolo Bonzini /*
1023c50d8ae3SPaolo Bonzini  * Used by the following functions to iterate through the sptes linked by a
1024c50d8ae3SPaolo Bonzini  * rmap.  All fields are private and not assumed to be used outside.
1025c50d8ae3SPaolo Bonzini  */
1026c50d8ae3SPaolo Bonzini struct rmap_iterator {
1027c50d8ae3SPaolo Bonzini 	/* private fields */
1028c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1029c50d8ae3SPaolo Bonzini 	int pos;			/* index of the sptep */
1030c50d8ae3SPaolo Bonzini };
1031c50d8ae3SPaolo Bonzini 
1032c50d8ae3SPaolo Bonzini /*
1033c50d8ae3SPaolo Bonzini  * Iteration must be started by this function.  This should also be used after
1034c50d8ae3SPaolo Bonzini  * removing/dropping sptes from the rmap link because in such cases the
10350a03cbdaSMiaohe Lin  * information in the iterator may not be valid.
1036c50d8ae3SPaolo Bonzini  *
1037c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1038c50d8ae3SPaolo Bonzini  */
1039c50d8ae3SPaolo Bonzini static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1040c50d8ae3SPaolo Bonzini 			   struct rmap_iterator *iter)
1041c50d8ae3SPaolo Bonzini {
1042c50d8ae3SPaolo Bonzini 	u64 *sptep;
1043c50d8ae3SPaolo Bonzini 
1044c50d8ae3SPaolo Bonzini 	if (!rmap_head->val)
1045c50d8ae3SPaolo Bonzini 		return NULL;
1046c50d8ae3SPaolo Bonzini 
1047c50d8ae3SPaolo Bonzini 	if (!(rmap_head->val & 1)) {
1048c50d8ae3SPaolo Bonzini 		iter->desc = NULL;
1049c50d8ae3SPaolo Bonzini 		sptep = (u64 *)rmap_head->val;
1050c50d8ae3SPaolo Bonzini 		goto out;
1051c50d8ae3SPaolo Bonzini 	}
1052c50d8ae3SPaolo Bonzini 
1053c50d8ae3SPaolo Bonzini 	iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1054c50d8ae3SPaolo Bonzini 	iter->pos = 0;
1055c50d8ae3SPaolo Bonzini 	sptep = iter->desc->sptes[iter->pos];
1056c50d8ae3SPaolo Bonzini out:
1057c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1058c50d8ae3SPaolo Bonzini 	return sptep;
1059c50d8ae3SPaolo Bonzini }
1060c50d8ae3SPaolo Bonzini 
1061c50d8ae3SPaolo Bonzini /*
1062c50d8ae3SPaolo Bonzini  * Must be used with a valid iterator: e.g. after rmap_get_first().
1063c50d8ae3SPaolo Bonzini  *
1064c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1065c50d8ae3SPaolo Bonzini  */
1066c50d8ae3SPaolo Bonzini static u64 *rmap_get_next(struct rmap_iterator *iter)
1067c50d8ae3SPaolo Bonzini {
1068c50d8ae3SPaolo Bonzini 	u64 *sptep;
1069c50d8ae3SPaolo Bonzini 
1070c50d8ae3SPaolo Bonzini 	if (iter->desc) {
1071c50d8ae3SPaolo Bonzini 		if (iter->pos < PTE_LIST_EXT - 1) {
1072c50d8ae3SPaolo Bonzini 			++iter->pos;
1073c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1074c50d8ae3SPaolo Bonzini 			if (sptep)
1075c50d8ae3SPaolo Bonzini 				goto out;
1076c50d8ae3SPaolo Bonzini 		}
1077c50d8ae3SPaolo Bonzini 
1078c50d8ae3SPaolo Bonzini 		iter->desc = iter->desc->more;
1079c50d8ae3SPaolo Bonzini 
1080c50d8ae3SPaolo Bonzini 		if (iter->desc) {
1081c50d8ae3SPaolo Bonzini 			iter->pos = 0;
1082c50d8ae3SPaolo Bonzini 			/* desc->sptes[0] cannot be NULL */
1083c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1084c50d8ae3SPaolo Bonzini 			goto out;
1085c50d8ae3SPaolo Bonzini 		}
1086c50d8ae3SPaolo Bonzini 	}
1087c50d8ae3SPaolo Bonzini 
1088c50d8ae3SPaolo Bonzini 	return NULL;
1089c50d8ae3SPaolo Bonzini out:
1090c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1091c50d8ae3SPaolo Bonzini 	return sptep;
1092c50d8ae3SPaolo Bonzini }
1093c50d8ae3SPaolo Bonzini 
1094c50d8ae3SPaolo Bonzini #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)			\
1095c50d8ae3SPaolo Bonzini 	for (_spte_ = rmap_get_first(_rmap_head_, _iter_);		\
1096c50d8ae3SPaolo Bonzini 	     _spte_; _spte_ = rmap_get_next(_iter_))
1097c50d8ae3SPaolo Bonzini 
1098c50d8ae3SPaolo Bonzini static void drop_spte(struct kvm *kvm, u64 *sptep)
1099c50d8ae3SPaolo Bonzini {
110071f51d2cSMingwei Zhang 	u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
11017fa2a347SSean Christopherson 
11027fa2a347SSean Christopherson 	if (is_shadow_present_pte(old_spte))
1103c50d8ae3SPaolo Bonzini 		rmap_remove(kvm, sptep);
1104c50d8ae3SPaolo Bonzini }
1105c50d8ae3SPaolo Bonzini 
1106c50d8ae3SPaolo Bonzini 
1107c50d8ae3SPaolo Bonzini static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1108c50d8ae3SPaolo Bonzini {
1109c50d8ae3SPaolo Bonzini 	if (is_large_pte(*sptep)) {
111057354682SSean Christopherson 		WARN_ON(sptep_to_sp(sptep)->role.level == PG_LEVEL_4K);
1111c50d8ae3SPaolo Bonzini 		drop_spte(kvm, sptep);
1112c50d8ae3SPaolo Bonzini 		return true;
1113c50d8ae3SPaolo Bonzini 	}
1114c50d8ae3SPaolo Bonzini 
1115c50d8ae3SPaolo Bonzini 	return false;
1116c50d8ae3SPaolo Bonzini }
1117c50d8ae3SPaolo Bonzini 
1118c50d8ae3SPaolo Bonzini static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1119c50d8ae3SPaolo Bonzini {
1120c50d8ae3SPaolo Bonzini 	if (__drop_large_spte(vcpu->kvm, sptep)) {
112157354682SSean Christopherson 		struct kvm_mmu_page *sp = sptep_to_sp(sptep);
1122c50d8ae3SPaolo Bonzini 
1123c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1124c50d8ae3SPaolo Bonzini 			KVM_PAGES_PER_HPAGE(sp->role.level));
1125c50d8ae3SPaolo Bonzini 	}
1126c50d8ae3SPaolo Bonzini }
1127c50d8ae3SPaolo Bonzini 
1128c50d8ae3SPaolo Bonzini /*
1129c50d8ae3SPaolo Bonzini  * Write-protect on the specified @sptep, @pt_protect indicates whether
1130c50d8ae3SPaolo Bonzini  * spte write-protection is caused by protecting shadow page table.
1131c50d8ae3SPaolo Bonzini  *
1132c50d8ae3SPaolo Bonzini  * Note: write protection is difference between dirty logging and spte
1133c50d8ae3SPaolo Bonzini  * protection:
1134c50d8ae3SPaolo Bonzini  * - for dirty logging, the spte can be set to writable at anytime if
1135c50d8ae3SPaolo Bonzini  *   its dirty bitmap is properly set.
1136c50d8ae3SPaolo Bonzini  * - for spte protection, the spte can be writable only after unsync-ing
1137c50d8ae3SPaolo Bonzini  *   shadow page.
1138c50d8ae3SPaolo Bonzini  *
1139c50d8ae3SPaolo Bonzini  * Return true if tlb need be flushed.
1140c50d8ae3SPaolo Bonzini  */
1141c50d8ae3SPaolo Bonzini static bool spte_write_protect(u64 *sptep, bool pt_protect)
1142c50d8ae3SPaolo Bonzini {
1143c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1144c50d8ae3SPaolo Bonzini 
1145c50d8ae3SPaolo Bonzini 	if (!is_writable_pte(spte) &&
1146706c9c55SSean Christopherson 	    !(pt_protect && is_mmu_writable_spte(spte)))
1147c50d8ae3SPaolo Bonzini 		return false;
1148c50d8ae3SPaolo Bonzini 
1149805a0f83SStephen Zhang 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1150c50d8ae3SPaolo Bonzini 
1151c50d8ae3SPaolo Bonzini 	if (pt_protect)
11525fc3424fSSean Christopherson 		spte &= ~shadow_mmu_writable_mask;
1153c50d8ae3SPaolo Bonzini 	spte = spte & ~PT_WRITABLE_MASK;
1154c50d8ae3SPaolo Bonzini 
1155c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1156c50d8ae3SPaolo Bonzini }
1157c50d8ae3SPaolo Bonzini 
11581346bbb6SDavid Matlack static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1159c50d8ae3SPaolo Bonzini 			       bool pt_protect)
1160c50d8ae3SPaolo Bonzini {
1161c50d8ae3SPaolo Bonzini 	u64 *sptep;
1162c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1163c50d8ae3SPaolo Bonzini 	bool flush = false;
1164c50d8ae3SPaolo Bonzini 
1165c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1166c50d8ae3SPaolo Bonzini 		flush |= spte_write_protect(sptep, pt_protect);
1167c50d8ae3SPaolo Bonzini 
1168c50d8ae3SPaolo Bonzini 	return flush;
1169c50d8ae3SPaolo Bonzini }
1170c50d8ae3SPaolo Bonzini 
1171c50d8ae3SPaolo Bonzini static bool spte_clear_dirty(u64 *sptep)
1172c50d8ae3SPaolo Bonzini {
1173c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1174c50d8ae3SPaolo Bonzini 
1175805a0f83SStephen Zhang 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1176c50d8ae3SPaolo Bonzini 
1177c50d8ae3SPaolo Bonzini 	MMU_WARN_ON(!spte_ad_enabled(spte));
1178c50d8ae3SPaolo Bonzini 	spte &= ~shadow_dirty_mask;
1179c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1180c50d8ae3SPaolo Bonzini }
1181c50d8ae3SPaolo Bonzini 
1182c50d8ae3SPaolo Bonzini static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1183c50d8ae3SPaolo Bonzini {
1184c50d8ae3SPaolo Bonzini 	bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1185c50d8ae3SPaolo Bonzini 					       (unsigned long *)sptep);
1186c50d8ae3SPaolo Bonzini 	if (was_writable && !spte_ad_enabled(*sptep))
1187c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1188c50d8ae3SPaolo Bonzini 
1189c50d8ae3SPaolo Bonzini 	return was_writable;
1190c50d8ae3SPaolo Bonzini }
1191c50d8ae3SPaolo Bonzini 
1192c50d8ae3SPaolo Bonzini /*
1193c50d8ae3SPaolo Bonzini  * Gets the GFN ready for another round of dirty logging by clearing the
1194c50d8ae3SPaolo Bonzini  *	- D bit on ad-enabled SPTEs, and
1195c50d8ae3SPaolo Bonzini  *	- W bit on ad-disabled SPTEs.
1196c50d8ae3SPaolo Bonzini  * Returns true iff any D or W bits were cleared.
1197c50d8ae3SPaolo Bonzini  */
11980a234f5dSSean Christopherson static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1199269e9552SHamza Mahfooz 			       const struct kvm_memory_slot *slot)
1200c50d8ae3SPaolo Bonzini {
1201c50d8ae3SPaolo Bonzini 	u64 *sptep;
1202c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1203c50d8ae3SPaolo Bonzini 	bool flush = false;
1204c50d8ae3SPaolo Bonzini 
1205c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1206c50d8ae3SPaolo Bonzini 		if (spte_ad_need_write_protect(*sptep))
1207c50d8ae3SPaolo Bonzini 			flush |= spte_wrprot_for_clear_dirty(sptep);
1208c50d8ae3SPaolo Bonzini 		else
1209c50d8ae3SPaolo Bonzini 			flush |= spte_clear_dirty(sptep);
1210c50d8ae3SPaolo Bonzini 
1211c50d8ae3SPaolo Bonzini 	return flush;
1212c50d8ae3SPaolo Bonzini }
1213c50d8ae3SPaolo Bonzini 
1214c50d8ae3SPaolo Bonzini /**
1215c50d8ae3SPaolo Bonzini  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1216c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1217c50d8ae3SPaolo Bonzini  * @slot: slot to protect
1218c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1219c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should protect
1220c50d8ae3SPaolo Bonzini  *
122189212919SKeqian Zhu  * Used when we do not need to care about huge page mappings.
1222c50d8ae3SPaolo Bonzini  */
1223c50d8ae3SPaolo Bonzini static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1224c50d8ae3SPaolo Bonzini 				     struct kvm_memory_slot *slot,
1225c50d8ae3SPaolo Bonzini 				     gfn_t gfn_offset, unsigned long mask)
1226c50d8ae3SPaolo Bonzini {
1227c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1228c50d8ae3SPaolo Bonzini 
1229897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
1230a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1231a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, true);
1232e2209710SBen Gardon 
1233e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1234e2209710SBen Gardon 		return;
1235e2209710SBen Gardon 
1236c50d8ae3SPaolo Bonzini 	while (mask) {
123793e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
12383bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
12391346bbb6SDavid Matlack 		rmap_write_protect(rmap_head, false);
1240c50d8ae3SPaolo Bonzini 
1241c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1242c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1243c50d8ae3SPaolo Bonzini 	}
1244c50d8ae3SPaolo Bonzini }
1245c50d8ae3SPaolo Bonzini 
1246c50d8ae3SPaolo Bonzini /**
1247c50d8ae3SPaolo Bonzini  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1248c50d8ae3SPaolo Bonzini  * protect the page if the D-bit isn't supported.
1249c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1250c50d8ae3SPaolo Bonzini  * @slot: slot to clear D-bit
1251c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1252c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should clear D-bit
1253c50d8ae3SPaolo Bonzini  *
1254c50d8ae3SPaolo Bonzini  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1255c50d8ae3SPaolo Bonzini  */
1256a018eba5SSean Christopherson static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1257c50d8ae3SPaolo Bonzini 					 struct kvm_memory_slot *slot,
1258c50d8ae3SPaolo Bonzini 					 gfn_t gfn_offset, unsigned long mask)
1259c50d8ae3SPaolo Bonzini {
1260c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1261c50d8ae3SPaolo Bonzini 
1262897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
1263a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1264a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, false);
1265e2209710SBen Gardon 
1266e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1267e2209710SBen Gardon 		return;
1268e2209710SBen Gardon 
1269c50d8ae3SPaolo Bonzini 	while (mask) {
127093e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
12713bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
12720a234f5dSSean Christopherson 		__rmap_clear_dirty(kvm, rmap_head, slot);
1273c50d8ae3SPaolo Bonzini 
1274c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1275c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1276c50d8ae3SPaolo Bonzini 	}
1277c50d8ae3SPaolo Bonzini }
1278c50d8ae3SPaolo Bonzini 
1279c50d8ae3SPaolo Bonzini /**
1280c50d8ae3SPaolo Bonzini  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1281c50d8ae3SPaolo Bonzini  * PT level pages.
1282c50d8ae3SPaolo Bonzini  *
1283c50d8ae3SPaolo Bonzini  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1284c50d8ae3SPaolo Bonzini  * enable dirty logging for them.
1285c50d8ae3SPaolo Bonzini  *
128689212919SKeqian Zhu  * We need to care about huge page mappings: e.g. during dirty logging we may
128789212919SKeqian Zhu  * have such mappings.
1288c50d8ae3SPaolo Bonzini  */
1289c50d8ae3SPaolo Bonzini void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1290c50d8ae3SPaolo Bonzini 				struct kvm_memory_slot *slot,
1291c50d8ae3SPaolo Bonzini 				gfn_t gfn_offset, unsigned long mask)
1292c50d8ae3SPaolo Bonzini {
129389212919SKeqian Zhu 	/*
129489212919SKeqian Zhu 	 * Huge pages are NOT write protected when we start dirty logging in
129589212919SKeqian Zhu 	 * initially-all-set mode; must write protect them here so that they
129689212919SKeqian Zhu 	 * are split to 4K on the first write.
129789212919SKeqian Zhu 	 *
129889212919SKeqian Zhu 	 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
129989212919SKeqian Zhu 	 * of memslot has no such restriction, so the range can cross two large
130089212919SKeqian Zhu 	 * pages.
130189212919SKeqian Zhu 	 */
130289212919SKeqian Zhu 	if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
130389212919SKeqian Zhu 		gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
130489212919SKeqian Zhu 		gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
130589212919SKeqian Zhu 
1306cb00a70bSDavid Matlack 		if (READ_ONCE(eager_page_split))
1307cb00a70bSDavid Matlack 			kvm_mmu_try_split_huge_pages(kvm, slot, start, end, PG_LEVEL_4K);
1308cb00a70bSDavid Matlack 
130989212919SKeqian Zhu 		kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
131089212919SKeqian Zhu 
131189212919SKeqian Zhu 		/* Cross two large pages? */
131289212919SKeqian Zhu 		if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
131389212919SKeqian Zhu 		    ALIGN(end << PAGE_SHIFT, PMD_SIZE))
131489212919SKeqian Zhu 			kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
131589212919SKeqian Zhu 						       PG_LEVEL_2M);
131689212919SKeqian Zhu 	}
131789212919SKeqian Zhu 
131889212919SKeqian Zhu 	/* Now handle 4K PTEs.  */
1319a018eba5SSean Christopherson 	if (kvm_x86_ops.cpu_dirty_log_size)
1320a018eba5SSean Christopherson 		kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1321c50d8ae3SPaolo Bonzini 	else
1322c50d8ae3SPaolo Bonzini 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1323c50d8ae3SPaolo Bonzini }
1324c50d8ae3SPaolo Bonzini 
1325fb04a1edSPeter Xu int kvm_cpu_dirty_log_size(void)
1326fb04a1edSPeter Xu {
13276dd03800SSean Christopherson 	return kvm_x86_ops.cpu_dirty_log_size;
1328fb04a1edSPeter Xu }
1329fb04a1edSPeter Xu 
1330c50d8ae3SPaolo Bonzini bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
13313ad93562SKeqian Zhu 				    struct kvm_memory_slot *slot, u64 gfn,
13323ad93562SKeqian Zhu 				    int min_level)
1333c50d8ae3SPaolo Bonzini {
1334c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1335c50d8ae3SPaolo Bonzini 	int i;
1336c50d8ae3SPaolo Bonzini 	bool write_protected = false;
1337c50d8ae3SPaolo Bonzini 
1338e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
13393ad93562SKeqian Zhu 		for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
134093e083d4SDavid Matlack 			rmap_head = gfn_to_rmap(gfn, i, slot);
13411346bbb6SDavid Matlack 			write_protected |= rmap_write_protect(rmap_head, true);
1342c50d8ae3SPaolo Bonzini 		}
1343e2209710SBen Gardon 	}
1344c50d8ae3SPaolo Bonzini 
1345897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
134646044f72SBen Gardon 		write_protected |=
13473ad93562SKeqian Zhu 			kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
134846044f72SBen Gardon 
1349c50d8ae3SPaolo Bonzini 	return write_protected;
1350c50d8ae3SPaolo Bonzini }
1351c50d8ae3SPaolo Bonzini 
1352cf48f9e2SDavid Matlack static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1353c50d8ae3SPaolo Bonzini {
1354c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
1355c50d8ae3SPaolo Bonzini 
1356c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
13573ad93562SKeqian Zhu 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1358c50d8ae3SPaolo Bonzini }
1359c50d8ae3SPaolo Bonzini 
13600a234f5dSSean Christopherson static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1361269e9552SHamza Mahfooz 			  const struct kvm_memory_slot *slot)
1362c50d8ae3SPaolo Bonzini {
136371f51d2cSMingwei Zhang 	return pte_list_destroy(kvm, rmap_head);
1364c50d8ae3SPaolo Bonzini }
1365c50d8ae3SPaolo Bonzini 
13663039bcc7SSean Christopherson static bool kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1367c50d8ae3SPaolo Bonzini 			    struct kvm_memory_slot *slot, gfn_t gfn, int level,
13683039bcc7SSean Christopherson 			    pte_t unused)
1369c50d8ae3SPaolo Bonzini {
13700a234f5dSSean Christopherson 	return kvm_zap_rmapp(kvm, rmap_head, slot);
1371c50d8ae3SPaolo Bonzini }
1372c50d8ae3SPaolo Bonzini 
13733039bcc7SSean Christopherson static bool kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1374c50d8ae3SPaolo Bonzini 			      struct kvm_memory_slot *slot, gfn_t gfn, int level,
13753039bcc7SSean Christopherson 			      pte_t pte)
1376c50d8ae3SPaolo Bonzini {
1377c50d8ae3SPaolo Bonzini 	u64 *sptep;
1378c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
137998a26b69SVihas Mak 	bool need_flush = false;
1380c50d8ae3SPaolo Bonzini 	u64 new_spte;
1381c50d8ae3SPaolo Bonzini 	kvm_pfn_t new_pfn;
1382c50d8ae3SPaolo Bonzini 
13833039bcc7SSean Christopherson 	WARN_ON(pte_huge(pte));
13843039bcc7SSean Christopherson 	new_pfn = pte_pfn(pte);
1385c50d8ae3SPaolo Bonzini 
1386c50d8ae3SPaolo Bonzini restart:
1387c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
1388805a0f83SStephen Zhang 		rmap_printk("spte %p %llx gfn %llx (%d)\n",
1389c50d8ae3SPaolo Bonzini 			    sptep, *sptep, gfn, level);
1390c50d8ae3SPaolo Bonzini 
139198a26b69SVihas Mak 		need_flush = true;
1392c50d8ae3SPaolo Bonzini 
13933039bcc7SSean Christopherson 		if (pte_write(pte)) {
139471f51d2cSMingwei Zhang 			pte_list_remove(kvm, rmap_head, sptep);
1395c50d8ae3SPaolo Bonzini 			goto restart;
1396c50d8ae3SPaolo Bonzini 		} else {
1397cb3eedabSPaolo Bonzini 			new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1398cb3eedabSPaolo Bonzini 					*sptep, new_pfn);
1399c50d8ae3SPaolo Bonzini 
140071f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, sptep);
1401c50d8ae3SPaolo Bonzini 			mmu_spte_set(sptep, new_spte);
1402c50d8ae3SPaolo Bonzini 		}
1403c50d8ae3SPaolo Bonzini 	}
1404c50d8ae3SPaolo Bonzini 
1405c50d8ae3SPaolo Bonzini 	if (need_flush && kvm_available_flush_tlb_with_range()) {
1406c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
140798a26b69SVihas Mak 		return false;
1408c50d8ae3SPaolo Bonzini 	}
1409c50d8ae3SPaolo Bonzini 
1410c50d8ae3SPaolo Bonzini 	return need_flush;
1411c50d8ae3SPaolo Bonzini }
1412c50d8ae3SPaolo Bonzini 
1413c50d8ae3SPaolo Bonzini struct slot_rmap_walk_iterator {
1414c50d8ae3SPaolo Bonzini 	/* input fields. */
1415269e9552SHamza Mahfooz 	const struct kvm_memory_slot *slot;
1416c50d8ae3SPaolo Bonzini 	gfn_t start_gfn;
1417c50d8ae3SPaolo Bonzini 	gfn_t end_gfn;
1418c50d8ae3SPaolo Bonzini 	int start_level;
1419c50d8ae3SPaolo Bonzini 	int end_level;
1420c50d8ae3SPaolo Bonzini 
1421c50d8ae3SPaolo Bonzini 	/* output fields. */
1422c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1423c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap;
1424c50d8ae3SPaolo Bonzini 	int level;
1425c50d8ae3SPaolo Bonzini 
1426c50d8ae3SPaolo Bonzini 	/* private field. */
1427c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *end_rmap;
1428c50d8ae3SPaolo Bonzini };
1429c50d8ae3SPaolo Bonzini 
1430c50d8ae3SPaolo Bonzini static void
1431c50d8ae3SPaolo Bonzini rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1432c50d8ae3SPaolo Bonzini {
1433c50d8ae3SPaolo Bonzini 	iterator->level = level;
1434c50d8ae3SPaolo Bonzini 	iterator->gfn = iterator->start_gfn;
143593e083d4SDavid Matlack 	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
143693e083d4SDavid Matlack 	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1437c50d8ae3SPaolo Bonzini }
1438c50d8ae3SPaolo Bonzini 
1439c50d8ae3SPaolo Bonzini static void
1440c50d8ae3SPaolo Bonzini slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1441269e9552SHamza Mahfooz 		    const struct kvm_memory_slot *slot, int start_level,
1442c50d8ae3SPaolo Bonzini 		    int end_level, gfn_t start_gfn, gfn_t end_gfn)
1443c50d8ae3SPaolo Bonzini {
1444c50d8ae3SPaolo Bonzini 	iterator->slot = slot;
1445c50d8ae3SPaolo Bonzini 	iterator->start_level = start_level;
1446c50d8ae3SPaolo Bonzini 	iterator->end_level = end_level;
1447c50d8ae3SPaolo Bonzini 	iterator->start_gfn = start_gfn;
1448c50d8ae3SPaolo Bonzini 	iterator->end_gfn = end_gfn;
1449c50d8ae3SPaolo Bonzini 
1450c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->start_level);
1451c50d8ae3SPaolo Bonzini }
1452c50d8ae3SPaolo Bonzini 
1453c50d8ae3SPaolo Bonzini static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1454c50d8ae3SPaolo Bonzini {
1455c50d8ae3SPaolo Bonzini 	return !!iterator->rmap;
1456c50d8ae3SPaolo Bonzini }
1457c50d8ae3SPaolo Bonzini 
1458c50d8ae3SPaolo Bonzini static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1459c50d8ae3SPaolo Bonzini {
14606ba1e04fSVipin Sharma 	while (++iterator->rmap <= iterator->end_rmap) {
1461c50d8ae3SPaolo Bonzini 		iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
14626ba1e04fSVipin Sharma 
14636ba1e04fSVipin Sharma 		if (iterator->rmap->val)
1464c50d8ae3SPaolo Bonzini 			return;
1465c50d8ae3SPaolo Bonzini 	}
1466c50d8ae3SPaolo Bonzini 
1467c50d8ae3SPaolo Bonzini 	if (++iterator->level > iterator->end_level) {
1468c50d8ae3SPaolo Bonzini 		iterator->rmap = NULL;
1469c50d8ae3SPaolo Bonzini 		return;
1470c50d8ae3SPaolo Bonzini 	}
1471c50d8ae3SPaolo Bonzini 
1472c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->level);
1473c50d8ae3SPaolo Bonzini }
1474c50d8ae3SPaolo Bonzini 
1475c50d8ae3SPaolo Bonzini #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1476c50d8ae3SPaolo Bonzini 	   _start_gfn, _end_gfn, _iter_)				\
1477c50d8ae3SPaolo Bonzini 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1478c50d8ae3SPaolo Bonzini 				 _end_level_, _start_gfn, _end_gfn);	\
1479c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_okay(_iter_);				\
1480c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_next(_iter_))
1481c50d8ae3SPaolo Bonzini 
14823039bcc7SSean Christopherson typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1483c1b91493SSean Christopherson 			       struct kvm_memory_slot *slot, gfn_t gfn,
14843039bcc7SSean Christopherson 			       int level, pte_t pte);
1485c1b91493SSean Christopherson 
14863039bcc7SSean Christopherson static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
14873039bcc7SSean Christopherson 						 struct kvm_gfn_range *range,
1488c1b91493SSean Christopherson 						 rmap_handler_t handler)
1489c50d8ae3SPaolo Bonzini {
1490c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
14913039bcc7SSean Christopherson 	bool ret = false;
1492c50d8ae3SPaolo Bonzini 
14933039bcc7SSean Christopherson 	for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
14943039bcc7SSean Christopherson 				 range->start, range->end - 1, &iterator)
14953039bcc7SSean Christopherson 		ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
14963039bcc7SSean Christopherson 			       iterator.level, range->pte);
1497c50d8ae3SPaolo Bonzini 
1498c50d8ae3SPaolo Bonzini 	return ret;
1499c50d8ae3SPaolo Bonzini }
1500c50d8ae3SPaolo Bonzini 
15013039bcc7SSean Christopherson bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1502c50d8ae3SPaolo Bonzini {
1503e2209710SBen Gardon 	bool flush = false;
1504c50d8ae3SPaolo Bonzini 
1505e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
15063039bcc7SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_unmap_rmapp);
1507063afacdSBen Gardon 
1508897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
1509c7785d85SHou Wenlong 		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1510063afacdSBen Gardon 
15113039bcc7SSean Christopherson 	return flush;
1512c50d8ae3SPaolo Bonzini }
1513c50d8ae3SPaolo Bonzini 
15143039bcc7SSean Christopherson bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1515c50d8ae3SPaolo Bonzini {
1516e2209710SBen Gardon 	bool flush = false;
15171d8dd6b3SBen Gardon 
1518e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
15193039bcc7SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmapp);
15201d8dd6b3SBen Gardon 
1521897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
15223039bcc7SSean Christopherson 		flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
15231d8dd6b3SBen Gardon 
15243039bcc7SSean Christopherson 	return flush;
1525c50d8ae3SPaolo Bonzini }
1526c50d8ae3SPaolo Bonzini 
15273039bcc7SSean Christopherson static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1528c50d8ae3SPaolo Bonzini 			  struct kvm_memory_slot *slot, gfn_t gfn, int level,
15293039bcc7SSean Christopherson 			  pte_t unused)
1530c50d8ae3SPaolo Bonzini {
1531c50d8ae3SPaolo Bonzini 	u64 *sptep;
15323f649ab7SKees Cook 	struct rmap_iterator iter;
1533c50d8ae3SPaolo Bonzini 	int young = 0;
1534c50d8ae3SPaolo Bonzini 
1535c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1536c50d8ae3SPaolo Bonzini 		young |= mmu_spte_age(sptep);
1537c50d8ae3SPaolo Bonzini 
1538c50d8ae3SPaolo Bonzini 	return young;
1539c50d8ae3SPaolo Bonzini }
1540c50d8ae3SPaolo Bonzini 
15413039bcc7SSean Christopherson static bool kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1542c50d8ae3SPaolo Bonzini 			       struct kvm_memory_slot *slot, gfn_t gfn,
15433039bcc7SSean Christopherson 			       int level, pte_t unused)
1544c50d8ae3SPaolo Bonzini {
1545c50d8ae3SPaolo Bonzini 	u64 *sptep;
1546c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1547c50d8ae3SPaolo Bonzini 
1548c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1549c50d8ae3SPaolo Bonzini 		if (is_accessed_spte(*sptep))
155098a26b69SVihas Mak 			return true;
155198a26b69SVihas Mak 	return false;
1552c50d8ae3SPaolo Bonzini }
1553c50d8ae3SPaolo Bonzini 
1554c50d8ae3SPaolo Bonzini #define RMAP_RECYCLE_THRESHOLD 1000
1555c50d8ae3SPaolo Bonzini 
15568a9f566aSDavid Matlack static void rmap_add(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
15578a9f566aSDavid Matlack 		     u64 *spte, gfn_t gfn)
1558c50d8ae3SPaolo Bonzini {
1559c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
156068be1306SDavid Matlack 	struct kvm_rmap_head *rmap_head;
156168be1306SDavid Matlack 	int rmap_count;
1562c50d8ae3SPaolo Bonzini 
156357354682SSean Christopherson 	sp = sptep_to_sp(spte);
156468be1306SDavid Matlack 	kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
156593e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
156668be1306SDavid Matlack 	rmap_count = pte_list_add(vcpu, spte, rmap_head);
1567c50d8ae3SPaolo Bonzini 
156868be1306SDavid Matlack 	if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
15693039bcc7SSean Christopherson 		kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, __pte(0));
157068be1306SDavid Matlack 		kvm_flush_remote_tlbs_with_address(
157168be1306SDavid Matlack 				vcpu->kvm, sp->gfn, KVM_PAGES_PER_HPAGE(sp->role.level));
157268be1306SDavid Matlack 	}
1573c50d8ae3SPaolo Bonzini }
1574c50d8ae3SPaolo Bonzini 
15753039bcc7SSean Christopherson bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1576c50d8ae3SPaolo Bonzini {
1577e2209710SBen Gardon 	bool young = false;
1578f8e14497SBen Gardon 
1579e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
15803039bcc7SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_age_rmapp);
15813039bcc7SSean Christopherson 
1582897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
15833039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1584f8e14497SBen Gardon 
1585f8e14497SBen Gardon 	return young;
1586c50d8ae3SPaolo Bonzini }
1587c50d8ae3SPaolo Bonzini 
15883039bcc7SSean Christopherson bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1589c50d8ae3SPaolo Bonzini {
1590e2209710SBen Gardon 	bool young = false;
1591f8e14497SBen Gardon 
1592e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
15933039bcc7SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmapp);
15943039bcc7SSean Christopherson 
1595897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
15963039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1597f8e14497SBen Gardon 
1598f8e14497SBen Gardon 	return young;
1599c50d8ae3SPaolo Bonzini }
1600c50d8ae3SPaolo Bonzini 
1601c50d8ae3SPaolo Bonzini #ifdef MMU_DEBUG
1602c50d8ae3SPaolo Bonzini static int is_empty_shadow_page(u64 *spt)
1603c50d8ae3SPaolo Bonzini {
1604c50d8ae3SPaolo Bonzini 	u64 *pos;
1605c50d8ae3SPaolo Bonzini 	u64 *end;
1606c50d8ae3SPaolo Bonzini 
1607c50d8ae3SPaolo Bonzini 	for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1608c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*pos)) {
1609c50d8ae3SPaolo Bonzini 			printk(KERN_ERR "%s: %p %llx\n", __func__,
1610c50d8ae3SPaolo Bonzini 			       pos, *pos);
1611c50d8ae3SPaolo Bonzini 			return 0;
1612c50d8ae3SPaolo Bonzini 		}
1613c50d8ae3SPaolo Bonzini 	return 1;
1614c50d8ae3SPaolo Bonzini }
1615c50d8ae3SPaolo Bonzini #endif
1616c50d8ae3SPaolo Bonzini 
1617c50d8ae3SPaolo Bonzini /*
1618c50d8ae3SPaolo Bonzini  * This value is the sum of all of the kvm instances's
1619c50d8ae3SPaolo Bonzini  * kvm->arch.n_used_mmu_pages values.  We need a global,
1620c50d8ae3SPaolo Bonzini  * aggregate version in order to make the slab shrinker
1621c50d8ae3SPaolo Bonzini  * faster
1622c50d8ae3SPaolo Bonzini  */
1623d5aaad6fSSean Christopherson static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1624c50d8ae3SPaolo Bonzini {
1625c50d8ae3SPaolo Bonzini 	kvm->arch.n_used_mmu_pages += nr;
1626c50d8ae3SPaolo Bonzini 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1627c50d8ae3SPaolo Bonzini }
1628c50d8ae3SPaolo Bonzini 
1629c50d8ae3SPaolo Bonzini static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
1630c50d8ae3SPaolo Bonzini {
1631c50d8ae3SPaolo Bonzini 	MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1632c50d8ae3SPaolo Bonzini 	hlist_del(&sp->hash_link);
1633c50d8ae3SPaolo Bonzini 	list_del(&sp->link);
1634c50d8ae3SPaolo Bonzini 	free_page((unsigned long)sp->spt);
1635c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
1636c50d8ae3SPaolo Bonzini 		free_page((unsigned long)sp->gfns);
1637c50d8ae3SPaolo Bonzini 	kmem_cache_free(mmu_page_header_cache, sp);
1638c50d8ae3SPaolo Bonzini }
1639c50d8ae3SPaolo Bonzini 
1640c50d8ae3SPaolo Bonzini static unsigned kvm_page_table_hashfn(gfn_t gfn)
1641c50d8ae3SPaolo Bonzini {
1642c50d8ae3SPaolo Bonzini 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1643c50d8ae3SPaolo Bonzini }
1644c50d8ae3SPaolo Bonzini 
1645c50d8ae3SPaolo Bonzini static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
1646c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp, u64 *parent_pte)
1647c50d8ae3SPaolo Bonzini {
1648c50d8ae3SPaolo Bonzini 	if (!parent_pte)
1649c50d8ae3SPaolo Bonzini 		return;
1650c50d8ae3SPaolo Bonzini 
1651c50d8ae3SPaolo Bonzini 	pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
1652c50d8ae3SPaolo Bonzini }
1653c50d8ae3SPaolo Bonzini 
1654c50d8ae3SPaolo Bonzini static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1655c50d8ae3SPaolo Bonzini 				       u64 *parent_pte)
1656c50d8ae3SPaolo Bonzini {
1657c50d8ae3SPaolo Bonzini 	__pte_list_remove(parent_pte, &sp->parent_ptes);
1658c50d8ae3SPaolo Bonzini }
1659c50d8ae3SPaolo Bonzini 
1660c50d8ae3SPaolo Bonzini static void drop_parent_pte(struct kvm_mmu_page *sp,
1661c50d8ae3SPaolo Bonzini 			    u64 *parent_pte)
1662c50d8ae3SPaolo Bonzini {
1663c50d8ae3SPaolo Bonzini 	mmu_page_remove_parent_pte(sp, parent_pte);
1664c50d8ae3SPaolo Bonzini 	mmu_spte_clear_no_track(parent_pte);
1665c50d8ae3SPaolo Bonzini }
1666c50d8ae3SPaolo Bonzini 
166727a59d57SDavid Matlack static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, bool direct)
1668c50d8ae3SPaolo Bonzini {
1669c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1670c50d8ae3SPaolo Bonzini 
167194ce87efSSean Christopherson 	sp = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
167294ce87efSSean Christopherson 	sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
1673c50d8ae3SPaolo Bonzini 	if (!direct)
167494ce87efSSean Christopherson 		sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
1675c50d8ae3SPaolo Bonzini 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
1676c50d8ae3SPaolo Bonzini 
1677c50d8ae3SPaolo Bonzini 	/*
1678c50d8ae3SPaolo Bonzini 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
1679c50d8ae3SPaolo Bonzini 	 * depends on valid pages being added to the head of the list.  See
1680c50d8ae3SPaolo Bonzini 	 * comments in kvm_zap_obsolete_pages().
1681c50d8ae3SPaolo Bonzini 	 */
1682c50d8ae3SPaolo Bonzini 	sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
1683c50d8ae3SPaolo Bonzini 	list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
1684c50d8ae3SPaolo Bonzini 	kvm_mod_used_mmu_pages(vcpu->kvm, +1);
1685c50d8ae3SPaolo Bonzini 	return sp;
1686c50d8ae3SPaolo Bonzini }
1687c50d8ae3SPaolo Bonzini 
1688c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte);
1689c50d8ae3SPaolo Bonzini static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1690c50d8ae3SPaolo Bonzini {
1691c50d8ae3SPaolo Bonzini 	u64 *sptep;
1692c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1693c50d8ae3SPaolo Bonzini 
1694c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1695c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
1696c50d8ae3SPaolo Bonzini 	}
1697c50d8ae3SPaolo Bonzini }
1698c50d8ae3SPaolo Bonzini 
1699c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte)
1700c50d8ae3SPaolo Bonzini {
1701c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1702c50d8ae3SPaolo Bonzini 	unsigned int index;
1703c50d8ae3SPaolo Bonzini 
170457354682SSean Christopherson 	sp = sptep_to_sp(spte);
1705c50d8ae3SPaolo Bonzini 	index = spte - sp->spt;
1706c50d8ae3SPaolo Bonzini 	if (__test_and_set_bit(index, sp->unsync_child_bitmap))
1707c50d8ae3SPaolo Bonzini 		return;
1708c50d8ae3SPaolo Bonzini 	if (sp->unsync_children++)
1709c50d8ae3SPaolo Bonzini 		return;
1710c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
1711c50d8ae3SPaolo Bonzini }
1712c50d8ae3SPaolo Bonzini 
1713c50d8ae3SPaolo Bonzini static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
1714c50d8ae3SPaolo Bonzini 			       struct kvm_mmu_page *sp)
1715c50d8ae3SPaolo Bonzini {
1716c3e5e415SLai Jiangshan 	return -1;
1717c50d8ae3SPaolo Bonzini }
1718c50d8ae3SPaolo Bonzini 
1719c50d8ae3SPaolo Bonzini #define KVM_PAGE_ARRAY_NR 16
1720c50d8ae3SPaolo Bonzini 
1721c50d8ae3SPaolo Bonzini struct kvm_mmu_pages {
1722c50d8ae3SPaolo Bonzini 	struct mmu_page_and_offset {
1723c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
1724c50d8ae3SPaolo Bonzini 		unsigned int idx;
1725c50d8ae3SPaolo Bonzini 	} page[KVM_PAGE_ARRAY_NR];
1726c50d8ae3SPaolo Bonzini 	unsigned int nr;
1727c50d8ae3SPaolo Bonzini };
1728c50d8ae3SPaolo Bonzini 
1729c50d8ae3SPaolo Bonzini static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1730c50d8ae3SPaolo Bonzini 			 int idx)
1731c50d8ae3SPaolo Bonzini {
1732c50d8ae3SPaolo Bonzini 	int i;
1733c50d8ae3SPaolo Bonzini 
1734c50d8ae3SPaolo Bonzini 	if (sp->unsync)
1735c50d8ae3SPaolo Bonzini 		for (i=0; i < pvec->nr; i++)
1736c50d8ae3SPaolo Bonzini 			if (pvec->page[i].sp == sp)
1737c50d8ae3SPaolo Bonzini 				return 0;
1738c50d8ae3SPaolo Bonzini 
1739c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].sp = sp;
1740c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].idx = idx;
1741c50d8ae3SPaolo Bonzini 	pvec->nr++;
1742c50d8ae3SPaolo Bonzini 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
1743c50d8ae3SPaolo Bonzini }
1744c50d8ae3SPaolo Bonzini 
1745c50d8ae3SPaolo Bonzini static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1746c50d8ae3SPaolo Bonzini {
1747c50d8ae3SPaolo Bonzini 	--sp->unsync_children;
1748c50d8ae3SPaolo Bonzini 	WARN_ON((int)sp->unsync_children < 0);
1749c50d8ae3SPaolo Bonzini 	__clear_bit(idx, sp->unsync_child_bitmap);
1750c50d8ae3SPaolo Bonzini }
1751c50d8ae3SPaolo Bonzini 
1752c50d8ae3SPaolo Bonzini static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1753c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1754c50d8ae3SPaolo Bonzini {
1755c50d8ae3SPaolo Bonzini 	int i, ret, nr_unsync_leaf = 0;
1756c50d8ae3SPaolo Bonzini 
1757c50d8ae3SPaolo Bonzini 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1758c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
1759c50d8ae3SPaolo Bonzini 		u64 ent = sp->spt[i];
1760c50d8ae3SPaolo Bonzini 
1761c50d8ae3SPaolo Bonzini 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1762c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1763c50d8ae3SPaolo Bonzini 			continue;
1764c50d8ae3SPaolo Bonzini 		}
1765c50d8ae3SPaolo Bonzini 
17662ca3129eSSean Christopherson 		child = to_shadow_page(ent & SPTE_BASE_ADDR_MASK);
1767c50d8ae3SPaolo Bonzini 
1768c50d8ae3SPaolo Bonzini 		if (child->unsync_children) {
1769c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1770c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1771c50d8ae3SPaolo Bonzini 
1772c50d8ae3SPaolo Bonzini 			ret = __mmu_unsync_walk(child, pvec);
1773c50d8ae3SPaolo Bonzini 			if (!ret) {
1774c50d8ae3SPaolo Bonzini 				clear_unsync_child_bit(sp, i);
1775c50d8ae3SPaolo Bonzini 				continue;
1776c50d8ae3SPaolo Bonzini 			} else if (ret > 0) {
1777c50d8ae3SPaolo Bonzini 				nr_unsync_leaf += ret;
1778c50d8ae3SPaolo Bonzini 			} else
1779c50d8ae3SPaolo Bonzini 				return ret;
1780c50d8ae3SPaolo Bonzini 		} else if (child->unsync) {
1781c50d8ae3SPaolo Bonzini 			nr_unsync_leaf++;
1782c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1783c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1784c50d8ae3SPaolo Bonzini 		} else
1785c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1786c50d8ae3SPaolo Bonzini 	}
1787c50d8ae3SPaolo Bonzini 
1788c50d8ae3SPaolo Bonzini 	return nr_unsync_leaf;
1789c50d8ae3SPaolo Bonzini }
1790c50d8ae3SPaolo Bonzini 
1791c50d8ae3SPaolo Bonzini #define INVALID_INDEX (-1)
1792c50d8ae3SPaolo Bonzini 
1793c50d8ae3SPaolo Bonzini static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1794c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1795c50d8ae3SPaolo Bonzini {
1796c50d8ae3SPaolo Bonzini 	pvec->nr = 0;
1797c50d8ae3SPaolo Bonzini 	if (!sp->unsync_children)
1798c50d8ae3SPaolo Bonzini 		return 0;
1799c50d8ae3SPaolo Bonzini 
1800c50d8ae3SPaolo Bonzini 	mmu_pages_add(pvec, sp, INVALID_INDEX);
1801c50d8ae3SPaolo Bonzini 	return __mmu_unsync_walk(sp, pvec);
1802c50d8ae3SPaolo Bonzini }
1803c50d8ae3SPaolo Bonzini 
1804c50d8ae3SPaolo Bonzini static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1805c50d8ae3SPaolo Bonzini {
1806c50d8ae3SPaolo Bonzini 	WARN_ON(!sp->unsync);
1807c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_sync_page(sp);
1808c50d8ae3SPaolo Bonzini 	sp->unsync = 0;
1809c50d8ae3SPaolo Bonzini 	--kvm->stat.mmu_unsync;
1810c50d8ae3SPaolo Bonzini }
1811c50d8ae3SPaolo Bonzini 
1812c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1813c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list);
1814c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1815c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list);
1816c50d8ae3SPaolo Bonzini 
1817767d8d8dSLai Jiangshan static bool sp_has_gptes(struct kvm_mmu_page *sp)
1818767d8d8dSLai Jiangshan {
1819767d8d8dSLai Jiangshan 	if (sp->role.direct)
1820767d8d8dSLai Jiangshan 		return false;
1821767d8d8dSLai Jiangshan 
182284e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
182384e5ffd0SLai Jiangshan 		return false;
182484e5ffd0SLai Jiangshan 
1825767d8d8dSLai Jiangshan 	return true;
1826767d8d8dSLai Jiangshan }
1827767d8d8dSLai Jiangshan 
1828ac101b7cSSean Christopherson #define for_each_valid_sp(_kvm, _sp, _list)				\
1829ac101b7cSSean Christopherson 	hlist_for_each_entry(_sp, _list, hash_link)			\
1830c50d8ae3SPaolo Bonzini 		if (is_obsolete_sp((_kvm), (_sp))) {			\
1831c50d8ae3SPaolo Bonzini 		} else
1832c50d8ae3SPaolo Bonzini 
1833767d8d8dSLai Jiangshan #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn)		\
1834ac101b7cSSean Christopherson 	for_each_valid_sp(_kvm, _sp,					\
1835ac101b7cSSean Christopherson 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
1836767d8d8dSLai Jiangshan 		if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1837c50d8ae3SPaolo Bonzini 
18388d5678a7SHou Wenlong static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1839c50d8ae3SPaolo Bonzini 			 struct list_head *invalid_list)
1840c50d8ae3SPaolo Bonzini {
1841c3e5e415SLai Jiangshan 	int ret = vcpu->arch.mmu->sync_page(vcpu, sp);
1842c3e5e415SLai Jiangshan 
18438d5678a7SHou Wenlong 	if (ret < 0)
1844c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
18458d5678a7SHou Wenlong 	return ret;
1846c50d8ae3SPaolo Bonzini }
1847c50d8ae3SPaolo Bonzini 
1848c50d8ae3SPaolo Bonzini static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1849c50d8ae3SPaolo Bonzini 					struct list_head *invalid_list,
1850c50d8ae3SPaolo Bonzini 					bool remote_flush)
1851c50d8ae3SPaolo Bonzini {
1852c50d8ae3SPaolo Bonzini 	if (!remote_flush && list_empty(invalid_list))
1853c50d8ae3SPaolo Bonzini 		return false;
1854c50d8ae3SPaolo Bonzini 
1855c50d8ae3SPaolo Bonzini 	if (!list_empty(invalid_list))
1856c50d8ae3SPaolo Bonzini 		kvm_mmu_commit_zap_page(kvm, invalid_list);
1857c50d8ae3SPaolo Bonzini 	else
1858c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
1859c50d8ae3SPaolo Bonzini 	return true;
1860c50d8ae3SPaolo Bonzini }
1861c50d8ae3SPaolo Bonzini 
1862c50d8ae3SPaolo Bonzini static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
1863c50d8ae3SPaolo Bonzini {
1864a955cad8SSean Christopherson 	if (sp->role.invalid)
1865a955cad8SSean Christopherson 		return true;
1866a955cad8SSean Christopherson 
1867a955cad8SSean Christopherson 	/* TDP MMU pages due not use the MMU generation. */
1868a955cad8SSean Christopherson 	return !sp->tdp_mmu_page &&
1869c50d8ae3SPaolo Bonzini 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
1870c50d8ae3SPaolo Bonzini }
1871c50d8ae3SPaolo Bonzini 
1872c50d8ae3SPaolo Bonzini struct mmu_page_path {
1873c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
1874c50d8ae3SPaolo Bonzini 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
1875c50d8ae3SPaolo Bonzini };
1876c50d8ae3SPaolo Bonzini 
1877c50d8ae3SPaolo Bonzini #define for_each_sp(pvec, sp, parents, i)			\
1878c50d8ae3SPaolo Bonzini 		for (i = mmu_pages_first(&pvec, &parents);	\
1879c50d8ae3SPaolo Bonzini 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
1880c50d8ae3SPaolo Bonzini 			i = mmu_pages_next(&pvec, &parents, i))
1881c50d8ae3SPaolo Bonzini 
1882c50d8ae3SPaolo Bonzini static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1883c50d8ae3SPaolo Bonzini 			  struct mmu_page_path *parents,
1884c50d8ae3SPaolo Bonzini 			  int i)
1885c50d8ae3SPaolo Bonzini {
1886c50d8ae3SPaolo Bonzini 	int n;
1887c50d8ae3SPaolo Bonzini 
1888c50d8ae3SPaolo Bonzini 	for (n = i+1; n < pvec->nr; n++) {
1889c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp = pvec->page[n].sp;
1890c50d8ae3SPaolo Bonzini 		unsigned idx = pvec->page[n].idx;
1891c50d8ae3SPaolo Bonzini 		int level = sp->role.level;
1892c50d8ae3SPaolo Bonzini 
1893c50d8ae3SPaolo Bonzini 		parents->idx[level-1] = idx;
18943bae0459SSean Christopherson 		if (level == PG_LEVEL_4K)
1895c50d8ae3SPaolo Bonzini 			break;
1896c50d8ae3SPaolo Bonzini 
1897c50d8ae3SPaolo Bonzini 		parents->parent[level-2] = sp;
1898c50d8ae3SPaolo Bonzini 	}
1899c50d8ae3SPaolo Bonzini 
1900c50d8ae3SPaolo Bonzini 	return n;
1901c50d8ae3SPaolo Bonzini }
1902c50d8ae3SPaolo Bonzini 
1903c50d8ae3SPaolo Bonzini static int mmu_pages_first(struct kvm_mmu_pages *pvec,
1904c50d8ae3SPaolo Bonzini 			   struct mmu_page_path *parents)
1905c50d8ae3SPaolo Bonzini {
1906c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1907c50d8ae3SPaolo Bonzini 	int level;
1908c50d8ae3SPaolo Bonzini 
1909c50d8ae3SPaolo Bonzini 	if (pvec->nr == 0)
1910c50d8ae3SPaolo Bonzini 		return 0;
1911c50d8ae3SPaolo Bonzini 
1912c50d8ae3SPaolo Bonzini 	WARN_ON(pvec->page[0].idx != INVALID_INDEX);
1913c50d8ae3SPaolo Bonzini 
1914c50d8ae3SPaolo Bonzini 	sp = pvec->page[0].sp;
1915c50d8ae3SPaolo Bonzini 	level = sp->role.level;
19163bae0459SSean Christopherson 	WARN_ON(level == PG_LEVEL_4K);
1917c50d8ae3SPaolo Bonzini 
1918c50d8ae3SPaolo Bonzini 	parents->parent[level-2] = sp;
1919c50d8ae3SPaolo Bonzini 
1920c50d8ae3SPaolo Bonzini 	/* Also set up a sentinel.  Further entries in pvec are all
1921c50d8ae3SPaolo Bonzini 	 * children of sp, so this element is never overwritten.
1922c50d8ae3SPaolo Bonzini 	 */
1923c50d8ae3SPaolo Bonzini 	parents->parent[level-1] = NULL;
1924c50d8ae3SPaolo Bonzini 	return mmu_pages_next(pvec, parents, 0);
1925c50d8ae3SPaolo Bonzini }
1926c50d8ae3SPaolo Bonzini 
1927c50d8ae3SPaolo Bonzini static void mmu_pages_clear_parents(struct mmu_page_path *parents)
1928c50d8ae3SPaolo Bonzini {
1929c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1930c50d8ae3SPaolo Bonzini 	unsigned int level = 0;
1931c50d8ae3SPaolo Bonzini 
1932c50d8ae3SPaolo Bonzini 	do {
1933c50d8ae3SPaolo Bonzini 		unsigned int idx = parents->idx[level];
1934c50d8ae3SPaolo Bonzini 		sp = parents->parent[level];
1935c50d8ae3SPaolo Bonzini 		if (!sp)
1936c50d8ae3SPaolo Bonzini 			return;
1937c50d8ae3SPaolo Bonzini 
1938c50d8ae3SPaolo Bonzini 		WARN_ON(idx == INVALID_INDEX);
1939c50d8ae3SPaolo Bonzini 		clear_unsync_child_bit(sp, idx);
1940c50d8ae3SPaolo Bonzini 		level++;
1941c50d8ae3SPaolo Bonzini 	} while (!sp->unsync_children);
1942c50d8ae3SPaolo Bonzini }
1943c50d8ae3SPaolo Bonzini 
194465855ed8SLai Jiangshan static int mmu_sync_children(struct kvm_vcpu *vcpu,
194565855ed8SLai Jiangshan 			     struct kvm_mmu_page *parent, bool can_yield)
1946c50d8ae3SPaolo Bonzini {
1947c50d8ae3SPaolo Bonzini 	int i;
1948c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1949c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
1950c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
1951c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
1952c50d8ae3SPaolo Bonzini 	bool flush = false;
1953c50d8ae3SPaolo Bonzini 
1954c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
1955c50d8ae3SPaolo Bonzini 		bool protected = false;
1956c50d8ae3SPaolo Bonzini 
1957c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i)
1958cf48f9e2SDavid Matlack 			protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
1959c50d8ae3SPaolo Bonzini 
1960c50d8ae3SPaolo Bonzini 		if (protected) {
19615591c069SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
1962c50d8ae3SPaolo Bonzini 			flush = false;
1963c50d8ae3SPaolo Bonzini 		}
1964c50d8ae3SPaolo Bonzini 
1965c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
1966479a1efcSSean Christopherson 			kvm_unlink_unsync_page(vcpu->kvm, sp);
19678d5678a7SHou Wenlong 			flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
1968c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
1969c50d8ae3SPaolo Bonzini 		}
1970531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
1971c3e5e415SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
197265855ed8SLai Jiangshan 			if (!can_yield) {
197365855ed8SLai Jiangshan 				kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
197465855ed8SLai Jiangshan 				return -EINTR;
197565855ed8SLai Jiangshan 			}
197665855ed8SLai Jiangshan 
1977531810caSBen Gardon 			cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
1978c50d8ae3SPaolo Bonzini 			flush = false;
1979c50d8ae3SPaolo Bonzini 		}
1980c50d8ae3SPaolo Bonzini 	}
1981c50d8ae3SPaolo Bonzini 
1982c3e5e415SLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
198365855ed8SLai Jiangshan 	return 0;
1984c50d8ae3SPaolo Bonzini }
1985c50d8ae3SPaolo Bonzini 
1986c50d8ae3SPaolo Bonzini static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
1987c50d8ae3SPaolo Bonzini {
1988c50d8ae3SPaolo Bonzini 	atomic_set(&sp->write_flooding_count,  0);
1989c50d8ae3SPaolo Bonzini }
1990c50d8ae3SPaolo Bonzini 
1991c50d8ae3SPaolo Bonzini static void clear_sp_write_flooding_count(u64 *spte)
1992c50d8ae3SPaolo Bonzini {
199357354682SSean Christopherson 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
1994c50d8ae3SPaolo Bonzini }
1995c50d8ae3SPaolo Bonzini 
1996*94c81364SDavid Matlack static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm_vcpu *vcpu,
1997*94c81364SDavid Matlack 						     gfn_t gfn,
1998*94c81364SDavid Matlack 						     struct hlist_head *sp_list,
19992e65e842SDavid Matlack 						     union kvm_mmu_page_role role)
2000c50d8ae3SPaolo Bonzini {
2001c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
20028d5678a7SHou Wenlong 	int ret;
2003c50d8ae3SPaolo Bonzini 	int collisions = 0;
2004c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2005c50d8ae3SPaolo Bonzini 
2006ac101b7cSSean Christopherson 	for_each_valid_sp(vcpu->kvm, sp, sp_list) {
2007c50d8ae3SPaolo Bonzini 		if (sp->gfn != gfn) {
2008c50d8ae3SPaolo Bonzini 			collisions++;
2009c50d8ae3SPaolo Bonzini 			continue;
2010c50d8ae3SPaolo Bonzini 		}
2011c50d8ae3SPaolo Bonzini 
2012ddc16abbSSean Christopherson 		if (sp->role.word != role.word) {
2013ddc16abbSSean Christopherson 			/*
2014ddc16abbSSean Christopherson 			 * If the guest is creating an upper-level page, zap
2015ddc16abbSSean Christopherson 			 * unsync pages for the same gfn.  While it's possible
2016ddc16abbSSean Christopherson 			 * the guest is using recursive page tables, in all
2017ddc16abbSSean Christopherson 			 * likelihood the guest has stopped using the unsync
2018ddc16abbSSean Christopherson 			 * page and is installing a completely unrelated page.
2019ddc16abbSSean Christopherson 			 * Unsync pages must not be left as is, because the new
2020ddc16abbSSean Christopherson 			 * upper-level page will be write-protected.
2021ddc16abbSSean Christopherson 			 */
20222e65e842SDavid Matlack 			if (role.level > PG_LEVEL_4K && sp->unsync)
2023ddc16abbSSean Christopherson 				kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
2024ddc16abbSSean Christopherson 							 &invalid_list);
2025c50d8ae3SPaolo Bonzini 			continue;
2026ddc16abbSSean Christopherson 		}
2027c50d8ae3SPaolo Bonzini 
2028bb924ca6SDavid Matlack 		/* unsync and write-flooding only apply to indirect SPs. */
2029bb924ca6SDavid Matlack 		if (sp->role.direct)
2030*94c81364SDavid Matlack 			goto out;
2031fb58a9c3SSean Christopherson 
2032c50d8ae3SPaolo Bonzini 		if (sp->unsync) {
203307dc4f35SSean Christopherson 			/*
2034479a1efcSSean Christopherson 			 * The page is good, but is stale.  kvm_sync_page does
203507dc4f35SSean Christopherson 			 * get the latest guest state, but (unlike mmu_unsync_children)
203607dc4f35SSean Christopherson 			 * it doesn't write-protect the page or mark it synchronized!
203707dc4f35SSean Christopherson 			 * This way the validity of the mapping is ensured, but the
203807dc4f35SSean Christopherson 			 * overhead of write protection is not incurred until the
203907dc4f35SSean Christopherson 			 * guest invalidates the TLB mapping.  This allows multiple
204007dc4f35SSean Christopherson 			 * SPs for a single gfn to be unsync.
204107dc4f35SSean Christopherson 			 *
204207dc4f35SSean Christopherson 			 * If the sync fails, the page is zapped.  If so, break
204307dc4f35SSean Christopherson 			 * in order to rebuild it.
2044c50d8ae3SPaolo Bonzini 			 */
20458d5678a7SHou Wenlong 			ret = kvm_sync_page(vcpu, sp, &invalid_list);
20468d5678a7SHou Wenlong 			if (ret < 0)
2047c50d8ae3SPaolo Bonzini 				break;
2048c50d8ae3SPaolo Bonzini 
2049c50d8ae3SPaolo Bonzini 			WARN_ON(!list_empty(&invalid_list));
20508d5678a7SHou Wenlong 			if (ret > 0)
2051c3e5e415SLai Jiangshan 				kvm_flush_remote_tlbs(vcpu->kvm);
2052c50d8ae3SPaolo Bonzini 		}
2053c50d8ae3SPaolo Bonzini 
2054c50d8ae3SPaolo Bonzini 		__clear_sp_write_flooding_count(sp);
2055fb58a9c3SSean Christopherson 
2056c50d8ae3SPaolo Bonzini 		goto out;
2057c50d8ae3SPaolo Bonzini 	}
2058c50d8ae3SPaolo Bonzini 
2059*94c81364SDavid Matlack 	sp = NULL;
2060c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_cache_miss;
2061c50d8ae3SPaolo Bonzini 
2062*94c81364SDavid Matlack out:
2063*94c81364SDavid Matlack 	kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
2064*94c81364SDavid Matlack 
2065*94c81364SDavid Matlack 	if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2066*94c81364SDavid Matlack 		vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2067*94c81364SDavid Matlack 	return sp;
2068*94c81364SDavid Matlack }
2069*94c81364SDavid Matlack 
2070*94c81364SDavid Matlack static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm_vcpu *vcpu,
2071*94c81364SDavid Matlack 						      gfn_t gfn,
2072*94c81364SDavid Matlack 						      struct hlist_head *sp_list,
2073*94c81364SDavid Matlack 						      union kvm_mmu_page_role role)
2074*94c81364SDavid Matlack {
2075*94c81364SDavid Matlack 	struct kvm_mmu_page *sp = kvm_mmu_alloc_page(vcpu, role.direct);
2076c50d8ae3SPaolo Bonzini 
2077c50d8ae3SPaolo Bonzini 	sp->gfn = gfn;
2078c50d8ae3SPaolo Bonzini 	sp->role = role;
2079ac101b7cSSean Christopherson 	hlist_add_head(&sp->hash_link, sp_list);
2080767d8d8dSLai Jiangshan 	if (sp_has_gptes(sp)) {
2081c50d8ae3SPaolo Bonzini 		account_shadowed(vcpu->kvm, sp);
20822e65e842SDavid Matlack 		if (role.level == PG_LEVEL_4K && kvm_vcpu_write_protect_gfn(vcpu, gfn))
2083c50d8ae3SPaolo Bonzini 			kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2084c50d8ae3SPaolo Bonzini 	}
2085ddc16abbSSean Christopherson 
2086*94c81364SDavid Matlack 	return sp;
2087*94c81364SDavid Matlack }
2088*94c81364SDavid Matlack 
2089*94c81364SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2090*94c81364SDavid Matlack 					     union kvm_mmu_page_role role)
2091*94c81364SDavid Matlack {
2092*94c81364SDavid Matlack 	struct hlist_head *sp_list;
2093*94c81364SDavid Matlack 	struct kvm_mmu_page *sp;
2094*94c81364SDavid Matlack 	bool created = false;
2095*94c81364SDavid Matlack 
2096*94c81364SDavid Matlack 	sp_list = &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2097*94c81364SDavid Matlack 
2098*94c81364SDavid Matlack 	sp = kvm_mmu_find_shadow_page(vcpu, gfn, sp_list, role);
2099*94c81364SDavid Matlack 	if (!sp) {
2100*94c81364SDavid Matlack 		created = true;
2101*94c81364SDavid Matlack 		sp = kvm_mmu_alloc_shadow_page(vcpu, gfn, sp_list, role);
2102*94c81364SDavid Matlack 	}
2103*94c81364SDavid Matlack 
2104*94c81364SDavid Matlack 	trace_kvm_mmu_get_page(sp, created);
2105c50d8ae3SPaolo Bonzini 	return sp;
2106c50d8ae3SPaolo Bonzini }
2107c50d8ae3SPaolo Bonzini 
21082e65e842SDavid Matlack static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct, unsigned int access)
21092e65e842SDavid Matlack {
21102e65e842SDavid Matlack 	struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
21112e65e842SDavid Matlack 	union kvm_mmu_page_role role;
21122e65e842SDavid Matlack 
21132e65e842SDavid Matlack 	role = parent_sp->role;
21142e65e842SDavid Matlack 	role.level--;
21152e65e842SDavid Matlack 	role.access = access;
21162e65e842SDavid Matlack 	role.direct = direct;
21172e65e842SDavid Matlack 	role.passthrough = 0;
21182e65e842SDavid Matlack 
21192e65e842SDavid Matlack 	/*
21202e65e842SDavid Matlack 	 * If the guest has 4-byte PTEs then that means it's using 32-bit,
21212e65e842SDavid Matlack 	 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
21222e65e842SDavid Matlack 	 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
21232e65e842SDavid Matlack 	 * shadow each guest page table with multiple shadow page tables, which
21242e65e842SDavid Matlack 	 * requires extra bookkeeping in the role.
21252e65e842SDavid Matlack 	 *
21262e65e842SDavid Matlack 	 * Specifically, to shadow the guest's page directory (which covers a
21272e65e842SDavid Matlack 	 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
21282e65e842SDavid Matlack 	 * 1GiB of the address space. @role.quadrant encodes which quarter of
21292e65e842SDavid Matlack 	 * the address space each maps.
21302e65e842SDavid Matlack 	 *
21312e65e842SDavid Matlack 	 * To shadow the guest's page tables (which each map a 4MiB region), KVM
21322e65e842SDavid Matlack 	 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
21332e65e842SDavid Matlack 	 * @role.quadrant encodes which half of the region they map.
21342e65e842SDavid Matlack 	 *
21352e65e842SDavid Matlack 	 * Note, the 4 PAE page directories are pre-allocated and the quadrant
21362e65e842SDavid Matlack 	 * assigned in mmu_alloc_root(). So only page tables need to be handled
21372e65e842SDavid Matlack 	 * here.
21382e65e842SDavid Matlack 	 */
21392e65e842SDavid Matlack 	if (role.has_4_byte_gpte) {
21402e65e842SDavid Matlack 		WARN_ON_ONCE(role.level != PG_LEVEL_4K);
21412e65e842SDavid Matlack 		role.quadrant = (sptep - parent_sp->spt) % 2;
21422e65e842SDavid Matlack 	}
21432e65e842SDavid Matlack 
21442e65e842SDavid Matlack 	return role;
21452e65e842SDavid Matlack }
21462e65e842SDavid Matlack 
21472e65e842SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
21482e65e842SDavid Matlack 						 u64 *sptep, gfn_t gfn,
21492e65e842SDavid Matlack 						 bool direct, unsigned int access)
21502e65e842SDavid Matlack {
21512e65e842SDavid Matlack 	union kvm_mmu_page_role role;
21522e65e842SDavid Matlack 
21532e65e842SDavid Matlack 	role = kvm_mmu_child_role(sptep, direct, access);
21542e65e842SDavid Matlack 	return kvm_mmu_get_page(vcpu, gfn, role);
21552e65e842SDavid Matlack }
21562e65e842SDavid Matlack 
2157c50d8ae3SPaolo Bonzini static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2158c50d8ae3SPaolo Bonzini 					struct kvm_vcpu *vcpu, hpa_t root,
2159c50d8ae3SPaolo Bonzini 					u64 addr)
2160c50d8ae3SPaolo Bonzini {
2161c50d8ae3SPaolo Bonzini 	iterator->addr = addr;
2162c50d8ae3SPaolo Bonzini 	iterator->shadow_addr = root;
2163a972e29cSPaolo Bonzini 	iterator->level = vcpu->arch.mmu->root_role.level;
2164c50d8ae3SPaolo Bonzini 
216512ec33a7SLai Jiangshan 	if (iterator->level >= PT64_ROOT_4LEVEL &&
21664d25502aSPaolo Bonzini 	    vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2167347a0d0dSPaolo Bonzini 	    !vcpu->arch.mmu->root_role.direct)
216812ec33a7SLai Jiangshan 		iterator->level = PT32E_ROOT_LEVEL;
2169c50d8ae3SPaolo Bonzini 
2170c50d8ae3SPaolo Bonzini 	if (iterator->level == PT32E_ROOT_LEVEL) {
2171c50d8ae3SPaolo Bonzini 		/*
2172c50d8ae3SPaolo Bonzini 		 * prev_root is currently only used for 64-bit hosts. So only
2173c50d8ae3SPaolo Bonzini 		 * the active root_hpa is valid here.
2174c50d8ae3SPaolo Bonzini 		 */
2175b9e5603cSPaolo Bonzini 		BUG_ON(root != vcpu->arch.mmu->root.hpa);
2176c50d8ae3SPaolo Bonzini 
2177c50d8ae3SPaolo Bonzini 		iterator->shadow_addr
2178c50d8ae3SPaolo Bonzini 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
21792ca3129eSSean Christopherson 		iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2180c50d8ae3SPaolo Bonzini 		--iterator->level;
2181c50d8ae3SPaolo Bonzini 		if (!iterator->shadow_addr)
2182c50d8ae3SPaolo Bonzini 			iterator->level = 0;
2183c50d8ae3SPaolo Bonzini 	}
2184c50d8ae3SPaolo Bonzini }
2185c50d8ae3SPaolo Bonzini 
2186c50d8ae3SPaolo Bonzini static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2187c50d8ae3SPaolo Bonzini 			     struct kvm_vcpu *vcpu, u64 addr)
2188c50d8ae3SPaolo Bonzini {
2189b9e5603cSPaolo Bonzini 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2190c50d8ae3SPaolo Bonzini 				    addr);
2191c50d8ae3SPaolo Bonzini }
2192c50d8ae3SPaolo Bonzini 
2193c50d8ae3SPaolo Bonzini static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2194c50d8ae3SPaolo Bonzini {
21953bae0459SSean Christopherson 	if (iterator->level < PG_LEVEL_4K)
2196c50d8ae3SPaolo Bonzini 		return false;
2197c50d8ae3SPaolo Bonzini 
21982ca3129eSSean Christopherson 	iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2199c50d8ae3SPaolo Bonzini 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2200c50d8ae3SPaolo Bonzini 	return true;
2201c50d8ae3SPaolo Bonzini }
2202c50d8ae3SPaolo Bonzini 
2203c50d8ae3SPaolo Bonzini static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2204c50d8ae3SPaolo Bonzini 			       u64 spte)
2205c50d8ae3SPaolo Bonzini {
22063e44dce4SLai Jiangshan 	if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2207c50d8ae3SPaolo Bonzini 		iterator->level = 0;
2208c50d8ae3SPaolo Bonzini 		return;
2209c50d8ae3SPaolo Bonzini 	}
2210c50d8ae3SPaolo Bonzini 
22112ca3129eSSean Christopherson 	iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2212c50d8ae3SPaolo Bonzini 	--iterator->level;
2213c50d8ae3SPaolo Bonzini }
2214c50d8ae3SPaolo Bonzini 
2215c50d8ae3SPaolo Bonzini static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2216c50d8ae3SPaolo Bonzini {
2217c50d8ae3SPaolo Bonzini 	__shadow_walk_next(iterator, *iterator->sptep);
2218c50d8ae3SPaolo Bonzini }
2219c50d8ae3SPaolo Bonzini 
2220c50d8ae3SPaolo Bonzini static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2221c50d8ae3SPaolo Bonzini 			     struct kvm_mmu_page *sp)
2222c50d8ae3SPaolo Bonzini {
2223c50d8ae3SPaolo Bonzini 	u64 spte;
2224c50d8ae3SPaolo Bonzini 
2225c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2226c50d8ae3SPaolo Bonzini 
2227cc4674d0SBen Gardon 	spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2228c50d8ae3SPaolo Bonzini 
2229c50d8ae3SPaolo Bonzini 	mmu_spte_set(sptep, spte);
2230c50d8ae3SPaolo Bonzini 
2231c50d8ae3SPaolo Bonzini 	mmu_page_add_parent_pte(vcpu, sp, sptep);
2232c50d8ae3SPaolo Bonzini 
2233c50d8ae3SPaolo Bonzini 	if (sp->unsync_children || sp->unsync)
2234c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
2235c50d8ae3SPaolo Bonzini }
2236c50d8ae3SPaolo Bonzini 
2237c50d8ae3SPaolo Bonzini static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2238c50d8ae3SPaolo Bonzini 				   unsigned direct_access)
2239c50d8ae3SPaolo Bonzini {
2240c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2241c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
2242c50d8ae3SPaolo Bonzini 
2243c50d8ae3SPaolo Bonzini 		/*
2244c50d8ae3SPaolo Bonzini 		 * For the direct sp, if the guest pte's dirty bit
2245c50d8ae3SPaolo Bonzini 		 * changed form clean to dirty, it will corrupt the
2246c50d8ae3SPaolo Bonzini 		 * sp's access: allow writable in the read-only sp,
2247c50d8ae3SPaolo Bonzini 		 * so we should update the spte at this point to get
2248c50d8ae3SPaolo Bonzini 		 * a new sp with the correct access.
2249c50d8ae3SPaolo Bonzini 		 */
22502ca3129eSSean Christopherson 		child = to_shadow_page(*sptep & SPTE_BASE_ADDR_MASK);
2251c50d8ae3SPaolo Bonzini 		if (child->role.access == direct_access)
2252c50d8ae3SPaolo Bonzini 			return;
2253c50d8ae3SPaolo Bonzini 
2254c50d8ae3SPaolo Bonzini 		drop_parent_pte(child, sptep);
2255c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2256c50d8ae3SPaolo Bonzini 	}
2257c50d8ae3SPaolo Bonzini }
2258c50d8ae3SPaolo Bonzini 
22592de4085cSBen Gardon /* Returns the number of zapped non-leaf child shadow pages. */
22602de4085cSBen Gardon static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
22612de4085cSBen Gardon 			    u64 *spte, struct list_head *invalid_list)
2262c50d8ae3SPaolo Bonzini {
2263c50d8ae3SPaolo Bonzini 	u64 pte;
2264c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *child;
2265c50d8ae3SPaolo Bonzini 
2266c50d8ae3SPaolo Bonzini 	pte = *spte;
2267c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(pte)) {
2268c50d8ae3SPaolo Bonzini 		if (is_last_spte(pte, sp->role.level)) {
2269c50d8ae3SPaolo Bonzini 			drop_spte(kvm, spte);
2270c50d8ae3SPaolo Bonzini 		} else {
22712ca3129eSSean Christopherson 			child = to_shadow_page(pte & SPTE_BASE_ADDR_MASK);
2272c50d8ae3SPaolo Bonzini 			drop_parent_pte(child, spte);
22732de4085cSBen Gardon 
22742de4085cSBen Gardon 			/*
22752de4085cSBen Gardon 			 * Recursively zap nested TDP SPs, parentless SPs are
22762de4085cSBen Gardon 			 * unlikely to be used again in the near future.  This
22772de4085cSBen Gardon 			 * avoids retaining a large number of stale nested SPs.
22782de4085cSBen Gardon 			 */
22792de4085cSBen Gardon 			if (tdp_enabled && invalid_list &&
22802de4085cSBen Gardon 			    child->role.guest_mode && !child->parent_ptes.val)
22812de4085cSBen Gardon 				return kvm_mmu_prepare_zap_page(kvm, child,
22822de4085cSBen Gardon 								invalid_list);
2283c50d8ae3SPaolo Bonzini 		}
2284ace569e0SSean Christopherson 	} else if (is_mmio_spte(pte)) {
2285c50d8ae3SPaolo Bonzini 		mmu_spte_clear_no_track(spte);
2286ace569e0SSean Christopherson 	}
22872de4085cSBen Gardon 	return 0;
2288c50d8ae3SPaolo Bonzini }
2289c50d8ae3SPaolo Bonzini 
22902de4085cSBen Gardon static int kvm_mmu_page_unlink_children(struct kvm *kvm,
22912de4085cSBen Gardon 					struct kvm_mmu_page *sp,
22922de4085cSBen Gardon 					struct list_head *invalid_list)
2293c50d8ae3SPaolo Bonzini {
22942de4085cSBen Gardon 	int zapped = 0;
2295c50d8ae3SPaolo Bonzini 	unsigned i;
2296c50d8ae3SPaolo Bonzini 
22972ca3129eSSean Christopherson 	for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
22982de4085cSBen Gardon 		zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
22992de4085cSBen Gardon 
23002de4085cSBen Gardon 	return zapped;
2301c50d8ae3SPaolo Bonzini }
2302c50d8ae3SPaolo Bonzini 
230361827671SJinrong Liang static void kvm_mmu_unlink_parents(struct kvm_mmu_page *sp)
2304c50d8ae3SPaolo Bonzini {
2305c50d8ae3SPaolo Bonzini 	u64 *sptep;
2306c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
2307c50d8ae3SPaolo Bonzini 
2308c50d8ae3SPaolo Bonzini 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2309c50d8ae3SPaolo Bonzini 		drop_parent_pte(sp, sptep);
2310c50d8ae3SPaolo Bonzini }
2311c50d8ae3SPaolo Bonzini 
2312c50d8ae3SPaolo Bonzini static int mmu_zap_unsync_children(struct kvm *kvm,
2313c50d8ae3SPaolo Bonzini 				   struct kvm_mmu_page *parent,
2314c50d8ae3SPaolo Bonzini 				   struct list_head *invalid_list)
2315c50d8ae3SPaolo Bonzini {
2316c50d8ae3SPaolo Bonzini 	int i, zapped = 0;
2317c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2318c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2319c50d8ae3SPaolo Bonzini 
23203bae0459SSean Christopherson 	if (parent->role.level == PG_LEVEL_4K)
2321c50d8ae3SPaolo Bonzini 		return 0;
2322c50d8ae3SPaolo Bonzini 
2323c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2324c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
2325c50d8ae3SPaolo Bonzini 
2326c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2327c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2328c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2329c50d8ae3SPaolo Bonzini 			zapped++;
2330c50d8ae3SPaolo Bonzini 		}
2331c50d8ae3SPaolo Bonzini 	}
2332c50d8ae3SPaolo Bonzini 
2333c50d8ae3SPaolo Bonzini 	return zapped;
2334c50d8ae3SPaolo Bonzini }
2335c50d8ae3SPaolo Bonzini 
2336c50d8ae3SPaolo Bonzini static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2337c50d8ae3SPaolo Bonzini 				       struct kvm_mmu_page *sp,
2338c50d8ae3SPaolo Bonzini 				       struct list_head *invalid_list,
2339c50d8ae3SPaolo Bonzini 				       int *nr_zapped)
2340c50d8ae3SPaolo Bonzini {
2341527d5cd7SSean Christopherson 	bool list_unstable, zapped_root = false;
2342c50d8ae3SPaolo Bonzini 
2343c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_prepare_zap_page(sp);
2344c50d8ae3SPaolo Bonzini 	++kvm->stat.mmu_shadow_zapped;
2345c50d8ae3SPaolo Bonzini 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
23462de4085cSBen Gardon 	*nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
234761827671SJinrong Liang 	kvm_mmu_unlink_parents(sp);
2348c50d8ae3SPaolo Bonzini 
2349c50d8ae3SPaolo Bonzini 	/* Zapping children means active_mmu_pages has become unstable. */
2350c50d8ae3SPaolo Bonzini 	list_unstable = *nr_zapped;
2351c50d8ae3SPaolo Bonzini 
2352767d8d8dSLai Jiangshan 	if (!sp->role.invalid && sp_has_gptes(sp))
2353c50d8ae3SPaolo Bonzini 		unaccount_shadowed(kvm, sp);
2354c50d8ae3SPaolo Bonzini 
2355c50d8ae3SPaolo Bonzini 	if (sp->unsync)
2356c50d8ae3SPaolo Bonzini 		kvm_unlink_unsync_page(kvm, sp);
2357c50d8ae3SPaolo Bonzini 	if (!sp->root_count) {
2358c50d8ae3SPaolo Bonzini 		/* Count self */
2359c50d8ae3SPaolo Bonzini 		(*nr_zapped)++;
2360f95eec9bSSean Christopherson 
2361f95eec9bSSean Christopherson 		/*
2362f95eec9bSSean Christopherson 		 * Already invalid pages (previously active roots) are not on
2363f95eec9bSSean Christopherson 		 * the active page list.  See list_del() in the "else" case of
2364f95eec9bSSean Christopherson 		 * !sp->root_count.
2365f95eec9bSSean Christopherson 		 */
2366f95eec9bSSean Christopherson 		if (sp->role.invalid)
2367f95eec9bSSean Christopherson 			list_add(&sp->link, invalid_list);
2368f95eec9bSSean Christopherson 		else
2369c50d8ae3SPaolo Bonzini 			list_move(&sp->link, invalid_list);
2370c50d8ae3SPaolo Bonzini 		kvm_mod_used_mmu_pages(kvm, -1);
2371c50d8ae3SPaolo Bonzini 	} else {
2372f95eec9bSSean Christopherson 		/*
2373f95eec9bSSean Christopherson 		 * Remove the active root from the active page list, the root
2374f95eec9bSSean Christopherson 		 * will be explicitly freed when the root_count hits zero.
2375f95eec9bSSean Christopherson 		 */
2376f95eec9bSSean Christopherson 		list_del(&sp->link);
2377c50d8ae3SPaolo Bonzini 
2378c50d8ae3SPaolo Bonzini 		/*
2379c50d8ae3SPaolo Bonzini 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2380c50d8ae3SPaolo Bonzini 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2381c50d8ae3SPaolo Bonzini 		 * treats invalid shadow pages as being obsolete.
2382c50d8ae3SPaolo Bonzini 		 */
2383527d5cd7SSean Christopherson 		zapped_root = !is_obsolete_sp(kvm, sp);
2384c50d8ae3SPaolo Bonzini 	}
2385c50d8ae3SPaolo Bonzini 
2386c50d8ae3SPaolo Bonzini 	if (sp->lpage_disallowed)
2387c50d8ae3SPaolo Bonzini 		unaccount_huge_nx_page(kvm, sp);
2388c50d8ae3SPaolo Bonzini 
2389c50d8ae3SPaolo Bonzini 	sp->role.invalid = 1;
2390527d5cd7SSean Christopherson 
2391527d5cd7SSean Christopherson 	/*
2392527d5cd7SSean Christopherson 	 * Make the request to free obsolete roots after marking the root
2393527d5cd7SSean Christopherson 	 * invalid, otherwise other vCPUs may not see it as invalid.
2394527d5cd7SSean Christopherson 	 */
2395527d5cd7SSean Christopherson 	if (zapped_root)
2396527d5cd7SSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2397c50d8ae3SPaolo Bonzini 	return list_unstable;
2398c50d8ae3SPaolo Bonzini }
2399c50d8ae3SPaolo Bonzini 
2400c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2401c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list)
2402c50d8ae3SPaolo Bonzini {
2403c50d8ae3SPaolo Bonzini 	int nr_zapped;
2404c50d8ae3SPaolo Bonzini 
2405c50d8ae3SPaolo Bonzini 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2406c50d8ae3SPaolo Bonzini 	return nr_zapped;
2407c50d8ae3SPaolo Bonzini }
2408c50d8ae3SPaolo Bonzini 
2409c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2410c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list)
2411c50d8ae3SPaolo Bonzini {
2412c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *nsp;
2413c50d8ae3SPaolo Bonzini 
2414c50d8ae3SPaolo Bonzini 	if (list_empty(invalid_list))
2415c50d8ae3SPaolo Bonzini 		return;
2416c50d8ae3SPaolo Bonzini 
2417c50d8ae3SPaolo Bonzini 	/*
2418c50d8ae3SPaolo Bonzini 	 * We need to make sure everyone sees our modifications to
2419c50d8ae3SPaolo Bonzini 	 * the page tables and see changes to vcpu->mode here. The barrier
2420c50d8ae3SPaolo Bonzini 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2421c50d8ae3SPaolo Bonzini 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2422c50d8ae3SPaolo Bonzini 	 *
2423c50d8ae3SPaolo Bonzini 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2424c50d8ae3SPaolo Bonzini 	 * guest mode and/or lockless shadow page table walks.
2425c50d8ae3SPaolo Bonzini 	 */
2426c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs(kvm);
2427c50d8ae3SPaolo Bonzini 
2428c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2429c50d8ae3SPaolo Bonzini 		WARN_ON(!sp->role.invalid || sp->root_count);
2430c50d8ae3SPaolo Bonzini 		kvm_mmu_free_page(sp);
2431c50d8ae3SPaolo Bonzini 	}
2432c50d8ae3SPaolo Bonzini }
2433c50d8ae3SPaolo Bonzini 
24346b82ef2cSSean Christopherson static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
24356b82ef2cSSean Christopherson 						  unsigned long nr_to_zap)
2436c50d8ae3SPaolo Bonzini {
24376b82ef2cSSean Christopherson 	unsigned long total_zapped = 0;
24386b82ef2cSSean Christopherson 	struct kvm_mmu_page *sp, *tmp;
2439ba7888ddSSean Christopherson 	LIST_HEAD(invalid_list);
24406b82ef2cSSean Christopherson 	bool unstable;
24416b82ef2cSSean Christopherson 	int nr_zapped;
2442c50d8ae3SPaolo Bonzini 
2443c50d8ae3SPaolo Bonzini 	if (list_empty(&kvm->arch.active_mmu_pages))
2444ba7888ddSSean Christopherson 		return 0;
2445c50d8ae3SPaolo Bonzini 
24466b82ef2cSSean Christopherson restart:
24478fc51726SSean Christopherson 	list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
24486b82ef2cSSean Christopherson 		/*
24496b82ef2cSSean Christopherson 		 * Don't zap active root pages, the page itself can't be freed
24506b82ef2cSSean Christopherson 		 * and zapping it will just force vCPUs to realloc and reload.
24516b82ef2cSSean Christopherson 		 */
24526b82ef2cSSean Christopherson 		if (sp->root_count)
24536b82ef2cSSean Christopherson 			continue;
24546b82ef2cSSean Christopherson 
24556b82ef2cSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
24566b82ef2cSSean Christopherson 						      &nr_zapped);
24576b82ef2cSSean Christopherson 		total_zapped += nr_zapped;
24586b82ef2cSSean Christopherson 		if (total_zapped >= nr_to_zap)
2459ba7888ddSSean Christopherson 			break;
2460ba7888ddSSean Christopherson 
24616b82ef2cSSean Christopherson 		if (unstable)
24626b82ef2cSSean Christopherson 			goto restart;
2463ba7888ddSSean Christopherson 	}
24646b82ef2cSSean Christopherson 
24656b82ef2cSSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
24666b82ef2cSSean Christopherson 
24676b82ef2cSSean Christopherson 	kvm->stat.mmu_recycled += total_zapped;
24686b82ef2cSSean Christopherson 	return total_zapped;
24696b82ef2cSSean Christopherson }
24706b82ef2cSSean Christopherson 
2471afe8d7e6SSean Christopherson static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2472afe8d7e6SSean Christopherson {
2473afe8d7e6SSean Christopherson 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2474afe8d7e6SSean Christopherson 		return kvm->arch.n_max_mmu_pages -
2475afe8d7e6SSean Christopherson 			kvm->arch.n_used_mmu_pages;
2476afe8d7e6SSean Christopherson 
2477afe8d7e6SSean Christopherson 	return 0;
2478c50d8ae3SPaolo Bonzini }
2479c50d8ae3SPaolo Bonzini 
2480ba7888ddSSean Christopherson static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2481ba7888ddSSean Christopherson {
24826b82ef2cSSean Christopherson 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2483ba7888ddSSean Christopherson 
24846b82ef2cSSean Christopherson 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2485ba7888ddSSean Christopherson 		return 0;
2486ba7888ddSSean Christopherson 
24876b82ef2cSSean Christopherson 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2488ba7888ddSSean Christopherson 
24896e6ec584SSean Christopherson 	/*
24906e6ec584SSean Christopherson 	 * Note, this check is intentionally soft, it only guarantees that one
24916e6ec584SSean Christopherson 	 * page is available, while the caller may end up allocating as many as
24926e6ec584SSean Christopherson 	 * four pages, e.g. for PAE roots or for 5-level paging.  Temporarily
24936e6ec584SSean Christopherson 	 * exceeding the (arbitrary by default) limit will not harm the host,
2494c4342633SIngo Molnar 	 * being too aggressive may unnecessarily kill the guest, and getting an
24956e6ec584SSean Christopherson 	 * exact count is far more trouble than it's worth, especially in the
24966e6ec584SSean Christopherson 	 * page fault paths.
24976e6ec584SSean Christopherson 	 */
2498ba7888ddSSean Christopherson 	if (!kvm_mmu_available_pages(vcpu->kvm))
2499ba7888ddSSean Christopherson 		return -ENOSPC;
2500ba7888ddSSean Christopherson 	return 0;
2501ba7888ddSSean Christopherson }
2502ba7888ddSSean Christopherson 
2503c50d8ae3SPaolo Bonzini /*
2504c50d8ae3SPaolo Bonzini  * Changing the number of mmu pages allocated to the vm
2505c50d8ae3SPaolo Bonzini  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2506c50d8ae3SPaolo Bonzini  */
2507c50d8ae3SPaolo Bonzini void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2508c50d8ae3SPaolo Bonzini {
2509531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2510c50d8ae3SPaolo Bonzini 
2511c50d8ae3SPaolo Bonzini 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
25126b82ef2cSSean Christopherson 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
25136b82ef2cSSean Christopherson 						  goal_nr_mmu_pages);
2514c50d8ae3SPaolo Bonzini 
2515c50d8ae3SPaolo Bonzini 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2516c50d8ae3SPaolo Bonzini 	}
2517c50d8ae3SPaolo Bonzini 
2518c50d8ae3SPaolo Bonzini 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2519c50d8ae3SPaolo Bonzini 
2520531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2521c50d8ae3SPaolo Bonzini }
2522c50d8ae3SPaolo Bonzini 
2523c50d8ae3SPaolo Bonzini int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2524c50d8ae3SPaolo Bonzini {
2525c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2526c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2527c50d8ae3SPaolo Bonzini 	int r;
2528c50d8ae3SPaolo Bonzini 
2529c50d8ae3SPaolo Bonzini 	pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2530c50d8ae3SPaolo Bonzini 	r = 0;
2531531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2532767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2533c50d8ae3SPaolo Bonzini 		pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2534c50d8ae3SPaolo Bonzini 			 sp->role.word);
2535c50d8ae3SPaolo Bonzini 		r = 1;
2536c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2537c50d8ae3SPaolo Bonzini 	}
2538c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2539531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2540c50d8ae3SPaolo Bonzini 
2541c50d8ae3SPaolo Bonzini 	return r;
2542c50d8ae3SPaolo Bonzini }
254396ad91aeSSean Christopherson 
254496ad91aeSSean Christopherson static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
254596ad91aeSSean Christopherson {
254696ad91aeSSean Christopherson 	gpa_t gpa;
254796ad91aeSSean Christopherson 	int r;
254896ad91aeSSean Christopherson 
2549347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
255096ad91aeSSean Christopherson 		return 0;
255196ad91aeSSean Christopherson 
255296ad91aeSSean Christopherson 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
255396ad91aeSSean Christopherson 
255496ad91aeSSean Christopherson 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
255596ad91aeSSean Christopherson 
255696ad91aeSSean Christopherson 	return r;
255796ad91aeSSean Christopherson }
2558c50d8ae3SPaolo Bonzini 
25594d78d0b3SBen Gardon static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2560c50d8ae3SPaolo Bonzini {
2561c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_unsync_page(sp);
25624d78d0b3SBen Gardon 	++kvm->stat.mmu_unsync;
2563c50d8ae3SPaolo Bonzini 	sp->unsync = 1;
2564c50d8ae3SPaolo Bonzini 
2565c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
2566c50d8ae3SPaolo Bonzini }
2567c50d8ae3SPaolo Bonzini 
25680337f585SSean Christopherson /*
25690337f585SSean Christopherson  * Attempt to unsync any shadow pages that can be reached by the specified gfn,
25700337f585SSean Christopherson  * KVM is creating a writable mapping for said gfn.  Returns 0 if all pages
25710337f585SSean Christopherson  * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
25720337f585SSean Christopherson  * be write-protected.
25730337f585SSean Christopherson  */
25748283e36aSBen Gardon int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
25752839180cSPaolo Bonzini 			    gfn_t gfn, bool can_unsync, bool prefetch)
2576c50d8ae3SPaolo Bonzini {
2577c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2578ce25681dSSean Christopherson 	bool locked = false;
2579c50d8ae3SPaolo Bonzini 
25800337f585SSean Christopherson 	/*
25810337f585SSean Christopherson 	 * Force write-protection if the page is being tracked.  Note, the page
25820337f585SSean Christopherson 	 * track machinery is used to write-protect upper-level shadow pages,
25830337f585SSean Christopherson 	 * i.e. this guards the role.level == 4K assertion below!
25840337f585SSean Christopherson 	 */
25854d78d0b3SBen Gardon 	if (kvm_slot_page_track_is_active(kvm, slot, gfn, KVM_PAGE_TRACK_WRITE))
25860337f585SSean Christopherson 		return -EPERM;
2587c50d8ae3SPaolo Bonzini 
25880337f585SSean Christopherson 	/*
25890337f585SSean Christopherson 	 * The page is not write-tracked, mark existing shadow pages unsync
25900337f585SSean Christopherson 	 * unless KVM is synchronizing an unsync SP (can_unsync = false).  In
25910337f585SSean Christopherson 	 * that case, KVM must complete emulation of the guest TLB flush before
25920337f585SSean Christopherson 	 * allowing shadow pages to become unsync (writable by the guest).
25930337f585SSean Christopherson 	 */
2594767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2595c50d8ae3SPaolo Bonzini 		if (!can_unsync)
25960337f585SSean Christopherson 			return -EPERM;
2597c50d8ae3SPaolo Bonzini 
2598c50d8ae3SPaolo Bonzini 		if (sp->unsync)
2599c50d8ae3SPaolo Bonzini 			continue;
2600c50d8ae3SPaolo Bonzini 
26012839180cSPaolo Bonzini 		if (prefetch)
2602f1c4a88cSLai Jiangshan 			return -EEXIST;
2603f1c4a88cSLai Jiangshan 
2604ce25681dSSean Christopherson 		/*
2605ce25681dSSean Christopherson 		 * TDP MMU page faults require an additional spinlock as they
2606ce25681dSSean Christopherson 		 * run with mmu_lock held for read, not write, and the unsync
2607ce25681dSSean Christopherson 		 * logic is not thread safe.  Take the spinklock regardless of
2608ce25681dSSean Christopherson 		 * the MMU type to avoid extra conditionals/parameters, there's
2609ce25681dSSean Christopherson 		 * no meaningful penalty if mmu_lock is held for write.
2610ce25681dSSean Christopherson 		 */
2611ce25681dSSean Christopherson 		if (!locked) {
2612ce25681dSSean Christopherson 			locked = true;
26134d78d0b3SBen Gardon 			spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2614ce25681dSSean Christopherson 
2615ce25681dSSean Christopherson 			/*
2616ce25681dSSean Christopherson 			 * Recheck after taking the spinlock, a different vCPU
2617ce25681dSSean Christopherson 			 * may have since marked the page unsync.  A false
2618ce25681dSSean Christopherson 			 * positive on the unprotected check above is not
2619ce25681dSSean Christopherson 			 * possible as clearing sp->unsync _must_ hold mmu_lock
2620ce25681dSSean Christopherson 			 * for write, i.e. unsync cannot transition from 0->1
2621ce25681dSSean Christopherson 			 * while this CPU holds mmu_lock for read (or write).
2622ce25681dSSean Christopherson 			 */
2623ce25681dSSean Christopherson 			if (READ_ONCE(sp->unsync))
2624ce25681dSSean Christopherson 				continue;
2625ce25681dSSean Christopherson 		}
2626ce25681dSSean Christopherson 
26273bae0459SSean Christopherson 		WARN_ON(sp->role.level != PG_LEVEL_4K);
26284d78d0b3SBen Gardon 		kvm_unsync_page(kvm, sp);
2629c50d8ae3SPaolo Bonzini 	}
2630ce25681dSSean Christopherson 	if (locked)
26314d78d0b3SBen Gardon 		spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2632c50d8ae3SPaolo Bonzini 
2633c50d8ae3SPaolo Bonzini 	/*
2634c50d8ae3SPaolo Bonzini 	 * We need to ensure that the marking of unsync pages is visible
2635c50d8ae3SPaolo Bonzini 	 * before the SPTE is updated to allow writes because
2636c50d8ae3SPaolo Bonzini 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2637c50d8ae3SPaolo Bonzini 	 * the MMU lock and so can race with this. If the SPTE was updated
2638c50d8ae3SPaolo Bonzini 	 * before the page had been marked as unsync-ed, something like the
2639c50d8ae3SPaolo Bonzini 	 * following could happen:
2640c50d8ae3SPaolo Bonzini 	 *
2641c50d8ae3SPaolo Bonzini 	 * CPU 1                    CPU 2
2642c50d8ae3SPaolo Bonzini 	 * ---------------------------------------------------------------------
2643c50d8ae3SPaolo Bonzini 	 * 1.2 Host updates SPTE
2644c50d8ae3SPaolo Bonzini 	 *     to be writable
2645c50d8ae3SPaolo Bonzini 	 *                      2.1 Guest writes a GPTE for GVA X.
2646c50d8ae3SPaolo Bonzini 	 *                          (GPTE being in the guest page table shadowed
2647c50d8ae3SPaolo Bonzini 	 *                           by the SP from CPU 1.)
2648c50d8ae3SPaolo Bonzini 	 *                          This reads SPTE during the page table walk.
2649c50d8ae3SPaolo Bonzini 	 *                          Since SPTE.W is read as 1, there is no
2650c50d8ae3SPaolo Bonzini 	 *                          fault.
2651c50d8ae3SPaolo Bonzini 	 *
2652c50d8ae3SPaolo Bonzini 	 *                      2.2 Guest issues TLB flush.
2653c50d8ae3SPaolo Bonzini 	 *                          That causes a VM Exit.
2654c50d8ae3SPaolo Bonzini 	 *
26550337f585SSean Christopherson 	 *                      2.3 Walking of unsync pages sees sp->unsync is
26560337f585SSean Christopherson 	 *                          false and skips the page.
2657c50d8ae3SPaolo Bonzini 	 *
2658c50d8ae3SPaolo Bonzini 	 *                      2.4 Guest accesses GVA X.
2659c50d8ae3SPaolo Bonzini 	 *                          Since the mapping in the SP was not updated,
2660c50d8ae3SPaolo Bonzini 	 *                          so the old mapping for GVA X incorrectly
2661c50d8ae3SPaolo Bonzini 	 *                          gets used.
2662c50d8ae3SPaolo Bonzini 	 * 1.1 Host marks SP
2663c50d8ae3SPaolo Bonzini 	 *     as unsync
2664c50d8ae3SPaolo Bonzini 	 *     (sp->unsync = true)
2665c50d8ae3SPaolo Bonzini 	 *
2666c50d8ae3SPaolo Bonzini 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2667264d3dc1SLai Jiangshan 	 * the situation in 2.4 does not arise.  It pairs with the read barrier
2668264d3dc1SLai Jiangshan 	 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2669c50d8ae3SPaolo Bonzini 	 */
2670c50d8ae3SPaolo Bonzini 	smp_wmb();
2671c50d8ae3SPaolo Bonzini 
26720337f585SSean Christopherson 	return 0;
2673c50d8ae3SPaolo Bonzini }
2674c50d8ae3SPaolo Bonzini 
26758a9f566aSDavid Matlack static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
26768a9f566aSDavid Matlack 			u64 *sptep, unsigned int pte_access, gfn_t gfn,
2677a12f4381SPaolo Bonzini 			kvm_pfn_t pfn, struct kvm_page_fault *fault)
2678799a4190SBen Gardon {
2679d786c778SPaolo Bonzini 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2680eb5cd7ffSPaolo Bonzini 	int level = sp->role.level;
2681c50d8ae3SPaolo Bonzini 	int was_rmapped = 0;
2682c4371c2aSSean Christopherson 	int ret = RET_PF_FIXED;
2683c50d8ae3SPaolo Bonzini 	bool flush = false;
2684ad67e480SPaolo Bonzini 	bool wrprot;
2685d786c778SPaolo Bonzini 	u64 spte;
2686c50d8ae3SPaolo Bonzini 
2687a12f4381SPaolo Bonzini 	/* Prefetching always gets a writable pfn.  */
2688a12f4381SPaolo Bonzini 	bool host_writable = !fault || fault->map_writable;
26892839180cSPaolo Bonzini 	bool prefetch = !fault || fault->prefetch;
2690a12f4381SPaolo Bonzini 	bool write_fault = fault && fault->write;
2691c50d8ae3SPaolo Bonzini 
2692c50d8ae3SPaolo Bonzini 	pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2693c50d8ae3SPaolo Bonzini 		 *sptep, write_fault, gfn);
2694c50d8ae3SPaolo Bonzini 
2695a54aa15cSSean Christopherson 	if (unlikely(is_noslot_pfn(pfn))) {
26961075d41eSSean Christopherson 		vcpu->stat.pf_mmio_spte_created++;
2697a54aa15cSSean Christopherson 		mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2698a54aa15cSSean Christopherson 		return RET_PF_EMULATE;
2699a54aa15cSSean Christopherson 	}
2700a54aa15cSSean Christopherson 
2701c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep)) {
2702c50d8ae3SPaolo Bonzini 		/*
2703c50d8ae3SPaolo Bonzini 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2704c50d8ae3SPaolo Bonzini 		 * the parent of the now unreachable PTE.
2705c50d8ae3SPaolo Bonzini 		 */
27063bae0459SSean Christopherson 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2707c50d8ae3SPaolo Bonzini 			struct kvm_mmu_page *child;
2708c50d8ae3SPaolo Bonzini 			u64 pte = *sptep;
2709c50d8ae3SPaolo Bonzini 
27102ca3129eSSean Christopherson 			child = to_shadow_page(pte & SPTE_BASE_ADDR_MASK);
2711c50d8ae3SPaolo Bonzini 			drop_parent_pte(child, sptep);
2712c50d8ae3SPaolo Bonzini 			flush = true;
2713c50d8ae3SPaolo Bonzini 		} else if (pfn != spte_to_pfn(*sptep)) {
2714c50d8ae3SPaolo Bonzini 			pgprintk("hfn old %llx new %llx\n",
2715c50d8ae3SPaolo Bonzini 				 spte_to_pfn(*sptep), pfn);
2716c50d8ae3SPaolo Bonzini 			drop_spte(vcpu->kvm, sptep);
2717c50d8ae3SPaolo Bonzini 			flush = true;
2718c50d8ae3SPaolo Bonzini 		} else
2719c50d8ae3SPaolo Bonzini 			was_rmapped = 1;
2720c50d8ae3SPaolo Bonzini 	}
2721c50d8ae3SPaolo Bonzini 
27222839180cSPaolo Bonzini 	wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
27237158bee4SPaolo Bonzini 			   true, host_writable, &spte);
2724d786c778SPaolo Bonzini 
2725d786c778SPaolo Bonzini 	if (*sptep == spte) {
2726d786c778SPaolo Bonzini 		ret = RET_PF_SPURIOUS;
2727d786c778SPaolo Bonzini 	} else {
2728d786c778SPaolo Bonzini 		flush |= mmu_spte_update(sptep, spte);
27295959ff4aSMaxim Levitsky 		trace_kvm_mmu_set_spte(level, gfn, sptep);
2730c50d8ae3SPaolo Bonzini 	}
2731c50d8ae3SPaolo Bonzini 
2732ad67e480SPaolo Bonzini 	if (wrprot) {
2733c50d8ae3SPaolo Bonzini 		if (write_fault)
2734c50d8ae3SPaolo Bonzini 			ret = RET_PF_EMULATE;
2735c50d8ae3SPaolo Bonzini 	}
2736c50d8ae3SPaolo Bonzini 
2737d786c778SPaolo Bonzini 	if (flush)
2738c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
2739c50d8ae3SPaolo Bonzini 				KVM_PAGES_PER_HPAGE(level));
2740c50d8ae3SPaolo Bonzini 
2741c50d8ae3SPaolo Bonzini 	pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2742c50d8ae3SPaolo Bonzini 
2743c50d8ae3SPaolo Bonzini 	if (!was_rmapped) {
2744d786c778SPaolo Bonzini 		WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
274571f51d2cSMingwei Zhang 		kvm_update_page_stats(vcpu->kvm, level, 1);
27468a9f566aSDavid Matlack 		rmap_add(vcpu, slot, sptep, gfn);
2747c50d8ae3SPaolo Bonzini 	}
2748c50d8ae3SPaolo Bonzini 
2749c50d8ae3SPaolo Bonzini 	return ret;
2750c50d8ae3SPaolo Bonzini }
2751c50d8ae3SPaolo Bonzini 
2752c50d8ae3SPaolo Bonzini static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2753c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp,
2754c50d8ae3SPaolo Bonzini 				    u64 *start, u64 *end)
2755c50d8ae3SPaolo Bonzini {
2756c50d8ae3SPaolo Bonzini 	struct page *pages[PTE_PREFETCH_NUM];
2757c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
27580a2b64c5SBen Gardon 	unsigned int access = sp->role.access;
2759c50d8ae3SPaolo Bonzini 	int i, ret;
2760c50d8ae3SPaolo Bonzini 	gfn_t gfn;
2761c50d8ae3SPaolo Bonzini 
2762c50d8ae3SPaolo Bonzini 	gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
2763c50d8ae3SPaolo Bonzini 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2764c50d8ae3SPaolo Bonzini 	if (!slot)
2765c50d8ae3SPaolo Bonzini 		return -1;
2766c50d8ae3SPaolo Bonzini 
2767c50d8ae3SPaolo Bonzini 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2768c50d8ae3SPaolo Bonzini 	if (ret <= 0)
2769c50d8ae3SPaolo Bonzini 		return -1;
2770c50d8ae3SPaolo Bonzini 
2771c50d8ae3SPaolo Bonzini 	for (i = 0; i < ret; i++, gfn++, start++) {
27728a9f566aSDavid Matlack 		mmu_set_spte(vcpu, slot, start, access, gfn,
2773a12f4381SPaolo Bonzini 			     page_to_pfn(pages[i]), NULL);
2774c50d8ae3SPaolo Bonzini 		put_page(pages[i]);
2775c50d8ae3SPaolo Bonzini 	}
2776c50d8ae3SPaolo Bonzini 
2777c50d8ae3SPaolo Bonzini 	return 0;
2778c50d8ae3SPaolo Bonzini }
2779c50d8ae3SPaolo Bonzini 
2780c50d8ae3SPaolo Bonzini static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2781c50d8ae3SPaolo Bonzini 				  struct kvm_mmu_page *sp, u64 *sptep)
2782c50d8ae3SPaolo Bonzini {
2783c50d8ae3SPaolo Bonzini 	u64 *spte, *start = NULL;
2784c50d8ae3SPaolo Bonzini 	int i;
2785c50d8ae3SPaolo Bonzini 
2786c50d8ae3SPaolo Bonzini 	WARN_ON(!sp->role.direct);
2787c50d8ae3SPaolo Bonzini 
2788c50d8ae3SPaolo Bonzini 	i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
2789c50d8ae3SPaolo Bonzini 	spte = sp->spt + i;
2790c50d8ae3SPaolo Bonzini 
2791c50d8ae3SPaolo Bonzini 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
2792c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*spte) || spte == sptep) {
2793c50d8ae3SPaolo Bonzini 			if (!start)
2794c50d8ae3SPaolo Bonzini 				continue;
2795c50d8ae3SPaolo Bonzini 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2796c6cecc4bSSean Christopherson 				return;
2797c50d8ae3SPaolo Bonzini 			start = NULL;
2798c50d8ae3SPaolo Bonzini 		} else if (!start)
2799c50d8ae3SPaolo Bonzini 			start = spte;
2800c50d8ae3SPaolo Bonzini 	}
2801c6cecc4bSSean Christopherson 	if (start)
2802c6cecc4bSSean Christopherson 		direct_pte_prefetch_many(vcpu, sp, start, spte);
2803c50d8ae3SPaolo Bonzini }
2804c50d8ae3SPaolo Bonzini 
2805c50d8ae3SPaolo Bonzini static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2806c50d8ae3SPaolo Bonzini {
2807c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2808c50d8ae3SPaolo Bonzini 
280957354682SSean Christopherson 	sp = sptep_to_sp(sptep);
2810c50d8ae3SPaolo Bonzini 
2811c50d8ae3SPaolo Bonzini 	/*
2812c50d8ae3SPaolo Bonzini 	 * Without accessed bits, there's no way to distinguish between
2813c50d8ae3SPaolo Bonzini 	 * actually accessed translations and prefetched, so disable pte
2814c50d8ae3SPaolo Bonzini 	 * prefetch if accessed bits aren't available.
2815c50d8ae3SPaolo Bonzini 	 */
2816c50d8ae3SPaolo Bonzini 	if (sp_ad_disabled(sp))
2817c50d8ae3SPaolo Bonzini 		return;
2818c50d8ae3SPaolo Bonzini 
28193bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
2820c50d8ae3SPaolo Bonzini 		return;
2821c50d8ae3SPaolo Bonzini 
28224a42d848SDavid Stevens 	/*
28234a42d848SDavid Stevens 	 * If addresses are being invalidated, skip prefetching to avoid
28244a42d848SDavid Stevens 	 * accidentally prefetching those addresses.
28254a42d848SDavid Stevens 	 */
28264a42d848SDavid Stevens 	if (unlikely(vcpu->kvm->mmu_notifier_count))
28274a42d848SDavid Stevens 		return;
28284a42d848SDavid Stevens 
2829c50d8ae3SPaolo Bonzini 	__direct_pte_prefetch(vcpu, sp, sptep);
2830c50d8ae3SPaolo Bonzini }
2831c50d8ae3SPaolo Bonzini 
28321b6d9d9eSSean Christopherson static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
28338ca6f063SBen Gardon 				  const struct kvm_memory_slot *slot)
2834db543216SSean Christopherson {
2835284dc493SSean Christopherson 	int level = PG_LEVEL_4K;
28365d49f08cSSean Christopherson 	struct page *page;
2837db543216SSean Christopherson 	unsigned long hva;
283844187235SMingwei Zhang 	unsigned long flags;
283944187235SMingwei Zhang 	pgd_t pgd;
284044187235SMingwei Zhang 	p4d_t p4d;
284144187235SMingwei Zhang 	pud_t pud;
284244187235SMingwei Zhang 	pmd_t pmd;
2843db543216SSean Christopherson 
28445d49f08cSSean Christopherson 	/*
28455d49f08cSSean Christopherson 	 * Note, @slot must be non-NULL, i.e. the caller is responsible for
28465d49f08cSSean Christopherson 	 * ensuring @pfn isn't garbage and is backed by a memslot.
28475d49f08cSSean Christopherson 	 */
28485d49f08cSSean Christopherson 	page = kvm_pfn_to_refcounted_page(pfn);
28495d49f08cSSean Christopherson 	if (!page)
28505d49f08cSSean Christopherson 		return PG_LEVEL_4K;
28515d49f08cSSean Christopherson 
2852284dc493SSean Christopherson 	if (!PageCompound(page) && !kvm_is_zone_device_page(page))
28533bae0459SSean Christopherson 		return PG_LEVEL_4K;
2854db543216SSean Christopherson 
2855293e306eSSean Christopherson 	/*
2856293e306eSSean Christopherson 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
2857293e306eSSean Christopherson 	 * is not solely for performance, it's also necessary to avoid the
2858293e306eSSean Christopherson 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
2859293e306eSSean Christopherson 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
2860293e306eSSean Christopherson 	 * page fault steps have already verified the guest isn't writing a
2861293e306eSSean Christopherson 	 * read-only memslot.
2862293e306eSSean Christopherson 	 */
2863db543216SSean Christopherson 	hva = __gfn_to_hva_memslot(slot, gfn);
2864db543216SSean Christopherson 
286544187235SMingwei Zhang 	/*
286644187235SMingwei Zhang 	 * Lookup the mapping level in the current mm.  The information
286744187235SMingwei Zhang 	 * may become stale soon, but it is safe to use as long as
286844187235SMingwei Zhang 	 * 1) mmu_notifier_retry was checked after taking mmu_lock, and
286944187235SMingwei Zhang 	 * 2) mmu_lock is taken now.
287044187235SMingwei Zhang 	 *
287144187235SMingwei Zhang 	 * We still need to disable IRQs to prevent concurrent tear down
287244187235SMingwei Zhang 	 * of page tables.
287344187235SMingwei Zhang 	 */
287444187235SMingwei Zhang 	local_irq_save(flags);
2875db543216SSean Christopherson 
287644187235SMingwei Zhang 	pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
287744187235SMingwei Zhang 	if (pgd_none(pgd))
287844187235SMingwei Zhang 		goto out;
287944187235SMingwei Zhang 
288044187235SMingwei Zhang 	p4d = READ_ONCE(*p4d_offset(&pgd, hva));
288144187235SMingwei Zhang 	if (p4d_none(p4d) || !p4d_present(p4d))
288244187235SMingwei Zhang 		goto out;
288344187235SMingwei Zhang 
288444187235SMingwei Zhang 	pud = READ_ONCE(*pud_offset(&p4d, hva));
288544187235SMingwei Zhang 	if (pud_none(pud) || !pud_present(pud))
288644187235SMingwei Zhang 		goto out;
288744187235SMingwei Zhang 
288844187235SMingwei Zhang 	if (pud_large(pud)) {
288944187235SMingwei Zhang 		level = PG_LEVEL_1G;
289044187235SMingwei Zhang 		goto out;
289144187235SMingwei Zhang 	}
289244187235SMingwei Zhang 
289344187235SMingwei Zhang 	pmd = READ_ONCE(*pmd_offset(&pud, hva));
289444187235SMingwei Zhang 	if (pmd_none(pmd) || !pmd_present(pmd))
289544187235SMingwei Zhang 		goto out;
289644187235SMingwei Zhang 
289744187235SMingwei Zhang 	if (pmd_large(pmd))
289844187235SMingwei Zhang 		level = PG_LEVEL_2M;
289944187235SMingwei Zhang 
290044187235SMingwei Zhang out:
290144187235SMingwei Zhang 	local_irq_restore(flags);
2902db543216SSean Christopherson 	return level;
2903db543216SSean Christopherson }
2904db543216SSean Christopherson 
29058ca6f063SBen Gardon int kvm_mmu_max_mapping_level(struct kvm *kvm,
29068ca6f063SBen Gardon 			      const struct kvm_memory_slot *slot, gfn_t gfn,
29078ca6f063SBen Gardon 			      kvm_pfn_t pfn, int max_level)
29081b6d9d9eSSean Christopherson {
29091b6d9d9eSSean Christopherson 	struct kvm_lpage_info *linfo;
2910ec607a56SPaolo Bonzini 	int host_level;
29111b6d9d9eSSean Christopherson 
29121b6d9d9eSSean Christopherson 	max_level = min(max_level, max_huge_page_level);
29131b6d9d9eSSean Christopherson 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
29141b6d9d9eSSean Christopherson 		linfo = lpage_info_slot(gfn, slot, max_level);
29151b6d9d9eSSean Christopherson 		if (!linfo->disallow_lpage)
29161b6d9d9eSSean Christopherson 			break;
29171b6d9d9eSSean Christopherson 	}
29181b6d9d9eSSean Christopherson 
29191b6d9d9eSSean Christopherson 	if (max_level == PG_LEVEL_4K)
29201b6d9d9eSSean Christopherson 		return PG_LEVEL_4K;
29211b6d9d9eSSean Christopherson 
2922ec607a56SPaolo Bonzini 	host_level = host_pfn_mapping_level(kvm, gfn, pfn, slot);
2923ec607a56SPaolo Bonzini 	return min(host_level, max_level);
29241b6d9d9eSSean Christopherson }
29251b6d9d9eSSean Christopherson 
292673a3c659SPaolo Bonzini void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
29270885904dSSean Christopherson {
2928e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
292917eff019SSean Christopherson 	kvm_pfn_t mask;
29300885904dSSean Christopherson 
293173a3c659SPaolo Bonzini 	fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
29323cf06612SSean Christopherson 
293373a3c659SPaolo Bonzini 	if (unlikely(fault->max_level == PG_LEVEL_4K))
293473a3c659SPaolo Bonzini 		return;
293517eff019SSean Christopherson 
29365d49f08cSSean Christopherson 	if (is_error_noslot_pfn(fault->pfn))
293773a3c659SPaolo Bonzini 		return;
293817eff019SSean Christopherson 
2939e710c5f6SDavid Matlack 	if (kvm_slot_dirty_track_enabled(slot))
294073a3c659SPaolo Bonzini 		return;
2941293e306eSSean Christopherson 
29423cf06612SSean Christopherson 	/*
29433cf06612SSean Christopherson 	 * Enforce the iTLB multihit workaround after capturing the requested
29443cf06612SSean Christopherson 	 * level, which will be used to do precise, accurate accounting.
29453cf06612SSean Christopherson 	 */
294673a3c659SPaolo Bonzini 	fault->req_level = kvm_mmu_max_mapping_level(vcpu->kvm, slot,
294773a3c659SPaolo Bonzini 						     fault->gfn, fault->pfn,
294873a3c659SPaolo Bonzini 						     fault->max_level);
294973a3c659SPaolo Bonzini 	if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
295073a3c659SPaolo Bonzini 		return;
29514cd071d1SSean Christopherson 
29520885904dSSean Christopherson 	/*
29534cd071d1SSean Christopherson 	 * mmu_notifier_retry() was successful and mmu_lock is held, so
29544cd071d1SSean Christopherson 	 * the pmd can't be split from under us.
29550885904dSSean Christopherson 	 */
295673a3c659SPaolo Bonzini 	fault->goal_level = fault->req_level;
295773a3c659SPaolo Bonzini 	mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
295873a3c659SPaolo Bonzini 	VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
295973a3c659SPaolo Bonzini 	fault->pfn &= ~mask;
29600885904dSSean Christopherson }
29610885904dSSean Christopherson 
2962536f0e6aSPaolo Bonzini void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
2963c50d8ae3SPaolo Bonzini {
2964536f0e6aSPaolo Bonzini 	if (cur_level > PG_LEVEL_4K &&
2965536f0e6aSPaolo Bonzini 	    cur_level == fault->goal_level &&
2966c50d8ae3SPaolo Bonzini 	    is_shadow_present_pte(spte) &&
2967c50d8ae3SPaolo Bonzini 	    !is_large_pte(spte)) {
2968c50d8ae3SPaolo Bonzini 		/*
2969c50d8ae3SPaolo Bonzini 		 * A small SPTE exists for this pfn, but FNAME(fetch)
2970c50d8ae3SPaolo Bonzini 		 * and __direct_map would like to create a large PTE
2971c50d8ae3SPaolo Bonzini 		 * instead: just force them to go down another level,
2972c50d8ae3SPaolo Bonzini 		 * patching back for them into pfn the next 9 bits of
2973c50d8ae3SPaolo Bonzini 		 * the address.
2974c50d8ae3SPaolo Bonzini 		 */
2975536f0e6aSPaolo Bonzini 		u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
2976536f0e6aSPaolo Bonzini 				KVM_PAGES_PER_HPAGE(cur_level - 1);
2977536f0e6aSPaolo Bonzini 		fault->pfn |= fault->gfn & page_mask;
2978536f0e6aSPaolo Bonzini 		fault->goal_level--;
2979c50d8ae3SPaolo Bonzini 	}
2980c50d8ae3SPaolo Bonzini }
2981c50d8ae3SPaolo Bonzini 
298243b74355SPaolo Bonzini static int __direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
2983c50d8ae3SPaolo Bonzini {
2984c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator it;
2985c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
298673a3c659SPaolo Bonzini 	int ret;
298743b74355SPaolo Bonzini 	gfn_t base_gfn = fault->gfn;
2988c50d8ae3SPaolo Bonzini 
298973a3c659SPaolo Bonzini 	kvm_mmu_hugepage_adjust(vcpu, fault);
29904cd071d1SSean Christopherson 
2991f0066d94SPaolo Bonzini 	trace_kvm_mmu_spte_requested(fault);
299243b74355SPaolo Bonzini 	for_each_shadow_entry(vcpu, fault->addr, it) {
2993c50d8ae3SPaolo Bonzini 		/*
2994c50d8ae3SPaolo Bonzini 		 * We cannot overwrite existing page tables with an NX
2995c50d8ae3SPaolo Bonzini 		 * large page, as the leaf could be executable.
2996c50d8ae3SPaolo Bonzini 		 */
299773a3c659SPaolo Bonzini 		if (fault->nx_huge_page_workaround_enabled)
2998536f0e6aSPaolo Bonzini 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
2999c50d8ae3SPaolo Bonzini 
300043b74355SPaolo Bonzini 		base_gfn = fault->gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
300173a3c659SPaolo Bonzini 		if (it.level == fault->goal_level)
3002c50d8ae3SPaolo Bonzini 			break;
3003c50d8ae3SPaolo Bonzini 
3004c50d8ae3SPaolo Bonzini 		drop_large_spte(vcpu, it.sptep);
300503fffc54SSean Christopherson 		if (is_shadow_present_pte(*it.sptep))
300603fffc54SSean Christopherson 			continue;
300703fffc54SSean Christopherson 
30082e65e842SDavid Matlack 		sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
3009c50d8ae3SPaolo Bonzini 
3010c50d8ae3SPaolo Bonzini 		link_shadow_page(vcpu, it.sptep, sp);
301173a3c659SPaolo Bonzini 		if (fault->is_tdp && fault->huge_page_disallowed &&
301273a3c659SPaolo Bonzini 		    fault->req_level >= it.level)
3013c50d8ae3SPaolo Bonzini 			account_huge_nx_page(vcpu->kvm, sp);
3014c50d8ae3SPaolo Bonzini 	}
3015c50d8ae3SPaolo Bonzini 
3016b1a429fbSSean Christopherson 	if (WARN_ON_ONCE(it.level != fault->goal_level))
3017b1a429fbSSean Christopherson 		return -EFAULT;
3018b1a429fbSSean Christopherson 
30198a9f566aSDavid Matlack 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3020a12f4381SPaolo Bonzini 			   base_gfn, fault->pfn, fault);
302112703759SSean Christopherson 	if (ret == RET_PF_SPURIOUS)
302212703759SSean Christopherson 		return ret;
302312703759SSean Christopherson 
3024c50d8ae3SPaolo Bonzini 	direct_pte_prefetch(vcpu, it.sptep);
3025c50d8ae3SPaolo Bonzini 	return ret;
3026c50d8ae3SPaolo Bonzini }
3027c50d8ae3SPaolo Bonzini 
3028c50d8ae3SPaolo Bonzini static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3029c50d8ae3SPaolo Bonzini {
3030c50d8ae3SPaolo Bonzini 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3031c50d8ae3SPaolo Bonzini }
3032c50d8ae3SPaolo Bonzini 
3033c50d8ae3SPaolo Bonzini static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3034c50d8ae3SPaolo Bonzini {
3035c50d8ae3SPaolo Bonzini 	/*
3036c50d8ae3SPaolo Bonzini 	 * Do not cache the mmio info caused by writing the readonly gfn
3037c50d8ae3SPaolo Bonzini 	 * into the spte otherwise read access on readonly gfn also can
3038c50d8ae3SPaolo Bonzini 	 * caused mmio page fault and treat it as mmio access.
3039c50d8ae3SPaolo Bonzini 	 */
3040c50d8ae3SPaolo Bonzini 	if (pfn == KVM_PFN_ERR_RO_FAULT)
3041c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3042c50d8ae3SPaolo Bonzini 
3043c50d8ae3SPaolo Bonzini 	if (pfn == KVM_PFN_ERR_HWPOISON) {
3044c50d8ae3SPaolo Bonzini 		kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3045c50d8ae3SPaolo Bonzini 		return RET_PF_RETRY;
3046c50d8ae3SPaolo Bonzini 	}
3047c50d8ae3SPaolo Bonzini 
3048c50d8ae3SPaolo Bonzini 	return -EFAULT;
3049c50d8ae3SPaolo Bonzini }
3050c50d8ae3SPaolo Bonzini 
30515276c616SSean Christopherson static int handle_abnormal_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
30525276c616SSean Christopherson 			       unsigned int access)
3053c50d8ae3SPaolo Bonzini {
3054c50d8ae3SPaolo Bonzini 	/* The pfn is invalid, report the error! */
30555276c616SSean Christopherson 	if (unlikely(is_error_pfn(fault->pfn)))
30565276c616SSean Christopherson 		return kvm_handle_bad_page(vcpu, fault->gfn, fault->pfn);
3057c50d8ae3SPaolo Bonzini 
3058e710c5f6SDavid Matlack 	if (unlikely(!fault->slot)) {
30593a13f4feSPaolo Bonzini 		gva_t gva = fault->is_tdp ? 0 : fault->addr;
30603a13f4feSPaolo Bonzini 
30613a13f4feSPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3062c50d8ae3SPaolo Bonzini 				     access & shadow_mmio_access_mask);
306330ab5901SSean Christopherson 		/*
306430ab5901SSean Christopherson 		 * If MMIO caching is disabled, emulate immediately without
306530ab5901SSean Christopherson 		 * touching the shadow page tables as attempting to install an
306686931ff7SSean Christopherson 		 * MMIO SPTE will just be an expensive nop.  Do not cache MMIO
306786931ff7SSean Christopherson 		 * whose gfn is greater than host.MAXPHYADDR, any guest that
306886931ff7SSean Christopherson 		 * generates such gfns is running nested and is being tricked
306986931ff7SSean Christopherson 		 * by L0 userspace (you can observe gfn > L1.MAXPHYADDR if
307086931ff7SSean Christopherson 		 * and only if L1's MAXPHYADDR is inaccurate with respect to
307186931ff7SSean Christopherson 		 * the hardware's).
307230ab5901SSean Christopherson 		 */
30738b9e74bfSSean Christopherson 		if (unlikely(!enable_mmio_caching) ||
30745276c616SSean Christopherson 		    unlikely(fault->gfn > kvm_mmu_max_gfn()))
30755276c616SSean Christopherson 			return RET_PF_EMULATE;
307630ab5901SSean Christopherson 	}
3077c50d8ae3SPaolo Bonzini 
30785276c616SSean Christopherson 	return RET_PF_CONTINUE;
3079c50d8ae3SPaolo Bonzini }
3080c50d8ae3SPaolo Bonzini 
30813c8ad5a6SPaolo Bonzini static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
3082c50d8ae3SPaolo Bonzini {
3083c50d8ae3SPaolo Bonzini 	/*
30845c64aba5SSean Christopherson 	 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
30855c64aba5SSean Christopherson 	 * reach the common page fault handler if the SPTE has an invalid MMIO
30865c64aba5SSean Christopherson 	 * generation number.  Refreshing the MMIO generation needs to go down
30875c64aba5SSean Christopherson 	 * the slow path.  Note, EPT Misconfigs do NOT set the PRESENT flag!
3088c50d8ae3SPaolo Bonzini 	 */
30893c8ad5a6SPaolo Bonzini 	if (fault->rsvd)
3090c50d8ae3SPaolo Bonzini 		return false;
3091c50d8ae3SPaolo Bonzini 
3092c50d8ae3SPaolo Bonzini 	/*
3093c50d8ae3SPaolo Bonzini 	 * #PF can be fast if:
3094c50d8ae3SPaolo Bonzini 	 *
309554275f74SSean Christopherson 	 * 1. The shadow page table entry is not present and A/D bits are
309654275f74SSean Christopherson 	 *    disabled _by KVM_, which could mean that the fault is potentially
309754275f74SSean Christopherson 	 *    caused by access tracking (if enabled).  If A/D bits are enabled
309854275f74SSean Christopherson 	 *    by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
309954275f74SSean Christopherson 	 *    bits for L2 and employ access tracking, but the fast page fault
310054275f74SSean Christopherson 	 *    mechanism only supports direct MMUs.
310154275f74SSean Christopherson 	 * 2. The shadow page table entry is present, the access is a write,
310254275f74SSean Christopherson 	 *    and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
310354275f74SSean Christopherson 	 *    the fault was caused by a write-protection violation.  If the
310454275f74SSean Christopherson 	 *    SPTE is MMU-writable (determined later), the fault can be fixed
310554275f74SSean Christopherson 	 *    by setting the Writable bit, which can be done out of mmu_lock.
3106c50d8ae3SPaolo Bonzini 	 */
31075c64aba5SSean Christopherson 	if (!fault->present)
31085c64aba5SSean Christopherson 		return !kvm_ad_enabled();
31095c64aba5SSean Christopherson 
31105c64aba5SSean Christopherson 	/*
31115c64aba5SSean Christopherson 	 * Note, instruction fetches and writes are mutually exclusive, ignore
31125c64aba5SSean Christopherson 	 * the "exec" flag.
31135c64aba5SSean Christopherson 	 */
31145c64aba5SSean Christopherson 	return fault->write;
3115c50d8ae3SPaolo Bonzini }
3116c50d8ae3SPaolo Bonzini 
3117c50d8ae3SPaolo Bonzini /*
3118c50d8ae3SPaolo Bonzini  * Returns true if the SPTE was fixed successfully. Otherwise,
3119c50d8ae3SPaolo Bonzini  * someone else modified the SPTE from its original value.
3120c50d8ae3SPaolo Bonzini  */
3121c50d8ae3SPaolo Bonzini static bool
3122e710c5f6SDavid Matlack fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
3123c50d8ae3SPaolo Bonzini 			u64 *sptep, u64 old_spte, u64 new_spte)
3124c50d8ae3SPaolo Bonzini {
3125c50d8ae3SPaolo Bonzini 	/*
3126c50d8ae3SPaolo Bonzini 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3127c50d8ae3SPaolo Bonzini 	 * order to eliminate unnecessary PML logging. See comments in
3128c50d8ae3SPaolo Bonzini 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3129c50d8ae3SPaolo Bonzini 	 * enabled, so we do not do this. This might result in the same GPA
3130c50d8ae3SPaolo Bonzini 	 * to be logged in PML buffer again when the write really happens, and
3131c50d8ae3SPaolo Bonzini 	 * eventually to be called by mark_page_dirty twice. But it's also no
3132c50d8ae3SPaolo Bonzini 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3133c50d8ae3SPaolo Bonzini 	 * so non-PML cases won't be impacted.
3134c50d8ae3SPaolo Bonzini 	 *
3135c50d8ae3SPaolo Bonzini 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3136c50d8ae3SPaolo Bonzini 	 */
31372db2f46fSUros Bizjak 	if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3138c50d8ae3SPaolo Bonzini 		return false;
3139c50d8ae3SPaolo Bonzini 
3140e710c5f6SDavid Matlack 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3141e710c5f6SDavid Matlack 		mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3142c50d8ae3SPaolo Bonzini 
3143c50d8ae3SPaolo Bonzini 	return true;
3144c50d8ae3SPaolo Bonzini }
3145c50d8ae3SPaolo Bonzini 
31463c8ad5a6SPaolo Bonzini static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3147c50d8ae3SPaolo Bonzini {
31483c8ad5a6SPaolo Bonzini 	if (fault->exec)
3149c50d8ae3SPaolo Bonzini 		return is_executable_pte(spte);
3150c50d8ae3SPaolo Bonzini 
31513c8ad5a6SPaolo Bonzini 	if (fault->write)
3152c50d8ae3SPaolo Bonzini 		return is_writable_pte(spte);
3153c50d8ae3SPaolo Bonzini 
3154c50d8ae3SPaolo Bonzini 	/* Fault was on Read access */
3155c50d8ae3SPaolo Bonzini 	return spte & PT_PRESENT_MASK;
3156c50d8ae3SPaolo Bonzini }
3157c50d8ae3SPaolo Bonzini 
3158c50d8ae3SPaolo Bonzini /*
31596e8eb206SDavid Matlack  * Returns the last level spte pointer of the shadow page walk for the given
31606e8eb206SDavid Matlack  * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
31616e8eb206SDavid Matlack  * walk could be performed, returns NULL and *spte does not contain valid data.
31626e8eb206SDavid Matlack  *
31636e8eb206SDavid Matlack  * Contract:
31646e8eb206SDavid Matlack  *  - Must be called between walk_shadow_page_lockless_{begin,end}.
31656e8eb206SDavid Matlack  *  - The returned sptep must not be used after walk_shadow_page_lockless_end.
31666e8eb206SDavid Matlack  */
31676e8eb206SDavid Matlack static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
31686e8eb206SDavid Matlack {
31696e8eb206SDavid Matlack 	struct kvm_shadow_walk_iterator iterator;
31706e8eb206SDavid Matlack 	u64 old_spte;
31716e8eb206SDavid Matlack 	u64 *sptep = NULL;
31726e8eb206SDavid Matlack 
31736e8eb206SDavid Matlack 	for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
31746e8eb206SDavid Matlack 		sptep = iterator.sptep;
31756e8eb206SDavid Matlack 		*spte = old_spte;
31766e8eb206SDavid Matlack 	}
31776e8eb206SDavid Matlack 
31786e8eb206SDavid Matlack 	return sptep;
31796e8eb206SDavid Matlack }
31806e8eb206SDavid Matlack 
31816e8eb206SDavid Matlack /*
3182c4371c2aSSean Christopherson  * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3183c50d8ae3SPaolo Bonzini  */
31843c8ad5a6SPaolo Bonzini static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3185c50d8ae3SPaolo Bonzini {
3186c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3187c4371c2aSSean Christopherson 	int ret = RET_PF_INVALID;
3188c50d8ae3SPaolo Bonzini 	u64 spte = 0ull;
31896e8eb206SDavid Matlack 	u64 *sptep = NULL;
3190c50d8ae3SPaolo Bonzini 	uint retry_count = 0;
3191c50d8ae3SPaolo Bonzini 
31923c8ad5a6SPaolo Bonzini 	if (!page_fault_can_be_fast(fault))
3193c4371c2aSSean Christopherson 		return ret;
3194c50d8ae3SPaolo Bonzini 
3195c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
3196c50d8ae3SPaolo Bonzini 
3197c50d8ae3SPaolo Bonzini 	do {
3198c50d8ae3SPaolo Bonzini 		u64 new_spte;
3199c50d8ae3SPaolo Bonzini 
32006e8eb206SDavid Matlack 		if (is_tdp_mmu(vcpu->arch.mmu))
32013c8ad5a6SPaolo Bonzini 			sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
32026e8eb206SDavid Matlack 		else
32033c8ad5a6SPaolo Bonzini 			sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3204c50d8ae3SPaolo Bonzini 
3205ec89e643SSean Christopherson 		if (!is_shadow_present_pte(spte))
3206ec89e643SSean Christopherson 			break;
3207ec89e643SSean Christopherson 
32086e8eb206SDavid Matlack 		sp = sptep_to_sp(sptep);
3209c50d8ae3SPaolo Bonzini 		if (!is_last_spte(spte, sp->role.level))
3210c50d8ae3SPaolo Bonzini 			break;
3211c50d8ae3SPaolo Bonzini 
3212c50d8ae3SPaolo Bonzini 		/*
3213c50d8ae3SPaolo Bonzini 		 * Check whether the memory access that caused the fault would
3214c50d8ae3SPaolo Bonzini 		 * still cause it if it were to be performed right now. If not,
3215c50d8ae3SPaolo Bonzini 		 * then this is a spurious fault caused by TLB lazily flushed,
3216c50d8ae3SPaolo Bonzini 		 * or some other CPU has already fixed the PTE after the
3217c50d8ae3SPaolo Bonzini 		 * current CPU took the fault.
3218c50d8ae3SPaolo Bonzini 		 *
3219c50d8ae3SPaolo Bonzini 		 * Need not check the access of upper level table entries since
3220c50d8ae3SPaolo Bonzini 		 * they are always ACC_ALL.
3221c50d8ae3SPaolo Bonzini 		 */
32223c8ad5a6SPaolo Bonzini 		if (is_access_allowed(fault, spte)) {
3223c4371c2aSSean Christopherson 			ret = RET_PF_SPURIOUS;
3224c50d8ae3SPaolo Bonzini 			break;
3225c50d8ae3SPaolo Bonzini 		}
3226c50d8ae3SPaolo Bonzini 
3227c50d8ae3SPaolo Bonzini 		new_spte = spte;
3228c50d8ae3SPaolo Bonzini 
322954275f74SSean Christopherson 		/*
323054275f74SSean Christopherson 		 * KVM only supports fixing page faults outside of MMU lock for
323154275f74SSean Christopherson 		 * direct MMUs, nested MMUs are always indirect, and KVM always
323254275f74SSean Christopherson 		 * uses A/D bits for non-nested MMUs.  Thus, if A/D bits are
323354275f74SSean Christopherson 		 * enabled, the SPTE can't be an access-tracked SPTE.
323454275f74SSean Christopherson 		 */
323554275f74SSean Christopherson 		if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3236c50d8ae3SPaolo Bonzini 			new_spte = restore_acc_track_spte(new_spte);
3237c50d8ae3SPaolo Bonzini 
3238c50d8ae3SPaolo Bonzini 		/*
323954275f74SSean Christopherson 		 * To keep things simple, only SPTEs that are MMU-writable can
324054275f74SSean Christopherson 		 * be made fully writable outside of mmu_lock, e.g. only SPTEs
324154275f74SSean Christopherson 		 * that were write-protected for dirty-logging or access
324254275f74SSean Christopherson 		 * tracking are handled here.  Don't bother checking if the
324354275f74SSean Christopherson 		 * SPTE is writable to prioritize running with A/D bits enabled.
324454275f74SSean Christopherson 		 * The is_access_allowed() check above handles the common case
324554275f74SSean Christopherson 		 * of the fault being spurious, and the SPTE is known to be
324654275f74SSean Christopherson 		 * shadow-present, i.e. except for access tracking restoration
324754275f74SSean Christopherson 		 * making the new SPTE writable, the check is wasteful.
3248c50d8ae3SPaolo Bonzini 		 */
3249706c9c55SSean Christopherson 		if (fault->write && is_mmu_writable_spte(spte)) {
3250c50d8ae3SPaolo Bonzini 			new_spte |= PT_WRITABLE_MASK;
3251c50d8ae3SPaolo Bonzini 
3252c50d8ae3SPaolo Bonzini 			/*
325310c30de0SJunaid Shahid 			 * Do not fix write-permission on the large spte when
325410c30de0SJunaid Shahid 			 * dirty logging is enabled. Since we only dirty the
325510c30de0SJunaid Shahid 			 * first page into the dirty-bitmap in
3256c50d8ae3SPaolo Bonzini 			 * fast_pf_fix_direct_spte(), other pages are missed
3257c50d8ae3SPaolo Bonzini 			 * if its slot has dirty logging enabled.
3258c50d8ae3SPaolo Bonzini 			 *
3259c50d8ae3SPaolo Bonzini 			 * Instead, we let the slow page fault path create a
3260c50d8ae3SPaolo Bonzini 			 * normal spte to fix the access.
3261c50d8ae3SPaolo Bonzini 			 */
326210c30de0SJunaid Shahid 			if (sp->role.level > PG_LEVEL_4K &&
326310c30de0SJunaid Shahid 			    kvm_slot_dirty_track_enabled(fault->slot))
3264c50d8ae3SPaolo Bonzini 				break;
3265c50d8ae3SPaolo Bonzini 		}
3266c50d8ae3SPaolo Bonzini 
3267c50d8ae3SPaolo Bonzini 		/* Verify that the fault can be handled in the fast path */
3268c50d8ae3SPaolo Bonzini 		if (new_spte == spte ||
32693c8ad5a6SPaolo Bonzini 		    !is_access_allowed(fault, new_spte))
3270c50d8ae3SPaolo Bonzini 			break;
3271c50d8ae3SPaolo Bonzini 
3272c50d8ae3SPaolo Bonzini 		/*
3273c50d8ae3SPaolo Bonzini 		 * Currently, fast page fault only works for direct mapping
3274c50d8ae3SPaolo Bonzini 		 * since the gfn is not stable for indirect shadow page. See
32753ecad8c2SMauro Carvalho Chehab 		 * Documentation/virt/kvm/locking.rst to get more detail.
3276c50d8ae3SPaolo Bonzini 		 */
3277e710c5f6SDavid Matlack 		if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3278c4371c2aSSean Christopherson 			ret = RET_PF_FIXED;
3279c50d8ae3SPaolo Bonzini 			break;
3280c4371c2aSSean Christopherson 		}
3281c50d8ae3SPaolo Bonzini 
3282c50d8ae3SPaolo Bonzini 		if (++retry_count > 4) {
3283c50d8ae3SPaolo Bonzini 			printk_once(KERN_WARNING
3284c50d8ae3SPaolo Bonzini 				"kvm: Fast #PF retrying more than 4 times.\n");
3285c50d8ae3SPaolo Bonzini 			break;
3286c50d8ae3SPaolo Bonzini 		}
3287c50d8ae3SPaolo Bonzini 
3288c50d8ae3SPaolo Bonzini 	} while (true);
3289c50d8ae3SPaolo Bonzini 
3290f0066d94SPaolo Bonzini 	trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3291c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3292c50d8ae3SPaolo Bonzini 
32931075d41eSSean Christopherson 	if (ret != RET_PF_INVALID)
32941075d41eSSean Christopherson 		vcpu->stat.pf_fast++;
32951075d41eSSean Christopherson 
3296c4371c2aSSean Christopherson 	return ret;
3297c50d8ae3SPaolo Bonzini }
3298c50d8ae3SPaolo Bonzini 
3299c50d8ae3SPaolo Bonzini static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3300c50d8ae3SPaolo Bonzini 			       struct list_head *invalid_list)
3301c50d8ae3SPaolo Bonzini {
3302c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3303c50d8ae3SPaolo Bonzini 
3304c50d8ae3SPaolo Bonzini 	if (!VALID_PAGE(*root_hpa))
3305c50d8ae3SPaolo Bonzini 		return;
3306c50d8ae3SPaolo Bonzini 
33072ca3129eSSean Christopherson 	sp = to_shadow_page(*root_hpa & SPTE_BASE_ADDR_MASK);
33089191b8f0SPaolo Bonzini 	if (WARN_ON(!sp))
33099191b8f0SPaolo Bonzini 		return;
331002c00b3aSBen Gardon 
3311897218ffSPaolo Bonzini 	if (is_tdp_mmu_page(sp))
33126103bc07SBen Gardon 		kvm_tdp_mmu_put_root(kvm, sp, false);
331376eb54e7SBen Gardon 	else if (!--sp->root_count && sp->role.invalid)
3314c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3315c50d8ae3SPaolo Bonzini 
3316c50d8ae3SPaolo Bonzini 	*root_hpa = INVALID_PAGE;
3317c50d8ae3SPaolo Bonzini }
3318c50d8ae3SPaolo Bonzini 
3319c50d8ae3SPaolo Bonzini /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
33200c1c92f1SPaolo Bonzini void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3321c50d8ae3SPaolo Bonzini 			ulong roots_to_free)
3322c50d8ae3SPaolo Bonzini {
3323c50d8ae3SPaolo Bonzini 	int i;
3324c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
3325594bef79SPaolo Bonzini 	bool free_active_root;
3326c50d8ae3SPaolo Bonzini 
3327c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3328c50d8ae3SPaolo Bonzini 
3329c50d8ae3SPaolo Bonzini 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3330594bef79SPaolo Bonzini 	free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3331594bef79SPaolo Bonzini 		&& VALID_PAGE(mmu->root.hpa);
3332594bef79SPaolo Bonzini 
3333594bef79SPaolo Bonzini 	if (!free_active_root) {
3334c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3335c50d8ae3SPaolo Bonzini 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3336c50d8ae3SPaolo Bonzini 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3337c50d8ae3SPaolo Bonzini 				break;
3338c50d8ae3SPaolo Bonzini 
3339c50d8ae3SPaolo Bonzini 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3340c50d8ae3SPaolo Bonzini 			return;
3341c50d8ae3SPaolo Bonzini 	}
3342c50d8ae3SPaolo Bonzini 
3343531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
3344c50d8ae3SPaolo Bonzini 
3345c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3346c50d8ae3SPaolo Bonzini 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
33474d710de9SSean Christopherson 			mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3348c50d8ae3SPaolo Bonzini 					   &invalid_list);
3349c50d8ae3SPaolo Bonzini 
3350c50d8ae3SPaolo Bonzini 	if (free_active_root) {
3351594bef79SPaolo Bonzini 		if (to_shadow_page(mmu->root.hpa)) {
3352b9e5603cSPaolo Bonzini 			mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
335304d45551SSean Christopherson 		} else if (mmu->pae_root) {
3354c834e5e4SSean Christopherson 			for (i = 0; i < 4; ++i) {
3355c834e5e4SSean Christopherson 				if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3356c834e5e4SSean Christopherson 					continue;
3357c834e5e4SSean Christopherson 
3358c834e5e4SSean Christopherson 				mmu_free_root_page(kvm, &mmu->pae_root[i],
3359c50d8ae3SPaolo Bonzini 						   &invalid_list);
3360c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3361c50d8ae3SPaolo Bonzini 			}
3362c50d8ae3SPaolo Bonzini 		}
3363b9e5603cSPaolo Bonzini 		mmu->root.hpa = INVALID_PAGE;
3364b9e5603cSPaolo Bonzini 		mmu->root.pgd = 0;
3365c50d8ae3SPaolo Bonzini 	}
3366c50d8ae3SPaolo Bonzini 
33674d710de9SSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
3368531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
3369c50d8ae3SPaolo Bonzini }
3370c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3371c50d8ae3SPaolo Bonzini 
33720c1c92f1SPaolo Bonzini void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
337325b62c62SSean Christopherson {
337425b62c62SSean Christopherson 	unsigned long roots_to_free = 0;
337525b62c62SSean Christopherson 	hpa_t root_hpa;
337625b62c62SSean Christopherson 	int i;
337725b62c62SSean Christopherson 
337825b62c62SSean Christopherson 	/*
337925b62c62SSean Christopherson 	 * This should not be called while L2 is active, L2 can't invalidate
338025b62c62SSean Christopherson 	 * _only_ its own roots, e.g. INVVPID unconditionally exits.
338125b62c62SSean Christopherson 	 */
33827a458f0eSPaolo Bonzini 	WARN_ON_ONCE(mmu->root_role.guest_mode);
338325b62c62SSean Christopherson 
338425b62c62SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
338525b62c62SSean Christopherson 		root_hpa = mmu->prev_roots[i].hpa;
338625b62c62SSean Christopherson 		if (!VALID_PAGE(root_hpa))
338725b62c62SSean Christopherson 			continue;
338825b62c62SSean Christopherson 
338925b62c62SSean Christopherson 		if (!to_shadow_page(root_hpa) ||
339025b62c62SSean Christopherson 			to_shadow_page(root_hpa)->role.guest_mode)
339125b62c62SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
339225b62c62SSean Christopherson 	}
339325b62c62SSean Christopherson 
33940c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, roots_to_free);
339525b62c62SSean Christopherson }
339625b62c62SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
339725b62c62SSean Christopherson 
339825b62c62SSean Christopherson 
3399c50d8ae3SPaolo Bonzini static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3400c50d8ae3SPaolo Bonzini {
3401c50d8ae3SPaolo Bonzini 	int ret = 0;
3402c50d8ae3SPaolo Bonzini 
3403995decb6SVitaly Kuznetsov 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3404c50d8ae3SPaolo Bonzini 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3405c50d8ae3SPaolo Bonzini 		ret = 1;
3406c50d8ae3SPaolo Bonzini 	}
3407c50d8ae3SPaolo Bonzini 
3408c50d8ae3SPaolo Bonzini 	return ret;
3409c50d8ae3SPaolo Bonzini }
3410c50d8ae3SPaolo Bonzini 
34112e65e842SDavid Matlack static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
341286938ab6SDavid Matlack 			    u8 level)
3413c50d8ae3SPaolo Bonzini {
34142e65e842SDavid Matlack 	union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3415c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
34168123f265SSean Christopherson 
34172e65e842SDavid Matlack 	role.level = level;
34182e65e842SDavid Matlack 	role.quadrant = quadrant;
34192e65e842SDavid Matlack 
34207f497775SDavid Matlack 	WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
34217f497775SDavid Matlack 	WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
34227f497775SDavid Matlack 
34232e65e842SDavid Matlack 	sp = kvm_mmu_get_page(vcpu, gfn, role);
34248123f265SSean Christopherson 	++sp->root_count;
34258123f265SSean Christopherson 
34268123f265SSean Christopherson 	return __pa(sp->spt);
34278123f265SSean Christopherson }
34288123f265SSean Christopherson 
34298123f265SSean Christopherson static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
34308123f265SSean Christopherson {
3431b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3432a972e29cSPaolo Bonzini 	u8 shadow_root_level = mmu->root_role.level;
34338123f265SSean Christopherson 	hpa_t root;
3434c50d8ae3SPaolo Bonzini 	unsigned i;
34354a38162eSPaolo Bonzini 	int r;
34364a38162eSPaolo Bonzini 
34374a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
34384a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
34394a38162eSPaolo Bonzini 	if (r < 0)
34404a38162eSPaolo Bonzini 		goto out_unlock;
3441c50d8ae3SPaolo Bonzini 
3442897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(vcpu->kvm)) {
344302c00b3aSBen Gardon 		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
3444b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
344502c00b3aSBen Gardon 	} else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
344686938ab6SDavid Matlack 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3447b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
34488123f265SSean Christopherson 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
34494a38162eSPaolo Bonzini 		if (WARN_ON_ONCE(!mmu->pae_root)) {
34504a38162eSPaolo Bonzini 			r = -EIO;
34514a38162eSPaolo Bonzini 			goto out_unlock;
34524a38162eSPaolo Bonzini 		}
345373ad1606SSean Christopherson 
3454c50d8ae3SPaolo Bonzini 		for (i = 0; i < 4; ++i) {
3455c834e5e4SSean Christopherson 			WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3456c50d8ae3SPaolo Bonzini 
34577f497775SDavid Matlack 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
34582e65e842SDavid Matlack 					      PT32_ROOT_LEVEL);
345917e368d9SSean Christopherson 			mmu->pae_root[i] = root | PT_PRESENT_MASK |
3460d2263de1SYuan Yao 					   shadow_me_value;
3461c50d8ae3SPaolo Bonzini 		}
3462b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
346373ad1606SSean Christopherson 	} else {
346473ad1606SSean Christopherson 		WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
34654a38162eSPaolo Bonzini 		r = -EIO;
34664a38162eSPaolo Bonzini 		goto out_unlock;
346773ad1606SSean Christopherson 	}
34683651c7fcSSean Christopherson 
3469b9e5603cSPaolo Bonzini 	/* root.pgd is ignored for direct MMUs. */
3470b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
34714a38162eSPaolo Bonzini out_unlock:
34724a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
34734a38162eSPaolo Bonzini 	return r;
3474c50d8ae3SPaolo Bonzini }
3475c50d8ae3SPaolo Bonzini 
34761e76a3ceSDavid Stevens static int mmu_first_shadow_root_alloc(struct kvm *kvm)
34771e76a3ceSDavid Stevens {
34781e76a3ceSDavid Stevens 	struct kvm_memslots *slots;
34791e76a3ceSDavid Stevens 	struct kvm_memory_slot *slot;
3480a54d8066SMaciej S. Szmigiero 	int r = 0, i, bkt;
34811e76a3ceSDavid Stevens 
34821e76a3ceSDavid Stevens 	/*
34831e76a3ceSDavid Stevens 	 * Check if this is the first shadow root being allocated before
34841e76a3ceSDavid Stevens 	 * taking the lock.
34851e76a3ceSDavid Stevens 	 */
34861e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
34871e76a3ceSDavid Stevens 		return 0;
34881e76a3ceSDavid Stevens 
34891e76a3ceSDavid Stevens 	mutex_lock(&kvm->slots_arch_lock);
34901e76a3ceSDavid Stevens 
34911e76a3ceSDavid Stevens 	/* Recheck, under the lock, whether this is the first shadow root. */
34921e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
34931e76a3ceSDavid Stevens 		goto out_unlock;
34941e76a3ceSDavid Stevens 
34951e76a3ceSDavid Stevens 	/*
34961e76a3ceSDavid Stevens 	 * Check if anything actually needs to be allocated, e.g. all metadata
34971e76a3ceSDavid Stevens 	 * will be allocated upfront if TDP is disabled.
34981e76a3ceSDavid Stevens 	 */
34991e76a3ceSDavid Stevens 	if (kvm_memslots_have_rmaps(kvm) &&
35001e76a3ceSDavid Stevens 	    kvm_page_track_write_tracking_enabled(kvm))
35011e76a3ceSDavid Stevens 		goto out_success;
35021e76a3ceSDavid Stevens 
35031e76a3ceSDavid Stevens 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
35041e76a3ceSDavid Stevens 		slots = __kvm_memslots(kvm, i);
3505a54d8066SMaciej S. Szmigiero 		kvm_for_each_memslot(slot, bkt, slots) {
35061e76a3ceSDavid Stevens 			/*
35071e76a3ceSDavid Stevens 			 * Both of these functions are no-ops if the target is
35081e76a3ceSDavid Stevens 			 * already allocated, so unconditionally calling both
35091e76a3ceSDavid Stevens 			 * is safe.  Intentionally do NOT free allocations on
35101e76a3ceSDavid Stevens 			 * failure to avoid having to track which allocations
35111e76a3ceSDavid Stevens 			 * were made now versus when the memslot was created.
35121e76a3ceSDavid Stevens 			 * The metadata is guaranteed to be freed when the slot
35131e76a3ceSDavid Stevens 			 * is freed, and will be kept/used if userspace retries
35141e76a3ceSDavid Stevens 			 * KVM_RUN instead of killing the VM.
35151e76a3ceSDavid Stevens 			 */
35161e76a3ceSDavid Stevens 			r = memslot_rmap_alloc(slot, slot->npages);
35171e76a3ceSDavid Stevens 			if (r)
35181e76a3ceSDavid Stevens 				goto out_unlock;
35191e76a3ceSDavid Stevens 			r = kvm_page_track_write_tracking_alloc(slot);
35201e76a3ceSDavid Stevens 			if (r)
35211e76a3ceSDavid Stevens 				goto out_unlock;
35221e76a3ceSDavid Stevens 		}
35231e76a3ceSDavid Stevens 	}
35241e76a3ceSDavid Stevens 
35251e76a3ceSDavid Stevens 	/*
35261e76a3ceSDavid Stevens 	 * Ensure that shadow_root_allocated becomes true strictly after
35271e76a3ceSDavid Stevens 	 * all the related pointers are set.
35281e76a3ceSDavid Stevens 	 */
35291e76a3ceSDavid Stevens out_success:
35301e76a3ceSDavid Stevens 	smp_store_release(&kvm->arch.shadow_root_allocated, true);
35311e76a3ceSDavid Stevens 
35321e76a3ceSDavid Stevens out_unlock:
35331e76a3ceSDavid Stevens 	mutex_unlock(&kvm->slots_arch_lock);
35341e76a3ceSDavid Stevens 	return r;
35351e76a3ceSDavid Stevens }
35361e76a3ceSDavid Stevens 
3537c50d8ae3SPaolo Bonzini static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3538c50d8ae3SPaolo Bonzini {
3539b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
35406e0918aeSSean Christopherson 	u64 pdptrs[4], pm_mask;
3541be01e8e2SSean Christopherson 	gfn_t root_gfn, root_pgd;
35427f497775SDavid Matlack 	int quadrant, i, r;
35438123f265SSean Christopherson 	hpa_t root;
3544c50d8ae3SPaolo Bonzini 
3545b37233c9SSean Christopherson 	root_pgd = mmu->get_guest_pgd(vcpu);
3546be01e8e2SSean Christopherson 	root_gfn = root_pgd >> PAGE_SHIFT;
3547c50d8ae3SPaolo Bonzini 
3548c50d8ae3SPaolo Bonzini 	if (mmu_check_root(vcpu, root_gfn))
3549c50d8ae3SPaolo Bonzini 		return 1;
3550c50d8ae3SPaolo Bonzini 
3551c50d8ae3SPaolo Bonzini 	/*
35524a38162eSPaolo Bonzini 	 * On SVM, reading PDPTRs might access guest memory, which might fault
35534a38162eSPaolo Bonzini 	 * and thus might sleep.  Grab the PDPTRs before acquiring mmu_lock.
35544a38162eSPaolo Bonzini 	 */
35554d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
35566e0918aeSSean Christopherson 		for (i = 0; i < 4; ++i) {
35576e0918aeSSean Christopherson 			pdptrs[i] = mmu->get_pdptr(vcpu, i);
35586e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK))
35596e0918aeSSean Christopherson 				continue;
35606e0918aeSSean Christopherson 
35616e0918aeSSean Christopherson 			if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
35626e0918aeSSean Christopherson 				return 1;
35636e0918aeSSean Christopherson 		}
35646e0918aeSSean Christopherson 	}
35656e0918aeSSean Christopherson 
35661e76a3ceSDavid Stevens 	r = mmu_first_shadow_root_alloc(vcpu->kvm);
3567d501f747SBen Gardon 	if (r)
3568d501f747SBen Gardon 		return r;
3569d501f747SBen Gardon 
35704a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
35714a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
35724a38162eSPaolo Bonzini 	if (r < 0)
35734a38162eSPaolo Bonzini 		goto out_unlock;
35744a38162eSPaolo Bonzini 
3575c50d8ae3SPaolo Bonzini 	/*
3576c50d8ae3SPaolo Bonzini 	 * Do we shadow a long mode page table? If so we need to
3577c50d8ae3SPaolo Bonzini 	 * write-protect the guests page table root.
3578c50d8ae3SPaolo Bonzini 	 */
35794d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
35808123f265SSean Christopherson 		root = mmu_alloc_root(vcpu, root_gfn, 0,
358186938ab6SDavid Matlack 				      mmu->root_role.level);
3582b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
3583be01e8e2SSean Christopherson 		goto set_root_pgd;
3584c50d8ae3SPaolo Bonzini 	}
3585c50d8ae3SPaolo Bonzini 
35864a38162eSPaolo Bonzini 	if (WARN_ON_ONCE(!mmu->pae_root)) {
35874a38162eSPaolo Bonzini 		r = -EIO;
35884a38162eSPaolo Bonzini 		goto out_unlock;
35894a38162eSPaolo Bonzini 	}
359073ad1606SSean Christopherson 
3591c50d8ae3SPaolo Bonzini 	/*
3592c50d8ae3SPaolo Bonzini 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3593c50d8ae3SPaolo Bonzini 	 * or a PAE 3-level page table. In either case we need to be aware that
3594c50d8ae3SPaolo Bonzini 	 * the shadow page table may be a PAE or a long mode page table.
3595c50d8ae3SPaolo Bonzini 	 */
3596e54f1ff2SKai Huang 	pm_mask = PT_PRESENT_MASK | shadow_me_value;
3597a972e29cSPaolo Bonzini 	if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3598c50d8ae3SPaolo Bonzini 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3599c50d8ae3SPaolo Bonzini 
360003ca4589SSean Christopherson 		if (WARN_ON_ONCE(!mmu->pml4_root)) {
36014a38162eSPaolo Bonzini 			r = -EIO;
36024a38162eSPaolo Bonzini 			goto out_unlock;
36034a38162eSPaolo Bonzini 		}
360403ca4589SSean Christopherson 		mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3605cb0f722aSWei Huang 
3606a972e29cSPaolo Bonzini 		if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3607cb0f722aSWei Huang 			if (WARN_ON_ONCE(!mmu->pml5_root)) {
3608cb0f722aSWei Huang 				r = -EIO;
3609cb0f722aSWei Huang 				goto out_unlock;
3610cb0f722aSWei Huang 			}
3611cb0f722aSWei Huang 			mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3612cb0f722aSWei Huang 		}
361304d45551SSean Christopherson 	}
361404d45551SSean Christopherson 
3615c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3616c834e5e4SSean Christopherson 		WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
36176e6ec584SSean Christopherson 
36184d25502aSPaolo Bonzini 		if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
36196e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3620c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3621c50d8ae3SPaolo Bonzini 				continue;
3622c50d8ae3SPaolo Bonzini 			}
36236e0918aeSSean Christopherson 			root_gfn = pdptrs[i] >> PAGE_SHIFT;
3624c50d8ae3SPaolo Bonzini 		}
3625c50d8ae3SPaolo Bonzini 
36267f497775SDavid Matlack 		/*
36277f497775SDavid Matlack 		 * If shadowing 32-bit non-PAE page tables, each PAE page
36287f497775SDavid Matlack 		 * directory maps one quarter of the guest's non-PAE page
36297f497775SDavid Matlack 		 * directory. Othwerise each PAE page direct shadows one guest
36307f497775SDavid Matlack 		 * PAE page directory so that quadrant should be 0.
36317f497775SDavid Matlack 		 */
36327f497775SDavid Matlack 		quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
36337f497775SDavid Matlack 
36347f497775SDavid Matlack 		root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3635b37233c9SSean Christopherson 		mmu->pae_root[i] = root | pm_mask;
3636c50d8ae3SPaolo Bonzini 	}
3637c50d8ae3SPaolo Bonzini 
3638a972e29cSPaolo Bonzini 	if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3639b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml5_root);
3640a972e29cSPaolo Bonzini 	else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3641b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml4_root);
3642ba0a194fSSean Christopherson 	else
3643b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
3644c50d8ae3SPaolo Bonzini 
3645be01e8e2SSean Christopherson set_root_pgd:
3646b9e5603cSPaolo Bonzini 	mmu->root.pgd = root_pgd;
36474a38162eSPaolo Bonzini out_unlock:
36484a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
3649c50d8ae3SPaolo Bonzini 
3650c6c937d6SLike Xu 	return r;
3651c50d8ae3SPaolo Bonzini }
3652c50d8ae3SPaolo Bonzini 
3653748e52b9SSean Christopherson static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3654c50d8ae3SPaolo Bonzini {
3655748e52b9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3656a972e29cSPaolo Bonzini 	bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3657cb0f722aSWei Huang 	u64 *pml5_root = NULL;
3658cb0f722aSWei Huang 	u64 *pml4_root = NULL;
3659cb0f722aSWei Huang 	u64 *pae_root;
3660748e52b9SSean Christopherson 
3661748e52b9SSean Christopherson 	/*
3662748e52b9SSean Christopherson 	 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3663748e52b9SSean Christopherson 	 * tables are allocated and initialized at root creation as there is no
3664748e52b9SSean Christopherson 	 * equivalent level in the guest's NPT to shadow.  Allocate the tables
3665748e52b9SSean Christopherson 	 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3666748e52b9SSean Christopherson 	 */
3667347a0d0dSPaolo Bonzini 	if (mmu->root_role.direct ||
3668347a0d0dSPaolo Bonzini 	    mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3669a972e29cSPaolo Bonzini 	    mmu->root_role.level < PT64_ROOT_4LEVEL)
3670748e52b9SSean Christopherson 		return 0;
3671748e52b9SSean Christopherson 
3672a717a780SSean Christopherson 	/*
3673a717a780SSean Christopherson 	 * NPT, the only paging mode that uses this horror, uses a fixed number
3674a717a780SSean Christopherson 	 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3675a717a780SSean Christopherson 	 * all MMus are 5-level.  Thus, this can safely require that pml5_root
3676a717a780SSean Christopherson 	 * is allocated if the other roots are valid and pml5 is needed, as any
3677a717a780SSean Christopherson 	 * prior MMU would also have required pml5.
3678a717a780SSean Christopherson 	 */
3679a717a780SSean Christopherson 	if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3680748e52b9SSean Christopherson 		return 0;
3681748e52b9SSean Christopherson 
3682748e52b9SSean Christopherson 	/*
3683748e52b9SSean Christopherson 	 * The special roots should always be allocated in concert.  Yell and
3684748e52b9SSean Christopherson 	 * bail if KVM ends up in a state where only one of the roots is valid.
3685748e52b9SSean Christopherson 	 */
3686cb0f722aSWei Huang 	if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3687a717a780SSean Christopherson 			 (need_pml5 && mmu->pml5_root)))
3688748e52b9SSean Christopherson 		return -EIO;
3689748e52b9SSean Christopherson 
36904a98623dSSean Christopherson 	/*
36914a98623dSSean Christopherson 	 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
36924a98623dSSean Christopherson 	 * doesn't need to be decrypted.
36934a98623dSSean Christopherson 	 */
3694748e52b9SSean Christopherson 	pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3695748e52b9SSean Christopherson 	if (!pae_root)
3696748e52b9SSean Christopherson 		return -ENOMEM;
3697748e52b9SSean Christopherson 
3698cb0f722aSWei Huang #ifdef CONFIG_X86_64
369903ca4589SSean Christopherson 	pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3700cb0f722aSWei Huang 	if (!pml4_root)
3701cb0f722aSWei Huang 		goto err_pml4;
3702cb0f722aSWei Huang 
3703a717a780SSean Christopherson 	if (need_pml5) {
3704cb0f722aSWei Huang 		pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3705cb0f722aSWei Huang 		if (!pml5_root)
3706cb0f722aSWei Huang 			goto err_pml5;
3707748e52b9SSean Christopherson 	}
3708cb0f722aSWei Huang #endif
3709748e52b9SSean Christopherson 
3710748e52b9SSean Christopherson 	mmu->pae_root = pae_root;
371103ca4589SSean Christopherson 	mmu->pml4_root = pml4_root;
3712cb0f722aSWei Huang 	mmu->pml5_root = pml5_root;
3713748e52b9SSean Christopherson 
3714748e52b9SSean Christopherson 	return 0;
3715cb0f722aSWei Huang 
3716cb0f722aSWei Huang #ifdef CONFIG_X86_64
3717cb0f722aSWei Huang err_pml5:
3718cb0f722aSWei Huang 	free_page((unsigned long)pml4_root);
3719cb0f722aSWei Huang err_pml4:
3720cb0f722aSWei Huang 	free_page((unsigned long)pae_root);
3721cb0f722aSWei Huang 	return -ENOMEM;
3722cb0f722aSWei Huang #endif
3723c50d8ae3SPaolo Bonzini }
3724c50d8ae3SPaolo Bonzini 
3725264d3dc1SLai Jiangshan static bool is_unsync_root(hpa_t root)
3726264d3dc1SLai Jiangshan {
3727264d3dc1SLai Jiangshan 	struct kvm_mmu_page *sp;
3728264d3dc1SLai Jiangshan 
372961b05a9fSLai Jiangshan 	if (!VALID_PAGE(root))
373061b05a9fSLai Jiangshan 		return false;
373161b05a9fSLai Jiangshan 
3732264d3dc1SLai Jiangshan 	/*
3733264d3dc1SLai Jiangshan 	 * The read barrier orders the CPU's read of SPTE.W during the page table
3734264d3dc1SLai Jiangshan 	 * walk before the reads of sp->unsync/sp->unsync_children here.
3735264d3dc1SLai Jiangshan 	 *
3736264d3dc1SLai Jiangshan 	 * Even if another CPU was marking the SP as unsync-ed simultaneously,
3737264d3dc1SLai Jiangshan 	 * any guest page table changes are not guaranteed to be visible anyway
3738264d3dc1SLai Jiangshan 	 * until this VCPU issues a TLB flush strictly after those changes are
3739264d3dc1SLai Jiangshan 	 * made.  We only need to ensure that the other CPU sets these flags
3740264d3dc1SLai Jiangshan 	 * before any actual changes to the page tables are made.  The comments
3741264d3dc1SLai Jiangshan 	 * in mmu_try_to_unsync_pages() describe what could go wrong if this
3742264d3dc1SLai Jiangshan 	 * requirement isn't satisfied.
3743264d3dc1SLai Jiangshan 	 */
3744264d3dc1SLai Jiangshan 	smp_rmb();
3745264d3dc1SLai Jiangshan 	sp = to_shadow_page(root);
37465d6a3221SSean Christopherson 
37475d6a3221SSean Christopherson 	/*
37485d6a3221SSean Christopherson 	 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
37495d6a3221SSean Christopherson 	 * PDPTEs for a given PAE root need to be synchronized individually.
37505d6a3221SSean Christopherson 	 */
37515d6a3221SSean Christopherson 	if (WARN_ON_ONCE(!sp))
37525d6a3221SSean Christopherson 		return false;
37535d6a3221SSean Christopherson 
3754264d3dc1SLai Jiangshan 	if (sp->unsync || sp->unsync_children)
3755264d3dc1SLai Jiangshan 		return true;
3756264d3dc1SLai Jiangshan 
3757264d3dc1SLai Jiangshan 	return false;
3758264d3dc1SLai Jiangshan }
3759264d3dc1SLai Jiangshan 
3760c50d8ae3SPaolo Bonzini void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3761c50d8ae3SPaolo Bonzini {
3762c50d8ae3SPaolo Bonzini 	int i;
3763c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3764c50d8ae3SPaolo Bonzini 
3765347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
3766c50d8ae3SPaolo Bonzini 		return;
3767c50d8ae3SPaolo Bonzini 
3768b9e5603cSPaolo Bonzini 	if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
3769c50d8ae3SPaolo Bonzini 		return;
3770c50d8ae3SPaolo Bonzini 
3771c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3772c50d8ae3SPaolo Bonzini 
37734d25502aSPaolo Bonzini 	if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
3774b9e5603cSPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->root.hpa;
3775e47c4aeeSSean Christopherson 		sp = to_shadow_page(root);
3776c50d8ae3SPaolo Bonzini 
3777264d3dc1SLai Jiangshan 		if (!is_unsync_root(root))
3778c50d8ae3SPaolo Bonzini 			return;
3779c50d8ae3SPaolo Bonzini 
3780531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
378165855ed8SLai Jiangshan 		mmu_sync_children(vcpu, sp, true);
3782531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
3783c50d8ae3SPaolo Bonzini 		return;
3784c50d8ae3SPaolo Bonzini 	}
3785c50d8ae3SPaolo Bonzini 
3786531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
3787c50d8ae3SPaolo Bonzini 
3788c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3789c50d8ae3SPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->pae_root[i];
3790c50d8ae3SPaolo Bonzini 
3791c834e5e4SSean Christopherson 		if (IS_VALID_PAE_ROOT(root)) {
37922ca3129eSSean Christopherson 			root &= SPTE_BASE_ADDR_MASK;
3793e47c4aeeSSean Christopherson 			sp = to_shadow_page(root);
379465855ed8SLai Jiangshan 			mmu_sync_children(vcpu, sp, true);
3795c50d8ae3SPaolo Bonzini 		}
3796c50d8ae3SPaolo Bonzini 	}
3797c50d8ae3SPaolo Bonzini 
3798531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
3799c50d8ae3SPaolo Bonzini }
3800c50d8ae3SPaolo Bonzini 
380161b05a9fSLai Jiangshan void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
380261b05a9fSLai Jiangshan {
380361b05a9fSLai Jiangshan 	unsigned long roots_to_free = 0;
380461b05a9fSLai Jiangshan 	int i;
380561b05a9fSLai Jiangshan 
380661b05a9fSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
380761b05a9fSLai Jiangshan 		if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
380861b05a9fSLai Jiangshan 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
380961b05a9fSLai Jiangshan 
381061b05a9fSLai Jiangshan 	/* sync prev_roots by simply freeing them */
38110c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
381261b05a9fSLai Jiangshan }
381361b05a9fSLai Jiangshan 
38141f5a21eeSLai Jiangshan static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
38155b22bbe7SLai Jiangshan 				  gpa_t vaddr, u64 access,
3816c50d8ae3SPaolo Bonzini 				  struct x86_exception *exception)
3817c50d8ae3SPaolo Bonzini {
3818c50d8ae3SPaolo Bonzini 	if (exception)
3819c50d8ae3SPaolo Bonzini 		exception->error_code = 0;
3820c59a0f57SLai Jiangshan 	return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
3821c50d8ae3SPaolo Bonzini }
3822c50d8ae3SPaolo Bonzini 
3823c50d8ae3SPaolo Bonzini static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3824c50d8ae3SPaolo Bonzini {
3825c50d8ae3SPaolo Bonzini 	/*
3826c50d8ae3SPaolo Bonzini 	 * A nested guest cannot use the MMIO cache if it is using nested
3827c50d8ae3SPaolo Bonzini 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3828c50d8ae3SPaolo Bonzini 	 */
3829c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
3830c50d8ae3SPaolo Bonzini 		return false;
3831c50d8ae3SPaolo Bonzini 
3832c50d8ae3SPaolo Bonzini 	if (direct)
3833c50d8ae3SPaolo Bonzini 		return vcpu_match_mmio_gpa(vcpu, addr);
3834c50d8ae3SPaolo Bonzini 
3835c50d8ae3SPaolo Bonzini 	return vcpu_match_mmio_gva(vcpu, addr);
3836c50d8ae3SPaolo Bonzini }
3837c50d8ae3SPaolo Bonzini 
383895fb5b02SBen Gardon /*
383995fb5b02SBen Gardon  * Return the level of the lowest level SPTE added to sptes.
384095fb5b02SBen Gardon  * That SPTE may be non-present.
3841c5c8c7c5SDavid Matlack  *
3842c5c8c7c5SDavid Matlack  * Must be called between walk_shadow_page_lockless_{begin,end}.
384395fb5b02SBen Gardon  */
384439b4d43eSSean Christopherson static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
3845c50d8ae3SPaolo Bonzini {
3846c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
38472aa07893SSean Christopherson 	int leaf = -1;
384895fb5b02SBen Gardon 	u64 spte;
3849c50d8ae3SPaolo Bonzini 
385039b4d43eSSean Christopherson 	for (shadow_walk_init(&iterator, vcpu, addr),
385139b4d43eSSean Christopherson 	     *root_level = iterator.level;
3852c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&iterator);
3853c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&iterator, spte)) {
385495fb5b02SBen Gardon 		leaf = iterator.level;
3855c50d8ae3SPaolo Bonzini 		spte = mmu_spte_get_lockless(iterator.sptep);
3856c50d8ae3SPaolo Bonzini 
3857dde81f94SSean Christopherson 		sptes[leaf] = spte;
385895fb5b02SBen Gardon 	}
385995fb5b02SBen Gardon 
386095fb5b02SBen Gardon 	return leaf;
386195fb5b02SBen Gardon }
386295fb5b02SBen Gardon 
38639aa41879SSean Christopherson /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
386495fb5b02SBen Gardon static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
386595fb5b02SBen Gardon {
3866dde81f94SSean Christopherson 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
386795fb5b02SBen Gardon 	struct rsvd_bits_validate *rsvd_check;
386839b4d43eSSean Christopherson 	int root, leaf, level;
386995fb5b02SBen Gardon 	bool reserved = false;
387095fb5b02SBen Gardon 
3871c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_begin(vcpu);
3872c5c8c7c5SDavid Matlack 
387363c0cac9SDavid Matlack 	if (is_tdp_mmu(vcpu->arch.mmu))
387439b4d43eSSean Christopherson 		leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
387595fb5b02SBen Gardon 	else
387639b4d43eSSean Christopherson 		leaf = get_walk(vcpu, addr, sptes, &root);
387795fb5b02SBen Gardon 
3878c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_end(vcpu);
3879c5c8c7c5SDavid Matlack 
38802aa07893SSean Christopherson 	if (unlikely(leaf < 0)) {
38812aa07893SSean Christopherson 		*sptep = 0ull;
38822aa07893SSean Christopherson 		return reserved;
38832aa07893SSean Christopherson 	}
38842aa07893SSean Christopherson 
38859aa41879SSean Christopherson 	*sptep = sptes[leaf];
38869aa41879SSean Christopherson 
38879aa41879SSean Christopherson 	/*
38889aa41879SSean Christopherson 	 * Skip reserved bits checks on the terminal leaf if it's not a valid
38899aa41879SSean Christopherson 	 * SPTE.  Note, this also (intentionally) skips MMIO SPTEs, which, by
38909aa41879SSean Christopherson 	 * design, always have reserved bits set.  The purpose of the checks is
38919aa41879SSean Christopherson 	 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
38929aa41879SSean Christopherson 	 */
38939aa41879SSean Christopherson 	if (!is_shadow_present_pte(sptes[leaf]))
38949aa41879SSean Christopherson 		leaf++;
389595fb5b02SBen Gardon 
389695fb5b02SBen Gardon 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
389795fb5b02SBen Gardon 
38989aa41879SSean Christopherson 	for (level = root; level >= leaf; level--)
3899961f8445SSean Christopherson 		reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
3900c50d8ae3SPaolo Bonzini 
3901c50d8ae3SPaolo Bonzini 	if (reserved) {
3902bb4cdf3aSSean Christopherson 		pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
3903c50d8ae3SPaolo Bonzini 		       __func__, addr);
390495fb5b02SBen Gardon 		for (level = root; level >= leaf; level--)
3905bb4cdf3aSSean Christopherson 			pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
3906bb4cdf3aSSean Christopherson 			       sptes[level], level,
3907961f8445SSean Christopherson 			       get_rsvd_bits(rsvd_check, sptes[level], level));
3908c50d8ae3SPaolo Bonzini 	}
3909ddce6208SSean Christopherson 
3910c50d8ae3SPaolo Bonzini 	return reserved;
3911c50d8ae3SPaolo Bonzini }
3912c50d8ae3SPaolo Bonzini 
3913c50d8ae3SPaolo Bonzini static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3914c50d8ae3SPaolo Bonzini {
3915c50d8ae3SPaolo Bonzini 	u64 spte;
3916c50d8ae3SPaolo Bonzini 	bool reserved;
3917c50d8ae3SPaolo Bonzini 
3918c50d8ae3SPaolo Bonzini 	if (mmio_info_in_cache(vcpu, addr, direct))
3919c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3920c50d8ae3SPaolo Bonzini 
392195fb5b02SBen Gardon 	reserved = get_mmio_spte(vcpu, addr, &spte);
3922c50d8ae3SPaolo Bonzini 	if (WARN_ON(reserved))
3923c50d8ae3SPaolo Bonzini 		return -EINVAL;
3924c50d8ae3SPaolo Bonzini 
3925c50d8ae3SPaolo Bonzini 	if (is_mmio_spte(spte)) {
3926c50d8ae3SPaolo Bonzini 		gfn_t gfn = get_mmio_spte_gfn(spte);
39270a2b64c5SBen Gardon 		unsigned int access = get_mmio_spte_access(spte);
3928c50d8ae3SPaolo Bonzini 
3929c50d8ae3SPaolo Bonzini 		if (!check_mmio_spte(vcpu, spte))
3930c50d8ae3SPaolo Bonzini 			return RET_PF_INVALID;
3931c50d8ae3SPaolo Bonzini 
3932c50d8ae3SPaolo Bonzini 		if (direct)
3933c50d8ae3SPaolo Bonzini 			addr = 0;
3934c50d8ae3SPaolo Bonzini 
3935c50d8ae3SPaolo Bonzini 		trace_handle_mmio_page_fault(addr, gfn, access);
3936c50d8ae3SPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3937c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3938c50d8ae3SPaolo Bonzini 	}
3939c50d8ae3SPaolo Bonzini 
3940c50d8ae3SPaolo Bonzini 	/*
3941c50d8ae3SPaolo Bonzini 	 * If the page table is zapped by other cpus, let CPU fault again on
3942c50d8ae3SPaolo Bonzini 	 * the address.
3943c50d8ae3SPaolo Bonzini 	 */
3944c50d8ae3SPaolo Bonzini 	return RET_PF_RETRY;
3945c50d8ae3SPaolo Bonzini }
3946c50d8ae3SPaolo Bonzini 
3947c50d8ae3SPaolo Bonzini static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3948b8a5d551SPaolo Bonzini 					 struct kvm_page_fault *fault)
3949c50d8ae3SPaolo Bonzini {
3950b8a5d551SPaolo Bonzini 	if (unlikely(fault->rsvd))
3951c50d8ae3SPaolo Bonzini 		return false;
3952c50d8ae3SPaolo Bonzini 
3953b8a5d551SPaolo Bonzini 	if (!fault->present || !fault->write)
3954c50d8ae3SPaolo Bonzini 		return false;
3955c50d8ae3SPaolo Bonzini 
3956c50d8ae3SPaolo Bonzini 	/*
3957c50d8ae3SPaolo Bonzini 	 * guest is writing the page which is write tracked which can
3958c50d8ae3SPaolo Bonzini 	 * not be fixed by page fault handler.
3959c50d8ae3SPaolo Bonzini 	 */
39609d395a0aSBen Gardon 	if (kvm_slot_page_track_is_active(vcpu->kvm, fault->slot, fault->gfn, KVM_PAGE_TRACK_WRITE))
3961c50d8ae3SPaolo Bonzini 		return true;
3962c50d8ae3SPaolo Bonzini 
3963c50d8ae3SPaolo Bonzini 	return false;
3964c50d8ae3SPaolo Bonzini }
3965c50d8ae3SPaolo Bonzini 
3966c50d8ae3SPaolo Bonzini static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3967c50d8ae3SPaolo Bonzini {
3968c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
3969c50d8ae3SPaolo Bonzini 	u64 spte;
3970c50d8ae3SPaolo Bonzini 
3971c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
39723e44dce4SLai Jiangshan 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
3973c50d8ae3SPaolo Bonzini 		clear_sp_write_flooding_count(iterator.sptep);
3974c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3975c50d8ae3SPaolo Bonzini }
3976c50d8ae3SPaolo Bonzini 
39776f3c1fc5SLiang Zhang static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
39786f3c1fc5SLiang Zhang {
39796f3c1fc5SLiang Zhang 	/* make sure the token value is not 0 */
39806f3c1fc5SLiang Zhang 	u32 id = vcpu->arch.apf.id;
39816f3c1fc5SLiang Zhang 
39826f3c1fc5SLiang Zhang 	if (id << 12 == 0)
39836f3c1fc5SLiang Zhang 		vcpu->arch.apf.id = 1;
39846f3c1fc5SLiang Zhang 
39856f3c1fc5SLiang Zhang 	return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
39866f3c1fc5SLiang Zhang }
39876f3c1fc5SLiang Zhang 
3988e8c22266SVitaly Kuznetsov static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
39899f1a8526SSean Christopherson 				    gfn_t gfn)
3990c50d8ae3SPaolo Bonzini {
3991c50d8ae3SPaolo Bonzini 	struct kvm_arch_async_pf arch;
3992c50d8ae3SPaolo Bonzini 
39936f3c1fc5SLiang Zhang 	arch.token = alloc_apf_token(vcpu);
3994c50d8ae3SPaolo Bonzini 	arch.gfn = gfn;
3995347a0d0dSPaolo Bonzini 	arch.direct_map = vcpu->arch.mmu->root_role.direct;
3996d8dd54e0SSean Christopherson 	arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
3997c50d8ae3SPaolo Bonzini 
39989f1a8526SSean Christopherson 	return kvm_setup_async_pf(vcpu, cr2_or_gpa,
39999f1a8526SSean Christopherson 				  kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4000c50d8ae3SPaolo Bonzini }
4001c50d8ae3SPaolo Bonzini 
40028a009d5bSSean Christopherson void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
40038a009d5bSSean Christopherson {
40048a009d5bSSean Christopherson 	int r;
40058a009d5bSSean Christopherson 
40068a009d5bSSean Christopherson 	if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
40078a009d5bSSean Christopherson 	      work->wakeup_all)
40088a009d5bSSean Christopherson 		return;
40098a009d5bSSean Christopherson 
40108a009d5bSSean Christopherson 	r = kvm_mmu_reload(vcpu);
40118a009d5bSSean Christopherson 	if (unlikely(r))
40128a009d5bSSean Christopherson 		return;
40138a009d5bSSean Christopherson 
40148a009d5bSSean Christopherson 	if (!vcpu->arch.mmu->root_role.direct &&
40158a009d5bSSean Christopherson 	      work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
40168a009d5bSSean Christopherson 		return;
40178a009d5bSSean Christopherson 
40188a009d5bSSean Christopherson 	kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
40198a009d5bSSean Christopherson }
40208a009d5bSSean Christopherson 
40215276c616SSean Christopherson static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4022c50d8ae3SPaolo Bonzini {
4023e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
4024c50d8ae3SPaolo Bonzini 	bool async;
4025c50d8ae3SPaolo Bonzini 
4026e0c37868SSean Christopherson 	/*
4027e0c37868SSean Christopherson 	 * Retry the page fault if the gfn hit a memslot that is being deleted
4028e0c37868SSean Christopherson 	 * or moved.  This ensures any existing SPTEs for the old memslot will
4029e0c37868SSean Christopherson 	 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4030e0c37868SSean Christopherson 	 */
4031e0c37868SSean Christopherson 	if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
40325276c616SSean Christopherson 		return RET_PF_RETRY;
4033e0c37868SSean Christopherson 
40349cc13d60SMaxim Levitsky 	if (!kvm_is_visible_memslot(slot)) {
4035c36b7150SPaolo Bonzini 		/* Don't expose private memslots to L2. */
40369cc13d60SMaxim Levitsky 		if (is_guest_mode(vcpu)) {
4037e710c5f6SDavid Matlack 			fault->slot = NULL;
40383647cd04SPaolo Bonzini 			fault->pfn = KVM_PFN_NOSLOT;
40393647cd04SPaolo Bonzini 			fault->map_writable = false;
40405276c616SSean Christopherson 			return RET_PF_CONTINUE;
4041c50d8ae3SPaolo Bonzini 		}
40429cc13d60SMaxim Levitsky 		/*
40439cc13d60SMaxim Levitsky 		 * If the APIC access page exists but is disabled, go directly
40449cc13d60SMaxim Levitsky 		 * to emulation without caching the MMIO access or creating a
40459cc13d60SMaxim Levitsky 		 * MMIO SPTE.  That way the cache doesn't need to be purged
40469cc13d60SMaxim Levitsky 		 * when the AVIC is re-enabled.
40479cc13d60SMaxim Levitsky 		 */
40489cc13d60SMaxim Levitsky 		if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
40495276c616SSean Christopherson 		    !kvm_apicv_activated(vcpu->kvm))
40505276c616SSean Christopherson 			return RET_PF_EMULATE;
40519cc13d60SMaxim Levitsky 	}
4052c50d8ae3SPaolo Bonzini 
4053c50d8ae3SPaolo Bonzini 	async = false;
40543647cd04SPaolo Bonzini 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, &async,
40553647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
40563647cd04SPaolo Bonzini 					  &fault->hva);
4057c50d8ae3SPaolo Bonzini 	if (!async)
40585276c616SSean Christopherson 		return RET_PF_CONTINUE; /* *pfn has correct page already */
4059c50d8ae3SPaolo Bonzini 
40602839180cSPaolo Bonzini 	if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
40613647cd04SPaolo Bonzini 		trace_kvm_try_async_get_page(fault->addr, fault->gfn);
40623647cd04SPaolo Bonzini 		if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
40633647cd04SPaolo Bonzini 			trace_kvm_async_pf_doublefault(fault->addr, fault->gfn);
4064c50d8ae3SPaolo Bonzini 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
40655276c616SSean Christopherson 			return RET_PF_RETRY;
40665276c616SSean Christopherson 		} else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn)) {
40675276c616SSean Christopherson 			return RET_PF_RETRY;
40685276c616SSean Christopherson 		}
4069c50d8ae3SPaolo Bonzini 	}
4070c50d8ae3SPaolo Bonzini 
40713647cd04SPaolo Bonzini 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, NULL,
40723647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
40733647cd04SPaolo Bonzini 					  &fault->hva);
40745276c616SSean Christopherson 	return RET_PF_CONTINUE;
4075c50d8ae3SPaolo Bonzini }
4076c50d8ae3SPaolo Bonzini 
4077a955cad8SSean Christopherson /*
4078a955cad8SSean Christopherson  * Returns true if the page fault is stale and needs to be retried, i.e. if the
4079a955cad8SSean Christopherson  * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4080a955cad8SSean Christopherson  */
4081a955cad8SSean Christopherson static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4082a955cad8SSean Christopherson 				struct kvm_page_fault *fault, int mmu_seq)
4083a955cad8SSean Christopherson {
4084b9e5603cSPaolo Bonzini 	struct kvm_mmu_page *sp = to_shadow_page(vcpu->arch.mmu->root.hpa);
408518c841e1SSean Christopherson 
408618c841e1SSean Christopherson 	/* Special roots, e.g. pae_root, are not backed by shadow pages. */
408718c841e1SSean Christopherson 	if (sp && is_obsolete_sp(vcpu->kvm, sp))
408818c841e1SSean Christopherson 		return true;
408918c841e1SSean Christopherson 
409018c841e1SSean Christopherson 	/*
409118c841e1SSean Christopherson 	 * Roots without an associated shadow page are considered invalid if
409218c841e1SSean Christopherson 	 * there is a pending request to free obsolete roots.  The request is
409318c841e1SSean Christopherson 	 * only a hint that the current root _may_ be obsolete and needs to be
409418c841e1SSean Christopherson 	 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
409518c841e1SSean Christopherson 	 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
409618c841e1SSean Christopherson 	 * to reload even if no vCPU is actively using the root.
409718c841e1SSean Christopherson 	 */
4098527d5cd7SSean Christopherson 	if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4099a955cad8SSean Christopherson 		return true;
4100a955cad8SSean Christopherson 
4101a955cad8SSean Christopherson 	return fault->slot &&
4102a955cad8SSean Christopherson 	       mmu_notifier_retry_hva(vcpu->kvm, mmu_seq, fault->hva);
4103a955cad8SSean Christopherson }
4104a955cad8SSean Christopherson 
41054326e57eSPaolo Bonzini static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4106c50d8ae3SPaolo Bonzini {
410763c0cac9SDavid Matlack 	bool is_tdp_mmu_fault = is_tdp_mmu(vcpu->arch.mmu);
4108c50d8ae3SPaolo Bonzini 
41090f90e1c1SSean Christopherson 	unsigned long mmu_seq;
411083f06fa7SSean Christopherson 	int r;
4111c50d8ae3SPaolo Bonzini 
41123c8ad5a6SPaolo Bonzini 	fault->gfn = fault->addr >> PAGE_SHIFT;
4113e710c5f6SDavid Matlack 	fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);
4114e710c5f6SDavid Matlack 
4115b8a5d551SPaolo Bonzini 	if (page_fault_handle_page_track(vcpu, fault))
4116c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4117c50d8ae3SPaolo Bonzini 
41183c8ad5a6SPaolo Bonzini 	r = fast_page_fault(vcpu, fault);
4119c4371c2aSSean Christopherson 	if (r != RET_PF_INVALID)
4120c4371c2aSSean Christopherson 		return r;
412183291445SSean Christopherson 
4122378f5cd6SSean Christopherson 	r = mmu_topup_memory_caches(vcpu, false);
4123c50d8ae3SPaolo Bonzini 	if (r)
4124c50d8ae3SPaolo Bonzini 		return r;
4125c50d8ae3SPaolo Bonzini 
4126367fd790SSean Christopherson 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
4127367fd790SSean Christopherson 	smp_rmb();
4128367fd790SSean Christopherson 
41295276c616SSean Christopherson 	r = kvm_faultin_pfn(vcpu, fault);
41305276c616SSean Christopherson 	if (r != RET_PF_CONTINUE)
41318f32d5e5SMaxim Levitsky 		return r;
4132367fd790SSean Christopherson 
41335276c616SSean Christopherson 	r = handle_abnormal_pfn(vcpu, fault, ACC_ALL);
41345276c616SSean Christopherson 	if (r != RET_PF_CONTINUE)
4135367fd790SSean Christopherson 		return r;
4136367fd790SSean Christopherson 
4137367fd790SSean Christopherson 	r = RET_PF_RETRY;
4138a2855afcSBen Gardon 
41390b873fd7SDavid Matlack 	if (is_tdp_mmu_fault)
4140a2855afcSBen Gardon 		read_lock(&vcpu->kvm->mmu_lock);
4141a2855afcSBen Gardon 	else
4142531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
4143a2855afcSBen Gardon 
4144a955cad8SSean Christopherson 	if (is_page_fault_stale(vcpu, fault, mmu_seq))
4145367fd790SSean Christopherson 		goto out_unlock;
4146a955cad8SSean Christopherson 
41477bd7ded6SSean Christopherson 	r = make_mmu_pages_available(vcpu);
41487bd7ded6SSean Christopherson 	if (r)
4149367fd790SSean Christopherson 		goto out_unlock;
4150bb18842eSBen Gardon 
41510b873fd7SDavid Matlack 	if (is_tdp_mmu_fault)
41522f6305ddSPaolo Bonzini 		r = kvm_tdp_mmu_map(vcpu, fault);
4153bb18842eSBen Gardon 	else
415443b74355SPaolo Bonzini 		r = __direct_map(vcpu, fault);
41550f90e1c1SSean Christopherson 
4156367fd790SSean Christopherson out_unlock:
41570b873fd7SDavid Matlack 	if (is_tdp_mmu_fault)
4158a2855afcSBen Gardon 		read_unlock(&vcpu->kvm->mmu_lock);
4159a2855afcSBen Gardon 	else
4160531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
41613647cd04SPaolo Bonzini 	kvm_release_pfn_clean(fault->pfn);
4162367fd790SSean Christopherson 	return r;
4163c50d8ae3SPaolo Bonzini }
4164c50d8ae3SPaolo Bonzini 
4165c501040aSPaolo Bonzini static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4166c501040aSPaolo Bonzini 				struct kvm_page_fault *fault)
41670f90e1c1SSean Christopherson {
41684326e57eSPaolo Bonzini 	pgprintk("%s: gva %lx error %x\n", __func__, fault->addr, fault->error_code);
41690f90e1c1SSean Christopherson 
41700f90e1c1SSean Christopherson 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
41714326e57eSPaolo Bonzini 	fault->max_level = PG_LEVEL_2M;
41724326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
41730f90e1c1SSean Christopherson }
41740f90e1c1SSean Christopherson 
4175c50d8ae3SPaolo Bonzini int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4176c50d8ae3SPaolo Bonzini 				u64 fault_address, char *insn, int insn_len)
4177c50d8ae3SPaolo Bonzini {
4178c50d8ae3SPaolo Bonzini 	int r = 1;
41799ce372b3SVitaly Kuznetsov 	u32 flags = vcpu->arch.apf.host_apf_flags;
4180c50d8ae3SPaolo Bonzini 
4181736c291cSSean Christopherson #ifndef CONFIG_X86_64
4182736c291cSSean Christopherson 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4183736c291cSSean Christopherson 	if (WARN_ON_ONCE(fault_address >> 32))
4184736c291cSSean Christopherson 		return -EFAULT;
4185736c291cSSean Christopherson #endif
4186736c291cSSean Christopherson 
4187c50d8ae3SPaolo Bonzini 	vcpu->arch.l1tf_flush_l1d = true;
41889ce372b3SVitaly Kuznetsov 	if (!flags) {
4189c50d8ae3SPaolo Bonzini 		trace_kvm_page_fault(fault_address, error_code);
4190c50d8ae3SPaolo Bonzini 
4191c50d8ae3SPaolo Bonzini 		if (kvm_event_needs_reinjection(vcpu))
4192c50d8ae3SPaolo Bonzini 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4193c50d8ae3SPaolo Bonzini 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4194c50d8ae3SPaolo Bonzini 				insn_len);
41959ce372b3SVitaly Kuznetsov 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
419668fd66f1SVitaly Kuznetsov 		vcpu->arch.apf.host_apf_flags = 0;
4197c50d8ae3SPaolo Bonzini 		local_irq_disable();
41986bca69adSThomas Gleixner 		kvm_async_pf_task_wait_schedule(fault_address);
4199c50d8ae3SPaolo Bonzini 		local_irq_enable();
42009ce372b3SVitaly Kuznetsov 	} else {
42019ce372b3SVitaly Kuznetsov 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4202c50d8ae3SPaolo Bonzini 	}
42039ce372b3SVitaly Kuznetsov 
4204c50d8ae3SPaolo Bonzini 	return r;
4205c50d8ae3SPaolo Bonzini }
4206c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4207c50d8ae3SPaolo Bonzini 
4208c501040aSPaolo Bonzini int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4209c50d8ae3SPaolo Bonzini {
42104326e57eSPaolo Bonzini 	while (fault->max_level > PG_LEVEL_4K) {
42114326e57eSPaolo Bonzini 		int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
42124326e57eSPaolo Bonzini 		gfn_t base = (fault->addr >> PAGE_SHIFT) & ~(page_num - 1);
4213c50d8ae3SPaolo Bonzini 
4214cb9b88c6SSean Christopherson 		if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4215cb9b88c6SSean Christopherson 			break;
42164326e57eSPaolo Bonzini 
42174326e57eSPaolo Bonzini 		--fault->max_level;
4218c50d8ae3SPaolo Bonzini 	}
4219c50d8ae3SPaolo Bonzini 
42204326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
4221c50d8ae3SPaolo Bonzini }
4222c50d8ae3SPaolo Bonzini 
422384a16226SSean Christopherson static void nonpaging_init_context(struct kvm_mmu *context)
4224c50d8ae3SPaolo Bonzini {
4225c50d8ae3SPaolo Bonzini 	context->page_fault = nonpaging_page_fault;
4226c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4227c50d8ae3SPaolo Bonzini 	context->sync_page = nonpaging_sync_page;
42285efac074SPaolo Bonzini 	context->invlpg = NULL;
4229c50d8ae3SPaolo Bonzini }
4230c50d8ae3SPaolo Bonzini 
4231be01e8e2SSean Christopherson static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
42320be44352SSean Christopherson 				  union kvm_mmu_page_role role)
42330be44352SSean Christopherson {
4234be01e8e2SSean Christopherson 	return (role.direct || pgd == root->pgd) &&
42355499ea73SPaolo Bonzini 	       VALID_PAGE(root->hpa) &&
4236e47c4aeeSSean Christopherson 	       role.word == to_shadow_page(root->hpa)->role.word;
42370be44352SSean Christopherson }
42380be44352SSean Christopherson 
4239c50d8ae3SPaolo Bonzini /*
42405499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available,
42415499ea73SPaolo Bonzini  * and insert the current root as the MRU in the cache.
42425499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root and
42435499ea73SPaolo Bonzini  * true is returned.
42445499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid, the LRU root is
42455499ea73SPaolo Bonzini  * evicted to make room for the current root, and false is returned.
4246c50d8ae3SPaolo Bonzini  */
42475499ea73SPaolo Bonzini static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
42485499ea73SPaolo Bonzini 					      gpa_t new_pgd,
4249c50d8ae3SPaolo Bonzini 					      union kvm_mmu_page_role new_role)
4250c50d8ae3SPaolo Bonzini {
4251c50d8ae3SPaolo Bonzini 	uint i;
4252c50d8ae3SPaolo Bonzini 
4253b9e5603cSPaolo Bonzini 	if (is_root_usable(&mmu->root, new_pgd, new_role))
42540be44352SSean Christopherson 		return true;
42550be44352SSean Christopherson 
4256c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
42575499ea73SPaolo Bonzini 		/*
42585499ea73SPaolo Bonzini 		 * The swaps end up rotating the cache like this:
42595499ea73SPaolo Bonzini 		 *   C   0 1 2 3   (on entry to the function)
42605499ea73SPaolo Bonzini 		 *   0   C 1 2 3
42615499ea73SPaolo Bonzini 		 *   1   C 0 2 3
42625499ea73SPaolo Bonzini 		 *   2   C 0 1 3
42635499ea73SPaolo Bonzini 		 *   3   C 0 1 2   (on exit from the loop)
42645499ea73SPaolo Bonzini 		 */
4265b9e5603cSPaolo Bonzini 		swap(mmu->root, mmu->prev_roots[i]);
4266b9e5603cSPaolo Bonzini 		if (is_root_usable(&mmu->root, new_pgd, new_role))
42675499ea73SPaolo Bonzini 			return true;
4268c50d8ae3SPaolo Bonzini 	}
4269c50d8ae3SPaolo Bonzini 
42705499ea73SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
42715499ea73SPaolo Bonzini 	return false;
4272c50d8ae3SPaolo Bonzini }
4273c50d8ae3SPaolo Bonzini 
4274c50d8ae3SPaolo Bonzini /*
42755499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available.
42765499ea73SPaolo Bonzini  * On entry, mmu->root is invalid.
42775499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
42785499ea73SPaolo Bonzini  * of the cache becomes invalid, and true is returned.
42795499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid and false is returned.
42805499ea73SPaolo Bonzini  */
42815499ea73SPaolo Bonzini static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
42825499ea73SPaolo Bonzini 					     gpa_t new_pgd,
42835499ea73SPaolo Bonzini 					     union kvm_mmu_page_role new_role)
42845499ea73SPaolo Bonzini {
42855499ea73SPaolo Bonzini 	uint i;
42865499ea73SPaolo Bonzini 
42875499ea73SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
42885499ea73SPaolo Bonzini 		if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
42895499ea73SPaolo Bonzini 			goto hit;
42905499ea73SPaolo Bonzini 
42915499ea73SPaolo Bonzini 	return false;
42925499ea73SPaolo Bonzini 
42935499ea73SPaolo Bonzini hit:
42945499ea73SPaolo Bonzini 	swap(mmu->root, mmu->prev_roots[i]);
42955499ea73SPaolo Bonzini 	/* Bubble up the remaining roots.  */
42965499ea73SPaolo Bonzini 	for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
42975499ea73SPaolo Bonzini 		mmu->prev_roots[i] = mmu->prev_roots[i + 1];
42985499ea73SPaolo Bonzini 	mmu->prev_roots[i].hpa = INVALID_PAGE;
42995499ea73SPaolo Bonzini 	return true;
43005499ea73SPaolo Bonzini }
43015499ea73SPaolo Bonzini 
43025499ea73SPaolo Bonzini static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
43035499ea73SPaolo Bonzini 			    gpa_t new_pgd, union kvm_mmu_page_role new_role)
43045499ea73SPaolo Bonzini {
43055499ea73SPaolo Bonzini 	/*
43065499ea73SPaolo Bonzini 	 * For now, limit the caching to 64-bit hosts+VMs in order to avoid
4307c50d8ae3SPaolo Bonzini 	 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4308c50d8ae3SPaolo Bonzini 	 * later if necessary.
4309c50d8ae3SPaolo Bonzini 	 */
43105499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa) && !to_shadow_page(mmu->root.hpa))
43115499ea73SPaolo Bonzini 		kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4312c50d8ae3SPaolo Bonzini 
43135499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa))
43145499ea73SPaolo Bonzini 		return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
43155499ea73SPaolo Bonzini 	else
43165499ea73SPaolo Bonzini 		return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4317c50d8ae3SPaolo Bonzini }
4318c50d8ae3SPaolo Bonzini 
4319d2e5f333SPaolo Bonzini void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4320c50d8ae3SPaolo Bonzini {
43210c1c92f1SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
43227a458f0eSPaolo Bonzini 	union kvm_mmu_page_role new_role = mmu->root_role;
43230c1c92f1SPaolo Bonzini 
43245499ea73SPaolo Bonzini 	if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role)) {
43255499ea73SPaolo Bonzini 		/* kvm_mmu_ensure_valid_pgd will set up a new root.  */
4326b869855bSSean Christopherson 		return;
4327c50d8ae3SPaolo Bonzini 	}
4328c50d8ae3SPaolo Bonzini 
4329c50d8ae3SPaolo Bonzini 	/*
4330b869855bSSean Christopherson 	 * It's possible that the cached previous root page is obsolete because
4331b869855bSSean Christopherson 	 * of a change in the MMU generation number. However, changing the
4332527d5cd7SSean Christopherson 	 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4333527d5cd7SSean Christopherson 	 * which will free the root set here and allocate a new one.
4334b869855bSSean Christopherson 	 */
4335b869855bSSean Christopherson 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4336b869855bSSean Christopherson 
4337b5129100SSean Christopherson 	if (force_flush_and_sync_on_reuse) {
4338b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4339b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4340b5129100SSean Christopherson 	}
4341b869855bSSean Christopherson 
4342b869855bSSean Christopherson 	/*
4343b869855bSSean Christopherson 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4344b869855bSSean Christopherson 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
4345b869855bSSean Christopherson 	 * valid. So clear any cached MMIO info even when we don't need to sync
4346b869855bSSean Christopherson 	 * the shadow page tables.
4347c50d8ae3SPaolo Bonzini 	 */
4348c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4349c50d8ae3SPaolo Bonzini 
4350daa5b6c1SBen Gardon 	/*
4351daa5b6c1SBen Gardon 	 * If this is a direct root page, it doesn't have a write flooding
4352daa5b6c1SBen Gardon 	 * count. Otherwise, clear the write flooding count.
4353daa5b6c1SBen Gardon 	 */
4354daa5b6c1SBen Gardon 	if (!new_role.direct)
4355daa5b6c1SBen Gardon 		__clear_sp_write_flooding_count(
4356b9e5603cSPaolo Bonzini 				to_shadow_page(vcpu->arch.mmu->root.hpa));
4357c50d8ae3SPaolo Bonzini }
4358be01e8e2SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4359c50d8ae3SPaolo Bonzini 
4360c50d8ae3SPaolo Bonzini static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4361c50d8ae3SPaolo Bonzini {
4362c50d8ae3SPaolo Bonzini 	return kvm_read_cr3(vcpu);
4363c50d8ae3SPaolo Bonzini }
4364c50d8ae3SPaolo Bonzini 
4365c50d8ae3SPaolo Bonzini static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4366c3e5e415SLai Jiangshan 			   unsigned int access)
4367c50d8ae3SPaolo Bonzini {
4368c50d8ae3SPaolo Bonzini 	if (unlikely(is_mmio_spte(*sptep))) {
4369c50d8ae3SPaolo Bonzini 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4370c50d8ae3SPaolo Bonzini 			mmu_spte_clear_no_track(sptep);
4371c50d8ae3SPaolo Bonzini 			return true;
4372c50d8ae3SPaolo Bonzini 		}
4373c50d8ae3SPaolo Bonzini 
4374c50d8ae3SPaolo Bonzini 		mark_mmio_spte(vcpu, sptep, gfn, access);
4375c50d8ae3SPaolo Bonzini 		return true;
4376c50d8ae3SPaolo Bonzini 	}
4377c50d8ae3SPaolo Bonzini 
4378c50d8ae3SPaolo Bonzini 	return false;
4379c50d8ae3SPaolo Bonzini }
4380c50d8ae3SPaolo Bonzini 
4381c50d8ae3SPaolo Bonzini #define PTTYPE_EPT 18 /* arbitrary */
4382c50d8ae3SPaolo Bonzini #define PTTYPE PTTYPE_EPT
4383c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4384c50d8ae3SPaolo Bonzini #undef PTTYPE
4385c50d8ae3SPaolo Bonzini 
4386c50d8ae3SPaolo Bonzini #define PTTYPE 64
4387c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4388c50d8ae3SPaolo Bonzini #undef PTTYPE
4389c50d8ae3SPaolo Bonzini 
4390c50d8ae3SPaolo Bonzini #define PTTYPE 32
4391c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4392c50d8ae3SPaolo Bonzini #undef PTTYPE
4393c50d8ae3SPaolo Bonzini 
4394c50d8ae3SPaolo Bonzini static void
4395b705a277SSean Christopherson __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
43965b7f575cSSean Christopherson 			u64 pa_bits_rsvd, int level, bool nx, bool gbpages,
4397c50d8ae3SPaolo Bonzini 			bool pse, bool amd)
4398c50d8ae3SPaolo Bonzini {
4399c50d8ae3SPaolo Bonzini 	u64 gbpages_bit_rsvd = 0;
4400c50d8ae3SPaolo Bonzini 	u64 nonleaf_bit8_rsvd = 0;
44015b7f575cSSean Christopherson 	u64 high_bits_rsvd;
4402c50d8ae3SPaolo Bonzini 
4403c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = 0;
4404c50d8ae3SPaolo Bonzini 
4405c50d8ae3SPaolo Bonzini 	if (!gbpages)
4406c50d8ae3SPaolo Bonzini 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4407c50d8ae3SPaolo Bonzini 
44085b7f575cSSean Christopherson 	if (level == PT32E_ROOT_LEVEL)
44095b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
44105b7f575cSSean Christopherson 	else
44115b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
44125b7f575cSSean Christopherson 
44135b7f575cSSean Christopherson 	/* Note, NX doesn't exist in PDPTEs, this is handled below. */
44145b7f575cSSean Christopherson 	if (!nx)
44155b7f575cSSean Christopherson 		high_bits_rsvd |= rsvd_bits(63, 63);
44165b7f575cSSean Christopherson 
4417c50d8ae3SPaolo Bonzini 	/*
4418c50d8ae3SPaolo Bonzini 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4419c50d8ae3SPaolo Bonzini 	 * leaf entries) on AMD CPUs only.
4420c50d8ae3SPaolo Bonzini 	 */
4421c50d8ae3SPaolo Bonzini 	if (amd)
4422c50d8ae3SPaolo Bonzini 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4423c50d8ae3SPaolo Bonzini 
4424c50d8ae3SPaolo Bonzini 	switch (level) {
4425c50d8ae3SPaolo Bonzini 	case PT32_ROOT_LEVEL:
4426c50d8ae3SPaolo Bonzini 		/* no rsvd bits for 2 level 4K page table entries */
4427c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4428c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4429c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4430c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4431c50d8ae3SPaolo Bonzini 
4432c50d8ae3SPaolo Bonzini 		if (!pse) {
4433c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4434c50d8ae3SPaolo Bonzini 			break;
4435c50d8ae3SPaolo Bonzini 		}
4436c50d8ae3SPaolo Bonzini 
4437c50d8ae3SPaolo Bonzini 		if (is_cpuid_PSE36())
4438c50d8ae3SPaolo Bonzini 			/* 36bits PSE 4MB page */
4439c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4440c50d8ae3SPaolo Bonzini 		else
4441c50d8ae3SPaolo Bonzini 			/* 32 bits PSE 4MB page */
4442c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4443c50d8ae3SPaolo Bonzini 		break;
4444c50d8ae3SPaolo Bonzini 	case PT32E_ROOT_LEVEL:
44455b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
44465b7f575cSSean Christopherson 						   high_bits_rsvd |
44475b7f575cSSean Christopherson 						   rsvd_bits(5, 8) |
44485b7f575cSSean Christopherson 						   rsvd_bits(1, 2);	/* PDPTE */
44495b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;	/* PDE */
44505b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;	/* PTE */
44515b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4452c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20);	/* large page */
4453c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4454c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4455c50d8ae3SPaolo Bonzini 		break;
4456c50d8ae3SPaolo Bonzini 	case PT64_ROOT_5LEVEL:
44575b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
44585b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
44595b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
4460c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][4] =
4461c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][4];
4462df561f66SGustavo A. R. Silva 		fallthrough;
4463c50d8ae3SPaolo Bonzini 	case PT64_ROOT_4LEVEL:
44645b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
44655b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
44665b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
44675b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
44685b7f575cSSean Christopherson 						   gbpages_bit_rsvd;
44695b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
44705b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4471c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][3] =
4472c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][3];
44735b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
44745b7f575cSSean Christopherson 						   gbpages_bit_rsvd |
4475c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 29);
44765b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4477c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20); /* large page */
4478c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4479c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4480c50d8ae3SPaolo Bonzini 		break;
4481c50d8ae3SPaolo Bonzini 	}
4482c50d8ae3SPaolo Bonzini }
4483c50d8ae3SPaolo Bonzini 
448427de9250SSean Christopherson static bool guest_can_use_gbpages(struct kvm_vcpu *vcpu)
448527de9250SSean Christopherson {
448627de9250SSean Christopherson 	/*
448727de9250SSean Christopherson 	 * If TDP is enabled, let the guest use GBPAGES if they're supported in
448827de9250SSean Christopherson 	 * hardware.  The hardware page walker doesn't let KVM disable GBPAGES,
448927de9250SSean Christopherson 	 * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
449027de9250SSean Christopherson 	 * walk for performance and complexity reasons.  Not to mention KVM
449127de9250SSean Christopherson 	 * _can't_ solve the problem because GVA->GPA walks aren't visible to
449227de9250SSean Christopherson 	 * KVM once a TDP translation is installed.  Mimic hardware behavior so
449327de9250SSean Christopherson 	 * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
449427de9250SSean Christopherson 	 */
449527de9250SSean Christopherson 	return tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
449627de9250SSean Christopherson 			     guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES);
449727de9250SSean Christopherson }
449827de9250SSean Christopherson 
4499c919e881SKai Huang static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4500c50d8ae3SPaolo Bonzini 					struct kvm_mmu *context)
4501c50d8ae3SPaolo Bonzini {
4502b705a277SSean Christopherson 	__reset_rsvds_bits_mask(&context->guest_rsvd_check,
45035b7f575cSSean Christopherson 				vcpu->arch.reserved_gpa_bits,
45044d25502aSPaolo Bonzini 				context->cpu_role.base.level, is_efer_nx(context),
450527de9250SSean Christopherson 				guest_can_use_gbpages(vcpu),
45064e9c0d80SSean Christopherson 				is_cr4_pse(context),
450723493d0aSSean Christopherson 				guest_cpuid_is_amd_or_hygon(vcpu));
4508c50d8ae3SPaolo Bonzini }
4509c50d8ae3SPaolo Bonzini 
4510c50d8ae3SPaolo Bonzini static void
4511c50d8ae3SPaolo Bonzini __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
451284ea5c09SLai Jiangshan 			    u64 pa_bits_rsvd, bool execonly, int huge_page_level)
4513c50d8ae3SPaolo Bonzini {
45145b7f575cSSean Christopherson 	u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
451584ea5c09SLai Jiangshan 	u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
4516c50d8ae3SPaolo Bonzini 	u64 bad_mt_xwr;
4517c50d8ae3SPaolo Bonzini 
451884ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_1G)
451984ea5c09SLai Jiangshan 		large_1g_rsvd = rsvd_bits(7, 7);
452084ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_2M)
452184ea5c09SLai Jiangshan 		large_2m_rsvd = rsvd_bits(7, 7);
452284ea5c09SLai Jiangshan 
45235b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
45245b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
452584ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
452684ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
45275b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4528c50d8ae3SPaolo Bonzini 
4529c50d8ae3SPaolo Bonzini 	/* large page */
4530c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4531c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
453284ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
453384ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
4534c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4535c50d8ae3SPaolo Bonzini 
4536c50d8ae3SPaolo Bonzini 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
4537c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
4538c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
4539c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
4540c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
4541c50d8ae3SPaolo Bonzini 	if (!execonly) {
4542c50d8ae3SPaolo Bonzini 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
4543c50d8ae3SPaolo Bonzini 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4544c50d8ae3SPaolo Bonzini 	}
4545c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
4546c50d8ae3SPaolo Bonzini }
4547c50d8ae3SPaolo Bonzini 
4548c50d8ae3SPaolo Bonzini static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
454984ea5c09SLai Jiangshan 		struct kvm_mmu *context, bool execonly, int huge_page_level)
4550c50d8ae3SPaolo Bonzini {
4551c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
455284ea5c09SLai Jiangshan 				    vcpu->arch.reserved_gpa_bits, execonly,
455384ea5c09SLai Jiangshan 				    huge_page_level);
4554c50d8ae3SPaolo Bonzini }
4555c50d8ae3SPaolo Bonzini 
45566f8e65a6SSean Christopherson static inline u64 reserved_hpa_bits(void)
45576f8e65a6SSean Christopherson {
45586f8e65a6SSean Christopherson 	return rsvd_bits(shadow_phys_bits, 63);
45596f8e65a6SSean Christopherson }
45606f8e65a6SSean Christopherson 
4561c50d8ae3SPaolo Bonzini /*
4562c50d8ae3SPaolo Bonzini  * the page table on host is the shadow page table for the page
4563c50d8ae3SPaolo Bonzini  * table in guest or amd nested guest, its mmu features completely
4564c50d8ae3SPaolo Bonzini  * follow the features in guest.
4565c50d8ae3SPaolo Bonzini  */
456616be1d12SSean Christopherson static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
456716be1d12SSean Christopherson 					struct kvm_mmu *context)
4568c50d8ae3SPaolo Bonzini {
45698c985b2dSSean Christopherson 	/* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
45708c985b2dSSean Christopherson 	bool is_amd = true;
45718c985b2dSSean Christopherson 	/* KVM doesn't use 2-level page tables for the shadow MMU. */
45728c985b2dSSean Christopherson 	bool is_pse = false;
4573c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4574c50d8ae3SPaolo Bonzini 	int i;
4575c50d8ae3SPaolo Bonzini 
4576a972e29cSPaolo Bonzini 	WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
45778c985b2dSSean Christopherson 
4578c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4579b705a277SSean Christopherson 	__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4580a972e29cSPaolo Bonzini 				context->root_role.level,
45817a458f0eSPaolo Bonzini 				context->root_role.efer_nx,
458227de9250SSean Christopherson 				guest_can_use_gbpages(vcpu), is_pse, is_amd);
4583c50d8ae3SPaolo Bonzini 
4584c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4585c50d8ae3SPaolo Bonzini 		return;
4586c50d8ae3SPaolo Bonzini 
4587a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
4588e54f1ff2SKai Huang 		/*
4589e54f1ff2SKai Huang 		 * So far shadow_me_value is a constant during KVM's life
4590e54f1ff2SKai Huang 		 * time.  Bits in shadow_me_value are allowed to be set.
4591e54f1ff2SKai Huang 		 * Bits in shadow_me_mask but not in shadow_me_value are
4592e54f1ff2SKai Huang 		 * not allowed to be set.
4593e54f1ff2SKai Huang 		 */
4594e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
4595e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
4596e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
4597e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
4598c50d8ae3SPaolo Bonzini 	}
4599c50d8ae3SPaolo Bonzini 
4600c50d8ae3SPaolo Bonzini }
4601c50d8ae3SPaolo Bonzini 
4602c50d8ae3SPaolo Bonzini static inline bool boot_cpu_is_amd(void)
4603c50d8ae3SPaolo Bonzini {
4604c50d8ae3SPaolo Bonzini 	WARN_ON_ONCE(!tdp_enabled);
4605c50d8ae3SPaolo Bonzini 	return shadow_x_mask == 0;
4606c50d8ae3SPaolo Bonzini }
4607c50d8ae3SPaolo Bonzini 
4608c50d8ae3SPaolo Bonzini /*
4609c50d8ae3SPaolo Bonzini  * the direct page table on host, use as much mmu features as
4610c50d8ae3SPaolo Bonzini  * possible, however, kvm currently does not do execution-protection.
4611c50d8ae3SPaolo Bonzini  */
4612c50d8ae3SPaolo Bonzini static void
4613e8f6e738SJinrong Liang reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
4614c50d8ae3SPaolo Bonzini {
4615c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4616c50d8ae3SPaolo Bonzini 	int i;
4617c50d8ae3SPaolo Bonzini 
4618c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4619c50d8ae3SPaolo Bonzini 
4620c50d8ae3SPaolo Bonzini 	if (boot_cpu_is_amd())
4621b705a277SSean Christopherson 		__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4622a972e29cSPaolo Bonzini 					context->root_role.level, false,
4623c50d8ae3SPaolo Bonzini 					boot_cpu_has(X86_FEATURE_GBPAGES),
46248c985b2dSSean Christopherson 					false, true);
4625c50d8ae3SPaolo Bonzini 	else
4626c50d8ae3SPaolo Bonzini 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
462784ea5c09SLai Jiangshan 					    reserved_hpa_bits(), false,
462884ea5c09SLai Jiangshan 					    max_huge_page_level);
4629c50d8ae3SPaolo Bonzini 
4630c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4631c50d8ae3SPaolo Bonzini 		return;
4632c50d8ae3SPaolo Bonzini 
4633a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
4634c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4635c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4636c50d8ae3SPaolo Bonzini 	}
4637c50d8ae3SPaolo Bonzini }
4638c50d8ae3SPaolo Bonzini 
4639c50d8ae3SPaolo Bonzini /*
4640c50d8ae3SPaolo Bonzini  * as the comments in reset_shadow_zero_bits_mask() except it
4641c50d8ae3SPaolo Bonzini  * is the shadow page table for intel nested guest.
4642c50d8ae3SPaolo Bonzini  */
4643c50d8ae3SPaolo Bonzini static void
4644e8f6e738SJinrong Liang reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
4645c50d8ae3SPaolo Bonzini {
4646c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
464784ea5c09SLai Jiangshan 				    reserved_hpa_bits(), execonly,
464884ea5c09SLai Jiangshan 				    max_huge_page_level);
4649c50d8ae3SPaolo Bonzini }
4650c50d8ae3SPaolo Bonzini 
4651c50d8ae3SPaolo Bonzini #define BYTE_MASK(access) \
4652c50d8ae3SPaolo Bonzini 	((1 & (access) ? 2 : 0) | \
4653c50d8ae3SPaolo Bonzini 	 (2 & (access) ? 4 : 0) | \
4654c50d8ae3SPaolo Bonzini 	 (3 & (access) ? 8 : 0) | \
4655c50d8ae3SPaolo Bonzini 	 (4 & (access) ? 16 : 0) | \
4656c50d8ae3SPaolo Bonzini 	 (5 & (access) ? 32 : 0) | \
4657c50d8ae3SPaolo Bonzini 	 (6 & (access) ? 64 : 0) | \
4658c50d8ae3SPaolo Bonzini 	 (7 & (access) ? 128 : 0))
4659c50d8ae3SPaolo Bonzini 
4660c50d8ae3SPaolo Bonzini 
4661c596f147SSean Christopherson static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
4662c50d8ae3SPaolo Bonzini {
4663c50d8ae3SPaolo Bonzini 	unsigned byte;
4664c50d8ae3SPaolo Bonzini 
4665c50d8ae3SPaolo Bonzini 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4666c50d8ae3SPaolo Bonzini 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4667c50d8ae3SPaolo Bonzini 	const u8 u = BYTE_MASK(ACC_USER_MASK);
4668c50d8ae3SPaolo Bonzini 
4669c596f147SSean Christopherson 	bool cr4_smep = is_cr4_smep(mmu);
4670c596f147SSean Christopherson 	bool cr4_smap = is_cr4_smap(mmu);
4671c596f147SSean Christopherson 	bool cr0_wp = is_cr0_wp(mmu);
467290599c28SSean Christopherson 	bool efer_nx = is_efer_nx(mmu);
4673c50d8ae3SPaolo Bonzini 
4674c50d8ae3SPaolo Bonzini 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4675c50d8ae3SPaolo Bonzini 		unsigned pfec = byte << 1;
4676c50d8ae3SPaolo Bonzini 
4677c50d8ae3SPaolo Bonzini 		/*
4678c50d8ae3SPaolo Bonzini 		 * Each "*f" variable has a 1 bit for each UWX value
4679c50d8ae3SPaolo Bonzini 		 * that causes a fault with the given PFEC.
4680c50d8ae3SPaolo Bonzini 		 */
4681c50d8ae3SPaolo Bonzini 
4682c50d8ae3SPaolo Bonzini 		/* Faults from writes to non-writable pages */
4683c50d8ae3SPaolo Bonzini 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4684c50d8ae3SPaolo Bonzini 		/* Faults from user mode accesses to supervisor pages */
4685c50d8ae3SPaolo Bonzini 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4686c50d8ae3SPaolo Bonzini 		/* Faults from fetches of non-executable pages*/
4687c50d8ae3SPaolo Bonzini 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4688c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode fetches of user pages */
4689c50d8ae3SPaolo Bonzini 		u8 smepf = 0;
4690c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode accesses of user pages */
4691c50d8ae3SPaolo Bonzini 		u8 smapf = 0;
4692c50d8ae3SPaolo Bonzini 
4693c50d8ae3SPaolo Bonzini 		if (!ept) {
4694c50d8ae3SPaolo Bonzini 			/* Faults from kernel mode accesses to user pages */
4695c50d8ae3SPaolo Bonzini 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4696c50d8ae3SPaolo Bonzini 
4697c50d8ae3SPaolo Bonzini 			/* Not really needed: !nx will cause pte.nx to fault */
469890599c28SSean Christopherson 			if (!efer_nx)
4699c50d8ae3SPaolo Bonzini 				ff = 0;
4700c50d8ae3SPaolo Bonzini 
4701c50d8ae3SPaolo Bonzini 			/* Allow supervisor writes if !cr0.wp */
4702c50d8ae3SPaolo Bonzini 			if (!cr0_wp)
4703c50d8ae3SPaolo Bonzini 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4704c50d8ae3SPaolo Bonzini 
4705c50d8ae3SPaolo Bonzini 			/* Disallow supervisor fetches of user code if cr4.smep */
4706c50d8ae3SPaolo Bonzini 			if (cr4_smep)
4707c50d8ae3SPaolo Bonzini 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4708c50d8ae3SPaolo Bonzini 
4709c50d8ae3SPaolo Bonzini 			/*
4710c50d8ae3SPaolo Bonzini 			 * SMAP:kernel-mode data accesses from user-mode
4711c50d8ae3SPaolo Bonzini 			 * mappings should fault. A fault is considered
4712c50d8ae3SPaolo Bonzini 			 * as a SMAP violation if all of the following
4713c50d8ae3SPaolo Bonzini 			 * conditions are true:
4714c50d8ae3SPaolo Bonzini 			 *   - X86_CR4_SMAP is set in CR4
4715c50d8ae3SPaolo Bonzini 			 *   - A user page is accessed
4716c50d8ae3SPaolo Bonzini 			 *   - The access is not a fetch
47174f4aa80eSLai Jiangshan 			 *   - The access is supervisor mode
47184f4aa80eSLai Jiangshan 			 *   - If implicit supervisor access or X86_EFLAGS_AC is clear
4719c50d8ae3SPaolo Bonzini 			 *
472094b4a2f1SLai Jiangshan 			 * Here, we cover the first four conditions.
472194b4a2f1SLai Jiangshan 			 * The fifth is computed dynamically in permission_fault();
4722c50d8ae3SPaolo Bonzini 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4723c50d8ae3SPaolo Bonzini 			 * *not* subject to SMAP restrictions.
4724c50d8ae3SPaolo Bonzini 			 */
4725c50d8ae3SPaolo Bonzini 			if (cr4_smap)
4726c50d8ae3SPaolo Bonzini 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4727c50d8ae3SPaolo Bonzini 		}
4728c50d8ae3SPaolo Bonzini 
4729c50d8ae3SPaolo Bonzini 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4730c50d8ae3SPaolo Bonzini 	}
4731c50d8ae3SPaolo Bonzini }
4732c50d8ae3SPaolo Bonzini 
4733c50d8ae3SPaolo Bonzini /*
4734c50d8ae3SPaolo Bonzini * PKU is an additional mechanism by which the paging controls access to
4735c50d8ae3SPaolo Bonzini * user-mode addresses based on the value in the PKRU register.  Protection
4736c50d8ae3SPaolo Bonzini * key violations are reported through a bit in the page fault error code.
4737c50d8ae3SPaolo Bonzini * Unlike other bits of the error code, the PK bit is not known at the
4738c50d8ae3SPaolo Bonzini * call site of e.g. gva_to_gpa; it must be computed directly in
4739c50d8ae3SPaolo Bonzini * permission_fault based on two bits of PKRU, on some machine state (CR4,
4740c50d8ae3SPaolo Bonzini * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4741c50d8ae3SPaolo Bonzini *
4742c50d8ae3SPaolo Bonzini * In particular the following conditions come from the error code, the
4743c50d8ae3SPaolo Bonzini * page tables and the machine state:
4744c50d8ae3SPaolo Bonzini * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4745c50d8ae3SPaolo Bonzini * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4746c50d8ae3SPaolo Bonzini * - PK is always zero if U=0 in the page tables
4747c50d8ae3SPaolo Bonzini * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4748c50d8ae3SPaolo Bonzini *
4749c50d8ae3SPaolo Bonzini * The PKRU bitmask caches the result of these four conditions.  The error
4750c50d8ae3SPaolo Bonzini * code (minus the P bit) and the page table's U bit form an index into the
4751c50d8ae3SPaolo Bonzini * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
4752c50d8ae3SPaolo Bonzini * with the two bits of the PKRU register corresponding to the protection key.
4753c50d8ae3SPaolo Bonzini * For the first three conditions above the bits will be 00, thus masking
4754c50d8ae3SPaolo Bonzini * away both AD and WD.  For all reads or if the last condition holds, WD
4755c50d8ae3SPaolo Bonzini * only will be masked away.
4756c50d8ae3SPaolo Bonzini */
47572e4c0661SSean Christopherson static void update_pkru_bitmask(struct kvm_mmu *mmu)
4758c50d8ae3SPaolo Bonzini {
4759c50d8ae3SPaolo Bonzini 	unsigned bit;
4760c50d8ae3SPaolo Bonzini 	bool wp;
4761c50d8ae3SPaolo Bonzini 
4762c50d8ae3SPaolo Bonzini 	mmu->pkru_mask = 0;
4763a3ca5281SChenyi Qiang 
4764a3ca5281SChenyi Qiang 	if (!is_cr4_pke(mmu))
4765c50d8ae3SPaolo Bonzini 		return;
4766c50d8ae3SPaolo Bonzini 
47672e4c0661SSean Christopherson 	wp = is_cr0_wp(mmu);
4768c50d8ae3SPaolo Bonzini 
4769c50d8ae3SPaolo Bonzini 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4770c50d8ae3SPaolo Bonzini 		unsigned pfec, pkey_bits;
4771c50d8ae3SPaolo Bonzini 		bool check_pkey, check_write, ff, uf, wf, pte_user;
4772c50d8ae3SPaolo Bonzini 
4773c50d8ae3SPaolo Bonzini 		pfec = bit << 1;
4774c50d8ae3SPaolo Bonzini 		ff = pfec & PFERR_FETCH_MASK;
4775c50d8ae3SPaolo Bonzini 		uf = pfec & PFERR_USER_MASK;
4776c50d8ae3SPaolo Bonzini 		wf = pfec & PFERR_WRITE_MASK;
4777c50d8ae3SPaolo Bonzini 
4778c50d8ae3SPaolo Bonzini 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
4779c50d8ae3SPaolo Bonzini 		pte_user = pfec & PFERR_RSVD_MASK;
4780c50d8ae3SPaolo Bonzini 
4781c50d8ae3SPaolo Bonzini 		/*
4782c50d8ae3SPaolo Bonzini 		 * Only need to check the access which is not an
4783c50d8ae3SPaolo Bonzini 		 * instruction fetch and is to a user page.
4784c50d8ae3SPaolo Bonzini 		 */
4785c50d8ae3SPaolo Bonzini 		check_pkey = (!ff && pte_user);
4786c50d8ae3SPaolo Bonzini 		/*
4787c50d8ae3SPaolo Bonzini 		 * write access is controlled by PKRU if it is a
4788c50d8ae3SPaolo Bonzini 		 * user access or CR0.WP = 1.
4789c50d8ae3SPaolo Bonzini 		 */
4790c50d8ae3SPaolo Bonzini 		check_write = check_pkey && wf && (uf || wp);
4791c50d8ae3SPaolo Bonzini 
4792c50d8ae3SPaolo Bonzini 		/* PKRU.AD stops both read and write access. */
4793c50d8ae3SPaolo Bonzini 		pkey_bits = !!check_pkey;
4794c50d8ae3SPaolo Bonzini 		/* PKRU.WD stops write access. */
4795c50d8ae3SPaolo Bonzini 		pkey_bits |= (!!check_write) << 1;
4796c50d8ae3SPaolo Bonzini 
4797c50d8ae3SPaolo Bonzini 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4798c50d8ae3SPaolo Bonzini 	}
4799c50d8ae3SPaolo Bonzini }
4800c50d8ae3SPaolo Bonzini 
4801533f9a4bSSean Christopherson static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
4802533f9a4bSSean Christopherson 					struct kvm_mmu *mmu)
4803c50d8ae3SPaolo Bonzini {
4804533f9a4bSSean Christopherson 	if (!is_cr0_pg(mmu))
4805533f9a4bSSean Christopherson 		return;
4806c50d8ae3SPaolo Bonzini 
4807c919e881SKai Huang 	reset_guest_rsvds_bits_mask(vcpu, mmu);
4808533f9a4bSSean Christopherson 	update_permission_bitmask(mmu, false);
4809533f9a4bSSean Christopherson 	update_pkru_bitmask(mmu);
4810c50d8ae3SPaolo Bonzini }
4811c50d8ae3SPaolo Bonzini 
4812fe660f72SSean Christopherson static void paging64_init_context(struct kvm_mmu *context)
4813c50d8ae3SPaolo Bonzini {
4814c50d8ae3SPaolo Bonzini 	context->page_fault = paging64_page_fault;
4815c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging64_gva_to_gpa;
4816c50d8ae3SPaolo Bonzini 	context->sync_page = paging64_sync_page;
4817c50d8ae3SPaolo Bonzini 	context->invlpg = paging64_invlpg;
4818c50d8ae3SPaolo Bonzini }
4819c50d8ae3SPaolo Bonzini 
482084a16226SSean Christopherson static void paging32_init_context(struct kvm_mmu *context)
4821c50d8ae3SPaolo Bonzini {
4822c50d8ae3SPaolo Bonzini 	context->page_fault = paging32_page_fault;
4823c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging32_gva_to_gpa;
4824c50d8ae3SPaolo Bonzini 	context->sync_page = paging32_sync_page;
4825c50d8ae3SPaolo Bonzini 	context->invlpg = paging32_invlpg;
4826c50d8ae3SPaolo Bonzini }
4827c50d8ae3SPaolo Bonzini 
48287a7ae829SPaolo Bonzini static union kvm_cpu_role
4829e5ed0fb0SPaolo Bonzini kvm_calc_cpu_role(struct kvm_vcpu *vcpu, const struct kvm_mmu_role_regs *regs)
4830e5ed0fb0SPaolo Bonzini {
48317a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
4832e5ed0fb0SPaolo Bonzini 
4833e5ed0fb0SPaolo Bonzini 	role.base.access = ACC_ALL;
4834e5ed0fb0SPaolo Bonzini 	role.base.smm = is_smm(vcpu);
4835e5ed0fb0SPaolo Bonzini 	role.base.guest_mode = is_guest_mode(vcpu);
4836e5ed0fb0SPaolo Bonzini 	role.ext.valid = 1;
4837e5ed0fb0SPaolo Bonzini 
4838e5ed0fb0SPaolo Bonzini 	if (!____is_cr0_pg(regs)) {
4839e5ed0fb0SPaolo Bonzini 		role.base.direct = 1;
4840e5ed0fb0SPaolo Bonzini 		return role;
4841e5ed0fb0SPaolo Bonzini 	}
4842e5ed0fb0SPaolo Bonzini 
4843e5ed0fb0SPaolo Bonzini 	role.base.efer_nx = ____is_efer_nx(regs);
4844e5ed0fb0SPaolo Bonzini 	role.base.cr0_wp = ____is_cr0_wp(regs);
4845e5ed0fb0SPaolo Bonzini 	role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
4846e5ed0fb0SPaolo Bonzini 	role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
4847e5ed0fb0SPaolo Bonzini 	role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
484860f3cb60SPaolo Bonzini 
484960f3cb60SPaolo Bonzini 	if (____is_efer_lma(regs))
485060f3cb60SPaolo Bonzini 		role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
485160f3cb60SPaolo Bonzini 							: PT64_ROOT_4LEVEL;
485260f3cb60SPaolo Bonzini 	else if (____is_cr4_pae(regs))
485360f3cb60SPaolo Bonzini 		role.base.level = PT32E_ROOT_LEVEL;
485460f3cb60SPaolo Bonzini 	else
485560f3cb60SPaolo Bonzini 		role.base.level = PT32_ROOT_LEVEL;
4856e5ed0fb0SPaolo Bonzini 
4857e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smep = ____is_cr4_smep(regs);
4858e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smap = ____is_cr4_smap(regs);
4859e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pse = ____is_cr4_pse(regs);
4860e5ed0fb0SPaolo Bonzini 
4861e5ed0fb0SPaolo Bonzini 	/* PKEY and LA57 are active iff long mode is active. */
4862e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
4863e5ed0fb0SPaolo Bonzini 	role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
4864e5ed0fb0SPaolo Bonzini 	role.ext.efer_lma = ____is_efer_lma(regs);
4865e5ed0fb0SPaolo Bonzini 	return role;
4866e5ed0fb0SPaolo Bonzini }
4867e5ed0fb0SPaolo Bonzini 
4868d468d94bSSean Christopherson static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
4869d468d94bSSean Christopherson {
4870746700d2SWei Huang 	/* tdp_root_level is architecture forced level, use it if nonzero */
4871746700d2SWei Huang 	if (tdp_root_level)
4872746700d2SWei Huang 		return tdp_root_level;
4873746700d2SWei Huang 
4874d468d94bSSean Christopherson 	/* Use 5-level TDP if and only if it's useful/necessary. */
487583013059SSean Christopherson 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
4876d468d94bSSean Christopherson 		return 4;
4877d468d94bSSean Christopherson 
487883013059SSean Christopherson 	return max_tdp_level;
4879d468d94bSSean Christopherson }
4880d468d94bSSean Christopherson 
48817a458f0eSPaolo Bonzini static union kvm_mmu_page_role
48828626c120SSean Christopherson kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
48837a7ae829SPaolo Bonzini 				union kvm_cpu_role cpu_role)
4884c50d8ae3SPaolo Bonzini {
48857a458f0eSPaolo Bonzini 	union kvm_mmu_page_role role = {0};
4886c50d8ae3SPaolo Bonzini 
48877a458f0eSPaolo Bonzini 	role.access = ACC_ALL;
48887a458f0eSPaolo Bonzini 	role.cr0_wp = true;
48897a458f0eSPaolo Bonzini 	role.efer_nx = true;
48907a458f0eSPaolo Bonzini 	role.smm = cpu_role.base.smm;
48917a458f0eSPaolo Bonzini 	role.guest_mode = cpu_role.base.guest_mode;
489254275f74SSean Christopherson 	role.ad_disabled = !kvm_ad_enabled();
48937a458f0eSPaolo Bonzini 	role.level = kvm_mmu_get_tdp_level(vcpu);
48947a458f0eSPaolo Bonzini 	role.direct = true;
48957a458f0eSPaolo Bonzini 	role.has_4_byte_gpte = false;
4896c50d8ae3SPaolo Bonzini 
4897c50d8ae3SPaolo Bonzini 	return role;
4898c50d8ae3SPaolo Bonzini }
4899c50d8ae3SPaolo Bonzini 
490039e7e2bfSPaolo Bonzini static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
4901a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
4902c50d8ae3SPaolo Bonzini {
49038c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
49047a458f0eSPaolo Bonzini 	union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
4905c50d8ae3SPaolo Bonzini 
4906e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
49077a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
4908c50d8ae3SPaolo Bonzini 		return;
4909c50d8ae3SPaolo Bonzini 
4910e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
49117a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
49127a02674dSSean Christopherson 	context->page_fault = kvm_tdp_page_fault;
4913c50d8ae3SPaolo Bonzini 	context->sync_page = nonpaging_sync_page;
49145efac074SPaolo Bonzini 	context->invlpg = NULL;
4915d8dd54e0SSean Christopherson 	context->get_guest_pgd = get_cr3;
4916c50d8ae3SPaolo Bonzini 	context->get_pdptr = kvm_pdptr_read;
4917c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
4918c50d8ae3SPaolo Bonzini 
491936f26787SSean Christopherson 	if (!is_cr0_pg(context))
4920c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = nonpaging_gva_to_gpa;
492136f26787SSean Christopherson 	else if (is_cr4_pae(context))
4922c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging64_gva_to_gpa;
4923f4bd6f73SSean Christopherson 	else
4924c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging32_gva_to_gpa;
4925c50d8ae3SPaolo Bonzini 
4926533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
4927e8f6e738SJinrong Liang 	reset_tdp_shadow_zero_bits_mask(context);
4928c50d8ae3SPaolo Bonzini }
4929c50d8ae3SPaolo Bonzini 
49308c008659SPaolo Bonzini static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
49317a7ae829SPaolo Bonzini 				    union kvm_cpu_role cpu_role,
49327a458f0eSPaolo Bonzini 				    union kvm_mmu_page_role root_role)
4933c50d8ae3SPaolo Bonzini {
4934e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
49357a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
493618db1b17SSean Christopherson 		return;
4937c50d8ae3SPaolo Bonzini 
4938e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
49397a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
494018db1b17SSean Christopherson 
494136f26787SSean Christopherson 	if (!is_cr0_pg(context))
494284a16226SSean Christopherson 		nonpaging_init_context(context);
494336f26787SSean Christopherson 	else if (is_cr4_pae(context))
4944fe660f72SSean Christopherson 		paging64_init_context(context);
4945c50d8ae3SPaolo Bonzini 	else
494684a16226SSean Christopherson 		paging32_init_context(context);
4947c50d8ae3SPaolo Bonzini 
4948533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
4949c50d8ae3SPaolo Bonzini 	reset_shadow_zero_bits_mask(vcpu, context);
4950c50d8ae3SPaolo Bonzini }
49510f04a2acSVitaly Kuznetsov 
4952594e91a1SSean Christopherson static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
4953a7f1de9bSPaolo Bonzini 				union kvm_cpu_role cpu_role)
49540f04a2acSVitaly Kuznetsov {
49558c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
495656b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
495756b321f9SPaolo Bonzini 
495856b321f9SPaolo Bonzini 	root_role = cpu_role.base;
495956b321f9SPaolo Bonzini 
496056b321f9SPaolo Bonzini 	/* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
496156b321f9SPaolo Bonzini 	root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
496256b321f9SPaolo Bonzini 
496356b321f9SPaolo Bonzini 	/*
496456b321f9SPaolo Bonzini 	 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
496556b321f9SPaolo Bonzini 	 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
496656b321f9SPaolo Bonzini 	 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
496756b321f9SPaolo Bonzini 	 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
496856b321f9SPaolo Bonzini 	 * The iTLB multi-hit workaround can be toggled at any time, so assume
496956b321f9SPaolo Bonzini 	 * NX can be used by any non-nested shadow MMU to avoid having to reset
497056b321f9SPaolo Bonzini 	 * MMU contexts.
497156b321f9SPaolo Bonzini 	 */
497256b321f9SPaolo Bonzini 	root_role.efer_nx = true;
49730f04a2acSVitaly Kuznetsov 
49747a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
49750f04a2acSVitaly Kuznetsov }
49760f04a2acSVitaly Kuznetsov 
4977dbc4739bSSean Christopherson void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
4978dbc4739bSSean Christopherson 			     unsigned long cr4, u64 efer, gpa_t nested_cr3)
49790f04a2acSVitaly Kuznetsov {
49808c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
4981594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
4982594e91a1SSean Christopherson 		.cr0 = cr0,
498328f091bcSPaolo Bonzini 		.cr4 = cr4 & ~X86_CR4_PKE,
4984594e91a1SSean Christopherson 		.efer = efer,
4985594e91a1SSean Christopherson 	};
49867a7ae829SPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
498756b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
498856b321f9SPaolo Bonzini 
498956b321f9SPaolo Bonzini 	/* NPT requires CR0.PG=1. */
499056b321f9SPaolo Bonzini 	WARN_ON_ONCE(cpu_role.base.direct);
499156b321f9SPaolo Bonzini 
499256b321f9SPaolo Bonzini 	root_role = cpu_role.base;
499356b321f9SPaolo Bonzini 	root_role.level = kvm_mmu_get_tdp_level(vcpu);
499484e5ffd0SLai Jiangshan 	if (root_role.level == PT64_ROOT_5LEVEL &&
499584e5ffd0SLai Jiangshan 	    cpu_role.base.level == PT64_ROOT_4LEVEL)
499684e5ffd0SLai Jiangshan 		root_role.passthrough = 1;
49970f04a2acSVitaly Kuznetsov 
49987a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
4999d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, nested_cr3);
50000f04a2acSVitaly Kuznetsov }
50010f04a2acSVitaly Kuznetsov EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5002c50d8ae3SPaolo Bonzini 
50037a7ae829SPaolo Bonzini static union kvm_cpu_role
5004c50d8ae3SPaolo Bonzini kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5005bb1fcc70SSean Christopherson 				   bool execonly, u8 level)
5006c50d8ae3SPaolo Bonzini {
50077a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5008c50d8ae3SPaolo Bonzini 
5009daed87b8SPaolo Bonzini 	/*
5010daed87b8SPaolo Bonzini 	 * KVM does not support SMM transfer monitors, and consequently does not
5011daed87b8SPaolo Bonzini 	 * support the "entry to SMM" control either.  role.base.smm is always 0.
5012daed87b8SPaolo Bonzini 	 */
5013daed87b8SPaolo Bonzini 	WARN_ON_ONCE(is_smm(vcpu));
5014bb1fcc70SSean Christopherson 	role.base.level = level;
5015bb3b394dSLai Jiangshan 	role.base.has_4_byte_gpte = false;
5016c50d8ae3SPaolo Bonzini 	role.base.direct = false;
5017c50d8ae3SPaolo Bonzini 	role.base.ad_disabled = !accessed_dirty;
5018c50d8ae3SPaolo Bonzini 	role.base.guest_mode = true;
5019c50d8ae3SPaolo Bonzini 	role.base.access = ACC_ALL;
5020c50d8ae3SPaolo Bonzini 
5021cd6767c3SSean Christopherson 	role.ext.word = 0;
5022c50d8ae3SPaolo Bonzini 	role.ext.execonly = execonly;
5023cd6767c3SSean Christopherson 	role.ext.valid = 1;
5024c50d8ae3SPaolo Bonzini 
5025c50d8ae3SPaolo Bonzini 	return role;
5026c50d8ae3SPaolo Bonzini }
5027c50d8ae3SPaolo Bonzini 
5028c50d8ae3SPaolo Bonzini void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5029cc022ae1SLai Jiangshan 			     int huge_page_level, bool accessed_dirty,
5030cc022ae1SLai Jiangshan 			     gpa_t new_eptp)
5031c50d8ae3SPaolo Bonzini {
50328c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5033bb1fcc70SSean Christopherson 	u8 level = vmx_eptp_page_walk_level(new_eptp);
50347a7ae829SPaolo Bonzini 	union kvm_cpu_role new_mode =
5035c50d8ae3SPaolo Bonzini 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5036bb1fcc70SSean Christopherson 						   execonly, level);
5037c50d8ae3SPaolo Bonzini 
5038e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 != context->cpu_role.as_u64) {
5039e5ed0fb0SPaolo Bonzini 		/* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5040e5ed0fb0SPaolo Bonzini 		context->cpu_role.as_u64 = new_mode.as_u64;
50417a458f0eSPaolo Bonzini 		context->root_role.word = new_mode.base.word;
504218db1b17SSean Christopherson 
5043c50d8ae3SPaolo Bonzini 		context->page_fault = ept_page_fault;
5044c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = ept_gva_to_gpa;
5045c50d8ae3SPaolo Bonzini 		context->sync_page = ept_sync_page;
5046c50d8ae3SPaolo Bonzini 		context->invlpg = ept_invlpg;
5047347a0d0dSPaolo Bonzini 
5048c596f147SSean Christopherson 		update_permission_bitmask(context, true);
504928f091bcSPaolo Bonzini 		context->pkru_mask = 0;
5050cc022ae1SLai Jiangshan 		reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5051e8f6e738SJinrong Liang 		reset_ept_shadow_zero_bits_mask(context, execonly);
5052c50d8ae3SPaolo Bonzini 	}
50533cffc89dSPaolo Bonzini 
5054d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, new_eptp);
50553cffc89dSPaolo Bonzini }
5056c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5057c50d8ae3SPaolo Bonzini 
505839e7e2bfSPaolo Bonzini static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5059a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5060c50d8ae3SPaolo Bonzini {
50618c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5062c50d8ae3SPaolo Bonzini 
5063a7f1de9bSPaolo Bonzini 	kvm_init_shadow_mmu(vcpu, cpu_role);
5064929d1cfaSPaolo Bonzini 
5065d8dd54e0SSean Christopherson 	context->get_guest_pgd     = get_cr3;
5066c50d8ae3SPaolo Bonzini 	context->get_pdptr         = kvm_pdptr_read;
5067c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5068c50d8ae3SPaolo Bonzini }
5069c50d8ae3SPaolo Bonzini 
507039e7e2bfSPaolo Bonzini static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5071a7f1de9bSPaolo Bonzini 				union kvm_cpu_role new_mode)
5072c50d8ae3SPaolo Bonzini {
5073c50d8ae3SPaolo Bonzini 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5074c50d8ae3SPaolo Bonzini 
5075e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5076c50d8ae3SPaolo Bonzini 		return;
5077c50d8ae3SPaolo Bonzini 
5078e5ed0fb0SPaolo Bonzini 	g_context->cpu_role.as_u64   = new_mode.as_u64;
5079d8dd54e0SSean Christopherson 	g_context->get_guest_pgd     = get_cr3;
5080c50d8ae3SPaolo Bonzini 	g_context->get_pdptr         = kvm_pdptr_read;
5081c50d8ae3SPaolo Bonzini 	g_context->inject_page_fault = kvm_inject_page_fault;
5082c50d8ae3SPaolo Bonzini 
5083c50d8ae3SPaolo Bonzini 	/*
50845efac074SPaolo Bonzini 	 * L2 page tables are never shadowed, so there is no need to sync
50855efac074SPaolo Bonzini 	 * SPTEs.
50865efac074SPaolo Bonzini 	 */
50875efac074SPaolo Bonzini 	g_context->invlpg            = NULL;
50885efac074SPaolo Bonzini 
50895efac074SPaolo Bonzini 	/*
5090c50d8ae3SPaolo Bonzini 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5091c50d8ae3SPaolo Bonzini 	 * L1's nested page tables (e.g. EPT12). The nested translation
5092c50d8ae3SPaolo Bonzini 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5093c50d8ae3SPaolo Bonzini 	 * L2's page tables as the first level of translation and L1's
5094c50d8ae3SPaolo Bonzini 	 * nested page tables as the second level of translation. Basically
5095c50d8ae3SPaolo Bonzini 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5096c50d8ae3SPaolo Bonzini 	 */
5097fa4b5588SSean Christopherson 	if (!is_paging(vcpu))
50981f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5099fa4b5588SSean Christopherson 	else if (is_long_mode(vcpu))
51001f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5101fa4b5588SSean Christopherson 	else if (is_pae(vcpu))
51021f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5103fa4b5588SSean Christopherson 	else
51041f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging32_gva_to_gpa;
5105fa4b5588SSean Christopherson 
5106533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, g_context);
5107c50d8ae3SPaolo Bonzini }
5108c50d8ae3SPaolo Bonzini 
5109c9060662SSean Christopherson void kvm_init_mmu(struct kvm_vcpu *vcpu)
5110c50d8ae3SPaolo Bonzini {
511139e7e2bfSPaolo Bonzini 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5112a7f1de9bSPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
511339e7e2bfSPaolo Bonzini 
5114c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
5115a7f1de9bSPaolo Bonzini 		init_kvm_nested_mmu(vcpu, cpu_role);
5116c50d8ae3SPaolo Bonzini 	else if (tdp_enabled)
5117a7f1de9bSPaolo Bonzini 		init_kvm_tdp_mmu(vcpu, cpu_role);
5118c50d8ae3SPaolo Bonzini 	else
5119a7f1de9bSPaolo Bonzini 		init_kvm_softmmu(vcpu, cpu_role);
5120c50d8ae3SPaolo Bonzini }
5121c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_mmu);
5122c50d8ae3SPaolo Bonzini 
512349c6f875SSean Christopherson void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
512449c6f875SSean Christopherson {
512549c6f875SSean Christopherson 	/*
512649c6f875SSean Christopherson 	 * Invalidate all MMU roles to force them to reinitialize as CPUID
512749c6f875SSean Christopherson 	 * information is factored into reserved bit calculations.
5128feb627e8SVitaly Kuznetsov 	 *
5129feb627e8SVitaly Kuznetsov 	 * Correctly handling multiple vCPU models with respect to paging and
5130feb627e8SVitaly Kuznetsov 	 * physical address properties) in a single VM would require tracking
5131feb627e8SVitaly Kuznetsov 	 * all relevant CPUID information in kvm_mmu_page_role. That is very
5132feb627e8SVitaly Kuznetsov 	 * undesirable as it would increase the memory requirements for
5133feb627e8SVitaly Kuznetsov 	 * gfn_track (see struct kvm_mmu_page_role comments).  For now that
5134feb627e8SVitaly Kuznetsov 	 * problem is swept under the rug; KVM's CPUID API is horrific and
5135feb627e8SVitaly Kuznetsov 	 * it's all but impossible to solve it without introducing a new API.
513649c6f875SSean Christopherson 	 */
51377a458f0eSPaolo Bonzini 	vcpu->arch.root_mmu.root_role.word = 0;
51387a458f0eSPaolo Bonzini 	vcpu->arch.guest_mmu.root_role.word = 0;
51397a458f0eSPaolo Bonzini 	vcpu->arch.nested_mmu.root_role.word = 0;
5140e5ed0fb0SPaolo Bonzini 	vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5141e5ed0fb0SPaolo Bonzini 	vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5142e5ed0fb0SPaolo Bonzini 	vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
514349c6f875SSean Christopherson 	kvm_mmu_reset_context(vcpu);
514463f5a190SSean Christopherson 
514563f5a190SSean Christopherson 	/*
5146feb627e8SVitaly Kuznetsov 	 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5147feb627e8SVitaly Kuznetsov 	 * kvm_arch_vcpu_ioctl().
514863f5a190SSean Christopherson 	 */
5149feb627e8SVitaly Kuznetsov 	KVM_BUG_ON(vcpu->arch.last_vmentry_cpu != -1, vcpu->kvm);
515049c6f875SSean Christopherson }
515149c6f875SSean Christopherson 
5152c50d8ae3SPaolo Bonzini void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5153c50d8ae3SPaolo Bonzini {
5154c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
5155c9060662SSean Christopherson 	kvm_init_mmu(vcpu);
5156c50d8ae3SPaolo Bonzini }
5157c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5158c50d8ae3SPaolo Bonzini 
5159c50d8ae3SPaolo Bonzini int kvm_mmu_load(struct kvm_vcpu *vcpu)
5160c50d8ae3SPaolo Bonzini {
5161c50d8ae3SPaolo Bonzini 	int r;
5162c50d8ae3SPaolo Bonzini 
5163347a0d0dSPaolo Bonzini 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5164c50d8ae3SPaolo Bonzini 	if (r)
5165c50d8ae3SPaolo Bonzini 		goto out;
5166748e52b9SSean Christopherson 	r = mmu_alloc_special_roots(vcpu);
5167c50d8ae3SPaolo Bonzini 	if (r)
5168c50d8ae3SPaolo Bonzini 		goto out;
5169347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
51706e6ec584SSean Christopherson 		r = mmu_alloc_direct_roots(vcpu);
51716e6ec584SSean Christopherson 	else
51726e6ec584SSean Christopherson 		r = mmu_alloc_shadow_roots(vcpu);
5173c50d8ae3SPaolo Bonzini 	if (r)
5174c50d8ae3SPaolo Bonzini 		goto out;
5175a91f387bSSean Christopherson 
5176a91f387bSSean Christopherson 	kvm_mmu_sync_roots(vcpu);
5177a91f387bSSean Christopherson 
5178727a7e27SPaolo Bonzini 	kvm_mmu_load_pgd(vcpu);
5179db01416bSSean Christopherson 
5180db01416bSSean Christopherson 	/*
5181db01416bSSean Christopherson 	 * Flush any TLB entries for the new root, the provenance of the root
5182db01416bSSean Christopherson 	 * is unknown.  Even if KVM ensures there are no stale TLB entries
5183db01416bSSean Christopherson 	 * for a freed root, in theory another hypervisor could have left
5184db01416bSSean Christopherson 	 * stale entries.  Flushing on alloc also allows KVM to skip the TLB
5185db01416bSSean Christopherson 	 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5186db01416bSSean Christopherson 	 */
5187e27bc044SSean Christopherson 	static_call(kvm_x86_flush_tlb_current)(vcpu);
5188c50d8ae3SPaolo Bonzini out:
5189c50d8ae3SPaolo Bonzini 	return r;
5190c50d8ae3SPaolo Bonzini }
5191c50d8ae3SPaolo Bonzini 
5192c50d8ae3SPaolo Bonzini void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5193c50d8ae3SPaolo Bonzini {
51940c1c92f1SPaolo Bonzini 	struct kvm *kvm = vcpu->kvm;
51950c1c92f1SPaolo Bonzini 
51960c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5197b9e5603cSPaolo Bonzini 	WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
51980c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5199b9e5603cSPaolo Bonzini 	WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
52006d58f275SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5201c50d8ae3SPaolo Bonzini }
5202c50d8ae3SPaolo Bonzini 
5203527d5cd7SSean Christopherson static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5204527d5cd7SSean Christopherson {
5205527d5cd7SSean Christopherson 	struct kvm_mmu_page *sp;
5206527d5cd7SSean Christopherson 
5207527d5cd7SSean Christopherson 	if (!VALID_PAGE(root_hpa))
5208527d5cd7SSean Christopherson 		return false;
5209527d5cd7SSean Christopherson 
5210527d5cd7SSean Christopherson 	/*
5211527d5cd7SSean Christopherson 	 * When freeing obsolete roots, treat roots as obsolete if they don't
5212527d5cd7SSean Christopherson 	 * have an associated shadow page.  This does mean KVM will get false
5213527d5cd7SSean Christopherson 	 * positives and free roots that don't strictly need to be freed, but
5214527d5cd7SSean Christopherson 	 * such false positives are relatively rare:
5215527d5cd7SSean Christopherson 	 *
5216527d5cd7SSean Christopherson 	 *  (a) only PAE paging and nested NPT has roots without shadow pages
5217527d5cd7SSean Christopherson 	 *  (b) remote reloads due to a memslot update obsoletes _all_ roots
5218527d5cd7SSean Christopherson 	 *  (c) KVM doesn't track previous roots for PAE paging, and the guest
5219527d5cd7SSean Christopherson 	 *      is unlikely to zap an in-use PGD.
5220527d5cd7SSean Christopherson 	 */
5221527d5cd7SSean Christopherson 	sp = to_shadow_page(root_hpa);
5222527d5cd7SSean Christopherson 	return !sp || is_obsolete_sp(kvm, sp);
5223527d5cd7SSean Christopherson }
5224527d5cd7SSean Christopherson 
5225527d5cd7SSean Christopherson static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5226527d5cd7SSean Christopherson {
5227527d5cd7SSean Christopherson 	unsigned long roots_to_free = 0;
5228527d5cd7SSean Christopherson 	int i;
5229527d5cd7SSean Christopherson 
5230527d5cd7SSean Christopherson 	if (is_obsolete_root(kvm, mmu->root.hpa))
5231527d5cd7SSean Christopherson 		roots_to_free |= KVM_MMU_ROOT_CURRENT;
5232527d5cd7SSean Christopherson 
5233527d5cd7SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5234cf4a8693SShaoqin Huang 		if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5235527d5cd7SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5236527d5cd7SSean Christopherson 	}
5237527d5cd7SSean Christopherson 
5238527d5cd7SSean Christopherson 	if (roots_to_free)
5239527d5cd7SSean Christopherson 		kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5240527d5cd7SSean Christopherson }
5241527d5cd7SSean Christopherson 
5242527d5cd7SSean Christopherson void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5243527d5cd7SSean Christopherson {
5244527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5245527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5246527d5cd7SSean Christopherson }
5247527d5cd7SSean Christopherson 
5248c50d8ae3SPaolo Bonzini static bool need_remote_flush(u64 old, u64 new)
5249c50d8ae3SPaolo Bonzini {
5250c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old))
5251c50d8ae3SPaolo Bonzini 		return false;
5252c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(new))
5253c50d8ae3SPaolo Bonzini 		return true;
52542ca3129eSSean Christopherson 	if ((old ^ new) & SPTE_BASE_ADDR_MASK)
5255c50d8ae3SPaolo Bonzini 		return true;
5256c50d8ae3SPaolo Bonzini 	old ^= shadow_nx_mask;
5257c50d8ae3SPaolo Bonzini 	new ^= shadow_nx_mask;
52582ca3129eSSean Christopherson 	return (old & ~new & SPTE_PERM_MASK) != 0;
5259c50d8ae3SPaolo Bonzini }
5260c50d8ae3SPaolo Bonzini 
5261c50d8ae3SPaolo Bonzini static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5262c50d8ae3SPaolo Bonzini 				    int *bytes)
5263c50d8ae3SPaolo Bonzini {
5264c50d8ae3SPaolo Bonzini 	u64 gentry = 0;
5265c50d8ae3SPaolo Bonzini 	int r;
5266c50d8ae3SPaolo Bonzini 
5267c50d8ae3SPaolo Bonzini 	/*
5268c50d8ae3SPaolo Bonzini 	 * Assume that the pte write on a page table of the same type
5269c50d8ae3SPaolo Bonzini 	 * as the current vcpu paging mode since we update the sptes only
5270c50d8ae3SPaolo Bonzini 	 * when they have the same mode.
5271c50d8ae3SPaolo Bonzini 	 */
5272c50d8ae3SPaolo Bonzini 	if (is_pae(vcpu) && *bytes == 4) {
5273c50d8ae3SPaolo Bonzini 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5274c50d8ae3SPaolo Bonzini 		*gpa &= ~(gpa_t)7;
5275c50d8ae3SPaolo Bonzini 		*bytes = 8;
5276c50d8ae3SPaolo Bonzini 	}
5277c50d8ae3SPaolo Bonzini 
5278c50d8ae3SPaolo Bonzini 	if (*bytes == 4 || *bytes == 8) {
5279c50d8ae3SPaolo Bonzini 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5280c50d8ae3SPaolo Bonzini 		if (r)
5281c50d8ae3SPaolo Bonzini 			gentry = 0;
5282c50d8ae3SPaolo Bonzini 	}
5283c50d8ae3SPaolo Bonzini 
5284c50d8ae3SPaolo Bonzini 	return gentry;
5285c50d8ae3SPaolo Bonzini }
5286c50d8ae3SPaolo Bonzini 
5287c50d8ae3SPaolo Bonzini /*
5288c50d8ae3SPaolo Bonzini  * If we're seeing too many writes to a page, it may no longer be a page table,
5289c50d8ae3SPaolo Bonzini  * or we may be forking, in which case it is better to unmap the page.
5290c50d8ae3SPaolo Bonzini  */
5291c50d8ae3SPaolo Bonzini static bool detect_write_flooding(struct kvm_mmu_page *sp)
5292c50d8ae3SPaolo Bonzini {
5293c50d8ae3SPaolo Bonzini 	/*
5294c50d8ae3SPaolo Bonzini 	 * Skip write-flooding detected for the sp whose level is 1, because
5295c50d8ae3SPaolo Bonzini 	 * it can become unsync, then the guest page is not write-protected.
5296c50d8ae3SPaolo Bonzini 	 */
52973bae0459SSean Christopherson 	if (sp->role.level == PG_LEVEL_4K)
5298c50d8ae3SPaolo Bonzini 		return false;
5299c50d8ae3SPaolo Bonzini 
5300c50d8ae3SPaolo Bonzini 	atomic_inc(&sp->write_flooding_count);
5301c50d8ae3SPaolo Bonzini 	return atomic_read(&sp->write_flooding_count) >= 3;
5302c50d8ae3SPaolo Bonzini }
5303c50d8ae3SPaolo Bonzini 
5304c50d8ae3SPaolo Bonzini /*
5305c50d8ae3SPaolo Bonzini  * Misaligned accesses are too much trouble to fix up; also, they usually
5306c50d8ae3SPaolo Bonzini  * indicate a page is not used as a page table.
5307c50d8ae3SPaolo Bonzini  */
5308c50d8ae3SPaolo Bonzini static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5309c50d8ae3SPaolo Bonzini 				    int bytes)
5310c50d8ae3SPaolo Bonzini {
5311c50d8ae3SPaolo Bonzini 	unsigned offset, pte_size, misaligned;
5312c50d8ae3SPaolo Bonzini 
5313c50d8ae3SPaolo Bonzini 	pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5314c50d8ae3SPaolo Bonzini 		 gpa, bytes, sp->role.word);
5315c50d8ae3SPaolo Bonzini 
5316c50d8ae3SPaolo Bonzini 	offset = offset_in_page(gpa);
5317bb3b394dSLai Jiangshan 	pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5318c50d8ae3SPaolo Bonzini 
5319c50d8ae3SPaolo Bonzini 	/*
5320c50d8ae3SPaolo Bonzini 	 * Sometimes, the OS only writes the last one bytes to update status
5321c50d8ae3SPaolo Bonzini 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5322c50d8ae3SPaolo Bonzini 	 */
5323c50d8ae3SPaolo Bonzini 	if (!(offset & (pte_size - 1)) && bytes == 1)
5324c50d8ae3SPaolo Bonzini 		return false;
5325c50d8ae3SPaolo Bonzini 
5326c50d8ae3SPaolo Bonzini 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5327c50d8ae3SPaolo Bonzini 	misaligned |= bytes < 4;
5328c50d8ae3SPaolo Bonzini 
5329c50d8ae3SPaolo Bonzini 	return misaligned;
5330c50d8ae3SPaolo Bonzini }
5331c50d8ae3SPaolo Bonzini 
5332c50d8ae3SPaolo Bonzini static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5333c50d8ae3SPaolo Bonzini {
5334c50d8ae3SPaolo Bonzini 	unsigned page_offset, quadrant;
5335c50d8ae3SPaolo Bonzini 	u64 *spte;
5336c50d8ae3SPaolo Bonzini 	int level;
5337c50d8ae3SPaolo Bonzini 
5338c50d8ae3SPaolo Bonzini 	page_offset = offset_in_page(gpa);
5339c50d8ae3SPaolo Bonzini 	level = sp->role.level;
5340c50d8ae3SPaolo Bonzini 	*nspte = 1;
5341bb3b394dSLai Jiangshan 	if (sp->role.has_4_byte_gpte) {
5342c50d8ae3SPaolo Bonzini 		page_offset <<= 1;	/* 32->64 */
5343c50d8ae3SPaolo Bonzini 		/*
5344c50d8ae3SPaolo Bonzini 		 * A 32-bit pde maps 4MB while the shadow pdes map
5345c50d8ae3SPaolo Bonzini 		 * only 2MB.  So we need to double the offset again
5346c50d8ae3SPaolo Bonzini 		 * and zap two pdes instead of one.
5347c50d8ae3SPaolo Bonzini 		 */
5348c50d8ae3SPaolo Bonzini 		if (level == PT32_ROOT_LEVEL) {
5349c50d8ae3SPaolo Bonzini 			page_offset &= ~7; /* kill rounding error */
5350c50d8ae3SPaolo Bonzini 			page_offset <<= 1;
5351c50d8ae3SPaolo Bonzini 			*nspte = 2;
5352c50d8ae3SPaolo Bonzini 		}
5353c50d8ae3SPaolo Bonzini 		quadrant = page_offset >> PAGE_SHIFT;
5354c50d8ae3SPaolo Bonzini 		page_offset &= ~PAGE_MASK;
5355c50d8ae3SPaolo Bonzini 		if (quadrant != sp->role.quadrant)
5356c50d8ae3SPaolo Bonzini 			return NULL;
5357c50d8ae3SPaolo Bonzini 	}
5358c50d8ae3SPaolo Bonzini 
5359c50d8ae3SPaolo Bonzini 	spte = &sp->spt[page_offset / sizeof(*spte)];
5360c50d8ae3SPaolo Bonzini 	return spte;
5361c50d8ae3SPaolo Bonzini }
5362c50d8ae3SPaolo Bonzini 
5363c50d8ae3SPaolo Bonzini static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5364c50d8ae3SPaolo Bonzini 			      const u8 *new, int bytes,
5365c50d8ae3SPaolo Bonzini 			      struct kvm_page_track_notifier_node *node)
5366c50d8ae3SPaolo Bonzini {
5367c50d8ae3SPaolo Bonzini 	gfn_t gfn = gpa >> PAGE_SHIFT;
5368c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
5369c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
5370c50d8ae3SPaolo Bonzini 	u64 entry, gentry, *spte;
5371c50d8ae3SPaolo Bonzini 	int npte;
537206152b2dSLai Jiangshan 	bool flush = false;
5373c50d8ae3SPaolo Bonzini 
5374c50d8ae3SPaolo Bonzini 	/*
5375c50d8ae3SPaolo Bonzini 	 * If we don't have indirect shadow pages, it means no page is
5376c50d8ae3SPaolo Bonzini 	 * write-protected, so we can exit simply.
5377c50d8ae3SPaolo Bonzini 	 */
5378c50d8ae3SPaolo Bonzini 	if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5379c50d8ae3SPaolo Bonzini 		return;
5380c50d8ae3SPaolo Bonzini 
5381c50d8ae3SPaolo Bonzini 	pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5382c50d8ae3SPaolo Bonzini 
5383531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
5384c50d8ae3SPaolo Bonzini 
5385c50d8ae3SPaolo Bonzini 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5386c50d8ae3SPaolo Bonzini 
5387c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_pte_write;
5388c50d8ae3SPaolo Bonzini 
5389767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5390c50d8ae3SPaolo Bonzini 		if (detect_write_misaligned(sp, gpa, bytes) ||
5391c50d8ae3SPaolo Bonzini 		      detect_write_flooding(sp)) {
5392c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5393c50d8ae3SPaolo Bonzini 			++vcpu->kvm->stat.mmu_flooded;
5394c50d8ae3SPaolo Bonzini 			continue;
5395c50d8ae3SPaolo Bonzini 		}
5396c50d8ae3SPaolo Bonzini 
5397c50d8ae3SPaolo Bonzini 		spte = get_written_sptes(sp, gpa, &npte);
5398c50d8ae3SPaolo Bonzini 		if (!spte)
5399c50d8ae3SPaolo Bonzini 			continue;
5400c50d8ae3SPaolo Bonzini 
5401c50d8ae3SPaolo Bonzini 		while (npte--) {
5402c50d8ae3SPaolo Bonzini 			entry = *spte;
54032de4085cSBen Gardon 			mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5404c5e2184dSSean Christopherson 			if (gentry && sp->role.level != PG_LEVEL_4K)
5405c5e2184dSSean Christopherson 				++vcpu->kvm->stat.mmu_pde_zapped;
5406c50d8ae3SPaolo Bonzini 			if (need_remote_flush(entry, *spte))
540706152b2dSLai Jiangshan 				flush = true;
5408c50d8ae3SPaolo Bonzini 			++spte;
5409c50d8ae3SPaolo Bonzini 		}
5410c50d8ae3SPaolo Bonzini 	}
541106152b2dSLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5412531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
5413c50d8ae3SPaolo Bonzini }
5414c50d8ae3SPaolo Bonzini 
54151075d41eSSean Christopherson int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5416c50d8ae3SPaolo Bonzini 		       void *insn, int insn_len)
5417c50d8ae3SPaolo Bonzini {
541892daa48bSSean Christopherson 	int r, emulation_type = EMULTYPE_PF;
5419347a0d0dSPaolo Bonzini 	bool direct = vcpu->arch.mmu->root_role.direct;
5420c50d8ae3SPaolo Bonzini 
5421b9e5603cSPaolo Bonzini 	if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5422ddce6208SSean Christopherson 		return RET_PF_RETRY;
5423ddce6208SSean Christopherson 
5424c50d8ae3SPaolo Bonzini 	r = RET_PF_INVALID;
5425c50d8ae3SPaolo Bonzini 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
5426736c291cSSean Christopherson 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5427c50d8ae3SPaolo Bonzini 		if (r == RET_PF_EMULATE)
5428c50d8ae3SPaolo Bonzini 			goto emulate;
5429c50d8ae3SPaolo Bonzini 	}
5430c50d8ae3SPaolo Bonzini 
5431c50d8ae3SPaolo Bonzini 	if (r == RET_PF_INVALID) {
54327a02674dSSean Christopherson 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
54337a02674dSSean Christopherson 					  lower_32_bits(error_code), false);
543419025e7bSSean Christopherson 		if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
54357b367bc9SSean Christopherson 			return -EIO;
5436c50d8ae3SPaolo Bonzini 	}
5437c50d8ae3SPaolo Bonzini 
5438c50d8ae3SPaolo Bonzini 	if (r < 0)
5439c50d8ae3SPaolo Bonzini 		return r;
544083a2ba4cSSean Christopherson 	if (r != RET_PF_EMULATE)
544183a2ba4cSSean Christopherson 		return 1;
5442c50d8ae3SPaolo Bonzini 
5443c50d8ae3SPaolo Bonzini 	/*
5444c50d8ae3SPaolo Bonzini 	 * Before emulating the instruction, check if the error code
5445c50d8ae3SPaolo Bonzini 	 * was due to a RO violation while translating the guest page.
5446c50d8ae3SPaolo Bonzini 	 * This can occur when using nested virtualization with nested
5447c50d8ae3SPaolo Bonzini 	 * paging in both guests. If true, we simply unprotect the page
5448c50d8ae3SPaolo Bonzini 	 * and resume the guest.
5449c50d8ae3SPaolo Bonzini 	 */
5450347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct &&
5451c50d8ae3SPaolo Bonzini 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5452736c291cSSean Christopherson 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5453c50d8ae3SPaolo Bonzini 		return 1;
5454c50d8ae3SPaolo Bonzini 	}
5455c50d8ae3SPaolo Bonzini 
5456c50d8ae3SPaolo Bonzini 	/*
5457c50d8ae3SPaolo Bonzini 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5458c50d8ae3SPaolo Bonzini 	 * optimistically try to just unprotect the page and let the processor
5459c50d8ae3SPaolo Bonzini 	 * re-execute the instruction that caused the page fault.  Do not allow
5460c50d8ae3SPaolo Bonzini 	 * retrying MMIO emulation, as it's not only pointless but could also
5461c50d8ae3SPaolo Bonzini 	 * cause us to enter an infinite loop because the processor will keep
5462c50d8ae3SPaolo Bonzini 	 * faulting on the non-existent MMIO address.  Retrying an instruction
5463c50d8ae3SPaolo Bonzini 	 * from a nested guest is also pointless and dangerous as we are only
5464c50d8ae3SPaolo Bonzini 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
5465c50d8ae3SPaolo Bonzini 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5466c50d8ae3SPaolo Bonzini 	 */
5467736c291cSSean Christopherson 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
546892daa48bSSean Christopherson 		emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5469c50d8ae3SPaolo Bonzini emulate:
5470736c291cSSean Christopherson 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5471c50d8ae3SPaolo Bonzini 				       insn_len);
5472c50d8ae3SPaolo Bonzini }
5473c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5474c50d8ae3SPaolo Bonzini 
54755efac074SPaolo Bonzini void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
54765efac074SPaolo Bonzini 			    gva_t gva, hpa_t root_hpa)
5477c50d8ae3SPaolo Bonzini {
5478c50d8ae3SPaolo Bonzini 	int i;
5479c50d8ae3SPaolo Bonzini 
54805efac074SPaolo Bonzini 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
54815efac074SPaolo Bonzini 	if (mmu != &vcpu->arch.guest_mmu) {
54825efac074SPaolo Bonzini 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
5483c50d8ae3SPaolo Bonzini 		if (is_noncanonical_address(gva, vcpu))
5484c50d8ae3SPaolo Bonzini 			return;
5485c50d8ae3SPaolo Bonzini 
5486e27bc044SSean Christopherson 		static_call(kvm_x86_flush_tlb_gva)(vcpu, gva);
54875efac074SPaolo Bonzini 	}
54885efac074SPaolo Bonzini 
54895efac074SPaolo Bonzini 	if (!mmu->invlpg)
54905efac074SPaolo Bonzini 		return;
54915efac074SPaolo Bonzini 
54925efac074SPaolo Bonzini 	if (root_hpa == INVALID_PAGE) {
5493b9e5603cSPaolo Bonzini 		mmu->invlpg(vcpu, gva, mmu->root.hpa);
5494c50d8ae3SPaolo Bonzini 
5495c50d8ae3SPaolo Bonzini 		/*
5496c50d8ae3SPaolo Bonzini 		 * INVLPG is required to invalidate any global mappings for the VA,
5497c50d8ae3SPaolo Bonzini 		 * irrespective of PCID. Since it would take us roughly similar amount
5498c50d8ae3SPaolo Bonzini 		 * of work to determine whether any of the prev_root mappings of the VA
5499c50d8ae3SPaolo Bonzini 		 * is marked global, or to just sync it blindly, so we might as well
5500c50d8ae3SPaolo Bonzini 		 * just always sync it.
5501c50d8ae3SPaolo Bonzini 		 *
5502c50d8ae3SPaolo Bonzini 		 * Mappings not reachable via the current cr3 or the prev_roots will be
5503c50d8ae3SPaolo Bonzini 		 * synced when switching to that cr3, so nothing needs to be done here
5504c50d8ae3SPaolo Bonzini 		 * for them.
5505c50d8ae3SPaolo Bonzini 		 */
5506c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5507c50d8ae3SPaolo Bonzini 			if (VALID_PAGE(mmu->prev_roots[i].hpa))
5508c50d8ae3SPaolo Bonzini 				mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
55095efac074SPaolo Bonzini 	} else {
55105efac074SPaolo Bonzini 		mmu->invlpg(vcpu, gva, root_hpa);
55115efac074SPaolo Bonzini 	}
55125efac074SPaolo Bonzini }
5513c50d8ae3SPaolo Bonzini 
55145efac074SPaolo Bonzini void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
55155efac074SPaolo Bonzini {
551605b29633SLai Jiangshan 	kvm_mmu_invalidate_gva(vcpu, vcpu->arch.walk_mmu, gva, INVALID_PAGE);
5517c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5518c50d8ae3SPaolo Bonzini }
5519c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5520c50d8ae3SPaolo Bonzini 
55215efac074SPaolo Bonzini 
5522c50d8ae3SPaolo Bonzini void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5523c50d8ae3SPaolo Bonzini {
5524c50d8ae3SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
5525c50d8ae3SPaolo Bonzini 	bool tlb_flush = false;
5526c50d8ae3SPaolo Bonzini 	uint i;
5527c50d8ae3SPaolo Bonzini 
5528c50d8ae3SPaolo Bonzini 	if (pcid == kvm_get_active_pcid(vcpu)) {
55299f46c187SPaolo Bonzini 		if (mmu->invlpg)
5530b9e5603cSPaolo Bonzini 			mmu->invlpg(vcpu, gva, mmu->root.hpa);
5531c50d8ae3SPaolo Bonzini 		tlb_flush = true;
5532c50d8ae3SPaolo Bonzini 	}
5533c50d8ae3SPaolo Bonzini 
5534c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5535c50d8ae3SPaolo Bonzini 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5536be01e8e2SSean Christopherson 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
55379f46c187SPaolo Bonzini 			if (mmu->invlpg)
5538c50d8ae3SPaolo Bonzini 				mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5539c50d8ae3SPaolo Bonzini 			tlb_flush = true;
5540c50d8ae3SPaolo Bonzini 		}
5541c50d8ae3SPaolo Bonzini 	}
5542c50d8ae3SPaolo Bonzini 
5543c50d8ae3SPaolo Bonzini 	if (tlb_flush)
5544e27bc044SSean Christopherson 		static_call(kvm_x86_flush_tlb_gva)(vcpu, gva);
5545c50d8ae3SPaolo Bonzini 
5546c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5547c50d8ae3SPaolo Bonzini 
5548c50d8ae3SPaolo Bonzini 	/*
5549c50d8ae3SPaolo Bonzini 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5550c50d8ae3SPaolo Bonzini 	 * synced when switching to that cr3, so nothing needs to be done here
5551c50d8ae3SPaolo Bonzini 	 * for them.
5552c50d8ae3SPaolo Bonzini 	 */
5553c50d8ae3SPaolo Bonzini }
5554c50d8ae3SPaolo Bonzini 
5555746700d2SWei Huang void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
5556746700d2SWei Huang 		       int tdp_max_root_level, int tdp_huge_page_level)
5557c50d8ae3SPaolo Bonzini {
5558bde77235SSean Christopherson 	tdp_enabled = enable_tdp;
5559746700d2SWei Huang 	tdp_root_level = tdp_forced_root_level;
556083013059SSean Christopherson 	max_tdp_level = tdp_max_root_level;
5561703c335dSSean Christopherson 
5562703c335dSSean Christopherson 	/*
55631d92d2e8SSean Christopherson 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5564703c335dSSean Christopherson 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5565703c335dSSean Christopherson 	 * the kernel is not.  But, KVM never creates a page size greater than
5566703c335dSSean Christopherson 	 * what is used by the kernel for any given HVA, i.e. the kernel's
5567703c335dSSean Christopherson 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5568703c335dSSean Christopherson 	 */
5569703c335dSSean Christopherson 	if (tdp_enabled)
55701d92d2e8SSean Christopherson 		max_huge_page_level = tdp_huge_page_level;
5571703c335dSSean Christopherson 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
55721d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_1G;
5573703c335dSSean Christopherson 	else
55741d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_2M;
5575c50d8ae3SPaolo Bonzini }
5576bde77235SSean Christopherson EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5577c50d8ae3SPaolo Bonzini 
5578c50d8ae3SPaolo Bonzini /* The return value indicates if tlb flush on all vcpus is needed. */
5579269e9552SHamza Mahfooz typedef bool (*slot_level_handler) (struct kvm *kvm,
5580269e9552SHamza Mahfooz 				    struct kvm_rmap_head *rmap_head,
5581269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot);
5582c50d8ae3SPaolo Bonzini 
5583c50d8ae3SPaolo Bonzini /* The caller should hold mmu-lock before calling this function. */
5584c50d8ae3SPaolo Bonzini static __always_inline bool
5585269e9552SHamza Mahfooz slot_handle_level_range(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5586c50d8ae3SPaolo Bonzini 			slot_level_handler fn, int start_level, int end_level,
55871a61b7dbSSean Christopherson 			gfn_t start_gfn, gfn_t end_gfn, bool flush_on_yield,
55881a61b7dbSSean Christopherson 			bool flush)
5589c50d8ae3SPaolo Bonzini {
5590c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
5591c50d8ae3SPaolo Bonzini 
5592c50d8ae3SPaolo Bonzini 	for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5593c50d8ae3SPaolo Bonzini 			end_gfn, &iterator) {
5594c50d8ae3SPaolo Bonzini 		if (iterator.rmap)
55950a234f5dSSean Christopherson 			flush |= fn(kvm, iterator.rmap, memslot);
5596c50d8ae3SPaolo Bonzini 
5597531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
5598302695a5SSean Christopherson 			if (flush && flush_on_yield) {
5599c50d8ae3SPaolo Bonzini 				kvm_flush_remote_tlbs_with_address(kvm,
5600c50d8ae3SPaolo Bonzini 						start_gfn,
5601c50d8ae3SPaolo Bonzini 						iterator.gfn - start_gfn + 1);
5602c50d8ae3SPaolo Bonzini 				flush = false;
5603c50d8ae3SPaolo Bonzini 			}
5604531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
5605c50d8ae3SPaolo Bonzini 		}
5606c50d8ae3SPaolo Bonzini 	}
5607c50d8ae3SPaolo Bonzini 
5608c50d8ae3SPaolo Bonzini 	return flush;
5609c50d8ae3SPaolo Bonzini }
5610c50d8ae3SPaolo Bonzini 
5611c50d8ae3SPaolo Bonzini static __always_inline bool
5612269e9552SHamza Mahfooz slot_handle_level(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5613c50d8ae3SPaolo Bonzini 		  slot_level_handler fn, int start_level, int end_level,
5614302695a5SSean Christopherson 		  bool flush_on_yield)
5615c50d8ae3SPaolo Bonzini {
5616c50d8ae3SPaolo Bonzini 	return slot_handle_level_range(kvm, memslot, fn, start_level,
5617c50d8ae3SPaolo Bonzini 			end_level, memslot->base_gfn,
5618c50d8ae3SPaolo Bonzini 			memslot->base_gfn + memslot->npages - 1,
56191a61b7dbSSean Christopherson 			flush_on_yield, false);
5620c50d8ae3SPaolo Bonzini }
5621c50d8ae3SPaolo Bonzini 
5622c50d8ae3SPaolo Bonzini static __always_inline bool
5623610265eaSDavid Matlack slot_handle_level_4k(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5624302695a5SSean Christopherson 		     slot_level_handler fn, bool flush_on_yield)
5625c50d8ae3SPaolo Bonzini {
56263bae0459SSean Christopherson 	return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5627302695a5SSean Christopherson 				 PG_LEVEL_4K, flush_on_yield);
5628c50d8ae3SPaolo Bonzini }
5629c50d8ae3SPaolo Bonzini 
5630c50d8ae3SPaolo Bonzini static void free_mmu_pages(struct kvm_mmu *mmu)
5631c50d8ae3SPaolo Bonzini {
56324a98623dSSean Christopherson 	if (!tdp_enabled && mmu->pae_root)
56334a98623dSSean Christopherson 		set_memory_encrypted((unsigned long)mmu->pae_root, 1);
5634c50d8ae3SPaolo Bonzini 	free_page((unsigned long)mmu->pae_root);
563503ca4589SSean Christopherson 	free_page((unsigned long)mmu->pml4_root);
5636cb0f722aSWei Huang 	free_page((unsigned long)mmu->pml5_root);
5637c50d8ae3SPaolo Bonzini }
5638c50d8ae3SPaolo Bonzini 
563904d28e37SSean Christopherson static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5640c50d8ae3SPaolo Bonzini {
5641c50d8ae3SPaolo Bonzini 	struct page *page;
5642c50d8ae3SPaolo Bonzini 	int i;
5643c50d8ae3SPaolo Bonzini 
5644b9e5603cSPaolo Bonzini 	mmu->root.hpa = INVALID_PAGE;
5645b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
564604d28e37SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
564704d28e37SSean Christopherson 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
564804d28e37SSean Christopherson 
564927f4fca2SLai Jiangshan 	/* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
565027f4fca2SLai Jiangshan 	if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
565127f4fca2SLai Jiangshan 		return 0;
565227f4fca2SLai Jiangshan 
5653c50d8ae3SPaolo Bonzini 	/*
5654c50d8ae3SPaolo Bonzini 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5655c50d8ae3SPaolo Bonzini 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
5656c50d8ae3SPaolo Bonzini 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
5657c50d8ae3SPaolo Bonzini 	 * x86_64.  Therefore we need to allocate the PDP table in the first
565804d45551SSean Christopherson 	 * 4GB of memory, which happens to fit the DMA32 zone.  TDP paging
565904d45551SSean Christopherson 	 * generally doesn't use PAE paging and can skip allocating the PDP
566004d45551SSean Christopherson 	 * table.  The main exception, handled here, is SVM's 32-bit NPT.  The
566104d45551SSean Christopherson 	 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
566284432316SLai Jiangshan 	 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
5663c50d8ae3SPaolo Bonzini 	 */
5664d468d94bSSean Christopherson 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5665c50d8ae3SPaolo Bonzini 		return 0;
5666c50d8ae3SPaolo Bonzini 
5667c50d8ae3SPaolo Bonzini 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5668c50d8ae3SPaolo Bonzini 	if (!page)
5669c50d8ae3SPaolo Bonzini 		return -ENOMEM;
5670c50d8ae3SPaolo Bonzini 
5671c50d8ae3SPaolo Bonzini 	mmu->pae_root = page_address(page);
56724a98623dSSean Christopherson 
56734a98623dSSean Christopherson 	/*
56744a98623dSSean Christopherson 	 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
56754a98623dSSean Christopherson 	 * get the CPU to treat the PDPTEs as encrypted.  Decrypt the page so
56764a98623dSSean Christopherson 	 * that KVM's writes and the CPU's reads get along.  Note, this is
56774a98623dSSean Christopherson 	 * only necessary when using shadow paging, as 64-bit NPT can get at
56784a98623dSSean Christopherson 	 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
56794a98623dSSean Christopherson 	 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
56804a98623dSSean Christopherson 	 */
56814a98623dSSean Christopherson 	if (!tdp_enabled)
56824a98623dSSean Christopherson 		set_memory_decrypted((unsigned long)mmu->pae_root, 1);
56834a98623dSSean Christopherson 	else
5684e54f1ff2SKai Huang 		WARN_ON_ONCE(shadow_me_value);
56854a98623dSSean Christopherson 
5686c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i)
5687c834e5e4SSean Christopherson 		mmu->pae_root[i] = INVALID_PAE_ROOT;
5688c50d8ae3SPaolo Bonzini 
5689c50d8ae3SPaolo Bonzini 	return 0;
5690c50d8ae3SPaolo Bonzini }
5691c50d8ae3SPaolo Bonzini 
5692c50d8ae3SPaolo Bonzini int kvm_mmu_create(struct kvm_vcpu *vcpu)
5693c50d8ae3SPaolo Bonzini {
5694c50d8ae3SPaolo Bonzini 	int ret;
5695c50d8ae3SPaolo Bonzini 
56965962bfb7SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
56975f6078f9SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
56985f6078f9SSean Christopherson 
56995962bfb7SSean Christopherson 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
57005f6078f9SSean Christopherson 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
57015962bfb7SSean Christopherson 
570296880883SSean Christopherson 	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
570396880883SSean Christopherson 
5704c50d8ae3SPaolo Bonzini 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
5705c50d8ae3SPaolo Bonzini 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5706c50d8ae3SPaolo Bonzini 
570704d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
5708c50d8ae3SPaolo Bonzini 	if (ret)
5709c50d8ae3SPaolo Bonzini 		return ret;
5710c50d8ae3SPaolo Bonzini 
571104d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
5712c50d8ae3SPaolo Bonzini 	if (ret)
5713c50d8ae3SPaolo Bonzini 		goto fail_allocate_root;
5714c50d8ae3SPaolo Bonzini 
5715c50d8ae3SPaolo Bonzini 	return ret;
5716c50d8ae3SPaolo Bonzini  fail_allocate_root:
5717c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
5718c50d8ae3SPaolo Bonzini 	return ret;
5719c50d8ae3SPaolo Bonzini }
5720c50d8ae3SPaolo Bonzini 
5721c50d8ae3SPaolo Bonzini #define BATCH_ZAP_PAGES	10
5722c50d8ae3SPaolo Bonzini static void kvm_zap_obsolete_pages(struct kvm *kvm)
5723c50d8ae3SPaolo Bonzini {
5724c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
5725c50d8ae3SPaolo Bonzini 	int nr_zapped, batch = 0;
5726b28cb0cdSSean Christopherson 	bool unstable;
5727c50d8ae3SPaolo Bonzini 
5728c50d8ae3SPaolo Bonzini restart:
5729c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe_reverse(sp, node,
5730c50d8ae3SPaolo Bonzini 	      &kvm->arch.active_mmu_pages, link) {
5731c50d8ae3SPaolo Bonzini 		/*
5732c50d8ae3SPaolo Bonzini 		 * No obsolete valid page exists before a newly created page
5733c50d8ae3SPaolo Bonzini 		 * since active_mmu_pages is a FIFO list.
5734c50d8ae3SPaolo Bonzini 		 */
5735c50d8ae3SPaolo Bonzini 		if (!is_obsolete_sp(kvm, sp))
5736c50d8ae3SPaolo Bonzini 			break;
5737c50d8ae3SPaolo Bonzini 
5738c50d8ae3SPaolo Bonzini 		/*
5739f95eec9bSSean Christopherson 		 * Invalid pages should never land back on the list of active
5740f95eec9bSSean Christopherson 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
5741f95eec9bSSean Christopherson 		 * infinite loop if the page gets put back on the list (again).
5742c50d8ae3SPaolo Bonzini 		 */
5743f95eec9bSSean Christopherson 		if (WARN_ON(sp->role.invalid))
5744c50d8ae3SPaolo Bonzini 			continue;
5745c50d8ae3SPaolo Bonzini 
5746c50d8ae3SPaolo Bonzini 		/*
5747c50d8ae3SPaolo Bonzini 		 * No need to flush the TLB since we're only zapping shadow
5748c50d8ae3SPaolo Bonzini 		 * pages with an obsolete generation number and all vCPUS have
5749c50d8ae3SPaolo Bonzini 		 * loaded a new root, i.e. the shadow pages being zapped cannot
5750c50d8ae3SPaolo Bonzini 		 * be in active use by the guest.
5751c50d8ae3SPaolo Bonzini 		 */
5752c50d8ae3SPaolo Bonzini 		if (batch >= BATCH_ZAP_PAGES &&
5753531810caSBen Gardon 		    cond_resched_rwlock_write(&kvm->mmu_lock)) {
5754c50d8ae3SPaolo Bonzini 			batch = 0;
5755c50d8ae3SPaolo Bonzini 			goto restart;
5756c50d8ae3SPaolo Bonzini 		}
5757c50d8ae3SPaolo Bonzini 
5758b28cb0cdSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
5759b28cb0cdSSean Christopherson 				&kvm->arch.zapped_obsolete_pages, &nr_zapped);
5760c50d8ae3SPaolo Bonzini 		batch += nr_zapped;
5761b28cb0cdSSean Christopherson 
5762b28cb0cdSSean Christopherson 		if (unstable)
5763c50d8ae3SPaolo Bonzini 			goto restart;
5764c50d8ae3SPaolo Bonzini 	}
5765c50d8ae3SPaolo Bonzini 
5766c50d8ae3SPaolo Bonzini 	/*
57677ae5840eSSean Christopherson 	 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
57687ae5840eSSean Christopherson 	 * to ensure KVM is not in the middle of a lockless shadow page table
57697ae5840eSSean Christopherson 	 * walk, which may reference the pages.  The remote TLB flush itself is
57707ae5840eSSean Christopherson 	 * not required and is simply a convenient way to kick vCPUs as needed.
57717ae5840eSSean Christopherson 	 * KVM performs a local TLB flush when allocating a new root (see
57727ae5840eSSean Christopherson 	 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
57737ae5840eSSean Christopherson 	 * running with an obsolete MMU.
5774c50d8ae3SPaolo Bonzini 	 */
5775c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5776c50d8ae3SPaolo Bonzini }
5777c50d8ae3SPaolo Bonzini 
5778c50d8ae3SPaolo Bonzini /*
5779c50d8ae3SPaolo Bonzini  * Fast invalidate all shadow pages and use lock-break technique
5780c50d8ae3SPaolo Bonzini  * to zap obsolete pages.
5781c50d8ae3SPaolo Bonzini  *
5782c50d8ae3SPaolo Bonzini  * It's required when memslot is being deleted or VM is being
5783c50d8ae3SPaolo Bonzini  * destroyed, in these cases, we should ensure that KVM MMU does
5784c50d8ae3SPaolo Bonzini  * not use any resource of the being-deleted slot or all slots
5785c50d8ae3SPaolo Bonzini  * after calling the function.
5786c50d8ae3SPaolo Bonzini  */
5787c50d8ae3SPaolo Bonzini static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5788c50d8ae3SPaolo Bonzini {
5789c50d8ae3SPaolo Bonzini 	lockdep_assert_held(&kvm->slots_lock);
5790c50d8ae3SPaolo Bonzini 
5791531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
5792c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_zap_all_fast(kvm);
5793c50d8ae3SPaolo Bonzini 
5794c50d8ae3SPaolo Bonzini 	/*
5795c50d8ae3SPaolo Bonzini 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
5796c50d8ae3SPaolo Bonzini 	 * held for the entire duration of zapping obsolete pages, it's
5797c50d8ae3SPaolo Bonzini 	 * impossible for there to be multiple invalid generations associated
5798c50d8ae3SPaolo Bonzini 	 * with *valid* shadow pages at any given time, i.e. there is exactly
5799c50d8ae3SPaolo Bonzini 	 * one valid generation and (at most) one invalid generation.
5800c50d8ae3SPaolo Bonzini 	 */
5801c50d8ae3SPaolo Bonzini 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5802c50d8ae3SPaolo Bonzini 
58032f6f66ccSSean Christopherson 	/*
58042f6f66ccSSean Christopherson 	 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
58052f6f66ccSSean Christopherson 	 * invalidating TDP MMU roots must be done while holding mmu_lock for
58062f6f66ccSSean Christopherson 	 * write and in the same critical section as making the reload request,
58072f6f66ccSSean Christopherson 	 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
5808b7cccd39SBen Gardon 	 */
5809b7cccd39SBen Gardon 	if (is_tdp_mmu_enabled(kvm))
5810b7cccd39SBen Gardon 		kvm_tdp_mmu_invalidate_all_roots(kvm);
5811b7cccd39SBen Gardon 
5812c50d8ae3SPaolo Bonzini 	/*
5813c50d8ae3SPaolo Bonzini 	 * Notify all vcpus to reload its shadow page table and flush TLB.
5814c50d8ae3SPaolo Bonzini 	 * Then all vcpus will switch to new shadow page table with the new
5815c50d8ae3SPaolo Bonzini 	 * mmu_valid_gen.
5816c50d8ae3SPaolo Bonzini 	 *
5817c50d8ae3SPaolo Bonzini 	 * Note: we need to do this under the protection of mmu_lock,
5818c50d8ae3SPaolo Bonzini 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
5819c50d8ae3SPaolo Bonzini 	 */
5820527d5cd7SSean Christopherson 	kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
5821c50d8ae3SPaolo Bonzini 
5822c50d8ae3SPaolo Bonzini 	kvm_zap_obsolete_pages(kvm);
5823faaf05b0SBen Gardon 
5824531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
58254c6654bdSBen Gardon 
5826f28e9c7fSSean Christopherson 	/*
5827f28e9c7fSSean Christopherson 	 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
5828f28e9c7fSSean Christopherson 	 * returning to the caller, e.g. if the zap is in response to a memslot
5829f28e9c7fSSean Christopherson 	 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
5830f28e9c7fSSean Christopherson 	 * associated with the deleted memslot once the update completes, and
5831f28e9c7fSSean Christopherson 	 * Deferring the zap until the final reference to the root is put would
5832f28e9c7fSSean Christopherson 	 * lead to use-after-free.
5833f28e9c7fSSean Christopherson 	 */
583422b94c4bSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
58354c6654bdSBen Gardon 		kvm_tdp_mmu_zap_invalidated_roots(kvm);
5836c50d8ae3SPaolo Bonzini }
5837c50d8ae3SPaolo Bonzini 
5838c50d8ae3SPaolo Bonzini static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5839c50d8ae3SPaolo Bonzini {
5840c50d8ae3SPaolo Bonzini 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5841c50d8ae3SPaolo Bonzini }
5842c50d8ae3SPaolo Bonzini 
5843c50d8ae3SPaolo Bonzini static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5844c50d8ae3SPaolo Bonzini 			struct kvm_memory_slot *slot,
5845c50d8ae3SPaolo Bonzini 			struct kvm_page_track_notifier_node *node)
5846c50d8ae3SPaolo Bonzini {
5847c50d8ae3SPaolo Bonzini 	kvm_mmu_zap_all_fast(kvm);
5848c50d8ae3SPaolo Bonzini }
5849c50d8ae3SPaolo Bonzini 
5850a1a39128SPaolo Bonzini int kvm_mmu_init_vm(struct kvm *kvm)
5851c50d8ae3SPaolo Bonzini {
5852c50d8ae3SPaolo Bonzini 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5853a1a39128SPaolo Bonzini 	int r;
5854c50d8ae3SPaolo Bonzini 
5855a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
5856a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
5857a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.lpage_disallowed_mmu_pages);
5858ce25681dSSean Christopherson 	spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
5859ce25681dSSean Christopherson 
5860a1a39128SPaolo Bonzini 	r = kvm_mmu_init_tdp_mmu(kvm);
5861a1a39128SPaolo Bonzini 	if (r < 0)
5862a1a39128SPaolo Bonzini 		return r;
5863fe5db27dSBen Gardon 
5864c50d8ae3SPaolo Bonzini 	node->track_write = kvm_mmu_pte_write;
5865c50d8ae3SPaolo Bonzini 	node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5866c50d8ae3SPaolo Bonzini 	kvm_page_track_register_notifier(kvm, node);
5867a1a39128SPaolo Bonzini 	return 0;
5868c50d8ae3SPaolo Bonzini }
5869c50d8ae3SPaolo Bonzini 
5870c50d8ae3SPaolo Bonzini void kvm_mmu_uninit_vm(struct kvm *kvm)
5871c50d8ae3SPaolo Bonzini {
5872c50d8ae3SPaolo Bonzini 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5873c50d8ae3SPaolo Bonzini 
5874c50d8ae3SPaolo Bonzini 	kvm_page_track_unregister_notifier(kvm, node);
5875fe5db27dSBen Gardon 
5876fe5db27dSBen Gardon 	kvm_mmu_uninit_tdp_mmu(kvm);
5877c50d8ae3SPaolo Bonzini }
5878c50d8ae3SPaolo Bonzini 
587921fa3246SSean Christopherson static bool __kvm_zap_rmaps(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
588021fa3246SSean Christopherson {
588121fa3246SSean Christopherson 	const struct kvm_memory_slot *memslot;
588221fa3246SSean Christopherson 	struct kvm_memslots *slots;
5883f4209439SMaciej S. Szmigiero 	struct kvm_memslot_iter iter;
588421fa3246SSean Christopherson 	bool flush = false;
588521fa3246SSean Christopherson 	gfn_t start, end;
5886f4209439SMaciej S. Szmigiero 	int i;
588721fa3246SSean Christopherson 
588821fa3246SSean Christopherson 	if (!kvm_memslots_have_rmaps(kvm))
588921fa3246SSean Christopherson 		return flush;
589021fa3246SSean Christopherson 
589121fa3246SSean Christopherson 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
589221fa3246SSean Christopherson 		slots = __kvm_memslots(kvm, i);
5893f4209439SMaciej S. Szmigiero 
5894f4209439SMaciej S. Szmigiero 		kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
5895f4209439SMaciej S. Szmigiero 			memslot = iter.slot;
589621fa3246SSean Christopherson 			start = max(gfn_start, memslot->base_gfn);
589721fa3246SSean Christopherson 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
5898f4209439SMaciej S. Szmigiero 			if (WARN_ON_ONCE(start >= end))
589921fa3246SSean Christopherson 				continue;
590021fa3246SSean Christopherson 
590121fa3246SSean Christopherson 			flush = slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
59026ff94f27SDavid Matlack 
590321fa3246SSean Christopherson 							PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
590421fa3246SSean Christopherson 							start, end - 1, true, flush);
590521fa3246SSean Christopherson 		}
590621fa3246SSean Christopherson 	}
590721fa3246SSean Christopherson 
590821fa3246SSean Christopherson 	return flush;
590921fa3246SSean Christopherson }
591021fa3246SSean Christopherson 
591188f58535SMaxim Levitsky /*
591288f58535SMaxim Levitsky  * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
591388f58535SMaxim Levitsky  * (not including it)
591488f58535SMaxim Levitsky  */
5915c50d8ae3SPaolo Bonzini void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5916c50d8ae3SPaolo Bonzini {
591721fa3246SSean Christopherson 	bool flush;
5918c50d8ae3SPaolo Bonzini 	int i;
5919c50d8ae3SPaolo Bonzini 
5920f4209439SMaciej S. Szmigiero 	if (WARN_ON_ONCE(gfn_end <= gfn_start))
5921f4209439SMaciej S. Szmigiero 		return;
5922f4209439SMaciej S. Szmigiero 
5923531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
59245a324c24SSean Christopherson 
5925edb298c6SMaxim Levitsky 	kvm_inc_notifier_count(kvm, gfn_start, gfn_end);
5926edb298c6SMaxim Levitsky 
592721fa3246SSean Christopherson 	flush = __kvm_zap_rmaps(kvm, gfn_start, gfn_end);
59286103bc07SBen Gardon 
59296103bc07SBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
59306103bc07SBen Gardon 		for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
5931f47e5bbbSSean Christopherson 			flush = kvm_tdp_mmu_zap_leafs(kvm, i, gfn_start,
5932f47e5bbbSSean Christopherson 						      gfn_end, true, flush);
59336103bc07SBen Gardon 	}
59345a324c24SSean Christopherson 
59355a324c24SSean Christopherson 	if (flush)
5936bc3b3c10SSean Christopherson 		kvm_flush_remote_tlbs_with_address(kvm, gfn_start,
5937bc3b3c10SSean Christopherson 						   gfn_end - gfn_start);
59385a324c24SSean Christopherson 
5939edb298c6SMaxim Levitsky 	kvm_dec_notifier_count(kvm, gfn_start, gfn_end);
5940edb298c6SMaxim Levitsky 
59415a324c24SSean Christopherson 	write_unlock(&kvm->mmu_lock);
5942c50d8ae3SPaolo Bonzini }
5943c50d8ae3SPaolo Bonzini 
5944c50d8ae3SPaolo Bonzini static bool slot_rmap_write_protect(struct kvm *kvm,
59450a234f5dSSean Christopherson 				    struct kvm_rmap_head *rmap_head,
5946269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot)
5947c50d8ae3SPaolo Bonzini {
59481346bbb6SDavid Matlack 	return rmap_write_protect(rmap_head, false);
5949c50d8ae3SPaolo Bonzini }
5950c50d8ae3SPaolo Bonzini 
5951c50d8ae3SPaolo Bonzini void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5952269e9552SHamza Mahfooz 				      const struct kvm_memory_slot *memslot,
59533c9bd400SJay Zhou 				      int start_level)
5954c50d8ae3SPaolo Bonzini {
5955e2209710SBen Gardon 	bool flush = false;
5956c50d8ae3SPaolo Bonzini 
5957e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
5958531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
59593c9bd400SJay Zhou 		flush = slot_handle_level(kvm, memslot, slot_rmap_write_protect,
5960e2209710SBen Gardon 					  start_level, KVM_MAX_HUGEPAGE_LEVEL,
5961e2209710SBen Gardon 					  false);
5962531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
5963e2209710SBen Gardon 	}
5964c50d8ae3SPaolo Bonzini 
596524ae4cfaSBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
596624ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
596724ae4cfaSBen Gardon 		flush |= kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
596824ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
596924ae4cfaSBen Gardon 	}
597024ae4cfaSBen Gardon 
5971c50d8ae3SPaolo Bonzini 	/*
59726ff94f27SDavid Matlack 	 * Flush TLBs if any SPTEs had to be write-protected to ensure that
59736ff94f27SDavid Matlack 	 * guest writes are reflected in the dirty bitmap before the memslot
59746ff94f27SDavid Matlack 	 * update completes, i.e. before enabling dirty logging is visible to
59756ff94f27SDavid Matlack 	 * userspace.
59766ff94f27SDavid Matlack 	 *
59776ff94f27SDavid Matlack 	 * Perform the TLB flush outside the mmu_lock to reduce the amount of
59786ff94f27SDavid Matlack 	 * time the lock is held. However, this does mean that another CPU can
59796ff94f27SDavid Matlack 	 * now grab mmu_lock and encounter a write-protected SPTE while CPUs
59806ff94f27SDavid Matlack 	 * still have a writable mapping for the associated GFN in their TLB.
59816ff94f27SDavid Matlack 	 *
59826ff94f27SDavid Matlack 	 * This is safe but requires KVM to be careful when making decisions
59836ff94f27SDavid Matlack 	 * based on the write-protection status of an SPTE. Specifically, KVM
59846ff94f27SDavid Matlack 	 * also write-protects SPTEs to monitor changes to guest page tables
59856ff94f27SDavid Matlack 	 * during shadow paging, and must guarantee no CPUs can write to those
59866ff94f27SDavid Matlack 	 * page before the lock is dropped. As mentioned in the previous
59876ff94f27SDavid Matlack 	 * paragraph, a write-protected SPTE is no guarantee that CPU cannot
59886ff94f27SDavid Matlack 	 * perform writes. So to determine if a TLB flush is truly required, KVM
59896ff94f27SDavid Matlack 	 * will clear a separate software-only bit (MMU-writable) and skip the
59906ff94f27SDavid Matlack 	 * flush if-and-only-if this bit was already clear.
59916ff94f27SDavid Matlack 	 *
599202844ac1SDavid Matlack 	 * See is_writable_pte() for more details.
5993c50d8ae3SPaolo Bonzini 	 */
5994c50d8ae3SPaolo Bonzini 	if (flush)
59957f42aa76SSean Christopherson 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
5996c50d8ae3SPaolo Bonzini }
5997c50d8ae3SPaolo Bonzini 
5998cb00a70bSDavid Matlack /* Must be called with the mmu_lock held in write-mode. */
5999cb00a70bSDavid Matlack void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6000cb00a70bSDavid Matlack 				   const struct kvm_memory_slot *memslot,
6001cb00a70bSDavid Matlack 				   u64 start, u64 end,
6002cb00a70bSDavid Matlack 				   int target_level)
6003cb00a70bSDavid Matlack {
6004cb00a70bSDavid Matlack 	if (is_tdp_mmu_enabled(kvm))
6005cb00a70bSDavid Matlack 		kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end,
6006cb00a70bSDavid Matlack 						 target_level, false);
6007cb00a70bSDavid Matlack 
6008cb00a70bSDavid Matlack 	/*
6009cb00a70bSDavid Matlack 	 * A TLB flush is unnecessary at this point for the same resons as in
6010cb00a70bSDavid Matlack 	 * kvm_mmu_slot_try_split_huge_pages().
6011cb00a70bSDavid Matlack 	 */
6012cb00a70bSDavid Matlack }
6013cb00a70bSDavid Matlack 
6014a3fe5dbdSDavid Matlack void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6015a3fe5dbdSDavid Matlack 					const struct kvm_memory_slot *memslot,
6016a3fe5dbdSDavid Matlack 					int target_level)
6017a3fe5dbdSDavid Matlack {
6018a3fe5dbdSDavid Matlack 	u64 start = memslot->base_gfn;
6019a3fe5dbdSDavid Matlack 	u64 end = start + memslot->npages;
6020a3fe5dbdSDavid Matlack 
6021a3fe5dbdSDavid Matlack 	if (is_tdp_mmu_enabled(kvm)) {
6022a3fe5dbdSDavid Matlack 		read_lock(&kvm->mmu_lock);
6023cb00a70bSDavid Matlack 		kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6024a3fe5dbdSDavid Matlack 		read_unlock(&kvm->mmu_lock);
6025a3fe5dbdSDavid Matlack 	}
6026a3fe5dbdSDavid Matlack 
6027a3fe5dbdSDavid Matlack 	/*
6028a3fe5dbdSDavid Matlack 	 * No TLB flush is necessary here. KVM will flush TLBs after
6029a3fe5dbdSDavid Matlack 	 * write-protecting and/or clearing dirty on the newly split SPTEs to
6030a3fe5dbdSDavid Matlack 	 * ensure that guest writes are reflected in the dirty log before the
6031a3fe5dbdSDavid Matlack 	 * ioctl to enable dirty logging on this memslot completes. Since the
6032a3fe5dbdSDavid Matlack 	 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6033a3fe5dbdSDavid Matlack 	 * safe for KVM to decide if a TLB flush is necessary based on the split
6034a3fe5dbdSDavid Matlack 	 * SPTEs.
6035a3fe5dbdSDavid Matlack 	 */
6036a3fe5dbdSDavid Matlack }
6037a3fe5dbdSDavid Matlack 
6038c50d8ae3SPaolo Bonzini static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
60390a234f5dSSean Christopherson 					 struct kvm_rmap_head *rmap_head,
6040269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
6041c50d8ae3SPaolo Bonzini {
6042c50d8ae3SPaolo Bonzini 	u64 *sptep;
6043c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
6044c50d8ae3SPaolo Bonzini 	int need_tlb_flush = 0;
6045c50d8ae3SPaolo Bonzini 	kvm_pfn_t pfn;
6046c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6047c50d8ae3SPaolo Bonzini 
6048c50d8ae3SPaolo Bonzini restart:
6049c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
605057354682SSean Christopherson 		sp = sptep_to_sp(sptep);
6051c50d8ae3SPaolo Bonzini 		pfn = spte_to_pfn(*sptep);
6052c50d8ae3SPaolo Bonzini 
6053c50d8ae3SPaolo Bonzini 		/*
6054c50d8ae3SPaolo Bonzini 		 * We cannot do huge page mapping for indirect shadow pages,
6055c50d8ae3SPaolo Bonzini 		 * which are found on the last rmap (level = 1) when not using
6056c50d8ae3SPaolo Bonzini 		 * tdp; such shadow pages are synced with the page table in
6057c50d8ae3SPaolo Bonzini 		 * the guest, and the guest page table is using 4K page size
6058c50d8ae3SPaolo Bonzini 		 * mapping if the indirect sp has level = 1.
6059c50d8ae3SPaolo Bonzini 		 */
60605d49f08cSSean Christopherson 		if (sp->role.direct &&
60619eba50f8SSean Christopherson 		    sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
60629eba50f8SSean Christopherson 							       pfn, PG_LEVEL_NUM)) {
606371f51d2cSMingwei Zhang 			pte_list_remove(kvm, rmap_head, sptep);
6064c50d8ae3SPaolo Bonzini 
6065c50d8ae3SPaolo Bonzini 			if (kvm_available_flush_tlb_with_range())
6066c50d8ae3SPaolo Bonzini 				kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
6067c50d8ae3SPaolo Bonzini 					KVM_PAGES_PER_HPAGE(sp->role.level));
6068c50d8ae3SPaolo Bonzini 			else
6069c50d8ae3SPaolo Bonzini 				need_tlb_flush = 1;
6070c50d8ae3SPaolo Bonzini 
6071c50d8ae3SPaolo Bonzini 			goto restart;
6072c50d8ae3SPaolo Bonzini 		}
6073c50d8ae3SPaolo Bonzini 	}
6074c50d8ae3SPaolo Bonzini 
6075c50d8ae3SPaolo Bonzini 	return need_tlb_flush;
6076c50d8ae3SPaolo Bonzini }
6077c50d8ae3SPaolo Bonzini 
6078c50d8ae3SPaolo Bonzini void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6079269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *slot)
6080c50d8ae3SPaolo Bonzini {
6081e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6082531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6083610265eaSDavid Matlack 		/*
6084610265eaSDavid Matlack 		 * Zap only 4k SPTEs since the legacy MMU only supports dirty
6085610265eaSDavid Matlack 		 * logging at a 4k granularity and never creates collapsible
6086610265eaSDavid Matlack 		 * 2m SPTEs during dirty logging.
6087610265eaSDavid Matlack 		 */
60884b85c921SSean Christopherson 		if (slot_handle_level_4k(kvm, slot, kvm_mmu_zap_collapsible_spte, true))
6089302695a5SSean Christopherson 			kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
6090531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6091e2209710SBen Gardon 	}
60922db6f772SBen Gardon 
60932db6f772SBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
60942db6f772SBen Gardon 		read_lock(&kvm->mmu_lock);
60954b85c921SSean Christopherson 		kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
60962db6f772SBen Gardon 		read_unlock(&kvm->mmu_lock);
60972db6f772SBen Gardon 	}
6098c50d8ae3SPaolo Bonzini }
6099c50d8ae3SPaolo Bonzini 
6100b3594ffbSSean Christopherson void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
61016c9dd6d2SPaolo Bonzini 					const struct kvm_memory_slot *memslot)
6102b3594ffbSSean Christopherson {
6103b3594ffbSSean Christopherson 	/*
61047f42aa76SSean Christopherson 	 * All current use cases for flushing the TLBs for a specific memslot
6105302695a5SSean Christopherson 	 * related to dirty logging, and many do the TLB flush out of mmu_lock.
61067f42aa76SSean Christopherson 	 * The interaction between the various operations on memslot must be
61077f42aa76SSean Christopherson 	 * serialized by slots_locks to ensure the TLB flush from one operation
61087f42aa76SSean Christopherson 	 * is observed by any other operation on the same memslot.
6109b3594ffbSSean Christopherson 	 */
6110b3594ffbSSean Christopherson 	lockdep_assert_held(&kvm->slots_lock);
6111cec37648SSean Christopherson 	kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6112cec37648SSean Christopherson 					   memslot->npages);
6113b3594ffbSSean Christopherson }
6114b3594ffbSSean Christopherson 
6115c50d8ae3SPaolo Bonzini void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6116269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *memslot)
6117c50d8ae3SPaolo Bonzini {
6118e2209710SBen Gardon 	bool flush = false;
6119c50d8ae3SPaolo Bonzini 
6120e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6121531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6122610265eaSDavid Matlack 		/*
6123610265eaSDavid Matlack 		 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6124610265eaSDavid Matlack 		 * support dirty logging at a 4k granularity.
6125610265eaSDavid Matlack 		 */
6126610265eaSDavid Matlack 		flush = slot_handle_level_4k(kvm, memslot, __rmap_clear_dirty, false);
6127531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6128e2209710SBen Gardon 	}
6129c50d8ae3SPaolo Bonzini 
613024ae4cfaSBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
613124ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
613224ae4cfaSBen Gardon 		flush |= kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
613324ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
613424ae4cfaSBen Gardon 	}
613524ae4cfaSBen Gardon 
6136c50d8ae3SPaolo Bonzini 	/*
6137c50d8ae3SPaolo Bonzini 	 * It's also safe to flush TLBs out of mmu lock here as currently this
6138c50d8ae3SPaolo Bonzini 	 * function is only used for dirty logging, in which case flushing TLB
6139c50d8ae3SPaolo Bonzini 	 * out of mmu lock also guarantees no dirty pages will be lost in
6140c50d8ae3SPaolo Bonzini 	 * dirty_bitmap.
6141c50d8ae3SPaolo Bonzini 	 */
6142c50d8ae3SPaolo Bonzini 	if (flush)
61437f42aa76SSean Christopherson 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6144c50d8ae3SPaolo Bonzini }
6145c50d8ae3SPaolo Bonzini 
6146c50d8ae3SPaolo Bonzini void kvm_mmu_zap_all(struct kvm *kvm)
6147c50d8ae3SPaolo Bonzini {
6148c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6149c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6150c50d8ae3SPaolo Bonzini 	int ign;
6151c50d8ae3SPaolo Bonzini 
6152531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6153c50d8ae3SPaolo Bonzini restart:
6154c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6155f95eec9bSSean Christopherson 		if (WARN_ON(sp->role.invalid))
6156c50d8ae3SPaolo Bonzini 			continue;
6157c50d8ae3SPaolo Bonzini 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6158c50d8ae3SPaolo Bonzini 			goto restart;
6159531810caSBen Gardon 		if (cond_resched_rwlock_write(&kvm->mmu_lock))
6160c50d8ae3SPaolo Bonzini 			goto restart;
6161c50d8ae3SPaolo Bonzini 	}
6162c50d8ae3SPaolo Bonzini 
6163c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6164faaf05b0SBen Gardon 
6165897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
6166faaf05b0SBen Gardon 		kvm_tdp_mmu_zap_all(kvm);
6167faaf05b0SBen Gardon 
6168531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
6169c50d8ae3SPaolo Bonzini }
6170c50d8ae3SPaolo Bonzini 
6171c50d8ae3SPaolo Bonzini void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6172c50d8ae3SPaolo Bonzini {
6173c50d8ae3SPaolo Bonzini 	WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6174c50d8ae3SPaolo Bonzini 
6175c50d8ae3SPaolo Bonzini 	gen &= MMIO_SPTE_GEN_MASK;
6176c50d8ae3SPaolo Bonzini 
6177c50d8ae3SPaolo Bonzini 	/*
6178c50d8ae3SPaolo Bonzini 	 * Generation numbers are incremented in multiples of the number of
6179c50d8ae3SPaolo Bonzini 	 * address spaces in order to provide unique generations across all
6180c50d8ae3SPaolo Bonzini 	 * address spaces.  Strip what is effectively the address space
6181c50d8ae3SPaolo Bonzini 	 * modifier prior to checking for a wrap of the MMIO generation so
6182c50d8ae3SPaolo Bonzini 	 * that a wrap in any address space is detected.
6183c50d8ae3SPaolo Bonzini 	 */
6184c50d8ae3SPaolo Bonzini 	gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6185c50d8ae3SPaolo Bonzini 
6186c50d8ae3SPaolo Bonzini 	/*
6187c50d8ae3SPaolo Bonzini 	 * The very rare case: if the MMIO generation number has wrapped,
6188c50d8ae3SPaolo Bonzini 	 * zap all shadow pages.
6189c50d8ae3SPaolo Bonzini 	 */
6190c50d8ae3SPaolo Bonzini 	if (unlikely(gen == 0)) {
6191c50d8ae3SPaolo Bonzini 		kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6192c50d8ae3SPaolo Bonzini 		kvm_mmu_zap_all_fast(kvm);
6193c50d8ae3SPaolo Bonzini 	}
6194c50d8ae3SPaolo Bonzini }
6195c50d8ae3SPaolo Bonzini 
6196c50d8ae3SPaolo Bonzini static unsigned long
6197c50d8ae3SPaolo Bonzini mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6198c50d8ae3SPaolo Bonzini {
6199c50d8ae3SPaolo Bonzini 	struct kvm *kvm;
6200c50d8ae3SPaolo Bonzini 	int nr_to_scan = sc->nr_to_scan;
6201c50d8ae3SPaolo Bonzini 	unsigned long freed = 0;
6202c50d8ae3SPaolo Bonzini 
6203c50d8ae3SPaolo Bonzini 	mutex_lock(&kvm_lock);
6204c50d8ae3SPaolo Bonzini 
6205c50d8ae3SPaolo Bonzini 	list_for_each_entry(kvm, &vm_list, vm_list) {
6206c50d8ae3SPaolo Bonzini 		int idx;
6207c50d8ae3SPaolo Bonzini 		LIST_HEAD(invalid_list);
6208c50d8ae3SPaolo Bonzini 
6209c50d8ae3SPaolo Bonzini 		/*
6210c50d8ae3SPaolo Bonzini 		 * Never scan more than sc->nr_to_scan VM instances.
6211c50d8ae3SPaolo Bonzini 		 * Will not hit this condition practically since we do not try
6212c50d8ae3SPaolo Bonzini 		 * to shrink more than one VM and it is very unlikely to see
6213c50d8ae3SPaolo Bonzini 		 * !n_used_mmu_pages so many times.
6214c50d8ae3SPaolo Bonzini 		 */
6215c50d8ae3SPaolo Bonzini 		if (!nr_to_scan--)
6216c50d8ae3SPaolo Bonzini 			break;
6217c50d8ae3SPaolo Bonzini 		/*
6218c50d8ae3SPaolo Bonzini 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6219c50d8ae3SPaolo Bonzini 		 * here. We may skip a VM instance errorneosly, but we do not
6220c50d8ae3SPaolo Bonzini 		 * want to shrink a VM that only started to populate its MMU
6221c50d8ae3SPaolo Bonzini 		 * anyway.
6222c50d8ae3SPaolo Bonzini 		 */
6223c50d8ae3SPaolo Bonzini 		if (!kvm->arch.n_used_mmu_pages &&
6224c50d8ae3SPaolo Bonzini 		    !kvm_has_zapped_obsolete_pages(kvm))
6225c50d8ae3SPaolo Bonzini 			continue;
6226c50d8ae3SPaolo Bonzini 
6227c50d8ae3SPaolo Bonzini 		idx = srcu_read_lock(&kvm->srcu);
6228531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6229c50d8ae3SPaolo Bonzini 
6230c50d8ae3SPaolo Bonzini 		if (kvm_has_zapped_obsolete_pages(kvm)) {
6231c50d8ae3SPaolo Bonzini 			kvm_mmu_commit_zap_page(kvm,
6232c50d8ae3SPaolo Bonzini 			      &kvm->arch.zapped_obsolete_pages);
6233c50d8ae3SPaolo Bonzini 			goto unlock;
6234c50d8ae3SPaolo Bonzini 		}
6235c50d8ae3SPaolo Bonzini 
6236ebdb292dSSean Christopherson 		freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6237c50d8ae3SPaolo Bonzini 
6238c50d8ae3SPaolo Bonzini unlock:
6239531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6240c50d8ae3SPaolo Bonzini 		srcu_read_unlock(&kvm->srcu, idx);
6241c50d8ae3SPaolo Bonzini 
6242c50d8ae3SPaolo Bonzini 		/*
6243c50d8ae3SPaolo Bonzini 		 * unfair on small ones
6244c50d8ae3SPaolo Bonzini 		 * per-vm shrinkers cry out
6245c50d8ae3SPaolo Bonzini 		 * sadness comes quickly
6246c50d8ae3SPaolo Bonzini 		 */
6247c50d8ae3SPaolo Bonzini 		list_move_tail(&kvm->vm_list, &vm_list);
6248c50d8ae3SPaolo Bonzini 		break;
6249c50d8ae3SPaolo Bonzini 	}
6250c50d8ae3SPaolo Bonzini 
6251c50d8ae3SPaolo Bonzini 	mutex_unlock(&kvm_lock);
6252c50d8ae3SPaolo Bonzini 	return freed;
6253c50d8ae3SPaolo Bonzini }
6254c50d8ae3SPaolo Bonzini 
6255c50d8ae3SPaolo Bonzini static unsigned long
6256c50d8ae3SPaolo Bonzini mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6257c50d8ae3SPaolo Bonzini {
6258c50d8ae3SPaolo Bonzini 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6259c50d8ae3SPaolo Bonzini }
6260c50d8ae3SPaolo Bonzini 
6261c50d8ae3SPaolo Bonzini static struct shrinker mmu_shrinker = {
6262c50d8ae3SPaolo Bonzini 	.count_objects = mmu_shrink_count,
6263c50d8ae3SPaolo Bonzini 	.scan_objects = mmu_shrink_scan,
6264c50d8ae3SPaolo Bonzini 	.seeks = DEFAULT_SEEKS * 10,
6265c50d8ae3SPaolo Bonzini };
6266c50d8ae3SPaolo Bonzini 
6267c50d8ae3SPaolo Bonzini static void mmu_destroy_caches(void)
6268c50d8ae3SPaolo Bonzini {
6269c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(pte_list_desc_cache);
6270c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(mmu_page_header_cache);
6271c50d8ae3SPaolo Bonzini }
6272c50d8ae3SPaolo Bonzini 
6273c50d8ae3SPaolo Bonzini static bool get_nx_auto_mode(void)
6274c50d8ae3SPaolo Bonzini {
6275c50d8ae3SPaolo Bonzini 	/* Return true when CPU has the bug, and mitigations are ON */
6276c50d8ae3SPaolo Bonzini 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6277c50d8ae3SPaolo Bonzini }
6278c50d8ae3SPaolo Bonzini 
6279c50d8ae3SPaolo Bonzini static void __set_nx_huge_pages(bool val)
6280c50d8ae3SPaolo Bonzini {
6281c50d8ae3SPaolo Bonzini 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6282c50d8ae3SPaolo Bonzini }
6283c50d8ae3SPaolo Bonzini 
6284c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6285c50d8ae3SPaolo Bonzini {
6286c50d8ae3SPaolo Bonzini 	bool old_val = nx_huge_pages;
6287c50d8ae3SPaolo Bonzini 	bool new_val;
6288c50d8ae3SPaolo Bonzini 
6289c50d8ae3SPaolo Bonzini 	/* In "auto" mode deploy workaround only if CPU has the bug. */
6290c50d8ae3SPaolo Bonzini 	if (sysfs_streq(val, "off"))
6291c50d8ae3SPaolo Bonzini 		new_val = 0;
6292c50d8ae3SPaolo Bonzini 	else if (sysfs_streq(val, "force"))
6293c50d8ae3SPaolo Bonzini 		new_val = 1;
6294c50d8ae3SPaolo Bonzini 	else if (sysfs_streq(val, "auto"))
6295c50d8ae3SPaolo Bonzini 		new_val = get_nx_auto_mode();
6296c50d8ae3SPaolo Bonzini 	else if (strtobool(val, &new_val) < 0)
6297c50d8ae3SPaolo Bonzini 		return -EINVAL;
6298c50d8ae3SPaolo Bonzini 
6299c50d8ae3SPaolo Bonzini 	__set_nx_huge_pages(new_val);
6300c50d8ae3SPaolo Bonzini 
6301c50d8ae3SPaolo Bonzini 	if (new_val != old_val) {
6302c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6303c50d8ae3SPaolo Bonzini 
6304c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6305c50d8ae3SPaolo Bonzini 
6306c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list) {
6307c50d8ae3SPaolo Bonzini 			mutex_lock(&kvm->slots_lock);
6308c50d8ae3SPaolo Bonzini 			kvm_mmu_zap_all_fast(kvm);
6309c50d8ae3SPaolo Bonzini 			mutex_unlock(&kvm->slots_lock);
6310c50d8ae3SPaolo Bonzini 
6311c50d8ae3SPaolo Bonzini 			wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6312c50d8ae3SPaolo Bonzini 		}
6313c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6314c50d8ae3SPaolo Bonzini 	}
6315c50d8ae3SPaolo Bonzini 
6316c50d8ae3SPaolo Bonzini 	return 0;
6317c50d8ae3SPaolo Bonzini }
6318c50d8ae3SPaolo Bonzini 
63191d0e8480SSean Christopherson /*
63201d0e8480SSean Christopherson  * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
63211d0e8480SSean Christopherson  * its default value of -1 is technically undefined behavior for a boolean.
63221d0e8480SSean Christopherson  */
63231d0e8480SSean Christopherson void kvm_mmu_x86_module_init(void)
6324c50d8ae3SPaolo Bonzini {
6325c50d8ae3SPaolo Bonzini 	if (nx_huge_pages == -1)
6326c50d8ae3SPaolo Bonzini 		__set_nx_huge_pages(get_nx_auto_mode());
63271d0e8480SSean Christopherson }
63281d0e8480SSean Christopherson 
63291d0e8480SSean Christopherson /*
63301d0e8480SSean Christopherson  * The bulk of the MMU initialization is deferred until the vendor module is
63311d0e8480SSean Christopherson  * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
63321d0e8480SSean Christopherson  * to be reset when a potentially different vendor module is loaded.
63331d0e8480SSean Christopherson  */
63341d0e8480SSean Christopherson int kvm_mmu_vendor_module_init(void)
63351d0e8480SSean Christopherson {
63361d0e8480SSean Christopherson 	int ret = -ENOMEM;
6337c50d8ae3SPaolo Bonzini 
6338c50d8ae3SPaolo Bonzini 	/*
6339c50d8ae3SPaolo Bonzini 	 * MMU roles use union aliasing which is, generally speaking, an
6340c50d8ae3SPaolo Bonzini 	 * undefined behavior. However, we supposedly know how compilers behave
6341c50d8ae3SPaolo Bonzini 	 * and the current status quo is unlikely to change. Guardians below are
6342c50d8ae3SPaolo Bonzini 	 * supposed to let us know if the assumption becomes false.
6343c50d8ae3SPaolo Bonzini 	 */
6344c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6345c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
63467a7ae829SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
6347c50d8ae3SPaolo Bonzini 
6348c50d8ae3SPaolo Bonzini 	kvm_mmu_reset_all_pte_masks();
6349c50d8ae3SPaolo Bonzini 
6350c50d8ae3SPaolo Bonzini 	pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6351c50d8ae3SPaolo Bonzini 					    sizeof(struct pte_list_desc),
6352c50d8ae3SPaolo Bonzini 					    0, SLAB_ACCOUNT, NULL);
6353c50d8ae3SPaolo Bonzini 	if (!pte_list_desc_cache)
6354c50d8ae3SPaolo Bonzini 		goto out;
6355c50d8ae3SPaolo Bonzini 
6356c50d8ae3SPaolo Bonzini 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6357c50d8ae3SPaolo Bonzini 						  sizeof(struct kvm_mmu_page),
6358c50d8ae3SPaolo Bonzini 						  0, SLAB_ACCOUNT, NULL);
6359c50d8ae3SPaolo Bonzini 	if (!mmu_page_header_cache)
6360c50d8ae3SPaolo Bonzini 		goto out;
6361c50d8ae3SPaolo Bonzini 
6362c50d8ae3SPaolo Bonzini 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6363c50d8ae3SPaolo Bonzini 		goto out;
6364c50d8ae3SPaolo Bonzini 
6365c50d8ae3SPaolo Bonzini 	ret = register_shrinker(&mmu_shrinker);
6366c50d8ae3SPaolo Bonzini 	if (ret)
6367c50d8ae3SPaolo Bonzini 		goto out;
6368c50d8ae3SPaolo Bonzini 
6369c50d8ae3SPaolo Bonzini 	return 0;
6370c50d8ae3SPaolo Bonzini 
6371c50d8ae3SPaolo Bonzini out:
6372c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6373c50d8ae3SPaolo Bonzini 	return ret;
6374c50d8ae3SPaolo Bonzini }
6375c50d8ae3SPaolo Bonzini 
6376c50d8ae3SPaolo Bonzini void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6377c50d8ae3SPaolo Bonzini {
6378c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
6379c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.root_mmu);
6380c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
6381c50d8ae3SPaolo Bonzini 	mmu_free_memory_caches(vcpu);
6382c50d8ae3SPaolo Bonzini }
6383c50d8ae3SPaolo Bonzini 
63841d0e8480SSean Christopherson void kvm_mmu_vendor_module_exit(void)
6385c50d8ae3SPaolo Bonzini {
6386c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6387c50d8ae3SPaolo Bonzini 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6388c50d8ae3SPaolo Bonzini 	unregister_shrinker(&mmu_shrinker);
6389c50d8ae3SPaolo Bonzini }
6390c50d8ae3SPaolo Bonzini 
6391f47491d7SSean Christopherson /*
6392f47491d7SSean Christopherson  * Calculate the effective recovery period, accounting for '0' meaning "let KVM
6393f47491d7SSean Christopherson  * select a halving time of 1 hour".  Returns true if recovery is enabled.
6394f47491d7SSean Christopherson  */
6395f47491d7SSean Christopherson static bool calc_nx_huge_pages_recovery_period(uint *period)
6396f47491d7SSean Christopherson {
6397f47491d7SSean Christopherson 	/*
6398f47491d7SSean Christopherson 	 * Use READ_ONCE to get the params, this may be called outside of the
6399f47491d7SSean Christopherson 	 * param setters, e.g. by the kthread to compute its next timeout.
6400f47491d7SSean Christopherson 	 */
6401f47491d7SSean Christopherson 	bool enabled = READ_ONCE(nx_huge_pages);
6402f47491d7SSean Christopherson 	uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6403f47491d7SSean Christopherson 
6404f47491d7SSean Christopherson 	if (!enabled || !ratio)
6405f47491d7SSean Christopherson 		return false;
6406f47491d7SSean Christopherson 
6407f47491d7SSean Christopherson 	*period = READ_ONCE(nx_huge_pages_recovery_period_ms);
6408f47491d7SSean Christopherson 	if (!*period) {
6409f47491d7SSean Christopherson 		/* Make sure the period is not less than one second.  */
6410f47491d7SSean Christopherson 		ratio = min(ratio, 3600u);
6411f47491d7SSean Christopherson 		*period = 60 * 60 * 1000 / ratio;
6412f47491d7SSean Christopherson 	}
6413f47491d7SSean Christopherson 	return true;
6414f47491d7SSean Christopherson }
6415f47491d7SSean Christopherson 
64164dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
6417c50d8ae3SPaolo Bonzini {
64184dfe4f40SJunaid Shahid 	bool was_recovery_enabled, is_recovery_enabled;
64194dfe4f40SJunaid Shahid 	uint old_period, new_period;
6420c50d8ae3SPaolo Bonzini 	int err;
6421c50d8ae3SPaolo Bonzini 
6422f47491d7SSean Christopherson 	was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
64234dfe4f40SJunaid Shahid 
6424c50d8ae3SPaolo Bonzini 	err = param_set_uint(val, kp);
6425c50d8ae3SPaolo Bonzini 	if (err)
6426c50d8ae3SPaolo Bonzini 		return err;
6427c50d8ae3SPaolo Bonzini 
6428f47491d7SSean Christopherson 	is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
64294dfe4f40SJunaid Shahid 
6430f47491d7SSean Christopherson 	if (is_recovery_enabled &&
64314dfe4f40SJunaid Shahid 	    (!was_recovery_enabled || old_period > new_period)) {
6432c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6433c50d8ae3SPaolo Bonzini 
6434c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6435c50d8ae3SPaolo Bonzini 
6436c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list)
6437c50d8ae3SPaolo Bonzini 			wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6438c50d8ae3SPaolo Bonzini 
6439c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6440c50d8ae3SPaolo Bonzini 	}
6441c50d8ae3SPaolo Bonzini 
6442c50d8ae3SPaolo Bonzini 	return err;
6443c50d8ae3SPaolo Bonzini }
6444c50d8ae3SPaolo Bonzini 
6445c50d8ae3SPaolo Bonzini static void kvm_recover_nx_lpages(struct kvm *kvm)
6446c50d8ae3SPaolo Bonzini {
6447ade74e14SSean Christopherson 	unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
6448c50d8ae3SPaolo Bonzini 	int rcu_idx;
6449c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6450c50d8ae3SPaolo Bonzini 	unsigned int ratio;
6451c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6452048f4980SSean Christopherson 	bool flush = false;
6453c50d8ae3SPaolo Bonzini 	ulong to_zap;
6454c50d8ae3SPaolo Bonzini 
6455c50d8ae3SPaolo Bonzini 	rcu_idx = srcu_read_lock(&kvm->srcu);
6456531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6457c50d8ae3SPaolo Bonzini 
6458bb95dfb9SSean Christopherson 	/*
6459bb95dfb9SSean Christopherson 	 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
6460bb95dfb9SSean Christopherson 	 * be done under RCU protection, because the pages are freed via RCU
6461bb95dfb9SSean Christopherson 	 * callback.
6462bb95dfb9SSean Christopherson 	 */
6463bb95dfb9SSean Christopherson 	rcu_read_lock();
6464bb95dfb9SSean Christopherson 
6465c50d8ae3SPaolo Bonzini 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6466ade74e14SSean Christopherson 	to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
64677d919c7aSSean Christopherson 	for ( ; to_zap; --to_zap) {
64687d919c7aSSean Christopherson 		if (list_empty(&kvm->arch.lpage_disallowed_mmu_pages))
64697d919c7aSSean Christopherson 			break;
64707d919c7aSSean Christopherson 
6471c50d8ae3SPaolo Bonzini 		/*
6472c50d8ae3SPaolo Bonzini 		 * We use a separate list instead of just using active_mmu_pages
6473c50d8ae3SPaolo Bonzini 		 * because the number of lpage_disallowed pages is expected to
6474c50d8ae3SPaolo Bonzini 		 * be relatively small compared to the total.
6475c50d8ae3SPaolo Bonzini 		 */
6476c50d8ae3SPaolo Bonzini 		sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6477c50d8ae3SPaolo Bonzini 				      struct kvm_mmu_page,
6478c50d8ae3SPaolo Bonzini 				      lpage_disallowed_link);
6479c50d8ae3SPaolo Bonzini 		WARN_ON_ONCE(!sp->lpage_disallowed);
6480897218ffSPaolo Bonzini 		if (is_tdp_mmu_page(sp)) {
6481315f02c6SPaolo Bonzini 			flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
64828d1a182eSBen Gardon 		} else {
6483c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6484c50d8ae3SPaolo Bonzini 			WARN_ON_ONCE(sp->lpage_disallowed);
648529cf0f50SBen Gardon 		}
6486c50d8ae3SPaolo Bonzini 
6487531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
6488048f4980SSean Christopherson 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
6489bb95dfb9SSean Christopherson 			rcu_read_unlock();
6490bb95dfb9SSean Christopherson 
6491531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
6492048f4980SSean Christopherson 			flush = false;
6493bb95dfb9SSean Christopherson 
6494bb95dfb9SSean Christopherson 			rcu_read_lock();
6495c50d8ae3SPaolo Bonzini 		}
6496c50d8ae3SPaolo Bonzini 	}
6497048f4980SSean Christopherson 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
6498c50d8ae3SPaolo Bonzini 
6499bb95dfb9SSean Christopherson 	rcu_read_unlock();
6500bb95dfb9SSean Christopherson 
6501531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
6502c50d8ae3SPaolo Bonzini 	srcu_read_unlock(&kvm->srcu, rcu_idx);
6503c50d8ae3SPaolo Bonzini }
6504c50d8ae3SPaolo Bonzini 
6505c50d8ae3SPaolo Bonzini static long get_nx_lpage_recovery_timeout(u64 start_time)
6506c50d8ae3SPaolo Bonzini {
6507f47491d7SSean Christopherson 	bool enabled;
6508f47491d7SSean Christopherson 	uint period;
65094dfe4f40SJunaid Shahid 
6510f47491d7SSean Christopherson 	enabled = calc_nx_huge_pages_recovery_period(&period);
65114dfe4f40SJunaid Shahid 
6512f47491d7SSean Christopherson 	return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
6513c50d8ae3SPaolo Bonzini 		       : MAX_SCHEDULE_TIMEOUT;
6514c50d8ae3SPaolo Bonzini }
6515c50d8ae3SPaolo Bonzini 
6516c50d8ae3SPaolo Bonzini static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6517c50d8ae3SPaolo Bonzini {
6518c50d8ae3SPaolo Bonzini 	u64 start_time;
6519c50d8ae3SPaolo Bonzini 	long remaining_time;
6520c50d8ae3SPaolo Bonzini 
6521c50d8ae3SPaolo Bonzini 	while (true) {
6522c50d8ae3SPaolo Bonzini 		start_time = get_jiffies_64();
6523c50d8ae3SPaolo Bonzini 		remaining_time = get_nx_lpage_recovery_timeout(start_time);
6524c50d8ae3SPaolo Bonzini 
6525c50d8ae3SPaolo Bonzini 		set_current_state(TASK_INTERRUPTIBLE);
6526c50d8ae3SPaolo Bonzini 		while (!kthread_should_stop() && remaining_time > 0) {
6527c50d8ae3SPaolo Bonzini 			schedule_timeout(remaining_time);
6528c50d8ae3SPaolo Bonzini 			remaining_time = get_nx_lpage_recovery_timeout(start_time);
6529c50d8ae3SPaolo Bonzini 			set_current_state(TASK_INTERRUPTIBLE);
6530c50d8ae3SPaolo Bonzini 		}
6531c50d8ae3SPaolo Bonzini 
6532c50d8ae3SPaolo Bonzini 		set_current_state(TASK_RUNNING);
6533c50d8ae3SPaolo Bonzini 
6534c50d8ae3SPaolo Bonzini 		if (kthread_should_stop())
6535c50d8ae3SPaolo Bonzini 			return 0;
6536c50d8ae3SPaolo Bonzini 
6537c50d8ae3SPaolo Bonzini 		kvm_recover_nx_lpages(kvm);
6538c50d8ae3SPaolo Bonzini 	}
6539c50d8ae3SPaolo Bonzini }
6540c50d8ae3SPaolo Bonzini 
6541c50d8ae3SPaolo Bonzini int kvm_mmu_post_init_vm(struct kvm *kvm)
6542c50d8ae3SPaolo Bonzini {
6543c50d8ae3SPaolo Bonzini 	int err;
6544c50d8ae3SPaolo Bonzini 
6545c50d8ae3SPaolo Bonzini 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6546c50d8ae3SPaolo Bonzini 					  "kvm-nx-lpage-recovery",
6547c50d8ae3SPaolo Bonzini 					  &kvm->arch.nx_lpage_recovery_thread);
6548c50d8ae3SPaolo Bonzini 	if (!err)
6549c50d8ae3SPaolo Bonzini 		kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6550c50d8ae3SPaolo Bonzini 
6551c50d8ae3SPaolo Bonzini 	return err;
6552c50d8ae3SPaolo Bonzini }
6553c50d8ae3SPaolo Bonzini 
6554c50d8ae3SPaolo Bonzini void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6555c50d8ae3SPaolo Bonzini {
6556c50d8ae3SPaolo Bonzini 	if (kvm->arch.nx_lpage_recovery_thread)
6557c50d8ae3SPaolo Bonzini 		kthread_stop(kvm->arch.nx_lpage_recovery_thread);
6558c50d8ae3SPaolo Bonzini }
6559