xref: /linux/arch/x86/kvm/mmu/mmu.c (revision dfe0ecc6f5d32da13783d203403bd3ecacbd3179)
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"
25b0b42197SPaolo Bonzini #include "smm.h"
262f728d66SSean Christopherson #include "kvm_emulate.h"
27c50d8ae3SPaolo Bonzini #include "cpuid.h"
285a9624afSPaolo Bonzini #include "spte.h"
29c50d8ae3SPaolo Bonzini 
30c50d8ae3SPaolo Bonzini #include <linux/kvm_host.h>
31c50d8ae3SPaolo Bonzini #include <linux/types.h>
32c50d8ae3SPaolo Bonzini #include <linux/string.h>
33c50d8ae3SPaolo Bonzini #include <linux/mm.h>
34c50d8ae3SPaolo Bonzini #include <linux/highmem.h>
35c50d8ae3SPaolo Bonzini #include <linux/moduleparam.h>
36c50d8ae3SPaolo Bonzini #include <linux/export.h>
37c50d8ae3SPaolo Bonzini #include <linux/swap.h>
38c50d8ae3SPaolo Bonzini #include <linux/hugetlb.h>
39c50d8ae3SPaolo Bonzini #include <linux/compiler.h>
40c50d8ae3SPaolo Bonzini #include <linux/srcu.h>
41c50d8ae3SPaolo Bonzini #include <linux/slab.h>
42c50d8ae3SPaolo Bonzini #include <linux/sched/signal.h>
43c50d8ae3SPaolo Bonzini #include <linux/uaccess.h>
44c50d8ae3SPaolo Bonzini #include <linux/hash.h>
45c50d8ae3SPaolo Bonzini #include <linux/kern_levels.h>
46c50d8ae3SPaolo Bonzini #include <linux/kthread.h>
47c50d8ae3SPaolo Bonzini 
48c50d8ae3SPaolo Bonzini #include <asm/page.h>
49eb243d1dSIngo Molnar #include <asm/memtype.h>
50c50d8ae3SPaolo Bonzini #include <asm/cmpxchg.h>
51c50d8ae3SPaolo Bonzini #include <asm/io.h>
524a98623dSSean Christopherson #include <asm/set_memory.h>
53c50d8ae3SPaolo Bonzini #include <asm/vmx.h>
54c50d8ae3SPaolo Bonzini #include <asm/kvm_page_track.h>
55c50d8ae3SPaolo Bonzini #include "trace.h"
56c50d8ae3SPaolo Bonzini 
57c50d8ae3SPaolo Bonzini extern bool itlb_multihit_kvm_mitigation;
58c50d8ae3SPaolo Bonzini 
59a9d6496dSShaokun Zhang int __read_mostly nx_huge_pages = -1;
604dfe4f40SJunaid Shahid static uint __read_mostly nx_huge_pages_recovery_period_ms;
61c50d8ae3SPaolo Bonzini #ifdef CONFIG_PREEMPT_RT
62c50d8ae3SPaolo Bonzini /* Recovery can cause latency spikes, disable it for PREEMPT_RT.  */
63c50d8ae3SPaolo Bonzini static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
64c50d8ae3SPaolo Bonzini #else
65c50d8ae3SPaolo Bonzini static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
66c50d8ae3SPaolo Bonzini #endif
67c50d8ae3SPaolo Bonzini 
68c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
694dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp);
70c50d8ae3SPaolo Bonzini 
71d5d6c18dSJoe Perches static const struct kernel_param_ops nx_huge_pages_ops = {
72c50d8ae3SPaolo Bonzini 	.set = set_nx_huge_pages,
73c50d8ae3SPaolo Bonzini 	.get = param_get_bool,
74c50d8ae3SPaolo Bonzini };
75c50d8ae3SPaolo Bonzini 
764dfe4f40SJunaid Shahid static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
774dfe4f40SJunaid Shahid 	.set = set_nx_huge_pages_recovery_param,
78c50d8ae3SPaolo Bonzini 	.get = param_get_uint,
79c50d8ae3SPaolo Bonzini };
80c50d8ae3SPaolo Bonzini 
81c50d8ae3SPaolo Bonzini module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
82c50d8ae3SPaolo Bonzini __MODULE_PARM_TYPE(nx_huge_pages, "bool");
834dfe4f40SJunaid Shahid module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_param_ops,
84c50d8ae3SPaolo Bonzini 		&nx_huge_pages_recovery_ratio, 0644);
85c50d8ae3SPaolo Bonzini __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
864dfe4f40SJunaid Shahid module_param_cb(nx_huge_pages_recovery_period_ms, &nx_huge_pages_recovery_param_ops,
874dfe4f40SJunaid Shahid 		&nx_huge_pages_recovery_period_ms, 0644);
884dfe4f40SJunaid Shahid __MODULE_PARM_TYPE(nx_huge_pages_recovery_period_ms, "uint");
89c50d8ae3SPaolo Bonzini 
9071fe7013SSean Christopherson static bool __read_mostly force_flush_and_sync_on_reuse;
9171fe7013SSean Christopherson module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
9271fe7013SSean Christopherson 
93c50d8ae3SPaolo Bonzini /*
94c50d8ae3SPaolo Bonzini  * When setting this variable to true it enables Two-Dimensional-Paging
95c50d8ae3SPaolo Bonzini  * where the hardware walks 2 page tables:
96c50d8ae3SPaolo Bonzini  * 1. the guest-virtual to guest-physical
97c50d8ae3SPaolo Bonzini  * 2. while doing 1. it walks guest-physical to host-physical
98c50d8ae3SPaolo Bonzini  * If the hardware supports that we don't need to do shadow paging.
99c50d8ae3SPaolo Bonzini  */
100c50d8ae3SPaolo Bonzini bool tdp_enabled = false;
101c50d8ae3SPaolo Bonzini 
1021f98f2bdSDavid Matlack bool __ro_after_init tdp_mmu_allowed;
1031f98f2bdSDavid Matlack 
1041f98f2bdSDavid Matlack #ifdef CONFIG_X86_64
1051f98f2bdSDavid Matlack bool __read_mostly tdp_mmu_enabled = true;
1061f98f2bdSDavid Matlack module_param_named(tdp_mmu, tdp_mmu_enabled, bool, 0444);
1071f98f2bdSDavid Matlack #endif
1081f98f2bdSDavid Matlack 
1091d92d2e8SSean Christopherson static int max_huge_page_level __read_mostly;
110746700d2SWei Huang static int tdp_root_level __read_mostly;
11183013059SSean Christopherson static int max_tdp_level __read_mostly;
112703c335dSSean Christopherson 
113c50d8ae3SPaolo Bonzini #ifdef MMU_DEBUG
1145a9624afSPaolo Bonzini bool dbg = 0;
115c50d8ae3SPaolo Bonzini module_param(dbg, bool, 0644);
116c50d8ae3SPaolo Bonzini #endif
117c50d8ae3SPaolo Bonzini 
118c50d8ae3SPaolo Bonzini #define PTE_PREFETCH_NUM		8
119c50d8ae3SPaolo Bonzini 
120c50d8ae3SPaolo Bonzini #include <trace/events/kvm.h>
121c50d8ae3SPaolo Bonzini 
122dc1cff96SPeter Xu /* make pte_list_desc fit well in cache lines */
12313236e25SPeter Xu #define PTE_LIST_EXT 14
124c50d8ae3SPaolo Bonzini 
12513236e25SPeter Xu /*
12613236e25SPeter Xu  * Slight optimization of cacheline layout, by putting `more' and `spte_count'
12713236e25SPeter Xu  * at the start; then accessing it will only use one single cacheline for
12813236e25SPeter Xu  * either full (entries==PTE_LIST_EXT) case or entries<=6.
12913236e25SPeter Xu  */
130c50d8ae3SPaolo Bonzini struct pte_list_desc {
131c50d8ae3SPaolo Bonzini 	struct pte_list_desc *more;
13213236e25SPeter Xu 	/*
13313236e25SPeter Xu 	 * Stores number of entries stored in the pte_list_desc.  No need to be
13413236e25SPeter Xu 	 * u64 but just for easier alignment.  When PTE_LIST_EXT, means full.
13513236e25SPeter Xu 	 */
13613236e25SPeter Xu 	u64 spte_count;
13713236e25SPeter Xu 	u64 *sptes[PTE_LIST_EXT];
138c50d8ae3SPaolo Bonzini };
139c50d8ae3SPaolo Bonzini 
140c50d8ae3SPaolo Bonzini struct kvm_shadow_walk_iterator {
141c50d8ae3SPaolo Bonzini 	u64 addr;
142c50d8ae3SPaolo Bonzini 	hpa_t shadow_addr;
143c50d8ae3SPaolo Bonzini 	u64 *sptep;
144c50d8ae3SPaolo Bonzini 	int level;
145c50d8ae3SPaolo Bonzini 	unsigned index;
146c50d8ae3SPaolo Bonzini };
147c50d8ae3SPaolo Bonzini 
148c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
149c50d8ae3SPaolo Bonzini 	for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
150c50d8ae3SPaolo Bonzini 					 (_root), (_addr));                \
151c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			           \
152c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
153c50d8ae3SPaolo Bonzini 
154c50d8ae3SPaolo Bonzini #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
155c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);	\
156c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			\
157c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
158c50d8ae3SPaolo Bonzini 
159c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)	\
160c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);		\
161c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker)) &&				\
162c50d8ae3SPaolo Bonzini 		({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });	\
163c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&(_walker), spte))
164c50d8ae3SPaolo Bonzini 
165c50d8ae3SPaolo Bonzini static struct kmem_cache *pte_list_desc_cache;
16602c00b3aSBen Gardon struct kmem_cache *mmu_page_header_cache;
167c50d8ae3SPaolo Bonzini static struct percpu_counter kvm_total_used_mmu_pages;
168c50d8ae3SPaolo Bonzini 
169c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 spte);
170c50d8ae3SPaolo Bonzini 
171594e91a1SSean Christopherson struct kvm_mmu_role_regs {
172594e91a1SSean Christopherson 	const unsigned long cr0;
173594e91a1SSean Christopherson 	const unsigned long cr4;
174594e91a1SSean Christopherson 	const u64 efer;
175594e91a1SSean Christopherson };
176594e91a1SSean Christopherson 
177c50d8ae3SPaolo Bonzini #define CREATE_TRACE_POINTS
178c50d8ae3SPaolo Bonzini #include "mmutrace.h"
179c50d8ae3SPaolo Bonzini 
180594e91a1SSean Christopherson /*
181594e91a1SSean Christopherson  * Yes, lot's of underscores.  They're a hint that you probably shouldn't be
1827a458f0eSPaolo Bonzini  * reading from the role_regs.  Once the root_role is constructed, it becomes
183594e91a1SSean Christopherson  * the single source of truth for the MMU's state.
184594e91a1SSean Christopherson  */
185594e91a1SSean Christopherson #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag)			\
18682ffa13fSPaolo Bonzini static inline bool __maybe_unused					\
18782ffa13fSPaolo Bonzini ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs)		\
188594e91a1SSean Christopherson {									\
189594e91a1SSean Christopherson 	return !!(regs->reg & flag);					\
190594e91a1SSean Christopherson }
191594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
192594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
193594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
194594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
195594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
196594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
197594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
198594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
199594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
200594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
201594e91a1SSean Christopherson 
20260667724SSean Christopherson /*
20360667724SSean Christopherson  * The MMU itself (with a valid role) is the single source of truth for the
20460667724SSean Christopherson  * MMU.  Do not use the regs used to build the MMU/role, nor the vCPU.  The
20560667724SSean Christopherson  * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
20660667724SSean Christopherson  * and the vCPU may be incorrect/irrelevant.
20760667724SSean Christopherson  */
20860667724SSean Christopherson #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name)		\
2094ac21457SPaolo Bonzini static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu)	\
21060667724SSean Christopherson {								\
211e5ed0fb0SPaolo Bonzini 	return !!(mmu->cpu_role. base_or_ext . reg##_##name);	\
21260667724SSean Christopherson }
21360667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
21460667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pse);
21560667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smep);
21660667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smap);
21760667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pke);
21860667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, la57);
21960667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
22056b321f9SPaolo Bonzini BUILD_MMU_ROLE_ACCESSOR(ext,  efer, lma);
22160667724SSean Christopherson 
222faf72962SPaolo Bonzini static inline bool is_cr0_pg(struct kvm_mmu *mmu)
223faf72962SPaolo Bonzini {
224faf72962SPaolo Bonzini         return mmu->cpu_role.base.level > 0;
225faf72962SPaolo Bonzini }
226faf72962SPaolo Bonzini 
227faf72962SPaolo Bonzini static inline bool is_cr4_pae(struct kvm_mmu *mmu)
228faf72962SPaolo Bonzini {
229faf72962SPaolo Bonzini         return !mmu->cpu_role.base.has_4_byte_gpte;
230faf72962SPaolo Bonzini }
231faf72962SPaolo Bonzini 
232594e91a1SSean Christopherson static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
233594e91a1SSean Christopherson {
234594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
235594e91a1SSean Christopherson 		.cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
236594e91a1SSean Christopherson 		.cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
237594e91a1SSean Christopherson 		.efer = vcpu->arch.efer,
238594e91a1SSean Christopherson 	};
239594e91a1SSean Christopherson 
240594e91a1SSean Christopherson 	return regs;
241594e91a1SSean Christopherson }
242c50d8ae3SPaolo Bonzini 
243c50d8ae3SPaolo Bonzini static inline bool kvm_available_flush_tlb_with_range(void)
244c50d8ae3SPaolo Bonzini {
245afaf0b2fSSean Christopherson 	return kvm_x86_ops.tlb_remote_flush_with_range;
246c50d8ae3SPaolo Bonzini }
247c50d8ae3SPaolo Bonzini 
248c50d8ae3SPaolo Bonzini static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
249c50d8ae3SPaolo Bonzini 		struct kvm_tlb_range *range)
250c50d8ae3SPaolo Bonzini {
251c50d8ae3SPaolo Bonzini 	int ret = -ENOTSUPP;
252c50d8ae3SPaolo Bonzini 
253afaf0b2fSSean Christopherson 	if (range && kvm_x86_ops.tlb_remote_flush_with_range)
254b3646477SJason Baron 		ret = static_call(kvm_x86_tlb_remote_flush_with_range)(kvm, range);
255c50d8ae3SPaolo Bonzini 
256c50d8ae3SPaolo Bonzini 	if (ret)
257c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
258c50d8ae3SPaolo Bonzini }
259c50d8ae3SPaolo Bonzini 
2602f2fad08SBen Gardon void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
261c50d8ae3SPaolo Bonzini 		u64 start_gfn, u64 pages)
262c50d8ae3SPaolo Bonzini {
263c50d8ae3SPaolo Bonzini 	struct kvm_tlb_range range;
264c50d8ae3SPaolo Bonzini 
265c50d8ae3SPaolo Bonzini 	range.start_gfn = start_gfn;
266c50d8ae3SPaolo Bonzini 	range.pages = pages;
267c50d8ae3SPaolo Bonzini 
268c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs_with_range(kvm, &range);
269c50d8ae3SPaolo Bonzini }
270c50d8ae3SPaolo Bonzini 
2718f79b064SBen Gardon static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
2728f79b064SBen Gardon 			   unsigned int access)
2738f79b064SBen Gardon {
274c236d962SSean Christopherson 	u64 spte = make_mmio_spte(vcpu, gfn, access);
2758f79b064SBen Gardon 
276c236d962SSean Christopherson 	trace_mark_mmio_spte(sptep, gfn, spte);
277c236d962SSean Christopherson 	mmu_spte_set(sptep, spte);
278c50d8ae3SPaolo Bonzini }
279c50d8ae3SPaolo Bonzini 
280c50d8ae3SPaolo Bonzini static gfn_t get_mmio_spte_gfn(u64 spte)
281c50d8ae3SPaolo Bonzini {
282c50d8ae3SPaolo Bonzini 	u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
283c50d8ae3SPaolo Bonzini 
2848a967d65SPaolo Bonzini 	gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
285c50d8ae3SPaolo Bonzini 	       & shadow_nonpresent_or_rsvd_mask;
286c50d8ae3SPaolo Bonzini 
287c50d8ae3SPaolo Bonzini 	return gpa >> PAGE_SHIFT;
288c50d8ae3SPaolo Bonzini }
289c50d8ae3SPaolo Bonzini 
290c50d8ae3SPaolo Bonzini static unsigned get_mmio_spte_access(u64 spte)
291c50d8ae3SPaolo Bonzini {
292c50d8ae3SPaolo Bonzini 	return spte & shadow_mmio_access_mask;
293c50d8ae3SPaolo Bonzini }
294c50d8ae3SPaolo Bonzini 
295c50d8ae3SPaolo Bonzini static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
296c50d8ae3SPaolo Bonzini {
297c50d8ae3SPaolo Bonzini 	u64 kvm_gen, spte_gen, gen;
298c50d8ae3SPaolo Bonzini 
299c50d8ae3SPaolo Bonzini 	gen = kvm_vcpu_memslots(vcpu)->generation;
300c50d8ae3SPaolo Bonzini 	if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
301c50d8ae3SPaolo Bonzini 		return false;
302c50d8ae3SPaolo Bonzini 
303c50d8ae3SPaolo Bonzini 	kvm_gen = gen & MMIO_SPTE_GEN_MASK;
304c50d8ae3SPaolo Bonzini 	spte_gen = get_mmio_spte_generation(spte);
305c50d8ae3SPaolo Bonzini 
306c50d8ae3SPaolo Bonzini 	trace_check_mmio_spte(spte, kvm_gen, spte_gen);
307c50d8ae3SPaolo Bonzini 	return likely(kvm_gen == spte_gen);
308c50d8ae3SPaolo Bonzini }
309c50d8ae3SPaolo Bonzini 
310c50d8ae3SPaolo Bonzini static int is_cpuid_PSE36(void)
311c50d8ae3SPaolo Bonzini {
312c50d8ae3SPaolo Bonzini 	return 1;
313c50d8ae3SPaolo Bonzini }
314c50d8ae3SPaolo Bonzini 
315c50d8ae3SPaolo Bonzini #ifdef CONFIG_X86_64
316c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
317c50d8ae3SPaolo Bonzini {
318c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
319c50d8ae3SPaolo Bonzini }
320c50d8ae3SPaolo Bonzini 
321c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
322c50d8ae3SPaolo Bonzini {
323c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
324c50d8ae3SPaolo Bonzini }
325c50d8ae3SPaolo Bonzini 
326c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
327c50d8ae3SPaolo Bonzini {
328c50d8ae3SPaolo Bonzini 	return xchg(sptep, spte);
329c50d8ae3SPaolo Bonzini }
330c50d8ae3SPaolo Bonzini 
331c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
332c50d8ae3SPaolo Bonzini {
333c50d8ae3SPaolo Bonzini 	return READ_ONCE(*sptep);
334c50d8ae3SPaolo Bonzini }
335c50d8ae3SPaolo Bonzini #else
336c50d8ae3SPaolo Bonzini union split_spte {
337c50d8ae3SPaolo Bonzini 	struct {
338c50d8ae3SPaolo Bonzini 		u32 spte_low;
339c50d8ae3SPaolo Bonzini 		u32 spte_high;
340c50d8ae3SPaolo Bonzini 	};
341c50d8ae3SPaolo Bonzini 	u64 spte;
342c50d8ae3SPaolo Bonzini };
343c50d8ae3SPaolo Bonzini 
344c50d8ae3SPaolo Bonzini static void count_spte_clear(u64 *sptep, u64 spte)
345c50d8ae3SPaolo Bonzini {
34657354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
347c50d8ae3SPaolo Bonzini 
348c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(spte))
349c50d8ae3SPaolo Bonzini 		return;
350c50d8ae3SPaolo Bonzini 
351c50d8ae3SPaolo Bonzini 	/* Ensure the spte is completely set before we increase the count */
352c50d8ae3SPaolo Bonzini 	smp_wmb();
353c50d8ae3SPaolo Bonzini 	sp->clear_spte_count++;
354c50d8ae3SPaolo Bonzini }
355c50d8ae3SPaolo Bonzini 
356c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
357c50d8ae3SPaolo Bonzini {
358c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
359c50d8ae3SPaolo Bonzini 
360c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
361c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
362c50d8ae3SPaolo Bonzini 
363c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
364c50d8ae3SPaolo Bonzini 
365c50d8ae3SPaolo Bonzini 	/*
366c50d8ae3SPaolo Bonzini 	 * If we map the spte from nonpresent to present, We should store
367c50d8ae3SPaolo Bonzini 	 * the high bits firstly, then set present bit, so cpu can not
368c50d8ae3SPaolo Bonzini 	 * fetch this spte while we are setting the spte.
369c50d8ae3SPaolo Bonzini 	 */
370c50d8ae3SPaolo Bonzini 	smp_wmb();
371c50d8ae3SPaolo Bonzini 
372c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
373c50d8ae3SPaolo Bonzini }
374c50d8ae3SPaolo Bonzini 
375c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
376c50d8ae3SPaolo Bonzini {
377c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
378c50d8ae3SPaolo Bonzini 
379c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
380c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
381c50d8ae3SPaolo Bonzini 
382c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
383c50d8ae3SPaolo Bonzini 
384c50d8ae3SPaolo Bonzini 	/*
385c50d8ae3SPaolo Bonzini 	 * If we map the spte from present to nonpresent, we should clear
386c50d8ae3SPaolo Bonzini 	 * present bit firstly to avoid vcpu fetch the old high bits.
387c50d8ae3SPaolo Bonzini 	 */
388c50d8ae3SPaolo Bonzini 	smp_wmb();
389c50d8ae3SPaolo Bonzini 
390c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
391c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
392c50d8ae3SPaolo Bonzini }
393c50d8ae3SPaolo Bonzini 
394c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
395c50d8ae3SPaolo Bonzini {
396c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte, orig;
397c50d8ae3SPaolo Bonzini 
398c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
399c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
400c50d8ae3SPaolo Bonzini 
401c50d8ae3SPaolo Bonzini 	/* xchg acts as a barrier before the setting of the high bits */
402c50d8ae3SPaolo Bonzini 	orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
403c50d8ae3SPaolo Bonzini 	orig.spte_high = ssptep->spte_high;
404c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
405c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
406c50d8ae3SPaolo Bonzini 
407c50d8ae3SPaolo Bonzini 	return orig.spte;
408c50d8ae3SPaolo Bonzini }
409c50d8ae3SPaolo Bonzini 
410c50d8ae3SPaolo Bonzini /*
411c50d8ae3SPaolo Bonzini  * The idea using the light way get the spte on x86_32 guest is from
412c50d8ae3SPaolo Bonzini  * gup_get_pte (mm/gup.c).
413c50d8ae3SPaolo Bonzini  *
414aed02fe3SSean Christopherson  * An spte tlb flush may be pending, because kvm_set_pte_rmap
415c50d8ae3SPaolo Bonzini  * coalesces them and we are running out of the MMU lock.  Therefore
416c50d8ae3SPaolo Bonzini  * we need to protect against in-progress updates of the spte.
417c50d8ae3SPaolo Bonzini  *
418c50d8ae3SPaolo Bonzini  * Reading the spte while an update is in progress may get the old value
419c50d8ae3SPaolo Bonzini  * for the high part of the spte.  The race is fine for a present->non-present
420c50d8ae3SPaolo Bonzini  * change (because the high part of the spte is ignored for non-present spte),
421c50d8ae3SPaolo Bonzini  * but for a present->present change we must reread the spte.
422c50d8ae3SPaolo Bonzini  *
423c50d8ae3SPaolo Bonzini  * All such changes are done in two steps (present->non-present and
424c50d8ae3SPaolo Bonzini  * non-present->present), hence it is enough to count the number of
425c50d8ae3SPaolo Bonzini  * present->non-present updates: if it changed while reading the spte,
426c50d8ae3SPaolo Bonzini  * we might have hit the race.  This is done using clear_spte_count.
427c50d8ae3SPaolo Bonzini  */
428c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
429c50d8ae3SPaolo Bonzini {
43057354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
431c50d8ae3SPaolo Bonzini 	union split_spte spte, *orig = (union split_spte *)sptep;
432c50d8ae3SPaolo Bonzini 	int count;
433c50d8ae3SPaolo Bonzini 
434c50d8ae3SPaolo Bonzini retry:
435c50d8ae3SPaolo Bonzini 	count = sp->clear_spte_count;
436c50d8ae3SPaolo Bonzini 	smp_rmb();
437c50d8ae3SPaolo Bonzini 
438c50d8ae3SPaolo Bonzini 	spte.spte_low = orig->spte_low;
439c50d8ae3SPaolo Bonzini 	smp_rmb();
440c50d8ae3SPaolo Bonzini 
441c50d8ae3SPaolo Bonzini 	spte.spte_high = orig->spte_high;
442c50d8ae3SPaolo Bonzini 	smp_rmb();
443c50d8ae3SPaolo Bonzini 
444c50d8ae3SPaolo Bonzini 	if (unlikely(spte.spte_low != orig->spte_low ||
445c50d8ae3SPaolo Bonzini 	      count != sp->clear_spte_count))
446c50d8ae3SPaolo Bonzini 		goto retry;
447c50d8ae3SPaolo Bonzini 
448c50d8ae3SPaolo Bonzini 	return spte.spte;
449c50d8ae3SPaolo Bonzini }
450c50d8ae3SPaolo Bonzini #endif
451c50d8ae3SPaolo Bonzini 
452c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_set:
453c50d8ae3SPaolo Bonzini  * Set the sptep from nonpresent to present.
454c50d8ae3SPaolo Bonzini  * Note: the sptep being assigned *must* be either not present
455c50d8ae3SPaolo Bonzini  * or in a state where the hardware will not attempt to update
456c50d8ae3SPaolo Bonzini  * the spte.
457c50d8ae3SPaolo Bonzini  */
458c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 new_spte)
459c50d8ae3SPaolo Bonzini {
460c50d8ae3SPaolo Bonzini 	WARN_ON(is_shadow_present_pte(*sptep));
461c50d8ae3SPaolo Bonzini 	__set_spte(sptep, new_spte);
462c50d8ae3SPaolo Bonzini }
463c50d8ae3SPaolo Bonzini 
464c50d8ae3SPaolo Bonzini /*
465c50d8ae3SPaolo Bonzini  * Update the SPTE (excluding the PFN), but do not track changes in its
466c50d8ae3SPaolo Bonzini  * accessed/dirty status.
467c50d8ae3SPaolo Bonzini  */
468c50d8ae3SPaolo Bonzini static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
469c50d8ae3SPaolo Bonzini {
470c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
471c50d8ae3SPaolo Bonzini 
472c50d8ae3SPaolo Bonzini 	WARN_ON(!is_shadow_present_pte(new_spte));
473115111efSDavid Matlack 	check_spte_writable_invariants(new_spte);
474c50d8ae3SPaolo Bonzini 
475c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte)) {
476c50d8ae3SPaolo Bonzini 		mmu_spte_set(sptep, new_spte);
477c50d8ae3SPaolo Bonzini 		return old_spte;
478c50d8ae3SPaolo Bonzini 	}
479c50d8ae3SPaolo Bonzini 
480c50d8ae3SPaolo Bonzini 	if (!spte_has_volatile_bits(old_spte))
481c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, new_spte);
482c50d8ae3SPaolo Bonzini 	else
483c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, new_spte);
484c50d8ae3SPaolo Bonzini 
485c50d8ae3SPaolo Bonzini 	WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
486c50d8ae3SPaolo Bonzini 
487c50d8ae3SPaolo Bonzini 	return old_spte;
488c50d8ae3SPaolo Bonzini }
489c50d8ae3SPaolo Bonzini 
490c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_update:
491c50d8ae3SPaolo Bonzini  * Update the state bits, it means the mapped pfn is not changed.
492c50d8ae3SPaolo Bonzini  *
49302844ac1SDavid Matlack  * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
49402844ac1SDavid Matlack  * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
49502844ac1SDavid Matlack  * spte, even though the writable spte might be cached on a CPU's TLB.
496c50d8ae3SPaolo Bonzini  *
497c50d8ae3SPaolo Bonzini  * Returns true if the TLB needs to be flushed
498c50d8ae3SPaolo Bonzini  */
499c50d8ae3SPaolo Bonzini static bool mmu_spte_update(u64 *sptep, u64 new_spte)
500c50d8ae3SPaolo Bonzini {
501c50d8ae3SPaolo Bonzini 	bool flush = false;
502c50d8ae3SPaolo Bonzini 	u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
503c50d8ae3SPaolo Bonzini 
504c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
505c50d8ae3SPaolo Bonzini 		return false;
506c50d8ae3SPaolo Bonzini 
507c50d8ae3SPaolo Bonzini 	/*
508c50d8ae3SPaolo Bonzini 	 * For the spte updated out of mmu-lock is safe, since
509c50d8ae3SPaolo Bonzini 	 * we always atomically update it, see the comments in
510c50d8ae3SPaolo Bonzini 	 * spte_has_volatile_bits().
511c50d8ae3SPaolo Bonzini 	 */
512706c9c55SSean Christopherson 	if (is_mmu_writable_spte(old_spte) &&
513c50d8ae3SPaolo Bonzini 	      !is_writable_pte(new_spte))
514c50d8ae3SPaolo Bonzini 		flush = true;
515c50d8ae3SPaolo Bonzini 
516c50d8ae3SPaolo Bonzini 	/*
517c50d8ae3SPaolo Bonzini 	 * Flush TLB when accessed/dirty states are changed in the page tables,
518c50d8ae3SPaolo Bonzini 	 * to guarantee consistency between TLB and page tables.
519c50d8ae3SPaolo Bonzini 	 */
520c50d8ae3SPaolo Bonzini 
521c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
522c50d8ae3SPaolo Bonzini 		flush = true;
523c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(spte_to_pfn(old_spte));
524c50d8ae3SPaolo Bonzini 	}
525c50d8ae3SPaolo Bonzini 
526c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
527c50d8ae3SPaolo Bonzini 		flush = true;
528c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(old_spte));
529c50d8ae3SPaolo Bonzini 	}
530c50d8ae3SPaolo Bonzini 
531c50d8ae3SPaolo Bonzini 	return flush;
532c50d8ae3SPaolo Bonzini }
533c50d8ae3SPaolo Bonzini 
534c50d8ae3SPaolo Bonzini /*
535c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_track_bits:
536c50d8ae3SPaolo Bonzini  * It sets the sptep from present to nonpresent, and track the
537c50d8ae3SPaolo Bonzini  * state bits, it is used to clear the last level sptep.
5387fa2a347SSean Christopherson  * Returns the old PTE.
539c50d8ae3SPaolo Bonzini  */
54035d539c3SSean Christopherson static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
541c50d8ae3SPaolo Bonzini {
542c50d8ae3SPaolo Bonzini 	kvm_pfn_t pfn;
543c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
54471f51d2cSMingwei Zhang 	int level = sptep_to_sp(sptep)->role.level;
545b14b2690SSean Christopherson 	struct page *page;
546c50d8ae3SPaolo Bonzini 
54754eb3ef5SSean Christopherson 	if (!is_shadow_present_pte(old_spte) ||
54854eb3ef5SSean Christopherson 	    !spte_has_volatile_bits(old_spte))
549c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, 0ull);
550c50d8ae3SPaolo Bonzini 	else
551c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, 0ull);
552c50d8ae3SPaolo Bonzini 
553c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
5547fa2a347SSean Christopherson 		return old_spte;
555c50d8ae3SPaolo Bonzini 
55671f51d2cSMingwei Zhang 	kvm_update_page_stats(kvm, level, -1);
55771f51d2cSMingwei Zhang 
558c50d8ae3SPaolo Bonzini 	pfn = spte_to_pfn(old_spte);
559c50d8ae3SPaolo Bonzini 
560c50d8ae3SPaolo Bonzini 	/*
561b14b2690SSean Christopherson 	 * KVM doesn't hold a reference to any pages mapped into the guest, and
562b14b2690SSean Christopherson 	 * instead uses the mmu_notifier to ensure that KVM unmaps any pages
563b14b2690SSean Christopherson 	 * before they are reclaimed.  Sanity check that, if the pfn is backed
564b14b2690SSean Christopherson 	 * by a refcounted page, the refcount is elevated.
565c50d8ae3SPaolo Bonzini 	 */
566b14b2690SSean Christopherson 	page = kvm_pfn_to_refcounted_page(pfn);
567b14b2690SSean Christopherson 	WARN_ON(page && !page_count(page));
568c50d8ae3SPaolo Bonzini 
569c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte))
570c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(pfn);
571c50d8ae3SPaolo Bonzini 
572c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte))
573c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(pfn);
574c50d8ae3SPaolo Bonzini 
5757fa2a347SSean Christopherson 	return old_spte;
576c50d8ae3SPaolo Bonzini }
577c50d8ae3SPaolo Bonzini 
578c50d8ae3SPaolo Bonzini /*
579c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_no_track:
580c50d8ae3SPaolo Bonzini  * Directly clear spte without caring the state bits of sptep,
581c50d8ae3SPaolo Bonzini  * it is used to set the upper level spte.
582c50d8ae3SPaolo Bonzini  */
583c50d8ae3SPaolo Bonzini static void mmu_spte_clear_no_track(u64 *sptep)
584c50d8ae3SPaolo Bonzini {
585c50d8ae3SPaolo Bonzini 	__update_clear_spte_fast(sptep, 0ull);
586c50d8ae3SPaolo Bonzini }
587c50d8ae3SPaolo Bonzini 
588c50d8ae3SPaolo Bonzini static u64 mmu_spte_get_lockless(u64 *sptep)
589c50d8ae3SPaolo Bonzini {
590c50d8ae3SPaolo Bonzini 	return __get_spte_lockless(sptep);
591c50d8ae3SPaolo Bonzini }
592c50d8ae3SPaolo Bonzini 
593c50d8ae3SPaolo Bonzini /* Returns the Accessed status of the PTE and resets it at the same time. */
594c50d8ae3SPaolo Bonzini static bool mmu_spte_age(u64 *sptep)
595c50d8ae3SPaolo Bonzini {
596c50d8ae3SPaolo Bonzini 	u64 spte = mmu_spte_get_lockless(sptep);
597c50d8ae3SPaolo Bonzini 
598c50d8ae3SPaolo Bonzini 	if (!is_accessed_spte(spte))
599c50d8ae3SPaolo Bonzini 		return false;
600c50d8ae3SPaolo Bonzini 
601c50d8ae3SPaolo Bonzini 	if (spte_ad_enabled(spte)) {
602c50d8ae3SPaolo Bonzini 		clear_bit((ffs(shadow_accessed_mask) - 1),
603c50d8ae3SPaolo Bonzini 			  (unsigned long *)sptep);
604c50d8ae3SPaolo Bonzini 	} else {
605c50d8ae3SPaolo Bonzini 		/*
606c50d8ae3SPaolo Bonzini 		 * Capture the dirty status of the page, so that it doesn't get
607c50d8ae3SPaolo Bonzini 		 * lost when the SPTE is marked for access tracking.
608c50d8ae3SPaolo Bonzini 		 */
609c50d8ae3SPaolo Bonzini 		if (is_writable_pte(spte))
610c50d8ae3SPaolo Bonzini 			kvm_set_pfn_dirty(spte_to_pfn(spte));
611c50d8ae3SPaolo Bonzini 
612c50d8ae3SPaolo Bonzini 		spte = mark_spte_for_access_track(spte);
613c50d8ae3SPaolo Bonzini 		mmu_spte_update_no_track(sptep, spte);
614c50d8ae3SPaolo Bonzini 	}
615c50d8ae3SPaolo Bonzini 
616c50d8ae3SPaolo Bonzini 	return true;
617c50d8ae3SPaolo Bonzini }
618c50d8ae3SPaolo Bonzini 
61978fdd2f0SSean Christopherson static inline bool is_tdp_mmu_active(struct kvm_vcpu *vcpu)
62078fdd2f0SSean Christopherson {
62178fdd2f0SSean Christopherson 	return tdp_mmu_enabled && vcpu->arch.mmu->root_role.direct;
62278fdd2f0SSean Christopherson }
62378fdd2f0SSean Christopherson 
624c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
625c50d8ae3SPaolo Bonzini {
62678fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu)) {
627c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_begin();
628c5c8c7c5SDavid Matlack 	} else {
629c50d8ae3SPaolo Bonzini 		/*
630c50d8ae3SPaolo Bonzini 		 * Prevent page table teardown by making any free-er wait during
631c50d8ae3SPaolo Bonzini 		 * kvm_flush_remote_tlbs() IPI to all active vcpus.
632c50d8ae3SPaolo Bonzini 		 */
633c50d8ae3SPaolo Bonzini 		local_irq_disable();
634c50d8ae3SPaolo Bonzini 
635c50d8ae3SPaolo Bonzini 		/*
636c50d8ae3SPaolo Bonzini 		 * Make sure a following spte read is not reordered ahead of the write
637c50d8ae3SPaolo Bonzini 		 * to vcpu->mode.
638c50d8ae3SPaolo Bonzini 		 */
639c50d8ae3SPaolo Bonzini 		smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
640c50d8ae3SPaolo Bonzini 	}
641c5c8c7c5SDavid Matlack }
642c50d8ae3SPaolo Bonzini 
643c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
644c50d8ae3SPaolo Bonzini {
64578fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu)) {
646c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_end();
647c5c8c7c5SDavid Matlack 	} else {
648c50d8ae3SPaolo Bonzini 		/*
649c50d8ae3SPaolo Bonzini 		 * Make sure the write to vcpu->mode is not reordered in front of
650c50d8ae3SPaolo Bonzini 		 * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
651c50d8ae3SPaolo Bonzini 		 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
652c50d8ae3SPaolo Bonzini 		 */
653c50d8ae3SPaolo Bonzini 		smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
654c50d8ae3SPaolo Bonzini 		local_irq_enable();
655c50d8ae3SPaolo Bonzini 	}
656c5c8c7c5SDavid Matlack }
657c50d8ae3SPaolo Bonzini 
658378f5cd6SSean Christopherson static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
659c50d8ae3SPaolo Bonzini {
660c50d8ae3SPaolo Bonzini 	int r;
661c50d8ae3SPaolo Bonzini 
662531281adSSean Christopherson 	/* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
66394ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
664531281adSSean Christopherson 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
665c50d8ae3SPaolo Bonzini 	if (r)
666c50d8ae3SPaolo Bonzini 		return r;
66794ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
668171a90d7SSean Christopherson 				       PT64_ROOT_MAX_LEVEL);
669171a90d7SSean Christopherson 	if (r)
670171a90d7SSean Christopherson 		return r;
671378f5cd6SSean Christopherson 	if (maybe_indirect) {
6726a97575dSDavid Matlack 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
673171a90d7SSean Christopherson 					       PT64_ROOT_MAX_LEVEL);
674c50d8ae3SPaolo Bonzini 		if (r)
675c50d8ae3SPaolo Bonzini 			return r;
676378f5cd6SSean Christopherson 	}
67794ce87efSSean Christopherson 	return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
678531281adSSean Christopherson 					  PT64_ROOT_MAX_LEVEL);
679c50d8ae3SPaolo Bonzini }
680c50d8ae3SPaolo Bonzini 
681c50d8ae3SPaolo Bonzini static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
682c50d8ae3SPaolo Bonzini {
68394ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
68494ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
6856a97575dSDavid Matlack 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
68694ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
687c50d8ae3SPaolo Bonzini }
688c50d8ae3SPaolo Bonzini 
689c50d8ae3SPaolo Bonzini static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
690c50d8ae3SPaolo Bonzini {
691c50d8ae3SPaolo Bonzini 	kmem_cache_free(pte_list_desc_cache, pte_list_desc);
692c50d8ae3SPaolo Bonzini }
693c50d8ae3SPaolo Bonzini 
6946a97575dSDavid Matlack static bool sp_has_gptes(struct kvm_mmu_page *sp);
6956a97575dSDavid Matlack 
696c50d8ae3SPaolo Bonzini static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
697c50d8ae3SPaolo Bonzini {
69884e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
69984e5ffd0SLai Jiangshan 		return sp->gfn;
70084e5ffd0SLai Jiangshan 
701c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
7026a97575dSDavid Matlack 		return sp->shadowed_translation[index] >> PAGE_SHIFT;
703c50d8ae3SPaolo Bonzini 
7042ca3129eSSean Christopherson 	return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
705c50d8ae3SPaolo Bonzini }
706c50d8ae3SPaolo Bonzini 
7076a97575dSDavid Matlack /*
7086a97575dSDavid Matlack  * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
7096a97575dSDavid Matlack  * that the SPTE itself may have a more constrained access permissions that
7106a97575dSDavid Matlack  * what the guest enforces. For example, a guest may create an executable
7116a97575dSDavid Matlack  * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
7126a97575dSDavid Matlack  */
7136a97575dSDavid Matlack static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
714c50d8ae3SPaolo Bonzini {
7156a97575dSDavid Matlack 	if (sp_has_gptes(sp))
7166a97575dSDavid Matlack 		return sp->shadowed_translation[index] & ACC_ALL;
7176a97575dSDavid Matlack 
7186a97575dSDavid Matlack 	/*
7196a97575dSDavid Matlack 	 * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
7206a97575dSDavid Matlack 	 * KVM is not shadowing any guest page tables, so the "guest access
7216a97575dSDavid Matlack 	 * permissions" are just ACC_ALL.
7226a97575dSDavid Matlack 	 *
7236a97575dSDavid Matlack 	 * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
7246a97575dSDavid Matlack 	 * is shadowing a guest huge page with small pages, the guest access
7256a97575dSDavid Matlack 	 * permissions being shadowed are the access permissions of the huge
7266a97575dSDavid Matlack 	 * page.
7276a97575dSDavid Matlack 	 *
7286a97575dSDavid Matlack 	 * In both cases, sp->role.access contains the correct access bits.
7296a97575dSDavid Matlack 	 */
7306a97575dSDavid Matlack 	return sp->role.access;
7316a97575dSDavid Matlack }
7326a97575dSDavid Matlack 
73372ae5822SSean Christopherson static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
73472ae5822SSean Christopherson 					 gfn_t gfn, unsigned int access)
7356a97575dSDavid Matlack {
7366a97575dSDavid Matlack 	if (sp_has_gptes(sp)) {
7376a97575dSDavid Matlack 		sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
73884e5ffd0SLai Jiangshan 		return;
73984e5ffd0SLai Jiangshan 	}
74084e5ffd0SLai Jiangshan 
7416a97575dSDavid Matlack 	WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
7426a97575dSDavid Matlack 	          "access mismatch under %s page %llx (expected %u, got %u)\n",
7436a97575dSDavid Matlack 	          sp->role.passthrough ? "passthrough" : "direct",
7446a97575dSDavid Matlack 	          sp->gfn, kvm_mmu_page_get_access(sp, index), access);
7456a97575dSDavid Matlack 
7466a97575dSDavid Matlack 	WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
7476a97575dSDavid Matlack 	          "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
7486a97575dSDavid Matlack 	          sp->role.passthrough ? "passthrough" : "direct",
7496a97575dSDavid Matlack 	          sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
750c50d8ae3SPaolo Bonzini }
751c50d8ae3SPaolo Bonzini 
75272ae5822SSean Christopherson static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
75372ae5822SSean Christopherson 				    unsigned int access)
7546a97575dSDavid Matlack {
7556a97575dSDavid Matlack 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
7566a97575dSDavid Matlack 
7576a97575dSDavid Matlack 	kvm_mmu_page_set_translation(sp, index, gfn, access);
758c50d8ae3SPaolo Bonzini }
759c50d8ae3SPaolo Bonzini 
760c50d8ae3SPaolo Bonzini /*
761c50d8ae3SPaolo Bonzini  * Return the pointer to the large page information for a given gfn,
762c50d8ae3SPaolo Bonzini  * handling slots that are not large page aligned.
763c50d8ae3SPaolo Bonzini  */
764c50d8ae3SPaolo Bonzini static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
7658ca6f063SBen Gardon 		const struct kvm_memory_slot *slot, int level)
766c50d8ae3SPaolo Bonzini {
767c50d8ae3SPaolo Bonzini 	unsigned long idx;
768c50d8ae3SPaolo Bonzini 
769c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
770c50d8ae3SPaolo Bonzini 	return &slot->arch.lpage_info[level - 2][idx];
771c50d8ae3SPaolo Bonzini }
772c50d8ae3SPaolo Bonzini 
773269e9552SHamza Mahfooz static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
774c50d8ae3SPaolo Bonzini 					    gfn_t gfn, int count)
775c50d8ae3SPaolo Bonzini {
776c50d8ae3SPaolo Bonzini 	struct kvm_lpage_info *linfo;
777c50d8ae3SPaolo Bonzini 	int i;
778c50d8ae3SPaolo Bonzini 
7793bae0459SSean Christopherson 	for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
780c50d8ae3SPaolo Bonzini 		linfo = lpage_info_slot(gfn, slot, i);
781c50d8ae3SPaolo Bonzini 		linfo->disallow_lpage += count;
782c50d8ae3SPaolo Bonzini 		WARN_ON(linfo->disallow_lpage < 0);
783c50d8ae3SPaolo Bonzini 	}
784c50d8ae3SPaolo Bonzini }
785c50d8ae3SPaolo Bonzini 
786269e9552SHamza Mahfooz void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
787c50d8ae3SPaolo Bonzini {
788c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, 1);
789c50d8ae3SPaolo Bonzini }
790c50d8ae3SPaolo Bonzini 
791269e9552SHamza Mahfooz void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
792c50d8ae3SPaolo Bonzini {
793c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, -1);
794c50d8ae3SPaolo Bonzini }
795c50d8ae3SPaolo Bonzini 
796c50d8ae3SPaolo Bonzini static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
797c50d8ae3SPaolo Bonzini {
798c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
799c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
800c50d8ae3SPaolo Bonzini 	gfn_t gfn;
801c50d8ae3SPaolo Bonzini 
802c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages++;
803c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
804c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
805c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
806c50d8ae3SPaolo Bonzini 
807c50d8ae3SPaolo Bonzini 	/* the non-leaf shadow pages are keeping readonly. */
8083bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
809c50d8ae3SPaolo Bonzini 		return kvm_slot_page_track_add_page(kvm, slot, gfn,
810c50d8ae3SPaolo Bonzini 						    KVM_PAGE_TRACK_WRITE);
811c50d8ae3SPaolo Bonzini 
812c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
813be911771SDavid Matlack 
814be911771SDavid Matlack 	if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
815be911771SDavid Matlack 		kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
816c50d8ae3SPaolo Bonzini }
817c50d8ae3SPaolo Bonzini 
81861f94478SSean Christopherson void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
819c50d8ae3SPaolo Bonzini {
820428e9216SSean Christopherson 	/*
821428e9216SSean Christopherson 	 * If it's possible to replace the shadow page with an NX huge page,
822428e9216SSean Christopherson 	 * i.e. if the shadow page is the only thing currently preventing KVM
823428e9216SSean Christopherson 	 * from using a huge page, add the shadow page to the list of "to be
824428e9216SSean Christopherson 	 * zapped for NX recovery" pages.  Note, the shadow page can already be
825428e9216SSean Christopherson 	 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
826428e9216SSean Christopherson 	 * links a shadow page at multiple points.
827428e9216SSean Christopherson 	 */
82861f94478SSean Christopherson 	if (!list_empty(&sp->possible_nx_huge_page_link))
829c50d8ae3SPaolo Bonzini 		return;
830c50d8ae3SPaolo Bonzini 
831c50d8ae3SPaolo Bonzini 	++kvm->stat.nx_lpage_splits;
83255c510e2SSean Christopherson 	list_add_tail(&sp->possible_nx_huge_page_link,
83355c510e2SSean Christopherson 		      &kvm->arch.possible_nx_huge_pages);
834c50d8ae3SPaolo Bonzini }
835c50d8ae3SPaolo Bonzini 
83661f94478SSean Christopherson static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
83761f94478SSean Christopherson 				 bool nx_huge_page_possible)
83861f94478SSean Christopherson {
83961f94478SSean Christopherson 	sp->nx_huge_page_disallowed = true;
84061f94478SSean Christopherson 
84161f94478SSean Christopherson 	if (nx_huge_page_possible)
84261f94478SSean Christopherson 		track_possible_nx_huge_page(kvm, sp);
84361f94478SSean Christopherson }
84461f94478SSean Christopherson 
845c50d8ae3SPaolo Bonzini static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
846c50d8ae3SPaolo Bonzini {
847c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
848c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
849c50d8ae3SPaolo Bonzini 	gfn_t gfn;
850c50d8ae3SPaolo Bonzini 
851c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages--;
852c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
853c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
854c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
8553bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
856c50d8ae3SPaolo Bonzini 		return kvm_slot_page_track_remove_page(kvm, slot, gfn,
857c50d8ae3SPaolo Bonzini 						       KVM_PAGE_TRACK_WRITE);
858c50d8ae3SPaolo Bonzini 
859c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_allow_lpage(slot, gfn);
860c50d8ae3SPaolo Bonzini }
861c50d8ae3SPaolo Bonzini 
86261f94478SSean Christopherson void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
863c50d8ae3SPaolo Bonzini {
86455c510e2SSean Christopherson 	if (list_empty(&sp->possible_nx_huge_page_link))
865428e9216SSean Christopherson 		return;
866428e9216SSean Christopherson 
867428e9216SSean Christopherson 	--kvm->stat.nx_lpage_splits;
86855c510e2SSean Christopherson 	list_del_init(&sp->possible_nx_huge_page_link);
869c50d8ae3SPaolo Bonzini }
870c50d8ae3SPaolo Bonzini 
87161f94478SSean Christopherson static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
87261f94478SSean Christopherson {
87361f94478SSean Christopherson 	sp->nx_huge_page_disallowed = false;
87461f94478SSean Christopherson 
87561f94478SSean Christopherson 	untrack_possible_nx_huge_page(kvm, sp);
87661f94478SSean Christopherson }
87761f94478SSean Christopherson 
878c50d8ae3SPaolo Bonzini static struct kvm_memory_slot *
879c50d8ae3SPaolo Bonzini gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
880c50d8ae3SPaolo Bonzini 			    bool no_dirty_log)
881c50d8ae3SPaolo Bonzini {
882c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
883c50d8ae3SPaolo Bonzini 
884c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
88591b0d268SPaolo Bonzini 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
88691b0d268SPaolo Bonzini 		return NULL;
887044c59c4SPeter Xu 	if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
88891b0d268SPaolo Bonzini 		return NULL;
889c50d8ae3SPaolo Bonzini 
890c50d8ae3SPaolo Bonzini 	return slot;
891c50d8ae3SPaolo Bonzini }
892c50d8ae3SPaolo Bonzini 
893c50d8ae3SPaolo Bonzini /*
894c50d8ae3SPaolo Bonzini  * About rmap_head encoding:
895c50d8ae3SPaolo Bonzini  *
896c50d8ae3SPaolo Bonzini  * If the bit zero of rmap_head->val is clear, then it points to the only spte
897c50d8ae3SPaolo Bonzini  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
898c50d8ae3SPaolo Bonzini  * pte_list_desc containing more mappings.
899c50d8ae3SPaolo Bonzini  */
900c50d8ae3SPaolo Bonzini 
901c50d8ae3SPaolo Bonzini /*
902c50d8ae3SPaolo Bonzini  * Returns the number of pointers in the rmap chain, not counting the new one.
903c50d8ae3SPaolo Bonzini  */
9042ff9039aSDavid Matlack static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
905c50d8ae3SPaolo Bonzini 			struct kvm_rmap_head *rmap_head)
906c50d8ae3SPaolo Bonzini {
907c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
90813236e25SPeter Xu 	int count = 0;
909c50d8ae3SPaolo Bonzini 
910c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
911805a0f83SStephen Zhang 		rmap_printk("%p %llx 0->1\n", spte, *spte);
912c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)spte;
913c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
914805a0f83SStephen Zhang 		rmap_printk("%p %llx 1->many\n", spte, *spte);
9152ff9039aSDavid Matlack 		desc = kvm_mmu_memory_cache_alloc(cache);
916c50d8ae3SPaolo Bonzini 		desc->sptes[0] = (u64 *)rmap_head->val;
917c50d8ae3SPaolo Bonzini 		desc->sptes[1] = spte;
91813236e25SPeter Xu 		desc->spte_count = 2;
919c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)desc | 1;
920c50d8ae3SPaolo Bonzini 		++count;
921c50d8ae3SPaolo Bonzini 	} else {
922805a0f83SStephen Zhang 		rmap_printk("%p %llx many->many\n", spte, *spte);
923c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
92413236e25SPeter Xu 		while (desc->spte_count == PTE_LIST_EXT) {
925c50d8ae3SPaolo Bonzini 			count += PTE_LIST_EXT;
926c6c4f961SLi RongQing 			if (!desc->more) {
9272ff9039aSDavid Matlack 				desc->more = kvm_mmu_memory_cache_alloc(cache);
928c50d8ae3SPaolo Bonzini 				desc = desc->more;
92913236e25SPeter Xu 				desc->spte_count = 0;
930c6c4f961SLi RongQing 				break;
931c6c4f961SLi RongQing 			}
932c6c4f961SLi RongQing 			desc = desc->more;
933c50d8ae3SPaolo Bonzini 		}
93413236e25SPeter Xu 		count += desc->spte_count;
93513236e25SPeter Xu 		desc->sptes[desc->spte_count++] = spte;
936c50d8ae3SPaolo Bonzini 	}
937c50d8ae3SPaolo Bonzini 	return count;
938c50d8ae3SPaolo Bonzini }
939c50d8ae3SPaolo Bonzini 
940c50d8ae3SPaolo Bonzini static void
941c50d8ae3SPaolo Bonzini pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
942c50d8ae3SPaolo Bonzini 			   struct pte_list_desc *desc, int i,
943c50d8ae3SPaolo Bonzini 			   struct pte_list_desc *prev_desc)
944c50d8ae3SPaolo Bonzini {
94513236e25SPeter Xu 	int j = desc->spte_count - 1;
946c50d8ae3SPaolo Bonzini 
947c50d8ae3SPaolo Bonzini 	desc->sptes[i] = desc->sptes[j];
948c50d8ae3SPaolo Bonzini 	desc->sptes[j] = NULL;
94913236e25SPeter Xu 	desc->spte_count--;
95013236e25SPeter Xu 	if (desc->spte_count)
951c50d8ae3SPaolo Bonzini 		return;
952c50d8ae3SPaolo Bonzini 	if (!prev_desc && !desc->more)
953fe3c2b4cSMiaohe Lin 		rmap_head->val = 0;
954c50d8ae3SPaolo Bonzini 	else
955c50d8ae3SPaolo Bonzini 		if (prev_desc)
956c50d8ae3SPaolo Bonzini 			prev_desc->more = desc->more;
957c50d8ae3SPaolo Bonzini 		else
958c50d8ae3SPaolo Bonzini 			rmap_head->val = (unsigned long)desc->more | 1;
959c50d8ae3SPaolo Bonzini 	mmu_free_pte_list_desc(desc);
960c50d8ae3SPaolo Bonzini }
961c50d8ae3SPaolo Bonzini 
9623c2e1037SSean Christopherson static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
963c50d8ae3SPaolo Bonzini {
964c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
965c50d8ae3SPaolo Bonzini 	struct pte_list_desc *prev_desc;
966c50d8ae3SPaolo Bonzini 	int i;
967c50d8ae3SPaolo Bonzini 
968c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
969c50d8ae3SPaolo Bonzini 		pr_err("%s: %p 0->BUG\n", __func__, spte);
970c50d8ae3SPaolo Bonzini 		BUG();
971c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
972805a0f83SStephen Zhang 		rmap_printk("%p 1->0\n", spte);
973c50d8ae3SPaolo Bonzini 		if ((u64 *)rmap_head->val != spte) {
974c50d8ae3SPaolo Bonzini 			pr_err("%s:  %p 1->BUG\n", __func__, spte);
975c50d8ae3SPaolo Bonzini 			BUG();
976c50d8ae3SPaolo Bonzini 		}
977c50d8ae3SPaolo Bonzini 		rmap_head->val = 0;
978c50d8ae3SPaolo Bonzini 	} else {
979805a0f83SStephen Zhang 		rmap_printk("%p many->many\n", spte);
980c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
981c50d8ae3SPaolo Bonzini 		prev_desc = NULL;
982c50d8ae3SPaolo Bonzini 		while (desc) {
98313236e25SPeter Xu 			for (i = 0; i < desc->spte_count; ++i) {
984c50d8ae3SPaolo Bonzini 				if (desc->sptes[i] == spte) {
985c50d8ae3SPaolo Bonzini 					pte_list_desc_remove_entry(rmap_head,
986c50d8ae3SPaolo Bonzini 							desc, i, prev_desc);
987c50d8ae3SPaolo Bonzini 					return;
988c50d8ae3SPaolo Bonzini 				}
989c50d8ae3SPaolo Bonzini 			}
990c50d8ae3SPaolo Bonzini 			prev_desc = desc;
991c50d8ae3SPaolo Bonzini 			desc = desc->more;
992c50d8ae3SPaolo Bonzini 		}
993c50d8ae3SPaolo Bonzini 		pr_err("%s: %p many->many\n", __func__, spte);
994c50d8ae3SPaolo Bonzini 		BUG();
995c50d8ae3SPaolo Bonzini 	}
996c50d8ae3SPaolo Bonzini }
997c50d8ae3SPaolo Bonzini 
9989202aee8SSean Christopherson static void kvm_zap_one_rmap_spte(struct kvm *kvm,
9999202aee8SSean Christopherson 				  struct kvm_rmap_head *rmap_head, u64 *sptep)
1000c50d8ae3SPaolo Bonzini {
100171f51d2cSMingwei Zhang 	mmu_spte_clear_track_bits(kvm, sptep);
10023c2e1037SSean Christopherson 	pte_list_remove(sptep, rmap_head);
1003c50d8ae3SPaolo Bonzini }
1004c50d8ae3SPaolo Bonzini 
10059202aee8SSean Christopherson /* Return true if at least one SPTE was zapped, false otherwise */
10069202aee8SSean Christopherson static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
10079202aee8SSean Christopherson 				   struct kvm_rmap_head *rmap_head)
1008a75b5404SPeter Xu {
1009a75b5404SPeter Xu 	struct pte_list_desc *desc, *next;
1010a75b5404SPeter Xu 	int i;
1011a75b5404SPeter Xu 
1012a75b5404SPeter Xu 	if (!rmap_head->val)
1013a75b5404SPeter Xu 		return false;
1014a75b5404SPeter Xu 
1015a75b5404SPeter Xu 	if (!(rmap_head->val & 1)) {
101671f51d2cSMingwei Zhang 		mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
1017a75b5404SPeter Xu 		goto out;
1018a75b5404SPeter Xu 	}
1019a75b5404SPeter Xu 
1020a75b5404SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1021a75b5404SPeter Xu 
1022a75b5404SPeter Xu 	for (; desc; desc = next) {
1023a75b5404SPeter Xu 		for (i = 0; i < desc->spte_count; i++)
102471f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1025a75b5404SPeter Xu 		next = desc->more;
1026a75b5404SPeter Xu 		mmu_free_pte_list_desc(desc);
1027a75b5404SPeter Xu 	}
1028a75b5404SPeter Xu out:
1029a75b5404SPeter Xu 	/* rmap_head is meaningless now, remember to reset it */
1030a75b5404SPeter Xu 	rmap_head->val = 0;
1031a75b5404SPeter Xu 	return true;
1032a75b5404SPeter Xu }
1033a75b5404SPeter Xu 
10343bcd0662SPeter Xu unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
10353bcd0662SPeter Xu {
10363bcd0662SPeter Xu 	struct pte_list_desc *desc;
10373bcd0662SPeter Xu 	unsigned int count = 0;
10383bcd0662SPeter Xu 
10393bcd0662SPeter Xu 	if (!rmap_head->val)
10403bcd0662SPeter Xu 		return 0;
10413bcd0662SPeter Xu 	else if (!(rmap_head->val & 1))
10423bcd0662SPeter Xu 		return 1;
10433bcd0662SPeter Xu 
10443bcd0662SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
10453bcd0662SPeter Xu 
10463bcd0662SPeter Xu 	while (desc) {
10473bcd0662SPeter Xu 		count += desc->spte_count;
10483bcd0662SPeter Xu 		desc = desc->more;
10493bcd0662SPeter Xu 	}
10503bcd0662SPeter Xu 
10513bcd0662SPeter Xu 	return count;
10523bcd0662SPeter Xu }
10533bcd0662SPeter Xu 
105493e083d4SDavid Matlack static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1055269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
1056c50d8ae3SPaolo Bonzini {
1057c50d8ae3SPaolo Bonzini 	unsigned long idx;
1058c50d8ae3SPaolo Bonzini 
1059c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
10603bae0459SSean Christopherson 	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1061c50d8ae3SPaolo Bonzini }
1062c50d8ae3SPaolo Bonzini 
1063c50d8ae3SPaolo Bonzini static bool rmap_can_add(struct kvm_vcpu *vcpu)
1064c50d8ae3SPaolo Bonzini {
1065356ec69aSSean Christopherson 	struct kvm_mmu_memory_cache *mc;
1066c50d8ae3SPaolo Bonzini 
1067356ec69aSSean Christopherson 	mc = &vcpu->arch.mmu_pte_list_desc_cache;
106894ce87efSSean Christopherson 	return kvm_mmu_memory_cache_nr_free_objects(mc);
1069c50d8ae3SPaolo Bonzini }
1070c50d8ae3SPaolo Bonzini 
1071c50d8ae3SPaolo Bonzini static void rmap_remove(struct kvm *kvm, u64 *spte)
1072c50d8ae3SPaolo Bonzini {
1073601f8af0SDavid Matlack 	struct kvm_memslots *slots;
1074601f8af0SDavid Matlack 	struct kvm_memory_slot *slot;
1075c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1076c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1077c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1078c50d8ae3SPaolo Bonzini 
107957354682SSean Christopherson 	sp = sptep_to_sp(spte);
108079e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1081601f8af0SDavid Matlack 
1082601f8af0SDavid Matlack 	/*
108368be1306SDavid Matlack 	 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
108468be1306SDavid Matlack 	 * so we have to determine which memslots to use based on context
108568be1306SDavid Matlack 	 * information in sp->role.
1086601f8af0SDavid Matlack 	 */
1087601f8af0SDavid Matlack 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1088601f8af0SDavid Matlack 
1089601f8af0SDavid Matlack 	slot = __gfn_to_memslot(slots, gfn);
109093e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1091601f8af0SDavid Matlack 
10923c2e1037SSean Christopherson 	pte_list_remove(spte, rmap_head);
1093c50d8ae3SPaolo Bonzini }
1094c50d8ae3SPaolo Bonzini 
1095c50d8ae3SPaolo Bonzini /*
1096c50d8ae3SPaolo Bonzini  * Used by the following functions to iterate through the sptes linked by a
1097c50d8ae3SPaolo Bonzini  * rmap.  All fields are private and not assumed to be used outside.
1098c50d8ae3SPaolo Bonzini  */
1099c50d8ae3SPaolo Bonzini struct rmap_iterator {
1100c50d8ae3SPaolo Bonzini 	/* private fields */
1101c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1102c50d8ae3SPaolo Bonzini 	int pos;			/* index of the sptep */
1103c50d8ae3SPaolo Bonzini };
1104c50d8ae3SPaolo Bonzini 
1105c50d8ae3SPaolo Bonzini /*
1106c50d8ae3SPaolo Bonzini  * Iteration must be started by this function.  This should also be used after
1107c50d8ae3SPaolo Bonzini  * removing/dropping sptes from the rmap link because in such cases the
11080a03cbdaSMiaohe Lin  * information in the iterator may not be valid.
1109c50d8ae3SPaolo Bonzini  *
1110c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1111c50d8ae3SPaolo Bonzini  */
1112c50d8ae3SPaolo Bonzini static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1113c50d8ae3SPaolo Bonzini 			   struct rmap_iterator *iter)
1114c50d8ae3SPaolo Bonzini {
1115c50d8ae3SPaolo Bonzini 	u64 *sptep;
1116c50d8ae3SPaolo Bonzini 
1117c50d8ae3SPaolo Bonzini 	if (!rmap_head->val)
1118c50d8ae3SPaolo Bonzini 		return NULL;
1119c50d8ae3SPaolo Bonzini 
1120c50d8ae3SPaolo Bonzini 	if (!(rmap_head->val & 1)) {
1121c50d8ae3SPaolo Bonzini 		iter->desc = NULL;
1122c50d8ae3SPaolo Bonzini 		sptep = (u64 *)rmap_head->val;
1123c50d8ae3SPaolo Bonzini 		goto out;
1124c50d8ae3SPaolo Bonzini 	}
1125c50d8ae3SPaolo Bonzini 
1126c50d8ae3SPaolo Bonzini 	iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1127c50d8ae3SPaolo Bonzini 	iter->pos = 0;
1128c50d8ae3SPaolo Bonzini 	sptep = iter->desc->sptes[iter->pos];
1129c50d8ae3SPaolo Bonzini out:
1130c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1131c50d8ae3SPaolo Bonzini 	return sptep;
1132c50d8ae3SPaolo Bonzini }
1133c50d8ae3SPaolo Bonzini 
1134c50d8ae3SPaolo Bonzini /*
1135c50d8ae3SPaolo Bonzini  * Must be used with a valid iterator: e.g. after rmap_get_first().
1136c50d8ae3SPaolo Bonzini  *
1137c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1138c50d8ae3SPaolo Bonzini  */
1139c50d8ae3SPaolo Bonzini static u64 *rmap_get_next(struct rmap_iterator *iter)
1140c50d8ae3SPaolo Bonzini {
1141c50d8ae3SPaolo Bonzini 	u64 *sptep;
1142c50d8ae3SPaolo Bonzini 
1143c50d8ae3SPaolo Bonzini 	if (iter->desc) {
1144c50d8ae3SPaolo Bonzini 		if (iter->pos < PTE_LIST_EXT - 1) {
1145c50d8ae3SPaolo Bonzini 			++iter->pos;
1146c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1147c50d8ae3SPaolo Bonzini 			if (sptep)
1148c50d8ae3SPaolo Bonzini 				goto out;
1149c50d8ae3SPaolo Bonzini 		}
1150c50d8ae3SPaolo Bonzini 
1151c50d8ae3SPaolo Bonzini 		iter->desc = iter->desc->more;
1152c50d8ae3SPaolo Bonzini 
1153c50d8ae3SPaolo Bonzini 		if (iter->desc) {
1154c50d8ae3SPaolo Bonzini 			iter->pos = 0;
1155c50d8ae3SPaolo Bonzini 			/* desc->sptes[0] cannot be NULL */
1156c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1157c50d8ae3SPaolo Bonzini 			goto out;
1158c50d8ae3SPaolo Bonzini 		}
1159c50d8ae3SPaolo Bonzini 	}
1160c50d8ae3SPaolo Bonzini 
1161c50d8ae3SPaolo Bonzini 	return NULL;
1162c50d8ae3SPaolo Bonzini out:
1163c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1164c50d8ae3SPaolo Bonzini 	return sptep;
1165c50d8ae3SPaolo Bonzini }
1166c50d8ae3SPaolo Bonzini 
1167c50d8ae3SPaolo Bonzini #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)			\
1168c50d8ae3SPaolo Bonzini 	for (_spte_ = rmap_get_first(_rmap_head_, _iter_);		\
1169c50d8ae3SPaolo Bonzini 	     _spte_; _spte_ = rmap_get_next(_iter_))
1170c50d8ae3SPaolo Bonzini 
1171c50d8ae3SPaolo Bonzini static void drop_spte(struct kvm *kvm, u64 *sptep)
1172c50d8ae3SPaolo Bonzini {
117371f51d2cSMingwei Zhang 	u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
11747fa2a347SSean Christopherson 
11757fa2a347SSean Christopherson 	if (is_shadow_present_pte(old_spte))
1176c50d8ae3SPaolo Bonzini 		rmap_remove(kvm, sptep);
1177c50d8ae3SPaolo Bonzini }
1178c50d8ae3SPaolo Bonzini 
117903787394SPaolo Bonzini static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1180c50d8ae3SPaolo Bonzini {
11810cd8dc73SPaolo Bonzini 	struct kvm_mmu_page *sp;
11820cd8dc73SPaolo Bonzini 
11830cd8dc73SPaolo Bonzini 	sp = sptep_to_sp(sptep);
11840cd8dc73SPaolo Bonzini 	WARN_ON(sp->role.level == PG_LEVEL_4K);
11850cd8dc73SPaolo Bonzini 
1186c50d8ae3SPaolo Bonzini 	drop_spte(kvm, sptep);
118703787394SPaolo Bonzini 
118803787394SPaolo Bonzini 	if (flush)
11890cd8dc73SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
1190c50d8ae3SPaolo Bonzini 			KVM_PAGES_PER_HPAGE(sp->role.level));
1191c50d8ae3SPaolo Bonzini }
1192c50d8ae3SPaolo Bonzini 
1193c50d8ae3SPaolo Bonzini /*
1194c50d8ae3SPaolo Bonzini  * Write-protect on the specified @sptep, @pt_protect indicates whether
1195c50d8ae3SPaolo Bonzini  * spte write-protection is caused by protecting shadow page table.
1196c50d8ae3SPaolo Bonzini  *
1197c50d8ae3SPaolo Bonzini  * Note: write protection is difference between dirty logging and spte
1198c50d8ae3SPaolo Bonzini  * protection:
1199c50d8ae3SPaolo Bonzini  * - for dirty logging, the spte can be set to writable at anytime if
1200c50d8ae3SPaolo Bonzini  *   its dirty bitmap is properly set.
1201c50d8ae3SPaolo Bonzini  * - for spte protection, the spte can be writable only after unsync-ing
1202c50d8ae3SPaolo Bonzini  *   shadow page.
1203c50d8ae3SPaolo Bonzini  *
1204c50d8ae3SPaolo Bonzini  * Return true if tlb need be flushed.
1205c50d8ae3SPaolo Bonzini  */
1206c50d8ae3SPaolo Bonzini static bool spte_write_protect(u64 *sptep, bool pt_protect)
1207c50d8ae3SPaolo Bonzini {
1208c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1209c50d8ae3SPaolo Bonzini 
1210c50d8ae3SPaolo Bonzini 	if (!is_writable_pte(spte) &&
1211706c9c55SSean Christopherson 	    !(pt_protect && is_mmu_writable_spte(spte)))
1212c50d8ae3SPaolo Bonzini 		return false;
1213c50d8ae3SPaolo Bonzini 
1214805a0f83SStephen Zhang 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1215c50d8ae3SPaolo Bonzini 
1216c50d8ae3SPaolo Bonzini 	if (pt_protect)
12175fc3424fSSean Christopherson 		spte &= ~shadow_mmu_writable_mask;
1218c50d8ae3SPaolo Bonzini 	spte = spte & ~PT_WRITABLE_MASK;
1219c50d8ae3SPaolo Bonzini 
1220c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1221c50d8ae3SPaolo Bonzini }
1222c50d8ae3SPaolo Bonzini 
12231346bbb6SDavid Matlack static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1224c50d8ae3SPaolo Bonzini 			       bool pt_protect)
1225c50d8ae3SPaolo Bonzini {
1226c50d8ae3SPaolo Bonzini 	u64 *sptep;
1227c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1228c50d8ae3SPaolo Bonzini 	bool flush = false;
1229c50d8ae3SPaolo Bonzini 
1230c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1231c50d8ae3SPaolo Bonzini 		flush |= spte_write_protect(sptep, pt_protect);
1232c50d8ae3SPaolo Bonzini 
1233c50d8ae3SPaolo Bonzini 	return flush;
1234c50d8ae3SPaolo Bonzini }
1235c50d8ae3SPaolo Bonzini 
1236c50d8ae3SPaolo Bonzini static bool spte_clear_dirty(u64 *sptep)
1237c50d8ae3SPaolo Bonzini {
1238c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1239c50d8ae3SPaolo Bonzini 
1240805a0f83SStephen Zhang 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1241c50d8ae3SPaolo Bonzini 
1242c50d8ae3SPaolo Bonzini 	MMU_WARN_ON(!spte_ad_enabled(spte));
1243c50d8ae3SPaolo Bonzini 	spte &= ~shadow_dirty_mask;
1244c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1245c50d8ae3SPaolo Bonzini }
1246c50d8ae3SPaolo Bonzini 
1247c50d8ae3SPaolo Bonzini static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1248c50d8ae3SPaolo Bonzini {
1249c50d8ae3SPaolo Bonzini 	bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1250c50d8ae3SPaolo Bonzini 					       (unsigned long *)sptep);
1251c50d8ae3SPaolo Bonzini 	if (was_writable && !spte_ad_enabled(*sptep))
1252c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1253c50d8ae3SPaolo Bonzini 
1254c50d8ae3SPaolo Bonzini 	return was_writable;
1255c50d8ae3SPaolo Bonzini }
1256c50d8ae3SPaolo Bonzini 
1257c50d8ae3SPaolo Bonzini /*
1258c50d8ae3SPaolo Bonzini  * Gets the GFN ready for another round of dirty logging by clearing the
1259c50d8ae3SPaolo Bonzini  *	- D bit on ad-enabled SPTEs, and
1260c50d8ae3SPaolo Bonzini  *	- W bit on ad-disabled SPTEs.
1261c50d8ae3SPaolo Bonzini  * Returns true iff any D or W bits were cleared.
1262c50d8ae3SPaolo Bonzini  */
12630a234f5dSSean Christopherson static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1264269e9552SHamza Mahfooz 			       const struct kvm_memory_slot *slot)
1265c50d8ae3SPaolo Bonzini {
1266c50d8ae3SPaolo Bonzini 	u64 *sptep;
1267c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1268c50d8ae3SPaolo Bonzini 	bool flush = false;
1269c50d8ae3SPaolo Bonzini 
1270c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1271c50d8ae3SPaolo Bonzini 		if (spte_ad_need_write_protect(*sptep))
1272c50d8ae3SPaolo Bonzini 			flush |= spte_wrprot_for_clear_dirty(sptep);
1273c50d8ae3SPaolo Bonzini 		else
1274c50d8ae3SPaolo Bonzini 			flush |= spte_clear_dirty(sptep);
1275c50d8ae3SPaolo Bonzini 
1276c50d8ae3SPaolo Bonzini 	return flush;
1277c50d8ae3SPaolo Bonzini }
1278c50d8ae3SPaolo Bonzini 
1279c50d8ae3SPaolo Bonzini /**
1280c50d8ae3SPaolo Bonzini  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1281c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1282c50d8ae3SPaolo Bonzini  * @slot: slot to protect
1283c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1284c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should protect
1285c50d8ae3SPaolo Bonzini  *
128689212919SKeqian Zhu  * Used when we do not need to care about huge page mappings.
1287c50d8ae3SPaolo Bonzini  */
1288c50d8ae3SPaolo Bonzini static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1289c50d8ae3SPaolo Bonzini 				     struct kvm_memory_slot *slot,
1290c50d8ae3SPaolo Bonzini 				     gfn_t gfn_offset, unsigned long mask)
1291c50d8ae3SPaolo Bonzini {
1292c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1293c50d8ae3SPaolo Bonzini 
12941f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1295a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1296a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, true);
1297e2209710SBen Gardon 
1298e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1299e2209710SBen Gardon 		return;
1300e2209710SBen Gardon 
1301c50d8ae3SPaolo Bonzini 	while (mask) {
130293e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13033bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13041346bbb6SDavid Matlack 		rmap_write_protect(rmap_head, false);
1305c50d8ae3SPaolo Bonzini 
1306c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1307c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1308c50d8ae3SPaolo Bonzini 	}
1309c50d8ae3SPaolo Bonzini }
1310c50d8ae3SPaolo Bonzini 
1311c50d8ae3SPaolo Bonzini /**
1312c50d8ae3SPaolo Bonzini  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1313c50d8ae3SPaolo Bonzini  * protect the page if the D-bit isn't supported.
1314c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1315c50d8ae3SPaolo Bonzini  * @slot: slot to clear D-bit
1316c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1317c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should clear D-bit
1318c50d8ae3SPaolo Bonzini  *
1319c50d8ae3SPaolo Bonzini  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1320c50d8ae3SPaolo Bonzini  */
1321a018eba5SSean Christopherson static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1322c50d8ae3SPaolo Bonzini 					 struct kvm_memory_slot *slot,
1323c50d8ae3SPaolo Bonzini 					 gfn_t gfn_offset, unsigned long mask)
1324c50d8ae3SPaolo Bonzini {
1325c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1326c50d8ae3SPaolo Bonzini 
13271f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1328a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1329a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, false);
1330e2209710SBen Gardon 
1331e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1332e2209710SBen Gardon 		return;
1333e2209710SBen Gardon 
1334c50d8ae3SPaolo Bonzini 	while (mask) {
133593e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13363bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13370a234f5dSSean Christopherson 		__rmap_clear_dirty(kvm, rmap_head, slot);
1338c50d8ae3SPaolo Bonzini 
1339c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1340c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1341c50d8ae3SPaolo Bonzini 	}
1342c50d8ae3SPaolo Bonzini }
1343c50d8ae3SPaolo Bonzini 
1344c50d8ae3SPaolo Bonzini /**
1345c50d8ae3SPaolo Bonzini  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1346c50d8ae3SPaolo Bonzini  * PT level pages.
1347c50d8ae3SPaolo Bonzini  *
1348c50d8ae3SPaolo Bonzini  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1349c50d8ae3SPaolo Bonzini  * enable dirty logging for them.
1350c50d8ae3SPaolo Bonzini  *
135189212919SKeqian Zhu  * We need to care about huge page mappings: e.g. during dirty logging we may
135289212919SKeqian Zhu  * have such mappings.
1353c50d8ae3SPaolo Bonzini  */
1354c50d8ae3SPaolo Bonzini void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1355c50d8ae3SPaolo Bonzini 				struct kvm_memory_slot *slot,
1356c50d8ae3SPaolo Bonzini 				gfn_t gfn_offset, unsigned long mask)
1357c50d8ae3SPaolo Bonzini {
135889212919SKeqian Zhu 	/*
135989212919SKeqian Zhu 	 * Huge pages are NOT write protected when we start dirty logging in
136089212919SKeqian Zhu 	 * initially-all-set mode; must write protect them here so that they
136189212919SKeqian Zhu 	 * are split to 4K on the first write.
136289212919SKeqian Zhu 	 *
136389212919SKeqian Zhu 	 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
136489212919SKeqian Zhu 	 * of memslot has no such restriction, so the range can cross two large
136589212919SKeqian Zhu 	 * pages.
136689212919SKeqian Zhu 	 */
136789212919SKeqian Zhu 	if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
136889212919SKeqian Zhu 		gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
136989212919SKeqian Zhu 		gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
137089212919SKeqian Zhu 
1371cb00a70bSDavid Matlack 		if (READ_ONCE(eager_page_split))
1372cb00a70bSDavid Matlack 			kvm_mmu_try_split_huge_pages(kvm, slot, start, end, PG_LEVEL_4K);
1373cb00a70bSDavid Matlack 
137489212919SKeqian Zhu 		kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
137589212919SKeqian Zhu 
137689212919SKeqian Zhu 		/* Cross two large pages? */
137789212919SKeqian Zhu 		if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
137889212919SKeqian Zhu 		    ALIGN(end << PAGE_SHIFT, PMD_SIZE))
137989212919SKeqian Zhu 			kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
138089212919SKeqian Zhu 						       PG_LEVEL_2M);
138189212919SKeqian Zhu 	}
138289212919SKeqian Zhu 
138389212919SKeqian Zhu 	/* Now handle 4K PTEs.  */
1384a018eba5SSean Christopherson 	if (kvm_x86_ops.cpu_dirty_log_size)
1385a018eba5SSean Christopherson 		kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1386c50d8ae3SPaolo Bonzini 	else
1387c50d8ae3SPaolo Bonzini 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1388c50d8ae3SPaolo Bonzini }
1389c50d8ae3SPaolo Bonzini 
1390fb04a1edSPeter Xu int kvm_cpu_dirty_log_size(void)
1391fb04a1edSPeter Xu {
13926dd03800SSean Christopherson 	return kvm_x86_ops.cpu_dirty_log_size;
1393fb04a1edSPeter Xu }
1394fb04a1edSPeter Xu 
1395c50d8ae3SPaolo Bonzini bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
13963ad93562SKeqian Zhu 				    struct kvm_memory_slot *slot, u64 gfn,
13973ad93562SKeqian Zhu 				    int min_level)
1398c50d8ae3SPaolo Bonzini {
1399c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1400c50d8ae3SPaolo Bonzini 	int i;
1401c50d8ae3SPaolo Bonzini 	bool write_protected = false;
1402c50d8ae3SPaolo Bonzini 
1403e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
14043ad93562SKeqian Zhu 		for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
140593e083d4SDavid Matlack 			rmap_head = gfn_to_rmap(gfn, i, slot);
14061346bbb6SDavid Matlack 			write_protected |= rmap_write_protect(rmap_head, true);
1407c50d8ae3SPaolo Bonzini 		}
1408e2209710SBen Gardon 	}
1409c50d8ae3SPaolo Bonzini 
14101f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
141146044f72SBen Gardon 		write_protected |=
14123ad93562SKeqian Zhu 			kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
141346044f72SBen Gardon 
1414c50d8ae3SPaolo Bonzini 	return write_protected;
1415c50d8ae3SPaolo Bonzini }
1416c50d8ae3SPaolo Bonzini 
1417cf48f9e2SDavid Matlack static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1418c50d8ae3SPaolo Bonzini {
1419c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
1420c50d8ae3SPaolo Bonzini 
1421c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
14223ad93562SKeqian Zhu 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1423c50d8ae3SPaolo Bonzini }
1424c50d8ae3SPaolo Bonzini 
1425f8480721SSean Christopherson static bool __kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1426269e9552SHamza Mahfooz 			   const struct kvm_memory_slot *slot)
1427c50d8ae3SPaolo Bonzini {
14289202aee8SSean Christopherson 	return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1429c50d8ae3SPaolo Bonzini }
1430c50d8ae3SPaolo Bonzini 
1431f8480721SSean Christopherson static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1432c50d8ae3SPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
14333039bcc7SSean Christopherson 			 pte_t unused)
1434c50d8ae3SPaolo Bonzini {
1435f8480721SSean Christopherson 	return __kvm_zap_rmap(kvm, rmap_head, slot);
1436c50d8ae3SPaolo Bonzini }
1437c50d8ae3SPaolo Bonzini 
1438aed02fe3SSean Christopherson static bool kvm_set_pte_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1439c50d8ae3SPaolo Bonzini 			     struct kvm_memory_slot *slot, gfn_t gfn, int level,
14403039bcc7SSean Christopherson 			     pte_t pte)
1441c50d8ae3SPaolo Bonzini {
1442c50d8ae3SPaolo Bonzini 	u64 *sptep;
1443c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
144498a26b69SVihas Mak 	bool need_flush = false;
1445c50d8ae3SPaolo Bonzini 	u64 new_spte;
1446c50d8ae3SPaolo Bonzini 	kvm_pfn_t new_pfn;
1447c50d8ae3SPaolo Bonzini 
14483039bcc7SSean Christopherson 	WARN_ON(pte_huge(pte));
14493039bcc7SSean Christopherson 	new_pfn = pte_pfn(pte);
1450c50d8ae3SPaolo Bonzini 
1451c50d8ae3SPaolo Bonzini restart:
1452c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
1453805a0f83SStephen Zhang 		rmap_printk("spte %p %llx gfn %llx (%d)\n",
1454c50d8ae3SPaolo Bonzini 			    sptep, *sptep, gfn, level);
1455c50d8ae3SPaolo Bonzini 
145698a26b69SVihas Mak 		need_flush = true;
1457c50d8ae3SPaolo Bonzini 
14583039bcc7SSean Christopherson 		if (pte_write(pte)) {
14599202aee8SSean Christopherson 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
1460c50d8ae3SPaolo Bonzini 			goto restart;
1461c50d8ae3SPaolo Bonzini 		} else {
1462cb3eedabSPaolo Bonzini 			new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1463cb3eedabSPaolo Bonzini 					*sptep, new_pfn);
1464c50d8ae3SPaolo Bonzini 
146571f51d2cSMingwei Zhang 			mmu_spte_clear_track_bits(kvm, sptep);
1466c50d8ae3SPaolo Bonzini 			mmu_spte_set(sptep, new_spte);
1467c50d8ae3SPaolo Bonzini 		}
1468c50d8ae3SPaolo Bonzini 	}
1469c50d8ae3SPaolo Bonzini 
1470c50d8ae3SPaolo Bonzini 	if (need_flush && kvm_available_flush_tlb_with_range()) {
1471c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
147298a26b69SVihas Mak 		return false;
1473c50d8ae3SPaolo Bonzini 	}
1474c50d8ae3SPaolo Bonzini 
1475c50d8ae3SPaolo Bonzini 	return need_flush;
1476c50d8ae3SPaolo Bonzini }
1477c50d8ae3SPaolo Bonzini 
1478c50d8ae3SPaolo Bonzini struct slot_rmap_walk_iterator {
1479c50d8ae3SPaolo Bonzini 	/* input fields. */
1480269e9552SHamza Mahfooz 	const struct kvm_memory_slot *slot;
1481c50d8ae3SPaolo Bonzini 	gfn_t start_gfn;
1482c50d8ae3SPaolo Bonzini 	gfn_t end_gfn;
1483c50d8ae3SPaolo Bonzini 	int start_level;
1484c50d8ae3SPaolo Bonzini 	int end_level;
1485c50d8ae3SPaolo Bonzini 
1486c50d8ae3SPaolo Bonzini 	/* output fields. */
1487c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1488c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap;
1489c50d8ae3SPaolo Bonzini 	int level;
1490c50d8ae3SPaolo Bonzini 
1491c50d8ae3SPaolo Bonzini 	/* private field. */
1492c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *end_rmap;
1493c50d8ae3SPaolo Bonzini };
1494c50d8ae3SPaolo Bonzini 
1495c50d8ae3SPaolo Bonzini static void
1496c50d8ae3SPaolo Bonzini rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1497c50d8ae3SPaolo Bonzini {
1498c50d8ae3SPaolo Bonzini 	iterator->level = level;
1499c50d8ae3SPaolo Bonzini 	iterator->gfn = iterator->start_gfn;
150093e083d4SDavid Matlack 	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
150193e083d4SDavid Matlack 	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1502c50d8ae3SPaolo Bonzini }
1503c50d8ae3SPaolo Bonzini 
1504c50d8ae3SPaolo Bonzini static void
1505c50d8ae3SPaolo Bonzini slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1506269e9552SHamza Mahfooz 		    const struct kvm_memory_slot *slot, int start_level,
1507c50d8ae3SPaolo Bonzini 		    int end_level, gfn_t start_gfn, gfn_t end_gfn)
1508c50d8ae3SPaolo Bonzini {
1509c50d8ae3SPaolo Bonzini 	iterator->slot = slot;
1510c50d8ae3SPaolo Bonzini 	iterator->start_level = start_level;
1511c50d8ae3SPaolo Bonzini 	iterator->end_level = end_level;
1512c50d8ae3SPaolo Bonzini 	iterator->start_gfn = start_gfn;
1513c50d8ae3SPaolo Bonzini 	iterator->end_gfn = end_gfn;
1514c50d8ae3SPaolo Bonzini 
1515c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->start_level);
1516c50d8ae3SPaolo Bonzini }
1517c50d8ae3SPaolo Bonzini 
1518c50d8ae3SPaolo Bonzini static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1519c50d8ae3SPaolo Bonzini {
1520c50d8ae3SPaolo Bonzini 	return !!iterator->rmap;
1521c50d8ae3SPaolo Bonzini }
1522c50d8ae3SPaolo Bonzini 
1523c50d8ae3SPaolo Bonzini static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1524c50d8ae3SPaolo Bonzini {
15256ba1e04fSVipin Sharma 	while (++iterator->rmap <= iterator->end_rmap) {
1526c50d8ae3SPaolo Bonzini 		iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
15276ba1e04fSVipin Sharma 
15286ba1e04fSVipin Sharma 		if (iterator->rmap->val)
1529c50d8ae3SPaolo Bonzini 			return;
1530c50d8ae3SPaolo Bonzini 	}
1531c50d8ae3SPaolo Bonzini 
1532c50d8ae3SPaolo Bonzini 	if (++iterator->level > iterator->end_level) {
1533c50d8ae3SPaolo Bonzini 		iterator->rmap = NULL;
1534c50d8ae3SPaolo Bonzini 		return;
1535c50d8ae3SPaolo Bonzini 	}
1536c50d8ae3SPaolo Bonzini 
1537c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->level);
1538c50d8ae3SPaolo Bonzini }
1539c50d8ae3SPaolo Bonzini 
1540c50d8ae3SPaolo Bonzini #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1541c50d8ae3SPaolo Bonzini 	   _start_gfn, _end_gfn, _iter_)				\
1542c50d8ae3SPaolo Bonzini 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1543c50d8ae3SPaolo Bonzini 				 _end_level_, _start_gfn, _end_gfn);	\
1544c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_okay(_iter_);				\
1545c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_next(_iter_))
1546c50d8ae3SPaolo Bonzini 
15473039bcc7SSean Christopherson typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1548c1b91493SSean Christopherson 			       struct kvm_memory_slot *slot, gfn_t gfn,
15493039bcc7SSean Christopherson 			       int level, pte_t pte);
1550c1b91493SSean Christopherson 
15513039bcc7SSean Christopherson static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
15523039bcc7SSean Christopherson 						 struct kvm_gfn_range *range,
1553c1b91493SSean Christopherson 						 rmap_handler_t handler)
1554c50d8ae3SPaolo Bonzini {
1555c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
15563039bcc7SSean Christopherson 	bool ret = false;
1557c50d8ae3SPaolo Bonzini 
15583039bcc7SSean Christopherson 	for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
15593039bcc7SSean Christopherson 				 range->start, range->end - 1, &iterator)
15603039bcc7SSean Christopherson 		ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
15613039bcc7SSean Christopherson 			       iterator.level, range->pte);
1562c50d8ae3SPaolo Bonzini 
1563c50d8ae3SPaolo Bonzini 	return ret;
1564c50d8ae3SPaolo Bonzini }
1565c50d8ae3SPaolo Bonzini 
15663039bcc7SSean Christopherson bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1567c50d8ae3SPaolo Bonzini {
1568e2209710SBen Gardon 	bool flush = false;
1569c50d8ae3SPaolo Bonzini 
1570e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1571f8480721SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
1572063afacdSBen Gardon 
15731f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
1574c7785d85SHou Wenlong 		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1575063afacdSBen Gardon 
15763039bcc7SSean Christopherson 	return flush;
1577c50d8ae3SPaolo Bonzini }
1578c50d8ae3SPaolo Bonzini 
15793039bcc7SSean Christopherson bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1580c50d8ae3SPaolo Bonzini {
1581e2209710SBen Gardon 	bool flush = false;
15821d8dd6b3SBen Gardon 
1583e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1584aed02fe3SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmap);
15851d8dd6b3SBen Gardon 
15861f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
15873039bcc7SSean Christopherson 		flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
15881d8dd6b3SBen Gardon 
15893039bcc7SSean Christopherson 	return flush;
1590c50d8ae3SPaolo Bonzini }
1591c50d8ae3SPaolo Bonzini 
1592aed02fe3SSean Christopherson static bool kvm_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1593c50d8ae3SPaolo Bonzini 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
15943039bcc7SSean Christopherson 			 pte_t unused)
1595c50d8ae3SPaolo Bonzini {
1596c50d8ae3SPaolo Bonzini 	u64 *sptep;
15973f649ab7SKees Cook 	struct rmap_iterator iter;
1598c50d8ae3SPaolo Bonzini 	int young = 0;
1599c50d8ae3SPaolo Bonzini 
1600c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1601c50d8ae3SPaolo Bonzini 		young |= mmu_spte_age(sptep);
1602c50d8ae3SPaolo Bonzini 
1603c50d8ae3SPaolo Bonzini 	return young;
1604c50d8ae3SPaolo Bonzini }
1605c50d8ae3SPaolo Bonzini 
1606aed02fe3SSean Christopherson static bool kvm_test_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1607c50d8ae3SPaolo Bonzini 			      struct kvm_memory_slot *slot, gfn_t gfn,
16083039bcc7SSean Christopherson 			      int level, pte_t unused)
1609c50d8ae3SPaolo Bonzini {
1610c50d8ae3SPaolo Bonzini 	u64 *sptep;
1611c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1612c50d8ae3SPaolo Bonzini 
1613c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1614c50d8ae3SPaolo Bonzini 		if (is_accessed_spte(*sptep))
161598a26b69SVihas Mak 			return true;
161698a26b69SVihas Mak 	return false;
1617c50d8ae3SPaolo Bonzini }
1618c50d8ae3SPaolo Bonzini 
1619c50d8ae3SPaolo Bonzini #define RMAP_RECYCLE_THRESHOLD 1000
1620c50d8ae3SPaolo Bonzini 
16212ff9039aSDavid Matlack static void __rmap_add(struct kvm *kvm,
16222ff9039aSDavid Matlack 		       struct kvm_mmu_memory_cache *cache,
16232ff9039aSDavid Matlack 		       const struct kvm_memory_slot *slot,
162472ae5822SSean Christopherson 		       u64 *spte, gfn_t gfn, unsigned int access)
1625c50d8ae3SPaolo Bonzini {
1626c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
162768be1306SDavid Matlack 	struct kvm_rmap_head *rmap_head;
162868be1306SDavid Matlack 	int rmap_count;
1629c50d8ae3SPaolo Bonzini 
163057354682SSean Christopherson 	sp = sptep_to_sp(spte);
163179e48cecSSean Christopherson 	kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
163281cb4657SDavid Matlack 	kvm_update_page_stats(kvm, sp->role.level, 1);
163381cb4657SDavid Matlack 
163493e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
16352ff9039aSDavid Matlack 	rmap_count = pte_list_add(cache, spte, rmap_head);
1636c50d8ae3SPaolo Bonzini 
1637604f5332SMiaohe Lin 	if (rmap_count > kvm->stat.max_mmu_rmap_size)
1638604f5332SMiaohe Lin 		kvm->stat.max_mmu_rmap_size = rmap_count;
163968be1306SDavid Matlack 	if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
16409202aee8SSean Christopherson 		kvm_zap_all_rmap_sptes(kvm, rmap_head);
164168be1306SDavid Matlack 		kvm_flush_remote_tlbs_with_address(
16422ff9039aSDavid Matlack 				kvm, sp->gfn, KVM_PAGES_PER_HPAGE(sp->role.level));
164368be1306SDavid Matlack 	}
1644c50d8ae3SPaolo Bonzini }
1645c50d8ae3SPaolo Bonzini 
16462ff9039aSDavid Matlack static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
164772ae5822SSean Christopherson 		     u64 *spte, gfn_t gfn, unsigned int access)
16482ff9039aSDavid Matlack {
16492ff9039aSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
16502ff9039aSDavid Matlack 
16516a97575dSDavid Matlack 	__rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
16522ff9039aSDavid Matlack }
16532ff9039aSDavid Matlack 
16543039bcc7SSean Christopherson bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1655c50d8ae3SPaolo Bonzini {
1656e2209710SBen Gardon 	bool young = false;
1657f8e14497SBen Gardon 
1658e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1659aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_age_rmap);
16603039bcc7SSean Christopherson 
16611f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16623039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1663f8e14497SBen Gardon 
1664f8e14497SBen Gardon 	return young;
1665c50d8ae3SPaolo Bonzini }
1666c50d8ae3SPaolo Bonzini 
16673039bcc7SSean Christopherson bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1668c50d8ae3SPaolo Bonzini {
1669e2209710SBen Gardon 	bool young = false;
1670f8e14497SBen Gardon 
1671e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
1672aed02fe3SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmap);
16733039bcc7SSean Christopherson 
16741f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
16753039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1676f8e14497SBen Gardon 
1677f8e14497SBen Gardon 	return young;
1678c50d8ae3SPaolo Bonzini }
1679c50d8ae3SPaolo Bonzini 
1680c50d8ae3SPaolo Bonzini #ifdef MMU_DEBUG
1681c50d8ae3SPaolo Bonzini static int is_empty_shadow_page(u64 *spt)
1682c50d8ae3SPaolo Bonzini {
1683c50d8ae3SPaolo Bonzini 	u64 *pos;
1684c50d8ae3SPaolo Bonzini 	u64 *end;
1685c50d8ae3SPaolo Bonzini 
16863adbdf81SMiaohe Lin 	for (pos = spt, end = pos + SPTE_ENT_PER_PAGE; pos != end; pos++)
1687c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*pos)) {
1688c50d8ae3SPaolo Bonzini 			printk(KERN_ERR "%s: %p %llx\n", __func__,
1689c50d8ae3SPaolo Bonzini 			       pos, *pos);
1690c50d8ae3SPaolo Bonzini 			return 0;
1691c50d8ae3SPaolo Bonzini 		}
1692c50d8ae3SPaolo Bonzini 	return 1;
1693c50d8ae3SPaolo Bonzini }
1694c50d8ae3SPaolo Bonzini #endif
1695c50d8ae3SPaolo Bonzini 
1696c50d8ae3SPaolo Bonzini /*
1697c50d8ae3SPaolo Bonzini  * This value is the sum of all of the kvm instances's
1698c50d8ae3SPaolo Bonzini  * kvm->arch.n_used_mmu_pages values.  We need a global,
1699c50d8ae3SPaolo Bonzini  * aggregate version in order to make the slab shrinker
1700c50d8ae3SPaolo Bonzini  * faster
1701c50d8ae3SPaolo Bonzini  */
1702d5aaad6fSSean Christopherson static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1703c50d8ae3SPaolo Bonzini {
1704c50d8ae3SPaolo Bonzini 	kvm->arch.n_used_mmu_pages += nr;
1705c50d8ae3SPaolo Bonzini 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1706c50d8ae3SPaolo Bonzini }
1707c50d8ae3SPaolo Bonzini 
170843a063caSYosry Ahmed static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
170943a063caSYosry Ahmed {
171043a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, +1);
171143a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, +1);
171243a063caSYosry Ahmed }
171343a063caSYosry Ahmed 
171443a063caSYosry Ahmed static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
171543a063caSYosry Ahmed {
171643a063caSYosry Ahmed 	kvm_mod_used_mmu_pages(kvm, -1);
171743a063caSYosry Ahmed 	kvm_account_pgtable_pages((void *)sp->spt, -1);
171843a063caSYosry Ahmed }
171943a063caSYosry Ahmed 
172087654643SDavid Matlack static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1721c50d8ae3SPaolo Bonzini {
1722c50d8ae3SPaolo Bonzini 	MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1723c50d8ae3SPaolo Bonzini 	hlist_del(&sp->hash_link);
1724c50d8ae3SPaolo Bonzini 	list_del(&sp->link);
1725c50d8ae3SPaolo Bonzini 	free_page((unsigned long)sp->spt);
1726c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
17276a97575dSDavid Matlack 		free_page((unsigned long)sp->shadowed_translation);
1728c50d8ae3SPaolo Bonzini 	kmem_cache_free(mmu_page_header_cache, sp);
1729c50d8ae3SPaolo Bonzini }
1730c50d8ae3SPaolo Bonzini 
1731c50d8ae3SPaolo Bonzini static unsigned kvm_page_table_hashfn(gfn_t gfn)
1732c50d8ae3SPaolo Bonzini {
1733c50d8ae3SPaolo Bonzini 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1734c50d8ae3SPaolo Bonzini }
1735c50d8ae3SPaolo Bonzini 
17362ff9039aSDavid Matlack static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
1737c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp, u64 *parent_pte)
1738c50d8ae3SPaolo Bonzini {
1739c50d8ae3SPaolo Bonzini 	if (!parent_pte)
1740c50d8ae3SPaolo Bonzini 		return;
1741c50d8ae3SPaolo Bonzini 
17422ff9039aSDavid Matlack 	pte_list_add(cache, parent_pte, &sp->parent_ptes);
1743c50d8ae3SPaolo Bonzini }
1744c50d8ae3SPaolo Bonzini 
1745c50d8ae3SPaolo Bonzini static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1746c50d8ae3SPaolo Bonzini 				       u64 *parent_pte)
1747c50d8ae3SPaolo Bonzini {
17483c2e1037SSean Christopherson 	pte_list_remove(parent_pte, &sp->parent_ptes);
1749c50d8ae3SPaolo Bonzini }
1750c50d8ae3SPaolo Bonzini 
1751c50d8ae3SPaolo Bonzini static void drop_parent_pte(struct kvm_mmu_page *sp,
1752c50d8ae3SPaolo Bonzini 			    u64 *parent_pte)
1753c50d8ae3SPaolo Bonzini {
1754c50d8ae3SPaolo Bonzini 	mmu_page_remove_parent_pte(sp, parent_pte);
1755c50d8ae3SPaolo Bonzini 	mmu_spte_clear_no_track(parent_pte);
1756c50d8ae3SPaolo Bonzini }
1757c50d8ae3SPaolo Bonzini 
1758c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte);
1759c50d8ae3SPaolo Bonzini static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1760c50d8ae3SPaolo Bonzini {
1761c50d8ae3SPaolo Bonzini 	u64 *sptep;
1762c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1763c50d8ae3SPaolo Bonzini 
1764c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1765c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
1766c50d8ae3SPaolo Bonzini 	}
1767c50d8ae3SPaolo Bonzini }
1768c50d8ae3SPaolo Bonzini 
1769c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte)
1770c50d8ae3SPaolo Bonzini {
1771c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1772c50d8ae3SPaolo Bonzini 
177357354682SSean Christopherson 	sp = sptep_to_sp(spte);
177479e48cecSSean Christopherson 	if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1775c50d8ae3SPaolo Bonzini 		return;
1776c50d8ae3SPaolo Bonzini 	if (sp->unsync_children++)
1777c50d8ae3SPaolo Bonzini 		return;
1778c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
1779c50d8ae3SPaolo Bonzini }
1780c50d8ae3SPaolo Bonzini 
1781c50d8ae3SPaolo Bonzini static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
1782c50d8ae3SPaolo Bonzini 			       struct kvm_mmu_page *sp)
1783c50d8ae3SPaolo Bonzini {
1784c3e5e415SLai Jiangshan 	return -1;
1785c50d8ae3SPaolo Bonzini }
1786c50d8ae3SPaolo Bonzini 
1787c50d8ae3SPaolo Bonzini #define KVM_PAGE_ARRAY_NR 16
1788c50d8ae3SPaolo Bonzini 
1789c50d8ae3SPaolo Bonzini struct kvm_mmu_pages {
1790c50d8ae3SPaolo Bonzini 	struct mmu_page_and_offset {
1791c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
1792c50d8ae3SPaolo Bonzini 		unsigned int idx;
1793c50d8ae3SPaolo Bonzini 	} page[KVM_PAGE_ARRAY_NR];
1794c50d8ae3SPaolo Bonzini 	unsigned int nr;
1795c50d8ae3SPaolo Bonzini };
1796c50d8ae3SPaolo Bonzini 
1797c50d8ae3SPaolo Bonzini static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1798c50d8ae3SPaolo Bonzini 			 int idx)
1799c50d8ae3SPaolo Bonzini {
1800c50d8ae3SPaolo Bonzini 	int i;
1801c50d8ae3SPaolo Bonzini 
1802c50d8ae3SPaolo Bonzini 	if (sp->unsync)
1803c50d8ae3SPaolo Bonzini 		for (i=0; i < pvec->nr; i++)
1804c50d8ae3SPaolo Bonzini 			if (pvec->page[i].sp == sp)
1805c50d8ae3SPaolo Bonzini 				return 0;
1806c50d8ae3SPaolo Bonzini 
1807c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].sp = sp;
1808c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].idx = idx;
1809c50d8ae3SPaolo Bonzini 	pvec->nr++;
1810c50d8ae3SPaolo Bonzini 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
1811c50d8ae3SPaolo Bonzini }
1812c50d8ae3SPaolo Bonzini 
1813c50d8ae3SPaolo Bonzini static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1814c50d8ae3SPaolo Bonzini {
1815c50d8ae3SPaolo Bonzini 	--sp->unsync_children;
1816c50d8ae3SPaolo Bonzini 	WARN_ON((int)sp->unsync_children < 0);
1817c50d8ae3SPaolo Bonzini 	__clear_bit(idx, sp->unsync_child_bitmap);
1818c50d8ae3SPaolo Bonzini }
1819c50d8ae3SPaolo Bonzini 
1820c50d8ae3SPaolo Bonzini static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1821c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1822c50d8ae3SPaolo Bonzini {
1823c50d8ae3SPaolo Bonzini 	int i, ret, nr_unsync_leaf = 0;
1824c50d8ae3SPaolo Bonzini 
1825c50d8ae3SPaolo Bonzini 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1826c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
1827c50d8ae3SPaolo Bonzini 		u64 ent = sp->spt[i];
1828c50d8ae3SPaolo Bonzini 
1829c50d8ae3SPaolo Bonzini 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1830c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1831c50d8ae3SPaolo Bonzini 			continue;
1832c50d8ae3SPaolo Bonzini 		}
1833c50d8ae3SPaolo Bonzini 
18345e3edd7eSSean Christopherson 		child = spte_to_child_sp(ent);
1835c50d8ae3SPaolo Bonzini 
1836c50d8ae3SPaolo Bonzini 		if (child->unsync_children) {
1837c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1838c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1839c50d8ae3SPaolo Bonzini 
1840c50d8ae3SPaolo Bonzini 			ret = __mmu_unsync_walk(child, pvec);
1841c50d8ae3SPaolo Bonzini 			if (!ret) {
1842c50d8ae3SPaolo Bonzini 				clear_unsync_child_bit(sp, i);
1843c50d8ae3SPaolo Bonzini 				continue;
1844c50d8ae3SPaolo Bonzini 			} else if (ret > 0) {
1845c50d8ae3SPaolo Bonzini 				nr_unsync_leaf += ret;
1846c50d8ae3SPaolo Bonzini 			} else
1847c50d8ae3SPaolo Bonzini 				return ret;
1848c50d8ae3SPaolo Bonzini 		} else if (child->unsync) {
1849c50d8ae3SPaolo Bonzini 			nr_unsync_leaf++;
1850c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1851c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1852c50d8ae3SPaolo Bonzini 		} else
1853c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1854c50d8ae3SPaolo Bonzini 	}
1855c50d8ae3SPaolo Bonzini 
1856c50d8ae3SPaolo Bonzini 	return nr_unsync_leaf;
1857c50d8ae3SPaolo Bonzini }
1858c50d8ae3SPaolo Bonzini 
1859c50d8ae3SPaolo Bonzini #define INVALID_INDEX (-1)
1860c50d8ae3SPaolo Bonzini 
1861c50d8ae3SPaolo Bonzini static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1862c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1863c50d8ae3SPaolo Bonzini {
1864c50d8ae3SPaolo Bonzini 	pvec->nr = 0;
1865c50d8ae3SPaolo Bonzini 	if (!sp->unsync_children)
1866c50d8ae3SPaolo Bonzini 		return 0;
1867c50d8ae3SPaolo Bonzini 
1868c50d8ae3SPaolo Bonzini 	mmu_pages_add(pvec, sp, INVALID_INDEX);
1869c50d8ae3SPaolo Bonzini 	return __mmu_unsync_walk(sp, pvec);
1870c50d8ae3SPaolo Bonzini }
1871c50d8ae3SPaolo Bonzini 
1872c50d8ae3SPaolo Bonzini static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1873c50d8ae3SPaolo Bonzini {
1874c50d8ae3SPaolo Bonzini 	WARN_ON(!sp->unsync);
1875c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_sync_page(sp);
1876c50d8ae3SPaolo Bonzini 	sp->unsync = 0;
1877c50d8ae3SPaolo Bonzini 	--kvm->stat.mmu_unsync;
1878c50d8ae3SPaolo Bonzini }
1879c50d8ae3SPaolo Bonzini 
1880c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1881c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list);
1882c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1883c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list);
1884c50d8ae3SPaolo Bonzini 
1885767d8d8dSLai Jiangshan static bool sp_has_gptes(struct kvm_mmu_page *sp)
1886767d8d8dSLai Jiangshan {
1887767d8d8dSLai Jiangshan 	if (sp->role.direct)
1888767d8d8dSLai Jiangshan 		return false;
1889767d8d8dSLai Jiangshan 
189084e5ffd0SLai Jiangshan 	if (sp->role.passthrough)
189184e5ffd0SLai Jiangshan 		return false;
189284e5ffd0SLai Jiangshan 
1893767d8d8dSLai Jiangshan 	return true;
1894767d8d8dSLai Jiangshan }
1895767d8d8dSLai Jiangshan 
1896ac101b7cSSean Christopherson #define for_each_valid_sp(_kvm, _sp, _list)				\
1897ac101b7cSSean Christopherson 	hlist_for_each_entry(_sp, _list, hash_link)			\
1898c50d8ae3SPaolo Bonzini 		if (is_obsolete_sp((_kvm), (_sp))) {			\
1899c50d8ae3SPaolo Bonzini 		} else
1900c50d8ae3SPaolo Bonzini 
1901767d8d8dSLai Jiangshan #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn)		\
1902ac101b7cSSean Christopherson 	for_each_valid_sp(_kvm, _sp,					\
1903ac101b7cSSean Christopherson 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
1904767d8d8dSLai Jiangshan 		if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1905c50d8ae3SPaolo Bonzini 
19068d5678a7SHou Wenlong static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1907c50d8ae3SPaolo Bonzini 			 struct list_head *invalid_list)
1908c50d8ae3SPaolo Bonzini {
1909c3e5e415SLai Jiangshan 	int ret = vcpu->arch.mmu->sync_page(vcpu, sp);
1910c3e5e415SLai Jiangshan 
19118d5678a7SHou Wenlong 	if (ret < 0)
1912c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
19138d5678a7SHou Wenlong 	return ret;
1914c50d8ae3SPaolo Bonzini }
1915c50d8ae3SPaolo Bonzini 
1916c50d8ae3SPaolo Bonzini static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1917c50d8ae3SPaolo Bonzini 					struct list_head *invalid_list,
1918c50d8ae3SPaolo Bonzini 					bool remote_flush)
1919c50d8ae3SPaolo Bonzini {
1920c50d8ae3SPaolo Bonzini 	if (!remote_flush && list_empty(invalid_list))
1921c50d8ae3SPaolo Bonzini 		return false;
1922c50d8ae3SPaolo Bonzini 
1923c50d8ae3SPaolo Bonzini 	if (!list_empty(invalid_list))
1924c50d8ae3SPaolo Bonzini 		kvm_mmu_commit_zap_page(kvm, invalid_list);
1925c50d8ae3SPaolo Bonzini 	else
1926c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
1927c50d8ae3SPaolo Bonzini 	return true;
1928c50d8ae3SPaolo Bonzini }
1929c50d8ae3SPaolo Bonzini 
1930c50d8ae3SPaolo Bonzini static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
1931c50d8ae3SPaolo Bonzini {
1932a955cad8SSean Christopherson 	if (sp->role.invalid)
1933a955cad8SSean Christopherson 		return true;
1934a955cad8SSean Christopherson 
1935fa3e4203SMiaohe Lin 	/* TDP MMU pages do not use the MMU generation. */
1936de0322f5SSean Christopherson 	return !is_tdp_mmu_page(sp) &&
1937c50d8ae3SPaolo Bonzini 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
1938c50d8ae3SPaolo Bonzini }
1939c50d8ae3SPaolo Bonzini 
1940c50d8ae3SPaolo Bonzini struct mmu_page_path {
1941c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
1942c50d8ae3SPaolo Bonzini 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
1943c50d8ae3SPaolo Bonzini };
1944c50d8ae3SPaolo Bonzini 
1945c50d8ae3SPaolo Bonzini #define for_each_sp(pvec, sp, parents, i)			\
1946c50d8ae3SPaolo Bonzini 		for (i = mmu_pages_first(&pvec, &parents);	\
1947c50d8ae3SPaolo Bonzini 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
1948c50d8ae3SPaolo Bonzini 			i = mmu_pages_next(&pvec, &parents, i))
1949c50d8ae3SPaolo Bonzini 
1950c50d8ae3SPaolo Bonzini static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1951c50d8ae3SPaolo Bonzini 			  struct mmu_page_path *parents,
1952c50d8ae3SPaolo Bonzini 			  int i)
1953c50d8ae3SPaolo Bonzini {
1954c50d8ae3SPaolo Bonzini 	int n;
1955c50d8ae3SPaolo Bonzini 
1956c50d8ae3SPaolo Bonzini 	for (n = i+1; n < pvec->nr; n++) {
1957c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp = pvec->page[n].sp;
1958c50d8ae3SPaolo Bonzini 		unsigned idx = pvec->page[n].idx;
1959c50d8ae3SPaolo Bonzini 		int level = sp->role.level;
1960c50d8ae3SPaolo Bonzini 
1961c50d8ae3SPaolo Bonzini 		parents->idx[level-1] = idx;
19623bae0459SSean Christopherson 		if (level == PG_LEVEL_4K)
1963c50d8ae3SPaolo Bonzini 			break;
1964c50d8ae3SPaolo Bonzini 
1965c50d8ae3SPaolo Bonzini 		parents->parent[level-2] = sp;
1966c50d8ae3SPaolo Bonzini 	}
1967c50d8ae3SPaolo Bonzini 
1968c50d8ae3SPaolo Bonzini 	return n;
1969c50d8ae3SPaolo Bonzini }
1970c50d8ae3SPaolo Bonzini 
1971c50d8ae3SPaolo Bonzini static int mmu_pages_first(struct kvm_mmu_pages *pvec,
1972c50d8ae3SPaolo Bonzini 			   struct mmu_page_path *parents)
1973c50d8ae3SPaolo Bonzini {
1974c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1975c50d8ae3SPaolo Bonzini 	int level;
1976c50d8ae3SPaolo Bonzini 
1977c50d8ae3SPaolo Bonzini 	if (pvec->nr == 0)
1978c50d8ae3SPaolo Bonzini 		return 0;
1979c50d8ae3SPaolo Bonzini 
1980c50d8ae3SPaolo Bonzini 	WARN_ON(pvec->page[0].idx != INVALID_INDEX);
1981c50d8ae3SPaolo Bonzini 
1982c50d8ae3SPaolo Bonzini 	sp = pvec->page[0].sp;
1983c50d8ae3SPaolo Bonzini 	level = sp->role.level;
19843bae0459SSean Christopherson 	WARN_ON(level == PG_LEVEL_4K);
1985c50d8ae3SPaolo Bonzini 
1986c50d8ae3SPaolo Bonzini 	parents->parent[level-2] = sp;
1987c50d8ae3SPaolo Bonzini 
1988c50d8ae3SPaolo Bonzini 	/* Also set up a sentinel.  Further entries in pvec are all
1989c50d8ae3SPaolo Bonzini 	 * children of sp, so this element is never overwritten.
1990c50d8ae3SPaolo Bonzini 	 */
1991c50d8ae3SPaolo Bonzini 	parents->parent[level-1] = NULL;
1992c50d8ae3SPaolo Bonzini 	return mmu_pages_next(pvec, parents, 0);
1993c50d8ae3SPaolo Bonzini }
1994c50d8ae3SPaolo Bonzini 
1995c50d8ae3SPaolo Bonzini static void mmu_pages_clear_parents(struct mmu_page_path *parents)
1996c50d8ae3SPaolo Bonzini {
1997c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1998c50d8ae3SPaolo Bonzini 	unsigned int level = 0;
1999c50d8ae3SPaolo Bonzini 
2000c50d8ae3SPaolo Bonzini 	do {
2001c50d8ae3SPaolo Bonzini 		unsigned int idx = parents->idx[level];
2002c50d8ae3SPaolo Bonzini 		sp = parents->parent[level];
2003c50d8ae3SPaolo Bonzini 		if (!sp)
2004c50d8ae3SPaolo Bonzini 			return;
2005c50d8ae3SPaolo Bonzini 
2006c50d8ae3SPaolo Bonzini 		WARN_ON(idx == INVALID_INDEX);
2007c50d8ae3SPaolo Bonzini 		clear_unsync_child_bit(sp, idx);
2008c50d8ae3SPaolo Bonzini 		level++;
2009c50d8ae3SPaolo Bonzini 	} while (!sp->unsync_children);
2010c50d8ae3SPaolo Bonzini }
2011c50d8ae3SPaolo Bonzini 
201265855ed8SLai Jiangshan static int mmu_sync_children(struct kvm_vcpu *vcpu,
201365855ed8SLai Jiangshan 			     struct kvm_mmu_page *parent, bool can_yield)
2014c50d8ae3SPaolo Bonzini {
2015c50d8ae3SPaolo Bonzini 	int i;
2016c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2017c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2018c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2019c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2020c50d8ae3SPaolo Bonzini 	bool flush = false;
2021c50d8ae3SPaolo Bonzini 
2022c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2023c50d8ae3SPaolo Bonzini 		bool protected = false;
2024c50d8ae3SPaolo Bonzini 
2025c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i)
2026cf48f9e2SDavid Matlack 			protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2027c50d8ae3SPaolo Bonzini 
2028c50d8ae3SPaolo Bonzini 		if (protected) {
20295591c069SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2030c50d8ae3SPaolo Bonzini 			flush = false;
2031c50d8ae3SPaolo Bonzini 		}
2032c50d8ae3SPaolo Bonzini 
2033c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2034479a1efcSSean Christopherson 			kvm_unlink_unsync_page(vcpu->kvm, sp);
20358d5678a7SHou Wenlong 			flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2036c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2037c50d8ae3SPaolo Bonzini 		}
2038531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2039c3e5e415SLai Jiangshan 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
204065855ed8SLai Jiangshan 			if (!can_yield) {
204165855ed8SLai Jiangshan 				kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
204265855ed8SLai Jiangshan 				return -EINTR;
204365855ed8SLai Jiangshan 			}
204465855ed8SLai Jiangshan 
2045531810caSBen Gardon 			cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2046c50d8ae3SPaolo Bonzini 			flush = false;
2047c50d8ae3SPaolo Bonzini 		}
2048c50d8ae3SPaolo Bonzini 	}
2049c50d8ae3SPaolo Bonzini 
2050c3e5e415SLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
205165855ed8SLai Jiangshan 	return 0;
2052c50d8ae3SPaolo Bonzini }
2053c50d8ae3SPaolo Bonzini 
2054c50d8ae3SPaolo Bonzini static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2055c50d8ae3SPaolo Bonzini {
2056c50d8ae3SPaolo Bonzini 	atomic_set(&sp->write_flooding_count,  0);
2057c50d8ae3SPaolo Bonzini }
2058c50d8ae3SPaolo Bonzini 
2059c50d8ae3SPaolo Bonzini static void clear_sp_write_flooding_count(u64 *spte)
2060c50d8ae3SPaolo Bonzini {
206157354682SSean Christopherson 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
2062c50d8ae3SPaolo Bonzini }
2063c50d8ae3SPaolo Bonzini 
2064cbd858b1SDavid Matlack /*
2065cbd858b1SDavid Matlack  * The vCPU is required when finding indirect shadow pages; the shadow
2066cbd858b1SDavid Matlack  * page may already exist and syncing it needs the vCPU pointer in
2067cbd858b1SDavid Matlack  * order to read guest page tables.  Direct shadow pages are never
2068cbd858b1SDavid Matlack  * unsync, thus @vcpu can be NULL if @role.direct is true.
2069cbd858b1SDavid Matlack  */
20703cc736b3SDavid Matlack static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
20713cc736b3SDavid Matlack 						     struct kvm_vcpu *vcpu,
207294c81364SDavid Matlack 						     gfn_t gfn,
207394c81364SDavid Matlack 						     struct hlist_head *sp_list,
20742e65e842SDavid Matlack 						     union kvm_mmu_page_role role)
2075c50d8ae3SPaolo Bonzini {
2076c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
20778d5678a7SHou Wenlong 	int ret;
2078c50d8ae3SPaolo Bonzini 	int collisions = 0;
2079c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2080c50d8ae3SPaolo Bonzini 
20813cc736b3SDavid Matlack 	for_each_valid_sp(kvm, sp, sp_list) {
2082c50d8ae3SPaolo Bonzini 		if (sp->gfn != gfn) {
2083c50d8ae3SPaolo Bonzini 			collisions++;
2084c50d8ae3SPaolo Bonzini 			continue;
2085c50d8ae3SPaolo Bonzini 		}
2086c50d8ae3SPaolo Bonzini 
2087ddc16abbSSean Christopherson 		if (sp->role.word != role.word) {
2088ddc16abbSSean Christopherson 			/*
2089ddc16abbSSean Christopherson 			 * If the guest is creating an upper-level page, zap
2090ddc16abbSSean Christopherson 			 * unsync pages for the same gfn.  While it's possible
2091ddc16abbSSean Christopherson 			 * the guest is using recursive page tables, in all
2092ddc16abbSSean Christopherson 			 * likelihood the guest has stopped using the unsync
2093ddc16abbSSean Christopherson 			 * page and is installing a completely unrelated page.
2094ddc16abbSSean Christopherson 			 * Unsync pages must not be left as is, because the new
2095ddc16abbSSean Christopherson 			 * upper-level page will be write-protected.
2096ddc16abbSSean Christopherson 			 */
20972e65e842SDavid Matlack 			if (role.level > PG_LEVEL_4K && sp->unsync)
20983cc736b3SDavid Matlack 				kvm_mmu_prepare_zap_page(kvm, sp,
2099ddc16abbSSean Christopherson 							 &invalid_list);
2100c50d8ae3SPaolo Bonzini 			continue;
2101ddc16abbSSean Christopherson 		}
2102c50d8ae3SPaolo Bonzini 
2103bb924ca6SDavid Matlack 		/* unsync and write-flooding only apply to indirect SPs. */
2104bb924ca6SDavid Matlack 		if (sp->role.direct)
210594c81364SDavid Matlack 			goto out;
2106fb58a9c3SSean Christopherson 
2107c50d8ae3SPaolo Bonzini 		if (sp->unsync) {
2108cbd858b1SDavid Matlack 			if (KVM_BUG_ON(!vcpu, kvm))
2109cbd858b1SDavid Matlack 				break;
2110cbd858b1SDavid Matlack 
211107dc4f35SSean Christopherson 			/*
2112479a1efcSSean Christopherson 			 * The page is good, but is stale.  kvm_sync_page does
211307dc4f35SSean Christopherson 			 * get the latest guest state, but (unlike mmu_unsync_children)
211407dc4f35SSean Christopherson 			 * it doesn't write-protect the page or mark it synchronized!
211507dc4f35SSean Christopherson 			 * This way the validity of the mapping is ensured, but the
211607dc4f35SSean Christopherson 			 * overhead of write protection is not incurred until the
211707dc4f35SSean Christopherson 			 * guest invalidates the TLB mapping.  This allows multiple
211807dc4f35SSean Christopherson 			 * SPs for a single gfn to be unsync.
211907dc4f35SSean Christopherson 			 *
212007dc4f35SSean Christopherson 			 * If the sync fails, the page is zapped.  If so, break
212107dc4f35SSean Christopherson 			 * in order to rebuild it.
2122c50d8ae3SPaolo Bonzini 			 */
21238d5678a7SHou Wenlong 			ret = kvm_sync_page(vcpu, sp, &invalid_list);
21248d5678a7SHou Wenlong 			if (ret < 0)
2125c50d8ae3SPaolo Bonzini 				break;
2126c50d8ae3SPaolo Bonzini 
2127c50d8ae3SPaolo Bonzini 			WARN_ON(!list_empty(&invalid_list));
21288d5678a7SHou Wenlong 			if (ret > 0)
21293cc736b3SDavid Matlack 				kvm_flush_remote_tlbs(kvm);
2130c50d8ae3SPaolo Bonzini 		}
2131c50d8ae3SPaolo Bonzini 
2132c50d8ae3SPaolo Bonzini 		__clear_sp_write_flooding_count(sp);
2133fb58a9c3SSean Christopherson 
2134c50d8ae3SPaolo Bonzini 		goto out;
2135c50d8ae3SPaolo Bonzini 	}
2136c50d8ae3SPaolo Bonzini 
213794c81364SDavid Matlack 	sp = NULL;
21383cc736b3SDavid Matlack 	++kvm->stat.mmu_cache_miss;
2139c50d8ae3SPaolo Bonzini 
214094c81364SDavid Matlack out:
21413cc736b3SDavid Matlack 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
214294c81364SDavid Matlack 
21433cc736b3SDavid Matlack 	if (collisions > kvm->stat.max_mmu_page_hash_collisions)
21443cc736b3SDavid Matlack 		kvm->stat.max_mmu_page_hash_collisions = collisions;
214594c81364SDavid Matlack 	return sp;
214694c81364SDavid Matlack }
214794c81364SDavid Matlack 
21482f8b1b53SDavid Matlack /* Caches used when allocating a new shadow page. */
21492f8b1b53SDavid Matlack struct shadow_page_caches {
21502f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *page_header_cache;
21512f8b1b53SDavid Matlack 	struct kvm_mmu_memory_cache *shadow_page_cache;
21526a97575dSDavid Matlack 	struct kvm_mmu_memory_cache *shadowed_info_cache;
21532f8b1b53SDavid Matlack };
21542f8b1b53SDavid Matlack 
2155336081fbSDavid Matlack static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
21562f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
215794c81364SDavid Matlack 						      gfn_t gfn,
215894c81364SDavid Matlack 						      struct hlist_head *sp_list,
215994c81364SDavid Matlack 						      union kvm_mmu_page_role role)
216094c81364SDavid Matlack {
2161c306aec8SDavid Matlack 	struct kvm_mmu_page *sp;
2162c306aec8SDavid Matlack 
21632f8b1b53SDavid Matlack 	sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
21642f8b1b53SDavid Matlack 	sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
2165c306aec8SDavid Matlack 	if (!role.direct)
21666a97575dSDavid Matlack 		sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2167c306aec8SDavid Matlack 
2168c306aec8SDavid Matlack 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2169c306aec8SDavid Matlack 
217055c510e2SSean Christopherson 	INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2171428e9216SSean Christopherson 
2172c306aec8SDavid Matlack 	/*
2173c306aec8SDavid Matlack 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2174c306aec8SDavid Matlack 	 * depends on valid pages being added to the head of the list.  See
2175c306aec8SDavid Matlack 	 * comments in kvm_zap_obsolete_pages().
2176c306aec8SDavid Matlack 	 */
2177336081fbSDavid Matlack 	sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2178336081fbSDavid Matlack 	list_add(&sp->link, &kvm->arch.active_mmu_pages);
217943a063caSYosry Ahmed 	kvm_account_mmu_page(kvm, sp);
2180c50d8ae3SPaolo Bonzini 
2181c50d8ae3SPaolo Bonzini 	sp->gfn = gfn;
2182c50d8ae3SPaolo Bonzini 	sp->role = role;
2183ac101b7cSSean Christopherson 	hlist_add_head(&sp->hash_link, sp_list);
2184be911771SDavid Matlack 	if (sp_has_gptes(sp))
2185336081fbSDavid Matlack 		account_shadowed(kvm, sp);
2186ddc16abbSSean Christopherson 
218794c81364SDavid Matlack 	return sp;
218894c81364SDavid Matlack }
218994c81364SDavid Matlack 
2190cbd858b1SDavid Matlack /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
21913cc736b3SDavid Matlack static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
21923cc736b3SDavid Matlack 						      struct kvm_vcpu *vcpu,
21932f8b1b53SDavid Matlack 						      struct shadow_page_caches *caches,
219487654643SDavid Matlack 						      gfn_t gfn,
219594c81364SDavid Matlack 						      union kvm_mmu_page_role role)
219694c81364SDavid Matlack {
219794c81364SDavid Matlack 	struct hlist_head *sp_list;
219894c81364SDavid Matlack 	struct kvm_mmu_page *sp;
219994c81364SDavid Matlack 	bool created = false;
220094c81364SDavid Matlack 
22013cc736b3SDavid Matlack 	sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
220294c81364SDavid Matlack 
22033cc736b3SDavid Matlack 	sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
220494c81364SDavid Matlack 	if (!sp) {
220594c81364SDavid Matlack 		created = true;
22063cc736b3SDavid Matlack 		sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
220794c81364SDavid Matlack 	}
220894c81364SDavid Matlack 
220994c81364SDavid Matlack 	trace_kvm_mmu_get_page(sp, created);
2210c50d8ae3SPaolo Bonzini 	return sp;
2211c50d8ae3SPaolo Bonzini }
2212c50d8ae3SPaolo Bonzini 
22132f8b1b53SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
22142f8b1b53SDavid Matlack 						    gfn_t gfn,
22152f8b1b53SDavid Matlack 						    union kvm_mmu_page_role role)
22162f8b1b53SDavid Matlack {
22172f8b1b53SDavid Matlack 	struct shadow_page_caches caches = {
22182f8b1b53SDavid Matlack 		.page_header_cache = &vcpu->arch.mmu_page_header_cache,
22192f8b1b53SDavid Matlack 		.shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
22206a97575dSDavid Matlack 		.shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
22212f8b1b53SDavid Matlack 	};
22222f8b1b53SDavid Matlack 
22233cc736b3SDavid Matlack 	return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
22242f8b1b53SDavid Matlack }
22252f8b1b53SDavid Matlack 
222639944ab9SSean Christopherson static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
222739944ab9SSean Christopherson 						  unsigned int access)
22282e65e842SDavid Matlack {
22292e65e842SDavid Matlack 	struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
22302e65e842SDavid Matlack 	union kvm_mmu_page_role role;
22312e65e842SDavid Matlack 
22322e65e842SDavid Matlack 	role = parent_sp->role;
22332e65e842SDavid Matlack 	role.level--;
22342e65e842SDavid Matlack 	role.access = access;
22352e65e842SDavid Matlack 	role.direct = direct;
22362e65e842SDavid Matlack 	role.passthrough = 0;
22372e65e842SDavid Matlack 
22382e65e842SDavid Matlack 	/*
22392e65e842SDavid Matlack 	 * If the guest has 4-byte PTEs then that means it's using 32-bit,
22402e65e842SDavid Matlack 	 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
22412e65e842SDavid Matlack 	 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
22422e65e842SDavid Matlack 	 * shadow each guest page table with multiple shadow page tables, which
22432e65e842SDavid Matlack 	 * requires extra bookkeeping in the role.
22442e65e842SDavid Matlack 	 *
22452e65e842SDavid Matlack 	 * Specifically, to shadow the guest's page directory (which covers a
22462e65e842SDavid Matlack 	 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
22472e65e842SDavid Matlack 	 * 1GiB of the address space. @role.quadrant encodes which quarter of
22482e65e842SDavid Matlack 	 * the address space each maps.
22492e65e842SDavid Matlack 	 *
22502e65e842SDavid Matlack 	 * To shadow the guest's page tables (which each map a 4MiB region), KVM
22512e65e842SDavid Matlack 	 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
22522e65e842SDavid Matlack 	 * @role.quadrant encodes which half of the region they map.
22532e65e842SDavid Matlack 	 *
225439944ab9SSean Christopherson 	 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
225539944ab9SSean Christopherson 	 * consumes bits 29:21.  To consume bits 31:30, KVM's uses 4 shadow
225639944ab9SSean Christopherson 	 * PDPTEs; those 4 PAE page directories are pre-allocated and their
225739944ab9SSean Christopherson 	 * quadrant is assigned in mmu_alloc_root().   A 4-byte PTE consumes
225839944ab9SSean Christopherson 	 * bits 21:12, while an 8-byte PTE consumes bits 20:12.  To consume
225939944ab9SSean Christopherson 	 * bit 21 in the PTE (the child here), KVM propagates that bit to the
226039944ab9SSean Christopherson 	 * quadrant, i.e. sets quadrant to '0' or '1'.  The parent 8-byte PDE
226139944ab9SSean Christopherson 	 * covers bit 21 (see above), thus the quadrant is calculated from the
226239944ab9SSean Christopherson 	 * _least_ significant bit of the PDE index.
22632e65e842SDavid Matlack 	 */
22642e65e842SDavid Matlack 	if (role.has_4_byte_gpte) {
22652e65e842SDavid Matlack 		WARN_ON_ONCE(role.level != PG_LEVEL_4K);
226679e48cecSSean Christopherson 		role.quadrant = spte_index(sptep) & 1;
22672e65e842SDavid Matlack 	}
22682e65e842SDavid Matlack 
22692e65e842SDavid Matlack 	return role;
22702e65e842SDavid Matlack }
22712e65e842SDavid Matlack 
22722e65e842SDavid Matlack static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
22732e65e842SDavid Matlack 						 u64 *sptep, gfn_t gfn,
22742e65e842SDavid Matlack 						 bool direct, unsigned int access)
22752e65e842SDavid Matlack {
22762e65e842SDavid Matlack 	union kvm_mmu_page_role role;
22772e65e842SDavid Matlack 
22780cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
22790cd8dc73SPaolo Bonzini 		return ERR_PTR(-EEXIST);
22800cd8dc73SPaolo Bonzini 
22812e65e842SDavid Matlack 	role = kvm_mmu_child_role(sptep, direct, access);
228287654643SDavid Matlack 	return kvm_mmu_get_shadow_page(vcpu, gfn, role);
22832e65e842SDavid Matlack }
22842e65e842SDavid Matlack 
2285c50d8ae3SPaolo Bonzini static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2286c50d8ae3SPaolo Bonzini 					struct kvm_vcpu *vcpu, hpa_t root,
2287c50d8ae3SPaolo Bonzini 					u64 addr)
2288c50d8ae3SPaolo Bonzini {
2289c50d8ae3SPaolo Bonzini 	iterator->addr = addr;
2290c50d8ae3SPaolo Bonzini 	iterator->shadow_addr = root;
2291a972e29cSPaolo Bonzini 	iterator->level = vcpu->arch.mmu->root_role.level;
2292c50d8ae3SPaolo Bonzini 
229312ec33a7SLai Jiangshan 	if (iterator->level >= PT64_ROOT_4LEVEL &&
22944d25502aSPaolo Bonzini 	    vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2295347a0d0dSPaolo Bonzini 	    !vcpu->arch.mmu->root_role.direct)
229612ec33a7SLai Jiangshan 		iterator->level = PT32E_ROOT_LEVEL;
2297c50d8ae3SPaolo Bonzini 
2298c50d8ae3SPaolo Bonzini 	if (iterator->level == PT32E_ROOT_LEVEL) {
2299c50d8ae3SPaolo Bonzini 		/*
2300c50d8ae3SPaolo Bonzini 		 * prev_root is currently only used for 64-bit hosts. So only
2301c50d8ae3SPaolo Bonzini 		 * the active root_hpa is valid here.
2302c50d8ae3SPaolo Bonzini 		 */
2303b9e5603cSPaolo Bonzini 		BUG_ON(root != vcpu->arch.mmu->root.hpa);
2304c50d8ae3SPaolo Bonzini 
2305c50d8ae3SPaolo Bonzini 		iterator->shadow_addr
2306c50d8ae3SPaolo Bonzini 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
23072ca3129eSSean Christopherson 		iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2308c50d8ae3SPaolo Bonzini 		--iterator->level;
2309c50d8ae3SPaolo Bonzini 		if (!iterator->shadow_addr)
2310c50d8ae3SPaolo Bonzini 			iterator->level = 0;
2311c50d8ae3SPaolo Bonzini 	}
2312c50d8ae3SPaolo Bonzini }
2313c50d8ae3SPaolo Bonzini 
2314c50d8ae3SPaolo Bonzini static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2315c50d8ae3SPaolo Bonzini 			     struct kvm_vcpu *vcpu, u64 addr)
2316c50d8ae3SPaolo Bonzini {
2317b9e5603cSPaolo Bonzini 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2318c50d8ae3SPaolo Bonzini 				    addr);
2319c50d8ae3SPaolo Bonzini }
2320c50d8ae3SPaolo Bonzini 
2321c50d8ae3SPaolo Bonzini static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2322c50d8ae3SPaolo Bonzini {
23233bae0459SSean Christopherson 	if (iterator->level < PG_LEVEL_4K)
2324c50d8ae3SPaolo Bonzini 		return false;
2325c50d8ae3SPaolo Bonzini 
23262ca3129eSSean Christopherson 	iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2327c50d8ae3SPaolo Bonzini 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2328c50d8ae3SPaolo Bonzini 	return true;
2329c50d8ae3SPaolo Bonzini }
2330c50d8ae3SPaolo Bonzini 
2331c50d8ae3SPaolo Bonzini static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2332c50d8ae3SPaolo Bonzini 			       u64 spte)
2333c50d8ae3SPaolo Bonzini {
23343e44dce4SLai Jiangshan 	if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2335c50d8ae3SPaolo Bonzini 		iterator->level = 0;
2336c50d8ae3SPaolo Bonzini 		return;
2337c50d8ae3SPaolo Bonzini 	}
2338c50d8ae3SPaolo Bonzini 
23392ca3129eSSean Christopherson 	iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2340c50d8ae3SPaolo Bonzini 	--iterator->level;
2341c50d8ae3SPaolo Bonzini }
2342c50d8ae3SPaolo Bonzini 
2343c50d8ae3SPaolo Bonzini static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2344c50d8ae3SPaolo Bonzini {
2345c50d8ae3SPaolo Bonzini 	__shadow_walk_next(iterator, *iterator->sptep);
2346c50d8ae3SPaolo Bonzini }
2347c50d8ae3SPaolo Bonzini 
23480cd8dc73SPaolo Bonzini static void __link_shadow_page(struct kvm *kvm,
23490cd8dc73SPaolo Bonzini 			       struct kvm_mmu_memory_cache *cache, u64 *sptep,
235003787394SPaolo Bonzini 			       struct kvm_mmu_page *sp, bool flush)
2351c50d8ae3SPaolo Bonzini {
2352c50d8ae3SPaolo Bonzini 	u64 spte;
2353c50d8ae3SPaolo Bonzini 
2354c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2355c50d8ae3SPaolo Bonzini 
23560cd8dc73SPaolo Bonzini 	/*
23570cd8dc73SPaolo Bonzini 	 * If an SPTE is present already, it must be a leaf and therefore
235803787394SPaolo Bonzini 	 * a large one.  Drop it, and flush the TLB if needed, before
235903787394SPaolo Bonzini 	 * installing sp.
23600cd8dc73SPaolo Bonzini 	 */
23610cd8dc73SPaolo Bonzini 	if (is_shadow_present_pte(*sptep))
236203787394SPaolo Bonzini 		drop_large_spte(kvm, sptep, flush);
23630cd8dc73SPaolo Bonzini 
2364cc4674d0SBen Gardon 	spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2365c50d8ae3SPaolo Bonzini 
2366c50d8ae3SPaolo Bonzini 	mmu_spte_set(sptep, spte);
2367c50d8ae3SPaolo Bonzini 
23682ff9039aSDavid Matlack 	mmu_page_add_parent_pte(cache, sp, sptep);
2369c50d8ae3SPaolo Bonzini 
2370c4a48868SLai Jiangshan 	/*
2371c4a48868SLai Jiangshan 	 * The non-direct sub-pagetable must be updated before linking.  For
2372c4a48868SLai Jiangshan 	 * L1 sp, the pagetable is updated via kvm_sync_page() in
2373c4a48868SLai Jiangshan 	 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2374c4a48868SLai Jiangshan 	 * so sp->unsync can be true or false.  For higher level non-direct
2375c4a48868SLai Jiangshan 	 * sp, the pagetable is updated/synced via mmu_sync_children() in
2376c4a48868SLai Jiangshan 	 * FNAME(fetch)(), so sp->unsync_children can only be false.
2377c4a48868SLai Jiangshan 	 * WARN_ON_ONCE() if anything happens unexpectedly.
2378c4a48868SLai Jiangshan 	 */
2379c4a48868SLai Jiangshan 	if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2380c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
2381c50d8ae3SPaolo Bonzini }
2382c50d8ae3SPaolo Bonzini 
23832ff9039aSDavid Matlack static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
23842ff9039aSDavid Matlack 			     struct kvm_mmu_page *sp)
23852ff9039aSDavid Matlack {
238603787394SPaolo Bonzini 	__link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
23872ff9039aSDavid Matlack }
23882ff9039aSDavid Matlack 
2389c50d8ae3SPaolo Bonzini static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2390c50d8ae3SPaolo Bonzini 				   unsigned direct_access)
2391c50d8ae3SPaolo Bonzini {
2392c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2393c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
2394c50d8ae3SPaolo Bonzini 
2395c50d8ae3SPaolo Bonzini 		/*
2396c50d8ae3SPaolo Bonzini 		 * For the direct sp, if the guest pte's dirty bit
2397c50d8ae3SPaolo Bonzini 		 * changed form clean to dirty, it will corrupt the
2398c50d8ae3SPaolo Bonzini 		 * sp's access: allow writable in the read-only sp,
2399c50d8ae3SPaolo Bonzini 		 * so we should update the spte at this point to get
2400c50d8ae3SPaolo Bonzini 		 * a new sp with the correct access.
2401c50d8ae3SPaolo Bonzini 		 */
24025e3edd7eSSean Christopherson 		child = spte_to_child_sp(*sptep);
2403c50d8ae3SPaolo Bonzini 		if (child->role.access == direct_access)
2404c50d8ae3SPaolo Bonzini 			return;
2405c50d8ae3SPaolo Bonzini 
2406c50d8ae3SPaolo Bonzini 		drop_parent_pte(child, sptep);
2407c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2408c50d8ae3SPaolo Bonzini 	}
2409c50d8ae3SPaolo Bonzini }
2410c50d8ae3SPaolo Bonzini 
24112de4085cSBen Gardon /* Returns the number of zapped non-leaf child shadow pages. */
24122de4085cSBen Gardon static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
24132de4085cSBen Gardon 			    u64 *spte, struct list_head *invalid_list)
2414c50d8ae3SPaolo Bonzini {
2415c50d8ae3SPaolo Bonzini 	u64 pte;
2416c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *child;
2417c50d8ae3SPaolo Bonzini 
2418c50d8ae3SPaolo Bonzini 	pte = *spte;
2419c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(pte)) {
2420c50d8ae3SPaolo Bonzini 		if (is_last_spte(pte, sp->role.level)) {
2421c50d8ae3SPaolo Bonzini 			drop_spte(kvm, spte);
2422c50d8ae3SPaolo Bonzini 		} else {
24235e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2424c50d8ae3SPaolo Bonzini 			drop_parent_pte(child, spte);
24252de4085cSBen Gardon 
24262de4085cSBen Gardon 			/*
24272de4085cSBen Gardon 			 * Recursively zap nested TDP SPs, parentless SPs are
24282de4085cSBen Gardon 			 * unlikely to be used again in the near future.  This
24292de4085cSBen Gardon 			 * avoids retaining a large number of stale nested SPs.
24302de4085cSBen Gardon 			 */
24312de4085cSBen Gardon 			if (tdp_enabled && invalid_list &&
24322de4085cSBen Gardon 			    child->role.guest_mode && !child->parent_ptes.val)
24332de4085cSBen Gardon 				return kvm_mmu_prepare_zap_page(kvm, child,
24342de4085cSBen Gardon 								invalid_list);
2435c50d8ae3SPaolo Bonzini 		}
2436ace569e0SSean Christopherson 	} else if (is_mmio_spte(pte)) {
2437c50d8ae3SPaolo Bonzini 		mmu_spte_clear_no_track(spte);
2438ace569e0SSean Christopherson 	}
24392de4085cSBen Gardon 	return 0;
2440c50d8ae3SPaolo Bonzini }
2441c50d8ae3SPaolo Bonzini 
24422de4085cSBen Gardon static int kvm_mmu_page_unlink_children(struct kvm *kvm,
24432de4085cSBen Gardon 					struct kvm_mmu_page *sp,
24442de4085cSBen Gardon 					struct list_head *invalid_list)
2445c50d8ae3SPaolo Bonzini {
24462de4085cSBen Gardon 	int zapped = 0;
2447c50d8ae3SPaolo Bonzini 	unsigned i;
2448c50d8ae3SPaolo Bonzini 
24492ca3129eSSean Christopherson 	for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
24502de4085cSBen Gardon 		zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
24512de4085cSBen Gardon 
24522de4085cSBen Gardon 	return zapped;
2453c50d8ae3SPaolo Bonzini }
2454c50d8ae3SPaolo Bonzini 
245561827671SJinrong Liang static void kvm_mmu_unlink_parents(struct kvm_mmu_page *sp)
2456c50d8ae3SPaolo Bonzini {
2457c50d8ae3SPaolo Bonzini 	u64 *sptep;
2458c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
2459c50d8ae3SPaolo Bonzini 
2460c50d8ae3SPaolo Bonzini 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2461c50d8ae3SPaolo Bonzini 		drop_parent_pte(sp, sptep);
2462c50d8ae3SPaolo Bonzini }
2463c50d8ae3SPaolo Bonzini 
2464c50d8ae3SPaolo Bonzini static int mmu_zap_unsync_children(struct kvm *kvm,
2465c50d8ae3SPaolo Bonzini 				   struct kvm_mmu_page *parent,
2466c50d8ae3SPaolo Bonzini 				   struct list_head *invalid_list)
2467c50d8ae3SPaolo Bonzini {
2468c50d8ae3SPaolo Bonzini 	int i, zapped = 0;
2469c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2470c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2471c50d8ae3SPaolo Bonzini 
24723bae0459SSean Christopherson 	if (parent->role.level == PG_LEVEL_4K)
2473c50d8ae3SPaolo Bonzini 		return 0;
2474c50d8ae3SPaolo Bonzini 
2475c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2476c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
2477c50d8ae3SPaolo Bonzini 
2478c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2479c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2480c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2481c50d8ae3SPaolo Bonzini 			zapped++;
2482c50d8ae3SPaolo Bonzini 		}
2483c50d8ae3SPaolo Bonzini 	}
2484c50d8ae3SPaolo Bonzini 
2485c50d8ae3SPaolo Bonzini 	return zapped;
2486c50d8ae3SPaolo Bonzini }
2487c50d8ae3SPaolo Bonzini 
2488c50d8ae3SPaolo Bonzini static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2489c50d8ae3SPaolo Bonzini 				       struct kvm_mmu_page *sp,
2490c50d8ae3SPaolo Bonzini 				       struct list_head *invalid_list,
2491c50d8ae3SPaolo Bonzini 				       int *nr_zapped)
2492c50d8ae3SPaolo Bonzini {
2493527d5cd7SSean Christopherson 	bool list_unstable, zapped_root = false;
2494c50d8ae3SPaolo Bonzini 
2495c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_prepare_zap_page(sp);
2496c50d8ae3SPaolo Bonzini 	++kvm->stat.mmu_shadow_zapped;
2497c50d8ae3SPaolo Bonzini 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
24982de4085cSBen Gardon 	*nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
249961827671SJinrong Liang 	kvm_mmu_unlink_parents(sp);
2500c50d8ae3SPaolo Bonzini 
2501c50d8ae3SPaolo Bonzini 	/* Zapping children means active_mmu_pages has become unstable. */
2502c50d8ae3SPaolo Bonzini 	list_unstable = *nr_zapped;
2503c50d8ae3SPaolo Bonzini 
2504767d8d8dSLai Jiangshan 	if (!sp->role.invalid && sp_has_gptes(sp))
2505c50d8ae3SPaolo Bonzini 		unaccount_shadowed(kvm, sp);
2506c50d8ae3SPaolo Bonzini 
2507c50d8ae3SPaolo Bonzini 	if (sp->unsync)
2508c50d8ae3SPaolo Bonzini 		kvm_unlink_unsync_page(kvm, sp);
2509c50d8ae3SPaolo Bonzini 	if (!sp->root_count) {
2510c50d8ae3SPaolo Bonzini 		/* Count self */
2511c50d8ae3SPaolo Bonzini 		(*nr_zapped)++;
2512f95eec9bSSean Christopherson 
2513f95eec9bSSean Christopherson 		/*
2514f95eec9bSSean Christopherson 		 * Already invalid pages (previously active roots) are not on
2515f95eec9bSSean Christopherson 		 * the active page list.  See list_del() in the "else" case of
2516f95eec9bSSean Christopherson 		 * !sp->root_count.
2517f95eec9bSSean Christopherson 		 */
2518f95eec9bSSean Christopherson 		if (sp->role.invalid)
2519f95eec9bSSean Christopherson 			list_add(&sp->link, invalid_list);
2520f95eec9bSSean Christopherson 		else
2521c50d8ae3SPaolo Bonzini 			list_move(&sp->link, invalid_list);
252243a063caSYosry Ahmed 		kvm_unaccount_mmu_page(kvm, sp);
2523c50d8ae3SPaolo Bonzini 	} else {
2524f95eec9bSSean Christopherson 		/*
2525f95eec9bSSean Christopherson 		 * Remove the active root from the active page list, the root
2526f95eec9bSSean Christopherson 		 * will be explicitly freed when the root_count hits zero.
2527f95eec9bSSean Christopherson 		 */
2528f95eec9bSSean Christopherson 		list_del(&sp->link);
2529c50d8ae3SPaolo Bonzini 
2530c50d8ae3SPaolo Bonzini 		/*
2531c50d8ae3SPaolo Bonzini 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2532c50d8ae3SPaolo Bonzini 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2533c50d8ae3SPaolo Bonzini 		 * treats invalid shadow pages as being obsolete.
2534c50d8ae3SPaolo Bonzini 		 */
2535527d5cd7SSean Christopherson 		zapped_root = !is_obsolete_sp(kvm, sp);
2536c50d8ae3SPaolo Bonzini 	}
2537c50d8ae3SPaolo Bonzini 
253855c510e2SSean Christopherson 	if (sp->nx_huge_page_disallowed)
253955c510e2SSean Christopherson 		unaccount_nx_huge_page(kvm, sp);
2540c50d8ae3SPaolo Bonzini 
2541c50d8ae3SPaolo Bonzini 	sp->role.invalid = 1;
2542527d5cd7SSean Christopherson 
2543527d5cd7SSean Christopherson 	/*
2544527d5cd7SSean Christopherson 	 * Make the request to free obsolete roots after marking the root
2545527d5cd7SSean Christopherson 	 * invalid, otherwise other vCPUs may not see it as invalid.
2546527d5cd7SSean Christopherson 	 */
2547527d5cd7SSean Christopherson 	if (zapped_root)
2548527d5cd7SSean Christopherson 		kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2549c50d8ae3SPaolo Bonzini 	return list_unstable;
2550c50d8ae3SPaolo Bonzini }
2551c50d8ae3SPaolo Bonzini 
2552c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2553c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list)
2554c50d8ae3SPaolo Bonzini {
2555c50d8ae3SPaolo Bonzini 	int nr_zapped;
2556c50d8ae3SPaolo Bonzini 
2557c50d8ae3SPaolo Bonzini 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2558c50d8ae3SPaolo Bonzini 	return nr_zapped;
2559c50d8ae3SPaolo Bonzini }
2560c50d8ae3SPaolo Bonzini 
2561c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2562c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list)
2563c50d8ae3SPaolo Bonzini {
2564c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *nsp;
2565c50d8ae3SPaolo Bonzini 
2566c50d8ae3SPaolo Bonzini 	if (list_empty(invalid_list))
2567c50d8ae3SPaolo Bonzini 		return;
2568c50d8ae3SPaolo Bonzini 
2569c50d8ae3SPaolo Bonzini 	/*
2570c50d8ae3SPaolo Bonzini 	 * We need to make sure everyone sees our modifications to
2571c50d8ae3SPaolo Bonzini 	 * the page tables and see changes to vcpu->mode here. The barrier
2572c50d8ae3SPaolo Bonzini 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2573c50d8ae3SPaolo Bonzini 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2574c50d8ae3SPaolo Bonzini 	 *
2575c50d8ae3SPaolo Bonzini 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2576c50d8ae3SPaolo Bonzini 	 * guest mode and/or lockless shadow page table walks.
2577c50d8ae3SPaolo Bonzini 	 */
2578c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs(kvm);
2579c50d8ae3SPaolo Bonzini 
2580c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2581c50d8ae3SPaolo Bonzini 		WARN_ON(!sp->role.invalid || sp->root_count);
258287654643SDavid Matlack 		kvm_mmu_free_shadow_page(sp);
2583c50d8ae3SPaolo Bonzini 	}
2584c50d8ae3SPaolo Bonzini }
2585c50d8ae3SPaolo Bonzini 
25866b82ef2cSSean Christopherson static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
25876b82ef2cSSean Christopherson 						  unsigned long nr_to_zap)
2588c50d8ae3SPaolo Bonzini {
25896b82ef2cSSean Christopherson 	unsigned long total_zapped = 0;
25906b82ef2cSSean Christopherson 	struct kvm_mmu_page *sp, *tmp;
2591ba7888ddSSean Christopherson 	LIST_HEAD(invalid_list);
25926b82ef2cSSean Christopherson 	bool unstable;
25936b82ef2cSSean Christopherson 	int nr_zapped;
2594c50d8ae3SPaolo Bonzini 
2595c50d8ae3SPaolo Bonzini 	if (list_empty(&kvm->arch.active_mmu_pages))
2596ba7888ddSSean Christopherson 		return 0;
2597c50d8ae3SPaolo Bonzini 
25986b82ef2cSSean Christopherson restart:
25998fc51726SSean Christopherson 	list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
26006b82ef2cSSean Christopherson 		/*
26016b82ef2cSSean Christopherson 		 * Don't zap active root pages, the page itself can't be freed
26026b82ef2cSSean Christopherson 		 * and zapping it will just force vCPUs to realloc and reload.
26036b82ef2cSSean Christopherson 		 */
26046b82ef2cSSean Christopherson 		if (sp->root_count)
26056b82ef2cSSean Christopherson 			continue;
26066b82ef2cSSean Christopherson 
26076b82ef2cSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
26086b82ef2cSSean Christopherson 						      &nr_zapped);
26096b82ef2cSSean Christopherson 		total_zapped += nr_zapped;
26106b82ef2cSSean Christopherson 		if (total_zapped >= nr_to_zap)
2611ba7888ddSSean Christopherson 			break;
2612ba7888ddSSean Christopherson 
26136b82ef2cSSean Christopherson 		if (unstable)
26146b82ef2cSSean Christopherson 			goto restart;
2615ba7888ddSSean Christopherson 	}
26166b82ef2cSSean Christopherson 
26176b82ef2cSSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
26186b82ef2cSSean Christopherson 
26196b82ef2cSSean Christopherson 	kvm->stat.mmu_recycled += total_zapped;
26206b82ef2cSSean Christopherson 	return total_zapped;
26216b82ef2cSSean Christopherson }
26226b82ef2cSSean Christopherson 
2623afe8d7e6SSean Christopherson static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2624afe8d7e6SSean Christopherson {
2625afe8d7e6SSean Christopherson 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2626afe8d7e6SSean Christopherson 		return kvm->arch.n_max_mmu_pages -
2627afe8d7e6SSean Christopherson 			kvm->arch.n_used_mmu_pages;
2628afe8d7e6SSean Christopherson 
2629afe8d7e6SSean Christopherson 	return 0;
2630c50d8ae3SPaolo Bonzini }
2631c50d8ae3SPaolo Bonzini 
2632ba7888ddSSean Christopherson static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2633ba7888ddSSean Christopherson {
26346b82ef2cSSean Christopherson 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2635ba7888ddSSean Christopherson 
26366b82ef2cSSean Christopherson 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2637ba7888ddSSean Christopherson 		return 0;
2638ba7888ddSSean Christopherson 
26396b82ef2cSSean Christopherson 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2640ba7888ddSSean Christopherson 
26416e6ec584SSean Christopherson 	/*
26426e6ec584SSean Christopherson 	 * Note, this check is intentionally soft, it only guarantees that one
26436e6ec584SSean Christopherson 	 * page is available, while the caller may end up allocating as many as
26446e6ec584SSean Christopherson 	 * four pages, e.g. for PAE roots or for 5-level paging.  Temporarily
26456e6ec584SSean Christopherson 	 * exceeding the (arbitrary by default) limit will not harm the host,
2646c4342633SIngo Molnar 	 * being too aggressive may unnecessarily kill the guest, and getting an
26476e6ec584SSean Christopherson 	 * exact count is far more trouble than it's worth, especially in the
26486e6ec584SSean Christopherson 	 * page fault paths.
26496e6ec584SSean Christopherson 	 */
2650ba7888ddSSean Christopherson 	if (!kvm_mmu_available_pages(vcpu->kvm))
2651ba7888ddSSean Christopherson 		return -ENOSPC;
2652ba7888ddSSean Christopherson 	return 0;
2653ba7888ddSSean Christopherson }
2654ba7888ddSSean Christopherson 
2655c50d8ae3SPaolo Bonzini /*
2656c50d8ae3SPaolo Bonzini  * Changing the number of mmu pages allocated to the vm
2657c50d8ae3SPaolo Bonzini  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2658c50d8ae3SPaolo Bonzini  */
2659c50d8ae3SPaolo Bonzini void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2660c50d8ae3SPaolo Bonzini {
2661531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2662c50d8ae3SPaolo Bonzini 
2663c50d8ae3SPaolo Bonzini 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
26646b82ef2cSSean Christopherson 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
26656b82ef2cSSean Christopherson 						  goal_nr_mmu_pages);
2666c50d8ae3SPaolo Bonzini 
2667c50d8ae3SPaolo Bonzini 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2668c50d8ae3SPaolo Bonzini 	}
2669c50d8ae3SPaolo Bonzini 
2670c50d8ae3SPaolo Bonzini 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2671c50d8ae3SPaolo Bonzini 
2672531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2673c50d8ae3SPaolo Bonzini }
2674c50d8ae3SPaolo Bonzini 
2675c50d8ae3SPaolo Bonzini int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2676c50d8ae3SPaolo Bonzini {
2677c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2678c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2679c50d8ae3SPaolo Bonzini 	int r;
2680c50d8ae3SPaolo Bonzini 
2681c50d8ae3SPaolo Bonzini 	pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2682c50d8ae3SPaolo Bonzini 	r = 0;
2683531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2684767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2685c50d8ae3SPaolo Bonzini 		pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2686c50d8ae3SPaolo Bonzini 			 sp->role.word);
2687c50d8ae3SPaolo Bonzini 		r = 1;
2688c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2689c50d8ae3SPaolo Bonzini 	}
2690c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2691531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2692c50d8ae3SPaolo Bonzini 
2693c50d8ae3SPaolo Bonzini 	return r;
2694c50d8ae3SPaolo Bonzini }
269596ad91aeSSean Christopherson 
269696ad91aeSSean Christopherson static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
269796ad91aeSSean Christopherson {
269896ad91aeSSean Christopherson 	gpa_t gpa;
269996ad91aeSSean Christopherson 	int r;
270096ad91aeSSean Christopherson 
2701347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
270296ad91aeSSean Christopherson 		return 0;
270396ad91aeSSean Christopherson 
270496ad91aeSSean Christopherson 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
270596ad91aeSSean Christopherson 
270696ad91aeSSean Christopherson 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
270796ad91aeSSean Christopherson 
270896ad91aeSSean Christopherson 	return r;
270996ad91aeSSean Christopherson }
2710c50d8ae3SPaolo Bonzini 
27114d78d0b3SBen Gardon static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2712c50d8ae3SPaolo Bonzini {
2713c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_unsync_page(sp);
27144d78d0b3SBen Gardon 	++kvm->stat.mmu_unsync;
2715c50d8ae3SPaolo Bonzini 	sp->unsync = 1;
2716c50d8ae3SPaolo Bonzini 
2717c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
2718c50d8ae3SPaolo Bonzini }
2719c50d8ae3SPaolo Bonzini 
27200337f585SSean Christopherson /*
27210337f585SSean Christopherson  * Attempt to unsync any shadow pages that can be reached by the specified gfn,
27220337f585SSean Christopherson  * KVM is creating a writable mapping for said gfn.  Returns 0 if all pages
27230337f585SSean Christopherson  * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
27240337f585SSean Christopherson  * be write-protected.
27250337f585SSean Christopherson  */
27268283e36aSBen Gardon int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
27272839180cSPaolo Bonzini 			    gfn_t gfn, bool can_unsync, bool prefetch)
2728c50d8ae3SPaolo Bonzini {
2729c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2730ce25681dSSean Christopherson 	bool locked = false;
2731c50d8ae3SPaolo Bonzini 
27320337f585SSean Christopherson 	/*
27330337f585SSean Christopherson 	 * Force write-protection if the page is being tracked.  Note, the page
27340337f585SSean Christopherson 	 * track machinery is used to write-protect upper-level shadow pages,
27350337f585SSean Christopherson 	 * i.e. this guards the role.level == 4K assertion below!
27360337f585SSean Christopherson 	 */
27374d78d0b3SBen Gardon 	if (kvm_slot_page_track_is_active(kvm, slot, gfn, KVM_PAGE_TRACK_WRITE))
27380337f585SSean Christopherson 		return -EPERM;
2739c50d8ae3SPaolo Bonzini 
27400337f585SSean Christopherson 	/*
27410337f585SSean Christopherson 	 * The page is not write-tracked, mark existing shadow pages unsync
27420337f585SSean Christopherson 	 * unless KVM is synchronizing an unsync SP (can_unsync = false).  In
27430337f585SSean Christopherson 	 * that case, KVM must complete emulation of the guest TLB flush before
27440337f585SSean Christopherson 	 * allowing shadow pages to become unsync (writable by the guest).
27450337f585SSean Christopherson 	 */
2746767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2747c50d8ae3SPaolo Bonzini 		if (!can_unsync)
27480337f585SSean Christopherson 			return -EPERM;
2749c50d8ae3SPaolo Bonzini 
2750c50d8ae3SPaolo Bonzini 		if (sp->unsync)
2751c50d8ae3SPaolo Bonzini 			continue;
2752c50d8ae3SPaolo Bonzini 
27532839180cSPaolo Bonzini 		if (prefetch)
2754f1c4a88cSLai Jiangshan 			return -EEXIST;
2755f1c4a88cSLai Jiangshan 
2756ce25681dSSean Christopherson 		/*
2757ce25681dSSean Christopherson 		 * TDP MMU page faults require an additional spinlock as they
2758ce25681dSSean Christopherson 		 * run with mmu_lock held for read, not write, and the unsync
2759ce25681dSSean Christopherson 		 * logic is not thread safe.  Take the spinklock regardless of
2760ce25681dSSean Christopherson 		 * the MMU type to avoid extra conditionals/parameters, there's
2761ce25681dSSean Christopherson 		 * no meaningful penalty if mmu_lock is held for write.
2762ce25681dSSean Christopherson 		 */
2763ce25681dSSean Christopherson 		if (!locked) {
2764ce25681dSSean Christopherson 			locked = true;
27654d78d0b3SBen Gardon 			spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2766ce25681dSSean Christopherson 
2767ce25681dSSean Christopherson 			/*
2768ce25681dSSean Christopherson 			 * Recheck after taking the spinlock, a different vCPU
2769ce25681dSSean Christopherson 			 * may have since marked the page unsync.  A false
2770ce25681dSSean Christopherson 			 * positive on the unprotected check above is not
2771ce25681dSSean Christopherson 			 * possible as clearing sp->unsync _must_ hold mmu_lock
2772ce25681dSSean Christopherson 			 * for write, i.e. unsync cannot transition from 0->1
2773ce25681dSSean Christopherson 			 * while this CPU holds mmu_lock for read (or write).
2774ce25681dSSean Christopherson 			 */
2775ce25681dSSean Christopherson 			if (READ_ONCE(sp->unsync))
2776ce25681dSSean Christopherson 				continue;
2777ce25681dSSean Christopherson 		}
2778ce25681dSSean Christopherson 
27793bae0459SSean Christopherson 		WARN_ON(sp->role.level != PG_LEVEL_4K);
27804d78d0b3SBen Gardon 		kvm_unsync_page(kvm, sp);
2781c50d8ae3SPaolo Bonzini 	}
2782ce25681dSSean Christopherson 	if (locked)
27834d78d0b3SBen Gardon 		spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2784c50d8ae3SPaolo Bonzini 
2785c50d8ae3SPaolo Bonzini 	/*
2786c50d8ae3SPaolo Bonzini 	 * We need to ensure that the marking of unsync pages is visible
2787c50d8ae3SPaolo Bonzini 	 * before the SPTE is updated to allow writes because
2788c50d8ae3SPaolo Bonzini 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2789c50d8ae3SPaolo Bonzini 	 * the MMU lock and so can race with this. If the SPTE was updated
2790c50d8ae3SPaolo Bonzini 	 * before the page had been marked as unsync-ed, something like the
2791c50d8ae3SPaolo Bonzini 	 * following could happen:
2792c50d8ae3SPaolo Bonzini 	 *
2793c50d8ae3SPaolo Bonzini 	 * CPU 1                    CPU 2
2794c50d8ae3SPaolo Bonzini 	 * ---------------------------------------------------------------------
2795c50d8ae3SPaolo Bonzini 	 * 1.2 Host updates SPTE
2796c50d8ae3SPaolo Bonzini 	 *     to be writable
2797c50d8ae3SPaolo Bonzini 	 *                      2.1 Guest writes a GPTE for GVA X.
2798c50d8ae3SPaolo Bonzini 	 *                          (GPTE being in the guest page table shadowed
2799c50d8ae3SPaolo Bonzini 	 *                           by the SP from CPU 1.)
2800c50d8ae3SPaolo Bonzini 	 *                          This reads SPTE during the page table walk.
2801c50d8ae3SPaolo Bonzini 	 *                          Since SPTE.W is read as 1, there is no
2802c50d8ae3SPaolo Bonzini 	 *                          fault.
2803c50d8ae3SPaolo Bonzini 	 *
2804c50d8ae3SPaolo Bonzini 	 *                      2.2 Guest issues TLB flush.
2805c50d8ae3SPaolo Bonzini 	 *                          That causes a VM Exit.
2806c50d8ae3SPaolo Bonzini 	 *
28070337f585SSean Christopherson 	 *                      2.3 Walking of unsync pages sees sp->unsync is
28080337f585SSean Christopherson 	 *                          false and skips the page.
2809c50d8ae3SPaolo Bonzini 	 *
2810c50d8ae3SPaolo Bonzini 	 *                      2.4 Guest accesses GVA X.
2811c50d8ae3SPaolo Bonzini 	 *                          Since the mapping in the SP was not updated,
2812c50d8ae3SPaolo Bonzini 	 *                          so the old mapping for GVA X incorrectly
2813c50d8ae3SPaolo Bonzini 	 *                          gets used.
2814c50d8ae3SPaolo Bonzini 	 * 1.1 Host marks SP
2815c50d8ae3SPaolo Bonzini 	 *     as unsync
2816c50d8ae3SPaolo Bonzini 	 *     (sp->unsync = true)
2817c50d8ae3SPaolo Bonzini 	 *
2818c50d8ae3SPaolo Bonzini 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2819264d3dc1SLai Jiangshan 	 * the situation in 2.4 does not arise.  It pairs with the read barrier
2820264d3dc1SLai Jiangshan 	 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2821c50d8ae3SPaolo Bonzini 	 */
2822c50d8ae3SPaolo Bonzini 	smp_wmb();
2823c50d8ae3SPaolo Bonzini 
28240337f585SSean Christopherson 	return 0;
2825c50d8ae3SPaolo Bonzini }
2826c50d8ae3SPaolo Bonzini 
28278a9f566aSDavid Matlack static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
28288a9f566aSDavid Matlack 			u64 *sptep, unsigned int pte_access, gfn_t gfn,
2829a12f4381SPaolo Bonzini 			kvm_pfn_t pfn, struct kvm_page_fault *fault)
2830799a4190SBen Gardon {
2831d786c778SPaolo Bonzini 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2832eb5cd7ffSPaolo Bonzini 	int level = sp->role.level;
2833c50d8ae3SPaolo Bonzini 	int was_rmapped = 0;
2834c4371c2aSSean Christopherson 	int ret = RET_PF_FIXED;
2835c50d8ae3SPaolo Bonzini 	bool flush = false;
2836ad67e480SPaolo Bonzini 	bool wrprot;
2837d786c778SPaolo Bonzini 	u64 spte;
2838c50d8ae3SPaolo Bonzini 
2839a12f4381SPaolo Bonzini 	/* Prefetching always gets a writable pfn.  */
2840a12f4381SPaolo Bonzini 	bool host_writable = !fault || fault->map_writable;
28412839180cSPaolo Bonzini 	bool prefetch = !fault || fault->prefetch;
2842a12f4381SPaolo Bonzini 	bool write_fault = fault && fault->write;
2843c50d8ae3SPaolo Bonzini 
2844c50d8ae3SPaolo Bonzini 	pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2845c50d8ae3SPaolo Bonzini 		 *sptep, write_fault, gfn);
2846c50d8ae3SPaolo Bonzini 
2847a54aa15cSSean Christopherson 	if (unlikely(is_noslot_pfn(pfn))) {
28481075d41eSSean Christopherson 		vcpu->stat.pf_mmio_spte_created++;
2849a54aa15cSSean Christopherson 		mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2850a54aa15cSSean Christopherson 		return RET_PF_EMULATE;
2851a54aa15cSSean Christopherson 	}
2852a54aa15cSSean Christopherson 
2853c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep)) {
2854c50d8ae3SPaolo Bonzini 		/*
2855c50d8ae3SPaolo Bonzini 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2856c50d8ae3SPaolo Bonzini 		 * the parent of the now unreachable PTE.
2857c50d8ae3SPaolo Bonzini 		 */
28583bae0459SSean Christopherson 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2859c50d8ae3SPaolo Bonzini 			struct kvm_mmu_page *child;
2860c50d8ae3SPaolo Bonzini 			u64 pte = *sptep;
2861c50d8ae3SPaolo Bonzini 
28625e3edd7eSSean Christopherson 			child = spte_to_child_sp(pte);
2863c50d8ae3SPaolo Bonzini 			drop_parent_pte(child, sptep);
2864c50d8ae3SPaolo Bonzini 			flush = true;
2865c50d8ae3SPaolo Bonzini 		} else if (pfn != spte_to_pfn(*sptep)) {
2866c50d8ae3SPaolo Bonzini 			pgprintk("hfn old %llx new %llx\n",
2867c50d8ae3SPaolo Bonzini 				 spte_to_pfn(*sptep), pfn);
2868c50d8ae3SPaolo Bonzini 			drop_spte(vcpu->kvm, sptep);
2869c50d8ae3SPaolo Bonzini 			flush = true;
2870c50d8ae3SPaolo Bonzini 		} else
2871c50d8ae3SPaolo Bonzini 			was_rmapped = 1;
2872c50d8ae3SPaolo Bonzini 	}
2873c50d8ae3SPaolo Bonzini 
28742839180cSPaolo Bonzini 	wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
28757158bee4SPaolo Bonzini 			   true, host_writable, &spte);
2876d786c778SPaolo Bonzini 
2877d786c778SPaolo Bonzini 	if (*sptep == spte) {
2878d786c778SPaolo Bonzini 		ret = RET_PF_SPURIOUS;
2879d786c778SPaolo Bonzini 	} else {
2880d786c778SPaolo Bonzini 		flush |= mmu_spte_update(sptep, spte);
28815959ff4aSMaxim Levitsky 		trace_kvm_mmu_set_spte(level, gfn, sptep);
2882c50d8ae3SPaolo Bonzini 	}
2883c50d8ae3SPaolo Bonzini 
2884ad67e480SPaolo Bonzini 	if (wrprot) {
2885c50d8ae3SPaolo Bonzini 		if (write_fault)
2886c50d8ae3SPaolo Bonzini 			ret = RET_PF_EMULATE;
2887c50d8ae3SPaolo Bonzini 	}
2888c50d8ae3SPaolo Bonzini 
2889d786c778SPaolo Bonzini 	if (flush)
2890c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
2891c50d8ae3SPaolo Bonzini 				KVM_PAGES_PER_HPAGE(level));
2892c50d8ae3SPaolo Bonzini 
2893c50d8ae3SPaolo Bonzini 	pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2894c50d8ae3SPaolo Bonzini 
2895c50d8ae3SPaolo Bonzini 	if (!was_rmapped) {
2896d786c778SPaolo Bonzini 		WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
28976a97575dSDavid Matlack 		rmap_add(vcpu, slot, sptep, gfn, pte_access);
28986a97575dSDavid Matlack 	} else {
28996a97575dSDavid Matlack 		/* Already rmapped but the pte_access bits may have changed. */
290079e48cecSSean Christopherson 		kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
2901c50d8ae3SPaolo Bonzini 	}
2902c50d8ae3SPaolo Bonzini 
2903c50d8ae3SPaolo Bonzini 	return ret;
2904c50d8ae3SPaolo Bonzini }
2905c50d8ae3SPaolo Bonzini 
2906c50d8ae3SPaolo Bonzini static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2907c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp,
2908c50d8ae3SPaolo Bonzini 				    u64 *start, u64 *end)
2909c50d8ae3SPaolo Bonzini {
2910c50d8ae3SPaolo Bonzini 	struct page *pages[PTE_PREFETCH_NUM];
2911c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
29120a2b64c5SBen Gardon 	unsigned int access = sp->role.access;
2913c50d8ae3SPaolo Bonzini 	int i, ret;
2914c50d8ae3SPaolo Bonzini 	gfn_t gfn;
2915c50d8ae3SPaolo Bonzini 
291679e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
2917c50d8ae3SPaolo Bonzini 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2918c50d8ae3SPaolo Bonzini 	if (!slot)
2919c50d8ae3SPaolo Bonzini 		return -1;
2920c50d8ae3SPaolo Bonzini 
2921c50d8ae3SPaolo Bonzini 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2922c50d8ae3SPaolo Bonzini 	if (ret <= 0)
2923c50d8ae3SPaolo Bonzini 		return -1;
2924c50d8ae3SPaolo Bonzini 
2925c50d8ae3SPaolo Bonzini 	for (i = 0; i < ret; i++, gfn++, start++) {
29268a9f566aSDavid Matlack 		mmu_set_spte(vcpu, slot, start, access, gfn,
2927a12f4381SPaolo Bonzini 			     page_to_pfn(pages[i]), NULL);
2928c50d8ae3SPaolo Bonzini 		put_page(pages[i]);
2929c50d8ae3SPaolo Bonzini 	}
2930c50d8ae3SPaolo Bonzini 
2931c50d8ae3SPaolo Bonzini 	return 0;
2932c50d8ae3SPaolo Bonzini }
2933c50d8ae3SPaolo Bonzini 
2934c50d8ae3SPaolo Bonzini static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2935c50d8ae3SPaolo Bonzini 				  struct kvm_mmu_page *sp, u64 *sptep)
2936c50d8ae3SPaolo Bonzini {
2937c50d8ae3SPaolo Bonzini 	u64 *spte, *start = NULL;
2938c50d8ae3SPaolo Bonzini 	int i;
2939c50d8ae3SPaolo Bonzini 
2940c50d8ae3SPaolo Bonzini 	WARN_ON(!sp->role.direct);
2941c50d8ae3SPaolo Bonzini 
294279e48cecSSean Christopherson 	i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
2943c50d8ae3SPaolo Bonzini 	spte = sp->spt + i;
2944c50d8ae3SPaolo Bonzini 
2945c50d8ae3SPaolo Bonzini 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
2946c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*spte) || spte == sptep) {
2947c50d8ae3SPaolo Bonzini 			if (!start)
2948c50d8ae3SPaolo Bonzini 				continue;
2949c50d8ae3SPaolo Bonzini 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2950c6cecc4bSSean Christopherson 				return;
2951c50d8ae3SPaolo Bonzini 			start = NULL;
2952c50d8ae3SPaolo Bonzini 		} else if (!start)
2953c50d8ae3SPaolo Bonzini 			start = spte;
2954c50d8ae3SPaolo Bonzini 	}
2955c6cecc4bSSean Christopherson 	if (start)
2956c6cecc4bSSean Christopherson 		direct_pte_prefetch_many(vcpu, sp, start, spte);
2957c50d8ae3SPaolo Bonzini }
2958c50d8ae3SPaolo Bonzini 
2959c50d8ae3SPaolo Bonzini static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2960c50d8ae3SPaolo Bonzini {
2961c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2962c50d8ae3SPaolo Bonzini 
296357354682SSean Christopherson 	sp = sptep_to_sp(sptep);
2964c50d8ae3SPaolo Bonzini 
2965c50d8ae3SPaolo Bonzini 	/*
2966c50d8ae3SPaolo Bonzini 	 * Without accessed bits, there's no way to distinguish between
2967c50d8ae3SPaolo Bonzini 	 * actually accessed translations and prefetched, so disable pte
2968c50d8ae3SPaolo Bonzini 	 * prefetch if accessed bits aren't available.
2969c50d8ae3SPaolo Bonzini 	 */
2970c50d8ae3SPaolo Bonzini 	if (sp_ad_disabled(sp))
2971c50d8ae3SPaolo Bonzini 		return;
2972c50d8ae3SPaolo Bonzini 
29733bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
2974c50d8ae3SPaolo Bonzini 		return;
2975c50d8ae3SPaolo Bonzini 
29764a42d848SDavid Stevens 	/*
29774a42d848SDavid Stevens 	 * If addresses are being invalidated, skip prefetching to avoid
29784a42d848SDavid Stevens 	 * accidentally prefetching those addresses.
29794a42d848SDavid Stevens 	 */
298020ec3ebdSChao Peng 	if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
29814a42d848SDavid Stevens 		return;
29824a42d848SDavid Stevens 
2983c50d8ae3SPaolo Bonzini 	__direct_pte_prefetch(vcpu, sp, sptep);
2984c50d8ae3SPaolo Bonzini }
2985c50d8ae3SPaolo Bonzini 
298665e3b446SSean Christopherson /*
298765e3b446SSean Christopherson  * Lookup the mapping level for @gfn in the current mm.
298865e3b446SSean Christopherson  *
298965e3b446SSean Christopherson  * WARNING!  Use of host_pfn_mapping_level() requires the caller and the end
299065e3b446SSean Christopherson  * consumer to be tied into KVM's handlers for MMU notifier events!
299165e3b446SSean Christopherson  *
299265e3b446SSean Christopherson  * There are several ways to safely use this helper:
299365e3b446SSean Christopherson  *
299420ec3ebdSChao Peng  * - Check mmu_invalidate_retry_hva() after grabbing the mapping level, before
299565e3b446SSean Christopherson  *   consuming it.  In this case, mmu_lock doesn't need to be held during the
299665e3b446SSean Christopherson  *   lookup, but it does need to be held while checking the MMU notifier.
299765e3b446SSean Christopherson  *
299865e3b446SSean Christopherson  * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
299965e3b446SSean Christopherson  *   event for the hva.  This can be done by explicit checking the MMU notifier
300065e3b446SSean Christopherson  *   or by ensuring that KVM already has a valid mapping that covers the hva.
300165e3b446SSean Christopherson  *
300265e3b446SSean Christopherson  * - Do not use the result to install new mappings, e.g. use the host mapping
300365e3b446SSean Christopherson  *   level only to decide whether or not to zap an entry.  In this case, it's
300465e3b446SSean Christopherson  *   not required to hold mmu_lock (though it's highly likely the caller will
300565e3b446SSean Christopherson  *   want to hold mmu_lock anyways, e.g. to modify SPTEs).
300665e3b446SSean Christopherson  *
300765e3b446SSean Christopherson  * Note!  The lookup can still race with modifications to host page tables, but
300865e3b446SSean Christopherson  * the above "rules" ensure KVM will not _consume_ the result of the walk if a
300965e3b446SSean Christopherson  * race with the primary MMU occurs.
301065e3b446SSean Christopherson  */
3011a8ac499bSSean Christopherson static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
30128ca6f063SBen Gardon 				  const struct kvm_memory_slot *slot)
3013db543216SSean Christopherson {
3014284dc493SSean Christopherson 	int level = PG_LEVEL_4K;
3015db543216SSean Christopherson 	unsigned long hva;
301644187235SMingwei Zhang 	unsigned long flags;
301744187235SMingwei Zhang 	pgd_t pgd;
301844187235SMingwei Zhang 	p4d_t p4d;
301944187235SMingwei Zhang 	pud_t pud;
302044187235SMingwei Zhang 	pmd_t pmd;
3021db543216SSean Christopherson 
30225d49f08cSSean Christopherson 	/*
3023293e306eSSean Christopherson 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3024293e306eSSean Christopherson 	 * is not solely for performance, it's also necessary to avoid the
3025293e306eSSean Christopherson 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
3026293e306eSSean Christopherson 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
3027293e306eSSean Christopherson 	 * page fault steps have already verified the guest isn't writing a
3028293e306eSSean Christopherson 	 * read-only memslot.
3029293e306eSSean Christopherson 	 */
3030db543216SSean Christopherson 	hva = __gfn_to_hva_memslot(slot, gfn);
3031db543216SSean Christopherson 
303244187235SMingwei Zhang 	/*
303365e3b446SSean Christopherson 	 * Disable IRQs to prevent concurrent tear down of host page tables,
303465e3b446SSean Christopherson 	 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
303565e3b446SSean Christopherson 	 * the original page table.
303644187235SMingwei Zhang 	 */
303744187235SMingwei Zhang 	local_irq_save(flags);
3038db543216SSean Christopherson 
303965e3b446SSean Christopherson 	/*
304065e3b446SSean Christopherson 	 * Read each entry once.  As above, a non-leaf entry can be promoted to
304165e3b446SSean Christopherson 	 * a huge page _during_ this walk.  Re-reading the entry could send the
304265e3b446SSean Christopherson 	 * walk into the weeks, e.g. p*d_large() returns false (sees the old
304365e3b446SSean Christopherson 	 * value) and then p*d_offset() walks into the target huge page instead
304465e3b446SSean Christopherson 	 * of the old page table (sees the new value).
304565e3b446SSean Christopherson 	 */
304644187235SMingwei Zhang 	pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
304744187235SMingwei Zhang 	if (pgd_none(pgd))
304844187235SMingwei Zhang 		goto out;
304944187235SMingwei Zhang 
305044187235SMingwei Zhang 	p4d = READ_ONCE(*p4d_offset(&pgd, hva));
305144187235SMingwei Zhang 	if (p4d_none(p4d) || !p4d_present(p4d))
305244187235SMingwei Zhang 		goto out;
305344187235SMingwei Zhang 
305444187235SMingwei Zhang 	pud = READ_ONCE(*pud_offset(&p4d, hva));
305544187235SMingwei Zhang 	if (pud_none(pud) || !pud_present(pud))
305644187235SMingwei Zhang 		goto out;
305744187235SMingwei Zhang 
305844187235SMingwei Zhang 	if (pud_large(pud)) {
305944187235SMingwei Zhang 		level = PG_LEVEL_1G;
306044187235SMingwei Zhang 		goto out;
306144187235SMingwei Zhang 	}
306244187235SMingwei Zhang 
306344187235SMingwei Zhang 	pmd = READ_ONCE(*pmd_offset(&pud, hva));
306444187235SMingwei Zhang 	if (pmd_none(pmd) || !pmd_present(pmd))
306544187235SMingwei Zhang 		goto out;
306644187235SMingwei Zhang 
306744187235SMingwei Zhang 	if (pmd_large(pmd))
306844187235SMingwei Zhang 		level = PG_LEVEL_2M;
306944187235SMingwei Zhang 
307044187235SMingwei Zhang out:
307144187235SMingwei Zhang 	local_irq_restore(flags);
3072db543216SSean Christopherson 	return level;
3073db543216SSean Christopherson }
3074db543216SSean Christopherson 
30758ca6f063SBen Gardon int kvm_mmu_max_mapping_level(struct kvm *kvm,
30768ca6f063SBen Gardon 			      const struct kvm_memory_slot *slot, gfn_t gfn,
3077a8ac499bSSean Christopherson 			      int max_level)
30781b6d9d9eSSean Christopherson {
30791b6d9d9eSSean Christopherson 	struct kvm_lpage_info *linfo;
3080ec607a56SPaolo Bonzini 	int host_level;
30811b6d9d9eSSean Christopherson 
30821b6d9d9eSSean Christopherson 	max_level = min(max_level, max_huge_page_level);
30831b6d9d9eSSean Christopherson 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
30841b6d9d9eSSean Christopherson 		linfo = lpage_info_slot(gfn, slot, max_level);
30851b6d9d9eSSean Christopherson 		if (!linfo->disallow_lpage)
30861b6d9d9eSSean Christopherson 			break;
30871b6d9d9eSSean Christopherson 	}
30881b6d9d9eSSean Christopherson 
30891b6d9d9eSSean Christopherson 	if (max_level == PG_LEVEL_4K)
30901b6d9d9eSSean Christopherson 		return PG_LEVEL_4K;
30911b6d9d9eSSean Christopherson 
3092a8ac499bSSean Christopherson 	host_level = host_pfn_mapping_level(kvm, gfn, slot);
3093ec607a56SPaolo Bonzini 	return min(host_level, max_level);
30941b6d9d9eSSean Christopherson }
30951b6d9d9eSSean Christopherson 
309673a3c659SPaolo Bonzini void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
30970885904dSSean Christopherson {
3098e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
309917eff019SSean Christopherson 	kvm_pfn_t mask;
31000885904dSSean Christopherson 
310173a3c659SPaolo Bonzini 	fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
31023cf06612SSean Christopherson 
310373a3c659SPaolo Bonzini 	if (unlikely(fault->max_level == PG_LEVEL_4K))
310473a3c659SPaolo Bonzini 		return;
310517eff019SSean Christopherson 
31065d49f08cSSean Christopherson 	if (is_error_noslot_pfn(fault->pfn))
310773a3c659SPaolo Bonzini 		return;
310817eff019SSean Christopherson 
3109e710c5f6SDavid Matlack 	if (kvm_slot_dirty_track_enabled(slot))
311073a3c659SPaolo Bonzini 		return;
3111293e306eSSean Christopherson 
31123cf06612SSean Christopherson 	/*
31133cf06612SSean Christopherson 	 * Enforce the iTLB multihit workaround after capturing the requested
31143cf06612SSean Christopherson 	 * level, which will be used to do precise, accurate accounting.
31153cf06612SSean Christopherson 	 */
311673a3c659SPaolo Bonzini 	fault->req_level = kvm_mmu_max_mapping_level(vcpu->kvm, slot,
3117a8ac499bSSean Christopherson 						     fault->gfn, fault->max_level);
311873a3c659SPaolo Bonzini 	if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
311973a3c659SPaolo Bonzini 		return;
31204cd071d1SSean Christopherson 
31210885904dSSean Christopherson 	/*
312220ec3ebdSChao Peng 	 * mmu_invalidate_retry() was successful and mmu_lock is held, so
31234cd071d1SSean Christopherson 	 * the pmd can't be split from under us.
31240885904dSSean Christopherson 	 */
312573a3c659SPaolo Bonzini 	fault->goal_level = fault->req_level;
312673a3c659SPaolo Bonzini 	mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
312773a3c659SPaolo Bonzini 	VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
312873a3c659SPaolo Bonzini 	fault->pfn &= ~mask;
31290885904dSSean Christopherson }
31300885904dSSean Christopherson 
3131536f0e6aSPaolo Bonzini void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3132c50d8ae3SPaolo Bonzini {
3133536f0e6aSPaolo Bonzini 	if (cur_level > PG_LEVEL_4K &&
3134536f0e6aSPaolo Bonzini 	    cur_level == fault->goal_level &&
3135c50d8ae3SPaolo Bonzini 	    is_shadow_present_pte(spte) &&
313676901e56SMingwei Zhang 	    !is_large_pte(spte) &&
313776901e56SMingwei Zhang 	    spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3138c50d8ae3SPaolo Bonzini 		/*
31396c882ef4SDavid Matlack 		 * A small SPTE exists for this pfn, but FNAME(fetch),
31406c882ef4SDavid Matlack 		 * direct_map(), or kvm_tdp_mmu_map() would like to create a
31416c882ef4SDavid Matlack 		 * large PTE instead: just force them to go down another level,
31426c882ef4SDavid Matlack 		 * patching back for them into pfn the next 9 bits of the
31436c882ef4SDavid Matlack 		 * address.
3144c50d8ae3SPaolo Bonzini 		 */
3145536f0e6aSPaolo Bonzini 		u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3146536f0e6aSPaolo Bonzini 				KVM_PAGES_PER_HPAGE(cur_level - 1);
3147536f0e6aSPaolo Bonzini 		fault->pfn |= fault->gfn & page_mask;
3148536f0e6aSPaolo Bonzini 		fault->goal_level--;
3149c50d8ae3SPaolo Bonzini 	}
3150c50d8ae3SPaolo Bonzini }
3151c50d8ae3SPaolo Bonzini 
31526c882ef4SDavid Matlack static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3153c50d8ae3SPaolo Bonzini {
3154c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator it;
3155c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
315673a3c659SPaolo Bonzini 	int ret;
315743b74355SPaolo Bonzini 	gfn_t base_gfn = fault->gfn;
3158c50d8ae3SPaolo Bonzini 
315973a3c659SPaolo Bonzini 	kvm_mmu_hugepage_adjust(vcpu, fault);
31604cd071d1SSean Christopherson 
3161f0066d94SPaolo Bonzini 	trace_kvm_mmu_spte_requested(fault);
316243b74355SPaolo Bonzini 	for_each_shadow_entry(vcpu, fault->addr, it) {
3163c50d8ae3SPaolo Bonzini 		/*
3164c50d8ae3SPaolo Bonzini 		 * We cannot overwrite existing page tables with an NX
3165c50d8ae3SPaolo Bonzini 		 * large page, as the leaf could be executable.
3166c50d8ae3SPaolo Bonzini 		 */
316773a3c659SPaolo Bonzini 		if (fault->nx_huge_page_workaround_enabled)
3168536f0e6aSPaolo Bonzini 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3169c50d8ae3SPaolo Bonzini 
317043b74355SPaolo Bonzini 		base_gfn = fault->gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
317173a3c659SPaolo Bonzini 		if (it.level == fault->goal_level)
3172c50d8ae3SPaolo Bonzini 			break;
3173c50d8ae3SPaolo Bonzini 
31742e65e842SDavid Matlack 		sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
31750cd8dc73SPaolo Bonzini 		if (sp == ERR_PTR(-EEXIST))
31760cd8dc73SPaolo Bonzini 			continue;
3177c50d8ae3SPaolo Bonzini 
3178c50d8ae3SPaolo Bonzini 		link_shadow_page(vcpu, it.sptep, sp);
3179b5b0977fSSean Christopherson 		if (fault->huge_page_disallowed)
318055c510e2SSean Christopherson 			account_nx_huge_page(vcpu->kvm, sp,
3181428e9216SSean Christopherson 					     fault->req_level >= it.level);
3182c50d8ae3SPaolo Bonzini 	}
3183c50d8ae3SPaolo Bonzini 
3184b1a429fbSSean Christopherson 	if (WARN_ON_ONCE(it.level != fault->goal_level))
3185b1a429fbSSean Christopherson 		return -EFAULT;
3186b1a429fbSSean Christopherson 
31878a9f566aSDavid Matlack 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3188a12f4381SPaolo Bonzini 			   base_gfn, fault->pfn, fault);
318912703759SSean Christopherson 	if (ret == RET_PF_SPURIOUS)
319012703759SSean Christopherson 		return ret;
319112703759SSean Christopherson 
3192c50d8ae3SPaolo Bonzini 	direct_pte_prefetch(vcpu, it.sptep);
3193c50d8ae3SPaolo Bonzini 	return ret;
3194c50d8ae3SPaolo Bonzini }
3195c50d8ae3SPaolo Bonzini 
3196cd08d178SDavid Matlack static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3197c50d8ae3SPaolo Bonzini {
3198cd08d178SDavid Matlack 	unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3199cd08d178SDavid Matlack 
3200cd08d178SDavid Matlack 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3201c50d8ae3SPaolo Bonzini }
3202c50d8ae3SPaolo Bonzini 
3203cd08d178SDavid Matlack static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3204c50d8ae3SPaolo Bonzini {
3205cd08d178SDavid Matlack 	if (is_sigpending_pfn(fault->pfn)) {
320676657687SPeter Xu 		kvm_handle_signal_exit(vcpu);
320776657687SPeter Xu 		return -EINTR;
320876657687SPeter Xu 	}
320976657687SPeter Xu 
3210c50d8ae3SPaolo Bonzini 	/*
3211c50d8ae3SPaolo Bonzini 	 * Do not cache the mmio info caused by writing the readonly gfn
3212c50d8ae3SPaolo Bonzini 	 * into the spte otherwise read access on readonly gfn also can
3213c50d8ae3SPaolo Bonzini 	 * caused mmio page fault and treat it as mmio access.
3214c50d8ae3SPaolo Bonzini 	 */
3215cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3216c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3217c50d8ae3SPaolo Bonzini 
3218cd08d178SDavid Matlack 	if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3219cd08d178SDavid Matlack 		kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3220c50d8ae3SPaolo Bonzini 		return RET_PF_RETRY;
3221c50d8ae3SPaolo Bonzini 	}
3222c50d8ae3SPaolo Bonzini 
3223c50d8ae3SPaolo Bonzini 	return -EFAULT;
3224c50d8ae3SPaolo Bonzini }
3225c50d8ae3SPaolo Bonzini 
3226354c908cSDavid Matlack static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3227354c908cSDavid Matlack 				   struct kvm_page_fault *fault,
32285276c616SSean Christopherson 				   unsigned int access)
3229c50d8ae3SPaolo Bonzini {
32303a13f4feSPaolo Bonzini 	gva_t gva = fault->is_tdp ? 0 : fault->addr;
32313a13f4feSPaolo Bonzini 
32323a13f4feSPaolo Bonzini 	vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3233c50d8ae3SPaolo Bonzini 			     access & shadow_mmio_access_mask);
3234354c908cSDavid Matlack 
323530ab5901SSean Christopherson 	/*
323630ab5901SSean Christopherson 	 * If MMIO caching is disabled, emulate immediately without
323730ab5901SSean Christopherson 	 * touching the shadow page tables as attempting to install an
3238354c908cSDavid Matlack 	 * MMIO SPTE will just be an expensive nop.
323930ab5901SSean Christopherson 	 */
3240354c908cSDavid Matlack 	if (unlikely(!enable_mmio_caching))
32415276c616SSean Christopherson 		return RET_PF_EMULATE;
3242354c908cSDavid Matlack 
3243354c908cSDavid Matlack 	/*
3244354c908cSDavid Matlack 	 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3245354c908cSDavid Matlack 	 * any guest that generates such gfns is running nested and is being
3246354c908cSDavid Matlack 	 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3247354c908cSDavid Matlack 	 * only if L1's MAXPHYADDR is inaccurate with respect to the
3248354c908cSDavid Matlack 	 * hardware's).
3249354c908cSDavid Matlack 	 */
3250354c908cSDavid Matlack 	if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3251354c908cSDavid Matlack 		return RET_PF_EMULATE;
3252c50d8ae3SPaolo Bonzini 
32535276c616SSean Christopherson 	return RET_PF_CONTINUE;
3254c50d8ae3SPaolo Bonzini }
3255c50d8ae3SPaolo Bonzini 
32563c8ad5a6SPaolo Bonzini static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
3257c50d8ae3SPaolo Bonzini {
3258c50d8ae3SPaolo Bonzini 	/*
32595c64aba5SSean Christopherson 	 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
32605c64aba5SSean Christopherson 	 * reach the common page fault handler if the SPTE has an invalid MMIO
32615c64aba5SSean Christopherson 	 * generation number.  Refreshing the MMIO generation needs to go down
32625c64aba5SSean Christopherson 	 * the slow path.  Note, EPT Misconfigs do NOT set the PRESENT flag!
3263c50d8ae3SPaolo Bonzini 	 */
32643c8ad5a6SPaolo Bonzini 	if (fault->rsvd)
3265c50d8ae3SPaolo Bonzini 		return false;
3266c50d8ae3SPaolo Bonzini 
3267c50d8ae3SPaolo Bonzini 	/*
3268c50d8ae3SPaolo Bonzini 	 * #PF can be fast if:
3269c50d8ae3SPaolo Bonzini 	 *
327054275f74SSean Christopherson 	 * 1. The shadow page table entry is not present and A/D bits are
327154275f74SSean Christopherson 	 *    disabled _by KVM_, which could mean that the fault is potentially
327254275f74SSean Christopherson 	 *    caused by access tracking (if enabled).  If A/D bits are enabled
327354275f74SSean Christopherson 	 *    by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
327454275f74SSean Christopherson 	 *    bits for L2 and employ access tracking, but the fast page fault
327554275f74SSean Christopherson 	 *    mechanism only supports direct MMUs.
327654275f74SSean Christopherson 	 * 2. The shadow page table entry is present, the access is a write,
327754275f74SSean Christopherson 	 *    and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
327854275f74SSean Christopherson 	 *    the fault was caused by a write-protection violation.  If the
327954275f74SSean Christopherson 	 *    SPTE is MMU-writable (determined later), the fault can be fixed
328054275f74SSean Christopherson 	 *    by setting the Writable bit, which can be done out of mmu_lock.
3281c50d8ae3SPaolo Bonzini 	 */
32825c64aba5SSean Christopherson 	if (!fault->present)
32835c64aba5SSean Christopherson 		return !kvm_ad_enabled();
32845c64aba5SSean Christopherson 
32855c64aba5SSean Christopherson 	/*
32865c64aba5SSean Christopherson 	 * Note, instruction fetches and writes are mutually exclusive, ignore
32875c64aba5SSean Christopherson 	 * the "exec" flag.
32885c64aba5SSean Christopherson 	 */
32895c64aba5SSean Christopherson 	return fault->write;
3290c50d8ae3SPaolo Bonzini }
3291c50d8ae3SPaolo Bonzini 
3292c50d8ae3SPaolo Bonzini /*
3293c50d8ae3SPaolo Bonzini  * Returns true if the SPTE was fixed successfully. Otherwise,
3294c50d8ae3SPaolo Bonzini  * someone else modified the SPTE from its original value.
3295c50d8ae3SPaolo Bonzini  */
3296c50d8ae3SPaolo Bonzini static bool
3297e710c5f6SDavid Matlack fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
3298c50d8ae3SPaolo Bonzini 			u64 *sptep, u64 old_spte, u64 new_spte)
3299c50d8ae3SPaolo Bonzini {
3300c50d8ae3SPaolo Bonzini 	/*
3301c50d8ae3SPaolo Bonzini 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3302c50d8ae3SPaolo Bonzini 	 * order to eliminate unnecessary PML logging. See comments in
3303c50d8ae3SPaolo Bonzini 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3304c50d8ae3SPaolo Bonzini 	 * enabled, so we do not do this. This might result in the same GPA
3305c50d8ae3SPaolo Bonzini 	 * to be logged in PML buffer again when the write really happens, and
3306c50d8ae3SPaolo Bonzini 	 * eventually to be called by mark_page_dirty twice. But it's also no
3307c50d8ae3SPaolo Bonzini 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3308c50d8ae3SPaolo Bonzini 	 * so non-PML cases won't be impacted.
3309c50d8ae3SPaolo Bonzini 	 *
3310c50d8ae3SPaolo Bonzini 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3311c50d8ae3SPaolo Bonzini 	 */
33122db2f46fSUros Bizjak 	if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3313c50d8ae3SPaolo Bonzini 		return false;
3314c50d8ae3SPaolo Bonzini 
3315e710c5f6SDavid Matlack 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3316e710c5f6SDavid Matlack 		mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3317c50d8ae3SPaolo Bonzini 
3318c50d8ae3SPaolo Bonzini 	return true;
3319c50d8ae3SPaolo Bonzini }
3320c50d8ae3SPaolo Bonzini 
33213c8ad5a6SPaolo Bonzini static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3322c50d8ae3SPaolo Bonzini {
33233c8ad5a6SPaolo Bonzini 	if (fault->exec)
3324c50d8ae3SPaolo Bonzini 		return is_executable_pte(spte);
3325c50d8ae3SPaolo Bonzini 
33263c8ad5a6SPaolo Bonzini 	if (fault->write)
3327c50d8ae3SPaolo Bonzini 		return is_writable_pte(spte);
3328c50d8ae3SPaolo Bonzini 
3329c50d8ae3SPaolo Bonzini 	/* Fault was on Read access */
3330c50d8ae3SPaolo Bonzini 	return spte & PT_PRESENT_MASK;
3331c50d8ae3SPaolo Bonzini }
3332c50d8ae3SPaolo Bonzini 
3333c50d8ae3SPaolo Bonzini /*
33346e8eb206SDavid Matlack  * Returns the last level spte pointer of the shadow page walk for the given
33356e8eb206SDavid Matlack  * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
33366e8eb206SDavid Matlack  * walk could be performed, returns NULL and *spte does not contain valid data.
33376e8eb206SDavid Matlack  *
33386e8eb206SDavid Matlack  * Contract:
33396e8eb206SDavid Matlack  *  - Must be called between walk_shadow_page_lockless_{begin,end}.
33406e8eb206SDavid Matlack  *  - The returned sptep must not be used after walk_shadow_page_lockless_end.
33416e8eb206SDavid Matlack  */
33426e8eb206SDavid Matlack static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
33436e8eb206SDavid Matlack {
33446e8eb206SDavid Matlack 	struct kvm_shadow_walk_iterator iterator;
33456e8eb206SDavid Matlack 	u64 old_spte;
33466e8eb206SDavid Matlack 	u64 *sptep = NULL;
33476e8eb206SDavid Matlack 
33486e8eb206SDavid Matlack 	for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
33496e8eb206SDavid Matlack 		sptep = iterator.sptep;
33506e8eb206SDavid Matlack 		*spte = old_spte;
33516e8eb206SDavid Matlack 	}
33526e8eb206SDavid Matlack 
33536e8eb206SDavid Matlack 	return sptep;
33546e8eb206SDavid Matlack }
33556e8eb206SDavid Matlack 
33566e8eb206SDavid Matlack /*
3357c4371c2aSSean Christopherson  * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3358c50d8ae3SPaolo Bonzini  */
33593c8ad5a6SPaolo Bonzini static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3360c50d8ae3SPaolo Bonzini {
3361c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3362c4371c2aSSean Christopherson 	int ret = RET_PF_INVALID;
3363c50d8ae3SPaolo Bonzini 	u64 spte = 0ull;
33646e8eb206SDavid Matlack 	u64 *sptep = NULL;
3365c50d8ae3SPaolo Bonzini 	uint retry_count = 0;
3366c50d8ae3SPaolo Bonzini 
33673c8ad5a6SPaolo Bonzini 	if (!page_fault_can_be_fast(fault))
3368c4371c2aSSean Christopherson 		return ret;
3369c50d8ae3SPaolo Bonzini 
3370c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
3371c50d8ae3SPaolo Bonzini 
3372c50d8ae3SPaolo Bonzini 	do {
3373c50d8ae3SPaolo Bonzini 		u64 new_spte;
3374c50d8ae3SPaolo Bonzini 
3375*dfe0ecc6SSean Christopherson 		if (tdp_mmu_enabled)
33763c8ad5a6SPaolo Bonzini 			sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
33776e8eb206SDavid Matlack 		else
33783c8ad5a6SPaolo Bonzini 			sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3379c50d8ae3SPaolo Bonzini 
3380ec89e643SSean Christopherson 		if (!is_shadow_present_pte(spte))
3381ec89e643SSean Christopherson 			break;
3382ec89e643SSean Christopherson 
33836e8eb206SDavid Matlack 		sp = sptep_to_sp(sptep);
3384c50d8ae3SPaolo Bonzini 		if (!is_last_spte(spte, sp->role.level))
3385c50d8ae3SPaolo Bonzini 			break;
3386c50d8ae3SPaolo Bonzini 
3387c50d8ae3SPaolo Bonzini 		/*
3388c50d8ae3SPaolo Bonzini 		 * Check whether the memory access that caused the fault would
3389c50d8ae3SPaolo Bonzini 		 * still cause it if it were to be performed right now. If not,
3390c50d8ae3SPaolo Bonzini 		 * then this is a spurious fault caused by TLB lazily flushed,
3391c50d8ae3SPaolo Bonzini 		 * or some other CPU has already fixed the PTE after the
3392c50d8ae3SPaolo Bonzini 		 * current CPU took the fault.
3393c50d8ae3SPaolo Bonzini 		 *
3394c50d8ae3SPaolo Bonzini 		 * Need not check the access of upper level table entries since
3395c50d8ae3SPaolo Bonzini 		 * they are always ACC_ALL.
3396c50d8ae3SPaolo Bonzini 		 */
33973c8ad5a6SPaolo Bonzini 		if (is_access_allowed(fault, spte)) {
3398c4371c2aSSean Christopherson 			ret = RET_PF_SPURIOUS;
3399c50d8ae3SPaolo Bonzini 			break;
3400c50d8ae3SPaolo Bonzini 		}
3401c50d8ae3SPaolo Bonzini 
3402c50d8ae3SPaolo Bonzini 		new_spte = spte;
3403c50d8ae3SPaolo Bonzini 
340454275f74SSean Christopherson 		/*
340554275f74SSean Christopherson 		 * KVM only supports fixing page faults outside of MMU lock for
340654275f74SSean Christopherson 		 * direct MMUs, nested MMUs are always indirect, and KVM always
340754275f74SSean Christopherson 		 * uses A/D bits for non-nested MMUs.  Thus, if A/D bits are
340854275f74SSean Christopherson 		 * enabled, the SPTE can't be an access-tracked SPTE.
340954275f74SSean Christopherson 		 */
341054275f74SSean Christopherson 		if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3411c50d8ae3SPaolo Bonzini 			new_spte = restore_acc_track_spte(new_spte);
3412c50d8ae3SPaolo Bonzini 
3413c50d8ae3SPaolo Bonzini 		/*
341454275f74SSean Christopherson 		 * To keep things simple, only SPTEs that are MMU-writable can
341554275f74SSean Christopherson 		 * be made fully writable outside of mmu_lock, e.g. only SPTEs
341654275f74SSean Christopherson 		 * that were write-protected for dirty-logging or access
341754275f74SSean Christopherson 		 * tracking are handled here.  Don't bother checking if the
341854275f74SSean Christopherson 		 * SPTE is writable to prioritize running with A/D bits enabled.
341954275f74SSean Christopherson 		 * The is_access_allowed() check above handles the common case
342054275f74SSean Christopherson 		 * of the fault being spurious, and the SPTE is known to be
342154275f74SSean Christopherson 		 * shadow-present, i.e. except for access tracking restoration
342254275f74SSean Christopherson 		 * making the new SPTE writable, the check is wasteful.
3423c50d8ae3SPaolo Bonzini 		 */
3424706c9c55SSean Christopherson 		if (fault->write && is_mmu_writable_spte(spte)) {
3425c50d8ae3SPaolo Bonzini 			new_spte |= PT_WRITABLE_MASK;
3426c50d8ae3SPaolo Bonzini 
3427c50d8ae3SPaolo Bonzini 			/*
342810c30de0SJunaid Shahid 			 * Do not fix write-permission on the large spte when
342910c30de0SJunaid Shahid 			 * dirty logging is enabled. Since we only dirty the
343010c30de0SJunaid Shahid 			 * first page into the dirty-bitmap in
3431c50d8ae3SPaolo Bonzini 			 * fast_pf_fix_direct_spte(), other pages are missed
3432c50d8ae3SPaolo Bonzini 			 * if its slot has dirty logging enabled.
3433c50d8ae3SPaolo Bonzini 			 *
3434c50d8ae3SPaolo Bonzini 			 * Instead, we let the slow page fault path create a
3435c50d8ae3SPaolo Bonzini 			 * normal spte to fix the access.
3436c50d8ae3SPaolo Bonzini 			 */
343710c30de0SJunaid Shahid 			if (sp->role.level > PG_LEVEL_4K &&
343810c30de0SJunaid Shahid 			    kvm_slot_dirty_track_enabled(fault->slot))
3439c50d8ae3SPaolo Bonzini 				break;
3440c50d8ae3SPaolo Bonzini 		}
3441c50d8ae3SPaolo Bonzini 
3442c50d8ae3SPaolo Bonzini 		/* Verify that the fault can be handled in the fast path */
3443c50d8ae3SPaolo Bonzini 		if (new_spte == spte ||
34443c8ad5a6SPaolo Bonzini 		    !is_access_allowed(fault, new_spte))
3445c50d8ae3SPaolo Bonzini 			break;
3446c50d8ae3SPaolo Bonzini 
3447c50d8ae3SPaolo Bonzini 		/*
3448c50d8ae3SPaolo Bonzini 		 * Currently, fast page fault only works for direct mapping
3449c50d8ae3SPaolo Bonzini 		 * since the gfn is not stable for indirect shadow page. See
34503ecad8c2SMauro Carvalho Chehab 		 * Documentation/virt/kvm/locking.rst to get more detail.
3451c50d8ae3SPaolo Bonzini 		 */
3452e710c5f6SDavid Matlack 		if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3453c4371c2aSSean Christopherson 			ret = RET_PF_FIXED;
3454c50d8ae3SPaolo Bonzini 			break;
3455c4371c2aSSean Christopherson 		}
3456c50d8ae3SPaolo Bonzini 
3457c50d8ae3SPaolo Bonzini 		if (++retry_count > 4) {
3458c50d8ae3SPaolo Bonzini 			printk_once(KERN_WARNING
3459c50d8ae3SPaolo Bonzini 				"kvm: Fast #PF retrying more than 4 times.\n");
3460c50d8ae3SPaolo Bonzini 			break;
3461c50d8ae3SPaolo Bonzini 		}
3462c50d8ae3SPaolo Bonzini 
3463c50d8ae3SPaolo Bonzini 	} while (true);
3464c50d8ae3SPaolo Bonzini 
3465f0066d94SPaolo Bonzini 	trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3466c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3467c50d8ae3SPaolo Bonzini 
34681075d41eSSean Christopherson 	if (ret != RET_PF_INVALID)
34691075d41eSSean Christopherson 		vcpu->stat.pf_fast++;
34701075d41eSSean Christopherson 
3471c4371c2aSSean Christopherson 	return ret;
3472c50d8ae3SPaolo Bonzini }
3473c50d8ae3SPaolo Bonzini 
3474c50d8ae3SPaolo Bonzini static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3475c50d8ae3SPaolo Bonzini 			       struct list_head *invalid_list)
3476c50d8ae3SPaolo Bonzini {
3477c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3478c50d8ae3SPaolo Bonzini 
3479c50d8ae3SPaolo Bonzini 	if (!VALID_PAGE(*root_hpa))
3480c50d8ae3SPaolo Bonzini 		return;
3481c50d8ae3SPaolo Bonzini 
34825e3edd7eSSean Christopherson 	/*
34835e3edd7eSSean Christopherson 	 * The "root" may be a special root, e.g. a PAE entry, treat it as a
34845e3edd7eSSean Christopherson 	 * SPTE to ensure any non-PA bits are dropped.
34855e3edd7eSSean Christopherson 	 */
34865e3edd7eSSean Christopherson 	sp = spte_to_child_sp(*root_hpa);
34879191b8f0SPaolo Bonzini 	if (WARN_ON(!sp))
34889191b8f0SPaolo Bonzini 		return;
348902c00b3aSBen Gardon 
3490897218ffSPaolo Bonzini 	if (is_tdp_mmu_page(sp))
34916103bc07SBen Gardon 		kvm_tdp_mmu_put_root(kvm, sp, false);
349276eb54e7SBen Gardon 	else if (!--sp->root_count && sp->role.invalid)
3493c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3494c50d8ae3SPaolo Bonzini 
3495c50d8ae3SPaolo Bonzini 	*root_hpa = INVALID_PAGE;
3496c50d8ae3SPaolo Bonzini }
3497c50d8ae3SPaolo Bonzini 
3498c50d8ae3SPaolo Bonzini /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
34990c1c92f1SPaolo Bonzini void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3500c50d8ae3SPaolo Bonzini 			ulong roots_to_free)
3501c50d8ae3SPaolo Bonzini {
3502c50d8ae3SPaolo Bonzini 	int i;
3503c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
3504594bef79SPaolo Bonzini 	bool free_active_root;
3505c50d8ae3SPaolo Bonzini 
3506c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3507c50d8ae3SPaolo Bonzini 
3508c50d8ae3SPaolo Bonzini 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3509594bef79SPaolo Bonzini 	free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3510594bef79SPaolo Bonzini 		&& VALID_PAGE(mmu->root.hpa);
3511594bef79SPaolo Bonzini 
3512594bef79SPaolo Bonzini 	if (!free_active_root) {
3513c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3514c50d8ae3SPaolo Bonzini 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3515c50d8ae3SPaolo Bonzini 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3516c50d8ae3SPaolo Bonzini 				break;
3517c50d8ae3SPaolo Bonzini 
3518c50d8ae3SPaolo Bonzini 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3519c50d8ae3SPaolo Bonzini 			return;
3520c50d8ae3SPaolo Bonzini 	}
3521c50d8ae3SPaolo Bonzini 
3522531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
3523c50d8ae3SPaolo Bonzini 
3524c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3525c50d8ae3SPaolo Bonzini 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
35264d710de9SSean Christopherson 			mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3527c50d8ae3SPaolo Bonzini 					   &invalid_list);
3528c50d8ae3SPaolo Bonzini 
3529c50d8ae3SPaolo Bonzini 	if (free_active_root) {
3530594bef79SPaolo Bonzini 		if (to_shadow_page(mmu->root.hpa)) {
3531b9e5603cSPaolo Bonzini 			mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
353204d45551SSean Christopherson 		} else if (mmu->pae_root) {
3533c834e5e4SSean Christopherson 			for (i = 0; i < 4; ++i) {
3534c834e5e4SSean Christopherson 				if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3535c834e5e4SSean Christopherson 					continue;
3536c834e5e4SSean Christopherson 
3537c834e5e4SSean Christopherson 				mmu_free_root_page(kvm, &mmu->pae_root[i],
3538c50d8ae3SPaolo Bonzini 						   &invalid_list);
3539c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3540c50d8ae3SPaolo Bonzini 			}
3541c50d8ae3SPaolo Bonzini 		}
3542b9e5603cSPaolo Bonzini 		mmu->root.hpa = INVALID_PAGE;
3543b9e5603cSPaolo Bonzini 		mmu->root.pgd = 0;
3544c50d8ae3SPaolo Bonzini 	}
3545c50d8ae3SPaolo Bonzini 
35464d710de9SSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
3547531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
3548c50d8ae3SPaolo Bonzini }
3549c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3550c50d8ae3SPaolo Bonzini 
35510c1c92f1SPaolo Bonzini void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
355225b62c62SSean Christopherson {
355325b62c62SSean Christopherson 	unsigned long roots_to_free = 0;
355425b62c62SSean Christopherson 	hpa_t root_hpa;
355525b62c62SSean Christopherson 	int i;
355625b62c62SSean Christopherson 
355725b62c62SSean Christopherson 	/*
355825b62c62SSean Christopherson 	 * This should not be called while L2 is active, L2 can't invalidate
355925b62c62SSean Christopherson 	 * _only_ its own roots, e.g. INVVPID unconditionally exits.
356025b62c62SSean Christopherson 	 */
35617a458f0eSPaolo Bonzini 	WARN_ON_ONCE(mmu->root_role.guest_mode);
356225b62c62SSean Christopherson 
356325b62c62SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
356425b62c62SSean Christopherson 		root_hpa = mmu->prev_roots[i].hpa;
356525b62c62SSean Christopherson 		if (!VALID_PAGE(root_hpa))
356625b62c62SSean Christopherson 			continue;
356725b62c62SSean Christopherson 
356825b62c62SSean Christopherson 		if (!to_shadow_page(root_hpa) ||
356925b62c62SSean Christopherson 			to_shadow_page(root_hpa)->role.guest_mode)
357025b62c62SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
357125b62c62SSean Christopherson 	}
357225b62c62SSean Christopherson 
35730c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, roots_to_free);
357425b62c62SSean Christopherson }
357525b62c62SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
357625b62c62SSean Christopherson 
357725b62c62SSean Christopherson 
3578c50d8ae3SPaolo Bonzini static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3579c50d8ae3SPaolo Bonzini {
3580c50d8ae3SPaolo Bonzini 	int ret = 0;
3581c50d8ae3SPaolo Bonzini 
3582995decb6SVitaly Kuznetsov 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3583c50d8ae3SPaolo Bonzini 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3584c50d8ae3SPaolo Bonzini 		ret = 1;
3585c50d8ae3SPaolo Bonzini 	}
3586c50d8ae3SPaolo Bonzini 
3587c50d8ae3SPaolo Bonzini 	return ret;
3588c50d8ae3SPaolo Bonzini }
3589c50d8ae3SPaolo Bonzini 
35902e65e842SDavid Matlack static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
359186938ab6SDavid Matlack 			    u8 level)
3592c50d8ae3SPaolo Bonzini {
35932e65e842SDavid Matlack 	union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3594c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
35958123f265SSean Christopherson 
35962e65e842SDavid Matlack 	role.level = level;
35972e65e842SDavid Matlack 	role.quadrant = quadrant;
35982e65e842SDavid Matlack 
35997f497775SDavid Matlack 	WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
36007f497775SDavid Matlack 	WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
36017f497775SDavid Matlack 
360287654643SDavid Matlack 	sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
36038123f265SSean Christopherson 	++sp->root_count;
36048123f265SSean Christopherson 
36058123f265SSean Christopherson 	return __pa(sp->spt);
36068123f265SSean Christopherson }
36078123f265SSean Christopherson 
36088123f265SSean Christopherson static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
36098123f265SSean Christopherson {
3610b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3611a972e29cSPaolo Bonzini 	u8 shadow_root_level = mmu->root_role.level;
36128123f265SSean Christopherson 	hpa_t root;
3613c50d8ae3SPaolo Bonzini 	unsigned i;
36144a38162eSPaolo Bonzini 	int r;
36154a38162eSPaolo Bonzini 
36164a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
36174a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
36184a38162eSPaolo Bonzini 	if (r < 0)
36194a38162eSPaolo Bonzini 		goto out_unlock;
3620c50d8ae3SPaolo Bonzini 
36211f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
362202c00b3aSBen Gardon 		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
3623b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
362402c00b3aSBen Gardon 	} else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
362586938ab6SDavid Matlack 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3626b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
36278123f265SSean Christopherson 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
36284a38162eSPaolo Bonzini 		if (WARN_ON_ONCE(!mmu->pae_root)) {
36294a38162eSPaolo Bonzini 			r = -EIO;
36304a38162eSPaolo Bonzini 			goto out_unlock;
36314a38162eSPaolo Bonzini 		}
363273ad1606SSean Christopherson 
3633c50d8ae3SPaolo Bonzini 		for (i = 0; i < 4; ++i) {
3634c834e5e4SSean Christopherson 			WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3635c50d8ae3SPaolo Bonzini 
36367f497775SDavid Matlack 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
36372e65e842SDavid Matlack 					      PT32_ROOT_LEVEL);
363817e368d9SSean Christopherson 			mmu->pae_root[i] = root | PT_PRESENT_MASK |
3639d2263de1SYuan Yao 					   shadow_me_value;
3640c50d8ae3SPaolo Bonzini 		}
3641b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
364273ad1606SSean Christopherson 	} else {
364373ad1606SSean Christopherson 		WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
36444a38162eSPaolo Bonzini 		r = -EIO;
36454a38162eSPaolo Bonzini 		goto out_unlock;
364673ad1606SSean Christopherson 	}
36473651c7fcSSean Christopherson 
3648b9e5603cSPaolo Bonzini 	/* root.pgd is ignored for direct MMUs. */
3649b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
36504a38162eSPaolo Bonzini out_unlock:
36514a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
36524a38162eSPaolo Bonzini 	return r;
3653c50d8ae3SPaolo Bonzini }
3654c50d8ae3SPaolo Bonzini 
36551e76a3ceSDavid Stevens static int mmu_first_shadow_root_alloc(struct kvm *kvm)
36561e76a3ceSDavid Stevens {
36571e76a3ceSDavid Stevens 	struct kvm_memslots *slots;
36581e76a3ceSDavid Stevens 	struct kvm_memory_slot *slot;
3659a54d8066SMaciej S. Szmigiero 	int r = 0, i, bkt;
36601e76a3ceSDavid Stevens 
36611e76a3ceSDavid Stevens 	/*
36621e76a3ceSDavid Stevens 	 * Check if this is the first shadow root being allocated before
36631e76a3ceSDavid Stevens 	 * taking the lock.
36641e76a3ceSDavid Stevens 	 */
36651e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
36661e76a3ceSDavid Stevens 		return 0;
36671e76a3ceSDavid Stevens 
36681e76a3ceSDavid Stevens 	mutex_lock(&kvm->slots_arch_lock);
36691e76a3ceSDavid Stevens 
36701e76a3ceSDavid Stevens 	/* Recheck, under the lock, whether this is the first shadow root. */
36711e76a3ceSDavid Stevens 	if (kvm_shadow_root_allocated(kvm))
36721e76a3ceSDavid Stevens 		goto out_unlock;
36731e76a3ceSDavid Stevens 
36741e76a3ceSDavid Stevens 	/*
36751e76a3ceSDavid Stevens 	 * Check if anything actually needs to be allocated, e.g. all metadata
36761e76a3ceSDavid Stevens 	 * will be allocated upfront if TDP is disabled.
36771e76a3ceSDavid Stevens 	 */
36781e76a3ceSDavid Stevens 	if (kvm_memslots_have_rmaps(kvm) &&
36791e76a3ceSDavid Stevens 	    kvm_page_track_write_tracking_enabled(kvm))
36801e76a3ceSDavid Stevens 		goto out_success;
36811e76a3ceSDavid Stevens 
36821e76a3ceSDavid Stevens 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
36831e76a3ceSDavid Stevens 		slots = __kvm_memslots(kvm, i);
3684a54d8066SMaciej S. Szmigiero 		kvm_for_each_memslot(slot, bkt, slots) {
36851e76a3ceSDavid Stevens 			/*
36861e76a3ceSDavid Stevens 			 * Both of these functions are no-ops if the target is
36871e76a3ceSDavid Stevens 			 * already allocated, so unconditionally calling both
36881e76a3ceSDavid Stevens 			 * is safe.  Intentionally do NOT free allocations on
36891e76a3ceSDavid Stevens 			 * failure to avoid having to track which allocations
36901e76a3ceSDavid Stevens 			 * were made now versus when the memslot was created.
36911e76a3ceSDavid Stevens 			 * The metadata is guaranteed to be freed when the slot
36921e76a3ceSDavid Stevens 			 * is freed, and will be kept/used if userspace retries
36931e76a3ceSDavid Stevens 			 * KVM_RUN instead of killing the VM.
36941e76a3ceSDavid Stevens 			 */
36951e76a3ceSDavid Stevens 			r = memslot_rmap_alloc(slot, slot->npages);
36961e76a3ceSDavid Stevens 			if (r)
36971e76a3ceSDavid Stevens 				goto out_unlock;
36981e76a3ceSDavid Stevens 			r = kvm_page_track_write_tracking_alloc(slot);
36991e76a3ceSDavid Stevens 			if (r)
37001e76a3ceSDavid Stevens 				goto out_unlock;
37011e76a3ceSDavid Stevens 		}
37021e76a3ceSDavid Stevens 	}
37031e76a3ceSDavid Stevens 
37041e76a3ceSDavid Stevens 	/*
37051e76a3ceSDavid Stevens 	 * Ensure that shadow_root_allocated becomes true strictly after
37061e76a3ceSDavid Stevens 	 * all the related pointers are set.
37071e76a3ceSDavid Stevens 	 */
37081e76a3ceSDavid Stevens out_success:
37091e76a3ceSDavid Stevens 	smp_store_release(&kvm->arch.shadow_root_allocated, true);
37101e76a3ceSDavid Stevens 
37111e76a3ceSDavid Stevens out_unlock:
37121e76a3ceSDavid Stevens 	mutex_unlock(&kvm->slots_arch_lock);
37131e76a3ceSDavid Stevens 	return r;
37141e76a3ceSDavid Stevens }
37151e76a3ceSDavid Stevens 
3716c50d8ae3SPaolo Bonzini static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3717c50d8ae3SPaolo Bonzini {
3718b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
37196e0918aeSSean Christopherson 	u64 pdptrs[4], pm_mask;
3720be01e8e2SSean Christopherson 	gfn_t root_gfn, root_pgd;
37217f497775SDavid Matlack 	int quadrant, i, r;
37228123f265SSean Christopherson 	hpa_t root;
3723c50d8ae3SPaolo Bonzini 
3724b37233c9SSean Christopherson 	root_pgd = mmu->get_guest_pgd(vcpu);
3725be01e8e2SSean Christopherson 	root_gfn = root_pgd >> PAGE_SHIFT;
3726c50d8ae3SPaolo Bonzini 
3727c50d8ae3SPaolo Bonzini 	if (mmu_check_root(vcpu, root_gfn))
3728c50d8ae3SPaolo Bonzini 		return 1;
3729c50d8ae3SPaolo Bonzini 
3730c50d8ae3SPaolo Bonzini 	/*
37314a38162eSPaolo Bonzini 	 * On SVM, reading PDPTRs might access guest memory, which might fault
37324a38162eSPaolo Bonzini 	 * and thus might sleep.  Grab the PDPTRs before acquiring mmu_lock.
37334a38162eSPaolo Bonzini 	 */
37344d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
37356e0918aeSSean Christopherson 		for (i = 0; i < 4; ++i) {
37366e0918aeSSean Christopherson 			pdptrs[i] = mmu->get_pdptr(vcpu, i);
37376e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK))
37386e0918aeSSean Christopherson 				continue;
37396e0918aeSSean Christopherson 
37406e0918aeSSean Christopherson 			if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
37416e0918aeSSean Christopherson 				return 1;
37426e0918aeSSean Christopherson 		}
37436e0918aeSSean Christopherson 	}
37446e0918aeSSean Christopherson 
37451e76a3ceSDavid Stevens 	r = mmu_first_shadow_root_alloc(vcpu->kvm);
3746d501f747SBen Gardon 	if (r)
3747d501f747SBen Gardon 		return r;
3748d501f747SBen Gardon 
37494a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
37504a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
37514a38162eSPaolo Bonzini 	if (r < 0)
37524a38162eSPaolo Bonzini 		goto out_unlock;
37534a38162eSPaolo Bonzini 
3754c50d8ae3SPaolo Bonzini 	/*
3755c50d8ae3SPaolo Bonzini 	 * Do we shadow a long mode page table? If so we need to
3756c50d8ae3SPaolo Bonzini 	 * write-protect the guests page table root.
3757c50d8ae3SPaolo Bonzini 	 */
37584d25502aSPaolo Bonzini 	if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
37598123f265SSean Christopherson 		root = mmu_alloc_root(vcpu, root_gfn, 0,
376086938ab6SDavid Matlack 				      mmu->root_role.level);
3761b9e5603cSPaolo Bonzini 		mmu->root.hpa = root;
3762be01e8e2SSean Christopherson 		goto set_root_pgd;
3763c50d8ae3SPaolo Bonzini 	}
3764c50d8ae3SPaolo Bonzini 
37654a38162eSPaolo Bonzini 	if (WARN_ON_ONCE(!mmu->pae_root)) {
37664a38162eSPaolo Bonzini 		r = -EIO;
37674a38162eSPaolo Bonzini 		goto out_unlock;
37684a38162eSPaolo Bonzini 	}
376973ad1606SSean Christopherson 
3770c50d8ae3SPaolo Bonzini 	/*
3771c50d8ae3SPaolo Bonzini 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3772c50d8ae3SPaolo Bonzini 	 * or a PAE 3-level page table. In either case we need to be aware that
3773c50d8ae3SPaolo Bonzini 	 * the shadow page table may be a PAE or a long mode page table.
3774c50d8ae3SPaolo Bonzini 	 */
3775e54f1ff2SKai Huang 	pm_mask = PT_PRESENT_MASK | shadow_me_value;
3776a972e29cSPaolo Bonzini 	if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3777c50d8ae3SPaolo Bonzini 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3778c50d8ae3SPaolo Bonzini 
377903ca4589SSean Christopherson 		if (WARN_ON_ONCE(!mmu->pml4_root)) {
37804a38162eSPaolo Bonzini 			r = -EIO;
37814a38162eSPaolo Bonzini 			goto out_unlock;
37824a38162eSPaolo Bonzini 		}
378303ca4589SSean Christopherson 		mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3784cb0f722aSWei Huang 
3785a972e29cSPaolo Bonzini 		if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3786cb0f722aSWei Huang 			if (WARN_ON_ONCE(!mmu->pml5_root)) {
3787cb0f722aSWei Huang 				r = -EIO;
3788cb0f722aSWei Huang 				goto out_unlock;
3789cb0f722aSWei Huang 			}
3790cb0f722aSWei Huang 			mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3791cb0f722aSWei Huang 		}
379204d45551SSean Christopherson 	}
379304d45551SSean Christopherson 
3794c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3795c834e5e4SSean Christopherson 		WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
37966e6ec584SSean Christopherson 
37974d25502aSPaolo Bonzini 		if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
37986e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3799c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3800c50d8ae3SPaolo Bonzini 				continue;
3801c50d8ae3SPaolo Bonzini 			}
38026e0918aeSSean Christopherson 			root_gfn = pdptrs[i] >> PAGE_SHIFT;
3803c50d8ae3SPaolo Bonzini 		}
3804c50d8ae3SPaolo Bonzini 
38057f497775SDavid Matlack 		/*
38067f497775SDavid Matlack 		 * If shadowing 32-bit non-PAE page tables, each PAE page
38077f497775SDavid Matlack 		 * directory maps one quarter of the guest's non-PAE page
38087f497775SDavid Matlack 		 * directory. Othwerise each PAE page direct shadows one guest
38097f497775SDavid Matlack 		 * PAE page directory so that quadrant should be 0.
38107f497775SDavid Matlack 		 */
38117f497775SDavid Matlack 		quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
38127f497775SDavid Matlack 
38137f497775SDavid Matlack 		root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3814b37233c9SSean Christopherson 		mmu->pae_root[i] = root | pm_mask;
3815c50d8ae3SPaolo Bonzini 	}
3816c50d8ae3SPaolo Bonzini 
3817a972e29cSPaolo Bonzini 	if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3818b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml5_root);
3819a972e29cSPaolo Bonzini 	else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3820b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pml4_root);
3821ba0a194fSSean Christopherson 	else
3822b9e5603cSPaolo Bonzini 		mmu->root.hpa = __pa(mmu->pae_root);
3823c50d8ae3SPaolo Bonzini 
3824be01e8e2SSean Christopherson set_root_pgd:
3825b9e5603cSPaolo Bonzini 	mmu->root.pgd = root_pgd;
38264a38162eSPaolo Bonzini out_unlock:
38274a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
3828c50d8ae3SPaolo Bonzini 
3829c6c937d6SLike Xu 	return r;
3830c50d8ae3SPaolo Bonzini }
3831c50d8ae3SPaolo Bonzini 
3832748e52b9SSean Christopherson static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3833c50d8ae3SPaolo Bonzini {
3834748e52b9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3835a972e29cSPaolo Bonzini 	bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3836cb0f722aSWei Huang 	u64 *pml5_root = NULL;
3837cb0f722aSWei Huang 	u64 *pml4_root = NULL;
3838cb0f722aSWei Huang 	u64 *pae_root;
3839748e52b9SSean Christopherson 
3840748e52b9SSean Christopherson 	/*
3841748e52b9SSean Christopherson 	 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3842748e52b9SSean Christopherson 	 * tables are allocated and initialized at root creation as there is no
3843748e52b9SSean Christopherson 	 * equivalent level in the guest's NPT to shadow.  Allocate the tables
3844748e52b9SSean Christopherson 	 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3845748e52b9SSean Christopherson 	 */
3846347a0d0dSPaolo Bonzini 	if (mmu->root_role.direct ||
3847347a0d0dSPaolo Bonzini 	    mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3848a972e29cSPaolo Bonzini 	    mmu->root_role.level < PT64_ROOT_4LEVEL)
3849748e52b9SSean Christopherson 		return 0;
3850748e52b9SSean Christopherson 
3851a717a780SSean Christopherson 	/*
3852a717a780SSean Christopherson 	 * NPT, the only paging mode that uses this horror, uses a fixed number
3853a717a780SSean Christopherson 	 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3854a717a780SSean Christopherson 	 * all MMus are 5-level.  Thus, this can safely require that pml5_root
3855a717a780SSean Christopherson 	 * is allocated if the other roots are valid and pml5 is needed, as any
3856a717a780SSean Christopherson 	 * prior MMU would also have required pml5.
3857a717a780SSean Christopherson 	 */
3858a717a780SSean Christopherson 	if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3859748e52b9SSean Christopherson 		return 0;
3860748e52b9SSean Christopherson 
3861748e52b9SSean Christopherson 	/*
3862748e52b9SSean Christopherson 	 * The special roots should always be allocated in concert.  Yell and
3863748e52b9SSean Christopherson 	 * bail if KVM ends up in a state where only one of the roots is valid.
3864748e52b9SSean Christopherson 	 */
3865cb0f722aSWei Huang 	if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3866a717a780SSean Christopherson 			 (need_pml5 && mmu->pml5_root)))
3867748e52b9SSean Christopherson 		return -EIO;
3868748e52b9SSean Christopherson 
38694a98623dSSean Christopherson 	/*
38704a98623dSSean Christopherson 	 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
38714a98623dSSean Christopherson 	 * doesn't need to be decrypted.
38724a98623dSSean Christopherson 	 */
3873748e52b9SSean Christopherson 	pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3874748e52b9SSean Christopherson 	if (!pae_root)
3875748e52b9SSean Christopherson 		return -ENOMEM;
3876748e52b9SSean Christopherson 
3877cb0f722aSWei Huang #ifdef CONFIG_X86_64
387803ca4589SSean Christopherson 	pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3879cb0f722aSWei Huang 	if (!pml4_root)
3880cb0f722aSWei Huang 		goto err_pml4;
3881cb0f722aSWei Huang 
3882a717a780SSean Christopherson 	if (need_pml5) {
3883cb0f722aSWei Huang 		pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3884cb0f722aSWei Huang 		if (!pml5_root)
3885cb0f722aSWei Huang 			goto err_pml5;
3886748e52b9SSean Christopherson 	}
3887cb0f722aSWei Huang #endif
3888748e52b9SSean Christopherson 
3889748e52b9SSean Christopherson 	mmu->pae_root = pae_root;
389003ca4589SSean Christopherson 	mmu->pml4_root = pml4_root;
3891cb0f722aSWei Huang 	mmu->pml5_root = pml5_root;
3892748e52b9SSean Christopherson 
3893748e52b9SSean Christopherson 	return 0;
3894cb0f722aSWei Huang 
3895cb0f722aSWei Huang #ifdef CONFIG_X86_64
3896cb0f722aSWei Huang err_pml5:
3897cb0f722aSWei Huang 	free_page((unsigned long)pml4_root);
3898cb0f722aSWei Huang err_pml4:
3899cb0f722aSWei Huang 	free_page((unsigned long)pae_root);
3900cb0f722aSWei Huang 	return -ENOMEM;
3901cb0f722aSWei Huang #endif
3902c50d8ae3SPaolo Bonzini }
3903c50d8ae3SPaolo Bonzini 
3904264d3dc1SLai Jiangshan static bool is_unsync_root(hpa_t root)
3905264d3dc1SLai Jiangshan {
3906264d3dc1SLai Jiangshan 	struct kvm_mmu_page *sp;
3907264d3dc1SLai Jiangshan 
390861b05a9fSLai Jiangshan 	if (!VALID_PAGE(root))
390961b05a9fSLai Jiangshan 		return false;
391061b05a9fSLai Jiangshan 
3911264d3dc1SLai Jiangshan 	/*
3912264d3dc1SLai Jiangshan 	 * The read barrier orders the CPU's read of SPTE.W during the page table
3913264d3dc1SLai Jiangshan 	 * walk before the reads of sp->unsync/sp->unsync_children here.
3914264d3dc1SLai Jiangshan 	 *
3915264d3dc1SLai Jiangshan 	 * Even if another CPU was marking the SP as unsync-ed simultaneously,
3916264d3dc1SLai Jiangshan 	 * any guest page table changes are not guaranteed to be visible anyway
3917264d3dc1SLai Jiangshan 	 * until this VCPU issues a TLB flush strictly after those changes are
3918264d3dc1SLai Jiangshan 	 * made.  We only need to ensure that the other CPU sets these flags
3919264d3dc1SLai Jiangshan 	 * before any actual changes to the page tables are made.  The comments
3920264d3dc1SLai Jiangshan 	 * in mmu_try_to_unsync_pages() describe what could go wrong if this
3921264d3dc1SLai Jiangshan 	 * requirement isn't satisfied.
3922264d3dc1SLai Jiangshan 	 */
3923264d3dc1SLai Jiangshan 	smp_rmb();
3924264d3dc1SLai Jiangshan 	sp = to_shadow_page(root);
39255d6a3221SSean Christopherson 
39265d6a3221SSean Christopherson 	/*
39275d6a3221SSean Christopherson 	 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
39285d6a3221SSean Christopherson 	 * PDPTEs for a given PAE root need to be synchronized individually.
39295d6a3221SSean Christopherson 	 */
39305d6a3221SSean Christopherson 	if (WARN_ON_ONCE(!sp))
39315d6a3221SSean Christopherson 		return false;
39325d6a3221SSean Christopherson 
3933264d3dc1SLai Jiangshan 	if (sp->unsync || sp->unsync_children)
3934264d3dc1SLai Jiangshan 		return true;
3935264d3dc1SLai Jiangshan 
3936264d3dc1SLai Jiangshan 	return false;
3937264d3dc1SLai Jiangshan }
3938264d3dc1SLai Jiangshan 
3939c50d8ae3SPaolo Bonzini void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3940c50d8ae3SPaolo Bonzini {
3941c50d8ae3SPaolo Bonzini 	int i;
3942c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3943c50d8ae3SPaolo Bonzini 
3944347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
3945c50d8ae3SPaolo Bonzini 		return;
3946c50d8ae3SPaolo Bonzini 
3947b9e5603cSPaolo Bonzini 	if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
3948c50d8ae3SPaolo Bonzini 		return;
3949c50d8ae3SPaolo Bonzini 
3950c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3951c50d8ae3SPaolo Bonzini 
39524d25502aSPaolo Bonzini 	if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
3953b9e5603cSPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->root.hpa;
3954e47c4aeeSSean Christopherson 		sp = to_shadow_page(root);
3955c50d8ae3SPaolo Bonzini 
3956264d3dc1SLai Jiangshan 		if (!is_unsync_root(root))
3957c50d8ae3SPaolo Bonzini 			return;
3958c50d8ae3SPaolo Bonzini 
3959531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
396065855ed8SLai Jiangshan 		mmu_sync_children(vcpu, sp, true);
3961531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
3962c50d8ae3SPaolo Bonzini 		return;
3963c50d8ae3SPaolo Bonzini 	}
3964c50d8ae3SPaolo Bonzini 
3965531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
3966c50d8ae3SPaolo Bonzini 
3967c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3968c50d8ae3SPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->pae_root[i];
3969c50d8ae3SPaolo Bonzini 
3970c834e5e4SSean Christopherson 		if (IS_VALID_PAE_ROOT(root)) {
39715e3edd7eSSean Christopherson 			sp = spte_to_child_sp(root);
397265855ed8SLai Jiangshan 			mmu_sync_children(vcpu, sp, true);
3973c50d8ae3SPaolo Bonzini 		}
3974c50d8ae3SPaolo Bonzini 	}
3975c50d8ae3SPaolo Bonzini 
3976531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
3977c50d8ae3SPaolo Bonzini }
3978c50d8ae3SPaolo Bonzini 
397961b05a9fSLai Jiangshan void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
398061b05a9fSLai Jiangshan {
398161b05a9fSLai Jiangshan 	unsigned long roots_to_free = 0;
398261b05a9fSLai Jiangshan 	int i;
398361b05a9fSLai Jiangshan 
398461b05a9fSLai Jiangshan 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
398561b05a9fSLai Jiangshan 		if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
398661b05a9fSLai Jiangshan 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
398761b05a9fSLai Jiangshan 
398861b05a9fSLai Jiangshan 	/* sync prev_roots by simply freeing them */
39890c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
399061b05a9fSLai Jiangshan }
399161b05a9fSLai Jiangshan 
39921f5a21eeSLai Jiangshan static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
39935b22bbe7SLai Jiangshan 				  gpa_t vaddr, u64 access,
3994c50d8ae3SPaolo Bonzini 				  struct x86_exception *exception)
3995c50d8ae3SPaolo Bonzini {
3996c50d8ae3SPaolo Bonzini 	if (exception)
3997c50d8ae3SPaolo Bonzini 		exception->error_code = 0;
3998c59a0f57SLai Jiangshan 	return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
3999c50d8ae3SPaolo Bonzini }
4000c50d8ae3SPaolo Bonzini 
4001c50d8ae3SPaolo Bonzini static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4002c50d8ae3SPaolo Bonzini {
4003c50d8ae3SPaolo Bonzini 	/*
4004c50d8ae3SPaolo Bonzini 	 * A nested guest cannot use the MMIO cache if it is using nested
4005c50d8ae3SPaolo Bonzini 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4006c50d8ae3SPaolo Bonzini 	 */
4007c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
4008c50d8ae3SPaolo Bonzini 		return false;
4009c50d8ae3SPaolo Bonzini 
4010c50d8ae3SPaolo Bonzini 	if (direct)
4011c50d8ae3SPaolo Bonzini 		return vcpu_match_mmio_gpa(vcpu, addr);
4012c50d8ae3SPaolo Bonzini 
4013c50d8ae3SPaolo Bonzini 	return vcpu_match_mmio_gva(vcpu, addr);
4014c50d8ae3SPaolo Bonzini }
4015c50d8ae3SPaolo Bonzini 
401695fb5b02SBen Gardon /*
401795fb5b02SBen Gardon  * Return the level of the lowest level SPTE added to sptes.
401895fb5b02SBen Gardon  * That SPTE may be non-present.
4019c5c8c7c5SDavid Matlack  *
4020c5c8c7c5SDavid Matlack  * Must be called between walk_shadow_page_lockless_{begin,end}.
402195fb5b02SBen Gardon  */
402239b4d43eSSean Christopherson static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4023c50d8ae3SPaolo Bonzini {
4024c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
40252aa07893SSean Christopherson 	int leaf = -1;
402695fb5b02SBen Gardon 	u64 spte;
4027c50d8ae3SPaolo Bonzini 
402839b4d43eSSean Christopherson 	for (shadow_walk_init(&iterator, vcpu, addr),
402939b4d43eSSean Christopherson 	     *root_level = iterator.level;
4030c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&iterator);
4031c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&iterator, spte)) {
403295fb5b02SBen Gardon 		leaf = iterator.level;
4033c50d8ae3SPaolo Bonzini 		spte = mmu_spte_get_lockless(iterator.sptep);
4034c50d8ae3SPaolo Bonzini 
4035dde81f94SSean Christopherson 		sptes[leaf] = spte;
403695fb5b02SBen Gardon 	}
403795fb5b02SBen Gardon 
403895fb5b02SBen Gardon 	return leaf;
403995fb5b02SBen Gardon }
404095fb5b02SBen Gardon 
40419aa41879SSean Christopherson /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
404295fb5b02SBen Gardon static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
404395fb5b02SBen Gardon {
4044dde81f94SSean Christopherson 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
404595fb5b02SBen Gardon 	struct rsvd_bits_validate *rsvd_check;
404639b4d43eSSean Christopherson 	int root, leaf, level;
404795fb5b02SBen Gardon 	bool reserved = false;
404895fb5b02SBen Gardon 
4049c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_begin(vcpu);
4050c5c8c7c5SDavid Matlack 
405178fdd2f0SSean Christopherson 	if (is_tdp_mmu_active(vcpu))
405239b4d43eSSean Christopherson 		leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
405395fb5b02SBen Gardon 	else
405439b4d43eSSean Christopherson 		leaf = get_walk(vcpu, addr, sptes, &root);
405595fb5b02SBen Gardon 
4056c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_end(vcpu);
4057c5c8c7c5SDavid Matlack 
40582aa07893SSean Christopherson 	if (unlikely(leaf < 0)) {
40592aa07893SSean Christopherson 		*sptep = 0ull;
40602aa07893SSean Christopherson 		return reserved;
40612aa07893SSean Christopherson 	}
40622aa07893SSean Christopherson 
40639aa41879SSean Christopherson 	*sptep = sptes[leaf];
40649aa41879SSean Christopherson 
40659aa41879SSean Christopherson 	/*
40669aa41879SSean Christopherson 	 * Skip reserved bits checks on the terminal leaf if it's not a valid
40679aa41879SSean Christopherson 	 * SPTE.  Note, this also (intentionally) skips MMIO SPTEs, which, by
40689aa41879SSean Christopherson 	 * design, always have reserved bits set.  The purpose of the checks is
40699aa41879SSean Christopherson 	 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
40709aa41879SSean Christopherson 	 */
40719aa41879SSean Christopherson 	if (!is_shadow_present_pte(sptes[leaf]))
40729aa41879SSean Christopherson 		leaf++;
407395fb5b02SBen Gardon 
407495fb5b02SBen Gardon 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
407595fb5b02SBen Gardon 
40769aa41879SSean Christopherson 	for (level = root; level >= leaf; level--)
4077961f8445SSean Christopherson 		reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4078c50d8ae3SPaolo Bonzini 
4079c50d8ae3SPaolo Bonzini 	if (reserved) {
4080bb4cdf3aSSean Christopherson 		pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4081c50d8ae3SPaolo Bonzini 		       __func__, addr);
408295fb5b02SBen Gardon 		for (level = root; level >= leaf; level--)
4083bb4cdf3aSSean Christopherson 			pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4084bb4cdf3aSSean Christopherson 			       sptes[level], level,
4085961f8445SSean Christopherson 			       get_rsvd_bits(rsvd_check, sptes[level], level));
4086c50d8ae3SPaolo Bonzini 	}
4087ddce6208SSean Christopherson 
4088c50d8ae3SPaolo Bonzini 	return reserved;
4089c50d8ae3SPaolo Bonzini }
4090c50d8ae3SPaolo Bonzini 
4091c50d8ae3SPaolo Bonzini static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4092c50d8ae3SPaolo Bonzini {
4093c50d8ae3SPaolo Bonzini 	u64 spte;
4094c50d8ae3SPaolo Bonzini 	bool reserved;
4095c50d8ae3SPaolo Bonzini 
4096c50d8ae3SPaolo Bonzini 	if (mmio_info_in_cache(vcpu, addr, direct))
4097c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4098c50d8ae3SPaolo Bonzini 
409995fb5b02SBen Gardon 	reserved = get_mmio_spte(vcpu, addr, &spte);
4100c50d8ae3SPaolo Bonzini 	if (WARN_ON(reserved))
4101c50d8ae3SPaolo Bonzini 		return -EINVAL;
4102c50d8ae3SPaolo Bonzini 
4103c50d8ae3SPaolo Bonzini 	if (is_mmio_spte(spte)) {
4104c50d8ae3SPaolo Bonzini 		gfn_t gfn = get_mmio_spte_gfn(spte);
41050a2b64c5SBen Gardon 		unsigned int access = get_mmio_spte_access(spte);
4106c50d8ae3SPaolo Bonzini 
4107c50d8ae3SPaolo Bonzini 		if (!check_mmio_spte(vcpu, spte))
4108c50d8ae3SPaolo Bonzini 			return RET_PF_INVALID;
4109c50d8ae3SPaolo Bonzini 
4110c50d8ae3SPaolo Bonzini 		if (direct)
4111c50d8ae3SPaolo Bonzini 			addr = 0;
4112c50d8ae3SPaolo Bonzini 
4113c50d8ae3SPaolo Bonzini 		trace_handle_mmio_page_fault(addr, gfn, access);
4114c50d8ae3SPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4115c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4116c50d8ae3SPaolo Bonzini 	}
4117c50d8ae3SPaolo Bonzini 
4118c50d8ae3SPaolo Bonzini 	/*
4119c50d8ae3SPaolo Bonzini 	 * If the page table is zapped by other cpus, let CPU fault again on
4120c50d8ae3SPaolo Bonzini 	 * the address.
4121c50d8ae3SPaolo Bonzini 	 */
4122c50d8ae3SPaolo Bonzini 	return RET_PF_RETRY;
4123c50d8ae3SPaolo Bonzini }
4124c50d8ae3SPaolo Bonzini 
4125c50d8ae3SPaolo Bonzini static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4126b8a5d551SPaolo Bonzini 					 struct kvm_page_fault *fault)
4127c50d8ae3SPaolo Bonzini {
4128b8a5d551SPaolo Bonzini 	if (unlikely(fault->rsvd))
4129c50d8ae3SPaolo Bonzini 		return false;
4130c50d8ae3SPaolo Bonzini 
4131b8a5d551SPaolo Bonzini 	if (!fault->present || !fault->write)
4132c50d8ae3SPaolo Bonzini 		return false;
4133c50d8ae3SPaolo Bonzini 
4134c50d8ae3SPaolo Bonzini 	/*
4135c50d8ae3SPaolo Bonzini 	 * guest is writing the page which is write tracked which can
4136c50d8ae3SPaolo Bonzini 	 * not be fixed by page fault handler.
4137c50d8ae3SPaolo Bonzini 	 */
41389d395a0aSBen Gardon 	if (kvm_slot_page_track_is_active(vcpu->kvm, fault->slot, fault->gfn, KVM_PAGE_TRACK_WRITE))
4139c50d8ae3SPaolo Bonzini 		return true;
4140c50d8ae3SPaolo Bonzini 
4141c50d8ae3SPaolo Bonzini 	return false;
4142c50d8ae3SPaolo Bonzini }
4143c50d8ae3SPaolo Bonzini 
4144c50d8ae3SPaolo Bonzini static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4145c50d8ae3SPaolo Bonzini {
4146c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
4147c50d8ae3SPaolo Bonzini 	u64 spte;
4148c50d8ae3SPaolo Bonzini 
4149c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
41503e44dce4SLai Jiangshan 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4151c50d8ae3SPaolo Bonzini 		clear_sp_write_flooding_count(iterator.sptep);
4152c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
4153c50d8ae3SPaolo Bonzini }
4154c50d8ae3SPaolo Bonzini 
41556f3c1fc5SLiang Zhang static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
41566f3c1fc5SLiang Zhang {
41576f3c1fc5SLiang Zhang 	/* make sure the token value is not 0 */
41586f3c1fc5SLiang Zhang 	u32 id = vcpu->arch.apf.id;
41596f3c1fc5SLiang Zhang 
41606f3c1fc5SLiang Zhang 	if (id << 12 == 0)
41616f3c1fc5SLiang Zhang 		vcpu->arch.apf.id = 1;
41626f3c1fc5SLiang Zhang 
41636f3c1fc5SLiang Zhang 	return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
41646f3c1fc5SLiang Zhang }
41656f3c1fc5SLiang Zhang 
4166e8c22266SVitaly Kuznetsov static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
41679f1a8526SSean Christopherson 				    gfn_t gfn)
4168c50d8ae3SPaolo Bonzini {
4169c50d8ae3SPaolo Bonzini 	struct kvm_arch_async_pf arch;
4170c50d8ae3SPaolo Bonzini 
41716f3c1fc5SLiang Zhang 	arch.token = alloc_apf_token(vcpu);
4172c50d8ae3SPaolo Bonzini 	arch.gfn = gfn;
4173347a0d0dSPaolo Bonzini 	arch.direct_map = vcpu->arch.mmu->root_role.direct;
4174d8dd54e0SSean Christopherson 	arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
4175c50d8ae3SPaolo Bonzini 
41769f1a8526SSean Christopherson 	return kvm_setup_async_pf(vcpu, cr2_or_gpa,
41779f1a8526SSean Christopherson 				  kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4178c50d8ae3SPaolo Bonzini }
4179c50d8ae3SPaolo Bonzini 
41808a009d5bSSean Christopherson void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
41818a009d5bSSean Christopherson {
41828a009d5bSSean Christopherson 	int r;
41838a009d5bSSean Christopherson 
41848a009d5bSSean Christopherson 	if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
41858a009d5bSSean Christopherson 	      work->wakeup_all)
41868a009d5bSSean Christopherson 		return;
41878a009d5bSSean Christopherson 
41888a009d5bSSean Christopherson 	r = kvm_mmu_reload(vcpu);
41898a009d5bSSean Christopherson 	if (unlikely(r))
41908a009d5bSSean Christopherson 		return;
41918a009d5bSSean Christopherson 
41928a009d5bSSean Christopherson 	if (!vcpu->arch.mmu->root_role.direct &&
41938a009d5bSSean Christopherson 	      work->arch.cr3 != vcpu->arch.mmu->get_guest_pgd(vcpu))
41948a009d5bSSean Christopherson 		return;
41958a009d5bSSean Christopherson 
41968a009d5bSSean Christopherson 	kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
41978a009d5bSSean Christopherson }
41988a009d5bSSean Christopherson 
4199ba6e3fe2SDavid Matlack static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4200c50d8ae3SPaolo Bonzini {
4201e710c5f6SDavid Matlack 	struct kvm_memory_slot *slot = fault->slot;
4202c50d8ae3SPaolo Bonzini 	bool async;
4203c50d8ae3SPaolo Bonzini 
4204e0c37868SSean Christopherson 	/*
4205e0c37868SSean Christopherson 	 * Retry the page fault if the gfn hit a memslot that is being deleted
4206e0c37868SSean Christopherson 	 * or moved.  This ensures any existing SPTEs for the old memslot will
4207e0c37868SSean Christopherson 	 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4208e0c37868SSean Christopherson 	 */
4209e0c37868SSean Christopherson 	if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
42105276c616SSean Christopherson 		return RET_PF_RETRY;
4211e0c37868SSean Christopherson 
42129cc13d60SMaxim Levitsky 	if (!kvm_is_visible_memslot(slot)) {
4213c36b7150SPaolo Bonzini 		/* Don't expose private memslots to L2. */
42149cc13d60SMaxim Levitsky 		if (is_guest_mode(vcpu)) {
4215e710c5f6SDavid Matlack 			fault->slot = NULL;
42163647cd04SPaolo Bonzini 			fault->pfn = KVM_PFN_NOSLOT;
42173647cd04SPaolo Bonzini 			fault->map_writable = false;
42185276c616SSean Christopherson 			return RET_PF_CONTINUE;
4219c50d8ae3SPaolo Bonzini 		}
42209cc13d60SMaxim Levitsky 		/*
42219cc13d60SMaxim Levitsky 		 * If the APIC access page exists but is disabled, go directly
42229cc13d60SMaxim Levitsky 		 * to emulation without caching the MMIO access or creating a
42239cc13d60SMaxim Levitsky 		 * MMIO SPTE.  That way the cache doesn't need to be purged
42249cc13d60SMaxim Levitsky 		 * when the AVIC is re-enabled.
42259cc13d60SMaxim Levitsky 		 */
42269cc13d60SMaxim Levitsky 		if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
42275276c616SSean Christopherson 		    !kvm_apicv_activated(vcpu->kvm))
42285276c616SSean Christopherson 			return RET_PF_EMULATE;
42299cc13d60SMaxim Levitsky 	}
4230c50d8ae3SPaolo Bonzini 
4231c50d8ae3SPaolo Bonzini 	async = false;
4232c8b88b33SPeter Xu 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, false, &async,
42333647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
42343647cd04SPaolo Bonzini 					  &fault->hva);
4235c50d8ae3SPaolo Bonzini 	if (!async)
42365276c616SSean Christopherson 		return RET_PF_CONTINUE; /* *pfn has correct page already */
4237c50d8ae3SPaolo Bonzini 
42382839180cSPaolo Bonzini 	if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
42393647cd04SPaolo Bonzini 		trace_kvm_try_async_get_page(fault->addr, fault->gfn);
42403647cd04SPaolo Bonzini 		if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
42411685c0f3SMingwei Zhang 			trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4242c50d8ae3SPaolo Bonzini 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
42435276c616SSean Christopherson 			return RET_PF_RETRY;
42445276c616SSean Christopherson 		} else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn)) {
42455276c616SSean Christopherson 			return RET_PF_RETRY;
42465276c616SSean Christopherson 		}
4247c50d8ae3SPaolo Bonzini 	}
4248c50d8ae3SPaolo Bonzini 
424976657687SPeter Xu 	/*
425076657687SPeter Xu 	 * Allow gup to bail on pending non-fatal signals when it's also allowed
425176657687SPeter Xu 	 * to wait for IO.  Note, gup always bails if it is unable to quickly
425276657687SPeter Xu 	 * get a page and a fatal signal, i.e. SIGKILL, is pending.
425376657687SPeter Xu 	 */
425476657687SPeter Xu 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, true, NULL,
42553647cd04SPaolo Bonzini 					  fault->write, &fault->map_writable,
42563647cd04SPaolo Bonzini 					  &fault->hva);
42575276c616SSean Christopherson 	return RET_PF_CONTINUE;
4258c50d8ae3SPaolo Bonzini }
4259c50d8ae3SPaolo Bonzini 
4260354c908cSDavid Matlack static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
4261354c908cSDavid Matlack 			   unsigned int access)
4262ba6e3fe2SDavid Matlack {
426356c3a4e4SDavid Matlack 	int ret;
426456c3a4e4SDavid Matlack 
4265ba6e3fe2SDavid Matlack 	fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4266ba6e3fe2SDavid Matlack 	smp_rmb();
4267ba6e3fe2SDavid Matlack 
426856c3a4e4SDavid Matlack 	ret = __kvm_faultin_pfn(vcpu, fault);
426956c3a4e4SDavid Matlack 	if (ret != RET_PF_CONTINUE)
427056c3a4e4SDavid Matlack 		return ret;
427156c3a4e4SDavid Matlack 
427256c3a4e4SDavid Matlack 	if (unlikely(is_error_pfn(fault->pfn)))
4273cd08d178SDavid Matlack 		return kvm_handle_error_pfn(vcpu, fault);
427456c3a4e4SDavid Matlack 
4275354c908cSDavid Matlack 	if (unlikely(!fault->slot))
4276354c908cSDavid Matlack 		return kvm_handle_noslot_fault(vcpu, fault, access);
4277354c908cSDavid Matlack 
427856c3a4e4SDavid Matlack 	return RET_PF_CONTINUE;
4279ba6e3fe2SDavid Matlack }
4280ba6e3fe2SDavid Matlack 
4281a955cad8SSean Christopherson /*
4282a955cad8SSean Christopherson  * Returns true if the page fault is stale and needs to be retried, i.e. if the
4283a955cad8SSean Christopherson  * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4284a955cad8SSean Christopherson  */
4285a955cad8SSean Christopherson static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4286ba6e3fe2SDavid Matlack 				struct kvm_page_fault *fault)
4287a955cad8SSean Christopherson {
4288b9e5603cSPaolo Bonzini 	struct kvm_mmu_page *sp = to_shadow_page(vcpu->arch.mmu->root.hpa);
428918c841e1SSean Christopherson 
429018c841e1SSean Christopherson 	/* Special roots, e.g. pae_root, are not backed by shadow pages. */
429118c841e1SSean Christopherson 	if (sp && is_obsolete_sp(vcpu->kvm, sp))
429218c841e1SSean Christopherson 		return true;
429318c841e1SSean Christopherson 
429418c841e1SSean Christopherson 	/*
429518c841e1SSean Christopherson 	 * Roots without an associated shadow page are considered invalid if
429618c841e1SSean Christopherson 	 * there is a pending request to free obsolete roots.  The request is
429718c841e1SSean Christopherson 	 * only a hint that the current root _may_ be obsolete and needs to be
429818c841e1SSean Christopherson 	 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
429918c841e1SSean Christopherson 	 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
430018c841e1SSean Christopherson 	 * to reload even if no vCPU is actively using the root.
430118c841e1SSean Christopherson 	 */
4302527d5cd7SSean Christopherson 	if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4303a955cad8SSean Christopherson 		return true;
4304a955cad8SSean Christopherson 
4305a955cad8SSean Christopherson 	return fault->slot &&
4306ba6e3fe2SDavid Matlack 	       mmu_invalidate_retry_hva(vcpu->kvm, fault->mmu_seq, fault->hva);
4307a955cad8SSean Christopherson }
4308a955cad8SSean Christopherson 
43094326e57eSPaolo Bonzini static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4310c50d8ae3SPaolo Bonzini {
431183f06fa7SSean Christopherson 	int r;
4312c50d8ae3SPaolo Bonzini 
4313b8a5d551SPaolo Bonzini 	if (page_fault_handle_page_track(vcpu, fault))
4314c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
4315c50d8ae3SPaolo Bonzini 
43163c8ad5a6SPaolo Bonzini 	r = fast_page_fault(vcpu, fault);
4317c4371c2aSSean Christopherson 	if (r != RET_PF_INVALID)
4318c4371c2aSSean Christopherson 		return r;
431983291445SSean Christopherson 
4320378f5cd6SSean Christopherson 	r = mmu_topup_memory_caches(vcpu, false);
4321c50d8ae3SPaolo Bonzini 	if (r)
4322c50d8ae3SPaolo Bonzini 		return r;
4323c50d8ae3SPaolo Bonzini 
4324354c908cSDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
43255276c616SSean Christopherson 	if (r != RET_PF_CONTINUE)
4326367fd790SSean Christopherson 		return r;
4327367fd790SSean Christopherson 
4328367fd790SSean Christopherson 	r = RET_PF_RETRY;
4329531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
4330a2855afcSBen Gardon 
4331ba6e3fe2SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
4332367fd790SSean Christopherson 		goto out_unlock;
4333a955cad8SSean Christopherson 
43347bd7ded6SSean Christopherson 	r = make_mmu_pages_available(vcpu);
43357bd7ded6SSean Christopherson 	if (r)
4336367fd790SSean Christopherson 		goto out_unlock;
4337bb18842eSBen Gardon 
43386c882ef4SDavid Matlack 	r = direct_map(vcpu, fault);
43390f90e1c1SSean Christopherson 
4340367fd790SSean Christopherson out_unlock:
4341531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
43423647cd04SPaolo Bonzini 	kvm_release_pfn_clean(fault->pfn);
4343367fd790SSean Christopherson 	return r;
4344c50d8ae3SPaolo Bonzini }
4345c50d8ae3SPaolo Bonzini 
4346c501040aSPaolo Bonzini static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4347c501040aSPaolo Bonzini 				struct kvm_page_fault *fault)
43480f90e1c1SSean Christopherson {
43494326e57eSPaolo Bonzini 	pgprintk("%s: gva %lx error %x\n", __func__, fault->addr, fault->error_code);
43500f90e1c1SSean Christopherson 
43510f90e1c1SSean Christopherson 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
43524326e57eSPaolo Bonzini 	fault->max_level = PG_LEVEL_2M;
43534326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
43540f90e1c1SSean Christopherson }
43550f90e1c1SSean Christopherson 
4356c50d8ae3SPaolo Bonzini int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4357c50d8ae3SPaolo Bonzini 				u64 fault_address, char *insn, int insn_len)
4358c50d8ae3SPaolo Bonzini {
4359c50d8ae3SPaolo Bonzini 	int r = 1;
43609ce372b3SVitaly Kuznetsov 	u32 flags = vcpu->arch.apf.host_apf_flags;
4361c50d8ae3SPaolo Bonzini 
4362736c291cSSean Christopherson #ifndef CONFIG_X86_64
4363736c291cSSean Christopherson 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4364736c291cSSean Christopherson 	if (WARN_ON_ONCE(fault_address >> 32))
4365736c291cSSean Christopherson 		return -EFAULT;
4366736c291cSSean Christopherson #endif
4367736c291cSSean Christopherson 
4368c50d8ae3SPaolo Bonzini 	vcpu->arch.l1tf_flush_l1d = true;
43699ce372b3SVitaly Kuznetsov 	if (!flags) {
4370faa03b39SWonhyuk Yang 		trace_kvm_page_fault(vcpu, fault_address, error_code);
4371c50d8ae3SPaolo Bonzini 
4372c50d8ae3SPaolo Bonzini 		if (kvm_event_needs_reinjection(vcpu))
4373c50d8ae3SPaolo Bonzini 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4374c50d8ae3SPaolo Bonzini 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4375c50d8ae3SPaolo Bonzini 				insn_len);
43769ce372b3SVitaly Kuznetsov 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
437768fd66f1SVitaly Kuznetsov 		vcpu->arch.apf.host_apf_flags = 0;
4378c50d8ae3SPaolo Bonzini 		local_irq_disable();
43796bca69adSThomas Gleixner 		kvm_async_pf_task_wait_schedule(fault_address);
4380c50d8ae3SPaolo Bonzini 		local_irq_enable();
43819ce372b3SVitaly Kuznetsov 	} else {
43829ce372b3SVitaly Kuznetsov 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4383c50d8ae3SPaolo Bonzini 	}
43849ce372b3SVitaly Kuznetsov 
4385c50d8ae3SPaolo Bonzini 	return r;
4386c50d8ae3SPaolo Bonzini }
4387c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4388c50d8ae3SPaolo Bonzini 
43899aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
43909aa8ab43SDavid Matlack static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
43919aa8ab43SDavid Matlack 				  struct kvm_page_fault *fault)
43929aa8ab43SDavid Matlack {
43939aa8ab43SDavid Matlack 	int r;
43949aa8ab43SDavid Matlack 
43959aa8ab43SDavid Matlack 	if (page_fault_handle_page_track(vcpu, fault))
43969aa8ab43SDavid Matlack 		return RET_PF_EMULATE;
43979aa8ab43SDavid Matlack 
43989aa8ab43SDavid Matlack 	r = fast_page_fault(vcpu, fault);
43999aa8ab43SDavid Matlack 	if (r != RET_PF_INVALID)
44009aa8ab43SDavid Matlack 		return r;
44019aa8ab43SDavid Matlack 
44029aa8ab43SDavid Matlack 	r = mmu_topup_memory_caches(vcpu, false);
44039aa8ab43SDavid Matlack 	if (r)
44049aa8ab43SDavid Matlack 		return r;
44059aa8ab43SDavid Matlack 
44069aa8ab43SDavid Matlack 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
44079aa8ab43SDavid Matlack 	if (r != RET_PF_CONTINUE)
44089aa8ab43SDavid Matlack 		return r;
44099aa8ab43SDavid Matlack 
44109aa8ab43SDavid Matlack 	r = RET_PF_RETRY;
44119aa8ab43SDavid Matlack 	read_lock(&vcpu->kvm->mmu_lock);
44129aa8ab43SDavid Matlack 
44139aa8ab43SDavid Matlack 	if (is_page_fault_stale(vcpu, fault))
44149aa8ab43SDavid Matlack 		goto out_unlock;
44159aa8ab43SDavid Matlack 
44169aa8ab43SDavid Matlack 	r = kvm_tdp_mmu_map(vcpu, fault);
44179aa8ab43SDavid Matlack 
44189aa8ab43SDavid Matlack out_unlock:
44199aa8ab43SDavid Matlack 	read_unlock(&vcpu->kvm->mmu_lock);
44209aa8ab43SDavid Matlack 	kvm_release_pfn_clean(fault->pfn);
44219aa8ab43SDavid Matlack 	return r;
44229aa8ab43SDavid Matlack }
44239aa8ab43SDavid Matlack #endif
44249aa8ab43SDavid Matlack 
4425c501040aSPaolo Bonzini int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4426c50d8ae3SPaolo Bonzini {
4427d5e90a69SSean Christopherson 	/*
4428d5e90a69SSean Christopherson 	 * If the guest's MTRRs may be used to compute the "real" memtype,
4429d5e90a69SSean Christopherson 	 * restrict the mapping level to ensure KVM uses a consistent memtype
4430d5e90a69SSean Christopherson 	 * across the entire mapping.  If the host MTRRs are ignored by TDP
4431d5e90a69SSean Christopherson 	 * (shadow_memtype_mask is non-zero), and the VM has non-coherent DMA
4432d5e90a69SSean Christopherson 	 * (DMA doesn't snoop CPU caches), KVM's ABI is to honor the memtype
4433d5e90a69SSean Christopherson 	 * from the guest's MTRRs so that guest accesses to memory that is
4434d5e90a69SSean Christopherson 	 * DMA'd aren't cached against the guest's wishes.
4435d5e90a69SSean Christopherson 	 *
4436d5e90a69SSean Christopherson 	 * Note, KVM may still ultimately ignore guest MTRRs for certain PFNs,
4437d5e90a69SSean Christopherson 	 * e.g. KVM will force UC memtype for host MMIO.
4438d5e90a69SSean Christopherson 	 */
4439d5e90a69SSean Christopherson 	if (shadow_memtype_mask && kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
4440d5e90a69SSean Christopherson 		for ( ; fault->max_level > PG_LEVEL_4K; --fault->max_level) {
44414326e57eSPaolo Bonzini 			int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
4442e5e6f8d2SDavid Matlack 			gfn_t base = fault->gfn & ~(page_num - 1);
4443c50d8ae3SPaolo Bonzini 
4444cb9b88c6SSean Christopherson 			if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4445cb9b88c6SSean Christopherson 				break;
4446d5e90a69SSean Christopherson 		}
4447c50d8ae3SPaolo Bonzini 	}
4448c50d8ae3SPaolo Bonzini 
44499aa8ab43SDavid Matlack #ifdef CONFIG_X86_64
44509aa8ab43SDavid Matlack 	if (tdp_mmu_enabled)
44519aa8ab43SDavid Matlack 		return kvm_tdp_mmu_page_fault(vcpu, fault);
44529aa8ab43SDavid Matlack #endif
44539aa8ab43SDavid Matlack 
44544326e57eSPaolo Bonzini 	return direct_page_fault(vcpu, fault);
4455c50d8ae3SPaolo Bonzini }
4456c50d8ae3SPaolo Bonzini 
445784a16226SSean Christopherson static void nonpaging_init_context(struct kvm_mmu *context)
4458c50d8ae3SPaolo Bonzini {
4459c50d8ae3SPaolo Bonzini 	context->page_fault = nonpaging_page_fault;
4460c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4461c50d8ae3SPaolo Bonzini 	context->sync_page = nonpaging_sync_page;
44625efac074SPaolo Bonzini 	context->invlpg = NULL;
4463c50d8ae3SPaolo Bonzini }
4464c50d8ae3SPaolo Bonzini 
4465be01e8e2SSean Christopherson static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
44660be44352SSean Christopherson 				  union kvm_mmu_page_role role)
44670be44352SSean Christopherson {
4468be01e8e2SSean Christopherson 	return (role.direct || pgd == root->pgd) &&
44695499ea73SPaolo Bonzini 	       VALID_PAGE(root->hpa) &&
4470e47c4aeeSSean Christopherson 	       role.word == to_shadow_page(root->hpa)->role.word;
44710be44352SSean Christopherson }
44720be44352SSean Christopherson 
4473c50d8ae3SPaolo Bonzini /*
44745499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available,
44755499ea73SPaolo Bonzini  * and insert the current root as the MRU in the cache.
44765499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root and
44775499ea73SPaolo Bonzini  * true is returned.
44785499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid, the LRU root is
44795499ea73SPaolo Bonzini  * evicted to make room for the current root, and false is returned.
4480c50d8ae3SPaolo Bonzini  */
44815499ea73SPaolo Bonzini static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
44825499ea73SPaolo Bonzini 					      gpa_t new_pgd,
4483c50d8ae3SPaolo Bonzini 					      union kvm_mmu_page_role new_role)
4484c50d8ae3SPaolo Bonzini {
4485c50d8ae3SPaolo Bonzini 	uint i;
4486c50d8ae3SPaolo Bonzini 
4487b9e5603cSPaolo Bonzini 	if (is_root_usable(&mmu->root, new_pgd, new_role))
44880be44352SSean Christopherson 		return true;
44890be44352SSean Christopherson 
4490c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
44915499ea73SPaolo Bonzini 		/*
44925499ea73SPaolo Bonzini 		 * The swaps end up rotating the cache like this:
44935499ea73SPaolo Bonzini 		 *   C   0 1 2 3   (on entry to the function)
44945499ea73SPaolo Bonzini 		 *   0   C 1 2 3
44955499ea73SPaolo Bonzini 		 *   1   C 0 2 3
44965499ea73SPaolo Bonzini 		 *   2   C 0 1 3
44975499ea73SPaolo Bonzini 		 *   3   C 0 1 2   (on exit from the loop)
44985499ea73SPaolo Bonzini 		 */
4499b9e5603cSPaolo Bonzini 		swap(mmu->root, mmu->prev_roots[i]);
4500b9e5603cSPaolo Bonzini 		if (is_root_usable(&mmu->root, new_pgd, new_role))
45015499ea73SPaolo Bonzini 			return true;
4502c50d8ae3SPaolo Bonzini 	}
4503c50d8ae3SPaolo Bonzini 
45045499ea73SPaolo Bonzini 	kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
45055499ea73SPaolo Bonzini 	return false;
4506c50d8ae3SPaolo Bonzini }
4507c50d8ae3SPaolo Bonzini 
4508c50d8ae3SPaolo Bonzini /*
45095499ea73SPaolo Bonzini  * Find out if a previously cached root matching the new pgd/role is available.
45105499ea73SPaolo Bonzini  * On entry, mmu->root is invalid.
45115499ea73SPaolo Bonzini  * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
45125499ea73SPaolo Bonzini  * of the cache becomes invalid, and true is returned.
45135499ea73SPaolo Bonzini  * If no match is found, kvm_mmu->root is left invalid and false is returned.
45145499ea73SPaolo Bonzini  */
45155499ea73SPaolo Bonzini static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
45165499ea73SPaolo Bonzini 					     gpa_t new_pgd,
45175499ea73SPaolo Bonzini 					     union kvm_mmu_page_role new_role)
45185499ea73SPaolo Bonzini {
45195499ea73SPaolo Bonzini 	uint i;
45205499ea73SPaolo Bonzini 
45215499ea73SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
45225499ea73SPaolo Bonzini 		if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
45235499ea73SPaolo Bonzini 			goto hit;
45245499ea73SPaolo Bonzini 
45255499ea73SPaolo Bonzini 	return false;
45265499ea73SPaolo Bonzini 
45275499ea73SPaolo Bonzini hit:
45285499ea73SPaolo Bonzini 	swap(mmu->root, mmu->prev_roots[i]);
45295499ea73SPaolo Bonzini 	/* Bubble up the remaining roots.  */
45305499ea73SPaolo Bonzini 	for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
45315499ea73SPaolo Bonzini 		mmu->prev_roots[i] = mmu->prev_roots[i + 1];
45325499ea73SPaolo Bonzini 	mmu->prev_roots[i].hpa = INVALID_PAGE;
45335499ea73SPaolo Bonzini 	return true;
45345499ea73SPaolo Bonzini }
45355499ea73SPaolo Bonzini 
45365499ea73SPaolo Bonzini static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
45375499ea73SPaolo Bonzini 			    gpa_t new_pgd, union kvm_mmu_page_role new_role)
45385499ea73SPaolo Bonzini {
45395499ea73SPaolo Bonzini 	/*
45405499ea73SPaolo Bonzini 	 * For now, limit the caching to 64-bit hosts+VMs in order to avoid
4541c50d8ae3SPaolo Bonzini 	 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4542c50d8ae3SPaolo Bonzini 	 * later if necessary.
4543c50d8ae3SPaolo Bonzini 	 */
45445499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa) && !to_shadow_page(mmu->root.hpa))
45455499ea73SPaolo Bonzini 		kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4546c50d8ae3SPaolo Bonzini 
45475499ea73SPaolo Bonzini 	if (VALID_PAGE(mmu->root.hpa))
45485499ea73SPaolo Bonzini 		return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
45495499ea73SPaolo Bonzini 	else
45505499ea73SPaolo Bonzini 		return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4551c50d8ae3SPaolo Bonzini }
4552c50d8ae3SPaolo Bonzini 
4553d2e5f333SPaolo Bonzini void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4554c50d8ae3SPaolo Bonzini {
45550c1c92f1SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
45567a458f0eSPaolo Bonzini 	union kvm_mmu_page_role new_role = mmu->root_role;
45570c1c92f1SPaolo Bonzini 
45585499ea73SPaolo Bonzini 	if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role)) {
45595499ea73SPaolo Bonzini 		/* kvm_mmu_ensure_valid_pgd will set up a new root.  */
4560b869855bSSean Christopherson 		return;
4561c50d8ae3SPaolo Bonzini 	}
4562c50d8ae3SPaolo Bonzini 
4563c50d8ae3SPaolo Bonzini 	/*
4564b869855bSSean Christopherson 	 * It's possible that the cached previous root page is obsolete because
4565b869855bSSean Christopherson 	 * of a change in the MMU generation number. However, changing the
4566527d5cd7SSean Christopherson 	 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4567527d5cd7SSean Christopherson 	 * which will free the root set here and allocate a new one.
4568b869855bSSean Christopherson 	 */
4569b869855bSSean Christopherson 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4570b869855bSSean Christopherson 
4571b5129100SSean Christopherson 	if (force_flush_and_sync_on_reuse) {
4572b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4573b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4574b5129100SSean Christopherson 	}
4575b869855bSSean Christopherson 
4576b869855bSSean Christopherson 	/*
4577b869855bSSean Christopherson 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4578b869855bSSean Christopherson 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
4579b869855bSSean Christopherson 	 * valid. So clear any cached MMIO info even when we don't need to sync
4580b869855bSSean Christopherson 	 * the shadow page tables.
4581c50d8ae3SPaolo Bonzini 	 */
4582c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4583c50d8ae3SPaolo Bonzini 
4584daa5b6c1SBen Gardon 	/*
4585daa5b6c1SBen Gardon 	 * If this is a direct root page, it doesn't have a write flooding
4586daa5b6c1SBen Gardon 	 * count. Otherwise, clear the write flooding count.
4587daa5b6c1SBen Gardon 	 */
4588daa5b6c1SBen Gardon 	if (!new_role.direct)
4589daa5b6c1SBen Gardon 		__clear_sp_write_flooding_count(
4590b9e5603cSPaolo Bonzini 				to_shadow_page(vcpu->arch.mmu->root.hpa));
4591c50d8ae3SPaolo Bonzini }
4592be01e8e2SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4593c50d8ae3SPaolo Bonzini 
4594c50d8ae3SPaolo Bonzini static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4595c50d8ae3SPaolo Bonzini {
4596c50d8ae3SPaolo Bonzini 	return kvm_read_cr3(vcpu);
4597c50d8ae3SPaolo Bonzini }
4598c50d8ae3SPaolo Bonzini 
4599c50d8ae3SPaolo Bonzini static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4600c3e5e415SLai Jiangshan 			   unsigned int access)
4601c50d8ae3SPaolo Bonzini {
4602c50d8ae3SPaolo Bonzini 	if (unlikely(is_mmio_spte(*sptep))) {
4603c50d8ae3SPaolo Bonzini 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4604c50d8ae3SPaolo Bonzini 			mmu_spte_clear_no_track(sptep);
4605c50d8ae3SPaolo Bonzini 			return true;
4606c50d8ae3SPaolo Bonzini 		}
4607c50d8ae3SPaolo Bonzini 
4608c50d8ae3SPaolo Bonzini 		mark_mmio_spte(vcpu, sptep, gfn, access);
4609c50d8ae3SPaolo Bonzini 		return true;
4610c50d8ae3SPaolo Bonzini 	}
4611c50d8ae3SPaolo Bonzini 
4612c50d8ae3SPaolo Bonzini 	return false;
4613c50d8ae3SPaolo Bonzini }
4614c50d8ae3SPaolo Bonzini 
4615c50d8ae3SPaolo Bonzini #define PTTYPE_EPT 18 /* arbitrary */
4616c50d8ae3SPaolo Bonzini #define PTTYPE PTTYPE_EPT
4617c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4618c50d8ae3SPaolo Bonzini #undef PTTYPE
4619c50d8ae3SPaolo Bonzini 
4620c50d8ae3SPaolo Bonzini #define PTTYPE 64
4621c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4622c50d8ae3SPaolo Bonzini #undef PTTYPE
4623c50d8ae3SPaolo Bonzini 
4624c50d8ae3SPaolo Bonzini #define PTTYPE 32
4625c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4626c50d8ae3SPaolo Bonzini #undef PTTYPE
4627c50d8ae3SPaolo Bonzini 
4628c50d8ae3SPaolo Bonzini static void
4629b705a277SSean Christopherson __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
46305b7f575cSSean Christopherson 			u64 pa_bits_rsvd, int level, bool nx, bool gbpages,
4631c50d8ae3SPaolo Bonzini 			bool pse, bool amd)
4632c50d8ae3SPaolo Bonzini {
4633c50d8ae3SPaolo Bonzini 	u64 gbpages_bit_rsvd = 0;
4634c50d8ae3SPaolo Bonzini 	u64 nonleaf_bit8_rsvd = 0;
46355b7f575cSSean Christopherson 	u64 high_bits_rsvd;
4636c50d8ae3SPaolo Bonzini 
4637c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = 0;
4638c50d8ae3SPaolo Bonzini 
4639c50d8ae3SPaolo Bonzini 	if (!gbpages)
4640c50d8ae3SPaolo Bonzini 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4641c50d8ae3SPaolo Bonzini 
46425b7f575cSSean Christopherson 	if (level == PT32E_ROOT_LEVEL)
46435b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
46445b7f575cSSean Christopherson 	else
46455b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
46465b7f575cSSean Christopherson 
46475b7f575cSSean Christopherson 	/* Note, NX doesn't exist in PDPTEs, this is handled below. */
46485b7f575cSSean Christopherson 	if (!nx)
46495b7f575cSSean Christopherson 		high_bits_rsvd |= rsvd_bits(63, 63);
46505b7f575cSSean Christopherson 
4651c50d8ae3SPaolo Bonzini 	/*
4652c50d8ae3SPaolo Bonzini 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4653c50d8ae3SPaolo Bonzini 	 * leaf entries) on AMD CPUs only.
4654c50d8ae3SPaolo Bonzini 	 */
4655c50d8ae3SPaolo Bonzini 	if (amd)
4656c50d8ae3SPaolo Bonzini 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4657c50d8ae3SPaolo Bonzini 
4658c50d8ae3SPaolo Bonzini 	switch (level) {
4659c50d8ae3SPaolo Bonzini 	case PT32_ROOT_LEVEL:
4660c50d8ae3SPaolo Bonzini 		/* no rsvd bits for 2 level 4K page table entries */
4661c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4662c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4663c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4664c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4665c50d8ae3SPaolo Bonzini 
4666c50d8ae3SPaolo Bonzini 		if (!pse) {
4667c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4668c50d8ae3SPaolo Bonzini 			break;
4669c50d8ae3SPaolo Bonzini 		}
4670c50d8ae3SPaolo Bonzini 
4671c50d8ae3SPaolo Bonzini 		if (is_cpuid_PSE36())
4672c50d8ae3SPaolo Bonzini 			/* 36bits PSE 4MB page */
4673c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4674c50d8ae3SPaolo Bonzini 		else
4675c50d8ae3SPaolo Bonzini 			/* 32 bits PSE 4MB page */
4676c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4677c50d8ae3SPaolo Bonzini 		break;
4678c50d8ae3SPaolo Bonzini 	case PT32E_ROOT_LEVEL:
46795b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
46805b7f575cSSean Christopherson 						   high_bits_rsvd |
46815b7f575cSSean Christopherson 						   rsvd_bits(5, 8) |
46825b7f575cSSean Christopherson 						   rsvd_bits(1, 2);	/* PDPTE */
46835b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;	/* PDE */
46845b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;	/* PTE */
46855b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4686c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20);	/* large page */
4687c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4688c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4689c50d8ae3SPaolo Bonzini 		break;
4690c50d8ae3SPaolo Bonzini 	case PT64_ROOT_5LEVEL:
46915b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
46925b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
46935b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
4694c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][4] =
4695c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][4];
4696df561f66SGustavo A. R. Silva 		fallthrough;
4697c50d8ae3SPaolo Bonzini 	case PT64_ROOT_4LEVEL:
46985b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
46995b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
47005b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
47015b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
47025b7f575cSSean Christopherson 						   gbpages_bit_rsvd;
47035b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
47045b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4705c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][3] =
4706c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][3];
47075b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
47085b7f575cSSean Christopherson 						   gbpages_bit_rsvd |
4709c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 29);
47105b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4711c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20); /* large page */
4712c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4713c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4714c50d8ae3SPaolo Bonzini 		break;
4715c50d8ae3SPaolo Bonzini 	}
4716c50d8ae3SPaolo Bonzini }
4717c50d8ae3SPaolo Bonzini 
471827de9250SSean Christopherson static bool guest_can_use_gbpages(struct kvm_vcpu *vcpu)
471927de9250SSean Christopherson {
472027de9250SSean Christopherson 	/*
472127de9250SSean Christopherson 	 * If TDP is enabled, let the guest use GBPAGES if they're supported in
472227de9250SSean Christopherson 	 * hardware.  The hardware page walker doesn't let KVM disable GBPAGES,
472327de9250SSean Christopherson 	 * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
472427de9250SSean Christopherson 	 * walk for performance and complexity reasons.  Not to mention KVM
472527de9250SSean Christopherson 	 * _can't_ solve the problem because GVA->GPA walks aren't visible to
472627de9250SSean Christopherson 	 * KVM once a TDP translation is installed.  Mimic hardware behavior so
472727de9250SSean Christopherson 	 * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
472827de9250SSean Christopherson 	 */
472927de9250SSean Christopherson 	return tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
473027de9250SSean Christopherson 			     guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES);
473127de9250SSean Christopherson }
473227de9250SSean Christopherson 
4733c919e881SKai Huang static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4734c50d8ae3SPaolo Bonzini 					struct kvm_mmu *context)
4735c50d8ae3SPaolo Bonzini {
4736b705a277SSean Christopherson 	__reset_rsvds_bits_mask(&context->guest_rsvd_check,
47375b7f575cSSean Christopherson 				vcpu->arch.reserved_gpa_bits,
47384d25502aSPaolo Bonzini 				context->cpu_role.base.level, is_efer_nx(context),
473927de9250SSean Christopherson 				guest_can_use_gbpages(vcpu),
47404e9c0d80SSean Christopherson 				is_cr4_pse(context),
474123493d0aSSean Christopherson 				guest_cpuid_is_amd_or_hygon(vcpu));
4742c50d8ae3SPaolo Bonzini }
4743c50d8ae3SPaolo Bonzini 
4744c50d8ae3SPaolo Bonzini static void
4745c50d8ae3SPaolo Bonzini __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
474684ea5c09SLai Jiangshan 			    u64 pa_bits_rsvd, bool execonly, int huge_page_level)
4747c50d8ae3SPaolo Bonzini {
47485b7f575cSSean Christopherson 	u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
474984ea5c09SLai Jiangshan 	u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
4750c50d8ae3SPaolo Bonzini 	u64 bad_mt_xwr;
4751c50d8ae3SPaolo Bonzini 
475284ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_1G)
475384ea5c09SLai Jiangshan 		large_1g_rsvd = rsvd_bits(7, 7);
475484ea5c09SLai Jiangshan 	if (huge_page_level < PG_LEVEL_2M)
475584ea5c09SLai Jiangshan 		large_2m_rsvd = rsvd_bits(7, 7);
475684ea5c09SLai Jiangshan 
47575b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
47585b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
475984ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
476084ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
47615b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4762c50d8ae3SPaolo Bonzini 
4763c50d8ae3SPaolo Bonzini 	/* large page */
4764c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4765c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
476684ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
476784ea5c09SLai Jiangshan 	rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
4768c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4769c50d8ae3SPaolo Bonzini 
4770c50d8ae3SPaolo Bonzini 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
4771c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
4772c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
4773c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
4774c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
4775c50d8ae3SPaolo Bonzini 	if (!execonly) {
4776c50d8ae3SPaolo Bonzini 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
4777c50d8ae3SPaolo Bonzini 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4778c50d8ae3SPaolo Bonzini 	}
4779c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
4780c50d8ae3SPaolo Bonzini }
4781c50d8ae3SPaolo Bonzini 
4782c50d8ae3SPaolo Bonzini static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
478384ea5c09SLai Jiangshan 		struct kvm_mmu *context, bool execonly, int huge_page_level)
4784c50d8ae3SPaolo Bonzini {
4785c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
478684ea5c09SLai Jiangshan 				    vcpu->arch.reserved_gpa_bits, execonly,
478784ea5c09SLai Jiangshan 				    huge_page_level);
4788c50d8ae3SPaolo Bonzini }
4789c50d8ae3SPaolo Bonzini 
47906f8e65a6SSean Christopherson static inline u64 reserved_hpa_bits(void)
47916f8e65a6SSean Christopherson {
47926f8e65a6SSean Christopherson 	return rsvd_bits(shadow_phys_bits, 63);
47936f8e65a6SSean Christopherson }
47946f8e65a6SSean Christopherson 
4795c50d8ae3SPaolo Bonzini /*
4796c50d8ae3SPaolo Bonzini  * the page table on host is the shadow page table for the page
4797c50d8ae3SPaolo Bonzini  * table in guest or amd nested guest, its mmu features completely
4798c50d8ae3SPaolo Bonzini  * follow the features in guest.
4799c50d8ae3SPaolo Bonzini  */
480016be1d12SSean Christopherson static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
480116be1d12SSean Christopherson 					struct kvm_mmu *context)
4802c50d8ae3SPaolo Bonzini {
48038c985b2dSSean Christopherson 	/* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
48048c985b2dSSean Christopherson 	bool is_amd = true;
48058c985b2dSSean Christopherson 	/* KVM doesn't use 2-level page tables for the shadow MMU. */
48068c985b2dSSean Christopherson 	bool is_pse = false;
4807c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4808c50d8ae3SPaolo Bonzini 	int i;
4809c50d8ae3SPaolo Bonzini 
4810a972e29cSPaolo Bonzini 	WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
48118c985b2dSSean Christopherson 
4812c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4813b705a277SSean Christopherson 	__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4814a972e29cSPaolo Bonzini 				context->root_role.level,
48157a458f0eSPaolo Bonzini 				context->root_role.efer_nx,
481627de9250SSean Christopherson 				guest_can_use_gbpages(vcpu), is_pse, is_amd);
4817c50d8ae3SPaolo Bonzini 
4818c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4819c50d8ae3SPaolo Bonzini 		return;
4820c50d8ae3SPaolo Bonzini 
4821a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
4822e54f1ff2SKai Huang 		/*
4823e54f1ff2SKai Huang 		 * So far shadow_me_value is a constant during KVM's life
4824e54f1ff2SKai Huang 		 * time.  Bits in shadow_me_value are allowed to be set.
4825e54f1ff2SKai Huang 		 * Bits in shadow_me_mask but not in shadow_me_value are
4826e54f1ff2SKai Huang 		 * not allowed to be set.
4827e54f1ff2SKai Huang 		 */
4828e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
4829e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
4830e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
4831e54f1ff2SKai Huang 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
4832c50d8ae3SPaolo Bonzini 	}
4833c50d8ae3SPaolo Bonzini 
4834c50d8ae3SPaolo Bonzini }
4835c50d8ae3SPaolo Bonzini 
4836c50d8ae3SPaolo Bonzini static inline bool boot_cpu_is_amd(void)
4837c50d8ae3SPaolo Bonzini {
4838c50d8ae3SPaolo Bonzini 	WARN_ON_ONCE(!tdp_enabled);
4839c50d8ae3SPaolo Bonzini 	return shadow_x_mask == 0;
4840c50d8ae3SPaolo Bonzini }
4841c50d8ae3SPaolo Bonzini 
4842c50d8ae3SPaolo Bonzini /*
4843c50d8ae3SPaolo Bonzini  * the direct page table on host, use as much mmu features as
4844c50d8ae3SPaolo Bonzini  * possible, however, kvm currently does not do execution-protection.
4845c50d8ae3SPaolo Bonzini  */
4846c50d8ae3SPaolo Bonzini static void
4847e8f6e738SJinrong Liang reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
4848c50d8ae3SPaolo Bonzini {
4849c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4850c50d8ae3SPaolo Bonzini 	int i;
4851c50d8ae3SPaolo Bonzini 
4852c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4853c50d8ae3SPaolo Bonzini 
4854c50d8ae3SPaolo Bonzini 	if (boot_cpu_is_amd())
4855b705a277SSean Christopherson 		__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
48566c6ab524SSean Christopherson 					context->root_role.level, true,
4857c50d8ae3SPaolo Bonzini 					boot_cpu_has(X86_FEATURE_GBPAGES),
48588c985b2dSSean Christopherson 					false, true);
4859c50d8ae3SPaolo Bonzini 	else
4860c50d8ae3SPaolo Bonzini 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
486184ea5c09SLai Jiangshan 					    reserved_hpa_bits(), false,
486284ea5c09SLai Jiangshan 					    max_huge_page_level);
4863c50d8ae3SPaolo Bonzini 
4864c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4865c50d8ae3SPaolo Bonzini 		return;
4866c50d8ae3SPaolo Bonzini 
4867a972e29cSPaolo Bonzini 	for (i = context->root_role.level; --i >= 0;) {
4868c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4869c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4870c50d8ae3SPaolo Bonzini 	}
4871c50d8ae3SPaolo Bonzini }
4872c50d8ae3SPaolo Bonzini 
4873c50d8ae3SPaolo Bonzini /*
4874c50d8ae3SPaolo Bonzini  * as the comments in reset_shadow_zero_bits_mask() except it
4875c50d8ae3SPaolo Bonzini  * is the shadow page table for intel nested guest.
4876c50d8ae3SPaolo Bonzini  */
4877c50d8ae3SPaolo Bonzini static void
4878e8f6e738SJinrong Liang reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
4879c50d8ae3SPaolo Bonzini {
4880c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
488184ea5c09SLai Jiangshan 				    reserved_hpa_bits(), execonly,
488284ea5c09SLai Jiangshan 				    max_huge_page_level);
4883c50d8ae3SPaolo Bonzini }
4884c50d8ae3SPaolo Bonzini 
4885c50d8ae3SPaolo Bonzini #define BYTE_MASK(access) \
4886c50d8ae3SPaolo Bonzini 	((1 & (access) ? 2 : 0) | \
4887c50d8ae3SPaolo Bonzini 	 (2 & (access) ? 4 : 0) | \
4888c50d8ae3SPaolo Bonzini 	 (3 & (access) ? 8 : 0) | \
4889c50d8ae3SPaolo Bonzini 	 (4 & (access) ? 16 : 0) | \
4890c50d8ae3SPaolo Bonzini 	 (5 & (access) ? 32 : 0) | \
4891c50d8ae3SPaolo Bonzini 	 (6 & (access) ? 64 : 0) | \
4892c50d8ae3SPaolo Bonzini 	 (7 & (access) ? 128 : 0))
4893c50d8ae3SPaolo Bonzini 
4894c50d8ae3SPaolo Bonzini 
4895c596f147SSean Christopherson static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
4896c50d8ae3SPaolo Bonzini {
4897c50d8ae3SPaolo Bonzini 	unsigned byte;
4898c50d8ae3SPaolo Bonzini 
4899c50d8ae3SPaolo Bonzini 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4900c50d8ae3SPaolo Bonzini 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4901c50d8ae3SPaolo Bonzini 	const u8 u = BYTE_MASK(ACC_USER_MASK);
4902c50d8ae3SPaolo Bonzini 
4903c596f147SSean Christopherson 	bool cr4_smep = is_cr4_smep(mmu);
4904c596f147SSean Christopherson 	bool cr4_smap = is_cr4_smap(mmu);
4905c596f147SSean Christopherson 	bool cr0_wp = is_cr0_wp(mmu);
490690599c28SSean Christopherson 	bool efer_nx = is_efer_nx(mmu);
4907c50d8ae3SPaolo Bonzini 
4908c50d8ae3SPaolo Bonzini 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4909c50d8ae3SPaolo Bonzini 		unsigned pfec = byte << 1;
4910c50d8ae3SPaolo Bonzini 
4911c50d8ae3SPaolo Bonzini 		/*
4912c50d8ae3SPaolo Bonzini 		 * Each "*f" variable has a 1 bit for each UWX value
4913c50d8ae3SPaolo Bonzini 		 * that causes a fault with the given PFEC.
4914c50d8ae3SPaolo Bonzini 		 */
4915c50d8ae3SPaolo Bonzini 
4916c50d8ae3SPaolo Bonzini 		/* Faults from writes to non-writable pages */
4917c50d8ae3SPaolo Bonzini 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4918c50d8ae3SPaolo Bonzini 		/* Faults from user mode accesses to supervisor pages */
4919c50d8ae3SPaolo Bonzini 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4920c50d8ae3SPaolo Bonzini 		/* Faults from fetches of non-executable pages*/
4921c50d8ae3SPaolo Bonzini 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4922c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode fetches of user pages */
4923c50d8ae3SPaolo Bonzini 		u8 smepf = 0;
4924c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode accesses of user pages */
4925c50d8ae3SPaolo Bonzini 		u8 smapf = 0;
4926c50d8ae3SPaolo Bonzini 
4927c50d8ae3SPaolo Bonzini 		if (!ept) {
4928c50d8ae3SPaolo Bonzini 			/* Faults from kernel mode accesses to user pages */
4929c50d8ae3SPaolo Bonzini 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4930c50d8ae3SPaolo Bonzini 
4931c50d8ae3SPaolo Bonzini 			/* Not really needed: !nx will cause pte.nx to fault */
493290599c28SSean Christopherson 			if (!efer_nx)
4933c50d8ae3SPaolo Bonzini 				ff = 0;
4934c50d8ae3SPaolo Bonzini 
4935c50d8ae3SPaolo Bonzini 			/* Allow supervisor writes if !cr0.wp */
4936c50d8ae3SPaolo Bonzini 			if (!cr0_wp)
4937c50d8ae3SPaolo Bonzini 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4938c50d8ae3SPaolo Bonzini 
4939c50d8ae3SPaolo Bonzini 			/* Disallow supervisor fetches of user code if cr4.smep */
4940c50d8ae3SPaolo Bonzini 			if (cr4_smep)
4941c50d8ae3SPaolo Bonzini 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4942c50d8ae3SPaolo Bonzini 
4943c50d8ae3SPaolo Bonzini 			/*
4944c50d8ae3SPaolo Bonzini 			 * SMAP:kernel-mode data accesses from user-mode
4945c50d8ae3SPaolo Bonzini 			 * mappings should fault. A fault is considered
4946c50d8ae3SPaolo Bonzini 			 * as a SMAP violation if all of the following
4947c50d8ae3SPaolo Bonzini 			 * conditions are true:
4948c50d8ae3SPaolo Bonzini 			 *   - X86_CR4_SMAP is set in CR4
4949c50d8ae3SPaolo Bonzini 			 *   - A user page is accessed
4950c50d8ae3SPaolo Bonzini 			 *   - The access is not a fetch
49514f4aa80eSLai Jiangshan 			 *   - The access is supervisor mode
49524f4aa80eSLai Jiangshan 			 *   - If implicit supervisor access or X86_EFLAGS_AC is clear
4953c50d8ae3SPaolo Bonzini 			 *
495494b4a2f1SLai Jiangshan 			 * Here, we cover the first four conditions.
495594b4a2f1SLai Jiangshan 			 * The fifth is computed dynamically in permission_fault();
4956c50d8ae3SPaolo Bonzini 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4957c50d8ae3SPaolo Bonzini 			 * *not* subject to SMAP restrictions.
4958c50d8ae3SPaolo Bonzini 			 */
4959c50d8ae3SPaolo Bonzini 			if (cr4_smap)
4960c50d8ae3SPaolo Bonzini 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4961c50d8ae3SPaolo Bonzini 		}
4962c50d8ae3SPaolo Bonzini 
4963c50d8ae3SPaolo Bonzini 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4964c50d8ae3SPaolo Bonzini 	}
4965c50d8ae3SPaolo Bonzini }
4966c50d8ae3SPaolo Bonzini 
4967c50d8ae3SPaolo Bonzini /*
4968c50d8ae3SPaolo Bonzini * PKU is an additional mechanism by which the paging controls access to
4969c50d8ae3SPaolo Bonzini * user-mode addresses based on the value in the PKRU register.  Protection
4970c50d8ae3SPaolo Bonzini * key violations are reported through a bit in the page fault error code.
4971c50d8ae3SPaolo Bonzini * Unlike other bits of the error code, the PK bit is not known at the
4972c50d8ae3SPaolo Bonzini * call site of e.g. gva_to_gpa; it must be computed directly in
4973c50d8ae3SPaolo Bonzini * permission_fault based on two bits of PKRU, on some machine state (CR4,
4974c50d8ae3SPaolo Bonzini * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4975c50d8ae3SPaolo Bonzini *
4976c50d8ae3SPaolo Bonzini * In particular the following conditions come from the error code, the
4977c50d8ae3SPaolo Bonzini * page tables and the machine state:
4978c50d8ae3SPaolo Bonzini * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4979c50d8ae3SPaolo Bonzini * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4980c50d8ae3SPaolo Bonzini * - PK is always zero if U=0 in the page tables
4981c50d8ae3SPaolo Bonzini * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4982c50d8ae3SPaolo Bonzini *
4983c50d8ae3SPaolo Bonzini * The PKRU bitmask caches the result of these four conditions.  The error
4984c50d8ae3SPaolo Bonzini * code (minus the P bit) and the page table's U bit form an index into the
4985c50d8ae3SPaolo Bonzini * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
4986c50d8ae3SPaolo Bonzini * with the two bits of the PKRU register corresponding to the protection key.
4987c50d8ae3SPaolo Bonzini * For the first three conditions above the bits will be 00, thus masking
4988c50d8ae3SPaolo Bonzini * away both AD and WD.  For all reads or if the last condition holds, WD
4989c50d8ae3SPaolo Bonzini * only will be masked away.
4990c50d8ae3SPaolo Bonzini */
49912e4c0661SSean Christopherson static void update_pkru_bitmask(struct kvm_mmu *mmu)
4992c50d8ae3SPaolo Bonzini {
4993c50d8ae3SPaolo Bonzini 	unsigned bit;
4994c50d8ae3SPaolo Bonzini 	bool wp;
4995c50d8ae3SPaolo Bonzini 
4996c50d8ae3SPaolo Bonzini 	mmu->pkru_mask = 0;
4997a3ca5281SChenyi Qiang 
4998a3ca5281SChenyi Qiang 	if (!is_cr4_pke(mmu))
4999c50d8ae3SPaolo Bonzini 		return;
5000c50d8ae3SPaolo Bonzini 
50012e4c0661SSean Christopherson 	wp = is_cr0_wp(mmu);
5002c50d8ae3SPaolo Bonzini 
5003c50d8ae3SPaolo Bonzini 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5004c50d8ae3SPaolo Bonzini 		unsigned pfec, pkey_bits;
5005c50d8ae3SPaolo Bonzini 		bool check_pkey, check_write, ff, uf, wf, pte_user;
5006c50d8ae3SPaolo Bonzini 
5007c50d8ae3SPaolo Bonzini 		pfec = bit << 1;
5008c50d8ae3SPaolo Bonzini 		ff = pfec & PFERR_FETCH_MASK;
5009c50d8ae3SPaolo Bonzini 		uf = pfec & PFERR_USER_MASK;
5010c50d8ae3SPaolo Bonzini 		wf = pfec & PFERR_WRITE_MASK;
5011c50d8ae3SPaolo Bonzini 
5012c50d8ae3SPaolo Bonzini 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
5013c50d8ae3SPaolo Bonzini 		pte_user = pfec & PFERR_RSVD_MASK;
5014c50d8ae3SPaolo Bonzini 
5015c50d8ae3SPaolo Bonzini 		/*
5016c50d8ae3SPaolo Bonzini 		 * Only need to check the access which is not an
5017c50d8ae3SPaolo Bonzini 		 * instruction fetch and is to a user page.
5018c50d8ae3SPaolo Bonzini 		 */
5019c50d8ae3SPaolo Bonzini 		check_pkey = (!ff && pte_user);
5020c50d8ae3SPaolo Bonzini 		/*
5021c50d8ae3SPaolo Bonzini 		 * write access is controlled by PKRU if it is a
5022c50d8ae3SPaolo Bonzini 		 * user access or CR0.WP = 1.
5023c50d8ae3SPaolo Bonzini 		 */
5024c50d8ae3SPaolo Bonzini 		check_write = check_pkey && wf && (uf || wp);
5025c50d8ae3SPaolo Bonzini 
5026c50d8ae3SPaolo Bonzini 		/* PKRU.AD stops both read and write access. */
5027c50d8ae3SPaolo Bonzini 		pkey_bits = !!check_pkey;
5028c50d8ae3SPaolo Bonzini 		/* PKRU.WD stops write access. */
5029c50d8ae3SPaolo Bonzini 		pkey_bits |= (!!check_write) << 1;
5030c50d8ae3SPaolo Bonzini 
5031c50d8ae3SPaolo Bonzini 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5032c50d8ae3SPaolo Bonzini 	}
5033c50d8ae3SPaolo Bonzini }
5034c50d8ae3SPaolo Bonzini 
5035533f9a4bSSean Christopherson static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5036533f9a4bSSean Christopherson 					struct kvm_mmu *mmu)
5037c50d8ae3SPaolo Bonzini {
5038533f9a4bSSean Christopherson 	if (!is_cr0_pg(mmu))
5039533f9a4bSSean Christopherson 		return;
5040c50d8ae3SPaolo Bonzini 
5041c919e881SKai Huang 	reset_guest_rsvds_bits_mask(vcpu, mmu);
5042533f9a4bSSean Christopherson 	update_permission_bitmask(mmu, false);
5043533f9a4bSSean Christopherson 	update_pkru_bitmask(mmu);
5044c50d8ae3SPaolo Bonzini }
5045c50d8ae3SPaolo Bonzini 
5046fe660f72SSean Christopherson static void paging64_init_context(struct kvm_mmu *context)
5047c50d8ae3SPaolo Bonzini {
5048c50d8ae3SPaolo Bonzini 	context->page_fault = paging64_page_fault;
5049c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging64_gva_to_gpa;
5050c50d8ae3SPaolo Bonzini 	context->sync_page = paging64_sync_page;
5051c50d8ae3SPaolo Bonzini 	context->invlpg = paging64_invlpg;
5052c50d8ae3SPaolo Bonzini }
5053c50d8ae3SPaolo Bonzini 
505484a16226SSean Christopherson static void paging32_init_context(struct kvm_mmu *context)
5055c50d8ae3SPaolo Bonzini {
5056c50d8ae3SPaolo Bonzini 	context->page_fault = paging32_page_fault;
5057c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging32_gva_to_gpa;
5058c50d8ae3SPaolo Bonzini 	context->sync_page = paging32_sync_page;
5059c50d8ae3SPaolo Bonzini 	context->invlpg = paging32_invlpg;
5060c50d8ae3SPaolo Bonzini }
5061c50d8ae3SPaolo Bonzini 
50627a7ae829SPaolo Bonzini static union kvm_cpu_role
5063e5ed0fb0SPaolo Bonzini kvm_calc_cpu_role(struct kvm_vcpu *vcpu, const struct kvm_mmu_role_regs *regs)
5064e5ed0fb0SPaolo Bonzini {
50657a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5066e5ed0fb0SPaolo Bonzini 
5067e5ed0fb0SPaolo Bonzini 	role.base.access = ACC_ALL;
5068e5ed0fb0SPaolo Bonzini 	role.base.smm = is_smm(vcpu);
5069e5ed0fb0SPaolo Bonzini 	role.base.guest_mode = is_guest_mode(vcpu);
5070e5ed0fb0SPaolo Bonzini 	role.ext.valid = 1;
5071e5ed0fb0SPaolo Bonzini 
5072e5ed0fb0SPaolo Bonzini 	if (!____is_cr0_pg(regs)) {
5073e5ed0fb0SPaolo Bonzini 		role.base.direct = 1;
5074e5ed0fb0SPaolo Bonzini 		return role;
5075e5ed0fb0SPaolo Bonzini 	}
5076e5ed0fb0SPaolo Bonzini 
5077e5ed0fb0SPaolo Bonzini 	role.base.efer_nx = ____is_efer_nx(regs);
5078e5ed0fb0SPaolo Bonzini 	role.base.cr0_wp = ____is_cr0_wp(regs);
5079e5ed0fb0SPaolo Bonzini 	role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5080e5ed0fb0SPaolo Bonzini 	role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5081e5ed0fb0SPaolo Bonzini 	role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
508260f3cb60SPaolo Bonzini 
508360f3cb60SPaolo Bonzini 	if (____is_efer_lma(regs))
508460f3cb60SPaolo Bonzini 		role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
508560f3cb60SPaolo Bonzini 							: PT64_ROOT_4LEVEL;
508660f3cb60SPaolo Bonzini 	else if (____is_cr4_pae(regs))
508760f3cb60SPaolo Bonzini 		role.base.level = PT32E_ROOT_LEVEL;
508860f3cb60SPaolo Bonzini 	else
508960f3cb60SPaolo Bonzini 		role.base.level = PT32_ROOT_LEVEL;
5090e5ed0fb0SPaolo Bonzini 
5091e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smep = ____is_cr4_smep(regs);
5092e5ed0fb0SPaolo Bonzini 	role.ext.cr4_smap = ____is_cr4_smap(regs);
5093e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pse = ____is_cr4_pse(regs);
5094e5ed0fb0SPaolo Bonzini 
5095e5ed0fb0SPaolo Bonzini 	/* PKEY and LA57 are active iff long mode is active. */
5096e5ed0fb0SPaolo Bonzini 	role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5097e5ed0fb0SPaolo Bonzini 	role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5098e5ed0fb0SPaolo Bonzini 	role.ext.efer_lma = ____is_efer_lma(regs);
5099e5ed0fb0SPaolo Bonzini 	return role;
5100e5ed0fb0SPaolo Bonzini }
5101e5ed0fb0SPaolo Bonzini 
5102d468d94bSSean Christopherson static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5103d468d94bSSean Christopherson {
5104746700d2SWei Huang 	/* tdp_root_level is architecture forced level, use it if nonzero */
5105746700d2SWei Huang 	if (tdp_root_level)
5106746700d2SWei Huang 		return tdp_root_level;
5107746700d2SWei Huang 
5108d468d94bSSean Christopherson 	/* Use 5-level TDP if and only if it's useful/necessary. */
510983013059SSean Christopherson 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5110d468d94bSSean Christopherson 		return 4;
5111d468d94bSSean Christopherson 
511283013059SSean Christopherson 	return max_tdp_level;
5113d468d94bSSean Christopherson }
5114d468d94bSSean Christopherson 
51157a458f0eSPaolo Bonzini static union kvm_mmu_page_role
51168626c120SSean Christopherson kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
51177a7ae829SPaolo Bonzini 				union kvm_cpu_role cpu_role)
5118c50d8ae3SPaolo Bonzini {
51197a458f0eSPaolo Bonzini 	union kvm_mmu_page_role role = {0};
5120c50d8ae3SPaolo Bonzini 
51217a458f0eSPaolo Bonzini 	role.access = ACC_ALL;
51227a458f0eSPaolo Bonzini 	role.cr0_wp = true;
51237a458f0eSPaolo Bonzini 	role.efer_nx = true;
51247a458f0eSPaolo Bonzini 	role.smm = cpu_role.base.smm;
51257a458f0eSPaolo Bonzini 	role.guest_mode = cpu_role.base.guest_mode;
512654275f74SSean Christopherson 	role.ad_disabled = !kvm_ad_enabled();
51277a458f0eSPaolo Bonzini 	role.level = kvm_mmu_get_tdp_level(vcpu);
51287a458f0eSPaolo Bonzini 	role.direct = true;
51297a458f0eSPaolo Bonzini 	role.has_4_byte_gpte = false;
5130c50d8ae3SPaolo Bonzini 
5131c50d8ae3SPaolo Bonzini 	return role;
5132c50d8ae3SPaolo Bonzini }
5133c50d8ae3SPaolo Bonzini 
513439e7e2bfSPaolo Bonzini static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5135a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5136c50d8ae3SPaolo Bonzini {
51378c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
51387a458f0eSPaolo Bonzini 	union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5139c50d8ae3SPaolo Bonzini 
5140e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
51417a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
5142c50d8ae3SPaolo Bonzini 		return;
5143c50d8ae3SPaolo Bonzini 
5144e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
51457a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
51467a02674dSSean Christopherson 	context->page_fault = kvm_tdp_page_fault;
5147c50d8ae3SPaolo Bonzini 	context->sync_page = nonpaging_sync_page;
51485efac074SPaolo Bonzini 	context->invlpg = NULL;
5149d8dd54e0SSean Christopherson 	context->get_guest_pgd = get_cr3;
5150c50d8ae3SPaolo Bonzini 	context->get_pdptr = kvm_pdptr_read;
5151c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5152c50d8ae3SPaolo Bonzini 
515336f26787SSean Christopherson 	if (!is_cr0_pg(context))
5154c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = nonpaging_gva_to_gpa;
515536f26787SSean Christopherson 	else if (is_cr4_pae(context))
5156c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging64_gva_to_gpa;
5157f4bd6f73SSean Christopherson 	else
5158c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging32_gva_to_gpa;
5159c50d8ae3SPaolo Bonzini 
5160533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5161e8f6e738SJinrong Liang 	reset_tdp_shadow_zero_bits_mask(context);
5162c50d8ae3SPaolo Bonzini }
5163c50d8ae3SPaolo Bonzini 
51648c008659SPaolo Bonzini static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
51657a7ae829SPaolo Bonzini 				    union kvm_cpu_role cpu_role,
51667a458f0eSPaolo Bonzini 				    union kvm_mmu_page_role root_role)
5167c50d8ae3SPaolo Bonzini {
5168e5ed0fb0SPaolo Bonzini 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
51697a458f0eSPaolo Bonzini 	    root_role.word == context->root_role.word)
517018db1b17SSean Christopherson 		return;
5171c50d8ae3SPaolo Bonzini 
5172e5ed0fb0SPaolo Bonzini 	context->cpu_role.as_u64 = cpu_role.as_u64;
51737a458f0eSPaolo Bonzini 	context->root_role.word = root_role.word;
517418db1b17SSean Christopherson 
517536f26787SSean Christopherson 	if (!is_cr0_pg(context))
517684a16226SSean Christopherson 		nonpaging_init_context(context);
517736f26787SSean Christopherson 	else if (is_cr4_pae(context))
5178fe660f72SSean Christopherson 		paging64_init_context(context);
5179c50d8ae3SPaolo Bonzini 	else
518084a16226SSean Christopherson 		paging32_init_context(context);
5181c50d8ae3SPaolo Bonzini 
5182533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
5183c50d8ae3SPaolo Bonzini 	reset_shadow_zero_bits_mask(vcpu, context);
5184c50d8ae3SPaolo Bonzini }
51850f04a2acSVitaly Kuznetsov 
5186594e91a1SSean Christopherson static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5187a7f1de9bSPaolo Bonzini 				union kvm_cpu_role cpu_role)
51880f04a2acSVitaly Kuznetsov {
51898c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
519056b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
519156b321f9SPaolo Bonzini 
519256b321f9SPaolo Bonzini 	root_role = cpu_role.base;
519356b321f9SPaolo Bonzini 
519456b321f9SPaolo Bonzini 	/* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
519556b321f9SPaolo Bonzini 	root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
519656b321f9SPaolo Bonzini 
519756b321f9SPaolo Bonzini 	/*
519856b321f9SPaolo Bonzini 	 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
519956b321f9SPaolo Bonzini 	 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
520056b321f9SPaolo Bonzini 	 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
520156b321f9SPaolo Bonzini 	 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
520256b321f9SPaolo Bonzini 	 * The iTLB multi-hit workaround can be toggled at any time, so assume
520356b321f9SPaolo Bonzini 	 * NX can be used by any non-nested shadow MMU to avoid having to reset
520456b321f9SPaolo Bonzini 	 * MMU contexts.
520556b321f9SPaolo Bonzini 	 */
520656b321f9SPaolo Bonzini 	root_role.efer_nx = true;
52070f04a2acSVitaly Kuznetsov 
52087a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
52090f04a2acSVitaly Kuznetsov }
52100f04a2acSVitaly Kuznetsov 
5211dbc4739bSSean Christopherson void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5212dbc4739bSSean Christopherson 			     unsigned long cr4, u64 efer, gpa_t nested_cr3)
52130f04a2acSVitaly Kuznetsov {
52148c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5215594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
5216594e91a1SSean Christopherson 		.cr0 = cr0,
521728f091bcSPaolo Bonzini 		.cr4 = cr4 & ~X86_CR4_PKE,
5218594e91a1SSean Christopherson 		.efer = efer,
5219594e91a1SSean Christopherson 	};
52207a7ae829SPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
522156b321f9SPaolo Bonzini 	union kvm_mmu_page_role root_role;
522256b321f9SPaolo Bonzini 
522356b321f9SPaolo Bonzini 	/* NPT requires CR0.PG=1. */
522456b321f9SPaolo Bonzini 	WARN_ON_ONCE(cpu_role.base.direct);
522556b321f9SPaolo Bonzini 
522656b321f9SPaolo Bonzini 	root_role = cpu_role.base;
522756b321f9SPaolo Bonzini 	root_role.level = kvm_mmu_get_tdp_level(vcpu);
522884e5ffd0SLai Jiangshan 	if (root_role.level == PT64_ROOT_5LEVEL &&
522984e5ffd0SLai Jiangshan 	    cpu_role.base.level == PT64_ROOT_4LEVEL)
523084e5ffd0SLai Jiangshan 		root_role.passthrough = 1;
52310f04a2acSVitaly Kuznetsov 
52327a458f0eSPaolo Bonzini 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5233d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, nested_cr3);
52340f04a2acSVitaly Kuznetsov }
52350f04a2acSVitaly Kuznetsov EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5236c50d8ae3SPaolo Bonzini 
52377a7ae829SPaolo Bonzini static union kvm_cpu_role
5238c50d8ae3SPaolo Bonzini kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5239bb1fcc70SSean Christopherson 				   bool execonly, u8 level)
5240c50d8ae3SPaolo Bonzini {
52417a7ae829SPaolo Bonzini 	union kvm_cpu_role role = {0};
5242c50d8ae3SPaolo Bonzini 
5243daed87b8SPaolo Bonzini 	/*
5244daed87b8SPaolo Bonzini 	 * KVM does not support SMM transfer monitors, and consequently does not
5245daed87b8SPaolo Bonzini 	 * support the "entry to SMM" control either.  role.base.smm is always 0.
5246daed87b8SPaolo Bonzini 	 */
5247daed87b8SPaolo Bonzini 	WARN_ON_ONCE(is_smm(vcpu));
5248bb1fcc70SSean Christopherson 	role.base.level = level;
5249bb3b394dSLai Jiangshan 	role.base.has_4_byte_gpte = false;
5250c50d8ae3SPaolo Bonzini 	role.base.direct = false;
5251c50d8ae3SPaolo Bonzini 	role.base.ad_disabled = !accessed_dirty;
5252c50d8ae3SPaolo Bonzini 	role.base.guest_mode = true;
5253c50d8ae3SPaolo Bonzini 	role.base.access = ACC_ALL;
5254c50d8ae3SPaolo Bonzini 
5255cd6767c3SSean Christopherson 	role.ext.word = 0;
5256c50d8ae3SPaolo Bonzini 	role.ext.execonly = execonly;
5257cd6767c3SSean Christopherson 	role.ext.valid = 1;
5258c50d8ae3SPaolo Bonzini 
5259c50d8ae3SPaolo Bonzini 	return role;
5260c50d8ae3SPaolo Bonzini }
5261c50d8ae3SPaolo Bonzini 
5262c50d8ae3SPaolo Bonzini void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5263cc022ae1SLai Jiangshan 			     int huge_page_level, bool accessed_dirty,
5264cc022ae1SLai Jiangshan 			     gpa_t new_eptp)
5265c50d8ae3SPaolo Bonzini {
52668c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5267bb1fcc70SSean Christopherson 	u8 level = vmx_eptp_page_walk_level(new_eptp);
52687a7ae829SPaolo Bonzini 	union kvm_cpu_role new_mode =
5269c50d8ae3SPaolo Bonzini 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5270bb1fcc70SSean Christopherson 						   execonly, level);
5271c50d8ae3SPaolo Bonzini 
5272e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 != context->cpu_role.as_u64) {
5273e5ed0fb0SPaolo Bonzini 		/* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5274e5ed0fb0SPaolo Bonzini 		context->cpu_role.as_u64 = new_mode.as_u64;
52757a458f0eSPaolo Bonzini 		context->root_role.word = new_mode.base.word;
527618db1b17SSean Christopherson 
5277c50d8ae3SPaolo Bonzini 		context->page_fault = ept_page_fault;
5278c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = ept_gva_to_gpa;
5279c50d8ae3SPaolo Bonzini 		context->sync_page = ept_sync_page;
5280c50d8ae3SPaolo Bonzini 		context->invlpg = ept_invlpg;
5281347a0d0dSPaolo Bonzini 
5282c596f147SSean Christopherson 		update_permission_bitmask(context, true);
528328f091bcSPaolo Bonzini 		context->pkru_mask = 0;
5284cc022ae1SLai Jiangshan 		reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5285e8f6e738SJinrong Liang 		reset_ept_shadow_zero_bits_mask(context, execonly);
5286c50d8ae3SPaolo Bonzini 	}
52873cffc89dSPaolo Bonzini 
5288d2e5f333SPaolo Bonzini 	kvm_mmu_new_pgd(vcpu, new_eptp);
52893cffc89dSPaolo Bonzini }
5290c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5291c50d8ae3SPaolo Bonzini 
529239e7e2bfSPaolo Bonzini static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5293a7f1de9bSPaolo Bonzini 			     union kvm_cpu_role cpu_role)
5294c50d8ae3SPaolo Bonzini {
52958c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5296c50d8ae3SPaolo Bonzini 
5297a7f1de9bSPaolo Bonzini 	kvm_init_shadow_mmu(vcpu, cpu_role);
5298929d1cfaSPaolo Bonzini 
5299d8dd54e0SSean Christopherson 	context->get_guest_pgd     = get_cr3;
5300c50d8ae3SPaolo Bonzini 	context->get_pdptr         = kvm_pdptr_read;
5301c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
5302c50d8ae3SPaolo Bonzini }
5303c50d8ae3SPaolo Bonzini 
530439e7e2bfSPaolo Bonzini static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5305a7f1de9bSPaolo Bonzini 				union kvm_cpu_role new_mode)
5306c50d8ae3SPaolo Bonzini {
5307c50d8ae3SPaolo Bonzini 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5308c50d8ae3SPaolo Bonzini 
5309e5ed0fb0SPaolo Bonzini 	if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5310c50d8ae3SPaolo Bonzini 		return;
5311c50d8ae3SPaolo Bonzini 
5312e5ed0fb0SPaolo Bonzini 	g_context->cpu_role.as_u64   = new_mode.as_u64;
5313d8dd54e0SSean Christopherson 	g_context->get_guest_pgd     = get_cr3;
5314c50d8ae3SPaolo Bonzini 	g_context->get_pdptr         = kvm_pdptr_read;
5315c50d8ae3SPaolo Bonzini 	g_context->inject_page_fault = kvm_inject_page_fault;
5316c50d8ae3SPaolo Bonzini 
5317c50d8ae3SPaolo Bonzini 	/*
53185efac074SPaolo Bonzini 	 * L2 page tables are never shadowed, so there is no need to sync
53195efac074SPaolo Bonzini 	 * SPTEs.
53205efac074SPaolo Bonzini 	 */
53215efac074SPaolo Bonzini 	g_context->invlpg            = NULL;
53225efac074SPaolo Bonzini 
53235efac074SPaolo Bonzini 	/*
5324c50d8ae3SPaolo Bonzini 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5325c50d8ae3SPaolo Bonzini 	 * L1's nested page tables (e.g. EPT12). The nested translation
5326c50d8ae3SPaolo Bonzini 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5327c50d8ae3SPaolo Bonzini 	 * L2's page tables as the first level of translation and L1's
5328c50d8ae3SPaolo Bonzini 	 * nested page tables as the second level of translation. Basically
5329c50d8ae3SPaolo Bonzini 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5330c50d8ae3SPaolo Bonzini 	 */
5331fa4b5588SSean Christopherson 	if (!is_paging(vcpu))
53321f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5333fa4b5588SSean Christopherson 	else if (is_long_mode(vcpu))
53341f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5335fa4b5588SSean Christopherson 	else if (is_pae(vcpu))
53361f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5337fa4b5588SSean Christopherson 	else
53381f5a21eeSLai Jiangshan 		g_context->gva_to_gpa = paging32_gva_to_gpa;
5339fa4b5588SSean Christopherson 
5340533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, g_context);
5341c50d8ae3SPaolo Bonzini }
5342c50d8ae3SPaolo Bonzini 
5343c9060662SSean Christopherson void kvm_init_mmu(struct kvm_vcpu *vcpu)
5344c50d8ae3SPaolo Bonzini {
534539e7e2bfSPaolo Bonzini 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5346a7f1de9bSPaolo Bonzini 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
534739e7e2bfSPaolo Bonzini 
5348c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
5349a7f1de9bSPaolo Bonzini 		init_kvm_nested_mmu(vcpu, cpu_role);
5350c50d8ae3SPaolo Bonzini 	else if (tdp_enabled)
5351a7f1de9bSPaolo Bonzini 		init_kvm_tdp_mmu(vcpu, cpu_role);
5352c50d8ae3SPaolo Bonzini 	else
5353a7f1de9bSPaolo Bonzini 		init_kvm_softmmu(vcpu, cpu_role);
5354c50d8ae3SPaolo Bonzini }
5355c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_mmu);
5356c50d8ae3SPaolo Bonzini 
535749c6f875SSean Christopherson void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
535849c6f875SSean Christopherson {
535949c6f875SSean Christopherson 	/*
536049c6f875SSean Christopherson 	 * Invalidate all MMU roles to force them to reinitialize as CPUID
536149c6f875SSean Christopherson 	 * information is factored into reserved bit calculations.
5362feb627e8SVitaly Kuznetsov 	 *
5363feb627e8SVitaly Kuznetsov 	 * Correctly handling multiple vCPU models with respect to paging and
5364feb627e8SVitaly Kuznetsov 	 * physical address properties) in a single VM would require tracking
5365feb627e8SVitaly Kuznetsov 	 * all relevant CPUID information in kvm_mmu_page_role. That is very
5366feb627e8SVitaly Kuznetsov 	 * undesirable as it would increase the memory requirements for
5367feb627e8SVitaly Kuznetsov 	 * gfn_track (see struct kvm_mmu_page_role comments).  For now that
5368feb627e8SVitaly Kuznetsov 	 * problem is swept under the rug; KVM's CPUID API is horrific and
5369feb627e8SVitaly Kuznetsov 	 * it's all but impossible to solve it without introducing a new API.
537049c6f875SSean Christopherson 	 */
53717a458f0eSPaolo Bonzini 	vcpu->arch.root_mmu.root_role.word = 0;
53727a458f0eSPaolo Bonzini 	vcpu->arch.guest_mmu.root_role.word = 0;
53737a458f0eSPaolo Bonzini 	vcpu->arch.nested_mmu.root_role.word = 0;
5374e5ed0fb0SPaolo Bonzini 	vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5375e5ed0fb0SPaolo Bonzini 	vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5376e5ed0fb0SPaolo Bonzini 	vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
537749c6f875SSean Christopherson 	kvm_mmu_reset_context(vcpu);
537863f5a190SSean Christopherson 
537963f5a190SSean Christopherson 	/*
5380feb627e8SVitaly Kuznetsov 	 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5381feb627e8SVitaly Kuznetsov 	 * kvm_arch_vcpu_ioctl().
538263f5a190SSean Christopherson 	 */
5383feb627e8SVitaly Kuznetsov 	KVM_BUG_ON(vcpu->arch.last_vmentry_cpu != -1, vcpu->kvm);
538449c6f875SSean Christopherson }
538549c6f875SSean Christopherson 
5386c50d8ae3SPaolo Bonzini void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5387c50d8ae3SPaolo Bonzini {
5388c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
5389c9060662SSean Christopherson 	kvm_init_mmu(vcpu);
5390c50d8ae3SPaolo Bonzini }
5391c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5392c50d8ae3SPaolo Bonzini 
5393c50d8ae3SPaolo Bonzini int kvm_mmu_load(struct kvm_vcpu *vcpu)
5394c50d8ae3SPaolo Bonzini {
5395c50d8ae3SPaolo Bonzini 	int r;
5396c50d8ae3SPaolo Bonzini 
5397347a0d0dSPaolo Bonzini 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5398c50d8ae3SPaolo Bonzini 	if (r)
5399c50d8ae3SPaolo Bonzini 		goto out;
5400748e52b9SSean Christopherson 	r = mmu_alloc_special_roots(vcpu);
5401c50d8ae3SPaolo Bonzini 	if (r)
5402c50d8ae3SPaolo Bonzini 		goto out;
5403347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct)
54046e6ec584SSean Christopherson 		r = mmu_alloc_direct_roots(vcpu);
54056e6ec584SSean Christopherson 	else
54066e6ec584SSean Christopherson 		r = mmu_alloc_shadow_roots(vcpu);
5407c50d8ae3SPaolo Bonzini 	if (r)
5408c50d8ae3SPaolo Bonzini 		goto out;
5409a91f387bSSean Christopherson 
5410a91f387bSSean Christopherson 	kvm_mmu_sync_roots(vcpu);
5411a91f387bSSean Christopherson 
5412727a7e27SPaolo Bonzini 	kvm_mmu_load_pgd(vcpu);
5413db01416bSSean Christopherson 
5414db01416bSSean Christopherson 	/*
5415db01416bSSean Christopherson 	 * Flush any TLB entries for the new root, the provenance of the root
5416db01416bSSean Christopherson 	 * is unknown.  Even if KVM ensures there are no stale TLB entries
5417db01416bSSean Christopherson 	 * for a freed root, in theory another hypervisor could have left
5418db01416bSSean Christopherson 	 * stale entries.  Flushing on alloc also allows KVM to skip the TLB
5419db01416bSSean Christopherson 	 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5420db01416bSSean Christopherson 	 */
5421e27bc044SSean Christopherson 	static_call(kvm_x86_flush_tlb_current)(vcpu);
5422c50d8ae3SPaolo Bonzini out:
5423c50d8ae3SPaolo Bonzini 	return r;
5424c50d8ae3SPaolo Bonzini }
5425c50d8ae3SPaolo Bonzini 
5426c50d8ae3SPaolo Bonzini void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5427c50d8ae3SPaolo Bonzini {
54280c1c92f1SPaolo Bonzini 	struct kvm *kvm = vcpu->kvm;
54290c1c92f1SPaolo Bonzini 
54300c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5431b9e5603cSPaolo Bonzini 	WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
54320c1c92f1SPaolo Bonzini 	kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5433b9e5603cSPaolo Bonzini 	WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
54346d58f275SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5435c50d8ae3SPaolo Bonzini }
5436c50d8ae3SPaolo Bonzini 
5437527d5cd7SSean Christopherson static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5438527d5cd7SSean Christopherson {
5439527d5cd7SSean Christopherson 	struct kvm_mmu_page *sp;
5440527d5cd7SSean Christopherson 
5441527d5cd7SSean Christopherson 	if (!VALID_PAGE(root_hpa))
5442527d5cd7SSean Christopherson 		return false;
5443527d5cd7SSean Christopherson 
5444527d5cd7SSean Christopherson 	/*
5445527d5cd7SSean Christopherson 	 * When freeing obsolete roots, treat roots as obsolete if they don't
5446527d5cd7SSean Christopherson 	 * have an associated shadow page.  This does mean KVM will get false
5447527d5cd7SSean Christopherson 	 * positives and free roots that don't strictly need to be freed, but
5448527d5cd7SSean Christopherson 	 * such false positives are relatively rare:
5449527d5cd7SSean Christopherson 	 *
5450527d5cd7SSean Christopherson 	 *  (a) only PAE paging and nested NPT has roots without shadow pages
5451527d5cd7SSean Christopherson 	 *  (b) remote reloads due to a memslot update obsoletes _all_ roots
5452527d5cd7SSean Christopherson 	 *  (c) KVM doesn't track previous roots for PAE paging, and the guest
5453527d5cd7SSean Christopherson 	 *      is unlikely to zap an in-use PGD.
5454527d5cd7SSean Christopherson 	 */
5455527d5cd7SSean Christopherson 	sp = to_shadow_page(root_hpa);
5456527d5cd7SSean Christopherson 	return !sp || is_obsolete_sp(kvm, sp);
5457527d5cd7SSean Christopherson }
5458527d5cd7SSean Christopherson 
5459527d5cd7SSean Christopherson static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5460527d5cd7SSean Christopherson {
5461527d5cd7SSean Christopherson 	unsigned long roots_to_free = 0;
5462527d5cd7SSean Christopherson 	int i;
5463527d5cd7SSean Christopherson 
5464527d5cd7SSean Christopherson 	if (is_obsolete_root(kvm, mmu->root.hpa))
5465527d5cd7SSean Christopherson 		roots_to_free |= KVM_MMU_ROOT_CURRENT;
5466527d5cd7SSean Christopherson 
5467527d5cd7SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5468cf4a8693SShaoqin Huang 		if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5469527d5cd7SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5470527d5cd7SSean Christopherson 	}
5471527d5cd7SSean Christopherson 
5472527d5cd7SSean Christopherson 	if (roots_to_free)
5473527d5cd7SSean Christopherson 		kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5474527d5cd7SSean Christopherson }
5475527d5cd7SSean Christopherson 
5476527d5cd7SSean Christopherson void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5477527d5cd7SSean Christopherson {
5478527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5479527d5cd7SSean Christopherson 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5480527d5cd7SSean Christopherson }
5481527d5cd7SSean Christopherson 
5482c50d8ae3SPaolo Bonzini static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5483c50d8ae3SPaolo Bonzini 				    int *bytes)
5484c50d8ae3SPaolo Bonzini {
5485c50d8ae3SPaolo Bonzini 	u64 gentry = 0;
5486c50d8ae3SPaolo Bonzini 	int r;
5487c50d8ae3SPaolo Bonzini 
5488c50d8ae3SPaolo Bonzini 	/*
5489c50d8ae3SPaolo Bonzini 	 * Assume that the pte write on a page table of the same type
5490c50d8ae3SPaolo Bonzini 	 * as the current vcpu paging mode since we update the sptes only
5491c50d8ae3SPaolo Bonzini 	 * when they have the same mode.
5492c50d8ae3SPaolo Bonzini 	 */
5493c50d8ae3SPaolo Bonzini 	if (is_pae(vcpu) && *bytes == 4) {
5494c50d8ae3SPaolo Bonzini 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5495c50d8ae3SPaolo Bonzini 		*gpa &= ~(gpa_t)7;
5496c50d8ae3SPaolo Bonzini 		*bytes = 8;
5497c50d8ae3SPaolo Bonzini 	}
5498c50d8ae3SPaolo Bonzini 
5499c50d8ae3SPaolo Bonzini 	if (*bytes == 4 || *bytes == 8) {
5500c50d8ae3SPaolo Bonzini 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5501c50d8ae3SPaolo Bonzini 		if (r)
5502c50d8ae3SPaolo Bonzini 			gentry = 0;
5503c50d8ae3SPaolo Bonzini 	}
5504c50d8ae3SPaolo Bonzini 
5505c50d8ae3SPaolo Bonzini 	return gentry;
5506c50d8ae3SPaolo Bonzini }
5507c50d8ae3SPaolo Bonzini 
5508c50d8ae3SPaolo Bonzini /*
5509c50d8ae3SPaolo Bonzini  * If we're seeing too many writes to a page, it may no longer be a page table,
5510c50d8ae3SPaolo Bonzini  * or we may be forking, in which case it is better to unmap the page.
5511c50d8ae3SPaolo Bonzini  */
5512c50d8ae3SPaolo Bonzini static bool detect_write_flooding(struct kvm_mmu_page *sp)
5513c50d8ae3SPaolo Bonzini {
5514c50d8ae3SPaolo Bonzini 	/*
5515c50d8ae3SPaolo Bonzini 	 * Skip write-flooding detected for the sp whose level is 1, because
5516c50d8ae3SPaolo Bonzini 	 * it can become unsync, then the guest page is not write-protected.
5517c50d8ae3SPaolo Bonzini 	 */
55183bae0459SSean Christopherson 	if (sp->role.level == PG_LEVEL_4K)
5519c50d8ae3SPaolo Bonzini 		return false;
5520c50d8ae3SPaolo Bonzini 
5521c50d8ae3SPaolo Bonzini 	atomic_inc(&sp->write_flooding_count);
5522c50d8ae3SPaolo Bonzini 	return atomic_read(&sp->write_flooding_count) >= 3;
5523c50d8ae3SPaolo Bonzini }
5524c50d8ae3SPaolo Bonzini 
5525c50d8ae3SPaolo Bonzini /*
5526c50d8ae3SPaolo Bonzini  * Misaligned accesses are too much trouble to fix up; also, they usually
5527c50d8ae3SPaolo Bonzini  * indicate a page is not used as a page table.
5528c50d8ae3SPaolo Bonzini  */
5529c50d8ae3SPaolo Bonzini static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5530c50d8ae3SPaolo Bonzini 				    int bytes)
5531c50d8ae3SPaolo Bonzini {
5532c50d8ae3SPaolo Bonzini 	unsigned offset, pte_size, misaligned;
5533c50d8ae3SPaolo Bonzini 
5534c50d8ae3SPaolo Bonzini 	pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5535c50d8ae3SPaolo Bonzini 		 gpa, bytes, sp->role.word);
5536c50d8ae3SPaolo Bonzini 
5537c50d8ae3SPaolo Bonzini 	offset = offset_in_page(gpa);
5538bb3b394dSLai Jiangshan 	pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5539c50d8ae3SPaolo Bonzini 
5540c50d8ae3SPaolo Bonzini 	/*
5541c50d8ae3SPaolo Bonzini 	 * Sometimes, the OS only writes the last one bytes to update status
5542c50d8ae3SPaolo Bonzini 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5543c50d8ae3SPaolo Bonzini 	 */
5544c50d8ae3SPaolo Bonzini 	if (!(offset & (pte_size - 1)) && bytes == 1)
5545c50d8ae3SPaolo Bonzini 		return false;
5546c50d8ae3SPaolo Bonzini 
5547c50d8ae3SPaolo Bonzini 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5548c50d8ae3SPaolo Bonzini 	misaligned |= bytes < 4;
5549c50d8ae3SPaolo Bonzini 
5550c50d8ae3SPaolo Bonzini 	return misaligned;
5551c50d8ae3SPaolo Bonzini }
5552c50d8ae3SPaolo Bonzini 
5553c50d8ae3SPaolo Bonzini static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5554c50d8ae3SPaolo Bonzini {
5555c50d8ae3SPaolo Bonzini 	unsigned page_offset, quadrant;
5556c50d8ae3SPaolo Bonzini 	u64 *spte;
5557c50d8ae3SPaolo Bonzini 	int level;
5558c50d8ae3SPaolo Bonzini 
5559c50d8ae3SPaolo Bonzini 	page_offset = offset_in_page(gpa);
5560c50d8ae3SPaolo Bonzini 	level = sp->role.level;
5561c50d8ae3SPaolo Bonzini 	*nspte = 1;
5562bb3b394dSLai Jiangshan 	if (sp->role.has_4_byte_gpte) {
5563c50d8ae3SPaolo Bonzini 		page_offset <<= 1;	/* 32->64 */
5564c50d8ae3SPaolo Bonzini 		/*
5565c50d8ae3SPaolo Bonzini 		 * A 32-bit pde maps 4MB while the shadow pdes map
5566c50d8ae3SPaolo Bonzini 		 * only 2MB.  So we need to double the offset again
5567c50d8ae3SPaolo Bonzini 		 * and zap two pdes instead of one.
5568c50d8ae3SPaolo Bonzini 		 */
5569c50d8ae3SPaolo Bonzini 		if (level == PT32_ROOT_LEVEL) {
5570c50d8ae3SPaolo Bonzini 			page_offset &= ~7; /* kill rounding error */
5571c50d8ae3SPaolo Bonzini 			page_offset <<= 1;
5572c50d8ae3SPaolo Bonzini 			*nspte = 2;
5573c50d8ae3SPaolo Bonzini 		}
5574c50d8ae3SPaolo Bonzini 		quadrant = page_offset >> PAGE_SHIFT;
5575c50d8ae3SPaolo Bonzini 		page_offset &= ~PAGE_MASK;
5576c50d8ae3SPaolo Bonzini 		if (quadrant != sp->role.quadrant)
5577c50d8ae3SPaolo Bonzini 			return NULL;
5578c50d8ae3SPaolo Bonzini 	}
5579c50d8ae3SPaolo Bonzini 
5580c50d8ae3SPaolo Bonzini 	spte = &sp->spt[page_offset / sizeof(*spte)];
5581c50d8ae3SPaolo Bonzini 	return spte;
5582c50d8ae3SPaolo Bonzini }
5583c50d8ae3SPaolo Bonzini 
5584c50d8ae3SPaolo Bonzini static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5585c50d8ae3SPaolo Bonzini 			      const u8 *new, int bytes,
5586c50d8ae3SPaolo Bonzini 			      struct kvm_page_track_notifier_node *node)
5587c50d8ae3SPaolo Bonzini {
5588c50d8ae3SPaolo Bonzini 	gfn_t gfn = gpa >> PAGE_SHIFT;
5589c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
5590c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
5591c50d8ae3SPaolo Bonzini 	u64 entry, gentry, *spte;
5592c50d8ae3SPaolo Bonzini 	int npte;
559306152b2dSLai Jiangshan 	bool flush = false;
5594c50d8ae3SPaolo Bonzini 
5595c50d8ae3SPaolo Bonzini 	/*
5596c50d8ae3SPaolo Bonzini 	 * If we don't have indirect shadow pages, it means no page is
5597c50d8ae3SPaolo Bonzini 	 * write-protected, so we can exit simply.
5598c50d8ae3SPaolo Bonzini 	 */
5599c50d8ae3SPaolo Bonzini 	if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5600c50d8ae3SPaolo Bonzini 		return;
5601c50d8ae3SPaolo Bonzini 
5602c50d8ae3SPaolo Bonzini 	pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5603c50d8ae3SPaolo Bonzini 
5604531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
5605c50d8ae3SPaolo Bonzini 
5606c50d8ae3SPaolo Bonzini 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5607c50d8ae3SPaolo Bonzini 
5608c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_pte_write;
5609c50d8ae3SPaolo Bonzini 
5610767d8d8dSLai Jiangshan 	for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5611c50d8ae3SPaolo Bonzini 		if (detect_write_misaligned(sp, gpa, bytes) ||
5612c50d8ae3SPaolo Bonzini 		      detect_write_flooding(sp)) {
5613c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5614c50d8ae3SPaolo Bonzini 			++vcpu->kvm->stat.mmu_flooded;
5615c50d8ae3SPaolo Bonzini 			continue;
5616c50d8ae3SPaolo Bonzini 		}
5617c50d8ae3SPaolo Bonzini 
5618c50d8ae3SPaolo Bonzini 		spte = get_written_sptes(sp, gpa, &npte);
5619c50d8ae3SPaolo Bonzini 		if (!spte)
5620c50d8ae3SPaolo Bonzini 			continue;
5621c50d8ae3SPaolo Bonzini 
5622c50d8ae3SPaolo Bonzini 		while (npte--) {
5623c50d8ae3SPaolo Bonzini 			entry = *spte;
56242de4085cSBen Gardon 			mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5625c5e2184dSSean Christopherson 			if (gentry && sp->role.level != PG_LEVEL_4K)
5626c5e2184dSSean Christopherson 				++vcpu->kvm->stat.mmu_pde_zapped;
56271441ca14SJunaid Shahid 			if (is_shadow_present_pte(entry))
562806152b2dSLai Jiangshan 				flush = true;
5629c50d8ae3SPaolo Bonzini 			++spte;
5630c50d8ae3SPaolo Bonzini 		}
5631c50d8ae3SPaolo Bonzini 	}
563206152b2dSLai Jiangshan 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5633531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
5634c50d8ae3SPaolo Bonzini }
5635c50d8ae3SPaolo Bonzini 
56361075d41eSSean Christopherson int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5637c50d8ae3SPaolo Bonzini 		       void *insn, int insn_len)
5638c50d8ae3SPaolo Bonzini {
563992daa48bSSean Christopherson 	int r, emulation_type = EMULTYPE_PF;
5640347a0d0dSPaolo Bonzini 	bool direct = vcpu->arch.mmu->root_role.direct;
5641c50d8ae3SPaolo Bonzini 
5642b9e5603cSPaolo Bonzini 	if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5643ddce6208SSean Christopherson 		return RET_PF_RETRY;
5644ddce6208SSean Christopherson 
5645c50d8ae3SPaolo Bonzini 	r = RET_PF_INVALID;
5646c50d8ae3SPaolo Bonzini 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
5647736c291cSSean Christopherson 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5648c50d8ae3SPaolo Bonzini 		if (r == RET_PF_EMULATE)
5649c50d8ae3SPaolo Bonzini 			goto emulate;
5650c50d8ae3SPaolo Bonzini 	}
5651c50d8ae3SPaolo Bonzini 
5652c50d8ae3SPaolo Bonzini 	if (r == RET_PF_INVALID) {
56537a02674dSSean Christopherson 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
56547a02674dSSean Christopherson 					  lower_32_bits(error_code), false);
565519025e7bSSean Christopherson 		if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
56567b367bc9SSean Christopherson 			return -EIO;
5657c50d8ae3SPaolo Bonzini 	}
5658c50d8ae3SPaolo Bonzini 
5659c50d8ae3SPaolo Bonzini 	if (r < 0)
5660c50d8ae3SPaolo Bonzini 		return r;
566183a2ba4cSSean Christopherson 	if (r != RET_PF_EMULATE)
566283a2ba4cSSean Christopherson 		return 1;
5663c50d8ae3SPaolo Bonzini 
5664c50d8ae3SPaolo Bonzini 	/*
5665c50d8ae3SPaolo Bonzini 	 * Before emulating the instruction, check if the error code
5666c50d8ae3SPaolo Bonzini 	 * was due to a RO violation while translating the guest page.
5667c50d8ae3SPaolo Bonzini 	 * This can occur when using nested virtualization with nested
5668c50d8ae3SPaolo Bonzini 	 * paging in both guests. If true, we simply unprotect the page
5669c50d8ae3SPaolo Bonzini 	 * and resume the guest.
5670c50d8ae3SPaolo Bonzini 	 */
5671347a0d0dSPaolo Bonzini 	if (vcpu->arch.mmu->root_role.direct &&
5672c50d8ae3SPaolo Bonzini 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5673736c291cSSean Christopherson 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5674c50d8ae3SPaolo Bonzini 		return 1;
5675c50d8ae3SPaolo Bonzini 	}
5676c50d8ae3SPaolo Bonzini 
5677c50d8ae3SPaolo Bonzini 	/*
5678c50d8ae3SPaolo Bonzini 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5679c50d8ae3SPaolo Bonzini 	 * optimistically try to just unprotect the page and let the processor
5680c50d8ae3SPaolo Bonzini 	 * re-execute the instruction that caused the page fault.  Do not allow
5681c50d8ae3SPaolo Bonzini 	 * retrying MMIO emulation, as it's not only pointless but could also
5682c50d8ae3SPaolo Bonzini 	 * cause us to enter an infinite loop because the processor will keep
5683c50d8ae3SPaolo Bonzini 	 * faulting on the non-existent MMIO address.  Retrying an instruction
5684c50d8ae3SPaolo Bonzini 	 * from a nested guest is also pointless and dangerous as we are only
5685c50d8ae3SPaolo Bonzini 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
5686c50d8ae3SPaolo Bonzini 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5687c50d8ae3SPaolo Bonzini 	 */
5688736c291cSSean Christopherson 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
568992daa48bSSean Christopherson 		emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5690c50d8ae3SPaolo Bonzini emulate:
5691736c291cSSean Christopherson 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5692c50d8ae3SPaolo Bonzini 				       insn_len);
5693c50d8ae3SPaolo Bonzini }
5694c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5695c50d8ae3SPaolo Bonzini 
56965efac074SPaolo Bonzini void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
56975efac074SPaolo Bonzini 			    gva_t gva, hpa_t root_hpa)
5698c50d8ae3SPaolo Bonzini {
5699c50d8ae3SPaolo Bonzini 	int i;
5700c50d8ae3SPaolo Bonzini 
57015efac074SPaolo Bonzini 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
57025efac074SPaolo Bonzini 	if (mmu != &vcpu->arch.guest_mmu) {
57035efac074SPaolo Bonzini 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
5704c50d8ae3SPaolo Bonzini 		if (is_noncanonical_address(gva, vcpu))
5705c50d8ae3SPaolo Bonzini 			return;
5706c50d8ae3SPaolo Bonzini 
5707e27bc044SSean Christopherson 		static_call(kvm_x86_flush_tlb_gva)(vcpu, gva);
57085efac074SPaolo Bonzini 	}
57095efac074SPaolo Bonzini 
57105efac074SPaolo Bonzini 	if (!mmu->invlpg)
57115efac074SPaolo Bonzini 		return;
57125efac074SPaolo Bonzini 
57135efac074SPaolo Bonzini 	if (root_hpa == INVALID_PAGE) {
5714b9e5603cSPaolo Bonzini 		mmu->invlpg(vcpu, gva, mmu->root.hpa);
5715c50d8ae3SPaolo Bonzini 
5716c50d8ae3SPaolo Bonzini 		/*
5717c50d8ae3SPaolo Bonzini 		 * INVLPG is required to invalidate any global mappings for the VA,
5718c50d8ae3SPaolo Bonzini 		 * irrespective of PCID. Since it would take us roughly similar amount
5719c50d8ae3SPaolo Bonzini 		 * of work to determine whether any of the prev_root mappings of the VA
5720c50d8ae3SPaolo Bonzini 		 * is marked global, or to just sync it blindly, so we might as well
5721c50d8ae3SPaolo Bonzini 		 * just always sync it.
5722c50d8ae3SPaolo Bonzini 		 *
5723c50d8ae3SPaolo Bonzini 		 * Mappings not reachable via the current cr3 or the prev_roots will be
5724c50d8ae3SPaolo Bonzini 		 * synced when switching to that cr3, so nothing needs to be done here
5725c50d8ae3SPaolo Bonzini 		 * for them.
5726c50d8ae3SPaolo Bonzini 		 */
5727c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5728c50d8ae3SPaolo Bonzini 			if (VALID_PAGE(mmu->prev_roots[i].hpa))
5729c50d8ae3SPaolo Bonzini 				mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
57305efac074SPaolo Bonzini 	} else {
57315efac074SPaolo Bonzini 		mmu->invlpg(vcpu, gva, root_hpa);
57325efac074SPaolo Bonzini 	}
57335efac074SPaolo Bonzini }
5734c50d8ae3SPaolo Bonzini 
57355efac074SPaolo Bonzini void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
57365efac074SPaolo Bonzini {
573705b29633SLai Jiangshan 	kvm_mmu_invalidate_gva(vcpu, vcpu->arch.walk_mmu, gva, INVALID_PAGE);
5738c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5739c50d8ae3SPaolo Bonzini }
5740c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5741c50d8ae3SPaolo Bonzini 
57425efac074SPaolo Bonzini 
5743c50d8ae3SPaolo Bonzini void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5744c50d8ae3SPaolo Bonzini {
5745c50d8ae3SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
5746c50d8ae3SPaolo Bonzini 	bool tlb_flush = false;
5747c50d8ae3SPaolo Bonzini 	uint i;
5748c50d8ae3SPaolo Bonzini 
5749c50d8ae3SPaolo Bonzini 	if (pcid == kvm_get_active_pcid(vcpu)) {
57509f46c187SPaolo Bonzini 		if (mmu->invlpg)
5751b9e5603cSPaolo Bonzini 			mmu->invlpg(vcpu, gva, mmu->root.hpa);
5752c50d8ae3SPaolo Bonzini 		tlb_flush = true;
5753c50d8ae3SPaolo Bonzini 	}
5754c50d8ae3SPaolo Bonzini 
5755c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5756c50d8ae3SPaolo Bonzini 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5757be01e8e2SSean Christopherson 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
57589f46c187SPaolo Bonzini 			if (mmu->invlpg)
5759c50d8ae3SPaolo Bonzini 				mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5760c50d8ae3SPaolo Bonzini 			tlb_flush = true;
5761c50d8ae3SPaolo Bonzini 		}
5762c50d8ae3SPaolo Bonzini 	}
5763c50d8ae3SPaolo Bonzini 
5764c50d8ae3SPaolo Bonzini 	if (tlb_flush)
5765e27bc044SSean Christopherson 		static_call(kvm_x86_flush_tlb_gva)(vcpu, gva);
5766c50d8ae3SPaolo Bonzini 
5767c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5768c50d8ae3SPaolo Bonzini 
5769c50d8ae3SPaolo Bonzini 	/*
5770c50d8ae3SPaolo Bonzini 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5771c50d8ae3SPaolo Bonzini 	 * synced when switching to that cr3, so nothing needs to be done here
5772c50d8ae3SPaolo Bonzini 	 * for them.
5773c50d8ae3SPaolo Bonzini 	 */
5774c50d8ae3SPaolo Bonzini }
5775c50d8ae3SPaolo Bonzini 
5776746700d2SWei Huang void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
5777746700d2SWei Huang 		       int tdp_max_root_level, int tdp_huge_page_level)
5778c50d8ae3SPaolo Bonzini {
5779bde77235SSean Christopherson 	tdp_enabled = enable_tdp;
5780746700d2SWei Huang 	tdp_root_level = tdp_forced_root_level;
578183013059SSean Christopherson 	max_tdp_level = tdp_max_root_level;
5782703c335dSSean Christopherson 
57831f98f2bdSDavid Matlack #ifdef CONFIG_X86_64
57841f98f2bdSDavid Matlack 	tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
57851f98f2bdSDavid Matlack #endif
5786703c335dSSean Christopherson 	/*
57871d92d2e8SSean Christopherson 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5788703c335dSSean Christopherson 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5789703c335dSSean Christopherson 	 * the kernel is not.  But, KVM never creates a page size greater than
5790703c335dSSean Christopherson 	 * what is used by the kernel for any given HVA, i.e. the kernel's
5791703c335dSSean Christopherson 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5792703c335dSSean Christopherson 	 */
5793703c335dSSean Christopherson 	if (tdp_enabled)
57941d92d2e8SSean Christopherson 		max_huge_page_level = tdp_huge_page_level;
5795703c335dSSean Christopherson 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
57961d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_1G;
5797703c335dSSean Christopherson 	else
57981d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_2M;
5799c50d8ae3SPaolo Bonzini }
5800bde77235SSean Christopherson EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5801c50d8ae3SPaolo Bonzini 
5802c50d8ae3SPaolo Bonzini /* The return value indicates if tlb flush on all vcpus is needed. */
5803269e9552SHamza Mahfooz typedef bool (*slot_level_handler) (struct kvm *kvm,
5804269e9552SHamza Mahfooz 				    struct kvm_rmap_head *rmap_head,
5805269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot);
5806c50d8ae3SPaolo Bonzini 
5807c50d8ae3SPaolo Bonzini /* The caller should hold mmu-lock before calling this function. */
5808c50d8ae3SPaolo Bonzini static __always_inline bool
5809269e9552SHamza Mahfooz slot_handle_level_range(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5810c50d8ae3SPaolo Bonzini 			slot_level_handler fn, int start_level, int end_level,
58111a61b7dbSSean Christopherson 			gfn_t start_gfn, gfn_t end_gfn, bool flush_on_yield,
58121a61b7dbSSean Christopherson 			bool flush)
5813c50d8ae3SPaolo Bonzini {
5814c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
5815c50d8ae3SPaolo Bonzini 
5816c50d8ae3SPaolo Bonzini 	for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5817c50d8ae3SPaolo Bonzini 			end_gfn, &iterator) {
5818c50d8ae3SPaolo Bonzini 		if (iterator.rmap)
58190a234f5dSSean Christopherson 			flush |= fn(kvm, iterator.rmap, memslot);
5820c50d8ae3SPaolo Bonzini 
5821531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
5822302695a5SSean Christopherson 			if (flush && flush_on_yield) {
5823c50d8ae3SPaolo Bonzini 				kvm_flush_remote_tlbs_with_address(kvm,
5824c50d8ae3SPaolo Bonzini 						start_gfn,
5825c50d8ae3SPaolo Bonzini 						iterator.gfn - start_gfn + 1);
5826c50d8ae3SPaolo Bonzini 				flush = false;
5827c50d8ae3SPaolo Bonzini 			}
5828531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
5829c50d8ae3SPaolo Bonzini 		}
5830c50d8ae3SPaolo Bonzini 	}
5831c50d8ae3SPaolo Bonzini 
5832c50d8ae3SPaolo Bonzini 	return flush;
5833c50d8ae3SPaolo Bonzini }
5834c50d8ae3SPaolo Bonzini 
5835c50d8ae3SPaolo Bonzini static __always_inline bool
5836269e9552SHamza Mahfooz slot_handle_level(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5837c50d8ae3SPaolo Bonzini 		  slot_level_handler fn, int start_level, int end_level,
5838302695a5SSean Christopherson 		  bool flush_on_yield)
5839c50d8ae3SPaolo Bonzini {
5840c50d8ae3SPaolo Bonzini 	return slot_handle_level_range(kvm, memslot, fn, start_level,
5841c50d8ae3SPaolo Bonzini 			end_level, memslot->base_gfn,
5842c50d8ae3SPaolo Bonzini 			memslot->base_gfn + memslot->npages - 1,
58431a61b7dbSSean Christopherson 			flush_on_yield, false);
5844c50d8ae3SPaolo Bonzini }
5845c50d8ae3SPaolo Bonzini 
5846c50d8ae3SPaolo Bonzini static __always_inline bool
5847610265eaSDavid Matlack slot_handle_level_4k(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5848302695a5SSean Christopherson 		     slot_level_handler fn, bool flush_on_yield)
5849c50d8ae3SPaolo Bonzini {
58503bae0459SSean Christopherson 	return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5851302695a5SSean Christopherson 				 PG_LEVEL_4K, flush_on_yield);
5852c50d8ae3SPaolo Bonzini }
5853c50d8ae3SPaolo Bonzini 
5854c50d8ae3SPaolo Bonzini static void free_mmu_pages(struct kvm_mmu *mmu)
5855c50d8ae3SPaolo Bonzini {
58564a98623dSSean Christopherson 	if (!tdp_enabled && mmu->pae_root)
58574a98623dSSean Christopherson 		set_memory_encrypted((unsigned long)mmu->pae_root, 1);
5858c50d8ae3SPaolo Bonzini 	free_page((unsigned long)mmu->pae_root);
585903ca4589SSean Christopherson 	free_page((unsigned long)mmu->pml4_root);
5860cb0f722aSWei Huang 	free_page((unsigned long)mmu->pml5_root);
5861c50d8ae3SPaolo Bonzini }
5862c50d8ae3SPaolo Bonzini 
586304d28e37SSean Christopherson static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5864c50d8ae3SPaolo Bonzini {
5865c50d8ae3SPaolo Bonzini 	struct page *page;
5866c50d8ae3SPaolo Bonzini 	int i;
5867c50d8ae3SPaolo Bonzini 
5868b9e5603cSPaolo Bonzini 	mmu->root.hpa = INVALID_PAGE;
5869b9e5603cSPaolo Bonzini 	mmu->root.pgd = 0;
587004d28e37SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
587104d28e37SSean Christopherson 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
587204d28e37SSean Christopherson 
587327f4fca2SLai Jiangshan 	/* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
587427f4fca2SLai Jiangshan 	if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
587527f4fca2SLai Jiangshan 		return 0;
587627f4fca2SLai Jiangshan 
5877c50d8ae3SPaolo Bonzini 	/*
5878c50d8ae3SPaolo Bonzini 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5879c50d8ae3SPaolo Bonzini 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
5880c50d8ae3SPaolo Bonzini 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
5881c50d8ae3SPaolo Bonzini 	 * x86_64.  Therefore we need to allocate the PDP table in the first
588204d45551SSean Christopherson 	 * 4GB of memory, which happens to fit the DMA32 zone.  TDP paging
588304d45551SSean Christopherson 	 * generally doesn't use PAE paging and can skip allocating the PDP
588404d45551SSean Christopherson 	 * table.  The main exception, handled here, is SVM's 32-bit NPT.  The
588504d45551SSean Christopherson 	 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
588684432316SLai Jiangshan 	 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
5887c50d8ae3SPaolo Bonzini 	 */
5888d468d94bSSean Christopherson 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5889c50d8ae3SPaolo Bonzini 		return 0;
5890c50d8ae3SPaolo Bonzini 
5891c50d8ae3SPaolo Bonzini 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5892c50d8ae3SPaolo Bonzini 	if (!page)
5893c50d8ae3SPaolo Bonzini 		return -ENOMEM;
5894c50d8ae3SPaolo Bonzini 
5895c50d8ae3SPaolo Bonzini 	mmu->pae_root = page_address(page);
58964a98623dSSean Christopherson 
58974a98623dSSean Christopherson 	/*
58984a98623dSSean Christopherson 	 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
58994a98623dSSean Christopherson 	 * get the CPU to treat the PDPTEs as encrypted.  Decrypt the page so
59004a98623dSSean Christopherson 	 * that KVM's writes and the CPU's reads get along.  Note, this is
59014a98623dSSean Christopherson 	 * only necessary when using shadow paging, as 64-bit NPT can get at
59024a98623dSSean Christopherson 	 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
59034a98623dSSean Christopherson 	 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
59044a98623dSSean Christopherson 	 */
59054a98623dSSean Christopherson 	if (!tdp_enabled)
59064a98623dSSean Christopherson 		set_memory_decrypted((unsigned long)mmu->pae_root, 1);
59074a98623dSSean Christopherson 	else
5908e54f1ff2SKai Huang 		WARN_ON_ONCE(shadow_me_value);
59094a98623dSSean Christopherson 
5910c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i)
5911c834e5e4SSean Christopherson 		mmu->pae_root[i] = INVALID_PAE_ROOT;
5912c50d8ae3SPaolo Bonzini 
5913c50d8ae3SPaolo Bonzini 	return 0;
5914c50d8ae3SPaolo Bonzini }
5915c50d8ae3SPaolo Bonzini 
5916c50d8ae3SPaolo Bonzini int kvm_mmu_create(struct kvm_vcpu *vcpu)
5917c50d8ae3SPaolo Bonzini {
5918c50d8ae3SPaolo Bonzini 	int ret;
5919c50d8ae3SPaolo Bonzini 
59205962bfb7SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
59215f6078f9SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
59225f6078f9SSean Christopherson 
59235962bfb7SSean Christopherson 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
59245f6078f9SSean Christopherson 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
59255962bfb7SSean Christopherson 
592696880883SSean Christopherson 	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
592796880883SSean Christopherson 
5928c50d8ae3SPaolo Bonzini 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
5929c50d8ae3SPaolo Bonzini 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5930c50d8ae3SPaolo Bonzini 
593104d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
5932c50d8ae3SPaolo Bonzini 	if (ret)
5933c50d8ae3SPaolo Bonzini 		return ret;
5934c50d8ae3SPaolo Bonzini 
593504d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
5936c50d8ae3SPaolo Bonzini 	if (ret)
5937c50d8ae3SPaolo Bonzini 		goto fail_allocate_root;
5938c50d8ae3SPaolo Bonzini 
5939c50d8ae3SPaolo Bonzini 	return ret;
5940c50d8ae3SPaolo Bonzini  fail_allocate_root:
5941c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
5942c50d8ae3SPaolo Bonzini 	return ret;
5943c50d8ae3SPaolo Bonzini }
5944c50d8ae3SPaolo Bonzini 
5945c50d8ae3SPaolo Bonzini #define BATCH_ZAP_PAGES	10
5946c50d8ae3SPaolo Bonzini static void kvm_zap_obsolete_pages(struct kvm *kvm)
5947c50d8ae3SPaolo Bonzini {
5948c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
5949c50d8ae3SPaolo Bonzini 	int nr_zapped, batch = 0;
5950b28cb0cdSSean Christopherson 	bool unstable;
5951c50d8ae3SPaolo Bonzini 
5952c50d8ae3SPaolo Bonzini restart:
5953c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe_reverse(sp, node,
5954c50d8ae3SPaolo Bonzini 	      &kvm->arch.active_mmu_pages, link) {
5955c50d8ae3SPaolo Bonzini 		/*
5956c50d8ae3SPaolo Bonzini 		 * No obsolete valid page exists before a newly created page
5957c50d8ae3SPaolo Bonzini 		 * since active_mmu_pages is a FIFO list.
5958c50d8ae3SPaolo Bonzini 		 */
5959c50d8ae3SPaolo Bonzini 		if (!is_obsolete_sp(kvm, sp))
5960c50d8ae3SPaolo Bonzini 			break;
5961c50d8ae3SPaolo Bonzini 
5962c50d8ae3SPaolo Bonzini 		/*
5963f95eec9bSSean Christopherson 		 * Invalid pages should never land back on the list of active
5964f95eec9bSSean Christopherson 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
5965f95eec9bSSean Christopherson 		 * infinite loop if the page gets put back on the list (again).
5966c50d8ae3SPaolo Bonzini 		 */
5967f95eec9bSSean Christopherson 		if (WARN_ON(sp->role.invalid))
5968c50d8ae3SPaolo Bonzini 			continue;
5969c50d8ae3SPaolo Bonzini 
5970c50d8ae3SPaolo Bonzini 		/*
5971c50d8ae3SPaolo Bonzini 		 * No need to flush the TLB since we're only zapping shadow
5972c50d8ae3SPaolo Bonzini 		 * pages with an obsolete generation number and all vCPUS have
5973c50d8ae3SPaolo Bonzini 		 * loaded a new root, i.e. the shadow pages being zapped cannot
5974c50d8ae3SPaolo Bonzini 		 * be in active use by the guest.
5975c50d8ae3SPaolo Bonzini 		 */
5976c50d8ae3SPaolo Bonzini 		if (batch >= BATCH_ZAP_PAGES &&
5977531810caSBen Gardon 		    cond_resched_rwlock_write(&kvm->mmu_lock)) {
5978c50d8ae3SPaolo Bonzini 			batch = 0;
5979c50d8ae3SPaolo Bonzini 			goto restart;
5980c50d8ae3SPaolo Bonzini 		}
5981c50d8ae3SPaolo Bonzini 
5982b28cb0cdSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
5983b28cb0cdSSean Christopherson 				&kvm->arch.zapped_obsolete_pages, &nr_zapped);
5984c50d8ae3SPaolo Bonzini 		batch += nr_zapped;
5985b28cb0cdSSean Christopherson 
5986b28cb0cdSSean Christopherson 		if (unstable)
5987c50d8ae3SPaolo Bonzini 			goto restart;
5988c50d8ae3SPaolo Bonzini 	}
5989c50d8ae3SPaolo Bonzini 
5990c50d8ae3SPaolo Bonzini 	/*
59917ae5840eSSean Christopherson 	 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
59927ae5840eSSean Christopherson 	 * to ensure KVM is not in the middle of a lockless shadow page table
59937ae5840eSSean Christopherson 	 * walk, which may reference the pages.  The remote TLB flush itself is
59947ae5840eSSean Christopherson 	 * not required and is simply a convenient way to kick vCPUs as needed.
59957ae5840eSSean Christopherson 	 * KVM performs a local TLB flush when allocating a new root (see
59967ae5840eSSean Christopherson 	 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
59977ae5840eSSean Christopherson 	 * running with an obsolete MMU.
5998c50d8ae3SPaolo Bonzini 	 */
5999c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
6000c50d8ae3SPaolo Bonzini }
6001c50d8ae3SPaolo Bonzini 
6002c50d8ae3SPaolo Bonzini /*
6003c50d8ae3SPaolo Bonzini  * Fast invalidate all shadow pages and use lock-break technique
6004c50d8ae3SPaolo Bonzini  * to zap obsolete pages.
6005c50d8ae3SPaolo Bonzini  *
6006c50d8ae3SPaolo Bonzini  * It's required when memslot is being deleted or VM is being
6007c50d8ae3SPaolo Bonzini  * destroyed, in these cases, we should ensure that KVM MMU does
6008c50d8ae3SPaolo Bonzini  * not use any resource of the being-deleted slot or all slots
6009c50d8ae3SPaolo Bonzini  * after calling the function.
6010c50d8ae3SPaolo Bonzini  */
6011c50d8ae3SPaolo Bonzini static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6012c50d8ae3SPaolo Bonzini {
6013c50d8ae3SPaolo Bonzini 	lockdep_assert_held(&kvm->slots_lock);
6014c50d8ae3SPaolo Bonzini 
6015531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6016c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_zap_all_fast(kvm);
6017c50d8ae3SPaolo Bonzini 
6018c50d8ae3SPaolo Bonzini 	/*
6019c50d8ae3SPaolo Bonzini 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
6020c50d8ae3SPaolo Bonzini 	 * held for the entire duration of zapping obsolete pages, it's
6021c50d8ae3SPaolo Bonzini 	 * impossible for there to be multiple invalid generations associated
6022c50d8ae3SPaolo Bonzini 	 * with *valid* shadow pages at any given time, i.e. there is exactly
6023c50d8ae3SPaolo Bonzini 	 * one valid generation and (at most) one invalid generation.
6024c50d8ae3SPaolo Bonzini 	 */
6025c50d8ae3SPaolo Bonzini 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6026c50d8ae3SPaolo Bonzini 
60272f6f66ccSSean Christopherson 	/*
60282f6f66ccSSean Christopherson 	 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
60292f6f66ccSSean Christopherson 	 * invalidating TDP MMU roots must be done while holding mmu_lock for
60302f6f66ccSSean Christopherson 	 * write and in the same critical section as making the reload request,
60312f6f66ccSSean Christopherson 	 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6032b7cccd39SBen Gardon 	 */
60331f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6034b7cccd39SBen Gardon 		kvm_tdp_mmu_invalidate_all_roots(kvm);
6035b7cccd39SBen Gardon 
6036c50d8ae3SPaolo Bonzini 	/*
6037c50d8ae3SPaolo Bonzini 	 * Notify all vcpus to reload its shadow page table and flush TLB.
6038c50d8ae3SPaolo Bonzini 	 * Then all vcpus will switch to new shadow page table with the new
6039c50d8ae3SPaolo Bonzini 	 * mmu_valid_gen.
6040c50d8ae3SPaolo Bonzini 	 *
6041c50d8ae3SPaolo Bonzini 	 * Note: we need to do this under the protection of mmu_lock,
6042c50d8ae3SPaolo Bonzini 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
6043c50d8ae3SPaolo Bonzini 	 */
6044527d5cd7SSean Christopherson 	kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6045c50d8ae3SPaolo Bonzini 
6046c50d8ae3SPaolo Bonzini 	kvm_zap_obsolete_pages(kvm);
6047faaf05b0SBen Gardon 
6048531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
60494c6654bdSBen Gardon 
6050f28e9c7fSSean Christopherson 	/*
6051f28e9c7fSSean Christopherson 	 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6052f28e9c7fSSean Christopherson 	 * returning to the caller, e.g. if the zap is in response to a memslot
6053f28e9c7fSSean Christopherson 	 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6054f28e9c7fSSean Christopherson 	 * associated with the deleted memslot once the update completes, and
6055f28e9c7fSSean Christopherson 	 * Deferring the zap until the final reference to the root is put would
6056f28e9c7fSSean Christopherson 	 * lead to use-after-free.
6057f28e9c7fSSean Christopherson 	 */
60581f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
60594c6654bdSBen Gardon 		kvm_tdp_mmu_zap_invalidated_roots(kvm);
6060c50d8ae3SPaolo Bonzini }
6061c50d8ae3SPaolo Bonzini 
6062c50d8ae3SPaolo Bonzini static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
6063c50d8ae3SPaolo Bonzini {
6064c50d8ae3SPaolo Bonzini 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
6065c50d8ae3SPaolo Bonzini }
6066c50d8ae3SPaolo Bonzini 
6067c50d8ae3SPaolo Bonzini static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
6068c50d8ae3SPaolo Bonzini 			struct kvm_memory_slot *slot,
6069c50d8ae3SPaolo Bonzini 			struct kvm_page_track_notifier_node *node)
6070c50d8ae3SPaolo Bonzini {
6071c50d8ae3SPaolo Bonzini 	kvm_mmu_zap_all_fast(kvm);
6072c50d8ae3SPaolo Bonzini }
6073c50d8ae3SPaolo Bonzini 
6074a1a39128SPaolo Bonzini int kvm_mmu_init_vm(struct kvm *kvm)
6075c50d8ae3SPaolo Bonzini {
6076c50d8ae3SPaolo Bonzini 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6077a1a39128SPaolo Bonzini 	int r;
6078c50d8ae3SPaolo Bonzini 
6079a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6080a1a39128SPaolo Bonzini 	INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
608155c510e2SSean Christopherson 	INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6082ce25681dSSean Christopherson 	spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6083ce25681dSSean Christopherson 
608409732d2bSDavid Matlack 	if (tdp_mmu_enabled) {
6085a1a39128SPaolo Bonzini 		r = kvm_mmu_init_tdp_mmu(kvm);
6086a1a39128SPaolo Bonzini 		if (r < 0)
6087a1a39128SPaolo Bonzini 			return r;
608809732d2bSDavid Matlack 	}
6089fe5db27dSBen Gardon 
6090c50d8ae3SPaolo Bonzini 	node->track_write = kvm_mmu_pte_write;
6091c50d8ae3SPaolo Bonzini 	node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
6092c50d8ae3SPaolo Bonzini 	kvm_page_track_register_notifier(kvm, node);
6093ada51a9dSDavid Matlack 
6094ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6095ada51a9dSDavid Matlack 	kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6096ada51a9dSDavid Matlack 
6097ada51a9dSDavid Matlack 	kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6098ada51a9dSDavid Matlack 
6099ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6100ada51a9dSDavid Matlack 	kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6101ada51a9dSDavid Matlack 
6102a1a39128SPaolo Bonzini 	return 0;
6103c50d8ae3SPaolo Bonzini }
6104c50d8ae3SPaolo Bonzini 
6105ada51a9dSDavid Matlack static void mmu_free_vm_memory_caches(struct kvm *kvm)
6106ada51a9dSDavid Matlack {
6107ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6108ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6109ada51a9dSDavid Matlack 	kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6110ada51a9dSDavid Matlack }
6111ada51a9dSDavid Matlack 
6112c50d8ae3SPaolo Bonzini void kvm_mmu_uninit_vm(struct kvm *kvm)
6113c50d8ae3SPaolo Bonzini {
6114c50d8ae3SPaolo Bonzini 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6115c50d8ae3SPaolo Bonzini 
6116c50d8ae3SPaolo Bonzini 	kvm_page_track_unregister_notifier(kvm, node);
6117fe5db27dSBen Gardon 
611809732d2bSDavid Matlack 	if (tdp_mmu_enabled)
6119fe5db27dSBen Gardon 		kvm_mmu_uninit_tdp_mmu(kvm);
6120ada51a9dSDavid Matlack 
6121ada51a9dSDavid Matlack 	mmu_free_vm_memory_caches(kvm);
6122c50d8ae3SPaolo Bonzini }
6123c50d8ae3SPaolo Bonzini 
61242833eda0SSean Christopherson static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
612521fa3246SSean Christopherson {
612621fa3246SSean Christopherson 	const struct kvm_memory_slot *memslot;
612721fa3246SSean Christopherson 	struct kvm_memslots *slots;
6128f4209439SMaciej S. Szmigiero 	struct kvm_memslot_iter iter;
612921fa3246SSean Christopherson 	bool flush = false;
613021fa3246SSean Christopherson 	gfn_t start, end;
6131f4209439SMaciej S. Szmigiero 	int i;
613221fa3246SSean Christopherson 
613321fa3246SSean Christopherson 	if (!kvm_memslots_have_rmaps(kvm))
613421fa3246SSean Christopherson 		return flush;
613521fa3246SSean Christopherson 
613621fa3246SSean Christopherson 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
613721fa3246SSean Christopherson 		slots = __kvm_memslots(kvm, i);
6138f4209439SMaciej S. Szmigiero 
6139f4209439SMaciej S. Szmigiero 		kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6140f4209439SMaciej S. Szmigiero 			memslot = iter.slot;
614121fa3246SSean Christopherson 			start = max(gfn_start, memslot->base_gfn);
614221fa3246SSean Christopherson 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
6143f4209439SMaciej S. Szmigiero 			if (WARN_ON_ONCE(start >= end))
614421fa3246SSean Christopherson 				continue;
614521fa3246SSean Christopherson 
6146f8480721SSean Christopherson 			flush = slot_handle_level_range(kvm, memslot, __kvm_zap_rmap,
614721fa3246SSean Christopherson 							PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
614821fa3246SSean Christopherson 							start, end - 1, true, flush);
614921fa3246SSean Christopherson 		}
615021fa3246SSean Christopherson 	}
615121fa3246SSean Christopherson 
615221fa3246SSean Christopherson 	return flush;
615321fa3246SSean Christopherson }
615421fa3246SSean Christopherson 
615588f58535SMaxim Levitsky /*
615688f58535SMaxim Levitsky  * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
615788f58535SMaxim Levitsky  * (not including it)
615888f58535SMaxim Levitsky  */
6159c50d8ae3SPaolo Bonzini void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6160c50d8ae3SPaolo Bonzini {
616121fa3246SSean Christopherson 	bool flush;
6162c50d8ae3SPaolo Bonzini 	int i;
6163c50d8ae3SPaolo Bonzini 
6164f4209439SMaciej S. Szmigiero 	if (WARN_ON_ONCE(gfn_end <= gfn_start))
6165f4209439SMaciej S. Szmigiero 		return;
6166f4209439SMaciej S. Szmigiero 
6167531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
61685a324c24SSean Christopherson 
616920ec3ebdSChao Peng 	kvm_mmu_invalidate_begin(kvm, gfn_start, gfn_end);
6170edb298c6SMaxim Levitsky 
61712833eda0SSean Christopherson 	flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
61726103bc07SBen Gardon 
61731f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
61746103bc07SBen Gardon 		for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
6175f47e5bbbSSean Christopherson 			flush = kvm_tdp_mmu_zap_leafs(kvm, i, gfn_start,
6176f47e5bbbSSean Christopherson 						      gfn_end, true, flush);
61776103bc07SBen Gardon 	}
61785a324c24SSean Christopherson 
61795a324c24SSean Christopherson 	if (flush)
6180bc3b3c10SSean Christopherson 		kvm_flush_remote_tlbs_with_address(kvm, gfn_start,
6181bc3b3c10SSean Christopherson 						   gfn_end - gfn_start);
61825a324c24SSean Christopherson 
618320ec3ebdSChao Peng 	kvm_mmu_invalidate_end(kvm, gfn_start, gfn_end);
6184edb298c6SMaxim Levitsky 
61855a324c24SSean Christopherson 	write_unlock(&kvm->mmu_lock);
6186c50d8ae3SPaolo Bonzini }
6187c50d8ae3SPaolo Bonzini 
6188c50d8ae3SPaolo Bonzini static bool slot_rmap_write_protect(struct kvm *kvm,
61890a234f5dSSean Christopherson 				    struct kvm_rmap_head *rmap_head,
6190269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot)
6191c50d8ae3SPaolo Bonzini {
61921346bbb6SDavid Matlack 	return rmap_write_protect(rmap_head, false);
6193c50d8ae3SPaolo Bonzini }
6194c50d8ae3SPaolo Bonzini 
6195c50d8ae3SPaolo Bonzini void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6196269e9552SHamza Mahfooz 				      const struct kvm_memory_slot *memslot,
61973c9bd400SJay Zhou 				      int start_level)
6198c50d8ae3SPaolo Bonzini {
6199e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6200531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6201b64d740eSJunaid Shahid 		slot_handle_level(kvm, memslot, slot_rmap_write_protect,
6202b64d740eSJunaid Shahid 				  start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6203531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6204e2209710SBen Gardon 	}
6205c50d8ae3SPaolo Bonzini 
62061f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
620724ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6208b64d740eSJunaid Shahid 		kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
620924ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
621024ae4cfaSBen Gardon 	}
6211c50d8ae3SPaolo Bonzini }
6212c50d8ae3SPaolo Bonzini 
6213ada51a9dSDavid Matlack static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6214ada51a9dSDavid Matlack {
6215ada51a9dSDavid Matlack 	return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6216ada51a9dSDavid Matlack }
6217ada51a9dSDavid Matlack 
6218ada51a9dSDavid Matlack static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6219ada51a9dSDavid Matlack {
6220ada51a9dSDavid Matlack 	if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6221ada51a9dSDavid Matlack 		return true;
6222ada51a9dSDavid Matlack 
6223ada51a9dSDavid Matlack 	/*
6224ada51a9dSDavid Matlack 	 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6225ada51a9dSDavid Matlack 	 * to split a single huge page. Calculating how many are actually needed
6226ada51a9dSDavid Matlack 	 * is possible but not worth the complexity.
6227ada51a9dSDavid Matlack 	 */
6228ada51a9dSDavid Matlack 	return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6229ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_page_header_cache, 1) ||
6230ada51a9dSDavid Matlack 	       need_topup(&kvm->arch.split_shadow_page_cache, 1);
6231ada51a9dSDavid Matlack }
6232ada51a9dSDavid Matlack 
6233ada51a9dSDavid Matlack static int topup_split_caches(struct kvm *kvm)
6234ada51a9dSDavid Matlack {
6235b9b71f43SSean Christopherson 	/*
6236b9b71f43SSean Christopherson 	 * Allocating rmap list entries when splitting huge pages for nested
6237dfd4eb44SSean Christopherson 	 * MMUs is uncommon as KVM needs to use a list if and only if there is
6238b9b71f43SSean Christopherson 	 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6239dfd4eb44SSean Christopherson 	 * aliased by multiple L2 gfns and/or from multiple nested roots with
6240dfd4eb44SSean Christopherson 	 * different roles.  Aliasing gfns when using TDP is atypical for VMMs;
6241dfd4eb44SSean Christopherson 	 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6242dfd4eb44SSean Christopherson 	 * but aliasing rarely occurs post-boot or for many gfns.  If there is
6243dfd4eb44SSean Christopherson 	 * only one rmap entry, rmap->val points directly at that one entry and
6244dfd4eb44SSean Christopherson 	 * doesn't need to allocate a list.  Buffer the cache by the default
6245dfd4eb44SSean Christopherson 	 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6246b9b71f43SSean Christopherson 	 * encounters an aliased gfn or two.
6247b9b71f43SSean Christopherson 	 */
6248b9b71f43SSean Christopherson 	const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6249b9b71f43SSean Christopherson 			     KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6250ada51a9dSDavid Matlack 	int r;
6251ada51a9dSDavid Matlack 
6252ada51a9dSDavid Matlack 	lockdep_assert_held(&kvm->slots_lock);
6253ada51a9dSDavid Matlack 
6254b9b71f43SSean Christopherson 	r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6255ada51a9dSDavid Matlack 					 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6256ada51a9dSDavid Matlack 	if (r)
6257ada51a9dSDavid Matlack 		return r;
6258ada51a9dSDavid Matlack 
6259ada51a9dSDavid Matlack 	r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6260ada51a9dSDavid Matlack 	if (r)
6261ada51a9dSDavid Matlack 		return r;
6262ada51a9dSDavid Matlack 
6263ada51a9dSDavid Matlack 	return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6264ada51a9dSDavid Matlack }
6265ada51a9dSDavid Matlack 
6266ada51a9dSDavid Matlack static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6267ada51a9dSDavid Matlack {
6268ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6269ada51a9dSDavid Matlack 	struct shadow_page_caches caches = {};
6270ada51a9dSDavid Matlack 	union kvm_mmu_page_role role;
6271ada51a9dSDavid Matlack 	unsigned int access;
6272ada51a9dSDavid Matlack 	gfn_t gfn;
6273ada51a9dSDavid Matlack 
627479e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
627579e48cecSSean Christopherson 	access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6276ada51a9dSDavid Matlack 
6277ada51a9dSDavid Matlack 	/*
6278ada51a9dSDavid Matlack 	 * Note, huge page splitting always uses direct shadow pages, regardless
6279ada51a9dSDavid Matlack 	 * of whether the huge page itself is mapped by a direct or indirect
6280ada51a9dSDavid Matlack 	 * shadow page, since the huge page region itself is being directly
6281ada51a9dSDavid Matlack 	 * mapped with smaller pages.
6282ada51a9dSDavid Matlack 	 */
6283ada51a9dSDavid Matlack 	role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6284ada51a9dSDavid Matlack 
6285ada51a9dSDavid Matlack 	/* Direct SPs do not require a shadowed_info_cache. */
6286ada51a9dSDavid Matlack 	caches.page_header_cache = &kvm->arch.split_page_header_cache;
6287ada51a9dSDavid Matlack 	caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6288ada51a9dSDavid Matlack 
6289ada51a9dSDavid Matlack 	/* Safe to pass NULL for vCPU since requesting a direct SP. */
6290ada51a9dSDavid Matlack 	return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6291ada51a9dSDavid Matlack }
6292ada51a9dSDavid Matlack 
6293ada51a9dSDavid Matlack static void shadow_mmu_split_huge_page(struct kvm *kvm,
6294ada51a9dSDavid Matlack 				       const struct kvm_memory_slot *slot,
6295ada51a9dSDavid Matlack 				       u64 *huge_sptep)
6296ada51a9dSDavid Matlack 
6297ada51a9dSDavid Matlack {
6298ada51a9dSDavid Matlack 	struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6299ada51a9dSDavid Matlack 	u64 huge_spte = READ_ONCE(*huge_sptep);
6300ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
630103787394SPaolo Bonzini 	bool flush = false;
6302ada51a9dSDavid Matlack 	u64 *sptep, spte;
6303ada51a9dSDavid Matlack 	gfn_t gfn;
6304ada51a9dSDavid Matlack 	int index;
6305ada51a9dSDavid Matlack 
6306ada51a9dSDavid Matlack 	sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6307ada51a9dSDavid Matlack 
6308ada51a9dSDavid Matlack 	for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6309ada51a9dSDavid Matlack 		sptep = &sp->spt[index];
6310ada51a9dSDavid Matlack 		gfn = kvm_mmu_page_get_gfn(sp, index);
6311ada51a9dSDavid Matlack 
6312ada51a9dSDavid Matlack 		/*
6313ada51a9dSDavid Matlack 		 * The SP may already have populated SPTEs, e.g. if this huge
6314ada51a9dSDavid Matlack 		 * page is aliased by multiple sptes with the same access
6315ada51a9dSDavid Matlack 		 * permissions. These entries are guaranteed to map the same
6316ada51a9dSDavid Matlack 		 * gfn-to-pfn translation since the SP is direct, so no need to
6317ada51a9dSDavid Matlack 		 * modify them.
6318ada51a9dSDavid Matlack 		 *
631903787394SPaolo Bonzini 		 * However, if a given SPTE points to a lower level page table,
632003787394SPaolo Bonzini 		 * that lower level page table may only be partially populated.
632103787394SPaolo Bonzini 		 * Installing such SPTEs would effectively unmap a potion of the
632203787394SPaolo Bonzini 		 * huge page. Unmapping guest memory always requires a TLB flush
632303787394SPaolo Bonzini 		 * since a subsequent operation on the unmapped regions would
632403787394SPaolo Bonzini 		 * fail to detect the need to flush.
6325ada51a9dSDavid Matlack 		 */
632603787394SPaolo Bonzini 		if (is_shadow_present_pte(*sptep)) {
632703787394SPaolo Bonzini 			flush |= !is_last_spte(*sptep, sp->role.level);
6328ada51a9dSDavid Matlack 			continue;
632903787394SPaolo Bonzini 		}
6330ada51a9dSDavid Matlack 
6331ada51a9dSDavid Matlack 		spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
6332ada51a9dSDavid Matlack 		mmu_spte_set(sptep, spte);
6333ada51a9dSDavid Matlack 		__rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6334ada51a9dSDavid Matlack 	}
6335ada51a9dSDavid Matlack 
633603787394SPaolo Bonzini 	__link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6337ada51a9dSDavid Matlack }
6338ada51a9dSDavid Matlack 
6339ada51a9dSDavid Matlack static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6340ada51a9dSDavid Matlack 					  const struct kvm_memory_slot *slot,
6341ada51a9dSDavid Matlack 					  u64 *huge_sptep)
6342ada51a9dSDavid Matlack {
6343ada51a9dSDavid Matlack 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6344ada51a9dSDavid Matlack 	int level, r = 0;
6345ada51a9dSDavid Matlack 	gfn_t gfn;
6346ada51a9dSDavid Matlack 	u64 spte;
6347ada51a9dSDavid Matlack 
6348ada51a9dSDavid Matlack 	/* Grab information for the tracepoint before dropping the MMU lock. */
634979e48cecSSean Christopherson 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6350ada51a9dSDavid Matlack 	level = huge_sp->role.level;
6351ada51a9dSDavid Matlack 	spte = *huge_sptep;
6352ada51a9dSDavid Matlack 
6353ada51a9dSDavid Matlack 	if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6354ada51a9dSDavid Matlack 		r = -ENOSPC;
6355ada51a9dSDavid Matlack 		goto out;
6356ada51a9dSDavid Matlack 	}
6357ada51a9dSDavid Matlack 
6358ada51a9dSDavid Matlack 	if (need_topup_split_caches_or_resched(kvm)) {
6359ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6360ada51a9dSDavid Matlack 		cond_resched();
6361ada51a9dSDavid Matlack 		/*
6362ada51a9dSDavid Matlack 		 * If the topup succeeds, return -EAGAIN to indicate that the
6363ada51a9dSDavid Matlack 		 * rmap iterator should be restarted because the MMU lock was
6364ada51a9dSDavid Matlack 		 * dropped.
6365ada51a9dSDavid Matlack 		 */
6366ada51a9dSDavid Matlack 		r = topup_split_caches(kvm) ?: -EAGAIN;
6367ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6368ada51a9dSDavid Matlack 		goto out;
6369ada51a9dSDavid Matlack 	}
6370ada51a9dSDavid Matlack 
6371ada51a9dSDavid Matlack 	shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6372ada51a9dSDavid Matlack 
6373ada51a9dSDavid Matlack out:
6374ada51a9dSDavid Matlack 	trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6375ada51a9dSDavid Matlack 	return r;
6376ada51a9dSDavid Matlack }
6377ada51a9dSDavid Matlack 
6378ada51a9dSDavid Matlack static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6379ada51a9dSDavid Matlack 					    struct kvm_rmap_head *rmap_head,
6380ada51a9dSDavid Matlack 					    const struct kvm_memory_slot *slot)
6381ada51a9dSDavid Matlack {
6382ada51a9dSDavid Matlack 	struct rmap_iterator iter;
6383ada51a9dSDavid Matlack 	struct kvm_mmu_page *sp;
6384ada51a9dSDavid Matlack 	u64 *huge_sptep;
6385ada51a9dSDavid Matlack 	int r;
6386ada51a9dSDavid Matlack 
6387ada51a9dSDavid Matlack restart:
6388ada51a9dSDavid Matlack 	for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6389ada51a9dSDavid Matlack 		sp = sptep_to_sp(huge_sptep);
6390ada51a9dSDavid Matlack 
6391ada51a9dSDavid Matlack 		/* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6392ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!sp->role.guest_mode))
6393ada51a9dSDavid Matlack 			continue;
6394ada51a9dSDavid Matlack 
6395ada51a9dSDavid Matlack 		/* The rmaps should never contain non-leaf SPTEs. */
6396ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6397ada51a9dSDavid Matlack 			continue;
6398ada51a9dSDavid Matlack 
6399ada51a9dSDavid Matlack 		/* SPs with level >PG_LEVEL_4K should never by unsync. */
6400ada51a9dSDavid Matlack 		if (WARN_ON_ONCE(sp->unsync))
6401ada51a9dSDavid Matlack 			continue;
6402ada51a9dSDavid Matlack 
6403ada51a9dSDavid Matlack 		/* Don't bother splitting huge pages on invalid SPs. */
6404ada51a9dSDavid Matlack 		if (sp->role.invalid)
6405ada51a9dSDavid Matlack 			continue;
6406ada51a9dSDavid Matlack 
6407ada51a9dSDavid Matlack 		r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6408ada51a9dSDavid Matlack 
6409ada51a9dSDavid Matlack 		/*
6410ada51a9dSDavid Matlack 		 * The split succeeded or needs to be retried because the MMU
6411ada51a9dSDavid Matlack 		 * lock was dropped. Either way, restart the iterator to get it
6412ada51a9dSDavid Matlack 		 * back into a consistent state.
6413ada51a9dSDavid Matlack 		 */
6414ada51a9dSDavid Matlack 		if (!r || r == -EAGAIN)
6415ada51a9dSDavid Matlack 			goto restart;
6416ada51a9dSDavid Matlack 
6417ada51a9dSDavid Matlack 		/* The split failed and shouldn't be retried (e.g. -ENOMEM). */
6418ada51a9dSDavid Matlack 		break;
6419ada51a9dSDavid Matlack 	}
6420ada51a9dSDavid Matlack 
6421ada51a9dSDavid Matlack 	return false;
6422ada51a9dSDavid Matlack }
6423ada51a9dSDavid Matlack 
6424ada51a9dSDavid Matlack static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6425ada51a9dSDavid Matlack 						const struct kvm_memory_slot *slot,
6426ada51a9dSDavid Matlack 						gfn_t start, gfn_t end,
6427ada51a9dSDavid Matlack 						int target_level)
6428ada51a9dSDavid Matlack {
6429ada51a9dSDavid Matlack 	int level;
6430ada51a9dSDavid Matlack 
6431ada51a9dSDavid Matlack 	/*
6432ada51a9dSDavid Matlack 	 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
6433ada51a9dSDavid Matlack 	 * down to the target level. This ensures pages are recursively split
6434ada51a9dSDavid Matlack 	 * all the way to the target level. There's no need to split pages
6435ada51a9dSDavid Matlack 	 * already at the target level.
6436ada51a9dSDavid Matlack 	 */
6437ada51a9dSDavid Matlack 	for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--) {
6438ada51a9dSDavid Matlack 		slot_handle_level_range(kvm, slot, shadow_mmu_try_split_huge_pages,
6439ada51a9dSDavid Matlack 					level, level, start, end - 1, true, false);
6440ada51a9dSDavid Matlack 	}
6441ada51a9dSDavid Matlack }
6442ada51a9dSDavid Matlack 
6443cb00a70bSDavid Matlack /* Must be called with the mmu_lock held in write-mode. */
6444cb00a70bSDavid Matlack void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6445cb00a70bSDavid Matlack 				   const struct kvm_memory_slot *memslot,
6446cb00a70bSDavid Matlack 				   u64 start, u64 end,
6447cb00a70bSDavid Matlack 				   int target_level)
6448cb00a70bSDavid Matlack {
64491f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6450ada51a9dSDavid Matlack 		return;
6451ada51a9dSDavid Matlack 
6452ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm))
6453ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6454ada51a9dSDavid Matlack 
6455ada51a9dSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
6456cb00a70bSDavid Matlack 
6457cb00a70bSDavid Matlack 	/*
6458cb00a70bSDavid Matlack 	 * A TLB flush is unnecessary at this point for the same resons as in
6459cb00a70bSDavid Matlack 	 * kvm_mmu_slot_try_split_huge_pages().
6460cb00a70bSDavid Matlack 	 */
6461cb00a70bSDavid Matlack }
6462cb00a70bSDavid Matlack 
6463a3fe5dbdSDavid Matlack void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6464a3fe5dbdSDavid Matlack 					const struct kvm_memory_slot *memslot,
6465a3fe5dbdSDavid Matlack 					int target_level)
6466a3fe5dbdSDavid Matlack {
6467a3fe5dbdSDavid Matlack 	u64 start = memslot->base_gfn;
6468a3fe5dbdSDavid Matlack 	u64 end = start + memslot->npages;
6469a3fe5dbdSDavid Matlack 
64701f98f2bdSDavid Matlack 	if (!tdp_mmu_enabled)
6471ada51a9dSDavid Matlack 		return;
6472ada51a9dSDavid Matlack 
6473ada51a9dSDavid Matlack 	if (kvm_memslots_have_rmaps(kvm)) {
6474ada51a9dSDavid Matlack 		write_lock(&kvm->mmu_lock);
6475ada51a9dSDavid Matlack 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6476ada51a9dSDavid Matlack 		write_unlock(&kvm->mmu_lock);
6477ada51a9dSDavid Matlack 	}
6478ada51a9dSDavid Matlack 
6479a3fe5dbdSDavid Matlack 	read_lock(&kvm->mmu_lock);
6480cb00a70bSDavid Matlack 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6481a3fe5dbdSDavid Matlack 	read_unlock(&kvm->mmu_lock);
6482a3fe5dbdSDavid Matlack 
6483a3fe5dbdSDavid Matlack 	/*
6484a3fe5dbdSDavid Matlack 	 * No TLB flush is necessary here. KVM will flush TLBs after
6485a3fe5dbdSDavid Matlack 	 * write-protecting and/or clearing dirty on the newly split SPTEs to
6486a3fe5dbdSDavid Matlack 	 * ensure that guest writes are reflected in the dirty log before the
6487a3fe5dbdSDavid Matlack 	 * ioctl to enable dirty logging on this memslot completes. Since the
6488a3fe5dbdSDavid Matlack 	 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6489a3fe5dbdSDavid Matlack 	 * safe for KVM to decide if a TLB flush is necessary based on the split
6490a3fe5dbdSDavid Matlack 	 * SPTEs.
6491a3fe5dbdSDavid Matlack 	 */
6492a3fe5dbdSDavid Matlack }
6493a3fe5dbdSDavid Matlack 
6494c50d8ae3SPaolo Bonzini static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
64950a234f5dSSean Christopherson 					 struct kvm_rmap_head *rmap_head,
6496269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
6497c50d8ae3SPaolo Bonzini {
6498c50d8ae3SPaolo Bonzini 	u64 *sptep;
6499c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
6500c50d8ae3SPaolo Bonzini 	int need_tlb_flush = 0;
6501c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6502c50d8ae3SPaolo Bonzini 
6503c50d8ae3SPaolo Bonzini restart:
6504c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
650557354682SSean Christopherson 		sp = sptep_to_sp(sptep);
6506c50d8ae3SPaolo Bonzini 
6507c50d8ae3SPaolo Bonzini 		/*
6508c50d8ae3SPaolo Bonzini 		 * We cannot do huge page mapping for indirect shadow pages,
6509c50d8ae3SPaolo Bonzini 		 * which are found on the last rmap (level = 1) when not using
6510c50d8ae3SPaolo Bonzini 		 * tdp; such shadow pages are synced with the page table in
6511c50d8ae3SPaolo Bonzini 		 * the guest, and the guest page table is using 4K page size
6512c50d8ae3SPaolo Bonzini 		 * mapping if the indirect sp has level = 1.
6513c50d8ae3SPaolo Bonzini 		 */
65145d49f08cSSean Christopherson 		if (sp->role.direct &&
65159eba50f8SSean Christopherson 		    sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
6516a8ac499bSSean Christopherson 							       PG_LEVEL_NUM)) {
65179202aee8SSean Christopherson 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
6518c50d8ae3SPaolo Bonzini 
6519c50d8ae3SPaolo Bonzini 			if (kvm_available_flush_tlb_with_range())
6520c50d8ae3SPaolo Bonzini 				kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
6521c50d8ae3SPaolo Bonzini 					KVM_PAGES_PER_HPAGE(sp->role.level));
6522c50d8ae3SPaolo Bonzini 			else
6523c50d8ae3SPaolo Bonzini 				need_tlb_flush = 1;
6524c50d8ae3SPaolo Bonzini 
6525c50d8ae3SPaolo Bonzini 			goto restart;
6526c50d8ae3SPaolo Bonzini 		}
6527c50d8ae3SPaolo Bonzini 	}
6528c50d8ae3SPaolo Bonzini 
6529c50d8ae3SPaolo Bonzini 	return need_tlb_flush;
6530c50d8ae3SPaolo Bonzini }
6531c50d8ae3SPaolo Bonzini 
653220d49186SDavid Matlack static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
653320d49186SDavid Matlack 					   const struct kvm_memory_slot *slot)
653420d49186SDavid Matlack {
653520d49186SDavid Matlack 	/*
653620d49186SDavid Matlack 	 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
653720d49186SDavid Matlack 	 * pages that are already mapped at the maximum hugepage level.
653820d49186SDavid Matlack 	 */
653920d49186SDavid Matlack 	if (slot_handle_level(kvm, slot, kvm_mmu_zap_collapsible_spte,
654020d49186SDavid Matlack 			      PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
654120d49186SDavid Matlack 		kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
654220d49186SDavid Matlack }
654320d49186SDavid Matlack 
6544c50d8ae3SPaolo Bonzini void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6545269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *slot)
6546c50d8ae3SPaolo Bonzini {
6547e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6548531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
654920d49186SDavid Matlack 		kvm_rmap_zap_collapsible_sptes(kvm, slot);
6550531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6551e2209710SBen Gardon 	}
65522db6f772SBen Gardon 
65531f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
65542db6f772SBen Gardon 		read_lock(&kvm->mmu_lock);
65554b85c921SSean Christopherson 		kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
65562db6f772SBen Gardon 		read_unlock(&kvm->mmu_lock);
65572db6f772SBen Gardon 	}
6558c50d8ae3SPaolo Bonzini }
6559c50d8ae3SPaolo Bonzini 
6560b3594ffbSSean Christopherson void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
65616c9dd6d2SPaolo Bonzini 					const struct kvm_memory_slot *memslot)
6562b3594ffbSSean Christopherson {
6563b3594ffbSSean Christopherson 	/*
65647f42aa76SSean Christopherson 	 * All current use cases for flushing the TLBs for a specific memslot
6565302695a5SSean Christopherson 	 * related to dirty logging, and many do the TLB flush out of mmu_lock.
65667f42aa76SSean Christopherson 	 * The interaction between the various operations on memslot must be
65677f42aa76SSean Christopherson 	 * serialized by slots_locks to ensure the TLB flush from one operation
65687f42aa76SSean Christopherson 	 * is observed by any other operation on the same memslot.
6569b3594ffbSSean Christopherson 	 */
6570b3594ffbSSean Christopherson 	lockdep_assert_held(&kvm->slots_lock);
6571cec37648SSean Christopherson 	kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
6572cec37648SSean Christopherson 					   memslot->npages);
6573b3594ffbSSean Christopherson }
6574b3594ffbSSean Christopherson 
6575c50d8ae3SPaolo Bonzini void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6576269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *memslot)
6577c50d8ae3SPaolo Bonzini {
6578e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
6579531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6580610265eaSDavid Matlack 		/*
6581610265eaSDavid Matlack 		 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6582610265eaSDavid Matlack 		 * support dirty logging at a 4k granularity.
6583610265eaSDavid Matlack 		 */
6584b64d740eSJunaid Shahid 		slot_handle_level_4k(kvm, memslot, __rmap_clear_dirty, false);
6585531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6586e2209710SBen Gardon 	}
6587c50d8ae3SPaolo Bonzini 
65881f98f2bdSDavid Matlack 	if (tdp_mmu_enabled) {
658924ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
6590b64d740eSJunaid Shahid 		kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
659124ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
659224ae4cfaSBen Gardon 	}
659324ae4cfaSBen Gardon 
6594c50d8ae3SPaolo Bonzini 	/*
6595b64d740eSJunaid Shahid 	 * The caller will flush the TLBs after this function returns.
6596b64d740eSJunaid Shahid 	 *
6597c50d8ae3SPaolo Bonzini 	 * It's also safe to flush TLBs out of mmu lock here as currently this
6598c50d8ae3SPaolo Bonzini 	 * function is only used for dirty logging, in which case flushing TLB
6599c50d8ae3SPaolo Bonzini 	 * out of mmu lock also guarantees no dirty pages will be lost in
6600c50d8ae3SPaolo Bonzini 	 * dirty_bitmap.
6601c50d8ae3SPaolo Bonzini 	 */
6602c50d8ae3SPaolo Bonzini }
6603c50d8ae3SPaolo Bonzini 
6604c50d8ae3SPaolo Bonzini void kvm_mmu_zap_all(struct kvm *kvm)
6605c50d8ae3SPaolo Bonzini {
6606c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
6607c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6608c50d8ae3SPaolo Bonzini 	int ign;
6609c50d8ae3SPaolo Bonzini 
6610531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6611c50d8ae3SPaolo Bonzini restart:
6612c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6613f95eec9bSSean Christopherson 		if (WARN_ON(sp->role.invalid))
6614c50d8ae3SPaolo Bonzini 			continue;
6615c50d8ae3SPaolo Bonzini 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6616c50d8ae3SPaolo Bonzini 			goto restart;
6617531810caSBen Gardon 		if (cond_resched_rwlock_write(&kvm->mmu_lock))
6618c50d8ae3SPaolo Bonzini 			goto restart;
6619c50d8ae3SPaolo Bonzini 	}
6620c50d8ae3SPaolo Bonzini 
6621c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6622faaf05b0SBen Gardon 
66231f98f2bdSDavid Matlack 	if (tdp_mmu_enabled)
6624faaf05b0SBen Gardon 		kvm_tdp_mmu_zap_all(kvm);
6625faaf05b0SBen Gardon 
6626531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
6627c50d8ae3SPaolo Bonzini }
6628c50d8ae3SPaolo Bonzini 
6629c50d8ae3SPaolo Bonzini void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6630c50d8ae3SPaolo Bonzini {
6631c50d8ae3SPaolo Bonzini 	WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6632c50d8ae3SPaolo Bonzini 
6633c50d8ae3SPaolo Bonzini 	gen &= MMIO_SPTE_GEN_MASK;
6634c50d8ae3SPaolo Bonzini 
6635c50d8ae3SPaolo Bonzini 	/*
6636c50d8ae3SPaolo Bonzini 	 * Generation numbers are incremented in multiples of the number of
6637c50d8ae3SPaolo Bonzini 	 * address spaces in order to provide unique generations across all
6638c50d8ae3SPaolo Bonzini 	 * address spaces.  Strip what is effectively the address space
6639c50d8ae3SPaolo Bonzini 	 * modifier prior to checking for a wrap of the MMIO generation so
6640c50d8ae3SPaolo Bonzini 	 * that a wrap in any address space is detected.
6641c50d8ae3SPaolo Bonzini 	 */
6642c50d8ae3SPaolo Bonzini 	gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6643c50d8ae3SPaolo Bonzini 
6644c50d8ae3SPaolo Bonzini 	/*
6645c50d8ae3SPaolo Bonzini 	 * The very rare case: if the MMIO generation number has wrapped,
6646c50d8ae3SPaolo Bonzini 	 * zap all shadow pages.
6647c50d8ae3SPaolo Bonzini 	 */
6648c50d8ae3SPaolo Bonzini 	if (unlikely(gen == 0)) {
6649c50d8ae3SPaolo Bonzini 		kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6650c50d8ae3SPaolo Bonzini 		kvm_mmu_zap_all_fast(kvm);
6651c50d8ae3SPaolo Bonzini 	}
6652c50d8ae3SPaolo Bonzini }
6653c50d8ae3SPaolo Bonzini 
6654c50d8ae3SPaolo Bonzini static unsigned long
6655c50d8ae3SPaolo Bonzini mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6656c50d8ae3SPaolo Bonzini {
6657c50d8ae3SPaolo Bonzini 	struct kvm *kvm;
6658c50d8ae3SPaolo Bonzini 	int nr_to_scan = sc->nr_to_scan;
6659c50d8ae3SPaolo Bonzini 	unsigned long freed = 0;
6660c50d8ae3SPaolo Bonzini 
6661c50d8ae3SPaolo Bonzini 	mutex_lock(&kvm_lock);
6662c50d8ae3SPaolo Bonzini 
6663c50d8ae3SPaolo Bonzini 	list_for_each_entry(kvm, &vm_list, vm_list) {
6664c50d8ae3SPaolo Bonzini 		int idx;
6665c50d8ae3SPaolo Bonzini 		LIST_HEAD(invalid_list);
6666c50d8ae3SPaolo Bonzini 
6667c50d8ae3SPaolo Bonzini 		/*
6668c50d8ae3SPaolo Bonzini 		 * Never scan more than sc->nr_to_scan VM instances.
6669c50d8ae3SPaolo Bonzini 		 * Will not hit this condition practically since we do not try
6670c50d8ae3SPaolo Bonzini 		 * to shrink more than one VM and it is very unlikely to see
6671c50d8ae3SPaolo Bonzini 		 * !n_used_mmu_pages so many times.
6672c50d8ae3SPaolo Bonzini 		 */
6673c50d8ae3SPaolo Bonzini 		if (!nr_to_scan--)
6674c50d8ae3SPaolo Bonzini 			break;
6675c50d8ae3SPaolo Bonzini 		/*
6676c50d8ae3SPaolo Bonzini 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6677c50d8ae3SPaolo Bonzini 		 * here. We may skip a VM instance errorneosly, but we do not
6678c50d8ae3SPaolo Bonzini 		 * want to shrink a VM that only started to populate its MMU
6679c50d8ae3SPaolo Bonzini 		 * anyway.
6680c50d8ae3SPaolo Bonzini 		 */
6681c50d8ae3SPaolo Bonzini 		if (!kvm->arch.n_used_mmu_pages &&
6682c50d8ae3SPaolo Bonzini 		    !kvm_has_zapped_obsolete_pages(kvm))
6683c50d8ae3SPaolo Bonzini 			continue;
6684c50d8ae3SPaolo Bonzini 
6685c50d8ae3SPaolo Bonzini 		idx = srcu_read_lock(&kvm->srcu);
6686531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
6687c50d8ae3SPaolo Bonzini 
6688c50d8ae3SPaolo Bonzini 		if (kvm_has_zapped_obsolete_pages(kvm)) {
6689c50d8ae3SPaolo Bonzini 			kvm_mmu_commit_zap_page(kvm,
6690c50d8ae3SPaolo Bonzini 			      &kvm->arch.zapped_obsolete_pages);
6691c50d8ae3SPaolo Bonzini 			goto unlock;
6692c50d8ae3SPaolo Bonzini 		}
6693c50d8ae3SPaolo Bonzini 
6694ebdb292dSSean Christopherson 		freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6695c50d8ae3SPaolo Bonzini 
6696c50d8ae3SPaolo Bonzini unlock:
6697531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
6698c50d8ae3SPaolo Bonzini 		srcu_read_unlock(&kvm->srcu, idx);
6699c50d8ae3SPaolo Bonzini 
6700c50d8ae3SPaolo Bonzini 		/*
6701c50d8ae3SPaolo Bonzini 		 * unfair on small ones
6702c50d8ae3SPaolo Bonzini 		 * per-vm shrinkers cry out
6703c50d8ae3SPaolo Bonzini 		 * sadness comes quickly
6704c50d8ae3SPaolo Bonzini 		 */
6705c50d8ae3SPaolo Bonzini 		list_move_tail(&kvm->vm_list, &vm_list);
6706c50d8ae3SPaolo Bonzini 		break;
6707c50d8ae3SPaolo Bonzini 	}
6708c50d8ae3SPaolo Bonzini 
6709c50d8ae3SPaolo Bonzini 	mutex_unlock(&kvm_lock);
6710c50d8ae3SPaolo Bonzini 	return freed;
6711c50d8ae3SPaolo Bonzini }
6712c50d8ae3SPaolo Bonzini 
6713c50d8ae3SPaolo Bonzini static unsigned long
6714c50d8ae3SPaolo Bonzini mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6715c50d8ae3SPaolo Bonzini {
6716c50d8ae3SPaolo Bonzini 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6717c50d8ae3SPaolo Bonzini }
6718c50d8ae3SPaolo Bonzini 
6719c50d8ae3SPaolo Bonzini static struct shrinker mmu_shrinker = {
6720c50d8ae3SPaolo Bonzini 	.count_objects = mmu_shrink_count,
6721c50d8ae3SPaolo Bonzini 	.scan_objects = mmu_shrink_scan,
6722c50d8ae3SPaolo Bonzini 	.seeks = DEFAULT_SEEKS * 10,
6723c50d8ae3SPaolo Bonzini };
6724c50d8ae3SPaolo Bonzini 
6725c50d8ae3SPaolo Bonzini static void mmu_destroy_caches(void)
6726c50d8ae3SPaolo Bonzini {
6727c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(pte_list_desc_cache);
6728c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(mmu_page_header_cache);
6729c50d8ae3SPaolo Bonzini }
6730c50d8ae3SPaolo Bonzini 
6731c50d8ae3SPaolo Bonzini static bool get_nx_auto_mode(void)
6732c50d8ae3SPaolo Bonzini {
6733c50d8ae3SPaolo Bonzini 	/* Return true when CPU has the bug, and mitigations are ON */
6734c50d8ae3SPaolo Bonzini 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6735c50d8ae3SPaolo Bonzini }
6736c50d8ae3SPaolo Bonzini 
6737c50d8ae3SPaolo Bonzini static void __set_nx_huge_pages(bool val)
6738c50d8ae3SPaolo Bonzini {
6739c50d8ae3SPaolo Bonzini 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6740c50d8ae3SPaolo Bonzini }
6741c50d8ae3SPaolo Bonzini 
6742c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6743c50d8ae3SPaolo Bonzini {
6744c50d8ae3SPaolo Bonzini 	bool old_val = nx_huge_pages;
6745c50d8ae3SPaolo Bonzini 	bool new_val;
6746c50d8ae3SPaolo Bonzini 
6747c50d8ae3SPaolo Bonzini 	/* In "auto" mode deploy workaround only if CPU has the bug. */
6748c50d8ae3SPaolo Bonzini 	if (sysfs_streq(val, "off"))
6749c50d8ae3SPaolo Bonzini 		new_val = 0;
6750c50d8ae3SPaolo Bonzini 	else if (sysfs_streq(val, "force"))
6751c50d8ae3SPaolo Bonzini 		new_val = 1;
6752c50d8ae3SPaolo Bonzini 	else if (sysfs_streq(val, "auto"))
6753c50d8ae3SPaolo Bonzini 		new_val = get_nx_auto_mode();
6754c50d8ae3SPaolo Bonzini 	else if (strtobool(val, &new_val) < 0)
6755c50d8ae3SPaolo Bonzini 		return -EINVAL;
6756c50d8ae3SPaolo Bonzini 
6757c50d8ae3SPaolo Bonzini 	__set_nx_huge_pages(new_val);
6758c50d8ae3SPaolo Bonzini 
6759c50d8ae3SPaolo Bonzini 	if (new_val != old_val) {
6760c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6761c50d8ae3SPaolo Bonzini 
6762c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6763c50d8ae3SPaolo Bonzini 
6764c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list) {
6765c50d8ae3SPaolo Bonzini 			mutex_lock(&kvm->slots_lock);
6766c50d8ae3SPaolo Bonzini 			kvm_mmu_zap_all_fast(kvm);
6767c50d8ae3SPaolo Bonzini 			mutex_unlock(&kvm->slots_lock);
6768c50d8ae3SPaolo Bonzini 
676955c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
6770c50d8ae3SPaolo Bonzini 		}
6771c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6772c50d8ae3SPaolo Bonzini 	}
6773c50d8ae3SPaolo Bonzini 
6774c50d8ae3SPaolo Bonzini 	return 0;
6775c50d8ae3SPaolo Bonzini }
6776c50d8ae3SPaolo Bonzini 
67771d0e8480SSean Christopherson /*
67781d0e8480SSean Christopherson  * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
67791d0e8480SSean Christopherson  * its default value of -1 is technically undefined behavior for a boolean.
6780c3e0c8c2SSean Christopherson  * Forward the module init call to SPTE code so that it too can handle module
6781c3e0c8c2SSean Christopherson  * params that need to be resolved/snapshot.
67821d0e8480SSean Christopherson  */
6783982bae43SSean Christopherson void __init kvm_mmu_x86_module_init(void)
6784c50d8ae3SPaolo Bonzini {
6785c50d8ae3SPaolo Bonzini 	if (nx_huge_pages == -1)
6786c50d8ae3SPaolo Bonzini 		__set_nx_huge_pages(get_nx_auto_mode());
6787c3e0c8c2SSean Christopherson 
67881f98f2bdSDavid Matlack 	/*
67891f98f2bdSDavid Matlack 	 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
67901f98f2bdSDavid Matlack 	 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
67911f98f2bdSDavid Matlack 	 * when the vendor module is loaded.
67921f98f2bdSDavid Matlack 	 */
67931f98f2bdSDavid Matlack 	tdp_mmu_allowed = tdp_mmu_enabled;
67941f98f2bdSDavid Matlack 
6795c3e0c8c2SSean Christopherson 	kvm_mmu_spte_module_init();
67961d0e8480SSean Christopherson }
67971d0e8480SSean Christopherson 
67981d0e8480SSean Christopherson /*
67991d0e8480SSean Christopherson  * The bulk of the MMU initialization is deferred until the vendor module is
68001d0e8480SSean Christopherson  * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
68011d0e8480SSean Christopherson  * to be reset when a potentially different vendor module is loaded.
68021d0e8480SSean Christopherson  */
68031d0e8480SSean Christopherson int kvm_mmu_vendor_module_init(void)
68041d0e8480SSean Christopherson {
68051d0e8480SSean Christopherson 	int ret = -ENOMEM;
6806c50d8ae3SPaolo Bonzini 
6807c50d8ae3SPaolo Bonzini 	/*
6808c50d8ae3SPaolo Bonzini 	 * MMU roles use union aliasing which is, generally speaking, an
6809c50d8ae3SPaolo Bonzini 	 * undefined behavior. However, we supposedly know how compilers behave
6810c50d8ae3SPaolo Bonzini 	 * and the current status quo is unlikely to change. Guardians below are
6811c50d8ae3SPaolo Bonzini 	 * supposed to let us know if the assumption becomes false.
6812c50d8ae3SPaolo Bonzini 	 */
6813c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6814c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
68157a7ae829SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
6816c50d8ae3SPaolo Bonzini 
6817c50d8ae3SPaolo Bonzini 	kvm_mmu_reset_all_pte_masks();
6818c50d8ae3SPaolo Bonzini 
6819c50d8ae3SPaolo Bonzini 	pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6820c50d8ae3SPaolo Bonzini 					    sizeof(struct pte_list_desc),
6821c50d8ae3SPaolo Bonzini 					    0, SLAB_ACCOUNT, NULL);
6822c50d8ae3SPaolo Bonzini 	if (!pte_list_desc_cache)
6823c50d8ae3SPaolo Bonzini 		goto out;
6824c50d8ae3SPaolo Bonzini 
6825c50d8ae3SPaolo Bonzini 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6826c50d8ae3SPaolo Bonzini 						  sizeof(struct kvm_mmu_page),
6827c50d8ae3SPaolo Bonzini 						  0, SLAB_ACCOUNT, NULL);
6828c50d8ae3SPaolo Bonzini 	if (!mmu_page_header_cache)
6829c50d8ae3SPaolo Bonzini 		goto out;
6830c50d8ae3SPaolo Bonzini 
6831c50d8ae3SPaolo Bonzini 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6832c50d8ae3SPaolo Bonzini 		goto out;
6833c50d8ae3SPaolo Bonzini 
6834e33c267aSRoman Gushchin 	ret = register_shrinker(&mmu_shrinker, "x86-mmu");
6835c50d8ae3SPaolo Bonzini 	if (ret)
6836d7c9bfb9SMiaohe Lin 		goto out_shrinker;
6837c50d8ae3SPaolo Bonzini 
6838c50d8ae3SPaolo Bonzini 	return 0;
6839c50d8ae3SPaolo Bonzini 
6840d7c9bfb9SMiaohe Lin out_shrinker:
6841d7c9bfb9SMiaohe Lin 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6842c50d8ae3SPaolo Bonzini out:
6843c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6844c50d8ae3SPaolo Bonzini 	return ret;
6845c50d8ae3SPaolo Bonzini }
6846c50d8ae3SPaolo Bonzini 
6847c50d8ae3SPaolo Bonzini void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6848c50d8ae3SPaolo Bonzini {
6849c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
6850c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.root_mmu);
6851c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
6852c50d8ae3SPaolo Bonzini 	mmu_free_memory_caches(vcpu);
6853c50d8ae3SPaolo Bonzini }
6854c50d8ae3SPaolo Bonzini 
68551d0e8480SSean Christopherson void kvm_mmu_vendor_module_exit(void)
6856c50d8ae3SPaolo Bonzini {
6857c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6858c50d8ae3SPaolo Bonzini 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6859c50d8ae3SPaolo Bonzini 	unregister_shrinker(&mmu_shrinker);
6860c50d8ae3SPaolo Bonzini }
6861c50d8ae3SPaolo Bonzini 
6862f47491d7SSean Christopherson /*
6863f47491d7SSean Christopherson  * Calculate the effective recovery period, accounting for '0' meaning "let KVM
6864f47491d7SSean Christopherson  * select a halving time of 1 hour".  Returns true if recovery is enabled.
6865f47491d7SSean Christopherson  */
6866f47491d7SSean Christopherson static bool calc_nx_huge_pages_recovery_period(uint *period)
6867f47491d7SSean Christopherson {
6868f47491d7SSean Christopherson 	/*
6869f47491d7SSean Christopherson 	 * Use READ_ONCE to get the params, this may be called outside of the
6870f47491d7SSean Christopherson 	 * param setters, e.g. by the kthread to compute its next timeout.
6871f47491d7SSean Christopherson 	 */
6872f47491d7SSean Christopherson 	bool enabled = READ_ONCE(nx_huge_pages);
6873f47491d7SSean Christopherson 	uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6874f47491d7SSean Christopherson 
6875f47491d7SSean Christopherson 	if (!enabled || !ratio)
6876f47491d7SSean Christopherson 		return false;
6877f47491d7SSean Christopherson 
6878f47491d7SSean Christopherson 	*period = READ_ONCE(nx_huge_pages_recovery_period_ms);
6879f47491d7SSean Christopherson 	if (!*period) {
6880f47491d7SSean Christopherson 		/* Make sure the period is not less than one second.  */
6881f47491d7SSean Christopherson 		ratio = min(ratio, 3600u);
6882f47491d7SSean Christopherson 		*period = 60 * 60 * 1000 / ratio;
6883f47491d7SSean Christopherson 	}
6884f47491d7SSean Christopherson 	return true;
6885f47491d7SSean Christopherson }
6886f47491d7SSean Christopherson 
68874dfe4f40SJunaid Shahid static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
6888c50d8ae3SPaolo Bonzini {
68894dfe4f40SJunaid Shahid 	bool was_recovery_enabled, is_recovery_enabled;
68904dfe4f40SJunaid Shahid 	uint old_period, new_period;
6891c50d8ae3SPaolo Bonzini 	int err;
6892c50d8ae3SPaolo Bonzini 
6893f47491d7SSean Christopherson 	was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
68944dfe4f40SJunaid Shahid 
6895c50d8ae3SPaolo Bonzini 	err = param_set_uint(val, kp);
6896c50d8ae3SPaolo Bonzini 	if (err)
6897c50d8ae3SPaolo Bonzini 		return err;
6898c50d8ae3SPaolo Bonzini 
6899f47491d7SSean Christopherson 	is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
69004dfe4f40SJunaid Shahid 
6901f47491d7SSean Christopherson 	if (is_recovery_enabled &&
69024dfe4f40SJunaid Shahid 	    (!was_recovery_enabled || old_period > new_period)) {
6903c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6904c50d8ae3SPaolo Bonzini 
6905c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6906c50d8ae3SPaolo Bonzini 
6907c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list)
690855c510e2SSean Christopherson 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
6909c50d8ae3SPaolo Bonzini 
6910c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6911c50d8ae3SPaolo Bonzini 	}
6912c50d8ae3SPaolo Bonzini 
6913c50d8ae3SPaolo Bonzini 	return err;
6914c50d8ae3SPaolo Bonzini }
6915c50d8ae3SPaolo Bonzini 
691655c510e2SSean Christopherson static void kvm_recover_nx_huge_pages(struct kvm *kvm)
6917c50d8ae3SPaolo Bonzini {
6918ade74e14SSean Christopherson 	unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
6919eb298605SDavid Matlack 	struct kvm_memory_slot *slot;
6920c50d8ae3SPaolo Bonzini 	int rcu_idx;
6921c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6922c50d8ae3SPaolo Bonzini 	unsigned int ratio;
6923c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6924048f4980SSean Christopherson 	bool flush = false;
6925c50d8ae3SPaolo Bonzini 	ulong to_zap;
6926c50d8ae3SPaolo Bonzini 
6927c50d8ae3SPaolo Bonzini 	rcu_idx = srcu_read_lock(&kvm->srcu);
6928531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6929c50d8ae3SPaolo Bonzini 
6930bb95dfb9SSean Christopherson 	/*
6931bb95dfb9SSean Christopherson 	 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
6932bb95dfb9SSean Christopherson 	 * be done under RCU protection, because the pages are freed via RCU
6933bb95dfb9SSean Christopherson 	 * callback.
6934bb95dfb9SSean Christopherson 	 */
6935bb95dfb9SSean Christopherson 	rcu_read_lock();
6936bb95dfb9SSean Christopherson 
6937c50d8ae3SPaolo Bonzini 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6938ade74e14SSean Christopherson 	to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
69397d919c7aSSean Christopherson 	for ( ; to_zap; --to_zap) {
694055c510e2SSean Christopherson 		if (list_empty(&kvm->arch.possible_nx_huge_pages))
69417d919c7aSSean Christopherson 			break;
69427d919c7aSSean Christopherson 
6943c50d8ae3SPaolo Bonzini 		/*
6944c50d8ae3SPaolo Bonzini 		 * We use a separate list instead of just using active_mmu_pages
694555c510e2SSean Christopherson 		 * because the number of shadow pages that be replaced with an
694655c510e2SSean Christopherson 		 * NX huge page is expected to be relatively small compared to
694755c510e2SSean Christopherson 		 * the total number of shadow pages.  And because the TDP MMU
694855c510e2SSean Christopherson 		 * doesn't use active_mmu_pages.
6949c50d8ae3SPaolo Bonzini 		 */
695055c510e2SSean Christopherson 		sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
6951c50d8ae3SPaolo Bonzini 				      struct kvm_mmu_page,
695255c510e2SSean Christopherson 				      possible_nx_huge_page_link);
695355c510e2SSean Christopherson 		WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
6954eb298605SDavid Matlack 		WARN_ON_ONCE(!sp->role.direct);
6955eb298605SDavid Matlack 
6956eb298605SDavid Matlack 		/*
6957eb298605SDavid Matlack 		 * Unaccount and do not attempt to recover any NX Huge Pages
6958eb298605SDavid Matlack 		 * that are being dirty tracked, as they would just be faulted
6959eb298605SDavid Matlack 		 * back in as 4KiB pages. The NX Huge Pages in this slot will be
6960eb298605SDavid Matlack 		 * recovered, along with all the other huge pages in the slot,
6961eb298605SDavid Matlack 		 * when dirty logging is disabled.
69626c7b2202SPaolo Bonzini 		 *
69636c7b2202SPaolo Bonzini 		 * Since gfn_to_memslot() is relatively expensive, it helps to
69646c7b2202SPaolo Bonzini 		 * skip it if it the test cannot possibly return true.  On the
69656c7b2202SPaolo Bonzini 		 * other hand, if any memslot has logging enabled, chances are
69666c7b2202SPaolo Bonzini 		 * good that all of them do, in which case unaccount_nx_huge_page()
69676c7b2202SPaolo Bonzini 		 * is much cheaper than zapping the page.
69686c7b2202SPaolo Bonzini 		 *
69696c7b2202SPaolo Bonzini 		 * If a memslot update is in progress, reading an incorrect value
69706c7b2202SPaolo Bonzini 		 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
69716c7b2202SPaolo Bonzini 		 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
69726c7b2202SPaolo Bonzini 		 * it is becoming nonzero, the page will be zapped unnecessarily.
69736c7b2202SPaolo Bonzini 		 * Either way, this only affects efficiency in racy situations,
69746c7b2202SPaolo Bonzini 		 * and not correctness.
6975eb298605SDavid Matlack 		 */
69766c7b2202SPaolo Bonzini 		slot = NULL;
69776c7b2202SPaolo Bonzini 		if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
69786c7b2202SPaolo Bonzini 			slot = gfn_to_memslot(kvm, sp->gfn);
69796c7b2202SPaolo Bonzini 			WARN_ON_ONCE(!slot);
69806c7b2202SPaolo Bonzini 		}
69816c7b2202SPaolo Bonzini 
6982eb298605SDavid Matlack 		if (slot && kvm_slot_dirty_track_enabled(slot))
6983eb298605SDavid Matlack 			unaccount_nx_huge_page(kvm, sp);
6984eb298605SDavid Matlack 		else if (is_tdp_mmu_page(sp))
6985315f02c6SPaolo Bonzini 			flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
69863a056757SSean Christopherson 		else
6987c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
698855c510e2SSean Christopherson 		WARN_ON_ONCE(sp->nx_huge_page_disallowed);
6989c50d8ae3SPaolo Bonzini 
6990531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
6991048f4980SSean Christopherson 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
6992bb95dfb9SSean Christopherson 			rcu_read_unlock();
6993bb95dfb9SSean Christopherson 
6994531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
6995048f4980SSean Christopherson 			flush = false;
6996bb95dfb9SSean Christopherson 
6997bb95dfb9SSean Christopherson 			rcu_read_lock();
6998c50d8ae3SPaolo Bonzini 		}
6999c50d8ae3SPaolo Bonzini 	}
7000048f4980SSean Christopherson 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7001c50d8ae3SPaolo Bonzini 
7002bb95dfb9SSean Christopherson 	rcu_read_unlock();
7003bb95dfb9SSean Christopherson 
7004531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
7005c50d8ae3SPaolo Bonzini 	srcu_read_unlock(&kvm->srcu, rcu_idx);
7006c50d8ae3SPaolo Bonzini }
7007c50d8ae3SPaolo Bonzini 
700855c510e2SSean Christopherson static long get_nx_huge_page_recovery_timeout(u64 start_time)
7009c50d8ae3SPaolo Bonzini {
7010f47491d7SSean Christopherson 	bool enabled;
7011f47491d7SSean Christopherson 	uint period;
70124dfe4f40SJunaid Shahid 
7013f47491d7SSean Christopherson 	enabled = calc_nx_huge_pages_recovery_period(&period);
70144dfe4f40SJunaid Shahid 
7015f47491d7SSean Christopherson 	return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
7016c50d8ae3SPaolo Bonzini 		       : MAX_SCHEDULE_TIMEOUT;
7017c50d8ae3SPaolo Bonzini }
7018c50d8ae3SPaolo Bonzini 
701955c510e2SSean Christopherson static int kvm_nx_huge_page_recovery_worker(struct kvm *kvm, uintptr_t data)
7020c50d8ae3SPaolo Bonzini {
7021c50d8ae3SPaolo Bonzini 	u64 start_time;
7022c50d8ae3SPaolo Bonzini 	long remaining_time;
7023c50d8ae3SPaolo Bonzini 
7024c50d8ae3SPaolo Bonzini 	while (true) {
7025c50d8ae3SPaolo Bonzini 		start_time = get_jiffies_64();
702655c510e2SSean Christopherson 		remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7027c50d8ae3SPaolo Bonzini 
7028c50d8ae3SPaolo Bonzini 		set_current_state(TASK_INTERRUPTIBLE);
7029c50d8ae3SPaolo Bonzini 		while (!kthread_should_stop() && remaining_time > 0) {
7030c50d8ae3SPaolo Bonzini 			schedule_timeout(remaining_time);
703155c510e2SSean Christopherson 			remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7032c50d8ae3SPaolo Bonzini 			set_current_state(TASK_INTERRUPTIBLE);
7033c50d8ae3SPaolo Bonzini 		}
7034c50d8ae3SPaolo Bonzini 
7035c50d8ae3SPaolo Bonzini 		set_current_state(TASK_RUNNING);
7036c50d8ae3SPaolo Bonzini 
7037c50d8ae3SPaolo Bonzini 		if (kthread_should_stop())
7038c50d8ae3SPaolo Bonzini 			return 0;
7039c50d8ae3SPaolo Bonzini 
704055c510e2SSean Christopherson 		kvm_recover_nx_huge_pages(kvm);
7041c50d8ae3SPaolo Bonzini 	}
7042c50d8ae3SPaolo Bonzini }
7043c50d8ae3SPaolo Bonzini 
7044c50d8ae3SPaolo Bonzini int kvm_mmu_post_init_vm(struct kvm *kvm)
7045c50d8ae3SPaolo Bonzini {
7046c50d8ae3SPaolo Bonzini 	int err;
7047c50d8ae3SPaolo Bonzini 
704855c510e2SSean Christopherson 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_huge_page_recovery_worker, 0,
7049c50d8ae3SPaolo Bonzini 					  "kvm-nx-lpage-recovery",
705055c510e2SSean Christopherson 					  &kvm->arch.nx_huge_page_recovery_thread);
7051c50d8ae3SPaolo Bonzini 	if (!err)
705255c510e2SSean Christopherson 		kthread_unpark(kvm->arch.nx_huge_page_recovery_thread);
7053c50d8ae3SPaolo Bonzini 
7054c50d8ae3SPaolo Bonzini 	return err;
7055c50d8ae3SPaolo Bonzini }
7056c50d8ae3SPaolo Bonzini 
7057c50d8ae3SPaolo Bonzini void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7058c50d8ae3SPaolo Bonzini {
705955c510e2SSean Christopherson 	if (kvm->arch.nx_huge_page_recovery_thread)
706055c510e2SSean Christopherson 		kthread_stop(kvm->arch.nx_huge_page_recovery_thread);
7061c50d8ae3SPaolo Bonzini }
7062