xref: /linux/arch/x86/kvm/mmu/mmu.c (revision 5a324c24b638d0f3194e1dc8f0cebd28a0745238)
1c50d8ae3SPaolo Bonzini // SPDX-License-Identifier: GPL-2.0-only
2c50d8ae3SPaolo Bonzini /*
3c50d8ae3SPaolo Bonzini  * Kernel-based Virtual Machine driver for Linux
4c50d8ae3SPaolo Bonzini  *
5c50d8ae3SPaolo Bonzini  * This module enables machines with Intel VT-x extensions to run virtual
6c50d8ae3SPaolo Bonzini  * machines without emulation or binary translation.
7c50d8ae3SPaolo Bonzini  *
8c50d8ae3SPaolo Bonzini  * MMU support
9c50d8ae3SPaolo Bonzini  *
10c50d8ae3SPaolo Bonzini  * Copyright (C) 2006 Qumranet, Inc.
11c50d8ae3SPaolo Bonzini  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12c50d8ae3SPaolo Bonzini  *
13c50d8ae3SPaolo Bonzini  * Authors:
14c50d8ae3SPaolo Bonzini  *   Yaniv Kamay  <yaniv@qumranet.com>
15c50d8ae3SPaolo Bonzini  *   Avi Kivity   <avi@qumranet.com>
16c50d8ae3SPaolo Bonzini  */
17c50d8ae3SPaolo Bonzini 
18c50d8ae3SPaolo Bonzini #include "irq.h"
1988197e6aS彭浩(Richard) #include "ioapic.h"
20c50d8ae3SPaolo Bonzini #include "mmu.h"
216ca9a6f3SSean Christopherson #include "mmu_internal.h"
22fe5db27dSBen Gardon #include "tdp_mmu.h"
23c50d8ae3SPaolo Bonzini #include "x86.h"
24c50d8ae3SPaolo Bonzini #include "kvm_cache_regs.h"
252f728d66SSean Christopherson #include "kvm_emulate.h"
26c50d8ae3SPaolo Bonzini #include "cpuid.h"
275a9624afSPaolo Bonzini #include "spte.h"
28c50d8ae3SPaolo Bonzini 
29c50d8ae3SPaolo Bonzini #include <linux/kvm_host.h>
30c50d8ae3SPaolo Bonzini #include <linux/types.h>
31c50d8ae3SPaolo Bonzini #include <linux/string.h>
32c50d8ae3SPaolo Bonzini #include <linux/mm.h>
33c50d8ae3SPaolo Bonzini #include <linux/highmem.h>
34c50d8ae3SPaolo Bonzini #include <linux/moduleparam.h>
35c50d8ae3SPaolo Bonzini #include <linux/export.h>
36c50d8ae3SPaolo Bonzini #include <linux/swap.h>
37c50d8ae3SPaolo Bonzini #include <linux/hugetlb.h>
38c50d8ae3SPaolo Bonzini #include <linux/compiler.h>
39c50d8ae3SPaolo Bonzini #include <linux/srcu.h>
40c50d8ae3SPaolo Bonzini #include <linux/slab.h>
41c50d8ae3SPaolo Bonzini #include <linux/sched/signal.h>
42c50d8ae3SPaolo Bonzini #include <linux/uaccess.h>
43c50d8ae3SPaolo Bonzini #include <linux/hash.h>
44c50d8ae3SPaolo Bonzini #include <linux/kern_levels.h>
45c50d8ae3SPaolo Bonzini #include <linux/kthread.h>
46c50d8ae3SPaolo Bonzini 
47c50d8ae3SPaolo Bonzini #include <asm/page.h>
48eb243d1dSIngo Molnar #include <asm/memtype.h>
49c50d8ae3SPaolo Bonzini #include <asm/cmpxchg.h>
50c50d8ae3SPaolo Bonzini #include <asm/io.h>
514a98623dSSean Christopherson #include <asm/set_memory.h>
52c50d8ae3SPaolo Bonzini #include <asm/vmx.h>
53c50d8ae3SPaolo Bonzini #include <asm/kvm_page_track.h>
54c50d8ae3SPaolo Bonzini #include "trace.h"
55c50d8ae3SPaolo Bonzini 
56fc9bf2e0SSean Christopherson #include "paging.h"
57fc9bf2e0SSean Christopherson 
58c50d8ae3SPaolo Bonzini extern bool itlb_multihit_kvm_mitigation;
59c50d8ae3SPaolo Bonzini 
60a9d6496dSShaokun Zhang int __read_mostly nx_huge_pages = -1;
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);
69c50d8ae3SPaolo Bonzini static int set_nx_huge_pages_recovery_ratio(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 
76d5d6c18dSJoe Perches static const struct kernel_param_ops nx_huge_pages_recovery_ratio_ops = {
77c50d8ae3SPaolo Bonzini 	.set = set_nx_huge_pages_recovery_ratio,
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");
83c50d8ae3SPaolo Bonzini module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_ratio_ops,
84c50d8ae3SPaolo Bonzini 		&nx_huge_pages_recovery_ratio, 0644);
85c50d8ae3SPaolo Bonzini __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
86c50d8ae3SPaolo Bonzini 
8771fe7013SSean Christopherson static bool __read_mostly force_flush_and_sync_on_reuse;
8871fe7013SSean Christopherson module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
8971fe7013SSean Christopherson 
90c50d8ae3SPaolo Bonzini /*
91c50d8ae3SPaolo Bonzini  * When setting this variable to true it enables Two-Dimensional-Paging
92c50d8ae3SPaolo Bonzini  * where the hardware walks 2 page tables:
93c50d8ae3SPaolo Bonzini  * 1. the guest-virtual to guest-physical
94c50d8ae3SPaolo Bonzini  * 2. while doing 1. it walks guest-physical to host-physical
95c50d8ae3SPaolo Bonzini  * If the hardware supports that we don't need to do shadow paging.
96c50d8ae3SPaolo Bonzini  */
97c50d8ae3SPaolo Bonzini bool tdp_enabled = false;
98c50d8ae3SPaolo Bonzini 
991d92d2e8SSean Christopherson static int max_huge_page_level __read_mostly;
10083013059SSean Christopherson static int max_tdp_level __read_mostly;
101703c335dSSean Christopherson 
102c50d8ae3SPaolo Bonzini enum {
103c50d8ae3SPaolo Bonzini 	AUDIT_PRE_PAGE_FAULT,
104c50d8ae3SPaolo Bonzini 	AUDIT_POST_PAGE_FAULT,
105c50d8ae3SPaolo Bonzini 	AUDIT_PRE_PTE_WRITE,
106c50d8ae3SPaolo Bonzini 	AUDIT_POST_PTE_WRITE,
107c50d8ae3SPaolo Bonzini 	AUDIT_PRE_SYNC,
108c50d8ae3SPaolo Bonzini 	AUDIT_POST_SYNC
109c50d8ae3SPaolo Bonzini };
110c50d8ae3SPaolo Bonzini 
111c50d8ae3SPaolo Bonzini #ifdef MMU_DEBUG
1125a9624afSPaolo Bonzini bool dbg = 0;
113c50d8ae3SPaolo Bonzini module_param(dbg, bool, 0644);
114c50d8ae3SPaolo Bonzini #endif
115c50d8ae3SPaolo Bonzini 
116c50d8ae3SPaolo Bonzini #define PTE_PREFETCH_NUM		8
117c50d8ae3SPaolo Bonzini 
118c50d8ae3SPaolo Bonzini #define PT32_LEVEL_BITS 10
119c50d8ae3SPaolo Bonzini 
120c50d8ae3SPaolo Bonzini #define PT32_LEVEL_SHIFT(level) \
121c50d8ae3SPaolo Bonzini 		(PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
122c50d8ae3SPaolo Bonzini 
123c50d8ae3SPaolo Bonzini #define PT32_LVL_OFFSET_MASK(level) \
124c50d8ae3SPaolo Bonzini 	(PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
125c50d8ae3SPaolo Bonzini 						* PT32_LEVEL_BITS))) - 1))
126c50d8ae3SPaolo Bonzini 
127c50d8ae3SPaolo Bonzini #define PT32_INDEX(address, level)\
128c50d8ae3SPaolo Bonzini 	(((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
129c50d8ae3SPaolo Bonzini 
130c50d8ae3SPaolo Bonzini 
131c50d8ae3SPaolo Bonzini #define PT32_BASE_ADDR_MASK PAGE_MASK
132c50d8ae3SPaolo Bonzini #define PT32_DIR_BASE_ADDR_MASK \
133c50d8ae3SPaolo Bonzini 	(PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
134c50d8ae3SPaolo Bonzini #define PT32_LVL_ADDR_MASK(level) \
135c50d8ae3SPaolo Bonzini 	(PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
136c50d8ae3SPaolo Bonzini 					    * PT32_LEVEL_BITS))) - 1))
137c50d8ae3SPaolo Bonzini 
138c50d8ae3SPaolo Bonzini #include <trace/events/kvm.h>
139c50d8ae3SPaolo Bonzini 
140dc1cff96SPeter Xu /* make pte_list_desc fit well in cache lines */
14113236e25SPeter Xu #define PTE_LIST_EXT 14
142c50d8ae3SPaolo Bonzini 
14313236e25SPeter Xu /*
14413236e25SPeter Xu  * Slight optimization of cacheline layout, by putting `more' and `spte_count'
14513236e25SPeter Xu  * at the start; then accessing it will only use one single cacheline for
14613236e25SPeter Xu  * either full (entries==PTE_LIST_EXT) case or entries<=6.
14713236e25SPeter Xu  */
148c50d8ae3SPaolo Bonzini struct pte_list_desc {
149c50d8ae3SPaolo Bonzini 	struct pte_list_desc *more;
15013236e25SPeter Xu 	/*
15113236e25SPeter Xu 	 * Stores number of entries stored in the pte_list_desc.  No need to be
15213236e25SPeter Xu 	 * u64 but just for easier alignment.  When PTE_LIST_EXT, means full.
15313236e25SPeter Xu 	 */
15413236e25SPeter Xu 	u64 spte_count;
15513236e25SPeter Xu 	u64 *sptes[PTE_LIST_EXT];
156c50d8ae3SPaolo Bonzini };
157c50d8ae3SPaolo Bonzini 
158c50d8ae3SPaolo Bonzini struct kvm_shadow_walk_iterator {
159c50d8ae3SPaolo Bonzini 	u64 addr;
160c50d8ae3SPaolo Bonzini 	hpa_t shadow_addr;
161c50d8ae3SPaolo Bonzini 	u64 *sptep;
162c50d8ae3SPaolo Bonzini 	int level;
163c50d8ae3SPaolo Bonzini 	unsigned index;
164c50d8ae3SPaolo Bonzini };
165c50d8ae3SPaolo Bonzini 
166c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
167c50d8ae3SPaolo Bonzini 	for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
168c50d8ae3SPaolo Bonzini 					 (_root), (_addr));                \
169c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			           \
170c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
171c50d8ae3SPaolo Bonzini 
172c50d8ae3SPaolo Bonzini #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
173c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);	\
174c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker));			\
175c50d8ae3SPaolo Bonzini 	     shadow_walk_next(&(_walker)))
176c50d8ae3SPaolo Bonzini 
177c50d8ae3SPaolo Bonzini #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)	\
178c50d8ae3SPaolo Bonzini 	for (shadow_walk_init(&(_walker), _vcpu, _addr);		\
179c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&(_walker)) &&				\
180c50d8ae3SPaolo Bonzini 		({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });	\
181c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&(_walker), spte))
182c50d8ae3SPaolo Bonzini 
183c50d8ae3SPaolo Bonzini static struct kmem_cache *pte_list_desc_cache;
18402c00b3aSBen Gardon struct kmem_cache *mmu_page_header_cache;
185c50d8ae3SPaolo Bonzini static struct percpu_counter kvm_total_used_mmu_pages;
186c50d8ae3SPaolo Bonzini 
187c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 spte);
188c50d8ae3SPaolo Bonzini static union kvm_mmu_page_role
189c50d8ae3SPaolo Bonzini kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
190c50d8ae3SPaolo Bonzini 
191594e91a1SSean Christopherson struct kvm_mmu_role_regs {
192594e91a1SSean Christopherson 	const unsigned long cr0;
193594e91a1SSean Christopherson 	const unsigned long cr4;
194594e91a1SSean Christopherson 	const u64 efer;
195594e91a1SSean Christopherson };
196594e91a1SSean Christopherson 
197c50d8ae3SPaolo Bonzini #define CREATE_TRACE_POINTS
198c50d8ae3SPaolo Bonzini #include "mmutrace.h"
199c50d8ae3SPaolo Bonzini 
200594e91a1SSean Christopherson /*
201594e91a1SSean Christopherson  * Yes, lot's of underscores.  They're a hint that you probably shouldn't be
202594e91a1SSean Christopherson  * reading from the role_regs.  Once the mmu_role is constructed, it becomes
203594e91a1SSean Christopherson  * the single source of truth for the MMU's state.
204594e91a1SSean Christopherson  */
205594e91a1SSean Christopherson #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag)			\
206594e91a1SSean Christopherson static inline bool ____is_##reg##_##name(struct kvm_mmu_role_regs *regs)\
207594e91a1SSean Christopherson {									\
208594e91a1SSean Christopherson 	return !!(regs->reg & flag);					\
209594e91a1SSean Christopherson }
210594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
211594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
212594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
213594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
214594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
215594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
216594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
217594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
218594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
219594e91a1SSean Christopherson BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
220594e91a1SSean Christopherson 
22160667724SSean Christopherson /*
22260667724SSean Christopherson  * The MMU itself (with a valid role) is the single source of truth for the
22360667724SSean Christopherson  * MMU.  Do not use the regs used to build the MMU/role, nor the vCPU.  The
22460667724SSean Christopherson  * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
22560667724SSean Christopherson  * and the vCPU may be incorrect/irrelevant.
22660667724SSean Christopherson  */
22760667724SSean Christopherson #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name)		\
22860667724SSean Christopherson static inline bool is_##reg##_##name(struct kvm_mmu *mmu)	\
22960667724SSean Christopherson {								\
23060667724SSean Christopherson 	return !!(mmu->mmu_role. base_or_ext . reg##_##name);	\
23160667724SSean Christopherson }
23260667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr0, pg);
23360667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
23460667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pse);
23560667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pae);
23660667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smep);
23760667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smap);
23860667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pke);
23960667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, la57);
24060667724SSean Christopherson BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
24160667724SSean Christopherson 
242594e91a1SSean Christopherson static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
243594e91a1SSean Christopherson {
244594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
245594e91a1SSean Christopherson 		.cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
246594e91a1SSean Christopherson 		.cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
247594e91a1SSean Christopherson 		.efer = vcpu->arch.efer,
248594e91a1SSean Christopherson 	};
249594e91a1SSean Christopherson 
250594e91a1SSean Christopherson 	return regs;
251594e91a1SSean Christopherson }
252c50d8ae3SPaolo Bonzini 
253f4bd6f73SSean Christopherson static int role_regs_to_root_level(struct kvm_mmu_role_regs *regs)
254f4bd6f73SSean Christopherson {
255f4bd6f73SSean Christopherson 	if (!____is_cr0_pg(regs))
256f4bd6f73SSean Christopherson 		return 0;
257f4bd6f73SSean Christopherson 	else if (____is_efer_lma(regs))
258f4bd6f73SSean Christopherson 		return ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL :
259f4bd6f73SSean Christopherson 					       PT64_ROOT_4LEVEL;
260f4bd6f73SSean Christopherson 	else if (____is_cr4_pae(regs))
261f4bd6f73SSean Christopherson 		return PT32E_ROOT_LEVEL;
262f4bd6f73SSean Christopherson 	else
263f4bd6f73SSean Christopherson 		return PT32_ROOT_LEVEL;
264f4bd6f73SSean Christopherson }
265c50d8ae3SPaolo Bonzini 
266c50d8ae3SPaolo Bonzini static inline bool kvm_available_flush_tlb_with_range(void)
267c50d8ae3SPaolo Bonzini {
268afaf0b2fSSean Christopherson 	return kvm_x86_ops.tlb_remote_flush_with_range;
269c50d8ae3SPaolo Bonzini }
270c50d8ae3SPaolo Bonzini 
271c50d8ae3SPaolo Bonzini static void kvm_flush_remote_tlbs_with_range(struct kvm *kvm,
272c50d8ae3SPaolo Bonzini 		struct kvm_tlb_range *range)
273c50d8ae3SPaolo Bonzini {
274c50d8ae3SPaolo Bonzini 	int ret = -ENOTSUPP;
275c50d8ae3SPaolo Bonzini 
276afaf0b2fSSean Christopherson 	if (range && kvm_x86_ops.tlb_remote_flush_with_range)
277b3646477SJason Baron 		ret = static_call(kvm_x86_tlb_remote_flush_with_range)(kvm, range);
278c50d8ae3SPaolo Bonzini 
279c50d8ae3SPaolo Bonzini 	if (ret)
280c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
281c50d8ae3SPaolo Bonzini }
282c50d8ae3SPaolo Bonzini 
2832f2fad08SBen Gardon void kvm_flush_remote_tlbs_with_address(struct kvm *kvm,
284c50d8ae3SPaolo Bonzini 		u64 start_gfn, u64 pages)
285c50d8ae3SPaolo Bonzini {
286c50d8ae3SPaolo Bonzini 	struct kvm_tlb_range range;
287c50d8ae3SPaolo Bonzini 
288c50d8ae3SPaolo Bonzini 	range.start_gfn = start_gfn;
289c50d8ae3SPaolo Bonzini 	range.pages = pages;
290c50d8ae3SPaolo Bonzini 
291c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs_with_range(kvm, &range);
292c50d8ae3SPaolo Bonzini }
293c50d8ae3SPaolo Bonzini 
2948f79b064SBen Gardon static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
2958f79b064SBen Gardon 			   unsigned int access)
2968f79b064SBen Gardon {
297c236d962SSean Christopherson 	u64 spte = make_mmio_spte(vcpu, gfn, access);
2988f79b064SBen Gardon 
299c236d962SSean Christopherson 	trace_mark_mmio_spte(sptep, gfn, spte);
300c236d962SSean Christopherson 	mmu_spte_set(sptep, spte);
301c50d8ae3SPaolo Bonzini }
302c50d8ae3SPaolo Bonzini 
303c50d8ae3SPaolo Bonzini static gfn_t get_mmio_spte_gfn(u64 spte)
304c50d8ae3SPaolo Bonzini {
305c50d8ae3SPaolo Bonzini 	u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
306c50d8ae3SPaolo Bonzini 
3078a967d65SPaolo Bonzini 	gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
308c50d8ae3SPaolo Bonzini 	       & shadow_nonpresent_or_rsvd_mask;
309c50d8ae3SPaolo Bonzini 
310c50d8ae3SPaolo Bonzini 	return gpa >> PAGE_SHIFT;
311c50d8ae3SPaolo Bonzini }
312c50d8ae3SPaolo Bonzini 
313c50d8ae3SPaolo Bonzini static unsigned get_mmio_spte_access(u64 spte)
314c50d8ae3SPaolo Bonzini {
315c50d8ae3SPaolo Bonzini 	return spte & shadow_mmio_access_mask;
316c50d8ae3SPaolo Bonzini }
317c50d8ae3SPaolo Bonzini 
318c50d8ae3SPaolo Bonzini static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
319c50d8ae3SPaolo Bonzini {
320c50d8ae3SPaolo Bonzini 	u64 kvm_gen, spte_gen, gen;
321c50d8ae3SPaolo Bonzini 
322c50d8ae3SPaolo Bonzini 	gen = kvm_vcpu_memslots(vcpu)->generation;
323c50d8ae3SPaolo Bonzini 	if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
324c50d8ae3SPaolo Bonzini 		return false;
325c50d8ae3SPaolo Bonzini 
326c50d8ae3SPaolo Bonzini 	kvm_gen = gen & MMIO_SPTE_GEN_MASK;
327c50d8ae3SPaolo Bonzini 	spte_gen = get_mmio_spte_generation(spte);
328c50d8ae3SPaolo Bonzini 
329c50d8ae3SPaolo Bonzini 	trace_check_mmio_spte(spte, kvm_gen, spte_gen);
330c50d8ae3SPaolo Bonzini 	return likely(kvm_gen == spte_gen);
331c50d8ae3SPaolo Bonzini }
332c50d8ae3SPaolo Bonzini 
333cd313569SMohammed Gamal static gpa_t translate_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access,
334cd313569SMohammed Gamal                                   struct x86_exception *exception)
335cd313569SMohammed Gamal {
336ec7771abSMohammed Gamal 	/* Check if guest physical address doesn't exceed guest maximum */
337dc46515cSSean Christopherson 	if (kvm_vcpu_is_illegal_gpa(vcpu, gpa)) {
338ec7771abSMohammed Gamal 		exception->error_code |= PFERR_RSVD_MASK;
339ec7771abSMohammed Gamal 		return UNMAPPED_GVA;
340ec7771abSMohammed Gamal 	}
341ec7771abSMohammed Gamal 
342cd313569SMohammed Gamal         return gpa;
343cd313569SMohammed Gamal }
344cd313569SMohammed Gamal 
345c50d8ae3SPaolo Bonzini static int is_cpuid_PSE36(void)
346c50d8ae3SPaolo Bonzini {
347c50d8ae3SPaolo Bonzini 	return 1;
348c50d8ae3SPaolo Bonzini }
349c50d8ae3SPaolo Bonzini 
350c50d8ae3SPaolo Bonzini static gfn_t pse36_gfn_delta(u32 gpte)
351c50d8ae3SPaolo Bonzini {
352c50d8ae3SPaolo Bonzini 	int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
353c50d8ae3SPaolo Bonzini 
354c50d8ae3SPaolo Bonzini 	return (gpte & PT32_DIR_PSE36_MASK) << shift;
355c50d8ae3SPaolo Bonzini }
356c50d8ae3SPaolo Bonzini 
357c50d8ae3SPaolo Bonzini #ifdef CONFIG_X86_64
358c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
359c50d8ae3SPaolo Bonzini {
360c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
361c50d8ae3SPaolo Bonzini }
362c50d8ae3SPaolo Bonzini 
363c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
364c50d8ae3SPaolo Bonzini {
365c50d8ae3SPaolo Bonzini 	WRITE_ONCE(*sptep, spte);
366c50d8ae3SPaolo Bonzini }
367c50d8ae3SPaolo Bonzini 
368c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
369c50d8ae3SPaolo Bonzini {
370c50d8ae3SPaolo Bonzini 	return xchg(sptep, spte);
371c50d8ae3SPaolo Bonzini }
372c50d8ae3SPaolo Bonzini 
373c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
374c50d8ae3SPaolo Bonzini {
375c50d8ae3SPaolo Bonzini 	return READ_ONCE(*sptep);
376c50d8ae3SPaolo Bonzini }
377c50d8ae3SPaolo Bonzini #else
378c50d8ae3SPaolo Bonzini union split_spte {
379c50d8ae3SPaolo Bonzini 	struct {
380c50d8ae3SPaolo Bonzini 		u32 spte_low;
381c50d8ae3SPaolo Bonzini 		u32 spte_high;
382c50d8ae3SPaolo Bonzini 	};
383c50d8ae3SPaolo Bonzini 	u64 spte;
384c50d8ae3SPaolo Bonzini };
385c50d8ae3SPaolo Bonzini 
386c50d8ae3SPaolo Bonzini static void count_spte_clear(u64 *sptep, u64 spte)
387c50d8ae3SPaolo Bonzini {
38857354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
389c50d8ae3SPaolo Bonzini 
390c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(spte))
391c50d8ae3SPaolo Bonzini 		return;
392c50d8ae3SPaolo Bonzini 
393c50d8ae3SPaolo Bonzini 	/* Ensure the spte is completely set before we increase the count */
394c50d8ae3SPaolo Bonzini 	smp_wmb();
395c50d8ae3SPaolo Bonzini 	sp->clear_spte_count++;
396c50d8ae3SPaolo Bonzini }
397c50d8ae3SPaolo Bonzini 
398c50d8ae3SPaolo Bonzini static void __set_spte(u64 *sptep, u64 spte)
399c50d8ae3SPaolo Bonzini {
400c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
401c50d8ae3SPaolo Bonzini 
402c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
403c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
404c50d8ae3SPaolo Bonzini 
405c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
406c50d8ae3SPaolo Bonzini 
407c50d8ae3SPaolo Bonzini 	/*
408c50d8ae3SPaolo Bonzini 	 * If we map the spte from nonpresent to present, We should store
409c50d8ae3SPaolo Bonzini 	 * the high bits firstly, then set present bit, so cpu can not
410c50d8ae3SPaolo Bonzini 	 * fetch this spte while we are setting the spte.
411c50d8ae3SPaolo Bonzini 	 */
412c50d8ae3SPaolo Bonzini 	smp_wmb();
413c50d8ae3SPaolo Bonzini 
414c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
415c50d8ae3SPaolo Bonzini }
416c50d8ae3SPaolo Bonzini 
417c50d8ae3SPaolo Bonzini static void __update_clear_spte_fast(u64 *sptep, u64 spte)
418c50d8ae3SPaolo Bonzini {
419c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte;
420c50d8ae3SPaolo Bonzini 
421c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
422c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
423c50d8ae3SPaolo Bonzini 
424c50d8ae3SPaolo Bonzini 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
425c50d8ae3SPaolo Bonzini 
426c50d8ae3SPaolo Bonzini 	/*
427c50d8ae3SPaolo Bonzini 	 * If we map the spte from present to nonpresent, we should clear
428c50d8ae3SPaolo Bonzini 	 * present bit firstly to avoid vcpu fetch the old high bits.
429c50d8ae3SPaolo Bonzini 	 */
430c50d8ae3SPaolo Bonzini 	smp_wmb();
431c50d8ae3SPaolo Bonzini 
432c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
433c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
434c50d8ae3SPaolo Bonzini }
435c50d8ae3SPaolo Bonzini 
436c50d8ae3SPaolo Bonzini static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
437c50d8ae3SPaolo Bonzini {
438c50d8ae3SPaolo Bonzini 	union split_spte *ssptep, sspte, orig;
439c50d8ae3SPaolo Bonzini 
440c50d8ae3SPaolo Bonzini 	ssptep = (union split_spte *)sptep;
441c50d8ae3SPaolo Bonzini 	sspte = (union split_spte)spte;
442c50d8ae3SPaolo Bonzini 
443c50d8ae3SPaolo Bonzini 	/* xchg acts as a barrier before the setting of the high bits */
444c50d8ae3SPaolo Bonzini 	orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
445c50d8ae3SPaolo Bonzini 	orig.spte_high = ssptep->spte_high;
446c50d8ae3SPaolo Bonzini 	ssptep->spte_high = sspte.spte_high;
447c50d8ae3SPaolo Bonzini 	count_spte_clear(sptep, spte);
448c50d8ae3SPaolo Bonzini 
449c50d8ae3SPaolo Bonzini 	return orig.spte;
450c50d8ae3SPaolo Bonzini }
451c50d8ae3SPaolo Bonzini 
452c50d8ae3SPaolo Bonzini /*
453c50d8ae3SPaolo Bonzini  * The idea using the light way get the spte on x86_32 guest is from
454c50d8ae3SPaolo Bonzini  * gup_get_pte (mm/gup.c).
455c50d8ae3SPaolo Bonzini  *
456c50d8ae3SPaolo Bonzini  * An spte tlb flush may be pending, because kvm_set_pte_rmapp
457c50d8ae3SPaolo Bonzini  * coalesces them and we are running out of the MMU lock.  Therefore
458c50d8ae3SPaolo Bonzini  * we need to protect against in-progress updates of the spte.
459c50d8ae3SPaolo Bonzini  *
460c50d8ae3SPaolo Bonzini  * Reading the spte while an update is in progress may get the old value
461c50d8ae3SPaolo Bonzini  * for the high part of the spte.  The race is fine for a present->non-present
462c50d8ae3SPaolo Bonzini  * change (because the high part of the spte is ignored for non-present spte),
463c50d8ae3SPaolo Bonzini  * but for a present->present change we must reread the spte.
464c50d8ae3SPaolo Bonzini  *
465c50d8ae3SPaolo Bonzini  * All such changes are done in two steps (present->non-present and
466c50d8ae3SPaolo Bonzini  * non-present->present), hence it is enough to count the number of
467c50d8ae3SPaolo Bonzini  * present->non-present updates: if it changed while reading the spte,
468c50d8ae3SPaolo Bonzini  * we might have hit the race.  This is done using clear_spte_count.
469c50d8ae3SPaolo Bonzini  */
470c50d8ae3SPaolo Bonzini static u64 __get_spte_lockless(u64 *sptep)
471c50d8ae3SPaolo Bonzini {
47257354682SSean Christopherson 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
473c50d8ae3SPaolo Bonzini 	union split_spte spte, *orig = (union split_spte *)sptep;
474c50d8ae3SPaolo Bonzini 	int count;
475c50d8ae3SPaolo Bonzini 
476c50d8ae3SPaolo Bonzini retry:
477c50d8ae3SPaolo Bonzini 	count = sp->clear_spte_count;
478c50d8ae3SPaolo Bonzini 	smp_rmb();
479c50d8ae3SPaolo Bonzini 
480c50d8ae3SPaolo Bonzini 	spte.spte_low = orig->spte_low;
481c50d8ae3SPaolo Bonzini 	smp_rmb();
482c50d8ae3SPaolo Bonzini 
483c50d8ae3SPaolo Bonzini 	spte.spte_high = orig->spte_high;
484c50d8ae3SPaolo Bonzini 	smp_rmb();
485c50d8ae3SPaolo Bonzini 
486c50d8ae3SPaolo Bonzini 	if (unlikely(spte.spte_low != orig->spte_low ||
487c50d8ae3SPaolo Bonzini 	      count != sp->clear_spte_count))
488c50d8ae3SPaolo Bonzini 		goto retry;
489c50d8ae3SPaolo Bonzini 
490c50d8ae3SPaolo Bonzini 	return spte.spte;
491c50d8ae3SPaolo Bonzini }
492c50d8ae3SPaolo Bonzini #endif
493c50d8ae3SPaolo Bonzini 
494c50d8ae3SPaolo Bonzini static bool spte_has_volatile_bits(u64 spte)
495c50d8ae3SPaolo Bonzini {
496c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(spte))
497c50d8ae3SPaolo Bonzini 		return false;
498c50d8ae3SPaolo Bonzini 
499c50d8ae3SPaolo Bonzini 	/*
500c50d8ae3SPaolo Bonzini 	 * Always atomically update spte if it can be updated
501c50d8ae3SPaolo Bonzini 	 * out of mmu-lock, it can ensure dirty bit is not lost,
502c50d8ae3SPaolo Bonzini 	 * also, it can help us to get a stable is_writable_pte()
503c50d8ae3SPaolo Bonzini 	 * to ensure tlb flush is not missed.
504c50d8ae3SPaolo Bonzini 	 */
505c50d8ae3SPaolo Bonzini 	if (spte_can_locklessly_be_made_writable(spte) ||
506c50d8ae3SPaolo Bonzini 	    is_access_track_spte(spte))
507c50d8ae3SPaolo Bonzini 		return true;
508c50d8ae3SPaolo Bonzini 
509c50d8ae3SPaolo Bonzini 	if (spte_ad_enabled(spte)) {
510c50d8ae3SPaolo Bonzini 		if ((spte & shadow_accessed_mask) == 0 ||
511c50d8ae3SPaolo Bonzini 	    	    (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
512c50d8ae3SPaolo Bonzini 			return true;
513c50d8ae3SPaolo Bonzini 	}
514c50d8ae3SPaolo Bonzini 
515c50d8ae3SPaolo Bonzini 	return false;
516c50d8ae3SPaolo Bonzini }
517c50d8ae3SPaolo Bonzini 
518c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_set:
519c50d8ae3SPaolo Bonzini  * Set the sptep from nonpresent to present.
520c50d8ae3SPaolo Bonzini  * Note: the sptep being assigned *must* be either not present
521c50d8ae3SPaolo Bonzini  * or in a state where the hardware will not attempt to update
522c50d8ae3SPaolo Bonzini  * the spte.
523c50d8ae3SPaolo Bonzini  */
524c50d8ae3SPaolo Bonzini static void mmu_spte_set(u64 *sptep, u64 new_spte)
525c50d8ae3SPaolo Bonzini {
526c50d8ae3SPaolo Bonzini 	WARN_ON(is_shadow_present_pte(*sptep));
527c50d8ae3SPaolo Bonzini 	__set_spte(sptep, new_spte);
528c50d8ae3SPaolo Bonzini }
529c50d8ae3SPaolo Bonzini 
530c50d8ae3SPaolo Bonzini /*
531c50d8ae3SPaolo Bonzini  * Update the SPTE (excluding the PFN), but do not track changes in its
532c50d8ae3SPaolo Bonzini  * accessed/dirty status.
533c50d8ae3SPaolo Bonzini  */
534c50d8ae3SPaolo Bonzini static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
535c50d8ae3SPaolo Bonzini {
536c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
537c50d8ae3SPaolo Bonzini 
538c50d8ae3SPaolo Bonzini 	WARN_ON(!is_shadow_present_pte(new_spte));
539c50d8ae3SPaolo Bonzini 
540c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte)) {
541c50d8ae3SPaolo Bonzini 		mmu_spte_set(sptep, new_spte);
542c50d8ae3SPaolo Bonzini 		return old_spte;
543c50d8ae3SPaolo Bonzini 	}
544c50d8ae3SPaolo Bonzini 
545c50d8ae3SPaolo Bonzini 	if (!spte_has_volatile_bits(old_spte))
546c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, new_spte);
547c50d8ae3SPaolo Bonzini 	else
548c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, new_spte);
549c50d8ae3SPaolo Bonzini 
550c50d8ae3SPaolo Bonzini 	WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
551c50d8ae3SPaolo Bonzini 
552c50d8ae3SPaolo Bonzini 	return old_spte;
553c50d8ae3SPaolo Bonzini }
554c50d8ae3SPaolo Bonzini 
555c50d8ae3SPaolo Bonzini /* Rules for using mmu_spte_update:
556c50d8ae3SPaolo Bonzini  * Update the state bits, it means the mapped pfn is not changed.
557c50d8ae3SPaolo Bonzini  *
558c50d8ae3SPaolo Bonzini  * Whenever we overwrite a writable spte with a read-only one we
559c50d8ae3SPaolo Bonzini  * should flush remote TLBs. Otherwise rmap_write_protect
560c50d8ae3SPaolo Bonzini  * will find a read-only spte, even though the writable spte
561c50d8ae3SPaolo Bonzini  * might be cached on a CPU's TLB, the return value indicates this
562c50d8ae3SPaolo Bonzini  * case.
563c50d8ae3SPaolo Bonzini  *
564c50d8ae3SPaolo Bonzini  * Returns true if the TLB needs to be flushed
565c50d8ae3SPaolo Bonzini  */
566c50d8ae3SPaolo Bonzini static bool mmu_spte_update(u64 *sptep, u64 new_spte)
567c50d8ae3SPaolo Bonzini {
568c50d8ae3SPaolo Bonzini 	bool flush = false;
569c50d8ae3SPaolo Bonzini 	u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
570c50d8ae3SPaolo Bonzini 
571c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
572c50d8ae3SPaolo Bonzini 		return false;
573c50d8ae3SPaolo Bonzini 
574c50d8ae3SPaolo Bonzini 	/*
575c50d8ae3SPaolo Bonzini 	 * For the spte updated out of mmu-lock is safe, since
576c50d8ae3SPaolo Bonzini 	 * we always atomically update it, see the comments in
577c50d8ae3SPaolo Bonzini 	 * spte_has_volatile_bits().
578c50d8ae3SPaolo Bonzini 	 */
579c50d8ae3SPaolo Bonzini 	if (spte_can_locklessly_be_made_writable(old_spte) &&
580c50d8ae3SPaolo Bonzini 	      !is_writable_pte(new_spte))
581c50d8ae3SPaolo Bonzini 		flush = true;
582c50d8ae3SPaolo Bonzini 
583c50d8ae3SPaolo Bonzini 	/*
584c50d8ae3SPaolo Bonzini 	 * Flush TLB when accessed/dirty states are changed in the page tables,
585c50d8ae3SPaolo Bonzini 	 * to guarantee consistency between TLB and page tables.
586c50d8ae3SPaolo Bonzini 	 */
587c50d8ae3SPaolo Bonzini 
588c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
589c50d8ae3SPaolo Bonzini 		flush = true;
590c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(spte_to_pfn(old_spte));
591c50d8ae3SPaolo Bonzini 	}
592c50d8ae3SPaolo Bonzini 
593c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
594c50d8ae3SPaolo Bonzini 		flush = true;
595c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(old_spte));
596c50d8ae3SPaolo Bonzini 	}
597c50d8ae3SPaolo Bonzini 
598c50d8ae3SPaolo Bonzini 	return flush;
599c50d8ae3SPaolo Bonzini }
600c50d8ae3SPaolo Bonzini 
601c50d8ae3SPaolo Bonzini /*
602c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_track_bits:
603c50d8ae3SPaolo Bonzini  * It sets the sptep from present to nonpresent, and track the
604c50d8ae3SPaolo Bonzini  * state bits, it is used to clear the last level sptep.
6057fa2a347SSean Christopherson  * Returns the old PTE.
606c50d8ae3SPaolo Bonzini  */
6077fa2a347SSean Christopherson static u64 mmu_spte_clear_track_bits(u64 *sptep)
608c50d8ae3SPaolo Bonzini {
609c50d8ae3SPaolo Bonzini 	kvm_pfn_t pfn;
610c50d8ae3SPaolo Bonzini 	u64 old_spte = *sptep;
611c50d8ae3SPaolo Bonzini 
612c50d8ae3SPaolo Bonzini 	if (!spte_has_volatile_bits(old_spte))
613c50d8ae3SPaolo Bonzini 		__update_clear_spte_fast(sptep, 0ull);
614c50d8ae3SPaolo Bonzini 	else
615c50d8ae3SPaolo Bonzini 		old_spte = __update_clear_spte_slow(sptep, 0ull);
616c50d8ae3SPaolo Bonzini 
617c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old_spte))
6187fa2a347SSean Christopherson 		return old_spte;
619c50d8ae3SPaolo Bonzini 
620c50d8ae3SPaolo Bonzini 	pfn = spte_to_pfn(old_spte);
621c50d8ae3SPaolo Bonzini 
622c50d8ae3SPaolo Bonzini 	/*
623c50d8ae3SPaolo Bonzini 	 * KVM does not hold the refcount of the page used by
624c50d8ae3SPaolo Bonzini 	 * kvm mmu, before reclaiming the page, we should
625c50d8ae3SPaolo Bonzini 	 * unmap it from mmu first.
626c50d8ae3SPaolo Bonzini 	 */
627c50d8ae3SPaolo Bonzini 	WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
628c50d8ae3SPaolo Bonzini 
629c50d8ae3SPaolo Bonzini 	if (is_accessed_spte(old_spte))
630c50d8ae3SPaolo Bonzini 		kvm_set_pfn_accessed(pfn);
631c50d8ae3SPaolo Bonzini 
632c50d8ae3SPaolo Bonzini 	if (is_dirty_spte(old_spte))
633c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(pfn);
634c50d8ae3SPaolo Bonzini 
6357fa2a347SSean Christopherson 	return old_spte;
636c50d8ae3SPaolo Bonzini }
637c50d8ae3SPaolo Bonzini 
638c50d8ae3SPaolo Bonzini /*
639c50d8ae3SPaolo Bonzini  * Rules for using mmu_spte_clear_no_track:
640c50d8ae3SPaolo Bonzini  * Directly clear spte without caring the state bits of sptep,
641c50d8ae3SPaolo Bonzini  * it is used to set the upper level spte.
642c50d8ae3SPaolo Bonzini  */
643c50d8ae3SPaolo Bonzini static void mmu_spte_clear_no_track(u64 *sptep)
644c50d8ae3SPaolo Bonzini {
645c50d8ae3SPaolo Bonzini 	__update_clear_spte_fast(sptep, 0ull);
646c50d8ae3SPaolo Bonzini }
647c50d8ae3SPaolo Bonzini 
648c50d8ae3SPaolo Bonzini static u64 mmu_spte_get_lockless(u64 *sptep)
649c50d8ae3SPaolo Bonzini {
650c50d8ae3SPaolo Bonzini 	return __get_spte_lockless(sptep);
651c50d8ae3SPaolo Bonzini }
652c50d8ae3SPaolo Bonzini 
653c50d8ae3SPaolo Bonzini /* Restore an acc-track PTE back to a regular PTE */
654c50d8ae3SPaolo Bonzini static u64 restore_acc_track_spte(u64 spte)
655c50d8ae3SPaolo Bonzini {
656c50d8ae3SPaolo Bonzini 	u64 new_spte = spte;
6578a967d65SPaolo Bonzini 	u64 saved_bits = (spte >> SHADOW_ACC_TRACK_SAVED_BITS_SHIFT)
6588a967d65SPaolo Bonzini 			 & SHADOW_ACC_TRACK_SAVED_BITS_MASK;
659c50d8ae3SPaolo Bonzini 
660c50d8ae3SPaolo Bonzini 	WARN_ON_ONCE(spte_ad_enabled(spte));
661c50d8ae3SPaolo Bonzini 	WARN_ON_ONCE(!is_access_track_spte(spte));
662c50d8ae3SPaolo Bonzini 
663c50d8ae3SPaolo Bonzini 	new_spte &= ~shadow_acc_track_mask;
6648a967d65SPaolo Bonzini 	new_spte &= ~(SHADOW_ACC_TRACK_SAVED_BITS_MASK <<
6658a967d65SPaolo Bonzini 		      SHADOW_ACC_TRACK_SAVED_BITS_SHIFT);
666c50d8ae3SPaolo Bonzini 	new_spte |= saved_bits;
667c50d8ae3SPaolo Bonzini 
668c50d8ae3SPaolo Bonzini 	return new_spte;
669c50d8ae3SPaolo Bonzini }
670c50d8ae3SPaolo Bonzini 
671c50d8ae3SPaolo Bonzini /* Returns the Accessed status of the PTE and resets it at the same time. */
672c50d8ae3SPaolo Bonzini static bool mmu_spte_age(u64 *sptep)
673c50d8ae3SPaolo Bonzini {
674c50d8ae3SPaolo Bonzini 	u64 spte = mmu_spte_get_lockless(sptep);
675c50d8ae3SPaolo Bonzini 
676c50d8ae3SPaolo Bonzini 	if (!is_accessed_spte(spte))
677c50d8ae3SPaolo Bonzini 		return false;
678c50d8ae3SPaolo Bonzini 
679c50d8ae3SPaolo Bonzini 	if (spte_ad_enabled(spte)) {
680c50d8ae3SPaolo Bonzini 		clear_bit((ffs(shadow_accessed_mask) - 1),
681c50d8ae3SPaolo Bonzini 			  (unsigned long *)sptep);
682c50d8ae3SPaolo Bonzini 	} else {
683c50d8ae3SPaolo Bonzini 		/*
684c50d8ae3SPaolo Bonzini 		 * Capture the dirty status of the page, so that it doesn't get
685c50d8ae3SPaolo Bonzini 		 * lost when the SPTE is marked for access tracking.
686c50d8ae3SPaolo Bonzini 		 */
687c50d8ae3SPaolo Bonzini 		if (is_writable_pte(spte))
688c50d8ae3SPaolo Bonzini 			kvm_set_pfn_dirty(spte_to_pfn(spte));
689c50d8ae3SPaolo Bonzini 
690c50d8ae3SPaolo Bonzini 		spte = mark_spte_for_access_track(spte);
691c50d8ae3SPaolo Bonzini 		mmu_spte_update_no_track(sptep, spte);
692c50d8ae3SPaolo Bonzini 	}
693c50d8ae3SPaolo Bonzini 
694c50d8ae3SPaolo Bonzini 	return true;
695c50d8ae3SPaolo Bonzini }
696c50d8ae3SPaolo Bonzini 
697c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
698c50d8ae3SPaolo Bonzini {
699c5c8c7c5SDavid Matlack 	if (is_tdp_mmu(vcpu->arch.mmu)) {
700c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_begin();
701c5c8c7c5SDavid Matlack 	} else {
702c50d8ae3SPaolo Bonzini 		/*
703c50d8ae3SPaolo Bonzini 		 * Prevent page table teardown by making any free-er wait during
704c50d8ae3SPaolo Bonzini 		 * kvm_flush_remote_tlbs() IPI to all active vcpus.
705c50d8ae3SPaolo Bonzini 		 */
706c50d8ae3SPaolo Bonzini 		local_irq_disable();
707c50d8ae3SPaolo Bonzini 
708c50d8ae3SPaolo Bonzini 		/*
709c50d8ae3SPaolo Bonzini 		 * Make sure a following spte read is not reordered ahead of the write
710c50d8ae3SPaolo Bonzini 		 * to vcpu->mode.
711c50d8ae3SPaolo Bonzini 		 */
712c50d8ae3SPaolo Bonzini 		smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
713c50d8ae3SPaolo Bonzini 	}
714c5c8c7c5SDavid Matlack }
715c50d8ae3SPaolo Bonzini 
716c50d8ae3SPaolo Bonzini static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
717c50d8ae3SPaolo Bonzini {
718c5c8c7c5SDavid Matlack 	if (is_tdp_mmu(vcpu->arch.mmu)) {
719c5c8c7c5SDavid Matlack 		kvm_tdp_mmu_walk_lockless_end();
720c5c8c7c5SDavid Matlack 	} else {
721c50d8ae3SPaolo Bonzini 		/*
722c50d8ae3SPaolo Bonzini 		 * Make sure the write to vcpu->mode is not reordered in front of
723c50d8ae3SPaolo Bonzini 		 * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
724c50d8ae3SPaolo Bonzini 		 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
725c50d8ae3SPaolo Bonzini 		 */
726c50d8ae3SPaolo Bonzini 		smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
727c50d8ae3SPaolo Bonzini 		local_irq_enable();
728c50d8ae3SPaolo Bonzini 	}
729c5c8c7c5SDavid Matlack }
730c50d8ae3SPaolo Bonzini 
731378f5cd6SSean Christopherson static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
732c50d8ae3SPaolo Bonzini {
733c50d8ae3SPaolo Bonzini 	int r;
734c50d8ae3SPaolo Bonzini 
735531281adSSean Christopherson 	/* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
73694ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
737531281adSSean Christopherson 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
738c50d8ae3SPaolo Bonzini 	if (r)
739c50d8ae3SPaolo Bonzini 		return r;
74094ce87efSSean Christopherson 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
741171a90d7SSean Christopherson 				       PT64_ROOT_MAX_LEVEL);
742171a90d7SSean Christopherson 	if (r)
743171a90d7SSean Christopherson 		return r;
744378f5cd6SSean Christopherson 	if (maybe_indirect) {
74594ce87efSSean Christopherson 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_gfn_array_cache,
746171a90d7SSean Christopherson 					       PT64_ROOT_MAX_LEVEL);
747c50d8ae3SPaolo Bonzini 		if (r)
748c50d8ae3SPaolo Bonzini 			return r;
749378f5cd6SSean Christopherson 	}
75094ce87efSSean Christopherson 	return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
751531281adSSean Christopherson 					  PT64_ROOT_MAX_LEVEL);
752c50d8ae3SPaolo Bonzini }
753c50d8ae3SPaolo Bonzini 
754c50d8ae3SPaolo Bonzini static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
755c50d8ae3SPaolo Bonzini {
75694ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
75794ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
75894ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_gfn_array_cache);
75994ce87efSSean Christopherson 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
760c50d8ae3SPaolo Bonzini }
761c50d8ae3SPaolo Bonzini 
762c50d8ae3SPaolo Bonzini static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
763c50d8ae3SPaolo Bonzini {
76494ce87efSSean Christopherson 	return kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
765c50d8ae3SPaolo Bonzini }
766c50d8ae3SPaolo Bonzini 
767c50d8ae3SPaolo Bonzini static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
768c50d8ae3SPaolo Bonzini {
769c50d8ae3SPaolo Bonzini 	kmem_cache_free(pte_list_desc_cache, pte_list_desc);
770c50d8ae3SPaolo Bonzini }
771c50d8ae3SPaolo Bonzini 
772c50d8ae3SPaolo Bonzini static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
773c50d8ae3SPaolo Bonzini {
774c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
775c50d8ae3SPaolo Bonzini 		return sp->gfns[index];
776c50d8ae3SPaolo Bonzini 
777c50d8ae3SPaolo Bonzini 	return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
778c50d8ae3SPaolo Bonzini }
779c50d8ae3SPaolo Bonzini 
780c50d8ae3SPaolo Bonzini static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
781c50d8ae3SPaolo Bonzini {
782c50d8ae3SPaolo Bonzini 	if (!sp->role.direct) {
783c50d8ae3SPaolo Bonzini 		sp->gfns[index] = gfn;
784c50d8ae3SPaolo Bonzini 		return;
785c50d8ae3SPaolo Bonzini 	}
786c50d8ae3SPaolo Bonzini 
787c50d8ae3SPaolo Bonzini 	if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
788c50d8ae3SPaolo Bonzini 		pr_err_ratelimited("gfn mismatch under direct page %llx "
789c50d8ae3SPaolo Bonzini 				   "(expected %llx, got %llx)\n",
790c50d8ae3SPaolo Bonzini 				   sp->gfn,
791c50d8ae3SPaolo Bonzini 				   kvm_mmu_page_get_gfn(sp, index), gfn);
792c50d8ae3SPaolo Bonzini }
793c50d8ae3SPaolo Bonzini 
794c50d8ae3SPaolo Bonzini /*
795c50d8ae3SPaolo Bonzini  * Return the pointer to the large page information for a given gfn,
796c50d8ae3SPaolo Bonzini  * handling slots that are not large page aligned.
797c50d8ae3SPaolo Bonzini  */
798c50d8ae3SPaolo Bonzini static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
7998ca6f063SBen Gardon 		const struct kvm_memory_slot *slot, int level)
800c50d8ae3SPaolo Bonzini {
801c50d8ae3SPaolo Bonzini 	unsigned long idx;
802c50d8ae3SPaolo Bonzini 
803c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
804c50d8ae3SPaolo Bonzini 	return &slot->arch.lpage_info[level - 2][idx];
805c50d8ae3SPaolo Bonzini }
806c50d8ae3SPaolo Bonzini 
807269e9552SHamza Mahfooz static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
808c50d8ae3SPaolo Bonzini 					    gfn_t gfn, int count)
809c50d8ae3SPaolo Bonzini {
810c50d8ae3SPaolo Bonzini 	struct kvm_lpage_info *linfo;
811c50d8ae3SPaolo Bonzini 	int i;
812c50d8ae3SPaolo Bonzini 
8133bae0459SSean Christopherson 	for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
814c50d8ae3SPaolo Bonzini 		linfo = lpage_info_slot(gfn, slot, i);
815c50d8ae3SPaolo Bonzini 		linfo->disallow_lpage += count;
816c50d8ae3SPaolo Bonzini 		WARN_ON(linfo->disallow_lpage < 0);
817c50d8ae3SPaolo Bonzini 	}
818c50d8ae3SPaolo Bonzini }
819c50d8ae3SPaolo Bonzini 
820269e9552SHamza Mahfooz void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
821c50d8ae3SPaolo Bonzini {
822c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, 1);
823c50d8ae3SPaolo Bonzini }
824c50d8ae3SPaolo Bonzini 
825269e9552SHamza Mahfooz void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
826c50d8ae3SPaolo Bonzini {
827c50d8ae3SPaolo Bonzini 	update_gfn_disallow_lpage_count(slot, gfn, -1);
828c50d8ae3SPaolo Bonzini }
829c50d8ae3SPaolo Bonzini 
830c50d8ae3SPaolo Bonzini static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
831c50d8ae3SPaolo Bonzini {
832c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
833c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
834c50d8ae3SPaolo Bonzini 	gfn_t gfn;
835c50d8ae3SPaolo Bonzini 
836c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages++;
837c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
838c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
839c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
840c50d8ae3SPaolo Bonzini 
841c50d8ae3SPaolo Bonzini 	/* the non-leaf shadow pages are keeping readonly. */
8423bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
843c50d8ae3SPaolo Bonzini 		return kvm_slot_page_track_add_page(kvm, slot, gfn,
844c50d8ae3SPaolo Bonzini 						    KVM_PAGE_TRACK_WRITE);
845c50d8ae3SPaolo Bonzini 
846c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
847c50d8ae3SPaolo Bonzini }
848c50d8ae3SPaolo Bonzini 
84929cf0f50SBen Gardon void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
850c50d8ae3SPaolo Bonzini {
851c50d8ae3SPaolo Bonzini 	if (sp->lpage_disallowed)
852c50d8ae3SPaolo Bonzini 		return;
853c50d8ae3SPaolo Bonzini 
854c50d8ae3SPaolo Bonzini 	++kvm->stat.nx_lpage_splits;
855c50d8ae3SPaolo Bonzini 	list_add_tail(&sp->lpage_disallowed_link,
856c50d8ae3SPaolo Bonzini 		      &kvm->arch.lpage_disallowed_mmu_pages);
857c50d8ae3SPaolo Bonzini 	sp->lpage_disallowed = true;
858c50d8ae3SPaolo Bonzini }
859c50d8ae3SPaolo Bonzini 
860c50d8ae3SPaolo Bonzini static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
861c50d8ae3SPaolo Bonzini {
862c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
863c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
864c50d8ae3SPaolo Bonzini 	gfn_t gfn;
865c50d8ae3SPaolo Bonzini 
866c50d8ae3SPaolo Bonzini 	kvm->arch.indirect_shadow_pages--;
867c50d8ae3SPaolo Bonzini 	gfn = sp->gfn;
868c50d8ae3SPaolo Bonzini 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
869c50d8ae3SPaolo Bonzini 	slot = __gfn_to_memslot(slots, gfn);
8703bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
871c50d8ae3SPaolo Bonzini 		return kvm_slot_page_track_remove_page(kvm, slot, gfn,
872c50d8ae3SPaolo Bonzini 						       KVM_PAGE_TRACK_WRITE);
873c50d8ae3SPaolo Bonzini 
874c50d8ae3SPaolo Bonzini 	kvm_mmu_gfn_allow_lpage(slot, gfn);
875c50d8ae3SPaolo Bonzini }
876c50d8ae3SPaolo Bonzini 
87729cf0f50SBen Gardon void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
878c50d8ae3SPaolo Bonzini {
879c50d8ae3SPaolo Bonzini 	--kvm->stat.nx_lpage_splits;
880c50d8ae3SPaolo Bonzini 	sp->lpage_disallowed = false;
881c50d8ae3SPaolo Bonzini 	list_del(&sp->lpage_disallowed_link);
882c50d8ae3SPaolo Bonzini }
883c50d8ae3SPaolo Bonzini 
884c50d8ae3SPaolo Bonzini static struct kvm_memory_slot *
885c50d8ae3SPaolo Bonzini gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
886c50d8ae3SPaolo Bonzini 			    bool no_dirty_log)
887c50d8ae3SPaolo Bonzini {
888c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
889c50d8ae3SPaolo Bonzini 
890c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
89191b0d268SPaolo Bonzini 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
89291b0d268SPaolo Bonzini 		return NULL;
893044c59c4SPeter Xu 	if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
89491b0d268SPaolo Bonzini 		return NULL;
895c50d8ae3SPaolo Bonzini 
896c50d8ae3SPaolo Bonzini 	return slot;
897c50d8ae3SPaolo Bonzini }
898c50d8ae3SPaolo Bonzini 
899c50d8ae3SPaolo Bonzini /*
900c50d8ae3SPaolo Bonzini  * About rmap_head encoding:
901c50d8ae3SPaolo Bonzini  *
902c50d8ae3SPaolo Bonzini  * If the bit zero of rmap_head->val is clear, then it points to the only spte
903c50d8ae3SPaolo Bonzini  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
904c50d8ae3SPaolo Bonzini  * pte_list_desc containing more mappings.
905c50d8ae3SPaolo Bonzini  */
906c50d8ae3SPaolo Bonzini 
907c50d8ae3SPaolo Bonzini /*
908c50d8ae3SPaolo Bonzini  * Returns the number of pointers in the rmap chain, not counting the new one.
909c50d8ae3SPaolo Bonzini  */
910c50d8ae3SPaolo Bonzini static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
911c50d8ae3SPaolo Bonzini 			struct kvm_rmap_head *rmap_head)
912c50d8ae3SPaolo Bonzini {
913c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
91413236e25SPeter Xu 	int count = 0;
915c50d8ae3SPaolo Bonzini 
916c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
917805a0f83SStephen Zhang 		rmap_printk("%p %llx 0->1\n", spte, *spte);
918c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)spte;
919c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
920805a0f83SStephen Zhang 		rmap_printk("%p %llx 1->many\n", spte, *spte);
921c50d8ae3SPaolo Bonzini 		desc = mmu_alloc_pte_list_desc(vcpu);
922c50d8ae3SPaolo Bonzini 		desc->sptes[0] = (u64 *)rmap_head->val;
923c50d8ae3SPaolo Bonzini 		desc->sptes[1] = spte;
92413236e25SPeter Xu 		desc->spte_count = 2;
925c50d8ae3SPaolo Bonzini 		rmap_head->val = (unsigned long)desc | 1;
926c50d8ae3SPaolo Bonzini 		++count;
927c50d8ae3SPaolo Bonzini 	} else {
928805a0f83SStephen Zhang 		rmap_printk("%p %llx many->many\n", spte, *spte);
929c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
93013236e25SPeter Xu 		while (desc->spte_count == PTE_LIST_EXT) {
931c50d8ae3SPaolo Bonzini 			count += PTE_LIST_EXT;
932c6c4f961SLi RongQing 			if (!desc->more) {
933c50d8ae3SPaolo Bonzini 				desc->more = mmu_alloc_pte_list_desc(vcpu);
934c50d8ae3SPaolo Bonzini 				desc = desc->more;
93513236e25SPeter Xu 				desc->spte_count = 0;
936c6c4f961SLi RongQing 				break;
937c6c4f961SLi RongQing 			}
938c6c4f961SLi RongQing 			desc = desc->more;
939c50d8ae3SPaolo Bonzini 		}
94013236e25SPeter Xu 		count += desc->spte_count;
94113236e25SPeter Xu 		desc->sptes[desc->spte_count++] = spte;
942c50d8ae3SPaolo Bonzini 	}
943c50d8ae3SPaolo Bonzini 	return count;
944c50d8ae3SPaolo Bonzini }
945c50d8ae3SPaolo Bonzini 
946c50d8ae3SPaolo Bonzini static void
947c50d8ae3SPaolo Bonzini pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
948c50d8ae3SPaolo Bonzini 			   struct pte_list_desc *desc, int i,
949c50d8ae3SPaolo Bonzini 			   struct pte_list_desc *prev_desc)
950c50d8ae3SPaolo Bonzini {
95113236e25SPeter Xu 	int j = desc->spte_count - 1;
952c50d8ae3SPaolo Bonzini 
953c50d8ae3SPaolo Bonzini 	desc->sptes[i] = desc->sptes[j];
954c50d8ae3SPaolo Bonzini 	desc->sptes[j] = NULL;
95513236e25SPeter Xu 	desc->spte_count--;
95613236e25SPeter Xu 	if (desc->spte_count)
957c50d8ae3SPaolo Bonzini 		return;
958c50d8ae3SPaolo Bonzini 	if (!prev_desc && !desc->more)
959fe3c2b4cSMiaohe Lin 		rmap_head->val = 0;
960c50d8ae3SPaolo Bonzini 	else
961c50d8ae3SPaolo Bonzini 		if (prev_desc)
962c50d8ae3SPaolo Bonzini 			prev_desc->more = desc->more;
963c50d8ae3SPaolo Bonzini 		else
964c50d8ae3SPaolo Bonzini 			rmap_head->val = (unsigned long)desc->more | 1;
965c50d8ae3SPaolo Bonzini 	mmu_free_pte_list_desc(desc);
966c50d8ae3SPaolo Bonzini }
967c50d8ae3SPaolo Bonzini 
968c50d8ae3SPaolo Bonzini static void __pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
969c50d8ae3SPaolo Bonzini {
970c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;
971c50d8ae3SPaolo Bonzini 	struct pte_list_desc *prev_desc;
972c50d8ae3SPaolo Bonzini 	int i;
973c50d8ae3SPaolo Bonzini 
974c50d8ae3SPaolo Bonzini 	if (!rmap_head->val) {
975c50d8ae3SPaolo Bonzini 		pr_err("%s: %p 0->BUG\n", __func__, spte);
976c50d8ae3SPaolo Bonzini 		BUG();
977c50d8ae3SPaolo Bonzini 	} else if (!(rmap_head->val & 1)) {
978805a0f83SStephen Zhang 		rmap_printk("%p 1->0\n", spte);
979c50d8ae3SPaolo Bonzini 		if ((u64 *)rmap_head->val != spte) {
980c50d8ae3SPaolo Bonzini 			pr_err("%s:  %p 1->BUG\n", __func__, spte);
981c50d8ae3SPaolo Bonzini 			BUG();
982c50d8ae3SPaolo Bonzini 		}
983c50d8ae3SPaolo Bonzini 		rmap_head->val = 0;
984c50d8ae3SPaolo Bonzini 	} else {
985805a0f83SStephen Zhang 		rmap_printk("%p many->many\n", spte);
986c50d8ae3SPaolo Bonzini 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
987c50d8ae3SPaolo Bonzini 		prev_desc = NULL;
988c50d8ae3SPaolo Bonzini 		while (desc) {
98913236e25SPeter Xu 			for (i = 0; i < desc->spte_count; ++i) {
990c50d8ae3SPaolo Bonzini 				if (desc->sptes[i] == spte) {
991c50d8ae3SPaolo Bonzini 					pte_list_desc_remove_entry(rmap_head,
992c50d8ae3SPaolo Bonzini 							desc, i, prev_desc);
993c50d8ae3SPaolo Bonzini 					return;
994c50d8ae3SPaolo Bonzini 				}
995c50d8ae3SPaolo Bonzini 			}
996c50d8ae3SPaolo Bonzini 			prev_desc = desc;
997c50d8ae3SPaolo Bonzini 			desc = desc->more;
998c50d8ae3SPaolo Bonzini 		}
999c50d8ae3SPaolo Bonzini 		pr_err("%s: %p many->many\n", __func__, spte);
1000c50d8ae3SPaolo Bonzini 		BUG();
1001c50d8ae3SPaolo Bonzini 	}
1002c50d8ae3SPaolo Bonzini }
1003c50d8ae3SPaolo Bonzini 
1004c50d8ae3SPaolo Bonzini static void pte_list_remove(struct kvm_rmap_head *rmap_head, u64 *sptep)
1005c50d8ae3SPaolo Bonzini {
1006c50d8ae3SPaolo Bonzini 	mmu_spte_clear_track_bits(sptep);
1007c50d8ae3SPaolo Bonzini 	__pte_list_remove(sptep, rmap_head);
1008c50d8ae3SPaolo Bonzini }
1009c50d8ae3SPaolo Bonzini 
1010a75b5404SPeter Xu /* Return true if rmap existed, false otherwise */
1011a75b5404SPeter Xu static bool pte_list_destroy(struct kvm_rmap_head *rmap_head)
1012a75b5404SPeter Xu {
1013a75b5404SPeter Xu 	struct pte_list_desc *desc, *next;
1014a75b5404SPeter Xu 	int i;
1015a75b5404SPeter Xu 
1016a75b5404SPeter Xu 	if (!rmap_head->val)
1017a75b5404SPeter Xu 		return false;
1018a75b5404SPeter Xu 
1019a75b5404SPeter Xu 	if (!(rmap_head->val & 1)) {
1020a75b5404SPeter Xu 		mmu_spte_clear_track_bits((u64 *)rmap_head->val);
1021a75b5404SPeter Xu 		goto out;
1022a75b5404SPeter Xu 	}
1023a75b5404SPeter Xu 
1024a75b5404SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1025a75b5404SPeter Xu 
1026a75b5404SPeter Xu 	for (; desc; desc = next) {
1027a75b5404SPeter Xu 		for (i = 0; i < desc->spte_count; i++)
1028a75b5404SPeter Xu 			mmu_spte_clear_track_bits(desc->sptes[i]);
1029a75b5404SPeter Xu 		next = desc->more;
1030a75b5404SPeter Xu 		mmu_free_pte_list_desc(desc);
1031a75b5404SPeter Xu 	}
1032a75b5404SPeter Xu out:
1033a75b5404SPeter Xu 	/* rmap_head is meaningless now, remember to reset it */
1034a75b5404SPeter Xu 	rmap_head->val = 0;
1035a75b5404SPeter Xu 	return true;
1036a75b5404SPeter Xu }
1037a75b5404SPeter Xu 
10383bcd0662SPeter Xu unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
10393bcd0662SPeter Xu {
10403bcd0662SPeter Xu 	struct pte_list_desc *desc;
10413bcd0662SPeter Xu 	unsigned int count = 0;
10423bcd0662SPeter Xu 
10433bcd0662SPeter Xu 	if (!rmap_head->val)
10443bcd0662SPeter Xu 		return 0;
10453bcd0662SPeter Xu 	else if (!(rmap_head->val & 1))
10463bcd0662SPeter Xu 		return 1;
10473bcd0662SPeter Xu 
10483bcd0662SPeter Xu 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
10493bcd0662SPeter Xu 
10503bcd0662SPeter Xu 	while (desc) {
10513bcd0662SPeter Xu 		count += desc->spte_count;
10523bcd0662SPeter Xu 		desc = desc->more;
10533bcd0662SPeter Xu 	}
10543bcd0662SPeter Xu 
10553bcd0662SPeter Xu 	return count;
10563bcd0662SPeter Xu }
10573bcd0662SPeter Xu 
105893e083d4SDavid Matlack static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1059269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
1060c50d8ae3SPaolo Bonzini {
1061c50d8ae3SPaolo Bonzini 	unsigned long idx;
1062c50d8ae3SPaolo Bonzini 
1063c50d8ae3SPaolo Bonzini 	idx = gfn_to_index(gfn, slot->base_gfn, level);
10643bae0459SSean Christopherson 	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1065c50d8ae3SPaolo Bonzini }
1066c50d8ae3SPaolo Bonzini 
1067c50d8ae3SPaolo Bonzini static bool rmap_can_add(struct kvm_vcpu *vcpu)
1068c50d8ae3SPaolo Bonzini {
1069356ec69aSSean Christopherson 	struct kvm_mmu_memory_cache *mc;
1070c50d8ae3SPaolo Bonzini 
1071356ec69aSSean Christopherson 	mc = &vcpu->arch.mmu_pte_list_desc_cache;
107294ce87efSSean Christopherson 	return kvm_mmu_memory_cache_nr_free_objects(mc);
1073c50d8ae3SPaolo Bonzini }
1074c50d8ae3SPaolo Bonzini 
1075c50d8ae3SPaolo Bonzini static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1076c50d8ae3SPaolo Bonzini {
1077601f8af0SDavid Matlack 	struct kvm_memory_slot *slot;
1078c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1079c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1080c50d8ae3SPaolo Bonzini 
108157354682SSean Christopherson 	sp = sptep_to_sp(spte);
1082c50d8ae3SPaolo Bonzini 	kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1083601f8af0SDavid Matlack 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
108493e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1085c50d8ae3SPaolo Bonzini 	return pte_list_add(vcpu, spte, rmap_head);
1086c50d8ae3SPaolo Bonzini }
1087c50d8ae3SPaolo Bonzini 
1088601f8af0SDavid Matlack 
1089c50d8ae3SPaolo Bonzini static void rmap_remove(struct kvm *kvm, u64 *spte)
1090c50d8ae3SPaolo Bonzini {
1091601f8af0SDavid Matlack 	struct kvm_memslots *slots;
1092601f8af0SDavid Matlack 	struct kvm_memory_slot *slot;
1093c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1094c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1095c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1096c50d8ae3SPaolo Bonzini 
109757354682SSean Christopherson 	sp = sptep_to_sp(spte);
1098c50d8ae3SPaolo Bonzini 	gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1099601f8af0SDavid Matlack 
1100601f8af0SDavid Matlack 	/*
1101601f8af0SDavid Matlack 	 * Unlike rmap_add and rmap_recycle, rmap_remove does not run in the
1102601f8af0SDavid Matlack 	 * context of a vCPU so have to determine which memslots to use based
1103601f8af0SDavid Matlack 	 * on context information in sp->role.
1104601f8af0SDavid Matlack 	 */
1105601f8af0SDavid Matlack 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1106601f8af0SDavid Matlack 
1107601f8af0SDavid Matlack 	slot = __gfn_to_memslot(slots, gfn);
110893e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1109601f8af0SDavid Matlack 
1110c50d8ae3SPaolo Bonzini 	__pte_list_remove(spte, rmap_head);
1111c50d8ae3SPaolo Bonzini }
1112c50d8ae3SPaolo Bonzini 
1113c50d8ae3SPaolo Bonzini /*
1114c50d8ae3SPaolo Bonzini  * Used by the following functions to iterate through the sptes linked by a
1115c50d8ae3SPaolo Bonzini  * rmap.  All fields are private and not assumed to be used outside.
1116c50d8ae3SPaolo Bonzini  */
1117c50d8ae3SPaolo Bonzini struct rmap_iterator {
1118c50d8ae3SPaolo Bonzini 	/* private fields */
1119c50d8ae3SPaolo Bonzini 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1120c50d8ae3SPaolo Bonzini 	int pos;			/* index of the sptep */
1121c50d8ae3SPaolo Bonzini };
1122c50d8ae3SPaolo Bonzini 
1123c50d8ae3SPaolo Bonzini /*
1124c50d8ae3SPaolo Bonzini  * Iteration must be started by this function.  This should also be used after
1125c50d8ae3SPaolo Bonzini  * removing/dropping sptes from the rmap link because in such cases the
11260a03cbdaSMiaohe Lin  * information in the iterator may not be valid.
1127c50d8ae3SPaolo Bonzini  *
1128c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1129c50d8ae3SPaolo Bonzini  */
1130c50d8ae3SPaolo Bonzini static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1131c50d8ae3SPaolo Bonzini 			   struct rmap_iterator *iter)
1132c50d8ae3SPaolo Bonzini {
1133c50d8ae3SPaolo Bonzini 	u64 *sptep;
1134c50d8ae3SPaolo Bonzini 
1135c50d8ae3SPaolo Bonzini 	if (!rmap_head->val)
1136c50d8ae3SPaolo Bonzini 		return NULL;
1137c50d8ae3SPaolo Bonzini 
1138c50d8ae3SPaolo Bonzini 	if (!(rmap_head->val & 1)) {
1139c50d8ae3SPaolo Bonzini 		iter->desc = NULL;
1140c50d8ae3SPaolo Bonzini 		sptep = (u64 *)rmap_head->val;
1141c50d8ae3SPaolo Bonzini 		goto out;
1142c50d8ae3SPaolo Bonzini 	}
1143c50d8ae3SPaolo Bonzini 
1144c50d8ae3SPaolo Bonzini 	iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1145c50d8ae3SPaolo Bonzini 	iter->pos = 0;
1146c50d8ae3SPaolo Bonzini 	sptep = iter->desc->sptes[iter->pos];
1147c50d8ae3SPaolo Bonzini out:
1148c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1149c50d8ae3SPaolo Bonzini 	return sptep;
1150c50d8ae3SPaolo Bonzini }
1151c50d8ae3SPaolo Bonzini 
1152c50d8ae3SPaolo Bonzini /*
1153c50d8ae3SPaolo Bonzini  * Must be used with a valid iterator: e.g. after rmap_get_first().
1154c50d8ae3SPaolo Bonzini  *
1155c50d8ae3SPaolo Bonzini  * Returns sptep if found, NULL otherwise.
1156c50d8ae3SPaolo Bonzini  */
1157c50d8ae3SPaolo Bonzini static u64 *rmap_get_next(struct rmap_iterator *iter)
1158c50d8ae3SPaolo Bonzini {
1159c50d8ae3SPaolo Bonzini 	u64 *sptep;
1160c50d8ae3SPaolo Bonzini 
1161c50d8ae3SPaolo Bonzini 	if (iter->desc) {
1162c50d8ae3SPaolo Bonzini 		if (iter->pos < PTE_LIST_EXT - 1) {
1163c50d8ae3SPaolo Bonzini 			++iter->pos;
1164c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1165c50d8ae3SPaolo Bonzini 			if (sptep)
1166c50d8ae3SPaolo Bonzini 				goto out;
1167c50d8ae3SPaolo Bonzini 		}
1168c50d8ae3SPaolo Bonzini 
1169c50d8ae3SPaolo Bonzini 		iter->desc = iter->desc->more;
1170c50d8ae3SPaolo Bonzini 
1171c50d8ae3SPaolo Bonzini 		if (iter->desc) {
1172c50d8ae3SPaolo Bonzini 			iter->pos = 0;
1173c50d8ae3SPaolo Bonzini 			/* desc->sptes[0] cannot be NULL */
1174c50d8ae3SPaolo Bonzini 			sptep = iter->desc->sptes[iter->pos];
1175c50d8ae3SPaolo Bonzini 			goto out;
1176c50d8ae3SPaolo Bonzini 		}
1177c50d8ae3SPaolo Bonzini 	}
1178c50d8ae3SPaolo Bonzini 
1179c50d8ae3SPaolo Bonzini 	return NULL;
1180c50d8ae3SPaolo Bonzini out:
1181c50d8ae3SPaolo Bonzini 	BUG_ON(!is_shadow_present_pte(*sptep));
1182c50d8ae3SPaolo Bonzini 	return sptep;
1183c50d8ae3SPaolo Bonzini }
1184c50d8ae3SPaolo Bonzini 
1185c50d8ae3SPaolo Bonzini #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)			\
1186c50d8ae3SPaolo Bonzini 	for (_spte_ = rmap_get_first(_rmap_head_, _iter_);		\
1187c50d8ae3SPaolo Bonzini 	     _spte_; _spte_ = rmap_get_next(_iter_))
1188c50d8ae3SPaolo Bonzini 
1189c50d8ae3SPaolo Bonzini static void drop_spte(struct kvm *kvm, u64 *sptep)
1190c50d8ae3SPaolo Bonzini {
11917fa2a347SSean Christopherson 	u64 old_spte = mmu_spte_clear_track_bits(sptep);
11927fa2a347SSean Christopherson 
11937fa2a347SSean Christopherson 	if (is_shadow_present_pte(old_spte))
1194c50d8ae3SPaolo Bonzini 		rmap_remove(kvm, sptep);
1195c50d8ae3SPaolo Bonzini }
1196c50d8ae3SPaolo Bonzini 
1197c50d8ae3SPaolo Bonzini 
1198c50d8ae3SPaolo Bonzini static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1199c50d8ae3SPaolo Bonzini {
1200c50d8ae3SPaolo Bonzini 	if (is_large_pte(*sptep)) {
120157354682SSean Christopherson 		WARN_ON(sptep_to_sp(sptep)->role.level == PG_LEVEL_4K);
1202c50d8ae3SPaolo Bonzini 		drop_spte(kvm, sptep);
1203c50d8ae3SPaolo Bonzini 		--kvm->stat.lpages;
1204c50d8ae3SPaolo Bonzini 		return true;
1205c50d8ae3SPaolo Bonzini 	}
1206c50d8ae3SPaolo Bonzini 
1207c50d8ae3SPaolo Bonzini 	return false;
1208c50d8ae3SPaolo Bonzini }
1209c50d8ae3SPaolo Bonzini 
1210c50d8ae3SPaolo Bonzini static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1211c50d8ae3SPaolo Bonzini {
1212c50d8ae3SPaolo Bonzini 	if (__drop_large_spte(vcpu->kvm, sptep)) {
121357354682SSean Christopherson 		struct kvm_mmu_page *sp = sptep_to_sp(sptep);
1214c50d8ae3SPaolo Bonzini 
1215c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1216c50d8ae3SPaolo Bonzini 			KVM_PAGES_PER_HPAGE(sp->role.level));
1217c50d8ae3SPaolo Bonzini 	}
1218c50d8ae3SPaolo Bonzini }
1219c50d8ae3SPaolo Bonzini 
1220c50d8ae3SPaolo Bonzini /*
1221c50d8ae3SPaolo Bonzini  * Write-protect on the specified @sptep, @pt_protect indicates whether
1222c50d8ae3SPaolo Bonzini  * spte write-protection is caused by protecting shadow page table.
1223c50d8ae3SPaolo Bonzini  *
1224c50d8ae3SPaolo Bonzini  * Note: write protection is difference between dirty logging and spte
1225c50d8ae3SPaolo Bonzini  * protection:
1226c50d8ae3SPaolo Bonzini  * - for dirty logging, the spte can be set to writable at anytime if
1227c50d8ae3SPaolo Bonzini  *   its dirty bitmap is properly set.
1228c50d8ae3SPaolo Bonzini  * - for spte protection, the spte can be writable only after unsync-ing
1229c50d8ae3SPaolo Bonzini  *   shadow page.
1230c50d8ae3SPaolo Bonzini  *
1231c50d8ae3SPaolo Bonzini  * Return true if tlb need be flushed.
1232c50d8ae3SPaolo Bonzini  */
1233c50d8ae3SPaolo Bonzini static bool spte_write_protect(u64 *sptep, bool pt_protect)
1234c50d8ae3SPaolo Bonzini {
1235c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1236c50d8ae3SPaolo Bonzini 
1237c50d8ae3SPaolo Bonzini 	if (!is_writable_pte(spte) &&
1238c50d8ae3SPaolo Bonzini 	      !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1239c50d8ae3SPaolo Bonzini 		return false;
1240c50d8ae3SPaolo Bonzini 
1241805a0f83SStephen Zhang 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1242c50d8ae3SPaolo Bonzini 
1243c50d8ae3SPaolo Bonzini 	if (pt_protect)
12445fc3424fSSean Christopherson 		spte &= ~shadow_mmu_writable_mask;
1245c50d8ae3SPaolo Bonzini 	spte = spte & ~PT_WRITABLE_MASK;
1246c50d8ae3SPaolo Bonzini 
1247c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1248c50d8ae3SPaolo Bonzini }
1249c50d8ae3SPaolo Bonzini 
1250c50d8ae3SPaolo Bonzini static bool __rmap_write_protect(struct kvm *kvm,
1251c50d8ae3SPaolo Bonzini 				 struct kvm_rmap_head *rmap_head,
1252c50d8ae3SPaolo Bonzini 				 bool pt_protect)
1253c50d8ae3SPaolo Bonzini {
1254c50d8ae3SPaolo Bonzini 	u64 *sptep;
1255c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1256c50d8ae3SPaolo Bonzini 	bool flush = false;
1257c50d8ae3SPaolo Bonzini 
1258c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1259c50d8ae3SPaolo Bonzini 		flush |= spte_write_protect(sptep, pt_protect);
1260c50d8ae3SPaolo Bonzini 
1261c50d8ae3SPaolo Bonzini 	return flush;
1262c50d8ae3SPaolo Bonzini }
1263c50d8ae3SPaolo Bonzini 
1264c50d8ae3SPaolo Bonzini static bool spte_clear_dirty(u64 *sptep)
1265c50d8ae3SPaolo Bonzini {
1266c50d8ae3SPaolo Bonzini 	u64 spte = *sptep;
1267c50d8ae3SPaolo Bonzini 
1268805a0f83SStephen Zhang 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1269c50d8ae3SPaolo Bonzini 
1270c50d8ae3SPaolo Bonzini 	MMU_WARN_ON(!spte_ad_enabled(spte));
1271c50d8ae3SPaolo Bonzini 	spte &= ~shadow_dirty_mask;
1272c50d8ae3SPaolo Bonzini 	return mmu_spte_update(sptep, spte);
1273c50d8ae3SPaolo Bonzini }
1274c50d8ae3SPaolo Bonzini 
1275c50d8ae3SPaolo Bonzini static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1276c50d8ae3SPaolo Bonzini {
1277c50d8ae3SPaolo Bonzini 	bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1278c50d8ae3SPaolo Bonzini 					       (unsigned long *)sptep);
1279c50d8ae3SPaolo Bonzini 	if (was_writable && !spte_ad_enabled(*sptep))
1280c50d8ae3SPaolo Bonzini 		kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1281c50d8ae3SPaolo Bonzini 
1282c50d8ae3SPaolo Bonzini 	return was_writable;
1283c50d8ae3SPaolo Bonzini }
1284c50d8ae3SPaolo Bonzini 
1285c50d8ae3SPaolo Bonzini /*
1286c50d8ae3SPaolo Bonzini  * Gets the GFN ready for another round of dirty logging by clearing the
1287c50d8ae3SPaolo Bonzini  *	- D bit on ad-enabled SPTEs, and
1288c50d8ae3SPaolo Bonzini  *	- W bit on ad-disabled SPTEs.
1289c50d8ae3SPaolo Bonzini  * Returns true iff any D or W bits were cleared.
1290c50d8ae3SPaolo Bonzini  */
12910a234f5dSSean Christopherson static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1292269e9552SHamza Mahfooz 			       const struct kvm_memory_slot *slot)
1293c50d8ae3SPaolo Bonzini {
1294c50d8ae3SPaolo Bonzini 	u64 *sptep;
1295c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1296c50d8ae3SPaolo Bonzini 	bool flush = false;
1297c50d8ae3SPaolo Bonzini 
1298c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1299c50d8ae3SPaolo Bonzini 		if (spte_ad_need_write_protect(*sptep))
1300c50d8ae3SPaolo Bonzini 			flush |= spte_wrprot_for_clear_dirty(sptep);
1301c50d8ae3SPaolo Bonzini 		else
1302c50d8ae3SPaolo Bonzini 			flush |= spte_clear_dirty(sptep);
1303c50d8ae3SPaolo Bonzini 
1304c50d8ae3SPaolo Bonzini 	return flush;
1305c50d8ae3SPaolo Bonzini }
1306c50d8ae3SPaolo Bonzini 
1307c50d8ae3SPaolo Bonzini /**
1308c50d8ae3SPaolo Bonzini  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1309c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1310c50d8ae3SPaolo Bonzini  * @slot: slot to protect
1311c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1312c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should protect
1313c50d8ae3SPaolo Bonzini  *
131489212919SKeqian Zhu  * Used when we do not need to care about huge page mappings.
1315c50d8ae3SPaolo Bonzini  */
1316c50d8ae3SPaolo Bonzini static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1317c50d8ae3SPaolo Bonzini 				     struct kvm_memory_slot *slot,
1318c50d8ae3SPaolo Bonzini 				     gfn_t gfn_offset, unsigned long mask)
1319c50d8ae3SPaolo Bonzini {
1320c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1321c50d8ae3SPaolo Bonzini 
1322897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
1323a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1324a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, true);
1325e2209710SBen Gardon 
1326e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1327e2209710SBen Gardon 		return;
1328e2209710SBen Gardon 
1329c50d8ae3SPaolo Bonzini 	while (mask) {
133093e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13313bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
1332c50d8ae3SPaolo Bonzini 		__rmap_write_protect(kvm, rmap_head, false);
1333c50d8ae3SPaolo Bonzini 
1334c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1335c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1336c50d8ae3SPaolo Bonzini 	}
1337c50d8ae3SPaolo Bonzini }
1338c50d8ae3SPaolo Bonzini 
1339c50d8ae3SPaolo Bonzini /**
1340c50d8ae3SPaolo Bonzini  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1341c50d8ae3SPaolo Bonzini  * protect the page if the D-bit isn't supported.
1342c50d8ae3SPaolo Bonzini  * @kvm: kvm instance
1343c50d8ae3SPaolo Bonzini  * @slot: slot to clear D-bit
1344c50d8ae3SPaolo Bonzini  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1345c50d8ae3SPaolo Bonzini  * @mask: indicates which pages we should clear D-bit
1346c50d8ae3SPaolo Bonzini  *
1347c50d8ae3SPaolo Bonzini  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1348c50d8ae3SPaolo Bonzini  */
1349a018eba5SSean Christopherson static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1350c50d8ae3SPaolo Bonzini 					 struct kvm_memory_slot *slot,
1351c50d8ae3SPaolo Bonzini 					 gfn_t gfn_offset, unsigned long mask)
1352c50d8ae3SPaolo Bonzini {
1353c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1354c50d8ae3SPaolo Bonzini 
1355897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
1356a6a0b05dSBen Gardon 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1357a6a0b05dSBen Gardon 				slot->base_gfn + gfn_offset, mask, false);
1358e2209710SBen Gardon 
1359e2209710SBen Gardon 	if (!kvm_memslots_have_rmaps(kvm))
1360e2209710SBen Gardon 		return;
1361e2209710SBen Gardon 
1362c50d8ae3SPaolo Bonzini 	while (mask) {
136393e083d4SDavid Matlack 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
13643bae0459SSean Christopherson 					PG_LEVEL_4K, slot);
13650a234f5dSSean Christopherson 		__rmap_clear_dirty(kvm, rmap_head, slot);
1366c50d8ae3SPaolo Bonzini 
1367c50d8ae3SPaolo Bonzini 		/* clear the first set bit */
1368c50d8ae3SPaolo Bonzini 		mask &= mask - 1;
1369c50d8ae3SPaolo Bonzini 	}
1370c50d8ae3SPaolo Bonzini }
1371c50d8ae3SPaolo Bonzini 
1372c50d8ae3SPaolo Bonzini /**
1373c50d8ae3SPaolo Bonzini  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1374c50d8ae3SPaolo Bonzini  * PT level pages.
1375c50d8ae3SPaolo Bonzini  *
1376c50d8ae3SPaolo Bonzini  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1377c50d8ae3SPaolo Bonzini  * enable dirty logging for them.
1378c50d8ae3SPaolo Bonzini  *
137989212919SKeqian Zhu  * We need to care about huge page mappings: e.g. during dirty logging we may
138089212919SKeqian Zhu  * have such mappings.
1381c50d8ae3SPaolo Bonzini  */
1382c50d8ae3SPaolo Bonzini void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1383c50d8ae3SPaolo Bonzini 				struct kvm_memory_slot *slot,
1384c50d8ae3SPaolo Bonzini 				gfn_t gfn_offset, unsigned long mask)
1385c50d8ae3SPaolo Bonzini {
138689212919SKeqian Zhu 	/*
138789212919SKeqian Zhu 	 * Huge pages are NOT write protected when we start dirty logging in
138889212919SKeqian Zhu 	 * initially-all-set mode; must write protect them here so that they
138989212919SKeqian Zhu 	 * are split to 4K on the first write.
139089212919SKeqian Zhu 	 *
139189212919SKeqian Zhu 	 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
139289212919SKeqian Zhu 	 * of memslot has no such restriction, so the range can cross two large
139389212919SKeqian Zhu 	 * pages.
139489212919SKeqian Zhu 	 */
139589212919SKeqian Zhu 	if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
139689212919SKeqian Zhu 		gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
139789212919SKeqian Zhu 		gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
139889212919SKeqian Zhu 
139989212919SKeqian Zhu 		kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
140089212919SKeqian Zhu 
140189212919SKeqian Zhu 		/* Cross two large pages? */
140289212919SKeqian Zhu 		if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
140389212919SKeqian Zhu 		    ALIGN(end << PAGE_SHIFT, PMD_SIZE))
140489212919SKeqian Zhu 			kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
140589212919SKeqian Zhu 						       PG_LEVEL_2M);
140689212919SKeqian Zhu 	}
140789212919SKeqian Zhu 
140889212919SKeqian Zhu 	/* Now handle 4K PTEs.  */
1409a018eba5SSean Christopherson 	if (kvm_x86_ops.cpu_dirty_log_size)
1410a018eba5SSean Christopherson 		kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1411c50d8ae3SPaolo Bonzini 	else
1412c50d8ae3SPaolo Bonzini 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1413c50d8ae3SPaolo Bonzini }
1414c50d8ae3SPaolo Bonzini 
1415fb04a1edSPeter Xu int kvm_cpu_dirty_log_size(void)
1416fb04a1edSPeter Xu {
14176dd03800SSean Christopherson 	return kvm_x86_ops.cpu_dirty_log_size;
1418fb04a1edSPeter Xu }
1419fb04a1edSPeter Xu 
1420c50d8ae3SPaolo Bonzini bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
14213ad93562SKeqian Zhu 				    struct kvm_memory_slot *slot, u64 gfn,
14223ad93562SKeqian Zhu 				    int min_level)
1423c50d8ae3SPaolo Bonzini {
1424c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1425c50d8ae3SPaolo Bonzini 	int i;
1426c50d8ae3SPaolo Bonzini 	bool write_protected = false;
1427c50d8ae3SPaolo Bonzini 
1428e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
14293ad93562SKeqian Zhu 		for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
143093e083d4SDavid Matlack 			rmap_head = gfn_to_rmap(gfn, i, slot);
1431c50d8ae3SPaolo Bonzini 			write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1432c50d8ae3SPaolo Bonzini 		}
1433e2209710SBen Gardon 	}
1434c50d8ae3SPaolo Bonzini 
1435897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
143646044f72SBen Gardon 		write_protected |=
14373ad93562SKeqian Zhu 			kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
143846044f72SBen Gardon 
1439c50d8ae3SPaolo Bonzini 	return write_protected;
1440c50d8ae3SPaolo Bonzini }
1441c50d8ae3SPaolo Bonzini 
1442c50d8ae3SPaolo Bonzini static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1443c50d8ae3SPaolo Bonzini {
1444c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
1445c50d8ae3SPaolo Bonzini 
1446c50d8ae3SPaolo Bonzini 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
14473ad93562SKeqian Zhu 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1448c50d8ae3SPaolo Bonzini }
1449c50d8ae3SPaolo Bonzini 
14500a234f5dSSean Christopherson static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1451269e9552SHamza Mahfooz 			  const struct kvm_memory_slot *slot)
1452c50d8ae3SPaolo Bonzini {
1453a75b5404SPeter Xu 	return pte_list_destroy(rmap_head);
1454c50d8ae3SPaolo Bonzini }
1455c50d8ae3SPaolo Bonzini 
14563039bcc7SSean Christopherson static bool kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1457c50d8ae3SPaolo Bonzini 			    struct kvm_memory_slot *slot, gfn_t gfn, int level,
14583039bcc7SSean Christopherson 			    pte_t unused)
1459c50d8ae3SPaolo Bonzini {
14600a234f5dSSean Christopherson 	return kvm_zap_rmapp(kvm, rmap_head, slot);
1461c50d8ae3SPaolo Bonzini }
1462c50d8ae3SPaolo Bonzini 
14633039bcc7SSean Christopherson static bool kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1464c50d8ae3SPaolo Bonzini 			      struct kvm_memory_slot *slot, gfn_t gfn, int level,
14653039bcc7SSean Christopherson 			      pte_t pte)
1466c50d8ae3SPaolo Bonzini {
1467c50d8ae3SPaolo Bonzini 	u64 *sptep;
1468c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1469c50d8ae3SPaolo Bonzini 	int need_flush = 0;
1470c50d8ae3SPaolo Bonzini 	u64 new_spte;
1471c50d8ae3SPaolo Bonzini 	kvm_pfn_t new_pfn;
1472c50d8ae3SPaolo Bonzini 
14733039bcc7SSean Christopherson 	WARN_ON(pte_huge(pte));
14743039bcc7SSean Christopherson 	new_pfn = pte_pfn(pte);
1475c50d8ae3SPaolo Bonzini 
1476c50d8ae3SPaolo Bonzini restart:
1477c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
1478805a0f83SStephen Zhang 		rmap_printk("spte %p %llx gfn %llx (%d)\n",
1479c50d8ae3SPaolo Bonzini 			    sptep, *sptep, gfn, level);
1480c50d8ae3SPaolo Bonzini 
1481c50d8ae3SPaolo Bonzini 		need_flush = 1;
1482c50d8ae3SPaolo Bonzini 
14833039bcc7SSean Christopherson 		if (pte_write(pte)) {
1484c50d8ae3SPaolo Bonzini 			pte_list_remove(rmap_head, sptep);
1485c50d8ae3SPaolo Bonzini 			goto restart;
1486c50d8ae3SPaolo Bonzini 		} else {
1487cb3eedabSPaolo Bonzini 			new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1488cb3eedabSPaolo Bonzini 					*sptep, new_pfn);
1489c50d8ae3SPaolo Bonzini 
1490c50d8ae3SPaolo Bonzini 			mmu_spte_clear_track_bits(sptep);
1491c50d8ae3SPaolo Bonzini 			mmu_spte_set(sptep, new_spte);
1492c50d8ae3SPaolo Bonzini 		}
1493c50d8ae3SPaolo Bonzini 	}
1494c50d8ae3SPaolo Bonzini 
1495c50d8ae3SPaolo Bonzini 	if (need_flush && kvm_available_flush_tlb_with_range()) {
1496c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(kvm, gfn, 1);
1497c50d8ae3SPaolo Bonzini 		return 0;
1498c50d8ae3SPaolo Bonzini 	}
1499c50d8ae3SPaolo Bonzini 
1500c50d8ae3SPaolo Bonzini 	return need_flush;
1501c50d8ae3SPaolo Bonzini }
1502c50d8ae3SPaolo Bonzini 
1503c50d8ae3SPaolo Bonzini struct slot_rmap_walk_iterator {
1504c50d8ae3SPaolo Bonzini 	/* input fields. */
1505269e9552SHamza Mahfooz 	const struct kvm_memory_slot *slot;
1506c50d8ae3SPaolo Bonzini 	gfn_t start_gfn;
1507c50d8ae3SPaolo Bonzini 	gfn_t end_gfn;
1508c50d8ae3SPaolo Bonzini 	int start_level;
1509c50d8ae3SPaolo Bonzini 	int end_level;
1510c50d8ae3SPaolo Bonzini 
1511c50d8ae3SPaolo Bonzini 	/* output fields. */
1512c50d8ae3SPaolo Bonzini 	gfn_t gfn;
1513c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap;
1514c50d8ae3SPaolo Bonzini 	int level;
1515c50d8ae3SPaolo Bonzini 
1516c50d8ae3SPaolo Bonzini 	/* private field. */
1517c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *end_rmap;
1518c50d8ae3SPaolo Bonzini };
1519c50d8ae3SPaolo Bonzini 
1520c50d8ae3SPaolo Bonzini static void
1521c50d8ae3SPaolo Bonzini rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1522c50d8ae3SPaolo Bonzini {
1523c50d8ae3SPaolo Bonzini 	iterator->level = level;
1524c50d8ae3SPaolo Bonzini 	iterator->gfn = iterator->start_gfn;
152593e083d4SDavid Matlack 	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
152693e083d4SDavid Matlack 	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1527c50d8ae3SPaolo Bonzini }
1528c50d8ae3SPaolo Bonzini 
1529c50d8ae3SPaolo Bonzini static void
1530c50d8ae3SPaolo Bonzini slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1531269e9552SHamza Mahfooz 		    const struct kvm_memory_slot *slot, int start_level,
1532c50d8ae3SPaolo Bonzini 		    int end_level, gfn_t start_gfn, gfn_t end_gfn)
1533c50d8ae3SPaolo Bonzini {
1534c50d8ae3SPaolo Bonzini 	iterator->slot = slot;
1535c50d8ae3SPaolo Bonzini 	iterator->start_level = start_level;
1536c50d8ae3SPaolo Bonzini 	iterator->end_level = end_level;
1537c50d8ae3SPaolo Bonzini 	iterator->start_gfn = start_gfn;
1538c50d8ae3SPaolo Bonzini 	iterator->end_gfn = end_gfn;
1539c50d8ae3SPaolo Bonzini 
1540c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->start_level);
1541c50d8ae3SPaolo Bonzini }
1542c50d8ae3SPaolo Bonzini 
1543c50d8ae3SPaolo Bonzini static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1544c50d8ae3SPaolo Bonzini {
1545c50d8ae3SPaolo Bonzini 	return !!iterator->rmap;
1546c50d8ae3SPaolo Bonzini }
1547c50d8ae3SPaolo Bonzini 
1548c50d8ae3SPaolo Bonzini static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1549c50d8ae3SPaolo Bonzini {
1550c50d8ae3SPaolo Bonzini 	if (++iterator->rmap <= iterator->end_rmap) {
1551c50d8ae3SPaolo Bonzini 		iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1552c50d8ae3SPaolo Bonzini 		return;
1553c50d8ae3SPaolo Bonzini 	}
1554c50d8ae3SPaolo Bonzini 
1555c50d8ae3SPaolo Bonzini 	if (++iterator->level > iterator->end_level) {
1556c50d8ae3SPaolo Bonzini 		iterator->rmap = NULL;
1557c50d8ae3SPaolo Bonzini 		return;
1558c50d8ae3SPaolo Bonzini 	}
1559c50d8ae3SPaolo Bonzini 
1560c50d8ae3SPaolo Bonzini 	rmap_walk_init_level(iterator, iterator->level);
1561c50d8ae3SPaolo Bonzini }
1562c50d8ae3SPaolo Bonzini 
1563c50d8ae3SPaolo Bonzini #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1564c50d8ae3SPaolo Bonzini 	   _start_gfn, _end_gfn, _iter_)				\
1565c50d8ae3SPaolo Bonzini 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1566c50d8ae3SPaolo Bonzini 				 _end_level_, _start_gfn, _end_gfn);	\
1567c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_okay(_iter_);				\
1568c50d8ae3SPaolo Bonzini 	     slot_rmap_walk_next(_iter_))
1569c50d8ae3SPaolo Bonzini 
15703039bcc7SSean Christopherson typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1571c1b91493SSean Christopherson 			       struct kvm_memory_slot *slot, gfn_t gfn,
15723039bcc7SSean Christopherson 			       int level, pte_t pte);
1573c1b91493SSean Christopherson 
15743039bcc7SSean Christopherson static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
15753039bcc7SSean Christopherson 						 struct kvm_gfn_range *range,
1576c1b91493SSean Christopherson 						 rmap_handler_t handler)
1577c50d8ae3SPaolo Bonzini {
1578c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
15793039bcc7SSean Christopherson 	bool ret = false;
1580c50d8ae3SPaolo Bonzini 
15813039bcc7SSean Christopherson 	for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
15823039bcc7SSean Christopherson 				 range->start, range->end - 1, &iterator)
15833039bcc7SSean Christopherson 		ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
15843039bcc7SSean Christopherson 			       iterator.level, range->pte);
1585c50d8ae3SPaolo Bonzini 
1586c50d8ae3SPaolo Bonzini 	return ret;
1587c50d8ae3SPaolo Bonzini }
1588c50d8ae3SPaolo Bonzini 
15893039bcc7SSean Christopherson bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1590c50d8ae3SPaolo Bonzini {
1591e2209710SBen Gardon 	bool flush = false;
1592c50d8ae3SPaolo Bonzini 
1593e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
15943039bcc7SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_unmap_rmapp);
1595063afacdSBen Gardon 
1596897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
15973039bcc7SSean Christopherson 		flush |= kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1598063afacdSBen Gardon 
15993039bcc7SSean Christopherson 	return flush;
1600c50d8ae3SPaolo Bonzini }
1601c50d8ae3SPaolo Bonzini 
16023039bcc7SSean Christopherson bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1603c50d8ae3SPaolo Bonzini {
1604e2209710SBen Gardon 	bool flush = false;
16051d8dd6b3SBen Gardon 
1606e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
16073039bcc7SSean Christopherson 		flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmapp);
16081d8dd6b3SBen Gardon 
1609897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
16103039bcc7SSean Christopherson 		flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
16111d8dd6b3SBen Gardon 
16123039bcc7SSean Christopherson 	return flush;
1613c50d8ae3SPaolo Bonzini }
1614c50d8ae3SPaolo Bonzini 
16153039bcc7SSean Christopherson static bool kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1616c50d8ae3SPaolo Bonzini 			  struct kvm_memory_slot *slot, gfn_t gfn, int level,
16173039bcc7SSean Christopherson 			  pte_t unused)
1618c50d8ae3SPaolo Bonzini {
1619c50d8ae3SPaolo Bonzini 	u64 *sptep;
16203f649ab7SKees Cook 	struct rmap_iterator iter;
1621c50d8ae3SPaolo Bonzini 	int young = 0;
1622c50d8ae3SPaolo Bonzini 
1623c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1624c50d8ae3SPaolo Bonzini 		young |= mmu_spte_age(sptep);
1625c50d8ae3SPaolo Bonzini 
1626c50d8ae3SPaolo Bonzini 	return young;
1627c50d8ae3SPaolo Bonzini }
1628c50d8ae3SPaolo Bonzini 
16293039bcc7SSean Christopherson static bool kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1630c50d8ae3SPaolo Bonzini 			       struct kvm_memory_slot *slot, gfn_t gfn,
16313039bcc7SSean Christopherson 			       int level, pte_t unused)
1632c50d8ae3SPaolo Bonzini {
1633c50d8ae3SPaolo Bonzini 	u64 *sptep;
1634c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1635c50d8ae3SPaolo Bonzini 
1636c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep)
1637c50d8ae3SPaolo Bonzini 		if (is_accessed_spte(*sptep))
1638c50d8ae3SPaolo Bonzini 			return 1;
1639c50d8ae3SPaolo Bonzini 	return 0;
1640c50d8ae3SPaolo Bonzini }
1641c50d8ae3SPaolo Bonzini 
1642c50d8ae3SPaolo Bonzini #define RMAP_RECYCLE_THRESHOLD 1000
1643c50d8ae3SPaolo Bonzini 
1644c50d8ae3SPaolo Bonzini static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1645c50d8ae3SPaolo Bonzini {
1646601f8af0SDavid Matlack 	struct kvm_memory_slot *slot;
1647c50d8ae3SPaolo Bonzini 	struct kvm_rmap_head *rmap_head;
1648c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1649c50d8ae3SPaolo Bonzini 
165057354682SSean Christopherson 	sp = sptep_to_sp(spte);
1651601f8af0SDavid Matlack 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
165293e083d4SDavid Matlack 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1653c50d8ae3SPaolo Bonzini 
16543039bcc7SSean Christopherson 	kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, __pte(0));
1655c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1656c50d8ae3SPaolo Bonzini 			KVM_PAGES_PER_HPAGE(sp->role.level));
1657c50d8ae3SPaolo Bonzini }
1658c50d8ae3SPaolo Bonzini 
16593039bcc7SSean Christopherson bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1660c50d8ae3SPaolo Bonzini {
1661e2209710SBen Gardon 	bool young = false;
1662f8e14497SBen Gardon 
1663e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
16643039bcc7SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_age_rmapp);
16653039bcc7SSean Christopherson 
1666897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
16673039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1668f8e14497SBen Gardon 
1669f8e14497SBen Gardon 	return young;
1670c50d8ae3SPaolo Bonzini }
1671c50d8ae3SPaolo Bonzini 
16723039bcc7SSean Christopherson bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1673c50d8ae3SPaolo Bonzini {
1674e2209710SBen Gardon 	bool young = false;
1675f8e14497SBen Gardon 
1676e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm))
16773039bcc7SSean Christopherson 		young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmapp);
16783039bcc7SSean Christopherson 
1679897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
16803039bcc7SSean Christopherson 		young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1681f8e14497SBen Gardon 
1682f8e14497SBen Gardon 	return young;
1683c50d8ae3SPaolo Bonzini }
1684c50d8ae3SPaolo Bonzini 
1685c50d8ae3SPaolo Bonzini #ifdef MMU_DEBUG
1686c50d8ae3SPaolo Bonzini static int is_empty_shadow_page(u64 *spt)
1687c50d8ae3SPaolo Bonzini {
1688c50d8ae3SPaolo Bonzini 	u64 *pos;
1689c50d8ae3SPaolo Bonzini 	u64 *end;
1690c50d8ae3SPaolo Bonzini 
1691c50d8ae3SPaolo Bonzini 	for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1692c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*pos)) {
1693c50d8ae3SPaolo Bonzini 			printk(KERN_ERR "%s: %p %llx\n", __func__,
1694c50d8ae3SPaolo Bonzini 			       pos, *pos);
1695c50d8ae3SPaolo Bonzini 			return 0;
1696c50d8ae3SPaolo Bonzini 		}
1697c50d8ae3SPaolo Bonzini 	return 1;
1698c50d8ae3SPaolo Bonzini }
1699c50d8ae3SPaolo Bonzini #endif
1700c50d8ae3SPaolo Bonzini 
1701c50d8ae3SPaolo Bonzini /*
1702c50d8ae3SPaolo Bonzini  * This value is the sum of all of the kvm instances's
1703c50d8ae3SPaolo Bonzini  * kvm->arch.n_used_mmu_pages values.  We need a global,
1704c50d8ae3SPaolo Bonzini  * aggregate version in order to make the slab shrinker
1705c50d8ae3SPaolo Bonzini  * faster
1706c50d8ae3SPaolo Bonzini  */
1707d5aaad6fSSean Christopherson static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1708c50d8ae3SPaolo Bonzini {
1709c50d8ae3SPaolo Bonzini 	kvm->arch.n_used_mmu_pages += nr;
1710c50d8ae3SPaolo Bonzini 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1711c50d8ae3SPaolo Bonzini }
1712c50d8ae3SPaolo Bonzini 
1713c50d8ae3SPaolo Bonzini static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
1714c50d8ae3SPaolo Bonzini {
1715c50d8ae3SPaolo Bonzini 	MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1716c50d8ae3SPaolo Bonzini 	hlist_del(&sp->hash_link);
1717c50d8ae3SPaolo Bonzini 	list_del(&sp->link);
1718c50d8ae3SPaolo Bonzini 	free_page((unsigned long)sp->spt);
1719c50d8ae3SPaolo Bonzini 	if (!sp->role.direct)
1720c50d8ae3SPaolo Bonzini 		free_page((unsigned long)sp->gfns);
1721c50d8ae3SPaolo Bonzini 	kmem_cache_free(mmu_page_header_cache, sp);
1722c50d8ae3SPaolo Bonzini }
1723c50d8ae3SPaolo Bonzini 
1724c50d8ae3SPaolo Bonzini static unsigned kvm_page_table_hashfn(gfn_t gfn)
1725c50d8ae3SPaolo Bonzini {
1726c50d8ae3SPaolo Bonzini 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1727c50d8ae3SPaolo Bonzini }
1728c50d8ae3SPaolo Bonzini 
1729c50d8ae3SPaolo Bonzini static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
1730c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp, u64 *parent_pte)
1731c50d8ae3SPaolo Bonzini {
1732c50d8ae3SPaolo Bonzini 	if (!parent_pte)
1733c50d8ae3SPaolo Bonzini 		return;
1734c50d8ae3SPaolo Bonzini 
1735c50d8ae3SPaolo Bonzini 	pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
1736c50d8ae3SPaolo Bonzini }
1737c50d8ae3SPaolo Bonzini 
1738c50d8ae3SPaolo Bonzini static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1739c50d8ae3SPaolo Bonzini 				       u64 *parent_pte)
1740c50d8ae3SPaolo Bonzini {
1741c50d8ae3SPaolo Bonzini 	__pte_list_remove(parent_pte, &sp->parent_ptes);
1742c50d8ae3SPaolo Bonzini }
1743c50d8ae3SPaolo Bonzini 
1744c50d8ae3SPaolo Bonzini static void drop_parent_pte(struct kvm_mmu_page *sp,
1745c50d8ae3SPaolo Bonzini 			    u64 *parent_pte)
1746c50d8ae3SPaolo Bonzini {
1747c50d8ae3SPaolo Bonzini 	mmu_page_remove_parent_pte(sp, parent_pte);
1748c50d8ae3SPaolo Bonzini 	mmu_spte_clear_no_track(parent_pte);
1749c50d8ae3SPaolo Bonzini }
1750c50d8ae3SPaolo Bonzini 
1751c50d8ae3SPaolo Bonzini static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
1752c50d8ae3SPaolo Bonzini {
1753c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1754c50d8ae3SPaolo Bonzini 
175594ce87efSSean Christopherson 	sp = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
175694ce87efSSean Christopherson 	sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
1757c50d8ae3SPaolo Bonzini 	if (!direct)
175894ce87efSSean Christopherson 		sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
1759c50d8ae3SPaolo Bonzini 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
1760c50d8ae3SPaolo Bonzini 
1761c50d8ae3SPaolo Bonzini 	/*
1762c50d8ae3SPaolo Bonzini 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
1763c50d8ae3SPaolo Bonzini 	 * depends on valid pages being added to the head of the list.  See
1764c50d8ae3SPaolo Bonzini 	 * comments in kvm_zap_obsolete_pages().
1765c50d8ae3SPaolo Bonzini 	 */
1766c50d8ae3SPaolo Bonzini 	sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
1767c50d8ae3SPaolo Bonzini 	list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
1768c50d8ae3SPaolo Bonzini 	kvm_mod_used_mmu_pages(vcpu->kvm, +1);
1769c50d8ae3SPaolo Bonzini 	return sp;
1770c50d8ae3SPaolo Bonzini }
1771c50d8ae3SPaolo Bonzini 
1772c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte);
1773c50d8ae3SPaolo Bonzini static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1774c50d8ae3SPaolo Bonzini {
1775c50d8ae3SPaolo Bonzini 	u64 *sptep;
1776c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
1777c50d8ae3SPaolo Bonzini 
1778c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1779c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
1780c50d8ae3SPaolo Bonzini 	}
1781c50d8ae3SPaolo Bonzini }
1782c50d8ae3SPaolo Bonzini 
1783c50d8ae3SPaolo Bonzini static void mark_unsync(u64 *spte)
1784c50d8ae3SPaolo Bonzini {
1785c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1786c50d8ae3SPaolo Bonzini 	unsigned int index;
1787c50d8ae3SPaolo Bonzini 
178857354682SSean Christopherson 	sp = sptep_to_sp(spte);
1789c50d8ae3SPaolo Bonzini 	index = spte - sp->spt;
1790c50d8ae3SPaolo Bonzini 	if (__test_and_set_bit(index, sp->unsync_child_bitmap))
1791c50d8ae3SPaolo Bonzini 		return;
1792c50d8ae3SPaolo Bonzini 	if (sp->unsync_children++)
1793c50d8ae3SPaolo Bonzini 		return;
1794c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
1795c50d8ae3SPaolo Bonzini }
1796c50d8ae3SPaolo Bonzini 
1797c50d8ae3SPaolo Bonzini static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
1798c50d8ae3SPaolo Bonzini 			       struct kvm_mmu_page *sp)
1799c50d8ae3SPaolo Bonzini {
1800c50d8ae3SPaolo Bonzini 	return 0;
1801c50d8ae3SPaolo Bonzini }
1802c50d8ae3SPaolo Bonzini 
1803c50d8ae3SPaolo Bonzini #define KVM_PAGE_ARRAY_NR 16
1804c50d8ae3SPaolo Bonzini 
1805c50d8ae3SPaolo Bonzini struct kvm_mmu_pages {
1806c50d8ae3SPaolo Bonzini 	struct mmu_page_and_offset {
1807c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
1808c50d8ae3SPaolo Bonzini 		unsigned int idx;
1809c50d8ae3SPaolo Bonzini 	} page[KVM_PAGE_ARRAY_NR];
1810c50d8ae3SPaolo Bonzini 	unsigned int nr;
1811c50d8ae3SPaolo Bonzini };
1812c50d8ae3SPaolo Bonzini 
1813c50d8ae3SPaolo Bonzini static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1814c50d8ae3SPaolo Bonzini 			 int idx)
1815c50d8ae3SPaolo Bonzini {
1816c50d8ae3SPaolo Bonzini 	int i;
1817c50d8ae3SPaolo Bonzini 
1818c50d8ae3SPaolo Bonzini 	if (sp->unsync)
1819c50d8ae3SPaolo Bonzini 		for (i=0; i < pvec->nr; i++)
1820c50d8ae3SPaolo Bonzini 			if (pvec->page[i].sp == sp)
1821c50d8ae3SPaolo Bonzini 				return 0;
1822c50d8ae3SPaolo Bonzini 
1823c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].sp = sp;
1824c50d8ae3SPaolo Bonzini 	pvec->page[pvec->nr].idx = idx;
1825c50d8ae3SPaolo Bonzini 	pvec->nr++;
1826c50d8ae3SPaolo Bonzini 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
1827c50d8ae3SPaolo Bonzini }
1828c50d8ae3SPaolo Bonzini 
1829c50d8ae3SPaolo Bonzini static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1830c50d8ae3SPaolo Bonzini {
1831c50d8ae3SPaolo Bonzini 	--sp->unsync_children;
1832c50d8ae3SPaolo Bonzini 	WARN_ON((int)sp->unsync_children < 0);
1833c50d8ae3SPaolo Bonzini 	__clear_bit(idx, sp->unsync_child_bitmap);
1834c50d8ae3SPaolo Bonzini }
1835c50d8ae3SPaolo Bonzini 
1836c50d8ae3SPaolo Bonzini static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1837c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1838c50d8ae3SPaolo Bonzini {
1839c50d8ae3SPaolo Bonzini 	int i, ret, nr_unsync_leaf = 0;
1840c50d8ae3SPaolo Bonzini 
1841c50d8ae3SPaolo Bonzini 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1842c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
1843c50d8ae3SPaolo Bonzini 		u64 ent = sp->spt[i];
1844c50d8ae3SPaolo Bonzini 
1845c50d8ae3SPaolo Bonzini 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1846c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1847c50d8ae3SPaolo Bonzini 			continue;
1848c50d8ae3SPaolo Bonzini 		}
1849c50d8ae3SPaolo Bonzini 
1850e47c4aeeSSean Christopherson 		child = to_shadow_page(ent & PT64_BASE_ADDR_MASK);
1851c50d8ae3SPaolo Bonzini 
1852c50d8ae3SPaolo Bonzini 		if (child->unsync_children) {
1853c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1854c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1855c50d8ae3SPaolo Bonzini 
1856c50d8ae3SPaolo Bonzini 			ret = __mmu_unsync_walk(child, pvec);
1857c50d8ae3SPaolo Bonzini 			if (!ret) {
1858c50d8ae3SPaolo Bonzini 				clear_unsync_child_bit(sp, i);
1859c50d8ae3SPaolo Bonzini 				continue;
1860c50d8ae3SPaolo Bonzini 			} else if (ret > 0) {
1861c50d8ae3SPaolo Bonzini 				nr_unsync_leaf += ret;
1862c50d8ae3SPaolo Bonzini 			} else
1863c50d8ae3SPaolo Bonzini 				return ret;
1864c50d8ae3SPaolo Bonzini 		} else if (child->unsync) {
1865c50d8ae3SPaolo Bonzini 			nr_unsync_leaf++;
1866c50d8ae3SPaolo Bonzini 			if (mmu_pages_add(pvec, child, i))
1867c50d8ae3SPaolo Bonzini 				return -ENOSPC;
1868c50d8ae3SPaolo Bonzini 		} else
1869c50d8ae3SPaolo Bonzini 			clear_unsync_child_bit(sp, i);
1870c50d8ae3SPaolo Bonzini 	}
1871c50d8ae3SPaolo Bonzini 
1872c50d8ae3SPaolo Bonzini 	return nr_unsync_leaf;
1873c50d8ae3SPaolo Bonzini }
1874c50d8ae3SPaolo Bonzini 
1875c50d8ae3SPaolo Bonzini #define INVALID_INDEX (-1)
1876c50d8ae3SPaolo Bonzini 
1877c50d8ae3SPaolo Bonzini static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1878c50d8ae3SPaolo Bonzini 			   struct kvm_mmu_pages *pvec)
1879c50d8ae3SPaolo Bonzini {
1880c50d8ae3SPaolo Bonzini 	pvec->nr = 0;
1881c50d8ae3SPaolo Bonzini 	if (!sp->unsync_children)
1882c50d8ae3SPaolo Bonzini 		return 0;
1883c50d8ae3SPaolo Bonzini 
1884c50d8ae3SPaolo Bonzini 	mmu_pages_add(pvec, sp, INVALID_INDEX);
1885c50d8ae3SPaolo Bonzini 	return __mmu_unsync_walk(sp, pvec);
1886c50d8ae3SPaolo Bonzini }
1887c50d8ae3SPaolo Bonzini 
1888c50d8ae3SPaolo Bonzini static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1889c50d8ae3SPaolo Bonzini {
1890c50d8ae3SPaolo Bonzini 	WARN_ON(!sp->unsync);
1891c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_sync_page(sp);
1892c50d8ae3SPaolo Bonzini 	sp->unsync = 0;
1893c50d8ae3SPaolo Bonzini 	--kvm->stat.mmu_unsync;
1894c50d8ae3SPaolo Bonzini }
1895c50d8ae3SPaolo Bonzini 
1896c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1897c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list);
1898c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1899c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list);
1900c50d8ae3SPaolo Bonzini 
1901ac101b7cSSean Christopherson #define for_each_valid_sp(_kvm, _sp, _list)				\
1902ac101b7cSSean Christopherson 	hlist_for_each_entry(_sp, _list, hash_link)			\
1903c50d8ae3SPaolo Bonzini 		if (is_obsolete_sp((_kvm), (_sp))) {			\
1904c50d8ae3SPaolo Bonzini 		} else
1905c50d8ae3SPaolo Bonzini 
1906c50d8ae3SPaolo Bonzini #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn)			\
1907ac101b7cSSean Christopherson 	for_each_valid_sp(_kvm, _sp,					\
1908ac101b7cSSean Christopherson 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
1909c50d8ae3SPaolo Bonzini 		if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
1910c50d8ae3SPaolo Bonzini 
1911479a1efcSSean Christopherson static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
1912c50d8ae3SPaolo Bonzini 			 struct list_head *invalid_list)
1913c50d8ae3SPaolo Bonzini {
19142640b086SSean Christopherson 	if (vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
1915c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
1916c50d8ae3SPaolo Bonzini 		return false;
1917c50d8ae3SPaolo Bonzini 	}
1918c50d8ae3SPaolo Bonzini 
1919c50d8ae3SPaolo Bonzini 	return true;
1920c50d8ae3SPaolo Bonzini }
1921c50d8ae3SPaolo Bonzini 
1922c50d8ae3SPaolo Bonzini static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
1923c50d8ae3SPaolo Bonzini 					struct list_head *invalid_list,
1924c50d8ae3SPaolo Bonzini 					bool remote_flush)
1925c50d8ae3SPaolo Bonzini {
1926c50d8ae3SPaolo Bonzini 	if (!remote_flush && list_empty(invalid_list))
1927c50d8ae3SPaolo Bonzini 		return false;
1928c50d8ae3SPaolo Bonzini 
1929c50d8ae3SPaolo Bonzini 	if (!list_empty(invalid_list))
1930c50d8ae3SPaolo Bonzini 		kvm_mmu_commit_zap_page(kvm, invalid_list);
1931c50d8ae3SPaolo Bonzini 	else
1932c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs(kvm);
1933c50d8ae3SPaolo Bonzini 	return true;
1934c50d8ae3SPaolo Bonzini }
1935c50d8ae3SPaolo Bonzini 
1936c50d8ae3SPaolo Bonzini static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
1937c50d8ae3SPaolo Bonzini 				 struct list_head *invalid_list,
1938c50d8ae3SPaolo Bonzini 				 bool remote_flush, bool local_flush)
1939c50d8ae3SPaolo Bonzini {
1940c50d8ae3SPaolo Bonzini 	if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
1941c50d8ae3SPaolo Bonzini 		return;
1942c50d8ae3SPaolo Bonzini 
1943c50d8ae3SPaolo Bonzini 	if (local_flush)
19448c8560b8SSean Christopherson 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
1945c50d8ae3SPaolo Bonzini }
1946c50d8ae3SPaolo Bonzini 
1947c50d8ae3SPaolo Bonzini #ifdef CONFIG_KVM_MMU_AUDIT
1948c50d8ae3SPaolo Bonzini #include "mmu_audit.c"
1949c50d8ae3SPaolo Bonzini #else
1950c50d8ae3SPaolo Bonzini static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
1951c50d8ae3SPaolo Bonzini static void mmu_audit_disable(void) { }
1952c50d8ae3SPaolo Bonzini #endif
1953c50d8ae3SPaolo Bonzini 
1954c50d8ae3SPaolo Bonzini static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
1955c50d8ae3SPaolo Bonzini {
1956c50d8ae3SPaolo Bonzini 	return sp->role.invalid ||
1957c50d8ae3SPaolo Bonzini 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
1958c50d8ae3SPaolo Bonzini }
1959c50d8ae3SPaolo Bonzini 
1960c50d8ae3SPaolo Bonzini struct mmu_page_path {
1961c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
1962c50d8ae3SPaolo Bonzini 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
1963c50d8ae3SPaolo Bonzini };
1964c50d8ae3SPaolo Bonzini 
1965c50d8ae3SPaolo Bonzini #define for_each_sp(pvec, sp, parents, i)			\
1966c50d8ae3SPaolo Bonzini 		for (i = mmu_pages_first(&pvec, &parents);	\
1967c50d8ae3SPaolo Bonzini 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
1968c50d8ae3SPaolo Bonzini 			i = mmu_pages_next(&pvec, &parents, i))
1969c50d8ae3SPaolo Bonzini 
1970c50d8ae3SPaolo Bonzini static int mmu_pages_next(struct kvm_mmu_pages *pvec,
1971c50d8ae3SPaolo Bonzini 			  struct mmu_page_path *parents,
1972c50d8ae3SPaolo Bonzini 			  int i)
1973c50d8ae3SPaolo Bonzini {
1974c50d8ae3SPaolo Bonzini 	int n;
1975c50d8ae3SPaolo Bonzini 
1976c50d8ae3SPaolo Bonzini 	for (n = i+1; n < pvec->nr; n++) {
1977c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp = pvec->page[n].sp;
1978c50d8ae3SPaolo Bonzini 		unsigned idx = pvec->page[n].idx;
1979c50d8ae3SPaolo Bonzini 		int level = sp->role.level;
1980c50d8ae3SPaolo Bonzini 
1981c50d8ae3SPaolo Bonzini 		parents->idx[level-1] = idx;
19823bae0459SSean Christopherson 		if (level == PG_LEVEL_4K)
1983c50d8ae3SPaolo Bonzini 			break;
1984c50d8ae3SPaolo Bonzini 
1985c50d8ae3SPaolo Bonzini 		parents->parent[level-2] = sp;
1986c50d8ae3SPaolo Bonzini 	}
1987c50d8ae3SPaolo Bonzini 
1988c50d8ae3SPaolo Bonzini 	return n;
1989c50d8ae3SPaolo Bonzini }
1990c50d8ae3SPaolo Bonzini 
1991c50d8ae3SPaolo Bonzini static int mmu_pages_first(struct kvm_mmu_pages *pvec,
1992c50d8ae3SPaolo Bonzini 			   struct mmu_page_path *parents)
1993c50d8ae3SPaolo Bonzini {
1994c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
1995c50d8ae3SPaolo Bonzini 	int level;
1996c50d8ae3SPaolo Bonzini 
1997c50d8ae3SPaolo Bonzini 	if (pvec->nr == 0)
1998c50d8ae3SPaolo Bonzini 		return 0;
1999c50d8ae3SPaolo Bonzini 
2000c50d8ae3SPaolo Bonzini 	WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2001c50d8ae3SPaolo Bonzini 
2002c50d8ae3SPaolo Bonzini 	sp = pvec->page[0].sp;
2003c50d8ae3SPaolo Bonzini 	level = sp->role.level;
20043bae0459SSean Christopherson 	WARN_ON(level == PG_LEVEL_4K);
2005c50d8ae3SPaolo Bonzini 
2006c50d8ae3SPaolo Bonzini 	parents->parent[level-2] = sp;
2007c50d8ae3SPaolo Bonzini 
2008c50d8ae3SPaolo Bonzini 	/* Also set up a sentinel.  Further entries in pvec are all
2009c50d8ae3SPaolo Bonzini 	 * children of sp, so this element is never overwritten.
2010c50d8ae3SPaolo Bonzini 	 */
2011c50d8ae3SPaolo Bonzini 	parents->parent[level-1] = NULL;
2012c50d8ae3SPaolo Bonzini 	return mmu_pages_next(pvec, parents, 0);
2013c50d8ae3SPaolo Bonzini }
2014c50d8ae3SPaolo Bonzini 
2015c50d8ae3SPaolo Bonzini static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2016c50d8ae3SPaolo Bonzini {
2017c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2018c50d8ae3SPaolo Bonzini 	unsigned int level = 0;
2019c50d8ae3SPaolo Bonzini 
2020c50d8ae3SPaolo Bonzini 	do {
2021c50d8ae3SPaolo Bonzini 		unsigned int idx = parents->idx[level];
2022c50d8ae3SPaolo Bonzini 		sp = parents->parent[level];
2023c50d8ae3SPaolo Bonzini 		if (!sp)
2024c50d8ae3SPaolo Bonzini 			return;
2025c50d8ae3SPaolo Bonzini 
2026c50d8ae3SPaolo Bonzini 		WARN_ON(idx == INVALID_INDEX);
2027c50d8ae3SPaolo Bonzini 		clear_unsync_child_bit(sp, idx);
2028c50d8ae3SPaolo Bonzini 		level++;
2029c50d8ae3SPaolo Bonzini 	} while (!sp->unsync_children);
2030c50d8ae3SPaolo Bonzini }
2031c50d8ae3SPaolo Bonzini 
2032c50d8ae3SPaolo Bonzini static void mmu_sync_children(struct kvm_vcpu *vcpu,
2033c50d8ae3SPaolo Bonzini 			      struct kvm_mmu_page *parent)
2034c50d8ae3SPaolo Bonzini {
2035c50d8ae3SPaolo Bonzini 	int i;
2036c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2037c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2038c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2039c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2040c50d8ae3SPaolo Bonzini 	bool flush = false;
2041c50d8ae3SPaolo Bonzini 
2042c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2043c50d8ae3SPaolo Bonzini 		bool protected = false;
2044c50d8ae3SPaolo Bonzini 
2045c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i)
2046c50d8ae3SPaolo Bonzini 			protected |= rmap_write_protect(vcpu, sp->gfn);
2047c50d8ae3SPaolo Bonzini 
2048c50d8ae3SPaolo Bonzini 		if (protected) {
2049c50d8ae3SPaolo Bonzini 			kvm_flush_remote_tlbs(vcpu->kvm);
2050c50d8ae3SPaolo Bonzini 			flush = false;
2051c50d8ae3SPaolo Bonzini 		}
2052c50d8ae3SPaolo Bonzini 
2053c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2054479a1efcSSean Christopherson 			kvm_unlink_unsync_page(vcpu->kvm, sp);
2055c50d8ae3SPaolo Bonzini 			flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2056c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2057c50d8ae3SPaolo Bonzini 		}
2058531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2059c50d8ae3SPaolo Bonzini 			kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2060531810caSBen Gardon 			cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2061c50d8ae3SPaolo Bonzini 			flush = false;
2062c50d8ae3SPaolo Bonzini 		}
2063c50d8ae3SPaolo Bonzini 	}
2064c50d8ae3SPaolo Bonzini 
2065c50d8ae3SPaolo Bonzini 	kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2066c50d8ae3SPaolo Bonzini }
2067c50d8ae3SPaolo Bonzini 
2068c50d8ae3SPaolo Bonzini static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2069c50d8ae3SPaolo Bonzini {
2070c50d8ae3SPaolo Bonzini 	atomic_set(&sp->write_flooding_count,  0);
2071c50d8ae3SPaolo Bonzini }
2072c50d8ae3SPaolo Bonzini 
2073c50d8ae3SPaolo Bonzini static void clear_sp_write_flooding_count(u64 *spte)
2074c50d8ae3SPaolo Bonzini {
207557354682SSean Christopherson 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
2076c50d8ae3SPaolo Bonzini }
2077c50d8ae3SPaolo Bonzini 
2078c50d8ae3SPaolo Bonzini static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2079c50d8ae3SPaolo Bonzini 					     gfn_t gfn,
2080c50d8ae3SPaolo Bonzini 					     gva_t gaddr,
2081c50d8ae3SPaolo Bonzini 					     unsigned level,
2082c50d8ae3SPaolo Bonzini 					     int direct,
20830a2b64c5SBen Gardon 					     unsigned int access)
2084c50d8ae3SPaolo Bonzini {
2085fb58a9c3SSean Christopherson 	bool direct_mmu = vcpu->arch.mmu->direct_map;
2086c50d8ae3SPaolo Bonzini 	union kvm_mmu_page_role role;
2087ac101b7cSSean Christopherson 	struct hlist_head *sp_list;
2088c50d8ae3SPaolo Bonzini 	unsigned quadrant;
2089c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2090c50d8ae3SPaolo Bonzini 	int collisions = 0;
2091c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2092c50d8ae3SPaolo Bonzini 
2093c50d8ae3SPaolo Bonzini 	role = vcpu->arch.mmu->mmu_role.base;
2094c50d8ae3SPaolo Bonzini 	role.level = level;
2095c50d8ae3SPaolo Bonzini 	role.direct = direct;
2096c50d8ae3SPaolo Bonzini 	if (role.direct)
2097c50d8ae3SPaolo Bonzini 		role.gpte_is_8_bytes = true;
2098c50d8ae3SPaolo Bonzini 	role.access = access;
2099fb58a9c3SSean Christopherson 	if (!direct_mmu && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2100c50d8ae3SPaolo Bonzini 		quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2101c50d8ae3SPaolo Bonzini 		quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2102c50d8ae3SPaolo Bonzini 		role.quadrant = quadrant;
2103c50d8ae3SPaolo Bonzini 	}
2104ac101b7cSSean Christopherson 
2105ac101b7cSSean Christopherson 	sp_list = &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2106ac101b7cSSean Christopherson 	for_each_valid_sp(vcpu->kvm, sp, sp_list) {
2107c50d8ae3SPaolo Bonzini 		if (sp->gfn != gfn) {
2108c50d8ae3SPaolo Bonzini 			collisions++;
2109c50d8ae3SPaolo Bonzini 			continue;
2110c50d8ae3SPaolo Bonzini 		}
2111c50d8ae3SPaolo Bonzini 
2112ddc16abbSSean Christopherson 		if (sp->role.word != role.word) {
2113ddc16abbSSean Christopherson 			/*
2114ddc16abbSSean Christopherson 			 * If the guest is creating an upper-level page, zap
2115ddc16abbSSean Christopherson 			 * unsync pages for the same gfn.  While it's possible
2116ddc16abbSSean Christopherson 			 * the guest is using recursive page tables, in all
2117ddc16abbSSean Christopherson 			 * likelihood the guest has stopped using the unsync
2118ddc16abbSSean Christopherson 			 * page and is installing a completely unrelated page.
2119ddc16abbSSean Christopherson 			 * Unsync pages must not be left as is, because the new
2120ddc16abbSSean Christopherson 			 * upper-level page will be write-protected.
2121ddc16abbSSean Christopherson 			 */
2122ddc16abbSSean Christopherson 			if (level > PG_LEVEL_4K && sp->unsync)
2123ddc16abbSSean Christopherson 				kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
2124ddc16abbSSean Christopherson 							 &invalid_list);
2125c50d8ae3SPaolo Bonzini 			continue;
2126ddc16abbSSean Christopherson 		}
2127c50d8ae3SPaolo Bonzini 
2128fb58a9c3SSean Christopherson 		if (direct_mmu)
2129fb58a9c3SSean Christopherson 			goto trace_get_page;
2130fb58a9c3SSean Christopherson 
2131c50d8ae3SPaolo Bonzini 		if (sp->unsync) {
213207dc4f35SSean Christopherson 			/*
2133479a1efcSSean Christopherson 			 * The page is good, but is stale.  kvm_sync_page does
213407dc4f35SSean Christopherson 			 * get the latest guest state, but (unlike mmu_unsync_children)
213507dc4f35SSean Christopherson 			 * it doesn't write-protect the page or mark it synchronized!
213607dc4f35SSean Christopherson 			 * This way the validity of the mapping is ensured, but the
213707dc4f35SSean Christopherson 			 * overhead of write protection is not incurred until the
213807dc4f35SSean Christopherson 			 * guest invalidates the TLB mapping.  This allows multiple
213907dc4f35SSean Christopherson 			 * SPs for a single gfn to be unsync.
214007dc4f35SSean Christopherson 			 *
214107dc4f35SSean Christopherson 			 * If the sync fails, the page is zapped.  If so, break
214207dc4f35SSean Christopherson 			 * in order to rebuild it.
2143c50d8ae3SPaolo Bonzini 			 */
2144479a1efcSSean Christopherson 			if (!kvm_sync_page(vcpu, sp, &invalid_list))
2145c50d8ae3SPaolo Bonzini 				break;
2146c50d8ae3SPaolo Bonzini 
2147c50d8ae3SPaolo Bonzini 			WARN_ON(!list_empty(&invalid_list));
21488c8560b8SSean Christopherson 			kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2149c50d8ae3SPaolo Bonzini 		}
2150c50d8ae3SPaolo Bonzini 
2151c50d8ae3SPaolo Bonzini 		if (sp->unsync_children)
2152f6f6195bSLai Jiangshan 			kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2153c50d8ae3SPaolo Bonzini 
2154c50d8ae3SPaolo Bonzini 		__clear_sp_write_flooding_count(sp);
2155fb58a9c3SSean Christopherson 
2156fb58a9c3SSean Christopherson trace_get_page:
2157c50d8ae3SPaolo Bonzini 		trace_kvm_mmu_get_page(sp, false);
2158c50d8ae3SPaolo Bonzini 		goto out;
2159c50d8ae3SPaolo Bonzini 	}
2160c50d8ae3SPaolo Bonzini 
2161c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_cache_miss;
2162c50d8ae3SPaolo Bonzini 
2163c50d8ae3SPaolo Bonzini 	sp = kvm_mmu_alloc_page(vcpu, direct);
2164c50d8ae3SPaolo Bonzini 
2165c50d8ae3SPaolo Bonzini 	sp->gfn = gfn;
2166c50d8ae3SPaolo Bonzini 	sp->role = role;
2167ac101b7cSSean Christopherson 	hlist_add_head(&sp->hash_link, sp_list);
2168c50d8ae3SPaolo Bonzini 	if (!direct) {
2169c50d8ae3SPaolo Bonzini 		account_shadowed(vcpu->kvm, sp);
21703bae0459SSean Christopherson 		if (level == PG_LEVEL_4K && rmap_write_protect(vcpu, gfn))
2171c50d8ae3SPaolo Bonzini 			kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2172c50d8ae3SPaolo Bonzini 	}
2173c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_get_page(sp, true);
2174c50d8ae3SPaolo Bonzini out:
2175ddc16abbSSean Christopherson 	kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
2176ddc16abbSSean Christopherson 
2177c50d8ae3SPaolo Bonzini 	if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2178c50d8ae3SPaolo Bonzini 		vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2179c50d8ae3SPaolo Bonzini 	return sp;
2180c50d8ae3SPaolo Bonzini }
2181c50d8ae3SPaolo Bonzini 
2182c50d8ae3SPaolo Bonzini static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2183c50d8ae3SPaolo Bonzini 					struct kvm_vcpu *vcpu, hpa_t root,
2184c50d8ae3SPaolo Bonzini 					u64 addr)
2185c50d8ae3SPaolo Bonzini {
2186c50d8ae3SPaolo Bonzini 	iterator->addr = addr;
2187c50d8ae3SPaolo Bonzini 	iterator->shadow_addr = root;
2188c50d8ae3SPaolo Bonzini 	iterator->level = vcpu->arch.mmu->shadow_root_level;
2189c50d8ae3SPaolo Bonzini 
2190c50d8ae3SPaolo Bonzini 	if (iterator->level == PT64_ROOT_4LEVEL &&
2191c50d8ae3SPaolo Bonzini 	    vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2192c50d8ae3SPaolo Bonzini 	    !vcpu->arch.mmu->direct_map)
2193c50d8ae3SPaolo Bonzini 		--iterator->level;
2194c50d8ae3SPaolo Bonzini 
2195c50d8ae3SPaolo Bonzini 	if (iterator->level == PT32E_ROOT_LEVEL) {
2196c50d8ae3SPaolo Bonzini 		/*
2197c50d8ae3SPaolo Bonzini 		 * prev_root is currently only used for 64-bit hosts. So only
2198c50d8ae3SPaolo Bonzini 		 * the active root_hpa is valid here.
2199c50d8ae3SPaolo Bonzini 		 */
2200c50d8ae3SPaolo Bonzini 		BUG_ON(root != vcpu->arch.mmu->root_hpa);
2201c50d8ae3SPaolo Bonzini 
2202c50d8ae3SPaolo Bonzini 		iterator->shadow_addr
2203c50d8ae3SPaolo Bonzini 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2204c50d8ae3SPaolo Bonzini 		iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2205c50d8ae3SPaolo Bonzini 		--iterator->level;
2206c50d8ae3SPaolo Bonzini 		if (!iterator->shadow_addr)
2207c50d8ae3SPaolo Bonzini 			iterator->level = 0;
2208c50d8ae3SPaolo Bonzini 	}
2209c50d8ae3SPaolo Bonzini }
2210c50d8ae3SPaolo Bonzini 
2211c50d8ae3SPaolo Bonzini static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2212c50d8ae3SPaolo Bonzini 			     struct kvm_vcpu *vcpu, u64 addr)
2213c50d8ae3SPaolo Bonzini {
2214c50d8ae3SPaolo Bonzini 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2215c50d8ae3SPaolo Bonzini 				    addr);
2216c50d8ae3SPaolo Bonzini }
2217c50d8ae3SPaolo Bonzini 
2218c50d8ae3SPaolo Bonzini static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2219c50d8ae3SPaolo Bonzini {
22203bae0459SSean Christopherson 	if (iterator->level < PG_LEVEL_4K)
2221c50d8ae3SPaolo Bonzini 		return false;
2222c50d8ae3SPaolo Bonzini 
2223c50d8ae3SPaolo Bonzini 	iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2224c50d8ae3SPaolo Bonzini 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2225c50d8ae3SPaolo Bonzini 	return true;
2226c50d8ae3SPaolo Bonzini }
2227c50d8ae3SPaolo Bonzini 
2228c50d8ae3SPaolo Bonzini static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2229c50d8ae3SPaolo Bonzini 			       u64 spte)
2230c50d8ae3SPaolo Bonzini {
2231c50d8ae3SPaolo Bonzini 	if (is_last_spte(spte, iterator->level)) {
2232c50d8ae3SPaolo Bonzini 		iterator->level = 0;
2233c50d8ae3SPaolo Bonzini 		return;
2234c50d8ae3SPaolo Bonzini 	}
2235c50d8ae3SPaolo Bonzini 
2236c50d8ae3SPaolo Bonzini 	iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2237c50d8ae3SPaolo Bonzini 	--iterator->level;
2238c50d8ae3SPaolo Bonzini }
2239c50d8ae3SPaolo Bonzini 
2240c50d8ae3SPaolo Bonzini static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2241c50d8ae3SPaolo Bonzini {
2242c50d8ae3SPaolo Bonzini 	__shadow_walk_next(iterator, *iterator->sptep);
2243c50d8ae3SPaolo Bonzini }
2244c50d8ae3SPaolo Bonzini 
2245c50d8ae3SPaolo Bonzini static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2246c50d8ae3SPaolo Bonzini 			     struct kvm_mmu_page *sp)
2247c50d8ae3SPaolo Bonzini {
2248c50d8ae3SPaolo Bonzini 	u64 spte;
2249c50d8ae3SPaolo Bonzini 
2250c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2251c50d8ae3SPaolo Bonzini 
2252cc4674d0SBen Gardon 	spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2253c50d8ae3SPaolo Bonzini 
2254c50d8ae3SPaolo Bonzini 	mmu_spte_set(sptep, spte);
2255c50d8ae3SPaolo Bonzini 
2256c50d8ae3SPaolo Bonzini 	mmu_page_add_parent_pte(vcpu, sp, sptep);
2257c50d8ae3SPaolo Bonzini 
2258c50d8ae3SPaolo Bonzini 	if (sp->unsync_children || sp->unsync)
2259c50d8ae3SPaolo Bonzini 		mark_unsync(sptep);
2260c50d8ae3SPaolo Bonzini }
2261c50d8ae3SPaolo Bonzini 
2262c50d8ae3SPaolo Bonzini static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2263c50d8ae3SPaolo Bonzini 				   unsigned direct_access)
2264c50d8ae3SPaolo Bonzini {
2265c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2266c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *child;
2267c50d8ae3SPaolo Bonzini 
2268c50d8ae3SPaolo Bonzini 		/*
2269c50d8ae3SPaolo Bonzini 		 * For the direct sp, if the guest pte's dirty bit
2270c50d8ae3SPaolo Bonzini 		 * changed form clean to dirty, it will corrupt the
2271c50d8ae3SPaolo Bonzini 		 * sp's access: allow writable in the read-only sp,
2272c50d8ae3SPaolo Bonzini 		 * so we should update the spte at this point to get
2273c50d8ae3SPaolo Bonzini 		 * a new sp with the correct access.
2274c50d8ae3SPaolo Bonzini 		 */
2275e47c4aeeSSean Christopherson 		child = to_shadow_page(*sptep & PT64_BASE_ADDR_MASK);
2276c50d8ae3SPaolo Bonzini 		if (child->role.access == direct_access)
2277c50d8ae3SPaolo Bonzini 			return;
2278c50d8ae3SPaolo Bonzini 
2279c50d8ae3SPaolo Bonzini 		drop_parent_pte(child, sptep);
2280c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2281c50d8ae3SPaolo Bonzini 	}
2282c50d8ae3SPaolo Bonzini }
2283c50d8ae3SPaolo Bonzini 
22842de4085cSBen Gardon /* Returns the number of zapped non-leaf child shadow pages. */
22852de4085cSBen Gardon static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
22862de4085cSBen Gardon 			    u64 *spte, struct list_head *invalid_list)
2287c50d8ae3SPaolo Bonzini {
2288c50d8ae3SPaolo Bonzini 	u64 pte;
2289c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *child;
2290c50d8ae3SPaolo Bonzini 
2291c50d8ae3SPaolo Bonzini 	pte = *spte;
2292c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(pte)) {
2293c50d8ae3SPaolo Bonzini 		if (is_last_spte(pte, sp->role.level)) {
2294c50d8ae3SPaolo Bonzini 			drop_spte(kvm, spte);
2295c50d8ae3SPaolo Bonzini 			if (is_large_pte(pte))
2296c50d8ae3SPaolo Bonzini 				--kvm->stat.lpages;
2297c50d8ae3SPaolo Bonzini 		} else {
2298e47c4aeeSSean Christopherson 			child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
2299c50d8ae3SPaolo Bonzini 			drop_parent_pte(child, spte);
23002de4085cSBen Gardon 
23012de4085cSBen Gardon 			/*
23022de4085cSBen Gardon 			 * Recursively zap nested TDP SPs, parentless SPs are
23032de4085cSBen Gardon 			 * unlikely to be used again in the near future.  This
23042de4085cSBen Gardon 			 * avoids retaining a large number of stale nested SPs.
23052de4085cSBen Gardon 			 */
23062de4085cSBen Gardon 			if (tdp_enabled && invalid_list &&
23072de4085cSBen Gardon 			    child->role.guest_mode && !child->parent_ptes.val)
23082de4085cSBen Gardon 				return kvm_mmu_prepare_zap_page(kvm, child,
23092de4085cSBen Gardon 								invalid_list);
2310c50d8ae3SPaolo Bonzini 		}
2311ace569e0SSean Christopherson 	} else if (is_mmio_spte(pte)) {
2312c50d8ae3SPaolo Bonzini 		mmu_spte_clear_no_track(spte);
2313ace569e0SSean Christopherson 	}
23142de4085cSBen Gardon 	return 0;
2315c50d8ae3SPaolo Bonzini }
2316c50d8ae3SPaolo Bonzini 
23172de4085cSBen Gardon static int kvm_mmu_page_unlink_children(struct kvm *kvm,
23182de4085cSBen Gardon 					struct kvm_mmu_page *sp,
23192de4085cSBen Gardon 					struct list_head *invalid_list)
2320c50d8ae3SPaolo Bonzini {
23212de4085cSBen Gardon 	int zapped = 0;
2322c50d8ae3SPaolo Bonzini 	unsigned i;
2323c50d8ae3SPaolo Bonzini 
2324c50d8ae3SPaolo Bonzini 	for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
23252de4085cSBen Gardon 		zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
23262de4085cSBen Gardon 
23272de4085cSBen Gardon 	return zapped;
2328c50d8ae3SPaolo Bonzini }
2329c50d8ae3SPaolo Bonzini 
2330c50d8ae3SPaolo Bonzini static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2331c50d8ae3SPaolo Bonzini {
2332c50d8ae3SPaolo Bonzini 	u64 *sptep;
2333c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
2334c50d8ae3SPaolo Bonzini 
2335c50d8ae3SPaolo Bonzini 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2336c50d8ae3SPaolo Bonzini 		drop_parent_pte(sp, sptep);
2337c50d8ae3SPaolo Bonzini }
2338c50d8ae3SPaolo Bonzini 
2339c50d8ae3SPaolo Bonzini static int mmu_zap_unsync_children(struct kvm *kvm,
2340c50d8ae3SPaolo Bonzini 				   struct kvm_mmu_page *parent,
2341c50d8ae3SPaolo Bonzini 				   struct list_head *invalid_list)
2342c50d8ae3SPaolo Bonzini {
2343c50d8ae3SPaolo Bonzini 	int i, zapped = 0;
2344c50d8ae3SPaolo Bonzini 	struct mmu_page_path parents;
2345c50d8ae3SPaolo Bonzini 	struct kvm_mmu_pages pages;
2346c50d8ae3SPaolo Bonzini 
23473bae0459SSean Christopherson 	if (parent->role.level == PG_LEVEL_4K)
2348c50d8ae3SPaolo Bonzini 		return 0;
2349c50d8ae3SPaolo Bonzini 
2350c50d8ae3SPaolo Bonzini 	while (mmu_unsync_walk(parent, &pages)) {
2351c50d8ae3SPaolo Bonzini 		struct kvm_mmu_page *sp;
2352c50d8ae3SPaolo Bonzini 
2353c50d8ae3SPaolo Bonzini 		for_each_sp(pages, sp, parents, i) {
2354c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2355c50d8ae3SPaolo Bonzini 			mmu_pages_clear_parents(&parents);
2356c50d8ae3SPaolo Bonzini 			zapped++;
2357c50d8ae3SPaolo Bonzini 		}
2358c50d8ae3SPaolo Bonzini 	}
2359c50d8ae3SPaolo Bonzini 
2360c50d8ae3SPaolo Bonzini 	return zapped;
2361c50d8ae3SPaolo Bonzini }
2362c50d8ae3SPaolo Bonzini 
2363c50d8ae3SPaolo Bonzini static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2364c50d8ae3SPaolo Bonzini 				       struct kvm_mmu_page *sp,
2365c50d8ae3SPaolo Bonzini 				       struct list_head *invalid_list,
2366c50d8ae3SPaolo Bonzini 				       int *nr_zapped)
2367c50d8ae3SPaolo Bonzini {
2368c50d8ae3SPaolo Bonzini 	bool list_unstable;
2369c50d8ae3SPaolo Bonzini 
2370c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_prepare_zap_page(sp);
2371c50d8ae3SPaolo Bonzini 	++kvm->stat.mmu_shadow_zapped;
2372c50d8ae3SPaolo Bonzini 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
23732de4085cSBen Gardon 	*nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2374c50d8ae3SPaolo Bonzini 	kvm_mmu_unlink_parents(kvm, sp);
2375c50d8ae3SPaolo Bonzini 
2376c50d8ae3SPaolo Bonzini 	/* Zapping children means active_mmu_pages has become unstable. */
2377c50d8ae3SPaolo Bonzini 	list_unstable = *nr_zapped;
2378c50d8ae3SPaolo Bonzini 
2379c50d8ae3SPaolo Bonzini 	if (!sp->role.invalid && !sp->role.direct)
2380c50d8ae3SPaolo Bonzini 		unaccount_shadowed(kvm, sp);
2381c50d8ae3SPaolo Bonzini 
2382c50d8ae3SPaolo Bonzini 	if (sp->unsync)
2383c50d8ae3SPaolo Bonzini 		kvm_unlink_unsync_page(kvm, sp);
2384c50d8ae3SPaolo Bonzini 	if (!sp->root_count) {
2385c50d8ae3SPaolo Bonzini 		/* Count self */
2386c50d8ae3SPaolo Bonzini 		(*nr_zapped)++;
2387f95eec9bSSean Christopherson 
2388f95eec9bSSean Christopherson 		/*
2389f95eec9bSSean Christopherson 		 * Already invalid pages (previously active roots) are not on
2390f95eec9bSSean Christopherson 		 * the active page list.  See list_del() in the "else" case of
2391f95eec9bSSean Christopherson 		 * !sp->root_count.
2392f95eec9bSSean Christopherson 		 */
2393f95eec9bSSean Christopherson 		if (sp->role.invalid)
2394f95eec9bSSean Christopherson 			list_add(&sp->link, invalid_list);
2395f95eec9bSSean Christopherson 		else
2396c50d8ae3SPaolo Bonzini 			list_move(&sp->link, invalid_list);
2397c50d8ae3SPaolo Bonzini 		kvm_mod_used_mmu_pages(kvm, -1);
2398c50d8ae3SPaolo Bonzini 	} else {
2399f95eec9bSSean Christopherson 		/*
2400f95eec9bSSean Christopherson 		 * Remove the active root from the active page list, the root
2401f95eec9bSSean Christopherson 		 * will be explicitly freed when the root_count hits zero.
2402f95eec9bSSean Christopherson 		 */
2403f95eec9bSSean Christopherson 		list_del(&sp->link);
2404c50d8ae3SPaolo Bonzini 
2405c50d8ae3SPaolo Bonzini 		/*
2406c50d8ae3SPaolo Bonzini 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2407c50d8ae3SPaolo Bonzini 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2408c50d8ae3SPaolo Bonzini 		 * treats invalid shadow pages as being obsolete.
2409c50d8ae3SPaolo Bonzini 		 */
2410c50d8ae3SPaolo Bonzini 		if (!is_obsolete_sp(kvm, sp))
2411c50d8ae3SPaolo Bonzini 			kvm_reload_remote_mmus(kvm);
2412c50d8ae3SPaolo Bonzini 	}
2413c50d8ae3SPaolo Bonzini 
2414c50d8ae3SPaolo Bonzini 	if (sp->lpage_disallowed)
2415c50d8ae3SPaolo Bonzini 		unaccount_huge_nx_page(kvm, sp);
2416c50d8ae3SPaolo Bonzini 
2417c50d8ae3SPaolo Bonzini 	sp->role.invalid = 1;
2418c50d8ae3SPaolo Bonzini 	return list_unstable;
2419c50d8ae3SPaolo Bonzini }
2420c50d8ae3SPaolo Bonzini 
2421c50d8ae3SPaolo Bonzini static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2422c50d8ae3SPaolo Bonzini 				     struct list_head *invalid_list)
2423c50d8ae3SPaolo Bonzini {
2424c50d8ae3SPaolo Bonzini 	int nr_zapped;
2425c50d8ae3SPaolo Bonzini 
2426c50d8ae3SPaolo Bonzini 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2427c50d8ae3SPaolo Bonzini 	return nr_zapped;
2428c50d8ae3SPaolo Bonzini }
2429c50d8ae3SPaolo Bonzini 
2430c50d8ae3SPaolo Bonzini static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2431c50d8ae3SPaolo Bonzini 				    struct list_head *invalid_list)
2432c50d8ae3SPaolo Bonzini {
2433c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *nsp;
2434c50d8ae3SPaolo Bonzini 
2435c50d8ae3SPaolo Bonzini 	if (list_empty(invalid_list))
2436c50d8ae3SPaolo Bonzini 		return;
2437c50d8ae3SPaolo Bonzini 
2438c50d8ae3SPaolo Bonzini 	/*
2439c50d8ae3SPaolo Bonzini 	 * We need to make sure everyone sees our modifications to
2440c50d8ae3SPaolo Bonzini 	 * the page tables and see changes to vcpu->mode here. The barrier
2441c50d8ae3SPaolo Bonzini 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2442c50d8ae3SPaolo Bonzini 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2443c50d8ae3SPaolo Bonzini 	 *
2444c50d8ae3SPaolo Bonzini 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2445c50d8ae3SPaolo Bonzini 	 * guest mode and/or lockless shadow page table walks.
2446c50d8ae3SPaolo Bonzini 	 */
2447c50d8ae3SPaolo Bonzini 	kvm_flush_remote_tlbs(kvm);
2448c50d8ae3SPaolo Bonzini 
2449c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2450c50d8ae3SPaolo Bonzini 		WARN_ON(!sp->role.invalid || sp->root_count);
2451c50d8ae3SPaolo Bonzini 		kvm_mmu_free_page(sp);
2452c50d8ae3SPaolo Bonzini 	}
2453c50d8ae3SPaolo Bonzini }
2454c50d8ae3SPaolo Bonzini 
24556b82ef2cSSean Christopherson static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
24566b82ef2cSSean Christopherson 						  unsigned long nr_to_zap)
2457c50d8ae3SPaolo Bonzini {
24586b82ef2cSSean Christopherson 	unsigned long total_zapped = 0;
24596b82ef2cSSean Christopherson 	struct kvm_mmu_page *sp, *tmp;
2460ba7888ddSSean Christopherson 	LIST_HEAD(invalid_list);
24616b82ef2cSSean Christopherson 	bool unstable;
24626b82ef2cSSean Christopherson 	int nr_zapped;
2463c50d8ae3SPaolo Bonzini 
2464c50d8ae3SPaolo Bonzini 	if (list_empty(&kvm->arch.active_mmu_pages))
2465ba7888ddSSean Christopherson 		return 0;
2466c50d8ae3SPaolo Bonzini 
24676b82ef2cSSean Christopherson restart:
24688fc51726SSean Christopherson 	list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
24696b82ef2cSSean Christopherson 		/*
24706b82ef2cSSean Christopherson 		 * Don't zap active root pages, the page itself can't be freed
24716b82ef2cSSean Christopherson 		 * and zapping it will just force vCPUs to realloc and reload.
24726b82ef2cSSean Christopherson 		 */
24736b82ef2cSSean Christopherson 		if (sp->root_count)
24746b82ef2cSSean Christopherson 			continue;
24756b82ef2cSSean Christopherson 
24766b82ef2cSSean Christopherson 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
24776b82ef2cSSean Christopherson 						      &nr_zapped);
24786b82ef2cSSean Christopherson 		total_zapped += nr_zapped;
24796b82ef2cSSean Christopherson 		if (total_zapped >= nr_to_zap)
2480ba7888ddSSean Christopherson 			break;
2481ba7888ddSSean Christopherson 
24826b82ef2cSSean Christopherson 		if (unstable)
24836b82ef2cSSean Christopherson 			goto restart;
2484ba7888ddSSean Christopherson 	}
24856b82ef2cSSean Christopherson 
24866b82ef2cSSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
24876b82ef2cSSean Christopherson 
24886b82ef2cSSean Christopherson 	kvm->stat.mmu_recycled += total_zapped;
24896b82ef2cSSean Christopherson 	return total_zapped;
24906b82ef2cSSean Christopherson }
24916b82ef2cSSean Christopherson 
2492afe8d7e6SSean Christopherson static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2493afe8d7e6SSean Christopherson {
2494afe8d7e6SSean Christopherson 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2495afe8d7e6SSean Christopherson 		return kvm->arch.n_max_mmu_pages -
2496afe8d7e6SSean Christopherson 			kvm->arch.n_used_mmu_pages;
2497afe8d7e6SSean Christopherson 
2498afe8d7e6SSean Christopherson 	return 0;
2499c50d8ae3SPaolo Bonzini }
2500c50d8ae3SPaolo Bonzini 
2501ba7888ddSSean Christopherson static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2502ba7888ddSSean Christopherson {
25036b82ef2cSSean Christopherson 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2504ba7888ddSSean Christopherson 
25056b82ef2cSSean Christopherson 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2506ba7888ddSSean Christopherson 		return 0;
2507ba7888ddSSean Christopherson 
25086b82ef2cSSean Christopherson 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2509ba7888ddSSean Christopherson 
25106e6ec584SSean Christopherson 	/*
25116e6ec584SSean Christopherson 	 * Note, this check is intentionally soft, it only guarantees that one
25126e6ec584SSean Christopherson 	 * page is available, while the caller may end up allocating as many as
25136e6ec584SSean Christopherson 	 * four pages, e.g. for PAE roots or for 5-level paging.  Temporarily
25146e6ec584SSean Christopherson 	 * exceeding the (arbitrary by default) limit will not harm the host,
2515c4342633SIngo Molnar 	 * being too aggressive may unnecessarily kill the guest, and getting an
25166e6ec584SSean Christopherson 	 * exact count is far more trouble than it's worth, especially in the
25176e6ec584SSean Christopherson 	 * page fault paths.
25186e6ec584SSean Christopherson 	 */
2519ba7888ddSSean Christopherson 	if (!kvm_mmu_available_pages(vcpu->kvm))
2520ba7888ddSSean Christopherson 		return -ENOSPC;
2521ba7888ddSSean Christopherson 	return 0;
2522ba7888ddSSean Christopherson }
2523ba7888ddSSean Christopherson 
2524c50d8ae3SPaolo Bonzini /*
2525c50d8ae3SPaolo Bonzini  * Changing the number of mmu pages allocated to the vm
2526c50d8ae3SPaolo Bonzini  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2527c50d8ae3SPaolo Bonzini  */
2528c50d8ae3SPaolo Bonzini void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2529c50d8ae3SPaolo Bonzini {
2530531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2531c50d8ae3SPaolo Bonzini 
2532c50d8ae3SPaolo Bonzini 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
25336b82ef2cSSean Christopherson 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
25346b82ef2cSSean Christopherson 						  goal_nr_mmu_pages);
2535c50d8ae3SPaolo Bonzini 
2536c50d8ae3SPaolo Bonzini 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2537c50d8ae3SPaolo Bonzini 	}
2538c50d8ae3SPaolo Bonzini 
2539c50d8ae3SPaolo Bonzini 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2540c50d8ae3SPaolo Bonzini 
2541531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2542c50d8ae3SPaolo Bonzini }
2543c50d8ae3SPaolo Bonzini 
2544c50d8ae3SPaolo Bonzini int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2545c50d8ae3SPaolo Bonzini {
2546c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2547c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
2548c50d8ae3SPaolo Bonzini 	int r;
2549c50d8ae3SPaolo Bonzini 
2550c50d8ae3SPaolo Bonzini 	pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2551c50d8ae3SPaolo Bonzini 	r = 0;
2552531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
2553c50d8ae3SPaolo Bonzini 	for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2554c50d8ae3SPaolo Bonzini 		pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2555c50d8ae3SPaolo Bonzini 			 sp->role.word);
2556c50d8ae3SPaolo Bonzini 		r = 1;
2557c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2558c50d8ae3SPaolo Bonzini 	}
2559c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2560531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
2561c50d8ae3SPaolo Bonzini 
2562c50d8ae3SPaolo Bonzini 	return r;
2563c50d8ae3SPaolo Bonzini }
256496ad91aeSSean Christopherson 
256596ad91aeSSean Christopherson static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
256696ad91aeSSean Christopherson {
256796ad91aeSSean Christopherson 	gpa_t gpa;
256896ad91aeSSean Christopherson 	int r;
256996ad91aeSSean Christopherson 
257096ad91aeSSean Christopherson 	if (vcpu->arch.mmu->direct_map)
257196ad91aeSSean Christopherson 		return 0;
257296ad91aeSSean Christopherson 
257396ad91aeSSean Christopherson 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
257496ad91aeSSean Christopherson 
257596ad91aeSSean Christopherson 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
257696ad91aeSSean Christopherson 
257796ad91aeSSean Christopherson 	return r;
257896ad91aeSSean Christopherson }
2579c50d8ae3SPaolo Bonzini 
2580c50d8ae3SPaolo Bonzini static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2581c50d8ae3SPaolo Bonzini {
2582c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_unsync_page(sp);
2583c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_unsync;
2584c50d8ae3SPaolo Bonzini 	sp->unsync = 1;
2585c50d8ae3SPaolo Bonzini 
2586c50d8ae3SPaolo Bonzini 	kvm_mmu_mark_parents_unsync(sp);
2587c50d8ae3SPaolo Bonzini }
2588c50d8ae3SPaolo Bonzini 
25890337f585SSean Christopherson /*
25900337f585SSean Christopherson  * Attempt to unsync any shadow pages that can be reached by the specified gfn,
25910337f585SSean Christopherson  * KVM is creating a writable mapping for said gfn.  Returns 0 if all pages
25920337f585SSean Christopherson  * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
25930337f585SSean Christopherson  * be write-protected.
25940337f585SSean Christopherson  */
25950337f585SSean Christopherson int mmu_try_to_unsync_pages(struct kvm_vcpu *vcpu, gfn_t gfn, bool can_unsync)
2596c50d8ae3SPaolo Bonzini {
2597c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2598ce25681dSSean Christopherson 	bool locked = false;
2599c50d8ae3SPaolo Bonzini 
26000337f585SSean Christopherson 	/*
26010337f585SSean Christopherson 	 * Force write-protection if the page is being tracked.  Note, the page
26020337f585SSean Christopherson 	 * track machinery is used to write-protect upper-level shadow pages,
26030337f585SSean Christopherson 	 * i.e. this guards the role.level == 4K assertion below!
26040337f585SSean Christopherson 	 */
2605c50d8ae3SPaolo Bonzini 	if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
26060337f585SSean Christopherson 		return -EPERM;
2607c50d8ae3SPaolo Bonzini 
26080337f585SSean Christopherson 	/*
26090337f585SSean Christopherson 	 * The page is not write-tracked, mark existing shadow pages unsync
26100337f585SSean Christopherson 	 * unless KVM is synchronizing an unsync SP (can_unsync = false).  In
26110337f585SSean Christopherson 	 * that case, KVM must complete emulation of the guest TLB flush before
26120337f585SSean Christopherson 	 * allowing shadow pages to become unsync (writable by the guest).
26130337f585SSean Christopherson 	 */
2614c50d8ae3SPaolo Bonzini 	for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2615c50d8ae3SPaolo Bonzini 		if (!can_unsync)
26160337f585SSean Christopherson 			return -EPERM;
2617c50d8ae3SPaolo Bonzini 
2618c50d8ae3SPaolo Bonzini 		if (sp->unsync)
2619c50d8ae3SPaolo Bonzini 			continue;
2620c50d8ae3SPaolo Bonzini 
2621ce25681dSSean Christopherson 		/*
2622ce25681dSSean Christopherson 		 * TDP MMU page faults require an additional spinlock as they
2623ce25681dSSean Christopherson 		 * run with mmu_lock held for read, not write, and the unsync
2624ce25681dSSean Christopherson 		 * logic is not thread safe.  Take the spinklock regardless of
2625ce25681dSSean Christopherson 		 * the MMU type to avoid extra conditionals/parameters, there's
2626ce25681dSSean Christopherson 		 * no meaningful penalty if mmu_lock is held for write.
2627ce25681dSSean Christopherson 		 */
2628ce25681dSSean Christopherson 		if (!locked) {
2629ce25681dSSean Christopherson 			locked = true;
2630ce25681dSSean Christopherson 			spin_lock(&vcpu->kvm->arch.mmu_unsync_pages_lock);
2631ce25681dSSean Christopherson 
2632ce25681dSSean Christopherson 			/*
2633ce25681dSSean Christopherson 			 * Recheck after taking the spinlock, a different vCPU
2634ce25681dSSean Christopherson 			 * may have since marked the page unsync.  A false
2635ce25681dSSean Christopherson 			 * positive on the unprotected check above is not
2636ce25681dSSean Christopherson 			 * possible as clearing sp->unsync _must_ hold mmu_lock
2637ce25681dSSean Christopherson 			 * for write, i.e. unsync cannot transition from 0->1
2638ce25681dSSean Christopherson 			 * while this CPU holds mmu_lock for read (or write).
2639ce25681dSSean Christopherson 			 */
2640ce25681dSSean Christopherson 			if (READ_ONCE(sp->unsync))
2641ce25681dSSean Christopherson 				continue;
2642ce25681dSSean Christopherson 		}
2643ce25681dSSean Christopherson 
26443bae0459SSean Christopherson 		WARN_ON(sp->role.level != PG_LEVEL_4K);
2645c50d8ae3SPaolo Bonzini 		kvm_unsync_page(vcpu, sp);
2646c50d8ae3SPaolo Bonzini 	}
2647ce25681dSSean Christopherson 	if (locked)
2648ce25681dSSean Christopherson 		spin_unlock(&vcpu->kvm->arch.mmu_unsync_pages_lock);
2649c50d8ae3SPaolo Bonzini 
2650c50d8ae3SPaolo Bonzini 	/*
2651c50d8ae3SPaolo Bonzini 	 * We need to ensure that the marking of unsync pages is visible
2652c50d8ae3SPaolo Bonzini 	 * before the SPTE is updated to allow writes because
2653c50d8ae3SPaolo Bonzini 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2654c50d8ae3SPaolo Bonzini 	 * the MMU lock and so can race with this. If the SPTE was updated
2655c50d8ae3SPaolo Bonzini 	 * before the page had been marked as unsync-ed, something like the
2656c50d8ae3SPaolo Bonzini 	 * following could happen:
2657c50d8ae3SPaolo Bonzini 	 *
2658c50d8ae3SPaolo Bonzini 	 * CPU 1                    CPU 2
2659c50d8ae3SPaolo Bonzini 	 * ---------------------------------------------------------------------
2660c50d8ae3SPaolo Bonzini 	 * 1.2 Host updates SPTE
2661c50d8ae3SPaolo Bonzini 	 *     to be writable
2662c50d8ae3SPaolo Bonzini 	 *                      2.1 Guest writes a GPTE for GVA X.
2663c50d8ae3SPaolo Bonzini 	 *                          (GPTE being in the guest page table shadowed
2664c50d8ae3SPaolo Bonzini 	 *                           by the SP from CPU 1.)
2665c50d8ae3SPaolo Bonzini 	 *                          This reads SPTE during the page table walk.
2666c50d8ae3SPaolo Bonzini 	 *                          Since SPTE.W is read as 1, there is no
2667c50d8ae3SPaolo Bonzini 	 *                          fault.
2668c50d8ae3SPaolo Bonzini 	 *
2669c50d8ae3SPaolo Bonzini 	 *                      2.2 Guest issues TLB flush.
2670c50d8ae3SPaolo Bonzini 	 *                          That causes a VM Exit.
2671c50d8ae3SPaolo Bonzini 	 *
26720337f585SSean Christopherson 	 *                      2.3 Walking of unsync pages sees sp->unsync is
26730337f585SSean Christopherson 	 *                          false and skips the page.
2674c50d8ae3SPaolo Bonzini 	 *
2675c50d8ae3SPaolo Bonzini 	 *                      2.4 Guest accesses GVA X.
2676c50d8ae3SPaolo Bonzini 	 *                          Since the mapping in the SP was not updated,
2677c50d8ae3SPaolo Bonzini 	 *                          so the old mapping for GVA X incorrectly
2678c50d8ae3SPaolo Bonzini 	 *                          gets used.
2679c50d8ae3SPaolo Bonzini 	 * 1.1 Host marks SP
2680c50d8ae3SPaolo Bonzini 	 *     as unsync
2681c50d8ae3SPaolo Bonzini 	 *     (sp->unsync = true)
2682c50d8ae3SPaolo Bonzini 	 *
2683c50d8ae3SPaolo Bonzini 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2684c50d8ae3SPaolo Bonzini 	 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2685c50d8ae3SPaolo Bonzini 	 * pairs with this write barrier.
2686c50d8ae3SPaolo Bonzini 	 */
2687c50d8ae3SPaolo Bonzini 	smp_wmb();
2688c50d8ae3SPaolo Bonzini 
26890337f585SSean Christopherson 	return 0;
2690c50d8ae3SPaolo Bonzini }
2691c50d8ae3SPaolo Bonzini 
2692799a4190SBen Gardon static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2693799a4190SBen Gardon 		    unsigned int pte_access, int level,
2694799a4190SBen Gardon 		    gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2695799a4190SBen Gardon 		    bool can_unsync, bool host_writable)
2696799a4190SBen Gardon {
2697799a4190SBen Gardon 	u64 spte;
2698799a4190SBen Gardon 	struct kvm_mmu_page *sp;
2699799a4190SBen Gardon 	int ret;
2700799a4190SBen Gardon 
2701799a4190SBen Gardon 	sp = sptep_to_sp(sptep);
2702799a4190SBen Gardon 
2703799a4190SBen Gardon 	ret = make_spte(vcpu, pte_access, level, gfn, pfn, *sptep, speculative,
2704799a4190SBen Gardon 			can_unsync, host_writable, sp_ad_disabled(sp), &spte);
2705799a4190SBen Gardon 
2706799a4190SBen Gardon 	if (spte & PT_WRITABLE_MASK)
2707799a4190SBen Gardon 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
2708799a4190SBen Gardon 
270912703759SSean Christopherson 	if (*sptep == spte)
271012703759SSean Christopherson 		ret |= SET_SPTE_SPURIOUS;
271112703759SSean Christopherson 	else if (mmu_spte_update(sptep, spte))
2712c50d8ae3SPaolo Bonzini 		ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
2713c50d8ae3SPaolo Bonzini 	return ret;
2714c50d8ae3SPaolo Bonzini }
2715c50d8ae3SPaolo Bonzini 
27160a2b64c5SBen Gardon static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2717e88b8093SSean Christopherson 			unsigned int pte_access, bool write_fault, int level,
27180a2b64c5SBen Gardon 			gfn_t gfn, kvm_pfn_t pfn, bool speculative,
27190a2b64c5SBen Gardon 			bool host_writable)
2720c50d8ae3SPaolo Bonzini {
2721c50d8ae3SPaolo Bonzini 	int was_rmapped = 0;
2722c50d8ae3SPaolo Bonzini 	int rmap_count;
2723c50d8ae3SPaolo Bonzini 	int set_spte_ret;
2724c4371c2aSSean Christopherson 	int ret = RET_PF_FIXED;
2725c50d8ae3SPaolo Bonzini 	bool flush = false;
2726c50d8ae3SPaolo Bonzini 
2727c50d8ae3SPaolo Bonzini 	pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2728c50d8ae3SPaolo Bonzini 		 *sptep, write_fault, gfn);
2729c50d8ae3SPaolo Bonzini 
2730a54aa15cSSean Christopherson 	if (unlikely(is_noslot_pfn(pfn))) {
2731a54aa15cSSean Christopherson 		mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2732a54aa15cSSean Christopherson 		return RET_PF_EMULATE;
2733a54aa15cSSean Christopherson 	}
2734a54aa15cSSean Christopherson 
2735c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep)) {
2736c50d8ae3SPaolo Bonzini 		/*
2737c50d8ae3SPaolo Bonzini 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2738c50d8ae3SPaolo Bonzini 		 * the parent of the now unreachable PTE.
2739c50d8ae3SPaolo Bonzini 		 */
27403bae0459SSean Christopherson 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2741c50d8ae3SPaolo Bonzini 			struct kvm_mmu_page *child;
2742c50d8ae3SPaolo Bonzini 			u64 pte = *sptep;
2743c50d8ae3SPaolo Bonzini 
2744e47c4aeeSSean Christopherson 			child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
2745c50d8ae3SPaolo Bonzini 			drop_parent_pte(child, sptep);
2746c50d8ae3SPaolo Bonzini 			flush = true;
2747c50d8ae3SPaolo Bonzini 		} else if (pfn != spte_to_pfn(*sptep)) {
2748c50d8ae3SPaolo Bonzini 			pgprintk("hfn old %llx new %llx\n",
2749c50d8ae3SPaolo Bonzini 				 spte_to_pfn(*sptep), pfn);
2750c50d8ae3SPaolo Bonzini 			drop_spte(vcpu->kvm, sptep);
2751c50d8ae3SPaolo Bonzini 			flush = true;
2752c50d8ae3SPaolo Bonzini 		} else
2753c50d8ae3SPaolo Bonzini 			was_rmapped = 1;
2754c50d8ae3SPaolo Bonzini 	}
2755c50d8ae3SPaolo Bonzini 
2756c50d8ae3SPaolo Bonzini 	set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
2757c50d8ae3SPaolo Bonzini 				speculative, true, host_writable);
2758c50d8ae3SPaolo Bonzini 	if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
2759c50d8ae3SPaolo Bonzini 		if (write_fault)
2760c50d8ae3SPaolo Bonzini 			ret = RET_PF_EMULATE;
27618c8560b8SSean Christopherson 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2762c50d8ae3SPaolo Bonzini 	}
2763c50d8ae3SPaolo Bonzini 
2764c50d8ae3SPaolo Bonzini 	if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
2765c50d8ae3SPaolo Bonzini 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
2766c50d8ae3SPaolo Bonzini 				KVM_PAGES_PER_HPAGE(level));
2767c50d8ae3SPaolo Bonzini 
276812703759SSean Christopherson 	/*
276912703759SSean Christopherson 	 * The fault is fully spurious if and only if the new SPTE and old SPTE
277012703759SSean Christopherson 	 * are identical, and emulation is not required.
277112703759SSean Christopherson 	 */
277212703759SSean Christopherson 	if ((set_spte_ret & SET_SPTE_SPURIOUS) && ret == RET_PF_FIXED) {
277312703759SSean Christopherson 		WARN_ON_ONCE(!was_rmapped);
277412703759SSean Christopherson 		return RET_PF_SPURIOUS;
277512703759SSean Christopherson 	}
277612703759SSean Christopherson 
2777c50d8ae3SPaolo Bonzini 	pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2778c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_set_spte(level, gfn, sptep);
2779c50d8ae3SPaolo Bonzini 	if (!was_rmapped && is_large_pte(*sptep))
2780c50d8ae3SPaolo Bonzini 		++vcpu->kvm->stat.lpages;
2781c50d8ae3SPaolo Bonzini 
2782c50d8ae3SPaolo Bonzini 	if (is_shadow_present_pte(*sptep)) {
2783c50d8ae3SPaolo Bonzini 		if (!was_rmapped) {
2784c50d8ae3SPaolo Bonzini 			rmap_count = rmap_add(vcpu, sptep, gfn);
2785ec1cf69cSPeter Xu 			if (rmap_count > vcpu->kvm->stat.max_mmu_rmap_size)
2786ec1cf69cSPeter Xu 				vcpu->kvm->stat.max_mmu_rmap_size = rmap_count;
2787c50d8ae3SPaolo Bonzini 			if (rmap_count > RMAP_RECYCLE_THRESHOLD)
2788c50d8ae3SPaolo Bonzini 				rmap_recycle(vcpu, sptep, gfn);
2789c50d8ae3SPaolo Bonzini 		}
2790c50d8ae3SPaolo Bonzini 	}
2791c50d8ae3SPaolo Bonzini 
2792c50d8ae3SPaolo Bonzini 	return ret;
2793c50d8ae3SPaolo Bonzini }
2794c50d8ae3SPaolo Bonzini 
2795c50d8ae3SPaolo Bonzini static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
2796c50d8ae3SPaolo Bonzini 				     bool no_dirty_log)
2797c50d8ae3SPaolo Bonzini {
2798c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
2799c50d8ae3SPaolo Bonzini 
2800c50d8ae3SPaolo Bonzini 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
2801c50d8ae3SPaolo Bonzini 	if (!slot)
2802c50d8ae3SPaolo Bonzini 		return KVM_PFN_ERR_FAULT;
2803c50d8ae3SPaolo Bonzini 
2804c50d8ae3SPaolo Bonzini 	return gfn_to_pfn_memslot_atomic(slot, gfn);
2805c50d8ae3SPaolo Bonzini }
2806c50d8ae3SPaolo Bonzini 
2807c50d8ae3SPaolo Bonzini static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
2808c50d8ae3SPaolo Bonzini 				    struct kvm_mmu_page *sp,
2809c50d8ae3SPaolo Bonzini 				    u64 *start, u64 *end)
2810c50d8ae3SPaolo Bonzini {
2811c50d8ae3SPaolo Bonzini 	struct page *pages[PTE_PREFETCH_NUM];
2812c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *slot;
28130a2b64c5SBen Gardon 	unsigned int access = sp->role.access;
2814c50d8ae3SPaolo Bonzini 	int i, ret;
2815c50d8ae3SPaolo Bonzini 	gfn_t gfn;
2816c50d8ae3SPaolo Bonzini 
2817c50d8ae3SPaolo Bonzini 	gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
2818c50d8ae3SPaolo Bonzini 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
2819c50d8ae3SPaolo Bonzini 	if (!slot)
2820c50d8ae3SPaolo Bonzini 		return -1;
2821c50d8ae3SPaolo Bonzini 
2822c50d8ae3SPaolo Bonzini 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
2823c50d8ae3SPaolo Bonzini 	if (ret <= 0)
2824c50d8ae3SPaolo Bonzini 		return -1;
2825c50d8ae3SPaolo Bonzini 
2826c50d8ae3SPaolo Bonzini 	for (i = 0; i < ret; i++, gfn++, start++) {
2827e88b8093SSean Christopherson 		mmu_set_spte(vcpu, start, access, false, sp->role.level, gfn,
2828c50d8ae3SPaolo Bonzini 			     page_to_pfn(pages[i]), true, true);
2829c50d8ae3SPaolo Bonzini 		put_page(pages[i]);
2830c50d8ae3SPaolo Bonzini 	}
2831c50d8ae3SPaolo Bonzini 
2832c50d8ae3SPaolo Bonzini 	return 0;
2833c50d8ae3SPaolo Bonzini }
2834c50d8ae3SPaolo Bonzini 
2835c50d8ae3SPaolo Bonzini static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
2836c50d8ae3SPaolo Bonzini 				  struct kvm_mmu_page *sp, u64 *sptep)
2837c50d8ae3SPaolo Bonzini {
2838c50d8ae3SPaolo Bonzini 	u64 *spte, *start = NULL;
2839c50d8ae3SPaolo Bonzini 	int i;
2840c50d8ae3SPaolo Bonzini 
2841c50d8ae3SPaolo Bonzini 	WARN_ON(!sp->role.direct);
2842c50d8ae3SPaolo Bonzini 
2843c50d8ae3SPaolo Bonzini 	i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
2844c50d8ae3SPaolo Bonzini 	spte = sp->spt + i;
2845c50d8ae3SPaolo Bonzini 
2846c50d8ae3SPaolo Bonzini 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
2847c50d8ae3SPaolo Bonzini 		if (is_shadow_present_pte(*spte) || spte == sptep) {
2848c50d8ae3SPaolo Bonzini 			if (!start)
2849c50d8ae3SPaolo Bonzini 				continue;
2850c50d8ae3SPaolo Bonzini 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
2851c50d8ae3SPaolo Bonzini 				break;
2852c50d8ae3SPaolo Bonzini 			start = NULL;
2853c50d8ae3SPaolo Bonzini 		} else if (!start)
2854c50d8ae3SPaolo Bonzini 			start = spte;
2855c50d8ae3SPaolo Bonzini 	}
2856c50d8ae3SPaolo Bonzini }
2857c50d8ae3SPaolo Bonzini 
2858c50d8ae3SPaolo Bonzini static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
2859c50d8ae3SPaolo Bonzini {
2860c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
2861c50d8ae3SPaolo Bonzini 
286257354682SSean Christopherson 	sp = sptep_to_sp(sptep);
2863c50d8ae3SPaolo Bonzini 
2864c50d8ae3SPaolo Bonzini 	/*
2865c50d8ae3SPaolo Bonzini 	 * Without accessed bits, there's no way to distinguish between
2866c50d8ae3SPaolo Bonzini 	 * actually accessed translations and prefetched, so disable pte
2867c50d8ae3SPaolo Bonzini 	 * prefetch if accessed bits aren't available.
2868c50d8ae3SPaolo Bonzini 	 */
2869c50d8ae3SPaolo Bonzini 	if (sp_ad_disabled(sp))
2870c50d8ae3SPaolo Bonzini 		return;
2871c50d8ae3SPaolo Bonzini 
28723bae0459SSean Christopherson 	if (sp->role.level > PG_LEVEL_4K)
2873c50d8ae3SPaolo Bonzini 		return;
2874c50d8ae3SPaolo Bonzini 
28754a42d848SDavid Stevens 	/*
28764a42d848SDavid Stevens 	 * If addresses are being invalidated, skip prefetching to avoid
28774a42d848SDavid Stevens 	 * accidentally prefetching those addresses.
28784a42d848SDavid Stevens 	 */
28794a42d848SDavid Stevens 	if (unlikely(vcpu->kvm->mmu_notifier_count))
28804a42d848SDavid Stevens 		return;
28814a42d848SDavid Stevens 
2882c50d8ae3SPaolo Bonzini 	__direct_pte_prefetch(vcpu, sp, sptep);
2883c50d8ae3SPaolo Bonzini }
2884c50d8ae3SPaolo Bonzini 
28851b6d9d9eSSean Christopherson static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
28868ca6f063SBen Gardon 				  const struct kvm_memory_slot *slot)
2887db543216SSean Christopherson {
2888db543216SSean Christopherson 	unsigned long hva;
2889db543216SSean Christopherson 	pte_t *pte;
2890db543216SSean Christopherson 	int level;
2891db543216SSean Christopherson 
2892e851265aSSean Christopherson 	if (!PageCompound(pfn_to_page(pfn)) && !kvm_is_zone_device_pfn(pfn))
28933bae0459SSean Christopherson 		return PG_LEVEL_4K;
2894db543216SSean Christopherson 
2895293e306eSSean Christopherson 	/*
2896293e306eSSean Christopherson 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
2897293e306eSSean Christopherson 	 * is not solely for performance, it's also necessary to avoid the
2898293e306eSSean Christopherson 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
2899293e306eSSean Christopherson 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
2900293e306eSSean Christopherson 	 * page fault steps have already verified the guest isn't writing a
2901293e306eSSean Christopherson 	 * read-only memslot.
2902293e306eSSean Christopherson 	 */
2903db543216SSean Christopherson 	hva = __gfn_to_hva_memslot(slot, gfn);
2904db543216SSean Christopherson 
29051b6d9d9eSSean Christopherson 	pte = lookup_address_in_mm(kvm->mm, hva, &level);
2906db543216SSean Christopherson 	if (unlikely(!pte))
29073bae0459SSean Christopherson 		return PG_LEVEL_4K;
2908db543216SSean Christopherson 
2909db543216SSean Christopherson 	return level;
2910db543216SSean Christopherson }
2911db543216SSean Christopherson 
29128ca6f063SBen Gardon int kvm_mmu_max_mapping_level(struct kvm *kvm,
29138ca6f063SBen Gardon 			      const struct kvm_memory_slot *slot, gfn_t gfn,
29148ca6f063SBen Gardon 			      kvm_pfn_t pfn, int max_level)
29151b6d9d9eSSean Christopherson {
29161b6d9d9eSSean Christopherson 	struct kvm_lpage_info *linfo;
29171b6d9d9eSSean Christopherson 
29181b6d9d9eSSean Christopherson 	max_level = min(max_level, max_huge_page_level);
29191b6d9d9eSSean Christopherson 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
29201b6d9d9eSSean Christopherson 		linfo = lpage_info_slot(gfn, slot, max_level);
29211b6d9d9eSSean Christopherson 		if (!linfo->disallow_lpage)
29221b6d9d9eSSean Christopherson 			break;
29231b6d9d9eSSean Christopherson 	}
29241b6d9d9eSSean Christopherson 
29251b6d9d9eSSean Christopherson 	if (max_level == PG_LEVEL_4K)
29261b6d9d9eSSean Christopherson 		return PG_LEVEL_4K;
29271b6d9d9eSSean Christopherson 
29281b6d9d9eSSean Christopherson 	return host_pfn_mapping_level(kvm, gfn, pfn, slot);
29291b6d9d9eSSean Christopherson }
29301b6d9d9eSSean Christopherson 
2931bb18842eSBen Gardon int kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, gfn_t gfn,
29323cf06612SSean Christopherson 			    int max_level, kvm_pfn_t *pfnp,
29333cf06612SSean Christopherson 			    bool huge_page_disallowed, int *req_level)
29340885904dSSean Christopherson {
2935293e306eSSean Christopherson 	struct kvm_memory_slot *slot;
29360885904dSSean Christopherson 	kvm_pfn_t pfn = *pfnp;
293717eff019SSean Christopherson 	kvm_pfn_t mask;
293883f06fa7SSean Christopherson 	int level;
29390885904dSSean Christopherson 
29403cf06612SSean Christopherson 	*req_level = PG_LEVEL_4K;
29413cf06612SSean Christopherson 
29423bae0459SSean Christopherson 	if (unlikely(max_level == PG_LEVEL_4K))
29433bae0459SSean Christopherson 		return PG_LEVEL_4K;
294417eff019SSean Christopherson 
2945e851265aSSean Christopherson 	if (is_error_noslot_pfn(pfn) || kvm_is_reserved_pfn(pfn))
29463bae0459SSean Christopherson 		return PG_LEVEL_4K;
294717eff019SSean Christopherson 
2948293e306eSSean Christopherson 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, true);
2949293e306eSSean Christopherson 	if (!slot)
29503bae0459SSean Christopherson 		return PG_LEVEL_4K;
2951293e306eSSean Christopherson 
29521b6d9d9eSSean Christopherson 	level = kvm_mmu_max_mapping_level(vcpu->kvm, slot, gfn, pfn, max_level);
29533bae0459SSean Christopherson 	if (level == PG_LEVEL_4K)
295483f06fa7SSean Christopherson 		return level;
295517eff019SSean Christopherson 
29563cf06612SSean Christopherson 	*req_level = level = min(level, max_level);
29573cf06612SSean Christopherson 
29583cf06612SSean Christopherson 	/*
29593cf06612SSean Christopherson 	 * Enforce the iTLB multihit workaround after capturing the requested
29603cf06612SSean Christopherson 	 * level, which will be used to do precise, accurate accounting.
29613cf06612SSean Christopherson 	 */
29623cf06612SSean Christopherson 	if (huge_page_disallowed)
29633cf06612SSean Christopherson 		return PG_LEVEL_4K;
29644cd071d1SSean Christopherson 
29650885904dSSean Christopherson 	/*
29664cd071d1SSean Christopherson 	 * mmu_notifier_retry() was successful and mmu_lock is held, so
29674cd071d1SSean Christopherson 	 * the pmd can't be split from under us.
29680885904dSSean Christopherson 	 */
29690885904dSSean Christopherson 	mask = KVM_PAGES_PER_HPAGE(level) - 1;
29700885904dSSean Christopherson 	VM_BUG_ON((gfn & mask) != (pfn & mask));
29714cd071d1SSean Christopherson 	*pfnp = pfn & ~mask;
297283f06fa7SSean Christopherson 
297383f06fa7SSean Christopherson 	return level;
29740885904dSSean Christopherson }
29750885904dSSean Christopherson 
2976bb18842eSBen Gardon void disallowed_hugepage_adjust(u64 spte, gfn_t gfn, int cur_level,
2977bb18842eSBen Gardon 				kvm_pfn_t *pfnp, int *goal_levelp)
2978c50d8ae3SPaolo Bonzini {
2979bb18842eSBen Gardon 	int level = *goal_levelp;
2980c50d8ae3SPaolo Bonzini 
29817d945312SBen Gardon 	if (cur_level == level && level > PG_LEVEL_4K &&
2982c50d8ae3SPaolo Bonzini 	    is_shadow_present_pte(spte) &&
2983c50d8ae3SPaolo Bonzini 	    !is_large_pte(spte)) {
2984c50d8ae3SPaolo Bonzini 		/*
2985c50d8ae3SPaolo Bonzini 		 * A small SPTE exists for this pfn, but FNAME(fetch)
2986c50d8ae3SPaolo Bonzini 		 * and __direct_map would like to create a large PTE
2987c50d8ae3SPaolo Bonzini 		 * instead: just force them to go down another level,
2988c50d8ae3SPaolo Bonzini 		 * patching back for them into pfn the next 9 bits of
2989c50d8ae3SPaolo Bonzini 		 * the address.
2990c50d8ae3SPaolo Bonzini 		 */
29917d945312SBen Gardon 		u64 page_mask = KVM_PAGES_PER_HPAGE(level) -
29927d945312SBen Gardon 				KVM_PAGES_PER_HPAGE(level - 1);
2993c50d8ae3SPaolo Bonzini 		*pfnp |= gfn & page_mask;
2994bb18842eSBen Gardon 		(*goal_levelp)--;
2995c50d8ae3SPaolo Bonzini 	}
2996c50d8ae3SPaolo Bonzini }
2997c50d8ae3SPaolo Bonzini 
29986c2fd34fSSean Christopherson static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
299983f06fa7SSean Christopherson 			int map_writable, int max_level, kvm_pfn_t pfn,
30006c2fd34fSSean Christopherson 			bool prefault, bool is_tdp)
3001c50d8ae3SPaolo Bonzini {
30026c2fd34fSSean Christopherson 	bool nx_huge_page_workaround_enabled = is_nx_huge_page_enabled();
30036c2fd34fSSean Christopherson 	bool write = error_code & PFERR_WRITE_MASK;
30046c2fd34fSSean Christopherson 	bool exec = error_code & PFERR_FETCH_MASK;
30056c2fd34fSSean Christopherson 	bool huge_page_disallowed = exec && nx_huge_page_workaround_enabled;
3006c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator it;
3007c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
30083cf06612SSean Christopherson 	int level, req_level, ret;
3009c50d8ae3SPaolo Bonzini 	gfn_t gfn = gpa >> PAGE_SHIFT;
3010c50d8ae3SPaolo Bonzini 	gfn_t base_gfn = gfn;
3011c50d8ae3SPaolo Bonzini 
30123cf06612SSean Christopherson 	level = kvm_mmu_hugepage_adjust(vcpu, gfn, max_level, &pfn,
30133cf06612SSean Christopherson 					huge_page_disallowed, &req_level);
30144cd071d1SSean Christopherson 
3015c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_spte_requested(gpa, level, pfn);
3016c50d8ae3SPaolo Bonzini 	for_each_shadow_entry(vcpu, gpa, it) {
3017c50d8ae3SPaolo Bonzini 		/*
3018c50d8ae3SPaolo Bonzini 		 * We cannot overwrite existing page tables with an NX
3019c50d8ae3SPaolo Bonzini 		 * large page, as the leaf could be executable.
3020c50d8ae3SPaolo Bonzini 		 */
3021dcc70651SSean Christopherson 		if (nx_huge_page_workaround_enabled)
30227d945312SBen Gardon 			disallowed_hugepage_adjust(*it.sptep, gfn, it.level,
30237d945312SBen Gardon 						   &pfn, &level);
3024c50d8ae3SPaolo Bonzini 
3025c50d8ae3SPaolo Bonzini 		base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3026c50d8ae3SPaolo Bonzini 		if (it.level == level)
3027c50d8ae3SPaolo Bonzini 			break;
3028c50d8ae3SPaolo Bonzini 
3029c50d8ae3SPaolo Bonzini 		drop_large_spte(vcpu, it.sptep);
303003fffc54SSean Christopherson 		if (is_shadow_present_pte(*it.sptep))
303103fffc54SSean Christopherson 			continue;
303203fffc54SSean Christopherson 
3033c50d8ae3SPaolo Bonzini 		sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3034c50d8ae3SPaolo Bonzini 				      it.level - 1, true, ACC_ALL);
3035c50d8ae3SPaolo Bonzini 
3036c50d8ae3SPaolo Bonzini 		link_shadow_page(vcpu, it.sptep, sp);
30375bcaf3e1SSean Christopherson 		if (is_tdp && huge_page_disallowed &&
30385bcaf3e1SSean Christopherson 		    req_level >= it.level)
3039c50d8ae3SPaolo Bonzini 			account_huge_nx_page(vcpu->kvm, sp);
3040c50d8ae3SPaolo Bonzini 	}
3041c50d8ae3SPaolo Bonzini 
3042c50d8ae3SPaolo Bonzini 	ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3043c50d8ae3SPaolo Bonzini 			   write, level, base_gfn, pfn, prefault,
3044c50d8ae3SPaolo Bonzini 			   map_writable);
304512703759SSean Christopherson 	if (ret == RET_PF_SPURIOUS)
304612703759SSean Christopherson 		return ret;
304712703759SSean Christopherson 
3048c50d8ae3SPaolo Bonzini 	direct_pte_prefetch(vcpu, it.sptep);
3049c50d8ae3SPaolo Bonzini 	++vcpu->stat.pf_fixed;
3050c50d8ae3SPaolo Bonzini 	return ret;
3051c50d8ae3SPaolo Bonzini }
3052c50d8ae3SPaolo Bonzini 
3053c50d8ae3SPaolo Bonzini static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3054c50d8ae3SPaolo Bonzini {
3055c50d8ae3SPaolo Bonzini 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3056c50d8ae3SPaolo Bonzini }
3057c50d8ae3SPaolo Bonzini 
3058c50d8ae3SPaolo Bonzini static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3059c50d8ae3SPaolo Bonzini {
3060c50d8ae3SPaolo Bonzini 	/*
3061c50d8ae3SPaolo Bonzini 	 * Do not cache the mmio info caused by writing the readonly gfn
3062c50d8ae3SPaolo Bonzini 	 * into the spte otherwise read access on readonly gfn also can
3063c50d8ae3SPaolo Bonzini 	 * caused mmio page fault and treat it as mmio access.
3064c50d8ae3SPaolo Bonzini 	 */
3065c50d8ae3SPaolo Bonzini 	if (pfn == KVM_PFN_ERR_RO_FAULT)
3066c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3067c50d8ae3SPaolo Bonzini 
3068c50d8ae3SPaolo Bonzini 	if (pfn == KVM_PFN_ERR_HWPOISON) {
3069c50d8ae3SPaolo Bonzini 		kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3070c50d8ae3SPaolo Bonzini 		return RET_PF_RETRY;
3071c50d8ae3SPaolo Bonzini 	}
3072c50d8ae3SPaolo Bonzini 
3073c50d8ae3SPaolo Bonzini 	return -EFAULT;
3074c50d8ae3SPaolo Bonzini }
3075c50d8ae3SPaolo Bonzini 
3076c50d8ae3SPaolo Bonzini static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
30770a2b64c5SBen Gardon 				kvm_pfn_t pfn, unsigned int access,
30780a2b64c5SBen Gardon 				int *ret_val)
3079c50d8ae3SPaolo Bonzini {
3080c50d8ae3SPaolo Bonzini 	/* The pfn is invalid, report the error! */
3081c50d8ae3SPaolo Bonzini 	if (unlikely(is_error_pfn(pfn))) {
3082c50d8ae3SPaolo Bonzini 		*ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3083c50d8ae3SPaolo Bonzini 		return true;
3084c50d8ae3SPaolo Bonzini 	}
3085c50d8ae3SPaolo Bonzini 
308630ab5901SSean Christopherson 	if (unlikely(is_noslot_pfn(pfn))) {
3087c50d8ae3SPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, gva, gfn,
3088c50d8ae3SPaolo Bonzini 				     access & shadow_mmio_access_mask);
308930ab5901SSean Christopherson 		/*
309030ab5901SSean Christopherson 		 * If MMIO caching is disabled, emulate immediately without
309130ab5901SSean Christopherson 		 * touching the shadow page tables as attempting to install an
309230ab5901SSean Christopherson 		 * MMIO SPTE will just be an expensive nop.
309330ab5901SSean Christopherson 		 */
309430ab5901SSean Christopherson 		if (unlikely(!shadow_mmio_value)) {
309530ab5901SSean Christopherson 			*ret_val = RET_PF_EMULATE;
309630ab5901SSean Christopherson 			return true;
309730ab5901SSean Christopherson 		}
309830ab5901SSean Christopherson 	}
3099c50d8ae3SPaolo Bonzini 
3100c50d8ae3SPaolo Bonzini 	return false;
3101c50d8ae3SPaolo Bonzini }
3102c50d8ae3SPaolo Bonzini 
3103c50d8ae3SPaolo Bonzini static bool page_fault_can_be_fast(u32 error_code)
3104c50d8ae3SPaolo Bonzini {
3105c50d8ae3SPaolo Bonzini 	/*
3106c50d8ae3SPaolo Bonzini 	 * Do not fix the mmio spte with invalid generation number which
3107c50d8ae3SPaolo Bonzini 	 * need to be updated by slow page fault path.
3108c50d8ae3SPaolo Bonzini 	 */
3109c50d8ae3SPaolo Bonzini 	if (unlikely(error_code & PFERR_RSVD_MASK))
3110c50d8ae3SPaolo Bonzini 		return false;
3111c50d8ae3SPaolo Bonzini 
3112c50d8ae3SPaolo Bonzini 	/* See if the page fault is due to an NX violation */
3113c50d8ae3SPaolo Bonzini 	if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3114c50d8ae3SPaolo Bonzini 		      == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3115c50d8ae3SPaolo Bonzini 		return false;
3116c50d8ae3SPaolo Bonzini 
3117c50d8ae3SPaolo Bonzini 	/*
3118c50d8ae3SPaolo Bonzini 	 * #PF can be fast if:
3119c50d8ae3SPaolo Bonzini 	 * 1. The shadow page table entry is not present, which could mean that
3120c50d8ae3SPaolo Bonzini 	 *    the fault is potentially caused by access tracking (if enabled).
3121c50d8ae3SPaolo Bonzini 	 * 2. The shadow page table entry is present and the fault
3122c50d8ae3SPaolo Bonzini 	 *    is caused by write-protect, that means we just need change the W
3123c50d8ae3SPaolo Bonzini 	 *    bit of the spte which can be done out of mmu-lock.
3124c50d8ae3SPaolo Bonzini 	 *
3125c50d8ae3SPaolo Bonzini 	 * However, if access tracking is disabled we know that a non-present
3126c50d8ae3SPaolo Bonzini 	 * page must be a genuine page fault where we have to create a new SPTE.
3127c50d8ae3SPaolo Bonzini 	 * So, if access tracking is disabled, we return true only for write
3128c50d8ae3SPaolo Bonzini 	 * accesses to a present page.
3129c50d8ae3SPaolo Bonzini 	 */
3130c50d8ae3SPaolo Bonzini 
3131c50d8ae3SPaolo Bonzini 	return shadow_acc_track_mask != 0 ||
3132c50d8ae3SPaolo Bonzini 	       ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3133c50d8ae3SPaolo Bonzini 		== (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3134c50d8ae3SPaolo Bonzini }
3135c50d8ae3SPaolo Bonzini 
3136c50d8ae3SPaolo Bonzini /*
3137c50d8ae3SPaolo Bonzini  * Returns true if the SPTE was fixed successfully. Otherwise,
3138c50d8ae3SPaolo Bonzini  * someone else modified the SPTE from its original value.
3139c50d8ae3SPaolo Bonzini  */
3140c50d8ae3SPaolo Bonzini static bool
3141c50d8ae3SPaolo Bonzini fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3142c50d8ae3SPaolo Bonzini 			u64 *sptep, u64 old_spte, u64 new_spte)
3143c50d8ae3SPaolo Bonzini {
3144c50d8ae3SPaolo Bonzini 	gfn_t gfn;
3145c50d8ae3SPaolo Bonzini 
3146c50d8ae3SPaolo Bonzini 	WARN_ON(!sp->role.direct);
3147c50d8ae3SPaolo Bonzini 
3148c50d8ae3SPaolo Bonzini 	/*
3149c50d8ae3SPaolo Bonzini 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3150c50d8ae3SPaolo Bonzini 	 * order to eliminate unnecessary PML logging. See comments in
3151c50d8ae3SPaolo Bonzini 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3152c50d8ae3SPaolo Bonzini 	 * enabled, so we do not do this. This might result in the same GPA
3153c50d8ae3SPaolo Bonzini 	 * to be logged in PML buffer again when the write really happens, and
3154c50d8ae3SPaolo Bonzini 	 * eventually to be called by mark_page_dirty twice. But it's also no
3155c50d8ae3SPaolo Bonzini 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3156c50d8ae3SPaolo Bonzini 	 * so non-PML cases won't be impacted.
3157c50d8ae3SPaolo Bonzini 	 *
3158c50d8ae3SPaolo Bonzini 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3159c50d8ae3SPaolo Bonzini 	 */
3160c50d8ae3SPaolo Bonzini 	if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3161c50d8ae3SPaolo Bonzini 		return false;
3162c50d8ae3SPaolo Bonzini 
3163c50d8ae3SPaolo Bonzini 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3164c50d8ae3SPaolo Bonzini 		/*
3165c50d8ae3SPaolo Bonzini 		 * The gfn of direct spte is stable since it is
3166c50d8ae3SPaolo Bonzini 		 * calculated by sp->gfn.
3167c50d8ae3SPaolo Bonzini 		 */
3168c50d8ae3SPaolo Bonzini 		gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3169c50d8ae3SPaolo Bonzini 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
3170c50d8ae3SPaolo Bonzini 	}
3171c50d8ae3SPaolo Bonzini 
3172c50d8ae3SPaolo Bonzini 	return true;
3173c50d8ae3SPaolo Bonzini }
3174c50d8ae3SPaolo Bonzini 
3175c50d8ae3SPaolo Bonzini static bool is_access_allowed(u32 fault_err_code, u64 spte)
3176c50d8ae3SPaolo Bonzini {
3177c50d8ae3SPaolo Bonzini 	if (fault_err_code & PFERR_FETCH_MASK)
3178c50d8ae3SPaolo Bonzini 		return is_executable_pte(spte);
3179c50d8ae3SPaolo Bonzini 
3180c50d8ae3SPaolo Bonzini 	if (fault_err_code & PFERR_WRITE_MASK)
3181c50d8ae3SPaolo Bonzini 		return is_writable_pte(spte);
3182c50d8ae3SPaolo Bonzini 
3183c50d8ae3SPaolo Bonzini 	/* Fault was on Read access */
3184c50d8ae3SPaolo Bonzini 	return spte & PT_PRESENT_MASK;
3185c50d8ae3SPaolo Bonzini }
3186c50d8ae3SPaolo Bonzini 
3187c50d8ae3SPaolo Bonzini /*
31886e8eb206SDavid Matlack  * Returns the last level spte pointer of the shadow page walk for the given
31896e8eb206SDavid Matlack  * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
31906e8eb206SDavid Matlack  * walk could be performed, returns NULL and *spte does not contain valid data.
31916e8eb206SDavid Matlack  *
31926e8eb206SDavid Matlack  * Contract:
31936e8eb206SDavid Matlack  *  - Must be called between walk_shadow_page_lockless_{begin,end}.
31946e8eb206SDavid Matlack  *  - The returned sptep must not be used after walk_shadow_page_lockless_end.
31956e8eb206SDavid Matlack  */
31966e8eb206SDavid Matlack static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
31976e8eb206SDavid Matlack {
31986e8eb206SDavid Matlack 	struct kvm_shadow_walk_iterator iterator;
31996e8eb206SDavid Matlack 	u64 old_spte;
32006e8eb206SDavid Matlack 	u64 *sptep = NULL;
32016e8eb206SDavid Matlack 
32026e8eb206SDavid Matlack 	for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
32036e8eb206SDavid Matlack 		sptep = iterator.sptep;
32046e8eb206SDavid Matlack 		*spte = old_spte;
32056e8eb206SDavid Matlack 
32066e8eb206SDavid Matlack 		if (!is_shadow_present_pte(old_spte))
32076e8eb206SDavid Matlack 			break;
32086e8eb206SDavid Matlack 	}
32096e8eb206SDavid Matlack 
32106e8eb206SDavid Matlack 	return sptep;
32116e8eb206SDavid Matlack }
32126e8eb206SDavid Matlack 
32136e8eb206SDavid Matlack /*
3214c4371c2aSSean Christopherson  * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3215c50d8ae3SPaolo Bonzini  */
321676cd325eSDavid Matlack static int fast_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code)
3217c50d8ae3SPaolo Bonzini {
3218c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3219c4371c2aSSean Christopherson 	int ret = RET_PF_INVALID;
3220c50d8ae3SPaolo Bonzini 	u64 spte = 0ull;
32216e8eb206SDavid Matlack 	u64 *sptep = NULL;
3222c50d8ae3SPaolo Bonzini 	uint retry_count = 0;
3223c50d8ae3SPaolo Bonzini 
3224c50d8ae3SPaolo Bonzini 	if (!page_fault_can_be_fast(error_code))
3225c4371c2aSSean Christopherson 		return ret;
3226c50d8ae3SPaolo Bonzini 
3227c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
3228c50d8ae3SPaolo Bonzini 
3229c50d8ae3SPaolo Bonzini 	do {
3230c50d8ae3SPaolo Bonzini 		u64 new_spte;
3231c50d8ae3SPaolo Bonzini 
32326e8eb206SDavid Matlack 		if (is_tdp_mmu(vcpu->arch.mmu))
32336e8eb206SDavid Matlack 			sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, gpa, &spte);
32346e8eb206SDavid Matlack 		else
32356e8eb206SDavid Matlack 			sptep = fast_pf_get_last_sptep(vcpu, gpa, &spte);
3236c50d8ae3SPaolo Bonzini 
3237ec89e643SSean Christopherson 		if (!is_shadow_present_pte(spte))
3238ec89e643SSean Christopherson 			break;
3239ec89e643SSean Christopherson 
32406e8eb206SDavid Matlack 		sp = sptep_to_sp(sptep);
3241c50d8ae3SPaolo Bonzini 		if (!is_last_spte(spte, sp->role.level))
3242c50d8ae3SPaolo Bonzini 			break;
3243c50d8ae3SPaolo Bonzini 
3244c50d8ae3SPaolo Bonzini 		/*
3245c50d8ae3SPaolo Bonzini 		 * Check whether the memory access that caused the fault would
3246c50d8ae3SPaolo Bonzini 		 * still cause it if it were to be performed right now. If not,
3247c50d8ae3SPaolo Bonzini 		 * then this is a spurious fault caused by TLB lazily flushed,
3248c50d8ae3SPaolo Bonzini 		 * or some other CPU has already fixed the PTE after the
3249c50d8ae3SPaolo Bonzini 		 * current CPU took the fault.
3250c50d8ae3SPaolo Bonzini 		 *
3251c50d8ae3SPaolo Bonzini 		 * Need not check the access of upper level table entries since
3252c50d8ae3SPaolo Bonzini 		 * they are always ACC_ALL.
3253c50d8ae3SPaolo Bonzini 		 */
3254c50d8ae3SPaolo Bonzini 		if (is_access_allowed(error_code, spte)) {
3255c4371c2aSSean Christopherson 			ret = RET_PF_SPURIOUS;
3256c50d8ae3SPaolo Bonzini 			break;
3257c50d8ae3SPaolo Bonzini 		}
3258c50d8ae3SPaolo Bonzini 
3259c50d8ae3SPaolo Bonzini 		new_spte = spte;
3260c50d8ae3SPaolo Bonzini 
3261c50d8ae3SPaolo Bonzini 		if (is_access_track_spte(spte))
3262c50d8ae3SPaolo Bonzini 			new_spte = restore_acc_track_spte(new_spte);
3263c50d8ae3SPaolo Bonzini 
3264c50d8ae3SPaolo Bonzini 		/*
3265c50d8ae3SPaolo Bonzini 		 * Currently, to simplify the code, write-protection can
3266c50d8ae3SPaolo Bonzini 		 * be removed in the fast path only if the SPTE was
3267c50d8ae3SPaolo Bonzini 		 * write-protected for dirty-logging or access tracking.
3268c50d8ae3SPaolo Bonzini 		 */
3269c50d8ae3SPaolo Bonzini 		if ((error_code & PFERR_WRITE_MASK) &&
3270e6302698SMiaohe Lin 		    spte_can_locklessly_be_made_writable(spte)) {
3271c50d8ae3SPaolo Bonzini 			new_spte |= PT_WRITABLE_MASK;
3272c50d8ae3SPaolo Bonzini 
3273c50d8ae3SPaolo Bonzini 			/*
3274c50d8ae3SPaolo Bonzini 			 * Do not fix write-permission on the large spte.  Since
3275c50d8ae3SPaolo Bonzini 			 * we only dirty the first page into the dirty-bitmap in
3276c50d8ae3SPaolo Bonzini 			 * fast_pf_fix_direct_spte(), other pages are missed
3277c50d8ae3SPaolo Bonzini 			 * if its slot has dirty logging enabled.
3278c50d8ae3SPaolo Bonzini 			 *
3279c50d8ae3SPaolo Bonzini 			 * Instead, we let the slow page fault path create a
3280c50d8ae3SPaolo Bonzini 			 * normal spte to fix the access.
3281c50d8ae3SPaolo Bonzini 			 *
3282c50d8ae3SPaolo Bonzini 			 * See the comments in kvm_arch_commit_memory_region().
3283c50d8ae3SPaolo Bonzini 			 */
32843bae0459SSean Christopherson 			if (sp->role.level > PG_LEVEL_4K)
3285c50d8ae3SPaolo Bonzini 				break;
3286c50d8ae3SPaolo Bonzini 		}
3287c50d8ae3SPaolo Bonzini 
3288c50d8ae3SPaolo Bonzini 		/* Verify that the fault can be handled in the fast path */
3289c50d8ae3SPaolo Bonzini 		if (new_spte == spte ||
3290c50d8ae3SPaolo Bonzini 		    !is_access_allowed(error_code, new_spte))
3291c50d8ae3SPaolo Bonzini 			break;
3292c50d8ae3SPaolo Bonzini 
3293c50d8ae3SPaolo Bonzini 		/*
3294c50d8ae3SPaolo Bonzini 		 * Currently, fast page fault only works for direct mapping
3295c50d8ae3SPaolo Bonzini 		 * since the gfn is not stable for indirect shadow page. See
32963ecad8c2SMauro Carvalho Chehab 		 * Documentation/virt/kvm/locking.rst to get more detail.
3297c50d8ae3SPaolo Bonzini 		 */
32986e8eb206SDavid Matlack 		if (fast_pf_fix_direct_spte(vcpu, sp, sptep, spte, new_spte)) {
3299c4371c2aSSean Christopherson 			ret = RET_PF_FIXED;
3300c50d8ae3SPaolo Bonzini 			break;
3301c4371c2aSSean Christopherson 		}
3302c50d8ae3SPaolo Bonzini 
3303c50d8ae3SPaolo Bonzini 		if (++retry_count > 4) {
3304c50d8ae3SPaolo Bonzini 			printk_once(KERN_WARNING
3305c50d8ae3SPaolo Bonzini 				"kvm: Fast #PF retrying more than 4 times.\n");
3306c50d8ae3SPaolo Bonzini 			break;
3307c50d8ae3SPaolo Bonzini 		}
3308c50d8ae3SPaolo Bonzini 
3309c50d8ae3SPaolo Bonzini 	} while (true);
3310c50d8ae3SPaolo Bonzini 
33116e8eb206SDavid Matlack 	trace_fast_page_fault(vcpu, gpa, error_code, sptep, spte, ret);
3312c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3313c50d8ae3SPaolo Bonzini 
3314c4371c2aSSean Christopherson 	return ret;
3315c50d8ae3SPaolo Bonzini }
3316c50d8ae3SPaolo Bonzini 
3317c50d8ae3SPaolo Bonzini static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3318c50d8ae3SPaolo Bonzini 			       struct list_head *invalid_list)
3319c50d8ae3SPaolo Bonzini {
3320c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3321c50d8ae3SPaolo Bonzini 
3322c50d8ae3SPaolo Bonzini 	if (!VALID_PAGE(*root_hpa))
3323c50d8ae3SPaolo Bonzini 		return;
3324c50d8ae3SPaolo Bonzini 
3325e47c4aeeSSean Christopherson 	sp = to_shadow_page(*root_hpa & PT64_BASE_ADDR_MASK);
332602c00b3aSBen Gardon 
3327897218ffSPaolo Bonzini 	if (is_tdp_mmu_page(sp))
33286103bc07SBen Gardon 		kvm_tdp_mmu_put_root(kvm, sp, false);
332976eb54e7SBen Gardon 	else if (!--sp->root_count && sp->role.invalid)
3330c50d8ae3SPaolo Bonzini 		kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3331c50d8ae3SPaolo Bonzini 
3332c50d8ae3SPaolo Bonzini 	*root_hpa = INVALID_PAGE;
3333c50d8ae3SPaolo Bonzini }
3334c50d8ae3SPaolo Bonzini 
3335c50d8ae3SPaolo Bonzini /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3336c50d8ae3SPaolo Bonzini void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3337c50d8ae3SPaolo Bonzini 			ulong roots_to_free)
3338c50d8ae3SPaolo Bonzini {
33394d710de9SSean Christopherson 	struct kvm *kvm = vcpu->kvm;
3340c50d8ae3SPaolo Bonzini 	int i;
3341c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
3342c50d8ae3SPaolo Bonzini 	bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3343c50d8ae3SPaolo Bonzini 
3344c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3345c50d8ae3SPaolo Bonzini 
3346c50d8ae3SPaolo Bonzini 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3347c50d8ae3SPaolo Bonzini 	if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3348c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3349c50d8ae3SPaolo Bonzini 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3350c50d8ae3SPaolo Bonzini 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3351c50d8ae3SPaolo Bonzini 				break;
3352c50d8ae3SPaolo Bonzini 
3353c50d8ae3SPaolo Bonzini 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3354c50d8ae3SPaolo Bonzini 			return;
3355c50d8ae3SPaolo Bonzini 	}
3356c50d8ae3SPaolo Bonzini 
3357531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
3358c50d8ae3SPaolo Bonzini 
3359c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3360c50d8ae3SPaolo Bonzini 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
33614d710de9SSean Christopherson 			mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3362c50d8ae3SPaolo Bonzini 					   &invalid_list);
3363c50d8ae3SPaolo Bonzini 
3364c50d8ae3SPaolo Bonzini 	if (free_active_root) {
3365c50d8ae3SPaolo Bonzini 		if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3366c50d8ae3SPaolo Bonzini 		    (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
33674d710de9SSean Christopherson 			mmu_free_root_page(kvm, &mmu->root_hpa, &invalid_list);
336804d45551SSean Christopherson 		} else if (mmu->pae_root) {
3369c834e5e4SSean Christopherson 			for (i = 0; i < 4; ++i) {
3370c834e5e4SSean Christopherson 				if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3371c834e5e4SSean Christopherson 					continue;
3372c834e5e4SSean Christopherson 
3373c834e5e4SSean Christopherson 				mmu_free_root_page(kvm, &mmu->pae_root[i],
3374c50d8ae3SPaolo Bonzini 						   &invalid_list);
3375c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3376c50d8ae3SPaolo Bonzini 			}
3377c50d8ae3SPaolo Bonzini 		}
337804d45551SSean Christopherson 		mmu->root_hpa = INVALID_PAGE;
3379be01e8e2SSean Christopherson 		mmu->root_pgd = 0;
3380c50d8ae3SPaolo Bonzini 	}
3381c50d8ae3SPaolo Bonzini 
33824d710de9SSean Christopherson 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
3383531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
3384c50d8ae3SPaolo Bonzini }
3385c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3386c50d8ae3SPaolo Bonzini 
338725b62c62SSean Christopherson void kvm_mmu_free_guest_mode_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
338825b62c62SSean Christopherson {
338925b62c62SSean Christopherson 	unsigned long roots_to_free = 0;
339025b62c62SSean Christopherson 	hpa_t root_hpa;
339125b62c62SSean Christopherson 	int i;
339225b62c62SSean Christopherson 
339325b62c62SSean Christopherson 	/*
339425b62c62SSean Christopherson 	 * This should not be called while L2 is active, L2 can't invalidate
339525b62c62SSean Christopherson 	 * _only_ its own roots, e.g. INVVPID unconditionally exits.
339625b62c62SSean Christopherson 	 */
339725b62c62SSean Christopherson 	WARN_ON_ONCE(mmu->mmu_role.base.guest_mode);
339825b62c62SSean Christopherson 
339925b62c62SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
340025b62c62SSean Christopherson 		root_hpa = mmu->prev_roots[i].hpa;
340125b62c62SSean Christopherson 		if (!VALID_PAGE(root_hpa))
340225b62c62SSean Christopherson 			continue;
340325b62c62SSean Christopherson 
340425b62c62SSean Christopherson 		if (!to_shadow_page(root_hpa) ||
340525b62c62SSean Christopherson 			to_shadow_page(root_hpa)->role.guest_mode)
340625b62c62SSean Christopherson 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
340725b62c62SSean Christopherson 	}
340825b62c62SSean Christopherson 
340925b62c62SSean Christopherson 	kvm_mmu_free_roots(vcpu, mmu, roots_to_free);
341025b62c62SSean Christopherson }
341125b62c62SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
341225b62c62SSean Christopherson 
341325b62c62SSean Christopherson 
3414c50d8ae3SPaolo Bonzini static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3415c50d8ae3SPaolo Bonzini {
3416c50d8ae3SPaolo Bonzini 	int ret = 0;
3417c50d8ae3SPaolo Bonzini 
3418995decb6SVitaly Kuznetsov 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3419c50d8ae3SPaolo Bonzini 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3420c50d8ae3SPaolo Bonzini 		ret = 1;
3421c50d8ae3SPaolo Bonzini 	}
3422c50d8ae3SPaolo Bonzini 
3423c50d8ae3SPaolo Bonzini 	return ret;
3424c50d8ae3SPaolo Bonzini }
3425c50d8ae3SPaolo Bonzini 
34268123f265SSean Christopherson static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
34278123f265SSean Christopherson 			    u8 level, bool direct)
3428c50d8ae3SPaolo Bonzini {
3429c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
34308123f265SSean Christopherson 
34318123f265SSean Christopherson 	sp = kvm_mmu_get_page(vcpu, gfn, gva, level, direct, ACC_ALL);
34328123f265SSean Christopherson 	++sp->root_count;
34338123f265SSean Christopherson 
34348123f265SSean Christopherson 	return __pa(sp->spt);
34358123f265SSean Christopherson }
34368123f265SSean Christopherson 
34378123f265SSean Christopherson static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
34388123f265SSean Christopherson {
3439b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3440b37233c9SSean Christopherson 	u8 shadow_root_level = mmu->shadow_root_level;
34418123f265SSean Christopherson 	hpa_t root;
3442c50d8ae3SPaolo Bonzini 	unsigned i;
34434a38162eSPaolo Bonzini 	int r;
34444a38162eSPaolo Bonzini 
34454a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
34464a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
34474a38162eSPaolo Bonzini 	if (r < 0)
34484a38162eSPaolo Bonzini 		goto out_unlock;
3449c50d8ae3SPaolo Bonzini 
3450897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(vcpu->kvm)) {
345102c00b3aSBen Gardon 		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
3452b37233c9SSean Christopherson 		mmu->root_hpa = root;
345302c00b3aSBen Gardon 	} else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
34546e6ec584SSean Christopherson 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level, true);
3455b37233c9SSean Christopherson 		mmu->root_hpa = root;
34568123f265SSean Christopherson 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
34574a38162eSPaolo Bonzini 		if (WARN_ON_ONCE(!mmu->pae_root)) {
34584a38162eSPaolo Bonzini 			r = -EIO;
34594a38162eSPaolo Bonzini 			goto out_unlock;
34604a38162eSPaolo Bonzini 		}
346173ad1606SSean Christopherson 
3462c50d8ae3SPaolo Bonzini 		for (i = 0; i < 4; ++i) {
3463c834e5e4SSean Christopherson 			WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3464c50d8ae3SPaolo Bonzini 
34658123f265SSean Christopherson 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT),
34668123f265SSean Christopherson 					      i << 30, PT32_ROOT_LEVEL, true);
346717e368d9SSean Christopherson 			mmu->pae_root[i] = root | PT_PRESENT_MASK |
346817e368d9SSean Christopherson 					   shadow_me_mask;
3469c50d8ae3SPaolo Bonzini 		}
3470b37233c9SSean Christopherson 		mmu->root_hpa = __pa(mmu->pae_root);
347173ad1606SSean Christopherson 	} else {
347273ad1606SSean Christopherson 		WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
34734a38162eSPaolo Bonzini 		r = -EIO;
34744a38162eSPaolo Bonzini 		goto out_unlock;
347573ad1606SSean Christopherson 	}
34763651c7fcSSean Christopherson 
3477be01e8e2SSean Christopherson 	/* root_pgd is ignored for direct MMUs. */
3478b37233c9SSean Christopherson 	mmu->root_pgd = 0;
34794a38162eSPaolo Bonzini out_unlock:
34804a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
34814a38162eSPaolo Bonzini 	return r;
3482c50d8ae3SPaolo Bonzini }
3483c50d8ae3SPaolo Bonzini 
3484c50d8ae3SPaolo Bonzini static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3485c50d8ae3SPaolo Bonzini {
3486b37233c9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
34876e0918aeSSean Christopherson 	u64 pdptrs[4], pm_mask;
3488be01e8e2SSean Christopherson 	gfn_t root_gfn, root_pgd;
34898123f265SSean Christopherson 	hpa_t root;
34904a38162eSPaolo Bonzini 	unsigned i;
34914a38162eSPaolo Bonzini 	int r;
3492c50d8ae3SPaolo Bonzini 
3493b37233c9SSean Christopherson 	root_pgd = mmu->get_guest_pgd(vcpu);
3494be01e8e2SSean Christopherson 	root_gfn = root_pgd >> PAGE_SHIFT;
3495c50d8ae3SPaolo Bonzini 
3496c50d8ae3SPaolo Bonzini 	if (mmu_check_root(vcpu, root_gfn))
3497c50d8ae3SPaolo Bonzini 		return 1;
3498c50d8ae3SPaolo Bonzini 
3499c50d8ae3SPaolo Bonzini 	/*
35004a38162eSPaolo Bonzini 	 * On SVM, reading PDPTRs might access guest memory, which might fault
35014a38162eSPaolo Bonzini 	 * and thus might sleep.  Grab the PDPTRs before acquiring mmu_lock.
35024a38162eSPaolo Bonzini 	 */
35036e0918aeSSean Christopherson 	if (mmu->root_level == PT32E_ROOT_LEVEL) {
35046e0918aeSSean Christopherson 		for (i = 0; i < 4; ++i) {
35056e0918aeSSean Christopherson 			pdptrs[i] = mmu->get_pdptr(vcpu, i);
35066e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK))
35076e0918aeSSean Christopherson 				continue;
35086e0918aeSSean Christopherson 
35096e0918aeSSean Christopherson 			if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
35106e0918aeSSean Christopherson 				return 1;
35116e0918aeSSean Christopherson 		}
35126e0918aeSSean Christopherson 	}
35136e0918aeSSean Christopherson 
3514d501f747SBen Gardon 	r = alloc_all_memslots_rmaps(vcpu->kvm);
3515d501f747SBen Gardon 	if (r)
3516d501f747SBen Gardon 		return r;
3517d501f747SBen Gardon 
35184a38162eSPaolo Bonzini 	write_lock(&vcpu->kvm->mmu_lock);
35194a38162eSPaolo Bonzini 	r = make_mmu_pages_available(vcpu);
35204a38162eSPaolo Bonzini 	if (r < 0)
35214a38162eSPaolo Bonzini 		goto out_unlock;
35224a38162eSPaolo Bonzini 
3523c50d8ae3SPaolo Bonzini 	/*
3524c50d8ae3SPaolo Bonzini 	 * Do we shadow a long mode page table? If so we need to
3525c50d8ae3SPaolo Bonzini 	 * write-protect the guests page table root.
3526c50d8ae3SPaolo Bonzini 	 */
3527b37233c9SSean Christopherson 	if (mmu->root_level >= PT64_ROOT_4LEVEL) {
35288123f265SSean Christopherson 		root = mmu_alloc_root(vcpu, root_gfn, 0,
3529b37233c9SSean Christopherson 				      mmu->shadow_root_level, false);
3530b37233c9SSean Christopherson 		mmu->root_hpa = root;
3531be01e8e2SSean Christopherson 		goto set_root_pgd;
3532c50d8ae3SPaolo Bonzini 	}
3533c50d8ae3SPaolo Bonzini 
35344a38162eSPaolo Bonzini 	if (WARN_ON_ONCE(!mmu->pae_root)) {
35354a38162eSPaolo Bonzini 		r = -EIO;
35364a38162eSPaolo Bonzini 		goto out_unlock;
35374a38162eSPaolo Bonzini 	}
353873ad1606SSean Christopherson 
3539c50d8ae3SPaolo Bonzini 	/*
3540c50d8ae3SPaolo Bonzini 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3541c50d8ae3SPaolo Bonzini 	 * or a PAE 3-level page table. In either case we need to be aware that
3542c50d8ae3SPaolo Bonzini 	 * the shadow page table may be a PAE or a long mode page table.
3543c50d8ae3SPaolo Bonzini 	 */
354417e368d9SSean Christopherson 	pm_mask = PT_PRESENT_MASK | shadow_me_mask;
3545748e52b9SSean Christopherson 	if (mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3546c50d8ae3SPaolo Bonzini 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3547c50d8ae3SPaolo Bonzini 
354803ca4589SSean Christopherson 		if (WARN_ON_ONCE(!mmu->pml4_root)) {
35494a38162eSPaolo Bonzini 			r = -EIO;
35504a38162eSPaolo Bonzini 			goto out_unlock;
35514a38162eSPaolo Bonzini 		}
355273ad1606SSean Christopherson 
355303ca4589SSean Christopherson 		mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
355404d45551SSean Christopherson 	}
355504d45551SSean Christopherson 
3556c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3557c834e5e4SSean Christopherson 		WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
35586e6ec584SSean Christopherson 
3559b37233c9SSean Christopherson 		if (mmu->root_level == PT32E_ROOT_LEVEL) {
35606e0918aeSSean Christopherson 			if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3561c834e5e4SSean Christopherson 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3562c50d8ae3SPaolo Bonzini 				continue;
3563c50d8ae3SPaolo Bonzini 			}
35646e0918aeSSean Christopherson 			root_gfn = pdptrs[i] >> PAGE_SHIFT;
3565c50d8ae3SPaolo Bonzini 		}
3566c50d8ae3SPaolo Bonzini 
35678123f265SSean Christopherson 		root = mmu_alloc_root(vcpu, root_gfn, i << 30,
35688123f265SSean Christopherson 				      PT32_ROOT_LEVEL, false);
3569b37233c9SSean Christopherson 		mmu->pae_root[i] = root | pm_mask;
3570c50d8ae3SPaolo Bonzini 	}
3571c50d8ae3SPaolo Bonzini 
3572ba0a194fSSean Christopherson 	if (mmu->shadow_root_level == PT64_ROOT_4LEVEL)
357303ca4589SSean Christopherson 		mmu->root_hpa = __pa(mmu->pml4_root);
3574ba0a194fSSean Christopherson 	else
3575ba0a194fSSean Christopherson 		mmu->root_hpa = __pa(mmu->pae_root);
3576c50d8ae3SPaolo Bonzini 
3577be01e8e2SSean Christopherson set_root_pgd:
3578b37233c9SSean Christopherson 	mmu->root_pgd = root_pgd;
35794a38162eSPaolo Bonzini out_unlock:
35804a38162eSPaolo Bonzini 	write_unlock(&vcpu->kvm->mmu_lock);
3581c50d8ae3SPaolo Bonzini 
3582c50d8ae3SPaolo Bonzini 	return 0;
3583c50d8ae3SPaolo Bonzini }
3584c50d8ae3SPaolo Bonzini 
3585748e52b9SSean Christopherson static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3586c50d8ae3SPaolo Bonzini {
3587748e52b9SSean Christopherson 	struct kvm_mmu *mmu = vcpu->arch.mmu;
358803ca4589SSean Christopherson 	u64 *pml4_root, *pae_root;
3589748e52b9SSean Christopherson 
3590748e52b9SSean Christopherson 	/*
3591748e52b9SSean Christopherson 	 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3592748e52b9SSean Christopherson 	 * tables are allocated and initialized at root creation as there is no
3593748e52b9SSean Christopherson 	 * equivalent level in the guest's NPT to shadow.  Allocate the tables
3594748e52b9SSean Christopherson 	 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3595748e52b9SSean Christopherson 	 */
3596748e52b9SSean Christopherson 	if (mmu->direct_map || mmu->root_level >= PT64_ROOT_4LEVEL ||
3597748e52b9SSean Christopherson 	    mmu->shadow_root_level < PT64_ROOT_4LEVEL)
3598748e52b9SSean Christopherson 		return 0;
3599748e52b9SSean Christopherson 
3600748e52b9SSean Christopherson 	/*
3601748e52b9SSean Christopherson 	 * This mess only works with 4-level paging and needs to be updated to
3602748e52b9SSean Christopherson 	 * work with 5-level paging.
3603748e52b9SSean Christopherson 	 */
3604748e52b9SSean Christopherson 	if (WARN_ON_ONCE(mmu->shadow_root_level != PT64_ROOT_4LEVEL))
3605748e52b9SSean Christopherson 		return -EIO;
3606748e52b9SSean Christopherson 
360703ca4589SSean Christopherson 	if (mmu->pae_root && mmu->pml4_root)
3608748e52b9SSean Christopherson 		return 0;
3609748e52b9SSean Christopherson 
3610748e52b9SSean Christopherson 	/*
3611748e52b9SSean Christopherson 	 * The special roots should always be allocated in concert.  Yell and
3612748e52b9SSean Christopherson 	 * bail if KVM ends up in a state where only one of the roots is valid.
3613748e52b9SSean Christopherson 	 */
361403ca4589SSean Christopherson 	if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root))
3615748e52b9SSean Christopherson 		return -EIO;
3616748e52b9SSean Christopherson 
36174a98623dSSean Christopherson 	/*
36184a98623dSSean Christopherson 	 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
36194a98623dSSean Christopherson 	 * doesn't need to be decrypted.
36204a98623dSSean Christopherson 	 */
3621748e52b9SSean Christopherson 	pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3622748e52b9SSean Christopherson 	if (!pae_root)
3623748e52b9SSean Christopherson 		return -ENOMEM;
3624748e52b9SSean Christopherson 
362503ca4589SSean Christopherson 	pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
362603ca4589SSean Christopherson 	if (!pml4_root) {
3627748e52b9SSean Christopherson 		free_page((unsigned long)pae_root);
3628748e52b9SSean Christopherson 		return -ENOMEM;
3629748e52b9SSean Christopherson 	}
3630748e52b9SSean Christopherson 
3631748e52b9SSean Christopherson 	mmu->pae_root = pae_root;
363203ca4589SSean Christopherson 	mmu->pml4_root = pml4_root;
3633748e52b9SSean Christopherson 
3634748e52b9SSean Christopherson 	return 0;
3635c50d8ae3SPaolo Bonzini }
3636c50d8ae3SPaolo Bonzini 
3637c50d8ae3SPaolo Bonzini void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3638c50d8ae3SPaolo Bonzini {
3639c50d8ae3SPaolo Bonzini 	int i;
3640c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
3641c50d8ae3SPaolo Bonzini 
3642c50d8ae3SPaolo Bonzini 	if (vcpu->arch.mmu->direct_map)
3643c50d8ae3SPaolo Bonzini 		return;
3644c50d8ae3SPaolo Bonzini 
3645c50d8ae3SPaolo Bonzini 	if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3646c50d8ae3SPaolo Bonzini 		return;
3647c50d8ae3SPaolo Bonzini 
3648c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3649c50d8ae3SPaolo Bonzini 
3650c50d8ae3SPaolo Bonzini 	if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3651c50d8ae3SPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->root_hpa;
3652e47c4aeeSSean Christopherson 		sp = to_shadow_page(root);
3653c50d8ae3SPaolo Bonzini 
3654c50d8ae3SPaolo Bonzini 		/*
3655c50d8ae3SPaolo Bonzini 		 * Even if another CPU was marking the SP as unsync-ed
3656c50d8ae3SPaolo Bonzini 		 * simultaneously, any guest page table changes are not
3657c50d8ae3SPaolo Bonzini 		 * guaranteed to be visible anyway until this VCPU issues a TLB
3658c50d8ae3SPaolo Bonzini 		 * flush strictly after those changes are made. We only need to
3659c50d8ae3SPaolo Bonzini 		 * ensure that the other CPU sets these flags before any actual
3660c50d8ae3SPaolo Bonzini 		 * changes to the page tables are made. The comments in
36610337f585SSean Christopherson 		 * mmu_try_to_unsync_pages() describe what could go wrong if
36620337f585SSean Christopherson 		 * this requirement isn't satisfied.
3663c50d8ae3SPaolo Bonzini 		 */
3664c50d8ae3SPaolo Bonzini 		if (!smp_load_acquire(&sp->unsync) &&
3665c50d8ae3SPaolo Bonzini 		    !smp_load_acquire(&sp->unsync_children))
3666c50d8ae3SPaolo Bonzini 			return;
3667c50d8ae3SPaolo Bonzini 
3668531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
3669c50d8ae3SPaolo Bonzini 		kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3670c50d8ae3SPaolo Bonzini 
3671c50d8ae3SPaolo Bonzini 		mmu_sync_children(vcpu, sp);
3672c50d8ae3SPaolo Bonzini 
3673c50d8ae3SPaolo Bonzini 		kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3674531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
3675c50d8ae3SPaolo Bonzini 		return;
3676c50d8ae3SPaolo Bonzini 	}
3677c50d8ae3SPaolo Bonzini 
3678531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
3679c50d8ae3SPaolo Bonzini 	kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3680c50d8ae3SPaolo Bonzini 
3681c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i) {
3682c50d8ae3SPaolo Bonzini 		hpa_t root = vcpu->arch.mmu->pae_root[i];
3683c50d8ae3SPaolo Bonzini 
3684c834e5e4SSean Christopherson 		if (IS_VALID_PAE_ROOT(root)) {
3685c50d8ae3SPaolo Bonzini 			root &= PT64_BASE_ADDR_MASK;
3686e47c4aeeSSean Christopherson 			sp = to_shadow_page(root);
3687c50d8ae3SPaolo Bonzini 			mmu_sync_children(vcpu, sp);
3688c50d8ae3SPaolo Bonzini 		}
3689c50d8ae3SPaolo Bonzini 	}
3690c50d8ae3SPaolo Bonzini 
3691c50d8ae3SPaolo Bonzini 	kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3692531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
3693c50d8ae3SPaolo Bonzini }
3694c50d8ae3SPaolo Bonzini 
3695736c291cSSean Christopherson static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
3696c50d8ae3SPaolo Bonzini 				  u32 access, struct x86_exception *exception)
3697c50d8ae3SPaolo Bonzini {
3698c50d8ae3SPaolo Bonzini 	if (exception)
3699c50d8ae3SPaolo Bonzini 		exception->error_code = 0;
3700c50d8ae3SPaolo Bonzini 	return vaddr;
3701c50d8ae3SPaolo Bonzini }
3702c50d8ae3SPaolo Bonzini 
3703736c291cSSean Christopherson static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
3704c50d8ae3SPaolo Bonzini 					 u32 access,
3705c50d8ae3SPaolo Bonzini 					 struct x86_exception *exception)
3706c50d8ae3SPaolo Bonzini {
3707c50d8ae3SPaolo Bonzini 	if (exception)
3708c50d8ae3SPaolo Bonzini 		exception->error_code = 0;
3709c50d8ae3SPaolo Bonzini 	return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3710c50d8ae3SPaolo Bonzini }
3711c50d8ae3SPaolo Bonzini 
3712c50d8ae3SPaolo Bonzini static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3713c50d8ae3SPaolo Bonzini {
3714c50d8ae3SPaolo Bonzini 	/*
3715c50d8ae3SPaolo Bonzini 	 * A nested guest cannot use the MMIO cache if it is using nested
3716c50d8ae3SPaolo Bonzini 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3717c50d8ae3SPaolo Bonzini 	 */
3718c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
3719c50d8ae3SPaolo Bonzini 		return false;
3720c50d8ae3SPaolo Bonzini 
3721c50d8ae3SPaolo Bonzini 	if (direct)
3722c50d8ae3SPaolo Bonzini 		return vcpu_match_mmio_gpa(vcpu, addr);
3723c50d8ae3SPaolo Bonzini 
3724c50d8ae3SPaolo Bonzini 	return vcpu_match_mmio_gva(vcpu, addr);
3725c50d8ae3SPaolo Bonzini }
3726c50d8ae3SPaolo Bonzini 
372795fb5b02SBen Gardon /*
372895fb5b02SBen Gardon  * Return the level of the lowest level SPTE added to sptes.
372995fb5b02SBen Gardon  * That SPTE may be non-present.
3730c5c8c7c5SDavid Matlack  *
3731c5c8c7c5SDavid Matlack  * Must be called between walk_shadow_page_lockless_{begin,end}.
373295fb5b02SBen Gardon  */
373339b4d43eSSean Christopherson static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
3734c50d8ae3SPaolo Bonzini {
3735c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
37362aa07893SSean Christopherson 	int leaf = -1;
373795fb5b02SBen Gardon 	u64 spte;
3738c50d8ae3SPaolo Bonzini 
373939b4d43eSSean Christopherson 	for (shadow_walk_init(&iterator, vcpu, addr),
374039b4d43eSSean Christopherson 	     *root_level = iterator.level;
3741c50d8ae3SPaolo Bonzini 	     shadow_walk_okay(&iterator);
3742c50d8ae3SPaolo Bonzini 	     __shadow_walk_next(&iterator, spte)) {
374395fb5b02SBen Gardon 		leaf = iterator.level;
3744c50d8ae3SPaolo Bonzini 		spte = mmu_spte_get_lockless(iterator.sptep);
3745c50d8ae3SPaolo Bonzini 
3746dde81f94SSean Christopherson 		sptes[leaf] = spte;
3747c50d8ae3SPaolo Bonzini 
3748c50d8ae3SPaolo Bonzini 		if (!is_shadow_present_pte(spte))
3749c50d8ae3SPaolo Bonzini 			break;
375095fb5b02SBen Gardon 	}
375195fb5b02SBen Gardon 
375295fb5b02SBen Gardon 	return leaf;
375395fb5b02SBen Gardon }
375495fb5b02SBen Gardon 
37559aa41879SSean Christopherson /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
375695fb5b02SBen Gardon static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
375795fb5b02SBen Gardon {
3758dde81f94SSean Christopherson 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
375995fb5b02SBen Gardon 	struct rsvd_bits_validate *rsvd_check;
376039b4d43eSSean Christopherson 	int root, leaf, level;
376195fb5b02SBen Gardon 	bool reserved = false;
376295fb5b02SBen Gardon 
3763c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_begin(vcpu);
3764c5c8c7c5SDavid Matlack 
376563c0cac9SDavid Matlack 	if (is_tdp_mmu(vcpu->arch.mmu))
376639b4d43eSSean Christopherson 		leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
376795fb5b02SBen Gardon 	else
376839b4d43eSSean Christopherson 		leaf = get_walk(vcpu, addr, sptes, &root);
376995fb5b02SBen Gardon 
3770c5c8c7c5SDavid Matlack 	walk_shadow_page_lockless_end(vcpu);
3771c5c8c7c5SDavid Matlack 
37722aa07893SSean Christopherson 	if (unlikely(leaf < 0)) {
37732aa07893SSean Christopherson 		*sptep = 0ull;
37742aa07893SSean Christopherson 		return reserved;
37752aa07893SSean Christopherson 	}
37762aa07893SSean Christopherson 
37779aa41879SSean Christopherson 	*sptep = sptes[leaf];
37789aa41879SSean Christopherson 
37799aa41879SSean Christopherson 	/*
37809aa41879SSean Christopherson 	 * Skip reserved bits checks on the terminal leaf if it's not a valid
37819aa41879SSean Christopherson 	 * SPTE.  Note, this also (intentionally) skips MMIO SPTEs, which, by
37829aa41879SSean Christopherson 	 * design, always have reserved bits set.  The purpose of the checks is
37839aa41879SSean Christopherson 	 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
37849aa41879SSean Christopherson 	 */
37859aa41879SSean Christopherson 	if (!is_shadow_present_pte(sptes[leaf]))
37869aa41879SSean Christopherson 		leaf++;
378795fb5b02SBen Gardon 
378895fb5b02SBen Gardon 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
378995fb5b02SBen Gardon 
37909aa41879SSean Christopherson 	for (level = root; level >= leaf; level--)
3791961f8445SSean Christopherson 		reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
3792c50d8ae3SPaolo Bonzini 
3793c50d8ae3SPaolo Bonzini 	if (reserved) {
3794bb4cdf3aSSean Christopherson 		pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
3795c50d8ae3SPaolo Bonzini 		       __func__, addr);
379695fb5b02SBen Gardon 		for (level = root; level >= leaf; level--)
3797bb4cdf3aSSean Christopherson 			pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
3798bb4cdf3aSSean Christopherson 			       sptes[level], level,
3799961f8445SSean Christopherson 			       get_rsvd_bits(rsvd_check, sptes[level], level));
3800c50d8ae3SPaolo Bonzini 	}
3801ddce6208SSean Christopherson 
3802c50d8ae3SPaolo Bonzini 	return reserved;
3803c50d8ae3SPaolo Bonzini }
3804c50d8ae3SPaolo Bonzini 
3805c50d8ae3SPaolo Bonzini static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3806c50d8ae3SPaolo Bonzini {
3807c50d8ae3SPaolo Bonzini 	u64 spte;
3808c50d8ae3SPaolo Bonzini 	bool reserved;
3809c50d8ae3SPaolo Bonzini 
3810c50d8ae3SPaolo Bonzini 	if (mmio_info_in_cache(vcpu, addr, direct))
3811c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3812c50d8ae3SPaolo Bonzini 
381395fb5b02SBen Gardon 	reserved = get_mmio_spte(vcpu, addr, &spte);
3814c50d8ae3SPaolo Bonzini 	if (WARN_ON(reserved))
3815c50d8ae3SPaolo Bonzini 		return -EINVAL;
3816c50d8ae3SPaolo Bonzini 
3817c50d8ae3SPaolo Bonzini 	if (is_mmio_spte(spte)) {
3818c50d8ae3SPaolo Bonzini 		gfn_t gfn = get_mmio_spte_gfn(spte);
38190a2b64c5SBen Gardon 		unsigned int access = get_mmio_spte_access(spte);
3820c50d8ae3SPaolo Bonzini 
3821c50d8ae3SPaolo Bonzini 		if (!check_mmio_spte(vcpu, spte))
3822c50d8ae3SPaolo Bonzini 			return RET_PF_INVALID;
3823c50d8ae3SPaolo Bonzini 
3824c50d8ae3SPaolo Bonzini 		if (direct)
3825c50d8ae3SPaolo Bonzini 			addr = 0;
3826c50d8ae3SPaolo Bonzini 
3827c50d8ae3SPaolo Bonzini 		trace_handle_mmio_page_fault(addr, gfn, access);
3828c50d8ae3SPaolo Bonzini 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3829c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3830c50d8ae3SPaolo Bonzini 	}
3831c50d8ae3SPaolo Bonzini 
3832c50d8ae3SPaolo Bonzini 	/*
3833c50d8ae3SPaolo Bonzini 	 * If the page table is zapped by other cpus, let CPU fault again on
3834c50d8ae3SPaolo Bonzini 	 * the address.
3835c50d8ae3SPaolo Bonzini 	 */
3836c50d8ae3SPaolo Bonzini 	return RET_PF_RETRY;
3837c50d8ae3SPaolo Bonzini }
3838c50d8ae3SPaolo Bonzini 
3839c50d8ae3SPaolo Bonzini static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3840c50d8ae3SPaolo Bonzini 					 u32 error_code, gfn_t gfn)
3841c50d8ae3SPaolo Bonzini {
3842c50d8ae3SPaolo Bonzini 	if (unlikely(error_code & PFERR_RSVD_MASK))
3843c50d8ae3SPaolo Bonzini 		return false;
3844c50d8ae3SPaolo Bonzini 
3845c50d8ae3SPaolo Bonzini 	if (!(error_code & PFERR_PRESENT_MASK) ||
3846c50d8ae3SPaolo Bonzini 	      !(error_code & PFERR_WRITE_MASK))
3847c50d8ae3SPaolo Bonzini 		return false;
3848c50d8ae3SPaolo Bonzini 
3849c50d8ae3SPaolo Bonzini 	/*
3850c50d8ae3SPaolo Bonzini 	 * guest is writing the page which is write tracked which can
3851c50d8ae3SPaolo Bonzini 	 * not be fixed by page fault handler.
3852c50d8ae3SPaolo Bonzini 	 */
3853c50d8ae3SPaolo Bonzini 	if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3854c50d8ae3SPaolo Bonzini 		return true;
3855c50d8ae3SPaolo Bonzini 
3856c50d8ae3SPaolo Bonzini 	return false;
3857c50d8ae3SPaolo Bonzini }
3858c50d8ae3SPaolo Bonzini 
3859c50d8ae3SPaolo Bonzini static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3860c50d8ae3SPaolo Bonzini {
3861c50d8ae3SPaolo Bonzini 	struct kvm_shadow_walk_iterator iterator;
3862c50d8ae3SPaolo Bonzini 	u64 spte;
3863c50d8ae3SPaolo Bonzini 
3864c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_begin(vcpu);
3865c50d8ae3SPaolo Bonzini 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
3866c50d8ae3SPaolo Bonzini 		clear_sp_write_flooding_count(iterator.sptep);
3867c50d8ae3SPaolo Bonzini 		if (!is_shadow_present_pte(spte))
3868c50d8ae3SPaolo Bonzini 			break;
3869c50d8ae3SPaolo Bonzini 	}
3870c50d8ae3SPaolo Bonzini 	walk_shadow_page_lockless_end(vcpu);
3871c50d8ae3SPaolo Bonzini }
3872c50d8ae3SPaolo Bonzini 
3873e8c22266SVitaly Kuznetsov static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
38749f1a8526SSean Christopherson 				    gfn_t gfn)
3875c50d8ae3SPaolo Bonzini {
3876c50d8ae3SPaolo Bonzini 	struct kvm_arch_async_pf arch;
3877c50d8ae3SPaolo Bonzini 
3878c50d8ae3SPaolo Bonzini 	arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
3879c50d8ae3SPaolo Bonzini 	arch.gfn = gfn;
3880c50d8ae3SPaolo Bonzini 	arch.direct_map = vcpu->arch.mmu->direct_map;
3881d8dd54e0SSean Christopherson 	arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
3882c50d8ae3SPaolo Bonzini 
38839f1a8526SSean Christopherson 	return kvm_setup_async_pf(vcpu, cr2_or_gpa,
38849f1a8526SSean Christopherson 				  kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
3885c50d8ae3SPaolo Bonzini }
3886c50d8ae3SPaolo Bonzini 
3887c50d8ae3SPaolo Bonzini static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
38884a42d848SDavid Stevens 			 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, hva_t *hva,
38894a42d848SDavid Stevens 			 bool write, bool *writable)
3890c50d8ae3SPaolo Bonzini {
3891c36b7150SPaolo Bonzini 	struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3892c50d8ae3SPaolo Bonzini 	bool async;
3893c50d8ae3SPaolo Bonzini 
3894e0c37868SSean Christopherson 	/*
3895e0c37868SSean Christopherson 	 * Retry the page fault if the gfn hit a memslot that is being deleted
3896e0c37868SSean Christopherson 	 * or moved.  This ensures any existing SPTEs for the old memslot will
3897e0c37868SSean Christopherson 	 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
3898e0c37868SSean Christopherson 	 */
3899e0c37868SSean Christopherson 	if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
3900e0c37868SSean Christopherson 		return true;
3901e0c37868SSean Christopherson 
3902c36b7150SPaolo Bonzini 	/* Don't expose private memslots to L2. */
3903c36b7150SPaolo Bonzini 	if (is_guest_mode(vcpu) && !kvm_is_visible_memslot(slot)) {
3904c50d8ae3SPaolo Bonzini 		*pfn = KVM_PFN_NOSLOT;
3905c583eed6SSean Christopherson 		*writable = false;
3906c50d8ae3SPaolo Bonzini 		return false;
3907c50d8ae3SPaolo Bonzini 	}
3908c50d8ae3SPaolo Bonzini 
3909c50d8ae3SPaolo Bonzini 	async = false;
39104a42d848SDavid Stevens 	*pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async,
39114a42d848SDavid Stevens 				    write, writable, hva);
3912c50d8ae3SPaolo Bonzini 	if (!async)
3913c50d8ae3SPaolo Bonzini 		return false; /* *pfn has correct page already */
3914c50d8ae3SPaolo Bonzini 
3915c50d8ae3SPaolo Bonzini 	if (!prefault && kvm_can_do_async_pf(vcpu)) {
39169f1a8526SSean Christopherson 		trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
3917c50d8ae3SPaolo Bonzini 		if (kvm_find_async_pf_gfn(vcpu, gfn)) {
39189f1a8526SSean Christopherson 			trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
3919c50d8ae3SPaolo Bonzini 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
3920c50d8ae3SPaolo Bonzini 			return true;
39219f1a8526SSean Christopherson 		} else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
3922c50d8ae3SPaolo Bonzini 			return true;
3923c50d8ae3SPaolo Bonzini 	}
3924c50d8ae3SPaolo Bonzini 
39254a42d848SDavid Stevens 	*pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL,
39264a42d848SDavid Stevens 				    write, writable, hva);
3927c50d8ae3SPaolo Bonzini 	return false;
3928c50d8ae3SPaolo Bonzini }
3929c50d8ae3SPaolo Bonzini 
39300f90e1c1SSean Christopherson static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
39310f90e1c1SSean Christopherson 			     bool prefault, int max_level, bool is_tdp)
3932c50d8ae3SPaolo Bonzini {
393363c0cac9SDavid Matlack 	bool is_tdp_mmu_fault = is_tdp_mmu(vcpu->arch.mmu);
3934367fd790SSean Christopherson 	bool write = error_code & PFERR_WRITE_MASK;
39350f90e1c1SSean Christopherson 	bool map_writable;
3936c50d8ae3SPaolo Bonzini 
39370f90e1c1SSean Christopherson 	gfn_t gfn = gpa >> PAGE_SHIFT;
39380f90e1c1SSean Christopherson 	unsigned long mmu_seq;
39390f90e1c1SSean Christopherson 	kvm_pfn_t pfn;
39404a42d848SDavid Stevens 	hva_t hva;
394183f06fa7SSean Christopherson 	int r;
3942c50d8ae3SPaolo Bonzini 
3943c50d8ae3SPaolo Bonzini 	if (page_fault_handle_page_track(vcpu, error_code, gfn))
3944c50d8ae3SPaolo Bonzini 		return RET_PF_EMULATE;
3945c50d8ae3SPaolo Bonzini 
3946c4371c2aSSean Christopherson 	r = fast_page_fault(vcpu, gpa, error_code);
3947c4371c2aSSean Christopherson 	if (r != RET_PF_INVALID)
3948c4371c2aSSean Christopherson 		return r;
394983291445SSean Christopherson 
3950378f5cd6SSean Christopherson 	r = mmu_topup_memory_caches(vcpu, false);
3951c50d8ae3SPaolo Bonzini 	if (r)
3952c50d8ae3SPaolo Bonzini 		return r;
3953c50d8ae3SPaolo Bonzini 
3954367fd790SSean Christopherson 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
3955367fd790SSean Christopherson 	smp_rmb();
3956367fd790SSean Christopherson 
39574a42d848SDavid Stevens 	if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, &hva,
39584a42d848SDavid Stevens 			 write, &map_writable))
3959367fd790SSean Christopherson 		return RET_PF_RETRY;
3960367fd790SSean Christopherson 
39610f90e1c1SSean Christopherson 	if (handle_abnormal_pfn(vcpu, is_tdp ? 0 : gpa, gfn, pfn, ACC_ALL, &r))
3962367fd790SSean Christopherson 		return r;
3963367fd790SSean Christopherson 
3964367fd790SSean Christopherson 	r = RET_PF_RETRY;
3965a2855afcSBen Gardon 
39660b873fd7SDavid Matlack 	if (is_tdp_mmu_fault)
3967a2855afcSBen Gardon 		read_lock(&vcpu->kvm->mmu_lock);
3968a2855afcSBen Gardon 	else
3969531810caSBen Gardon 		write_lock(&vcpu->kvm->mmu_lock);
3970a2855afcSBen Gardon 
39714a42d848SDavid Stevens 	if (!is_noslot_pfn(pfn) && mmu_notifier_retry_hva(vcpu->kvm, mmu_seq, hva))
3972367fd790SSean Christopherson 		goto out_unlock;
39737bd7ded6SSean Christopherson 	r = make_mmu_pages_available(vcpu);
39747bd7ded6SSean Christopherson 	if (r)
3975367fd790SSean Christopherson 		goto out_unlock;
3976bb18842eSBen Gardon 
39770b873fd7SDavid Matlack 	if (is_tdp_mmu_fault)
3978bb18842eSBen Gardon 		r = kvm_tdp_mmu_map(vcpu, gpa, error_code, map_writable, max_level,
3979bb18842eSBen Gardon 				    pfn, prefault);
3980bb18842eSBen Gardon 	else
39816c2fd34fSSean Christopherson 		r = __direct_map(vcpu, gpa, error_code, map_writable, max_level, pfn,
39826c2fd34fSSean Christopherson 				 prefault, is_tdp);
39830f90e1c1SSean Christopherson 
3984367fd790SSean Christopherson out_unlock:
39850b873fd7SDavid Matlack 	if (is_tdp_mmu_fault)
3986a2855afcSBen Gardon 		read_unlock(&vcpu->kvm->mmu_lock);
3987a2855afcSBen Gardon 	else
3988531810caSBen Gardon 		write_unlock(&vcpu->kvm->mmu_lock);
3989367fd790SSean Christopherson 	kvm_release_pfn_clean(pfn);
3990367fd790SSean Christopherson 	return r;
3991c50d8ae3SPaolo Bonzini }
3992c50d8ae3SPaolo Bonzini 
39930f90e1c1SSean Christopherson static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
39940f90e1c1SSean Christopherson 				u32 error_code, bool prefault)
39950f90e1c1SSean Christopherson {
39960f90e1c1SSean Christopherson 	pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
39970f90e1c1SSean Christopherson 
39980f90e1c1SSean Christopherson 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
39990f90e1c1SSean Christopherson 	return direct_page_fault(vcpu, gpa & PAGE_MASK, error_code, prefault,
40003bae0459SSean Christopherson 				 PG_LEVEL_2M, false);
40010f90e1c1SSean Christopherson }
40020f90e1c1SSean Christopherson 
4003c50d8ae3SPaolo Bonzini int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4004c50d8ae3SPaolo Bonzini 				u64 fault_address, char *insn, int insn_len)
4005c50d8ae3SPaolo Bonzini {
4006c50d8ae3SPaolo Bonzini 	int r = 1;
40079ce372b3SVitaly Kuznetsov 	u32 flags = vcpu->arch.apf.host_apf_flags;
4008c50d8ae3SPaolo Bonzini 
4009736c291cSSean Christopherson #ifndef CONFIG_X86_64
4010736c291cSSean Christopherson 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4011736c291cSSean Christopherson 	if (WARN_ON_ONCE(fault_address >> 32))
4012736c291cSSean Christopherson 		return -EFAULT;
4013736c291cSSean Christopherson #endif
4014736c291cSSean Christopherson 
4015c50d8ae3SPaolo Bonzini 	vcpu->arch.l1tf_flush_l1d = true;
40169ce372b3SVitaly Kuznetsov 	if (!flags) {
4017c50d8ae3SPaolo Bonzini 		trace_kvm_page_fault(fault_address, error_code);
4018c50d8ae3SPaolo Bonzini 
4019c50d8ae3SPaolo Bonzini 		if (kvm_event_needs_reinjection(vcpu))
4020c50d8ae3SPaolo Bonzini 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4021c50d8ae3SPaolo Bonzini 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4022c50d8ae3SPaolo Bonzini 				insn_len);
40239ce372b3SVitaly Kuznetsov 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
402468fd66f1SVitaly Kuznetsov 		vcpu->arch.apf.host_apf_flags = 0;
4025c50d8ae3SPaolo Bonzini 		local_irq_disable();
40266bca69adSThomas Gleixner 		kvm_async_pf_task_wait_schedule(fault_address);
4027c50d8ae3SPaolo Bonzini 		local_irq_enable();
40289ce372b3SVitaly Kuznetsov 	} else {
40299ce372b3SVitaly Kuznetsov 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4030c50d8ae3SPaolo Bonzini 	}
40319ce372b3SVitaly Kuznetsov 
4032c50d8ae3SPaolo Bonzini 	return r;
4033c50d8ae3SPaolo Bonzini }
4034c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4035c50d8ae3SPaolo Bonzini 
40367a02674dSSean Christopherson int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4037c50d8ae3SPaolo Bonzini 		       bool prefault)
4038c50d8ae3SPaolo Bonzini {
4039cb9b88c6SSean Christopherson 	int max_level;
4040c50d8ae3SPaolo Bonzini 
4041e662ec3eSSean Christopherson 	for (max_level = KVM_MAX_HUGEPAGE_LEVEL;
40423bae0459SSean Christopherson 	     max_level > PG_LEVEL_4K;
4043cb9b88c6SSean Christopherson 	     max_level--) {
4044cb9b88c6SSean Christopherson 		int page_num = KVM_PAGES_PER_HPAGE(max_level);
40450f90e1c1SSean Christopherson 		gfn_t base = (gpa >> PAGE_SHIFT) & ~(page_num - 1);
4046c50d8ae3SPaolo Bonzini 
4047cb9b88c6SSean Christopherson 		if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4048cb9b88c6SSean Christopherson 			break;
4049c50d8ae3SPaolo Bonzini 	}
4050c50d8ae3SPaolo Bonzini 
40510f90e1c1SSean Christopherson 	return direct_page_fault(vcpu, gpa, error_code, prefault,
40520f90e1c1SSean Christopherson 				 max_level, true);
4053c50d8ae3SPaolo Bonzini }
4054c50d8ae3SPaolo Bonzini 
405584a16226SSean Christopherson static void nonpaging_init_context(struct kvm_mmu *context)
4056c50d8ae3SPaolo Bonzini {
4057c50d8ae3SPaolo Bonzini 	context->page_fault = nonpaging_page_fault;
4058c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4059c50d8ae3SPaolo Bonzini 	context->sync_page = nonpaging_sync_page;
40605efac074SPaolo Bonzini 	context->invlpg = NULL;
4061c50d8ae3SPaolo Bonzini 	context->direct_map = true;
4062c50d8ae3SPaolo Bonzini }
4063c50d8ae3SPaolo Bonzini 
4064be01e8e2SSean Christopherson static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
40650be44352SSean Christopherson 				  union kvm_mmu_page_role role)
40660be44352SSean Christopherson {
4067be01e8e2SSean Christopherson 	return (role.direct || pgd == root->pgd) &&
4068e47c4aeeSSean Christopherson 	       VALID_PAGE(root->hpa) && to_shadow_page(root->hpa) &&
4069e47c4aeeSSean Christopherson 	       role.word == to_shadow_page(root->hpa)->role.word;
40700be44352SSean Christopherson }
40710be44352SSean Christopherson 
4072c50d8ae3SPaolo Bonzini /*
4073be01e8e2SSean Christopherson  * Find out if a previously cached root matching the new pgd/role is available.
4074c50d8ae3SPaolo Bonzini  * The current root is also inserted into the cache.
4075c50d8ae3SPaolo Bonzini  * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4076c50d8ae3SPaolo Bonzini  * returned.
4077c50d8ae3SPaolo Bonzini  * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4078c50d8ae3SPaolo Bonzini  * false is returned. This root should now be freed by the caller.
4079c50d8ae3SPaolo Bonzini  */
4080be01e8e2SSean Christopherson static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4081c50d8ae3SPaolo Bonzini 				  union kvm_mmu_page_role new_role)
4082c50d8ae3SPaolo Bonzini {
4083c50d8ae3SPaolo Bonzini 	uint i;
4084c50d8ae3SPaolo Bonzini 	struct kvm_mmu_root_info root;
4085c50d8ae3SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
4086c50d8ae3SPaolo Bonzini 
4087be01e8e2SSean Christopherson 	root.pgd = mmu->root_pgd;
4088c50d8ae3SPaolo Bonzini 	root.hpa = mmu->root_hpa;
4089c50d8ae3SPaolo Bonzini 
4090be01e8e2SSean Christopherson 	if (is_root_usable(&root, new_pgd, new_role))
40910be44352SSean Christopherson 		return true;
40920be44352SSean Christopherson 
4093c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4094c50d8ae3SPaolo Bonzini 		swap(root, mmu->prev_roots[i]);
4095c50d8ae3SPaolo Bonzini 
4096be01e8e2SSean Christopherson 		if (is_root_usable(&root, new_pgd, new_role))
4097c50d8ae3SPaolo Bonzini 			break;
4098c50d8ae3SPaolo Bonzini 	}
4099c50d8ae3SPaolo Bonzini 
4100c50d8ae3SPaolo Bonzini 	mmu->root_hpa = root.hpa;
4101be01e8e2SSean Christopherson 	mmu->root_pgd = root.pgd;
4102c50d8ae3SPaolo Bonzini 
4103c50d8ae3SPaolo Bonzini 	return i < KVM_MMU_NUM_PREV_ROOTS;
4104c50d8ae3SPaolo Bonzini }
4105c50d8ae3SPaolo Bonzini 
4106be01e8e2SSean Christopherson static bool fast_pgd_switch(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4107b869855bSSean Christopherson 			    union kvm_mmu_page_role new_role)
4108c50d8ae3SPaolo Bonzini {
4109c50d8ae3SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
4110c50d8ae3SPaolo Bonzini 
4111c50d8ae3SPaolo Bonzini 	/*
4112c50d8ae3SPaolo Bonzini 	 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4113c50d8ae3SPaolo Bonzini 	 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4114c50d8ae3SPaolo Bonzini 	 * later if necessary.
4115c50d8ae3SPaolo Bonzini 	 */
4116c50d8ae3SPaolo Bonzini 	if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4117b869855bSSean Christopherson 	    mmu->root_level >= PT64_ROOT_4LEVEL)
4118fe9304d3SVitaly Kuznetsov 		return cached_root_available(vcpu, new_pgd, new_role);
4119c50d8ae3SPaolo Bonzini 
4120c50d8ae3SPaolo Bonzini 	return false;
4121c50d8ae3SPaolo Bonzini }
4122c50d8ae3SPaolo Bonzini 
4123be01e8e2SSean Christopherson static void __kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4124b5129100SSean Christopherson 			      union kvm_mmu_page_role new_role)
4125c50d8ae3SPaolo Bonzini {
4126be01e8e2SSean Christopherson 	if (!fast_pgd_switch(vcpu, new_pgd, new_role)) {
4127b869855bSSean Christopherson 		kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, KVM_MMU_ROOT_CURRENT);
4128b869855bSSean Christopherson 		return;
4129c50d8ae3SPaolo Bonzini 	}
4130c50d8ae3SPaolo Bonzini 
4131c50d8ae3SPaolo Bonzini 	/*
4132b869855bSSean Christopherson 	 * It's possible that the cached previous root page is obsolete because
4133b869855bSSean Christopherson 	 * of a change in the MMU generation number. However, changing the
4134b869855bSSean Christopherson 	 * generation number is accompanied by KVM_REQ_MMU_RELOAD, which will
4135b869855bSSean Christopherson 	 * free the root set here and allocate a new one.
4136b869855bSSean Christopherson 	 */
4137b869855bSSean Christopherson 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4138b869855bSSean Christopherson 
4139b5129100SSean Christopherson 	if (force_flush_and_sync_on_reuse) {
4140b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4141b869855bSSean Christopherson 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4142b5129100SSean Christopherson 	}
4143b869855bSSean Christopherson 
4144b869855bSSean Christopherson 	/*
4145b869855bSSean Christopherson 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4146b869855bSSean Christopherson 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
4147b869855bSSean Christopherson 	 * valid. So clear any cached MMIO info even when we don't need to sync
4148b869855bSSean Christopherson 	 * the shadow page tables.
4149c50d8ae3SPaolo Bonzini 	 */
4150c50d8ae3SPaolo Bonzini 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4151c50d8ae3SPaolo Bonzini 
4152daa5b6c1SBen Gardon 	/*
4153daa5b6c1SBen Gardon 	 * If this is a direct root page, it doesn't have a write flooding
4154daa5b6c1SBen Gardon 	 * count. Otherwise, clear the write flooding count.
4155daa5b6c1SBen Gardon 	 */
4156daa5b6c1SBen Gardon 	if (!new_role.direct)
4157daa5b6c1SBen Gardon 		__clear_sp_write_flooding_count(
4158daa5b6c1SBen Gardon 				to_shadow_page(vcpu->arch.mmu->root_hpa));
4159c50d8ae3SPaolo Bonzini }
4160c50d8ae3SPaolo Bonzini 
4161b5129100SSean Christopherson void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4162c50d8ae3SPaolo Bonzini {
4163b5129100SSean Christopherson 	__kvm_mmu_new_pgd(vcpu, new_pgd, kvm_mmu_calc_root_page_role(vcpu));
4164c50d8ae3SPaolo Bonzini }
4165be01e8e2SSean Christopherson EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4166c50d8ae3SPaolo Bonzini 
4167c50d8ae3SPaolo Bonzini static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4168c50d8ae3SPaolo Bonzini {
4169c50d8ae3SPaolo Bonzini 	return kvm_read_cr3(vcpu);
4170c50d8ae3SPaolo Bonzini }
4171c50d8ae3SPaolo Bonzini 
4172c50d8ae3SPaolo Bonzini static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
41730a2b64c5SBen Gardon 			   unsigned int access, int *nr_present)
4174c50d8ae3SPaolo Bonzini {
4175c50d8ae3SPaolo Bonzini 	if (unlikely(is_mmio_spte(*sptep))) {
4176c50d8ae3SPaolo Bonzini 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4177c50d8ae3SPaolo Bonzini 			mmu_spte_clear_no_track(sptep);
4178c50d8ae3SPaolo Bonzini 			return true;
4179c50d8ae3SPaolo Bonzini 		}
4180c50d8ae3SPaolo Bonzini 
4181c50d8ae3SPaolo Bonzini 		(*nr_present)++;
4182c50d8ae3SPaolo Bonzini 		mark_mmio_spte(vcpu, sptep, gfn, access);
4183c50d8ae3SPaolo Bonzini 		return true;
4184c50d8ae3SPaolo Bonzini 	}
4185c50d8ae3SPaolo Bonzini 
4186c50d8ae3SPaolo Bonzini 	return false;
4187c50d8ae3SPaolo Bonzini }
4188c50d8ae3SPaolo Bonzini 
4189c50d8ae3SPaolo Bonzini #define PTTYPE_EPT 18 /* arbitrary */
4190c50d8ae3SPaolo Bonzini #define PTTYPE PTTYPE_EPT
4191c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4192c50d8ae3SPaolo Bonzini #undef PTTYPE
4193c50d8ae3SPaolo Bonzini 
4194c50d8ae3SPaolo Bonzini #define PTTYPE 64
4195c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4196c50d8ae3SPaolo Bonzini #undef PTTYPE
4197c50d8ae3SPaolo Bonzini 
4198c50d8ae3SPaolo Bonzini #define PTTYPE 32
4199c50d8ae3SPaolo Bonzini #include "paging_tmpl.h"
4200c50d8ae3SPaolo Bonzini #undef PTTYPE
4201c50d8ae3SPaolo Bonzini 
4202c50d8ae3SPaolo Bonzini static void
4203b705a277SSean Christopherson __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
42045b7f575cSSean Christopherson 			u64 pa_bits_rsvd, int level, bool nx, bool gbpages,
4205c50d8ae3SPaolo Bonzini 			bool pse, bool amd)
4206c50d8ae3SPaolo Bonzini {
4207c50d8ae3SPaolo Bonzini 	u64 gbpages_bit_rsvd = 0;
4208c50d8ae3SPaolo Bonzini 	u64 nonleaf_bit8_rsvd = 0;
42095b7f575cSSean Christopherson 	u64 high_bits_rsvd;
4210c50d8ae3SPaolo Bonzini 
4211c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = 0;
4212c50d8ae3SPaolo Bonzini 
4213c50d8ae3SPaolo Bonzini 	if (!gbpages)
4214c50d8ae3SPaolo Bonzini 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4215c50d8ae3SPaolo Bonzini 
42165b7f575cSSean Christopherson 	if (level == PT32E_ROOT_LEVEL)
42175b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
42185b7f575cSSean Christopherson 	else
42195b7f575cSSean Christopherson 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
42205b7f575cSSean Christopherson 
42215b7f575cSSean Christopherson 	/* Note, NX doesn't exist in PDPTEs, this is handled below. */
42225b7f575cSSean Christopherson 	if (!nx)
42235b7f575cSSean Christopherson 		high_bits_rsvd |= rsvd_bits(63, 63);
42245b7f575cSSean Christopherson 
4225c50d8ae3SPaolo Bonzini 	/*
4226c50d8ae3SPaolo Bonzini 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4227c50d8ae3SPaolo Bonzini 	 * leaf entries) on AMD CPUs only.
4228c50d8ae3SPaolo Bonzini 	 */
4229c50d8ae3SPaolo Bonzini 	if (amd)
4230c50d8ae3SPaolo Bonzini 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4231c50d8ae3SPaolo Bonzini 
4232c50d8ae3SPaolo Bonzini 	switch (level) {
4233c50d8ae3SPaolo Bonzini 	case PT32_ROOT_LEVEL:
4234c50d8ae3SPaolo Bonzini 		/* no rsvd bits for 2 level 4K page table entries */
4235c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4236c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4237c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4238c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4239c50d8ae3SPaolo Bonzini 
4240c50d8ae3SPaolo Bonzini 		if (!pse) {
4241c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4242c50d8ae3SPaolo Bonzini 			break;
4243c50d8ae3SPaolo Bonzini 		}
4244c50d8ae3SPaolo Bonzini 
4245c50d8ae3SPaolo Bonzini 		if (is_cpuid_PSE36())
4246c50d8ae3SPaolo Bonzini 			/* 36bits PSE 4MB page */
4247c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4248c50d8ae3SPaolo Bonzini 		else
4249c50d8ae3SPaolo Bonzini 			/* 32 bits PSE 4MB page */
4250c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4251c50d8ae3SPaolo Bonzini 		break;
4252c50d8ae3SPaolo Bonzini 	case PT32E_ROOT_LEVEL:
42535b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
42545b7f575cSSean Christopherson 						   high_bits_rsvd |
42555b7f575cSSean Christopherson 						   rsvd_bits(5, 8) |
42565b7f575cSSean Christopherson 						   rsvd_bits(1, 2);	/* PDPTE */
42575b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;	/* PDE */
42585b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;	/* PTE */
42595b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4260c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20);	/* large page */
4261c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4262c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4263c50d8ae3SPaolo Bonzini 		break;
4264c50d8ae3SPaolo Bonzini 	case PT64_ROOT_5LEVEL:
42655b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
42665b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
42675b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
4268c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][4] =
4269c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][4];
4270df561f66SGustavo A. R. Silva 		fallthrough;
4271c50d8ae3SPaolo Bonzini 	case PT64_ROOT_4LEVEL:
42725b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
42735b7f575cSSean Christopherson 						   nonleaf_bit8_rsvd |
42745b7f575cSSean Christopherson 						   rsvd_bits(7, 7);
42755b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
42765b7f575cSSean Christopherson 						   gbpages_bit_rsvd;
42775b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
42785b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4279c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][3] =
4280c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][3];
42815b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
42825b7f575cSSean Christopherson 						   gbpages_bit_rsvd |
4283c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 29);
42845b7f575cSSean Christopherson 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4285c50d8ae3SPaolo Bonzini 						   rsvd_bits(13, 20); /* large page */
4286c50d8ae3SPaolo Bonzini 		rsvd_check->rsvd_bits_mask[1][0] =
4287c50d8ae3SPaolo Bonzini 			rsvd_check->rsvd_bits_mask[0][0];
4288c50d8ae3SPaolo Bonzini 		break;
4289c50d8ae3SPaolo Bonzini 	}
4290c50d8ae3SPaolo Bonzini }
4291c50d8ae3SPaolo Bonzini 
429227de9250SSean Christopherson static bool guest_can_use_gbpages(struct kvm_vcpu *vcpu)
429327de9250SSean Christopherson {
429427de9250SSean Christopherson 	/*
429527de9250SSean Christopherson 	 * If TDP is enabled, let the guest use GBPAGES if they're supported in
429627de9250SSean Christopherson 	 * hardware.  The hardware page walker doesn't let KVM disable GBPAGES,
429727de9250SSean Christopherson 	 * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
429827de9250SSean Christopherson 	 * walk for performance and complexity reasons.  Not to mention KVM
429927de9250SSean Christopherson 	 * _can't_ solve the problem because GVA->GPA walks aren't visible to
430027de9250SSean Christopherson 	 * KVM once a TDP translation is installed.  Mimic hardware behavior so
430127de9250SSean Christopherson 	 * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
430227de9250SSean Christopherson 	 */
430327de9250SSean Christopherson 	return tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
430427de9250SSean Christopherson 			     guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES);
430527de9250SSean Christopherson }
430627de9250SSean Christopherson 
4307c50d8ae3SPaolo Bonzini static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4308c50d8ae3SPaolo Bonzini 				  struct kvm_mmu *context)
4309c50d8ae3SPaolo Bonzini {
4310b705a277SSean Christopherson 	__reset_rsvds_bits_mask(&context->guest_rsvd_check,
43115b7f575cSSean Christopherson 				vcpu->arch.reserved_gpa_bits,
431290599c28SSean Christopherson 				context->root_level, is_efer_nx(context),
431327de9250SSean Christopherson 				guest_can_use_gbpages(vcpu),
43144e9c0d80SSean Christopherson 				is_cr4_pse(context),
431523493d0aSSean Christopherson 				guest_cpuid_is_amd_or_hygon(vcpu));
4316c50d8ae3SPaolo Bonzini }
4317c50d8ae3SPaolo Bonzini 
4318c50d8ae3SPaolo Bonzini static void
4319c50d8ae3SPaolo Bonzini __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
43205b7f575cSSean Christopherson 			    u64 pa_bits_rsvd, bool execonly)
4321c50d8ae3SPaolo Bonzini {
43225b7f575cSSean Christopherson 	u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
4323c50d8ae3SPaolo Bonzini 	u64 bad_mt_xwr;
4324c50d8ae3SPaolo Bonzini 
43255b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
43265b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
43275b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6);
43285b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6);
43295b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4330c50d8ae3SPaolo Bonzini 
4331c50d8ae3SPaolo Bonzini 	/* large page */
4332c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4333c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
43345b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29);
43355b7f575cSSean Christopherson 	rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20);
4336c50d8ae3SPaolo Bonzini 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4337c50d8ae3SPaolo Bonzini 
4338c50d8ae3SPaolo Bonzini 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
4339c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
4340c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
4341c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
4342c50d8ae3SPaolo Bonzini 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
4343c50d8ae3SPaolo Bonzini 	if (!execonly) {
4344c50d8ae3SPaolo Bonzini 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
4345c50d8ae3SPaolo Bonzini 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4346c50d8ae3SPaolo Bonzini 	}
4347c50d8ae3SPaolo Bonzini 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
4348c50d8ae3SPaolo Bonzini }
4349c50d8ae3SPaolo Bonzini 
4350c50d8ae3SPaolo Bonzini static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4351c50d8ae3SPaolo Bonzini 		struct kvm_mmu *context, bool execonly)
4352c50d8ae3SPaolo Bonzini {
4353c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
43545b7f575cSSean Christopherson 				    vcpu->arch.reserved_gpa_bits, execonly);
4355c50d8ae3SPaolo Bonzini }
4356c50d8ae3SPaolo Bonzini 
43576f8e65a6SSean Christopherson static inline u64 reserved_hpa_bits(void)
43586f8e65a6SSean Christopherson {
43596f8e65a6SSean Christopherson 	return rsvd_bits(shadow_phys_bits, 63);
43606f8e65a6SSean Christopherson }
43616f8e65a6SSean Christopherson 
4362c50d8ae3SPaolo Bonzini /*
4363c50d8ae3SPaolo Bonzini  * the page table on host is the shadow page table for the page
4364c50d8ae3SPaolo Bonzini  * table in guest or amd nested guest, its mmu features completely
4365c50d8ae3SPaolo Bonzini  * follow the features in guest.
4366c50d8ae3SPaolo Bonzini  */
436716be1d12SSean Christopherson static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
436816be1d12SSean Christopherson 					struct kvm_mmu *context)
4369c50d8ae3SPaolo Bonzini {
4370112022bdSSean Christopherson 	/*
4371112022bdSSean Christopherson 	 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
4372112022bdSSean Christopherson 	 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
4373112022bdSSean Christopherson 	 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
4374112022bdSSean Christopherson 	 * The iTLB multi-hit workaround can be toggled at any time, so assume
4375112022bdSSean Christopherson 	 * NX can be used by any non-nested shadow MMU to avoid having to reset
4376112022bdSSean Christopherson 	 * MMU contexts.  Note, KVM forces EFER.NX=1 when TDP is disabled.
4377112022bdSSean Christopherson 	 */
437890599c28SSean Christopherson 	bool uses_nx = is_efer_nx(context) || !tdp_enabled;
43798c985b2dSSean Christopherson 
43808c985b2dSSean Christopherson 	/* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
43818c985b2dSSean Christopherson 	bool is_amd = true;
43828c985b2dSSean Christopherson 	/* KVM doesn't use 2-level page tables for the shadow MMU. */
43838c985b2dSSean Christopherson 	bool is_pse = false;
4384c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4385c50d8ae3SPaolo Bonzini 	int i;
4386c50d8ae3SPaolo Bonzini 
43878c985b2dSSean Christopherson 	WARN_ON_ONCE(context->shadow_root_level < PT32E_ROOT_LEVEL);
43888c985b2dSSean Christopherson 
4389c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4390b705a277SSean Christopherson 	__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4391c50d8ae3SPaolo Bonzini 				context->shadow_root_level, uses_nx,
439227de9250SSean Christopherson 				guest_can_use_gbpages(vcpu), is_pse, is_amd);
4393c50d8ae3SPaolo Bonzini 
4394c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4395c50d8ae3SPaolo Bonzini 		return;
4396c50d8ae3SPaolo Bonzini 
4397c50d8ae3SPaolo Bonzini 	for (i = context->shadow_root_level; --i >= 0;) {
4398c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4399c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4400c50d8ae3SPaolo Bonzini 	}
4401c50d8ae3SPaolo Bonzini 
4402c50d8ae3SPaolo Bonzini }
4403c50d8ae3SPaolo Bonzini 
4404c50d8ae3SPaolo Bonzini static inline bool boot_cpu_is_amd(void)
4405c50d8ae3SPaolo Bonzini {
4406c50d8ae3SPaolo Bonzini 	WARN_ON_ONCE(!tdp_enabled);
4407c50d8ae3SPaolo Bonzini 	return shadow_x_mask == 0;
4408c50d8ae3SPaolo Bonzini }
4409c50d8ae3SPaolo Bonzini 
4410c50d8ae3SPaolo Bonzini /*
4411c50d8ae3SPaolo Bonzini  * the direct page table on host, use as much mmu features as
4412c50d8ae3SPaolo Bonzini  * possible, however, kvm currently does not do execution-protection.
4413c50d8ae3SPaolo Bonzini  */
4414c50d8ae3SPaolo Bonzini static void
4415c50d8ae3SPaolo Bonzini reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4416c50d8ae3SPaolo Bonzini 				struct kvm_mmu *context)
4417c50d8ae3SPaolo Bonzini {
4418c50d8ae3SPaolo Bonzini 	struct rsvd_bits_validate *shadow_zero_check;
4419c50d8ae3SPaolo Bonzini 	int i;
4420c50d8ae3SPaolo Bonzini 
4421c50d8ae3SPaolo Bonzini 	shadow_zero_check = &context->shadow_zero_check;
4422c50d8ae3SPaolo Bonzini 
4423c50d8ae3SPaolo Bonzini 	if (boot_cpu_is_amd())
4424b705a277SSean Christopherson 		__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4425c50d8ae3SPaolo Bonzini 					context->shadow_root_level, false,
4426c50d8ae3SPaolo Bonzini 					boot_cpu_has(X86_FEATURE_GBPAGES),
44278c985b2dSSean Christopherson 					false, true);
4428c50d8ae3SPaolo Bonzini 	else
4429c50d8ae3SPaolo Bonzini 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
44306f8e65a6SSean Christopherson 					    reserved_hpa_bits(), false);
4431c50d8ae3SPaolo Bonzini 
4432c50d8ae3SPaolo Bonzini 	if (!shadow_me_mask)
4433c50d8ae3SPaolo Bonzini 		return;
4434c50d8ae3SPaolo Bonzini 
4435c50d8ae3SPaolo Bonzini 	for (i = context->shadow_root_level; --i >= 0;) {
4436c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4437c50d8ae3SPaolo Bonzini 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4438c50d8ae3SPaolo Bonzini 	}
4439c50d8ae3SPaolo Bonzini }
4440c50d8ae3SPaolo Bonzini 
4441c50d8ae3SPaolo Bonzini /*
4442c50d8ae3SPaolo Bonzini  * as the comments in reset_shadow_zero_bits_mask() except it
4443c50d8ae3SPaolo Bonzini  * is the shadow page table for intel nested guest.
4444c50d8ae3SPaolo Bonzini  */
4445c50d8ae3SPaolo Bonzini static void
4446c50d8ae3SPaolo Bonzini reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4447c50d8ae3SPaolo Bonzini 				struct kvm_mmu *context, bool execonly)
4448c50d8ae3SPaolo Bonzini {
4449c50d8ae3SPaolo Bonzini 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
44506f8e65a6SSean Christopherson 				    reserved_hpa_bits(), execonly);
4451c50d8ae3SPaolo Bonzini }
4452c50d8ae3SPaolo Bonzini 
4453c50d8ae3SPaolo Bonzini #define BYTE_MASK(access) \
4454c50d8ae3SPaolo Bonzini 	((1 & (access) ? 2 : 0) | \
4455c50d8ae3SPaolo Bonzini 	 (2 & (access) ? 4 : 0) | \
4456c50d8ae3SPaolo Bonzini 	 (3 & (access) ? 8 : 0) | \
4457c50d8ae3SPaolo Bonzini 	 (4 & (access) ? 16 : 0) | \
4458c50d8ae3SPaolo Bonzini 	 (5 & (access) ? 32 : 0) | \
4459c50d8ae3SPaolo Bonzini 	 (6 & (access) ? 64 : 0) | \
4460c50d8ae3SPaolo Bonzini 	 (7 & (access) ? 128 : 0))
4461c50d8ae3SPaolo Bonzini 
4462c50d8ae3SPaolo Bonzini 
4463c596f147SSean Christopherson static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
4464c50d8ae3SPaolo Bonzini {
4465c50d8ae3SPaolo Bonzini 	unsigned byte;
4466c50d8ae3SPaolo Bonzini 
4467c50d8ae3SPaolo Bonzini 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4468c50d8ae3SPaolo Bonzini 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4469c50d8ae3SPaolo Bonzini 	const u8 u = BYTE_MASK(ACC_USER_MASK);
4470c50d8ae3SPaolo Bonzini 
4471c596f147SSean Christopherson 	bool cr4_smep = is_cr4_smep(mmu);
4472c596f147SSean Christopherson 	bool cr4_smap = is_cr4_smap(mmu);
4473c596f147SSean Christopherson 	bool cr0_wp = is_cr0_wp(mmu);
447490599c28SSean Christopherson 	bool efer_nx = is_efer_nx(mmu);
4475c50d8ae3SPaolo Bonzini 
4476c50d8ae3SPaolo Bonzini 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4477c50d8ae3SPaolo Bonzini 		unsigned pfec = byte << 1;
4478c50d8ae3SPaolo Bonzini 
4479c50d8ae3SPaolo Bonzini 		/*
4480c50d8ae3SPaolo Bonzini 		 * Each "*f" variable has a 1 bit for each UWX value
4481c50d8ae3SPaolo Bonzini 		 * that causes a fault with the given PFEC.
4482c50d8ae3SPaolo Bonzini 		 */
4483c50d8ae3SPaolo Bonzini 
4484c50d8ae3SPaolo Bonzini 		/* Faults from writes to non-writable pages */
4485c50d8ae3SPaolo Bonzini 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4486c50d8ae3SPaolo Bonzini 		/* Faults from user mode accesses to supervisor pages */
4487c50d8ae3SPaolo Bonzini 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4488c50d8ae3SPaolo Bonzini 		/* Faults from fetches of non-executable pages*/
4489c50d8ae3SPaolo Bonzini 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4490c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode fetches of user pages */
4491c50d8ae3SPaolo Bonzini 		u8 smepf = 0;
4492c50d8ae3SPaolo Bonzini 		/* Faults from kernel mode accesses of user pages */
4493c50d8ae3SPaolo Bonzini 		u8 smapf = 0;
4494c50d8ae3SPaolo Bonzini 
4495c50d8ae3SPaolo Bonzini 		if (!ept) {
4496c50d8ae3SPaolo Bonzini 			/* Faults from kernel mode accesses to user pages */
4497c50d8ae3SPaolo Bonzini 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4498c50d8ae3SPaolo Bonzini 
4499c50d8ae3SPaolo Bonzini 			/* Not really needed: !nx will cause pte.nx to fault */
450090599c28SSean Christopherson 			if (!efer_nx)
4501c50d8ae3SPaolo Bonzini 				ff = 0;
4502c50d8ae3SPaolo Bonzini 
4503c50d8ae3SPaolo Bonzini 			/* Allow supervisor writes if !cr0.wp */
4504c50d8ae3SPaolo Bonzini 			if (!cr0_wp)
4505c50d8ae3SPaolo Bonzini 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4506c50d8ae3SPaolo Bonzini 
4507c50d8ae3SPaolo Bonzini 			/* Disallow supervisor fetches of user code if cr4.smep */
4508c50d8ae3SPaolo Bonzini 			if (cr4_smep)
4509c50d8ae3SPaolo Bonzini 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4510c50d8ae3SPaolo Bonzini 
4511c50d8ae3SPaolo Bonzini 			/*
4512c50d8ae3SPaolo Bonzini 			 * SMAP:kernel-mode data accesses from user-mode
4513c50d8ae3SPaolo Bonzini 			 * mappings should fault. A fault is considered
4514c50d8ae3SPaolo Bonzini 			 * as a SMAP violation if all of the following
4515c50d8ae3SPaolo Bonzini 			 * conditions are true:
4516c50d8ae3SPaolo Bonzini 			 *   - X86_CR4_SMAP is set in CR4
4517c50d8ae3SPaolo Bonzini 			 *   - A user page is accessed
4518c50d8ae3SPaolo Bonzini 			 *   - The access is not a fetch
4519c50d8ae3SPaolo Bonzini 			 *   - Page fault in kernel mode
4520c50d8ae3SPaolo Bonzini 			 *   - if CPL = 3 or X86_EFLAGS_AC is clear
4521c50d8ae3SPaolo Bonzini 			 *
4522c50d8ae3SPaolo Bonzini 			 * Here, we cover the first three conditions.
4523c50d8ae3SPaolo Bonzini 			 * The fourth is computed dynamically in permission_fault();
4524c50d8ae3SPaolo Bonzini 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4525c50d8ae3SPaolo Bonzini 			 * *not* subject to SMAP restrictions.
4526c50d8ae3SPaolo Bonzini 			 */
4527c50d8ae3SPaolo Bonzini 			if (cr4_smap)
4528c50d8ae3SPaolo Bonzini 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4529c50d8ae3SPaolo Bonzini 		}
4530c50d8ae3SPaolo Bonzini 
4531c50d8ae3SPaolo Bonzini 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4532c50d8ae3SPaolo Bonzini 	}
4533c50d8ae3SPaolo Bonzini }
4534c50d8ae3SPaolo Bonzini 
4535c50d8ae3SPaolo Bonzini /*
4536c50d8ae3SPaolo Bonzini * PKU is an additional mechanism by which the paging controls access to
4537c50d8ae3SPaolo Bonzini * user-mode addresses based on the value in the PKRU register.  Protection
4538c50d8ae3SPaolo Bonzini * key violations are reported through a bit in the page fault error code.
4539c50d8ae3SPaolo Bonzini * Unlike other bits of the error code, the PK bit is not known at the
4540c50d8ae3SPaolo Bonzini * call site of e.g. gva_to_gpa; it must be computed directly in
4541c50d8ae3SPaolo Bonzini * permission_fault based on two bits of PKRU, on some machine state (CR4,
4542c50d8ae3SPaolo Bonzini * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4543c50d8ae3SPaolo Bonzini *
4544c50d8ae3SPaolo Bonzini * In particular the following conditions come from the error code, the
4545c50d8ae3SPaolo Bonzini * page tables and the machine state:
4546c50d8ae3SPaolo Bonzini * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4547c50d8ae3SPaolo Bonzini * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4548c50d8ae3SPaolo Bonzini * - PK is always zero if U=0 in the page tables
4549c50d8ae3SPaolo Bonzini * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4550c50d8ae3SPaolo Bonzini *
4551c50d8ae3SPaolo Bonzini * The PKRU bitmask caches the result of these four conditions.  The error
4552c50d8ae3SPaolo Bonzini * code (minus the P bit) and the page table's U bit form an index into the
4553c50d8ae3SPaolo Bonzini * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
4554c50d8ae3SPaolo Bonzini * with the two bits of the PKRU register corresponding to the protection key.
4555c50d8ae3SPaolo Bonzini * For the first three conditions above the bits will be 00, thus masking
4556c50d8ae3SPaolo Bonzini * away both AD and WD.  For all reads or if the last condition holds, WD
4557c50d8ae3SPaolo Bonzini * only will be masked away.
4558c50d8ae3SPaolo Bonzini */
45592e4c0661SSean Christopherson static void update_pkru_bitmask(struct kvm_mmu *mmu)
4560c50d8ae3SPaolo Bonzini {
4561c50d8ae3SPaolo Bonzini 	unsigned bit;
4562c50d8ae3SPaolo Bonzini 	bool wp;
4563c50d8ae3SPaolo Bonzini 
45642e4c0661SSean Christopherson 	if (!is_cr4_pke(mmu)) {
4565c50d8ae3SPaolo Bonzini 		mmu->pkru_mask = 0;
4566c50d8ae3SPaolo Bonzini 		return;
4567c50d8ae3SPaolo Bonzini 	}
4568c50d8ae3SPaolo Bonzini 
45692e4c0661SSean Christopherson 	wp = is_cr0_wp(mmu);
4570c50d8ae3SPaolo Bonzini 
4571c50d8ae3SPaolo Bonzini 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4572c50d8ae3SPaolo Bonzini 		unsigned pfec, pkey_bits;
4573c50d8ae3SPaolo Bonzini 		bool check_pkey, check_write, ff, uf, wf, pte_user;
4574c50d8ae3SPaolo Bonzini 
4575c50d8ae3SPaolo Bonzini 		pfec = bit << 1;
4576c50d8ae3SPaolo Bonzini 		ff = pfec & PFERR_FETCH_MASK;
4577c50d8ae3SPaolo Bonzini 		uf = pfec & PFERR_USER_MASK;
4578c50d8ae3SPaolo Bonzini 		wf = pfec & PFERR_WRITE_MASK;
4579c50d8ae3SPaolo Bonzini 
4580c50d8ae3SPaolo Bonzini 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
4581c50d8ae3SPaolo Bonzini 		pte_user = pfec & PFERR_RSVD_MASK;
4582c50d8ae3SPaolo Bonzini 
4583c50d8ae3SPaolo Bonzini 		/*
4584c50d8ae3SPaolo Bonzini 		 * Only need to check the access which is not an
4585c50d8ae3SPaolo Bonzini 		 * instruction fetch and is to a user page.
4586c50d8ae3SPaolo Bonzini 		 */
4587c50d8ae3SPaolo Bonzini 		check_pkey = (!ff && pte_user);
4588c50d8ae3SPaolo Bonzini 		/*
4589c50d8ae3SPaolo Bonzini 		 * write access is controlled by PKRU if it is a
4590c50d8ae3SPaolo Bonzini 		 * user access or CR0.WP = 1.
4591c50d8ae3SPaolo Bonzini 		 */
4592c50d8ae3SPaolo Bonzini 		check_write = check_pkey && wf && (uf || wp);
4593c50d8ae3SPaolo Bonzini 
4594c50d8ae3SPaolo Bonzini 		/* PKRU.AD stops both read and write access. */
4595c50d8ae3SPaolo Bonzini 		pkey_bits = !!check_pkey;
4596c50d8ae3SPaolo Bonzini 		/* PKRU.WD stops write access. */
4597c50d8ae3SPaolo Bonzini 		pkey_bits |= (!!check_write) << 1;
4598c50d8ae3SPaolo Bonzini 
4599c50d8ae3SPaolo Bonzini 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4600c50d8ae3SPaolo Bonzini 	}
4601c50d8ae3SPaolo Bonzini }
4602c50d8ae3SPaolo Bonzini 
4603533f9a4bSSean Christopherson static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
4604533f9a4bSSean Christopherson 					struct kvm_mmu *mmu)
4605c50d8ae3SPaolo Bonzini {
4606533f9a4bSSean Christopherson 	if (!is_cr0_pg(mmu))
4607533f9a4bSSean Christopherson 		return;
4608c50d8ae3SPaolo Bonzini 
4609533f9a4bSSean Christopherson 	reset_rsvds_bits_mask(vcpu, mmu);
4610533f9a4bSSean Christopherson 	update_permission_bitmask(mmu, false);
4611533f9a4bSSean Christopherson 	update_pkru_bitmask(mmu);
4612c50d8ae3SPaolo Bonzini }
4613c50d8ae3SPaolo Bonzini 
4614fe660f72SSean Christopherson static void paging64_init_context(struct kvm_mmu *context)
4615c50d8ae3SPaolo Bonzini {
4616c50d8ae3SPaolo Bonzini 	context->page_fault = paging64_page_fault;
4617c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging64_gva_to_gpa;
4618c50d8ae3SPaolo Bonzini 	context->sync_page = paging64_sync_page;
4619c50d8ae3SPaolo Bonzini 	context->invlpg = paging64_invlpg;
4620c50d8ae3SPaolo Bonzini 	context->direct_map = false;
4621c50d8ae3SPaolo Bonzini }
4622c50d8ae3SPaolo Bonzini 
462384a16226SSean Christopherson static void paging32_init_context(struct kvm_mmu *context)
4624c50d8ae3SPaolo Bonzini {
4625c50d8ae3SPaolo Bonzini 	context->page_fault = paging32_page_fault;
4626c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = paging32_gva_to_gpa;
4627c50d8ae3SPaolo Bonzini 	context->sync_page = paging32_sync_page;
4628c50d8ae3SPaolo Bonzini 	context->invlpg = paging32_invlpg;
4629c50d8ae3SPaolo Bonzini 	context->direct_map = false;
4630c50d8ae3SPaolo Bonzini }
4631c50d8ae3SPaolo Bonzini 
46328626c120SSean Christopherson static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu,
46338626c120SSean Christopherson 							 struct kvm_mmu_role_regs *regs)
4634c50d8ae3SPaolo Bonzini {
4635c50d8ae3SPaolo Bonzini 	union kvm_mmu_extended_role ext = {0};
4636c50d8ae3SPaolo Bonzini 
4637ca8d664fSSean Christopherson 	if (____is_cr0_pg(regs)) {
4638ca8d664fSSean Christopherson 		ext.cr0_pg = 1;
46398626c120SSean Christopherson 		ext.cr4_pae = ____is_cr4_pae(regs);
46408626c120SSean Christopherson 		ext.cr4_smep = ____is_cr4_smep(regs);
46418626c120SSean Christopherson 		ext.cr4_smap = ____is_cr4_smap(regs);
46428626c120SSean Christopherson 		ext.cr4_pse = ____is_cr4_pse(regs);
464384c679f5SSean Christopherson 
464484c679f5SSean Christopherson 		/* PKEY and LA57 are active iff long mode is active. */
464584c679f5SSean Christopherson 		ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
464684c679f5SSean Christopherson 		ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
4647ca8d664fSSean Christopherson 	}
4648c50d8ae3SPaolo Bonzini 
4649c50d8ae3SPaolo Bonzini 	ext.valid = 1;
4650c50d8ae3SPaolo Bonzini 
4651c50d8ae3SPaolo Bonzini 	return ext;
4652c50d8ae3SPaolo Bonzini }
4653c50d8ae3SPaolo Bonzini 
4654c50d8ae3SPaolo Bonzini static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
46558626c120SSean Christopherson 						   struct kvm_mmu_role_regs *regs,
4656c50d8ae3SPaolo Bonzini 						   bool base_only)
4657c50d8ae3SPaolo Bonzini {
4658c50d8ae3SPaolo Bonzini 	union kvm_mmu_role role = {0};
4659c50d8ae3SPaolo Bonzini 
4660c50d8ae3SPaolo Bonzini 	role.base.access = ACC_ALL;
4661ca8d664fSSean Christopherson 	if (____is_cr0_pg(regs)) {
4662167f8a5cSSean Christopherson 		role.base.efer_nx = ____is_efer_nx(regs);
46638626c120SSean Christopherson 		role.base.cr0_wp = ____is_cr0_wp(regs);
4664ca8d664fSSean Christopherson 	}
4665c50d8ae3SPaolo Bonzini 	role.base.smm = is_smm(vcpu);
4666c50d8ae3SPaolo Bonzini 	role.base.guest_mode = is_guest_mode(vcpu);
4667c50d8ae3SPaolo Bonzini 
4668c50d8ae3SPaolo Bonzini 	if (base_only)
4669c50d8ae3SPaolo Bonzini 		return role;
4670c50d8ae3SPaolo Bonzini 
46718626c120SSean Christopherson 	role.ext = kvm_calc_mmu_role_ext(vcpu, regs);
4672c50d8ae3SPaolo Bonzini 
4673c50d8ae3SPaolo Bonzini 	return role;
4674c50d8ae3SPaolo Bonzini }
4675c50d8ae3SPaolo Bonzini 
4676d468d94bSSean Christopherson static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
4677d468d94bSSean Christopherson {
4678d468d94bSSean Christopherson 	/* Use 5-level TDP if and only if it's useful/necessary. */
467983013059SSean Christopherson 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
4680d468d94bSSean Christopherson 		return 4;
4681d468d94bSSean Christopherson 
468283013059SSean Christopherson 	return max_tdp_level;
4683d468d94bSSean Christopherson }
4684d468d94bSSean Christopherson 
4685c50d8ae3SPaolo Bonzini static union kvm_mmu_role
46868626c120SSean Christopherson kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
46878626c120SSean Christopherson 				struct kvm_mmu_role_regs *regs, bool base_only)
4688c50d8ae3SPaolo Bonzini {
46898626c120SSean Christopherson 	union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, regs, base_only);
4690c50d8ae3SPaolo Bonzini 
4691c50d8ae3SPaolo Bonzini 	role.base.ad_disabled = (shadow_accessed_mask == 0);
4692d468d94bSSean Christopherson 	role.base.level = kvm_mmu_get_tdp_level(vcpu);
4693c50d8ae3SPaolo Bonzini 	role.base.direct = true;
4694c50d8ae3SPaolo Bonzini 	role.base.gpte_is_8_bytes = true;
4695c50d8ae3SPaolo Bonzini 
4696c50d8ae3SPaolo Bonzini 	return role;
4697c50d8ae3SPaolo Bonzini }
4698c50d8ae3SPaolo Bonzini 
4699c50d8ae3SPaolo Bonzini static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4700c50d8ae3SPaolo Bonzini {
47018c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
47028626c120SSean Christopherson 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
4703c50d8ae3SPaolo Bonzini 	union kvm_mmu_role new_role =
47048626c120SSean Christopherson 		kvm_calc_tdp_mmu_root_page_role(vcpu, &regs, false);
4705c50d8ae3SPaolo Bonzini 
4706c50d8ae3SPaolo Bonzini 	if (new_role.as_u64 == context->mmu_role.as_u64)
4707c50d8ae3SPaolo Bonzini 		return;
4708c50d8ae3SPaolo Bonzini 
4709c50d8ae3SPaolo Bonzini 	context->mmu_role.as_u64 = new_role.as_u64;
47107a02674dSSean Christopherson 	context->page_fault = kvm_tdp_page_fault;
4711c50d8ae3SPaolo Bonzini 	context->sync_page = nonpaging_sync_page;
47125efac074SPaolo Bonzini 	context->invlpg = NULL;
4713d468d94bSSean Christopherson 	context->shadow_root_level = kvm_mmu_get_tdp_level(vcpu);
4714c50d8ae3SPaolo Bonzini 	context->direct_map = true;
4715d8dd54e0SSean Christopherson 	context->get_guest_pgd = get_cr3;
4716c50d8ae3SPaolo Bonzini 	context->get_pdptr = kvm_pdptr_read;
4717c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
4718f4bd6f73SSean Christopherson 	context->root_level = role_regs_to_root_level(&regs);
4719c50d8ae3SPaolo Bonzini 
472036f26787SSean Christopherson 	if (!is_cr0_pg(context))
4721c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = nonpaging_gva_to_gpa;
472236f26787SSean Christopherson 	else if (is_cr4_pae(context))
4723c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging64_gva_to_gpa;
4724f4bd6f73SSean Christopherson 	else
4725c50d8ae3SPaolo Bonzini 		context->gva_to_gpa = paging32_gva_to_gpa;
4726c50d8ae3SPaolo Bonzini 
4727533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
4728c50d8ae3SPaolo Bonzini 	reset_tdp_shadow_zero_bits_mask(vcpu, context);
4729c50d8ae3SPaolo Bonzini }
4730c50d8ae3SPaolo Bonzini 
4731c50d8ae3SPaolo Bonzini static union kvm_mmu_role
47328626c120SSean Christopherson kvm_calc_shadow_root_page_role_common(struct kvm_vcpu *vcpu,
47338626c120SSean Christopherson 				      struct kvm_mmu_role_regs *regs, bool base_only)
4734c50d8ae3SPaolo Bonzini {
47358626c120SSean Christopherson 	union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, regs, base_only);
4736c50d8ae3SPaolo Bonzini 
47378626c120SSean Christopherson 	role.base.smep_andnot_wp = role.ext.cr4_smep && !____is_cr0_wp(regs);
47388626c120SSean Christopherson 	role.base.smap_andnot_wp = role.ext.cr4_smap && !____is_cr0_wp(regs);
4739ca8d664fSSean Christopherson 	role.base.gpte_is_8_bytes = ____is_cr0_pg(regs) && ____is_cr4_pae(regs);
4740c50d8ae3SPaolo Bonzini 
474159505b55SSean Christopherson 	return role;
474259505b55SSean Christopherson }
474359505b55SSean Christopherson 
474459505b55SSean Christopherson static union kvm_mmu_role
47458626c120SSean Christopherson kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu,
47468626c120SSean Christopherson 				   struct kvm_mmu_role_regs *regs, bool base_only)
474759505b55SSean Christopherson {
474859505b55SSean Christopherson 	union kvm_mmu_role role =
47498626c120SSean Christopherson 		kvm_calc_shadow_root_page_role_common(vcpu, regs, base_only);
475059505b55SSean Christopherson 
47518626c120SSean Christopherson 	role.base.direct = !____is_cr0_pg(regs);
475259505b55SSean Christopherson 
47538626c120SSean Christopherson 	if (!____is_efer_lma(regs))
4754c50d8ae3SPaolo Bonzini 		role.base.level = PT32E_ROOT_LEVEL;
47558626c120SSean Christopherson 	else if (____is_cr4_la57(regs))
4756c50d8ae3SPaolo Bonzini 		role.base.level = PT64_ROOT_5LEVEL;
4757c50d8ae3SPaolo Bonzini 	else
4758c50d8ae3SPaolo Bonzini 		role.base.level = PT64_ROOT_4LEVEL;
4759c50d8ae3SPaolo Bonzini 
4760c50d8ae3SPaolo Bonzini 	return role;
4761c50d8ae3SPaolo Bonzini }
4762c50d8ae3SPaolo Bonzini 
47638c008659SPaolo Bonzini static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
4764594e91a1SSean Christopherson 				    struct kvm_mmu_role_regs *regs,
47658c008659SPaolo Bonzini 				    union kvm_mmu_role new_role)
4766c50d8ae3SPaolo Bonzini {
476718db1b17SSean Christopherson 	if (new_role.as_u64 == context->mmu_role.as_u64)
476818db1b17SSean Christopherson 		return;
4769c50d8ae3SPaolo Bonzini 
4770c50d8ae3SPaolo Bonzini 	context->mmu_role.as_u64 = new_role.as_u64;
477118db1b17SSean Christopherson 
477236f26787SSean Christopherson 	if (!is_cr0_pg(context))
477384a16226SSean Christopherson 		nonpaging_init_context(context);
477436f26787SSean Christopherson 	else if (is_cr4_pae(context))
4775fe660f72SSean Christopherson 		paging64_init_context(context);
4776c50d8ae3SPaolo Bonzini 	else
477784a16226SSean Christopherson 		paging32_init_context(context);
4778f4bd6f73SSean Christopherson 	context->root_level = role_regs_to_root_level(regs);
4779c50d8ae3SPaolo Bonzini 
4780533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, context);
4781d555f705SSean Christopherson 	context->shadow_root_level = new_role.base.level;
4782d555f705SSean Christopherson 
4783c50d8ae3SPaolo Bonzini 	reset_shadow_zero_bits_mask(vcpu, context);
4784c50d8ae3SPaolo Bonzini }
47850f04a2acSVitaly Kuznetsov 
4786594e91a1SSean Christopherson static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
4787594e91a1SSean Christopherson 				struct kvm_mmu_role_regs *regs)
47880f04a2acSVitaly Kuznetsov {
47898c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
47900f04a2acSVitaly Kuznetsov 	union kvm_mmu_role new_role =
47918626c120SSean Christopherson 		kvm_calc_shadow_mmu_root_page_role(vcpu, regs, false);
47920f04a2acSVitaly Kuznetsov 
4793594e91a1SSean Christopherson 	shadow_mmu_init_context(vcpu, context, regs, new_role);
47940f04a2acSVitaly Kuznetsov }
47950f04a2acSVitaly Kuznetsov 
479659505b55SSean Christopherson static union kvm_mmu_role
47978626c120SSean Christopherson kvm_calc_shadow_npt_root_page_role(struct kvm_vcpu *vcpu,
47988626c120SSean Christopherson 				   struct kvm_mmu_role_regs *regs)
479959505b55SSean Christopherson {
480059505b55SSean Christopherson 	union kvm_mmu_role role =
48018626c120SSean Christopherson 		kvm_calc_shadow_root_page_role_common(vcpu, regs, false);
480259505b55SSean Christopherson 
480359505b55SSean Christopherson 	role.base.direct = false;
4804d468d94bSSean Christopherson 	role.base.level = kvm_mmu_get_tdp_level(vcpu);
480559505b55SSean Christopherson 
480659505b55SSean Christopherson 	return role;
480759505b55SSean Christopherson }
480859505b55SSean Christopherson 
4809dbc4739bSSean Christopherson void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
4810dbc4739bSSean Christopherson 			     unsigned long cr4, u64 efer, gpa_t nested_cr3)
48110f04a2acSVitaly Kuznetsov {
48128c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
4813594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = {
4814594e91a1SSean Christopherson 		.cr0 = cr0,
4815594e91a1SSean Christopherson 		.cr4 = cr4,
4816594e91a1SSean Christopherson 		.efer = efer,
4817594e91a1SSean Christopherson 	};
48188626c120SSean Christopherson 	union kvm_mmu_role new_role;
48190f04a2acSVitaly Kuznetsov 
48208626c120SSean Christopherson 	new_role = kvm_calc_shadow_npt_root_page_role(vcpu, &regs);
4821a506fdd2SVitaly Kuznetsov 
4822b5129100SSean Christopherson 	__kvm_mmu_new_pgd(vcpu, nested_cr3, new_role.base);
4823a3322d5cSSean Christopherson 
4824594e91a1SSean Christopherson 	shadow_mmu_init_context(vcpu, context, &regs, new_role);
48250f04a2acSVitaly Kuznetsov }
48260f04a2acSVitaly Kuznetsov EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
4827c50d8ae3SPaolo Bonzini 
4828c50d8ae3SPaolo Bonzini static union kvm_mmu_role
4829c50d8ae3SPaolo Bonzini kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
4830bb1fcc70SSean Christopherson 				   bool execonly, u8 level)
4831c50d8ae3SPaolo Bonzini {
4832c50d8ae3SPaolo Bonzini 	union kvm_mmu_role role = {0};
4833c50d8ae3SPaolo Bonzini 
4834c50d8ae3SPaolo Bonzini 	/* SMM flag is inherited from root_mmu */
4835c50d8ae3SPaolo Bonzini 	role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
4836c50d8ae3SPaolo Bonzini 
4837bb1fcc70SSean Christopherson 	role.base.level = level;
4838c50d8ae3SPaolo Bonzini 	role.base.gpte_is_8_bytes = true;
4839c50d8ae3SPaolo Bonzini 	role.base.direct = false;
4840c50d8ae3SPaolo Bonzini 	role.base.ad_disabled = !accessed_dirty;
4841c50d8ae3SPaolo Bonzini 	role.base.guest_mode = true;
4842c50d8ae3SPaolo Bonzini 	role.base.access = ACC_ALL;
4843c50d8ae3SPaolo Bonzini 
4844cd6767c3SSean Christopherson 	/* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
4845cd6767c3SSean Christopherson 	role.ext.word = 0;
4846c50d8ae3SPaolo Bonzini 	role.ext.execonly = execonly;
4847cd6767c3SSean Christopherson 	role.ext.valid = 1;
4848c50d8ae3SPaolo Bonzini 
4849c50d8ae3SPaolo Bonzini 	return role;
4850c50d8ae3SPaolo Bonzini }
4851c50d8ae3SPaolo Bonzini 
4852c50d8ae3SPaolo Bonzini void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4853c50d8ae3SPaolo Bonzini 			     bool accessed_dirty, gpa_t new_eptp)
4854c50d8ae3SPaolo Bonzini {
48558c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
4856bb1fcc70SSean Christopherson 	u8 level = vmx_eptp_page_walk_level(new_eptp);
4857c50d8ae3SPaolo Bonzini 	union kvm_mmu_role new_role =
4858c50d8ae3SPaolo Bonzini 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
4859bb1fcc70SSean Christopherson 						   execonly, level);
4860c50d8ae3SPaolo Bonzini 
4861b5129100SSean Christopherson 	__kvm_mmu_new_pgd(vcpu, new_eptp, new_role.base);
4862c50d8ae3SPaolo Bonzini 
4863c50d8ae3SPaolo Bonzini 	if (new_role.as_u64 == context->mmu_role.as_u64)
4864c50d8ae3SPaolo Bonzini 		return;
4865c50d8ae3SPaolo Bonzini 
486618db1b17SSean Christopherson 	context->mmu_role.as_u64 = new_role.as_u64;
486718db1b17SSean Christopherson 
4868bb1fcc70SSean Christopherson 	context->shadow_root_level = level;
4869c50d8ae3SPaolo Bonzini 
4870c50d8ae3SPaolo Bonzini 	context->ept_ad = accessed_dirty;
4871c50d8ae3SPaolo Bonzini 	context->page_fault = ept_page_fault;
4872c50d8ae3SPaolo Bonzini 	context->gva_to_gpa = ept_gva_to_gpa;
4873c50d8ae3SPaolo Bonzini 	context->sync_page = ept_sync_page;
4874c50d8ae3SPaolo Bonzini 	context->invlpg = ept_invlpg;
4875bb1fcc70SSean Christopherson 	context->root_level = level;
4876c50d8ae3SPaolo Bonzini 	context->direct_map = false;
4877c50d8ae3SPaolo Bonzini 
4878c596f147SSean Christopherson 	update_permission_bitmask(context, true);
48792e4c0661SSean Christopherson 	update_pkru_bitmask(context);
4880c50d8ae3SPaolo Bonzini 	reset_rsvds_bits_mask_ept(vcpu, context, execonly);
4881c50d8ae3SPaolo Bonzini 	reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
4882c50d8ae3SPaolo Bonzini }
4883c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4884c50d8ae3SPaolo Bonzini 
4885c50d8ae3SPaolo Bonzini static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4886c50d8ae3SPaolo Bonzini {
48878c008659SPaolo Bonzini 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
4888594e91a1SSean Christopherson 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
4889c50d8ae3SPaolo Bonzini 
4890594e91a1SSean Christopherson 	kvm_init_shadow_mmu(vcpu, &regs);
4891929d1cfaSPaolo Bonzini 
4892d8dd54e0SSean Christopherson 	context->get_guest_pgd     = get_cr3;
4893c50d8ae3SPaolo Bonzini 	context->get_pdptr         = kvm_pdptr_read;
4894c50d8ae3SPaolo Bonzini 	context->inject_page_fault = kvm_inject_page_fault;
4895c50d8ae3SPaolo Bonzini }
4896c50d8ae3SPaolo Bonzini 
48978626c120SSean Christopherson static union kvm_mmu_role
48988626c120SSean Christopherson kvm_calc_nested_mmu_role(struct kvm_vcpu *vcpu, struct kvm_mmu_role_regs *regs)
4899654430efSSean Christopherson {
49008626c120SSean Christopherson 	union kvm_mmu_role role;
49018626c120SSean Christopherson 
49028626c120SSean Christopherson 	role = kvm_calc_shadow_root_page_role_common(vcpu, regs, false);
4903654430efSSean Christopherson 
4904654430efSSean Christopherson 	/*
4905654430efSSean Christopherson 	 * Nested MMUs are used only for walking L2's gva->gpa, they never have
4906654430efSSean Christopherson 	 * shadow pages of their own and so "direct" has no meaning.   Set it
4907654430efSSean Christopherson 	 * to "true" to try to detect bogus usage of the nested MMU.
4908654430efSSean Christopherson 	 */
4909654430efSSean Christopherson 	role.base.direct = true;
4910f4bd6f73SSean Christopherson 	role.base.level = role_regs_to_root_level(regs);
4911654430efSSean Christopherson 	return role;
4912654430efSSean Christopherson }
4913654430efSSean Christopherson 
4914c50d8ae3SPaolo Bonzini static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
4915c50d8ae3SPaolo Bonzini {
49168626c120SSean Christopherson 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
49178626c120SSean Christopherson 	union kvm_mmu_role new_role = kvm_calc_nested_mmu_role(vcpu, &regs);
4918c50d8ae3SPaolo Bonzini 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4919c50d8ae3SPaolo Bonzini 
4920c50d8ae3SPaolo Bonzini 	if (new_role.as_u64 == g_context->mmu_role.as_u64)
4921c50d8ae3SPaolo Bonzini 		return;
4922c50d8ae3SPaolo Bonzini 
4923c50d8ae3SPaolo Bonzini 	g_context->mmu_role.as_u64 = new_role.as_u64;
4924d8dd54e0SSean Christopherson 	g_context->get_guest_pgd     = get_cr3;
4925c50d8ae3SPaolo Bonzini 	g_context->get_pdptr         = kvm_pdptr_read;
4926c50d8ae3SPaolo Bonzini 	g_context->inject_page_fault = kvm_inject_page_fault;
49275472fcd4SSean Christopherson 	g_context->root_level        = new_role.base.level;
4928c50d8ae3SPaolo Bonzini 
4929c50d8ae3SPaolo Bonzini 	/*
49305efac074SPaolo Bonzini 	 * L2 page tables are never shadowed, so there is no need to sync
49315efac074SPaolo Bonzini 	 * SPTEs.
49325efac074SPaolo Bonzini 	 */
49335efac074SPaolo Bonzini 	g_context->invlpg            = NULL;
49345efac074SPaolo Bonzini 
49355efac074SPaolo Bonzini 	/*
4936c50d8ae3SPaolo Bonzini 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
4937c50d8ae3SPaolo Bonzini 	 * L1's nested page tables (e.g. EPT12). The nested translation
4938c50d8ae3SPaolo Bonzini 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4939c50d8ae3SPaolo Bonzini 	 * L2's page tables as the first level of translation and L1's
4940c50d8ae3SPaolo Bonzini 	 * nested page tables as the second level of translation. Basically
4941c50d8ae3SPaolo Bonzini 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
4942c50d8ae3SPaolo Bonzini 	 */
4943fa4b5588SSean Christopherson 	if (!is_paging(vcpu))
4944c50d8ae3SPaolo Bonzini 		g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
4945fa4b5588SSean Christopherson 	else if (is_long_mode(vcpu))
4946c50d8ae3SPaolo Bonzini 		g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4947fa4b5588SSean Christopherson 	else if (is_pae(vcpu))
4948c50d8ae3SPaolo Bonzini 		g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4949fa4b5588SSean Christopherson 	else
4950c50d8ae3SPaolo Bonzini 		g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
4951fa4b5588SSean Christopherson 
4952533f9a4bSSean Christopherson 	reset_guest_paging_metadata(vcpu, g_context);
4953c50d8ae3SPaolo Bonzini }
4954c50d8ae3SPaolo Bonzini 
4955c9060662SSean Christopherson void kvm_init_mmu(struct kvm_vcpu *vcpu)
4956c50d8ae3SPaolo Bonzini {
4957c50d8ae3SPaolo Bonzini 	if (mmu_is_nested(vcpu))
4958c50d8ae3SPaolo Bonzini 		init_kvm_nested_mmu(vcpu);
4959c50d8ae3SPaolo Bonzini 	else if (tdp_enabled)
4960c50d8ae3SPaolo Bonzini 		init_kvm_tdp_mmu(vcpu);
4961c50d8ae3SPaolo Bonzini 	else
4962c50d8ae3SPaolo Bonzini 		init_kvm_softmmu(vcpu);
4963c50d8ae3SPaolo Bonzini }
4964c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_init_mmu);
4965c50d8ae3SPaolo Bonzini 
4966c50d8ae3SPaolo Bonzini static union kvm_mmu_page_role
4967c50d8ae3SPaolo Bonzini kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
4968c50d8ae3SPaolo Bonzini {
49698626c120SSean Christopherson 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
4970c50d8ae3SPaolo Bonzini 	union kvm_mmu_role role;
4971c50d8ae3SPaolo Bonzini 
4972c50d8ae3SPaolo Bonzini 	if (tdp_enabled)
49738626c120SSean Christopherson 		role = kvm_calc_tdp_mmu_root_page_role(vcpu, &regs, true);
4974c50d8ae3SPaolo Bonzini 	else
49758626c120SSean Christopherson 		role = kvm_calc_shadow_mmu_root_page_role(vcpu, &regs, true);
4976c50d8ae3SPaolo Bonzini 
4977c50d8ae3SPaolo Bonzini 	return role.base;
4978c50d8ae3SPaolo Bonzini }
4979c50d8ae3SPaolo Bonzini 
498049c6f875SSean Christopherson void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
498149c6f875SSean Christopherson {
498249c6f875SSean Christopherson 	/*
498349c6f875SSean Christopherson 	 * Invalidate all MMU roles to force them to reinitialize as CPUID
498449c6f875SSean Christopherson 	 * information is factored into reserved bit calculations.
498549c6f875SSean Christopherson 	 */
498649c6f875SSean Christopherson 	vcpu->arch.root_mmu.mmu_role.ext.valid = 0;
498749c6f875SSean Christopherson 	vcpu->arch.guest_mmu.mmu_role.ext.valid = 0;
498849c6f875SSean Christopherson 	vcpu->arch.nested_mmu.mmu_role.ext.valid = 0;
498949c6f875SSean Christopherson 	kvm_mmu_reset_context(vcpu);
499063f5a190SSean Christopherson 
499163f5a190SSean Christopherson 	/*
499263f5a190SSean Christopherson 	 * KVM does not correctly handle changing guest CPUID after KVM_RUN, as
499363f5a190SSean Christopherson 	 * MAXPHYADDR, GBPAGES support, AMD reserved bit behavior, etc.. aren't
499463f5a190SSean Christopherson 	 * tracked in kvm_mmu_page_role.  As a result, KVM may miss guest page
499563f5a190SSean Christopherson 	 * faults due to reusing SPs/SPTEs.  Alert userspace, but otherwise
499663f5a190SSean Christopherson 	 * sweep the problem under the rug.
499763f5a190SSean Christopherson 	 *
499863f5a190SSean Christopherson 	 * KVM's horrific CPUID ABI makes the problem all but impossible to
499963f5a190SSean Christopherson 	 * solve, as correctly handling multiple vCPU models (with respect to
500063f5a190SSean Christopherson 	 * paging and physical address properties) in a single VM would require
500163f5a190SSean Christopherson 	 * tracking all relevant CPUID information in kvm_mmu_page_role.  That
500263f5a190SSean Christopherson 	 * is very undesirable as it would double the memory requirements for
500363f5a190SSean Christopherson 	 * gfn_track (see struct kvm_mmu_page_role comments), and in practice
500463f5a190SSean Christopherson 	 * no sane VMM mucks with the core vCPU model on the fly.
500563f5a190SSean Christopherson 	 */
500663f5a190SSean Christopherson 	if (vcpu->arch.last_vmentry_cpu != -1) {
500763f5a190SSean Christopherson 		pr_warn_ratelimited("KVM: KVM_SET_CPUID{,2} after KVM_RUN may cause guest instability\n");
500863f5a190SSean Christopherson 		pr_warn_ratelimited("KVM: KVM_SET_CPUID{,2} will fail after KVM_RUN starting with Linux 5.16\n");
500963f5a190SSean Christopherson 	}
501049c6f875SSean Christopherson }
501149c6f875SSean Christopherson 
5012c50d8ae3SPaolo Bonzini void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5013c50d8ae3SPaolo Bonzini {
5014c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
5015c9060662SSean Christopherson 	kvm_init_mmu(vcpu);
5016c50d8ae3SPaolo Bonzini }
5017c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5018c50d8ae3SPaolo Bonzini 
5019c50d8ae3SPaolo Bonzini int kvm_mmu_load(struct kvm_vcpu *vcpu)
5020c50d8ae3SPaolo Bonzini {
5021c50d8ae3SPaolo Bonzini 	int r;
5022c50d8ae3SPaolo Bonzini 
5023378f5cd6SSean Christopherson 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->direct_map);
5024c50d8ae3SPaolo Bonzini 	if (r)
5025c50d8ae3SPaolo Bonzini 		goto out;
5026748e52b9SSean Christopherson 	r = mmu_alloc_special_roots(vcpu);
5027c50d8ae3SPaolo Bonzini 	if (r)
5028c50d8ae3SPaolo Bonzini 		goto out;
50294a38162eSPaolo Bonzini 	if (vcpu->arch.mmu->direct_map)
50306e6ec584SSean Christopherson 		r = mmu_alloc_direct_roots(vcpu);
50316e6ec584SSean Christopherson 	else
50326e6ec584SSean Christopherson 		r = mmu_alloc_shadow_roots(vcpu);
5033c50d8ae3SPaolo Bonzini 	if (r)
5034c50d8ae3SPaolo Bonzini 		goto out;
5035a91f387bSSean Christopherson 
5036a91f387bSSean Christopherson 	kvm_mmu_sync_roots(vcpu);
5037a91f387bSSean Christopherson 
5038727a7e27SPaolo Bonzini 	kvm_mmu_load_pgd(vcpu);
5039b3646477SJason Baron 	static_call(kvm_x86_tlb_flush_current)(vcpu);
5040c50d8ae3SPaolo Bonzini out:
5041c50d8ae3SPaolo Bonzini 	return r;
5042c50d8ae3SPaolo Bonzini }
5043c50d8ae3SPaolo Bonzini 
5044c50d8ae3SPaolo Bonzini void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5045c50d8ae3SPaolo Bonzini {
5046c50d8ae3SPaolo Bonzini 	kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5047c50d8ae3SPaolo Bonzini 	WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5048c50d8ae3SPaolo Bonzini 	kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5049c50d8ae3SPaolo Bonzini 	WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5050c50d8ae3SPaolo Bonzini }
5051c50d8ae3SPaolo Bonzini 
5052c50d8ae3SPaolo Bonzini static bool need_remote_flush(u64 old, u64 new)
5053c50d8ae3SPaolo Bonzini {
5054c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(old))
5055c50d8ae3SPaolo Bonzini 		return false;
5056c50d8ae3SPaolo Bonzini 	if (!is_shadow_present_pte(new))
5057c50d8ae3SPaolo Bonzini 		return true;
5058c50d8ae3SPaolo Bonzini 	if ((old ^ new) & PT64_BASE_ADDR_MASK)
5059c50d8ae3SPaolo Bonzini 		return true;
5060c50d8ae3SPaolo Bonzini 	old ^= shadow_nx_mask;
5061c50d8ae3SPaolo Bonzini 	new ^= shadow_nx_mask;
5062c50d8ae3SPaolo Bonzini 	return (old & ~new & PT64_PERM_MASK) != 0;
5063c50d8ae3SPaolo Bonzini }
5064c50d8ae3SPaolo Bonzini 
5065c50d8ae3SPaolo Bonzini static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5066c50d8ae3SPaolo Bonzini 				    int *bytes)
5067c50d8ae3SPaolo Bonzini {
5068c50d8ae3SPaolo Bonzini 	u64 gentry = 0;
5069c50d8ae3SPaolo Bonzini 	int r;
5070c50d8ae3SPaolo Bonzini 
5071c50d8ae3SPaolo Bonzini 	/*
5072c50d8ae3SPaolo Bonzini 	 * Assume that the pte write on a page table of the same type
5073c50d8ae3SPaolo Bonzini 	 * as the current vcpu paging mode since we update the sptes only
5074c50d8ae3SPaolo Bonzini 	 * when they have the same mode.
5075c50d8ae3SPaolo Bonzini 	 */
5076c50d8ae3SPaolo Bonzini 	if (is_pae(vcpu) && *bytes == 4) {
5077c50d8ae3SPaolo Bonzini 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5078c50d8ae3SPaolo Bonzini 		*gpa &= ~(gpa_t)7;
5079c50d8ae3SPaolo Bonzini 		*bytes = 8;
5080c50d8ae3SPaolo Bonzini 	}
5081c50d8ae3SPaolo Bonzini 
5082c50d8ae3SPaolo Bonzini 	if (*bytes == 4 || *bytes == 8) {
5083c50d8ae3SPaolo Bonzini 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5084c50d8ae3SPaolo Bonzini 		if (r)
5085c50d8ae3SPaolo Bonzini 			gentry = 0;
5086c50d8ae3SPaolo Bonzini 	}
5087c50d8ae3SPaolo Bonzini 
5088c50d8ae3SPaolo Bonzini 	return gentry;
5089c50d8ae3SPaolo Bonzini }
5090c50d8ae3SPaolo Bonzini 
5091c50d8ae3SPaolo Bonzini /*
5092c50d8ae3SPaolo Bonzini  * If we're seeing too many writes to a page, it may no longer be a page table,
5093c50d8ae3SPaolo Bonzini  * or we may be forking, in which case it is better to unmap the page.
5094c50d8ae3SPaolo Bonzini  */
5095c50d8ae3SPaolo Bonzini static bool detect_write_flooding(struct kvm_mmu_page *sp)
5096c50d8ae3SPaolo Bonzini {
5097c50d8ae3SPaolo Bonzini 	/*
5098c50d8ae3SPaolo Bonzini 	 * Skip write-flooding detected for the sp whose level is 1, because
5099c50d8ae3SPaolo Bonzini 	 * it can become unsync, then the guest page is not write-protected.
5100c50d8ae3SPaolo Bonzini 	 */
51013bae0459SSean Christopherson 	if (sp->role.level == PG_LEVEL_4K)
5102c50d8ae3SPaolo Bonzini 		return false;
5103c50d8ae3SPaolo Bonzini 
5104c50d8ae3SPaolo Bonzini 	atomic_inc(&sp->write_flooding_count);
5105c50d8ae3SPaolo Bonzini 	return atomic_read(&sp->write_flooding_count) >= 3;
5106c50d8ae3SPaolo Bonzini }
5107c50d8ae3SPaolo Bonzini 
5108c50d8ae3SPaolo Bonzini /*
5109c50d8ae3SPaolo Bonzini  * Misaligned accesses are too much trouble to fix up; also, they usually
5110c50d8ae3SPaolo Bonzini  * indicate a page is not used as a page table.
5111c50d8ae3SPaolo Bonzini  */
5112c50d8ae3SPaolo Bonzini static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5113c50d8ae3SPaolo Bonzini 				    int bytes)
5114c50d8ae3SPaolo Bonzini {
5115c50d8ae3SPaolo Bonzini 	unsigned offset, pte_size, misaligned;
5116c50d8ae3SPaolo Bonzini 
5117c50d8ae3SPaolo Bonzini 	pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5118c50d8ae3SPaolo Bonzini 		 gpa, bytes, sp->role.word);
5119c50d8ae3SPaolo Bonzini 
5120c50d8ae3SPaolo Bonzini 	offset = offset_in_page(gpa);
5121c50d8ae3SPaolo Bonzini 	pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5122c50d8ae3SPaolo Bonzini 
5123c50d8ae3SPaolo Bonzini 	/*
5124c50d8ae3SPaolo Bonzini 	 * Sometimes, the OS only writes the last one bytes to update status
5125c50d8ae3SPaolo Bonzini 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5126c50d8ae3SPaolo Bonzini 	 */
5127c50d8ae3SPaolo Bonzini 	if (!(offset & (pte_size - 1)) && bytes == 1)
5128c50d8ae3SPaolo Bonzini 		return false;
5129c50d8ae3SPaolo Bonzini 
5130c50d8ae3SPaolo Bonzini 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5131c50d8ae3SPaolo Bonzini 	misaligned |= bytes < 4;
5132c50d8ae3SPaolo Bonzini 
5133c50d8ae3SPaolo Bonzini 	return misaligned;
5134c50d8ae3SPaolo Bonzini }
5135c50d8ae3SPaolo Bonzini 
5136c50d8ae3SPaolo Bonzini static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5137c50d8ae3SPaolo Bonzini {
5138c50d8ae3SPaolo Bonzini 	unsigned page_offset, quadrant;
5139c50d8ae3SPaolo Bonzini 	u64 *spte;
5140c50d8ae3SPaolo Bonzini 	int level;
5141c50d8ae3SPaolo Bonzini 
5142c50d8ae3SPaolo Bonzini 	page_offset = offset_in_page(gpa);
5143c50d8ae3SPaolo Bonzini 	level = sp->role.level;
5144c50d8ae3SPaolo Bonzini 	*nspte = 1;
5145c50d8ae3SPaolo Bonzini 	if (!sp->role.gpte_is_8_bytes) {
5146c50d8ae3SPaolo Bonzini 		page_offset <<= 1;	/* 32->64 */
5147c50d8ae3SPaolo Bonzini 		/*
5148c50d8ae3SPaolo Bonzini 		 * A 32-bit pde maps 4MB while the shadow pdes map
5149c50d8ae3SPaolo Bonzini 		 * only 2MB.  So we need to double the offset again
5150c50d8ae3SPaolo Bonzini 		 * and zap two pdes instead of one.
5151c50d8ae3SPaolo Bonzini 		 */
5152c50d8ae3SPaolo Bonzini 		if (level == PT32_ROOT_LEVEL) {
5153c50d8ae3SPaolo Bonzini 			page_offset &= ~7; /* kill rounding error */
5154c50d8ae3SPaolo Bonzini 			page_offset <<= 1;
5155c50d8ae3SPaolo Bonzini 			*nspte = 2;
5156c50d8ae3SPaolo Bonzini 		}
5157c50d8ae3SPaolo Bonzini 		quadrant = page_offset >> PAGE_SHIFT;
5158c50d8ae3SPaolo Bonzini 		page_offset &= ~PAGE_MASK;
5159c50d8ae3SPaolo Bonzini 		if (quadrant != sp->role.quadrant)
5160c50d8ae3SPaolo Bonzini 			return NULL;
5161c50d8ae3SPaolo Bonzini 	}
5162c50d8ae3SPaolo Bonzini 
5163c50d8ae3SPaolo Bonzini 	spte = &sp->spt[page_offset / sizeof(*spte)];
5164c50d8ae3SPaolo Bonzini 	return spte;
5165c50d8ae3SPaolo Bonzini }
5166c50d8ae3SPaolo Bonzini 
5167c50d8ae3SPaolo Bonzini static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5168c50d8ae3SPaolo Bonzini 			      const u8 *new, int bytes,
5169c50d8ae3SPaolo Bonzini 			      struct kvm_page_track_notifier_node *node)
5170c50d8ae3SPaolo Bonzini {
5171c50d8ae3SPaolo Bonzini 	gfn_t gfn = gpa >> PAGE_SHIFT;
5172c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
5173c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
5174c50d8ae3SPaolo Bonzini 	u64 entry, gentry, *spte;
5175c50d8ae3SPaolo Bonzini 	int npte;
5176c50d8ae3SPaolo Bonzini 	bool remote_flush, local_flush;
5177c50d8ae3SPaolo Bonzini 
5178c50d8ae3SPaolo Bonzini 	/*
5179c50d8ae3SPaolo Bonzini 	 * If we don't have indirect shadow pages, it means no page is
5180c50d8ae3SPaolo Bonzini 	 * write-protected, so we can exit simply.
5181c50d8ae3SPaolo Bonzini 	 */
5182c50d8ae3SPaolo Bonzini 	if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5183c50d8ae3SPaolo Bonzini 		return;
5184c50d8ae3SPaolo Bonzini 
5185c50d8ae3SPaolo Bonzini 	remote_flush = local_flush = false;
5186c50d8ae3SPaolo Bonzini 
5187c50d8ae3SPaolo Bonzini 	pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5188c50d8ae3SPaolo Bonzini 
5189c50d8ae3SPaolo Bonzini 	/*
5190c50d8ae3SPaolo Bonzini 	 * No need to care whether allocation memory is successful
5191d9f6e12fSIngo Molnar 	 * or not since pte prefetch is skipped if it does not have
5192c50d8ae3SPaolo Bonzini 	 * enough objects in the cache.
5193c50d8ae3SPaolo Bonzini 	 */
5194378f5cd6SSean Christopherson 	mmu_topup_memory_caches(vcpu, true);
5195c50d8ae3SPaolo Bonzini 
5196531810caSBen Gardon 	write_lock(&vcpu->kvm->mmu_lock);
5197c50d8ae3SPaolo Bonzini 
5198c50d8ae3SPaolo Bonzini 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5199c50d8ae3SPaolo Bonzini 
5200c50d8ae3SPaolo Bonzini 	++vcpu->kvm->stat.mmu_pte_write;
5201c50d8ae3SPaolo Bonzini 	kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5202c50d8ae3SPaolo Bonzini 
5203c50d8ae3SPaolo Bonzini 	for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5204c50d8ae3SPaolo Bonzini 		if (detect_write_misaligned(sp, gpa, bytes) ||
5205c50d8ae3SPaolo Bonzini 		      detect_write_flooding(sp)) {
5206c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5207c50d8ae3SPaolo Bonzini 			++vcpu->kvm->stat.mmu_flooded;
5208c50d8ae3SPaolo Bonzini 			continue;
5209c50d8ae3SPaolo Bonzini 		}
5210c50d8ae3SPaolo Bonzini 
5211c50d8ae3SPaolo Bonzini 		spte = get_written_sptes(sp, gpa, &npte);
5212c50d8ae3SPaolo Bonzini 		if (!spte)
5213c50d8ae3SPaolo Bonzini 			continue;
5214c50d8ae3SPaolo Bonzini 
5215c50d8ae3SPaolo Bonzini 		local_flush = true;
5216c50d8ae3SPaolo Bonzini 		while (npte--) {
5217c50d8ae3SPaolo Bonzini 			entry = *spte;
52182de4085cSBen Gardon 			mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5219c5e2184dSSean Christopherson 			if (gentry && sp->role.level != PG_LEVEL_4K)
5220c5e2184dSSean Christopherson 				++vcpu->kvm->stat.mmu_pde_zapped;
5221c50d8ae3SPaolo Bonzini 			if (need_remote_flush(entry, *spte))
5222c50d8ae3SPaolo Bonzini 				remote_flush = true;
5223c50d8ae3SPaolo Bonzini 			++spte;
5224c50d8ae3SPaolo Bonzini 		}
5225c50d8ae3SPaolo Bonzini 	}
5226c50d8ae3SPaolo Bonzini 	kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5227c50d8ae3SPaolo Bonzini 	kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5228531810caSBen Gardon 	write_unlock(&vcpu->kvm->mmu_lock);
5229c50d8ae3SPaolo Bonzini }
5230c50d8ae3SPaolo Bonzini 
5231736c291cSSean Christopherson int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5232c50d8ae3SPaolo Bonzini 		       void *insn, int insn_len)
5233c50d8ae3SPaolo Bonzini {
523492daa48bSSean Christopherson 	int r, emulation_type = EMULTYPE_PF;
5235c50d8ae3SPaolo Bonzini 	bool direct = vcpu->arch.mmu->direct_map;
5236c50d8ae3SPaolo Bonzini 
52376948199aSSean Christopherson 	if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
5238ddce6208SSean Christopherson 		return RET_PF_RETRY;
5239ddce6208SSean Christopherson 
5240c50d8ae3SPaolo Bonzini 	r = RET_PF_INVALID;
5241c50d8ae3SPaolo Bonzini 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
5242736c291cSSean Christopherson 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5243c50d8ae3SPaolo Bonzini 		if (r == RET_PF_EMULATE)
5244c50d8ae3SPaolo Bonzini 			goto emulate;
5245c50d8ae3SPaolo Bonzini 	}
5246c50d8ae3SPaolo Bonzini 
5247c50d8ae3SPaolo Bonzini 	if (r == RET_PF_INVALID) {
52487a02674dSSean Christopherson 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
52497a02674dSSean Christopherson 					  lower_32_bits(error_code), false);
525019025e7bSSean Christopherson 		if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
52517b367bc9SSean Christopherson 			return -EIO;
5252c50d8ae3SPaolo Bonzini 	}
5253c50d8ae3SPaolo Bonzini 
5254c50d8ae3SPaolo Bonzini 	if (r < 0)
5255c50d8ae3SPaolo Bonzini 		return r;
525683a2ba4cSSean Christopherson 	if (r != RET_PF_EMULATE)
525783a2ba4cSSean Christopherson 		return 1;
5258c50d8ae3SPaolo Bonzini 
5259c50d8ae3SPaolo Bonzini 	/*
5260c50d8ae3SPaolo Bonzini 	 * Before emulating the instruction, check if the error code
5261c50d8ae3SPaolo Bonzini 	 * was due to a RO violation while translating the guest page.
5262c50d8ae3SPaolo Bonzini 	 * This can occur when using nested virtualization with nested
5263c50d8ae3SPaolo Bonzini 	 * paging in both guests. If true, we simply unprotect the page
5264c50d8ae3SPaolo Bonzini 	 * and resume the guest.
5265c50d8ae3SPaolo Bonzini 	 */
5266c50d8ae3SPaolo Bonzini 	if (vcpu->arch.mmu->direct_map &&
5267c50d8ae3SPaolo Bonzini 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5268736c291cSSean Christopherson 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5269c50d8ae3SPaolo Bonzini 		return 1;
5270c50d8ae3SPaolo Bonzini 	}
5271c50d8ae3SPaolo Bonzini 
5272c50d8ae3SPaolo Bonzini 	/*
5273c50d8ae3SPaolo Bonzini 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5274c50d8ae3SPaolo Bonzini 	 * optimistically try to just unprotect the page and let the processor
5275c50d8ae3SPaolo Bonzini 	 * re-execute the instruction that caused the page fault.  Do not allow
5276c50d8ae3SPaolo Bonzini 	 * retrying MMIO emulation, as it's not only pointless but could also
5277c50d8ae3SPaolo Bonzini 	 * cause us to enter an infinite loop because the processor will keep
5278c50d8ae3SPaolo Bonzini 	 * faulting on the non-existent MMIO address.  Retrying an instruction
5279c50d8ae3SPaolo Bonzini 	 * from a nested guest is also pointless and dangerous as we are only
5280c50d8ae3SPaolo Bonzini 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
5281c50d8ae3SPaolo Bonzini 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5282c50d8ae3SPaolo Bonzini 	 */
5283736c291cSSean Christopherson 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
528492daa48bSSean Christopherson 		emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5285c50d8ae3SPaolo Bonzini emulate:
5286736c291cSSean Christopherson 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5287c50d8ae3SPaolo Bonzini 				       insn_len);
5288c50d8ae3SPaolo Bonzini }
5289c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5290c50d8ae3SPaolo Bonzini 
52915efac074SPaolo Bonzini void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
52925efac074SPaolo Bonzini 			    gva_t gva, hpa_t root_hpa)
5293c50d8ae3SPaolo Bonzini {
5294c50d8ae3SPaolo Bonzini 	int i;
5295c50d8ae3SPaolo Bonzini 
52965efac074SPaolo Bonzini 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
52975efac074SPaolo Bonzini 	if (mmu != &vcpu->arch.guest_mmu) {
52985efac074SPaolo Bonzini 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
5299c50d8ae3SPaolo Bonzini 		if (is_noncanonical_address(gva, vcpu))
5300c50d8ae3SPaolo Bonzini 			return;
5301c50d8ae3SPaolo Bonzini 
5302b3646477SJason Baron 		static_call(kvm_x86_tlb_flush_gva)(vcpu, gva);
53035efac074SPaolo Bonzini 	}
53045efac074SPaolo Bonzini 
53055efac074SPaolo Bonzini 	if (!mmu->invlpg)
53065efac074SPaolo Bonzini 		return;
53075efac074SPaolo Bonzini 
53085efac074SPaolo Bonzini 	if (root_hpa == INVALID_PAGE) {
5309c50d8ae3SPaolo Bonzini 		mmu->invlpg(vcpu, gva, mmu->root_hpa);
5310c50d8ae3SPaolo Bonzini 
5311c50d8ae3SPaolo Bonzini 		/*
5312c50d8ae3SPaolo Bonzini 		 * INVLPG is required to invalidate any global mappings for the VA,
5313c50d8ae3SPaolo Bonzini 		 * irrespective of PCID. Since it would take us roughly similar amount
5314c50d8ae3SPaolo Bonzini 		 * of work to determine whether any of the prev_root mappings of the VA
5315c50d8ae3SPaolo Bonzini 		 * is marked global, or to just sync it blindly, so we might as well
5316c50d8ae3SPaolo Bonzini 		 * just always sync it.
5317c50d8ae3SPaolo Bonzini 		 *
5318c50d8ae3SPaolo Bonzini 		 * Mappings not reachable via the current cr3 or the prev_roots will be
5319c50d8ae3SPaolo Bonzini 		 * synced when switching to that cr3, so nothing needs to be done here
5320c50d8ae3SPaolo Bonzini 		 * for them.
5321c50d8ae3SPaolo Bonzini 		 */
5322c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5323c50d8ae3SPaolo Bonzini 			if (VALID_PAGE(mmu->prev_roots[i].hpa))
5324c50d8ae3SPaolo Bonzini 				mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
53255efac074SPaolo Bonzini 	} else {
53265efac074SPaolo Bonzini 		mmu->invlpg(vcpu, gva, root_hpa);
53275efac074SPaolo Bonzini 	}
53285efac074SPaolo Bonzini }
5329c50d8ae3SPaolo Bonzini 
53305efac074SPaolo Bonzini void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
53315efac074SPaolo Bonzini {
53325efac074SPaolo Bonzini 	kvm_mmu_invalidate_gva(vcpu, vcpu->arch.mmu, gva, INVALID_PAGE);
5333c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5334c50d8ae3SPaolo Bonzini }
5335c50d8ae3SPaolo Bonzini EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5336c50d8ae3SPaolo Bonzini 
53375efac074SPaolo Bonzini 
5338c50d8ae3SPaolo Bonzini void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5339c50d8ae3SPaolo Bonzini {
5340c50d8ae3SPaolo Bonzini 	struct kvm_mmu *mmu = vcpu->arch.mmu;
5341c50d8ae3SPaolo Bonzini 	bool tlb_flush = false;
5342c50d8ae3SPaolo Bonzini 	uint i;
5343c50d8ae3SPaolo Bonzini 
5344c50d8ae3SPaolo Bonzini 	if (pcid == kvm_get_active_pcid(vcpu)) {
5345c50d8ae3SPaolo Bonzini 		mmu->invlpg(vcpu, gva, mmu->root_hpa);
5346c50d8ae3SPaolo Bonzini 		tlb_flush = true;
5347c50d8ae3SPaolo Bonzini 	}
5348c50d8ae3SPaolo Bonzini 
5349c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5350c50d8ae3SPaolo Bonzini 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5351be01e8e2SSean Christopherson 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
5352c50d8ae3SPaolo Bonzini 			mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5353c50d8ae3SPaolo Bonzini 			tlb_flush = true;
5354c50d8ae3SPaolo Bonzini 		}
5355c50d8ae3SPaolo Bonzini 	}
5356c50d8ae3SPaolo Bonzini 
5357c50d8ae3SPaolo Bonzini 	if (tlb_flush)
5358b3646477SJason Baron 		static_call(kvm_x86_tlb_flush_gva)(vcpu, gva);
5359c50d8ae3SPaolo Bonzini 
5360c50d8ae3SPaolo Bonzini 	++vcpu->stat.invlpg;
5361c50d8ae3SPaolo Bonzini 
5362c50d8ae3SPaolo Bonzini 	/*
5363c50d8ae3SPaolo Bonzini 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5364c50d8ae3SPaolo Bonzini 	 * synced when switching to that cr3, so nothing needs to be done here
5365c50d8ae3SPaolo Bonzini 	 * for them.
5366c50d8ae3SPaolo Bonzini 	 */
5367c50d8ae3SPaolo Bonzini }
5368c50d8ae3SPaolo Bonzini 
536983013059SSean Christopherson void kvm_configure_mmu(bool enable_tdp, int tdp_max_root_level,
537083013059SSean Christopherson 		       int tdp_huge_page_level)
5371c50d8ae3SPaolo Bonzini {
5372bde77235SSean Christopherson 	tdp_enabled = enable_tdp;
537383013059SSean Christopherson 	max_tdp_level = tdp_max_root_level;
5374703c335dSSean Christopherson 
5375703c335dSSean Christopherson 	/*
53761d92d2e8SSean Christopherson 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5377703c335dSSean Christopherson 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5378703c335dSSean Christopherson 	 * the kernel is not.  But, KVM never creates a page size greater than
5379703c335dSSean Christopherson 	 * what is used by the kernel for any given HVA, i.e. the kernel's
5380703c335dSSean Christopherson 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5381703c335dSSean Christopherson 	 */
5382703c335dSSean Christopherson 	if (tdp_enabled)
53831d92d2e8SSean Christopherson 		max_huge_page_level = tdp_huge_page_level;
5384703c335dSSean Christopherson 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
53851d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_1G;
5386703c335dSSean Christopherson 	else
53871d92d2e8SSean Christopherson 		max_huge_page_level = PG_LEVEL_2M;
5388c50d8ae3SPaolo Bonzini }
5389bde77235SSean Christopherson EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5390c50d8ae3SPaolo Bonzini 
5391c50d8ae3SPaolo Bonzini /* The return value indicates if tlb flush on all vcpus is needed. */
5392269e9552SHamza Mahfooz typedef bool (*slot_level_handler) (struct kvm *kvm,
5393269e9552SHamza Mahfooz 				    struct kvm_rmap_head *rmap_head,
5394269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot);
5395c50d8ae3SPaolo Bonzini 
5396c50d8ae3SPaolo Bonzini /* The caller should hold mmu-lock before calling this function. */
5397c50d8ae3SPaolo Bonzini static __always_inline bool
5398269e9552SHamza Mahfooz slot_handle_level_range(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5399c50d8ae3SPaolo Bonzini 			slot_level_handler fn, int start_level, int end_level,
54001a61b7dbSSean Christopherson 			gfn_t start_gfn, gfn_t end_gfn, bool flush_on_yield,
54011a61b7dbSSean Christopherson 			bool flush)
5402c50d8ae3SPaolo Bonzini {
5403c50d8ae3SPaolo Bonzini 	struct slot_rmap_walk_iterator iterator;
5404c50d8ae3SPaolo Bonzini 
5405c50d8ae3SPaolo Bonzini 	for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5406c50d8ae3SPaolo Bonzini 			end_gfn, &iterator) {
5407c50d8ae3SPaolo Bonzini 		if (iterator.rmap)
54080a234f5dSSean Christopherson 			flush |= fn(kvm, iterator.rmap, memslot);
5409c50d8ae3SPaolo Bonzini 
5410531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
5411302695a5SSean Christopherson 			if (flush && flush_on_yield) {
5412c50d8ae3SPaolo Bonzini 				kvm_flush_remote_tlbs_with_address(kvm,
5413c50d8ae3SPaolo Bonzini 						start_gfn,
5414c50d8ae3SPaolo Bonzini 						iterator.gfn - start_gfn + 1);
5415c50d8ae3SPaolo Bonzini 				flush = false;
5416c50d8ae3SPaolo Bonzini 			}
5417531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
5418c50d8ae3SPaolo Bonzini 		}
5419c50d8ae3SPaolo Bonzini 	}
5420c50d8ae3SPaolo Bonzini 
5421c50d8ae3SPaolo Bonzini 	return flush;
5422c50d8ae3SPaolo Bonzini }
5423c50d8ae3SPaolo Bonzini 
5424c50d8ae3SPaolo Bonzini static __always_inline bool
5425269e9552SHamza Mahfooz slot_handle_level(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5426c50d8ae3SPaolo Bonzini 		  slot_level_handler fn, int start_level, int end_level,
5427302695a5SSean Christopherson 		  bool flush_on_yield)
5428c50d8ae3SPaolo Bonzini {
5429c50d8ae3SPaolo Bonzini 	return slot_handle_level_range(kvm, memslot, fn, start_level,
5430c50d8ae3SPaolo Bonzini 			end_level, memslot->base_gfn,
5431c50d8ae3SPaolo Bonzini 			memslot->base_gfn + memslot->npages - 1,
54321a61b7dbSSean Christopherson 			flush_on_yield, false);
5433c50d8ae3SPaolo Bonzini }
5434c50d8ae3SPaolo Bonzini 
5435c50d8ae3SPaolo Bonzini static __always_inline bool
5436269e9552SHamza Mahfooz slot_handle_leaf(struct kvm *kvm, const struct kvm_memory_slot *memslot,
5437302695a5SSean Christopherson 		 slot_level_handler fn, bool flush_on_yield)
5438c50d8ae3SPaolo Bonzini {
54393bae0459SSean Christopherson 	return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5440302695a5SSean Christopherson 				 PG_LEVEL_4K, flush_on_yield);
5441c50d8ae3SPaolo Bonzini }
5442c50d8ae3SPaolo Bonzini 
5443c50d8ae3SPaolo Bonzini static void free_mmu_pages(struct kvm_mmu *mmu)
5444c50d8ae3SPaolo Bonzini {
54454a98623dSSean Christopherson 	if (!tdp_enabled && mmu->pae_root)
54464a98623dSSean Christopherson 		set_memory_encrypted((unsigned long)mmu->pae_root, 1);
5447c50d8ae3SPaolo Bonzini 	free_page((unsigned long)mmu->pae_root);
544803ca4589SSean Christopherson 	free_page((unsigned long)mmu->pml4_root);
5449c50d8ae3SPaolo Bonzini }
5450c50d8ae3SPaolo Bonzini 
545104d28e37SSean Christopherson static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5452c50d8ae3SPaolo Bonzini {
5453c50d8ae3SPaolo Bonzini 	struct page *page;
5454c50d8ae3SPaolo Bonzini 	int i;
5455c50d8ae3SPaolo Bonzini 
545604d28e37SSean Christopherson 	mmu->root_hpa = INVALID_PAGE;
545704d28e37SSean Christopherson 	mmu->root_pgd = 0;
545804d28e37SSean Christopherson 	mmu->translate_gpa = translate_gpa;
545904d28e37SSean Christopherson 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
546004d28e37SSean Christopherson 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
546104d28e37SSean Christopherson 
5462c50d8ae3SPaolo Bonzini 	/*
5463c50d8ae3SPaolo Bonzini 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5464c50d8ae3SPaolo Bonzini 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
5465c50d8ae3SPaolo Bonzini 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
5466c50d8ae3SPaolo Bonzini 	 * x86_64.  Therefore we need to allocate the PDP table in the first
546704d45551SSean Christopherson 	 * 4GB of memory, which happens to fit the DMA32 zone.  TDP paging
546804d45551SSean Christopherson 	 * generally doesn't use PAE paging and can skip allocating the PDP
546904d45551SSean Christopherson 	 * table.  The main exception, handled here, is SVM's 32-bit NPT.  The
547004d45551SSean Christopherson 	 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
547104d45551SSean Christopherson 	 * KVM; that horror is handled on-demand by mmu_alloc_shadow_roots().
5472c50d8ae3SPaolo Bonzini 	 */
5473d468d94bSSean Christopherson 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5474c50d8ae3SPaolo Bonzini 		return 0;
5475c50d8ae3SPaolo Bonzini 
5476c50d8ae3SPaolo Bonzini 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5477c50d8ae3SPaolo Bonzini 	if (!page)
5478c50d8ae3SPaolo Bonzini 		return -ENOMEM;
5479c50d8ae3SPaolo Bonzini 
5480c50d8ae3SPaolo Bonzini 	mmu->pae_root = page_address(page);
54814a98623dSSean Christopherson 
54824a98623dSSean Christopherson 	/*
54834a98623dSSean Christopherson 	 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
54844a98623dSSean Christopherson 	 * get the CPU to treat the PDPTEs as encrypted.  Decrypt the page so
54854a98623dSSean Christopherson 	 * that KVM's writes and the CPU's reads get along.  Note, this is
54864a98623dSSean Christopherson 	 * only necessary when using shadow paging, as 64-bit NPT can get at
54874a98623dSSean Christopherson 	 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
54884a98623dSSean Christopherson 	 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
54894a98623dSSean Christopherson 	 */
54904a98623dSSean Christopherson 	if (!tdp_enabled)
54914a98623dSSean Christopherson 		set_memory_decrypted((unsigned long)mmu->pae_root, 1);
54924a98623dSSean Christopherson 	else
54934a98623dSSean Christopherson 		WARN_ON_ONCE(shadow_me_mask);
54944a98623dSSean Christopherson 
5495c50d8ae3SPaolo Bonzini 	for (i = 0; i < 4; ++i)
5496c834e5e4SSean Christopherson 		mmu->pae_root[i] = INVALID_PAE_ROOT;
5497c50d8ae3SPaolo Bonzini 
5498c50d8ae3SPaolo Bonzini 	return 0;
5499c50d8ae3SPaolo Bonzini }
5500c50d8ae3SPaolo Bonzini 
5501c50d8ae3SPaolo Bonzini int kvm_mmu_create(struct kvm_vcpu *vcpu)
5502c50d8ae3SPaolo Bonzini {
5503c50d8ae3SPaolo Bonzini 	int ret;
5504c50d8ae3SPaolo Bonzini 
55055962bfb7SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
55065f6078f9SSean Christopherson 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
55075f6078f9SSean Christopherson 
55085962bfb7SSean Christopherson 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
55095f6078f9SSean Christopherson 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
55105962bfb7SSean Christopherson 
551196880883SSean Christopherson 	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
551296880883SSean Christopherson 
5513c50d8ae3SPaolo Bonzini 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
5514c50d8ae3SPaolo Bonzini 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5515c50d8ae3SPaolo Bonzini 
5516c50d8ae3SPaolo Bonzini 	vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5517c50d8ae3SPaolo Bonzini 
551804d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
5519c50d8ae3SPaolo Bonzini 	if (ret)
5520c50d8ae3SPaolo Bonzini 		return ret;
5521c50d8ae3SPaolo Bonzini 
552204d28e37SSean Christopherson 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
5523c50d8ae3SPaolo Bonzini 	if (ret)
5524c50d8ae3SPaolo Bonzini 		goto fail_allocate_root;
5525c50d8ae3SPaolo Bonzini 
5526c50d8ae3SPaolo Bonzini 	return ret;
5527c50d8ae3SPaolo Bonzini  fail_allocate_root:
5528c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
5529c50d8ae3SPaolo Bonzini 	return ret;
5530c50d8ae3SPaolo Bonzini }
5531c50d8ae3SPaolo Bonzini 
5532c50d8ae3SPaolo Bonzini #define BATCH_ZAP_PAGES	10
5533c50d8ae3SPaolo Bonzini static void kvm_zap_obsolete_pages(struct kvm *kvm)
5534c50d8ae3SPaolo Bonzini {
5535c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
5536c50d8ae3SPaolo Bonzini 	int nr_zapped, batch = 0;
5537c50d8ae3SPaolo Bonzini 
5538c50d8ae3SPaolo Bonzini restart:
5539c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe_reverse(sp, node,
5540c50d8ae3SPaolo Bonzini 	      &kvm->arch.active_mmu_pages, link) {
5541c50d8ae3SPaolo Bonzini 		/*
5542c50d8ae3SPaolo Bonzini 		 * No obsolete valid page exists before a newly created page
5543c50d8ae3SPaolo Bonzini 		 * since active_mmu_pages is a FIFO list.
5544c50d8ae3SPaolo Bonzini 		 */
5545c50d8ae3SPaolo Bonzini 		if (!is_obsolete_sp(kvm, sp))
5546c50d8ae3SPaolo Bonzini 			break;
5547c50d8ae3SPaolo Bonzini 
5548c50d8ae3SPaolo Bonzini 		/*
5549f95eec9bSSean Christopherson 		 * Invalid pages should never land back on the list of active
5550f95eec9bSSean Christopherson 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
5551f95eec9bSSean Christopherson 		 * infinite loop if the page gets put back on the list (again).
5552c50d8ae3SPaolo Bonzini 		 */
5553f95eec9bSSean Christopherson 		if (WARN_ON(sp->role.invalid))
5554c50d8ae3SPaolo Bonzini 			continue;
5555c50d8ae3SPaolo Bonzini 
5556c50d8ae3SPaolo Bonzini 		/*
5557c50d8ae3SPaolo Bonzini 		 * No need to flush the TLB since we're only zapping shadow
5558c50d8ae3SPaolo Bonzini 		 * pages with an obsolete generation number and all vCPUS have
5559c50d8ae3SPaolo Bonzini 		 * loaded a new root, i.e. the shadow pages being zapped cannot
5560c50d8ae3SPaolo Bonzini 		 * be in active use by the guest.
5561c50d8ae3SPaolo Bonzini 		 */
5562c50d8ae3SPaolo Bonzini 		if (batch >= BATCH_ZAP_PAGES &&
5563531810caSBen Gardon 		    cond_resched_rwlock_write(&kvm->mmu_lock)) {
5564c50d8ae3SPaolo Bonzini 			batch = 0;
5565c50d8ae3SPaolo Bonzini 			goto restart;
5566c50d8ae3SPaolo Bonzini 		}
5567c50d8ae3SPaolo Bonzini 
5568c50d8ae3SPaolo Bonzini 		if (__kvm_mmu_prepare_zap_page(kvm, sp,
5569c50d8ae3SPaolo Bonzini 				&kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
5570c50d8ae3SPaolo Bonzini 			batch += nr_zapped;
5571c50d8ae3SPaolo Bonzini 			goto restart;
5572c50d8ae3SPaolo Bonzini 		}
5573c50d8ae3SPaolo Bonzini 	}
5574c50d8ae3SPaolo Bonzini 
5575c50d8ae3SPaolo Bonzini 	/*
5576c50d8ae3SPaolo Bonzini 	 * Trigger a remote TLB flush before freeing the page tables to ensure
5577c50d8ae3SPaolo Bonzini 	 * KVM is not in the middle of a lockless shadow page table walk, which
5578c50d8ae3SPaolo Bonzini 	 * may reference the pages.
5579c50d8ae3SPaolo Bonzini 	 */
5580c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5581c50d8ae3SPaolo Bonzini }
5582c50d8ae3SPaolo Bonzini 
5583c50d8ae3SPaolo Bonzini /*
5584c50d8ae3SPaolo Bonzini  * Fast invalidate all shadow pages and use lock-break technique
5585c50d8ae3SPaolo Bonzini  * to zap obsolete pages.
5586c50d8ae3SPaolo Bonzini  *
5587c50d8ae3SPaolo Bonzini  * It's required when memslot is being deleted or VM is being
5588c50d8ae3SPaolo Bonzini  * destroyed, in these cases, we should ensure that KVM MMU does
5589c50d8ae3SPaolo Bonzini  * not use any resource of the being-deleted slot or all slots
5590c50d8ae3SPaolo Bonzini  * after calling the function.
5591c50d8ae3SPaolo Bonzini  */
5592c50d8ae3SPaolo Bonzini static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5593c50d8ae3SPaolo Bonzini {
5594c50d8ae3SPaolo Bonzini 	lockdep_assert_held(&kvm->slots_lock);
5595c50d8ae3SPaolo Bonzini 
5596531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
5597c50d8ae3SPaolo Bonzini 	trace_kvm_mmu_zap_all_fast(kvm);
5598c50d8ae3SPaolo Bonzini 
5599c50d8ae3SPaolo Bonzini 	/*
5600c50d8ae3SPaolo Bonzini 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
5601c50d8ae3SPaolo Bonzini 	 * held for the entire duration of zapping obsolete pages, it's
5602c50d8ae3SPaolo Bonzini 	 * impossible for there to be multiple invalid generations associated
5603c50d8ae3SPaolo Bonzini 	 * with *valid* shadow pages at any given time, i.e. there is exactly
5604c50d8ae3SPaolo Bonzini 	 * one valid generation and (at most) one invalid generation.
5605c50d8ae3SPaolo Bonzini 	 */
5606c50d8ae3SPaolo Bonzini 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5607c50d8ae3SPaolo Bonzini 
5608b7cccd39SBen Gardon 	/* In order to ensure all threads see this change when
5609b7cccd39SBen Gardon 	 * handling the MMU reload signal, this must happen in the
5610b7cccd39SBen Gardon 	 * same critical section as kvm_reload_remote_mmus, and
5611b7cccd39SBen Gardon 	 * before kvm_zap_obsolete_pages as kvm_zap_obsolete_pages
5612b7cccd39SBen Gardon 	 * could drop the MMU lock and yield.
5613b7cccd39SBen Gardon 	 */
5614b7cccd39SBen Gardon 	if (is_tdp_mmu_enabled(kvm))
5615b7cccd39SBen Gardon 		kvm_tdp_mmu_invalidate_all_roots(kvm);
5616b7cccd39SBen Gardon 
5617c50d8ae3SPaolo Bonzini 	/*
5618c50d8ae3SPaolo Bonzini 	 * Notify all vcpus to reload its shadow page table and flush TLB.
5619c50d8ae3SPaolo Bonzini 	 * Then all vcpus will switch to new shadow page table with the new
5620c50d8ae3SPaolo Bonzini 	 * mmu_valid_gen.
5621c50d8ae3SPaolo Bonzini 	 *
5622c50d8ae3SPaolo Bonzini 	 * Note: we need to do this under the protection of mmu_lock,
5623c50d8ae3SPaolo Bonzini 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
5624c50d8ae3SPaolo Bonzini 	 */
5625c50d8ae3SPaolo Bonzini 	kvm_reload_remote_mmus(kvm);
5626c50d8ae3SPaolo Bonzini 
5627c50d8ae3SPaolo Bonzini 	kvm_zap_obsolete_pages(kvm);
5628faaf05b0SBen Gardon 
5629531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
56304c6654bdSBen Gardon 
56314c6654bdSBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
56324c6654bdSBen Gardon 		read_lock(&kvm->mmu_lock);
56334c6654bdSBen Gardon 		kvm_tdp_mmu_zap_invalidated_roots(kvm);
56344c6654bdSBen Gardon 		read_unlock(&kvm->mmu_lock);
56354c6654bdSBen Gardon 	}
5636c50d8ae3SPaolo Bonzini }
5637c50d8ae3SPaolo Bonzini 
5638c50d8ae3SPaolo Bonzini static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5639c50d8ae3SPaolo Bonzini {
5640c50d8ae3SPaolo Bonzini 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5641c50d8ae3SPaolo Bonzini }
5642c50d8ae3SPaolo Bonzini 
5643c50d8ae3SPaolo Bonzini static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5644c50d8ae3SPaolo Bonzini 			struct kvm_memory_slot *slot,
5645c50d8ae3SPaolo Bonzini 			struct kvm_page_track_notifier_node *node)
5646c50d8ae3SPaolo Bonzini {
5647c50d8ae3SPaolo Bonzini 	kvm_mmu_zap_all_fast(kvm);
5648c50d8ae3SPaolo Bonzini }
5649c50d8ae3SPaolo Bonzini 
5650c50d8ae3SPaolo Bonzini void kvm_mmu_init_vm(struct kvm *kvm)
5651c50d8ae3SPaolo Bonzini {
5652c50d8ae3SPaolo Bonzini 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5653c50d8ae3SPaolo Bonzini 
5654ce25681dSSean Christopherson 	spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
5655ce25681dSSean Christopherson 
5656d501f747SBen Gardon 	if (!kvm_mmu_init_tdp_mmu(kvm))
5657d501f747SBen Gardon 		/*
5658d501f747SBen Gardon 		 * No smp_load/store wrappers needed here as we are in
5659d501f747SBen Gardon 		 * VM init and there cannot be any memslots / other threads
5660d501f747SBen Gardon 		 * accessing this struct kvm yet.
5661d501f747SBen Gardon 		 */
5662a2557408SBen Gardon 		kvm->arch.memslots_have_rmaps = true;
5663fe5db27dSBen Gardon 
5664c50d8ae3SPaolo Bonzini 	node->track_write = kvm_mmu_pte_write;
5665c50d8ae3SPaolo Bonzini 	node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5666c50d8ae3SPaolo Bonzini 	kvm_page_track_register_notifier(kvm, node);
5667c50d8ae3SPaolo Bonzini }
5668c50d8ae3SPaolo Bonzini 
5669c50d8ae3SPaolo Bonzini void kvm_mmu_uninit_vm(struct kvm *kvm)
5670c50d8ae3SPaolo Bonzini {
5671c50d8ae3SPaolo Bonzini 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5672c50d8ae3SPaolo Bonzini 
5673c50d8ae3SPaolo Bonzini 	kvm_page_track_unregister_notifier(kvm, node);
5674fe5db27dSBen Gardon 
5675fe5db27dSBen Gardon 	kvm_mmu_uninit_tdp_mmu(kvm);
5676c50d8ae3SPaolo Bonzini }
5677c50d8ae3SPaolo Bonzini 
5678c50d8ae3SPaolo Bonzini void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5679c50d8ae3SPaolo Bonzini {
5680c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
5681c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *memslot;
5682c50d8ae3SPaolo Bonzini 	int i;
56831a61b7dbSSean Christopherson 	bool flush = false;
5684c50d8ae3SPaolo Bonzini 
5685531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
5686*5a324c24SSean Christopherson 
5687*5a324c24SSean Christopherson 	if (kvm_memslots_have_rmaps(kvm)) {
5688c50d8ae3SPaolo Bonzini 		for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5689c50d8ae3SPaolo Bonzini 			slots = __kvm_memslots(kvm, i);
5690c50d8ae3SPaolo Bonzini 			kvm_for_each_memslot(memslot, slots) {
5691c50d8ae3SPaolo Bonzini 				gfn_t start, end;
5692c50d8ae3SPaolo Bonzini 
5693c50d8ae3SPaolo Bonzini 				start = max(gfn_start, memslot->base_gfn);
5694c50d8ae3SPaolo Bonzini 				end = min(gfn_end, memslot->base_gfn + memslot->npages);
5695c50d8ae3SPaolo Bonzini 				if (start >= end)
5696c50d8ae3SPaolo Bonzini 					continue;
5697c50d8ae3SPaolo Bonzini 
5698269e9552SHamza Mahfooz 				flush = slot_handle_level_range(kvm,
5699269e9552SHamza Mahfooz 						(const struct kvm_memory_slot *) memslot,
5700e2209710SBen Gardon 						kvm_zap_rmapp, PG_LEVEL_4K,
5701e2209710SBen Gardon 						KVM_MAX_HUGEPAGE_LEVEL, start,
5702e2209710SBen Gardon 						end - 1, true, flush);
5703c50d8ae3SPaolo Bonzini 			}
5704c50d8ae3SPaolo Bonzini 		}
5705faaf05b0SBen Gardon 		if (flush)
57061a61b7dbSSean Christopherson 			kvm_flush_remote_tlbs_with_address(kvm, gfn_start, gfn_end);
5707e2209710SBen Gardon 	}
57086103bc07SBen Gardon 
57096103bc07SBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
57106103bc07SBen Gardon 		for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
57116103bc07SBen Gardon 			flush = kvm_tdp_mmu_zap_gfn_range(kvm, i, gfn_start,
5712*5a324c24SSean Christopherson 							  gfn_end, flush);
57136103bc07SBen Gardon 	}
5714*5a324c24SSean Christopherson 
5715*5a324c24SSean Christopherson 	if (flush)
5716*5a324c24SSean Christopherson 		kvm_flush_remote_tlbs_with_address(kvm, gfn_start, gfn_end);
5717*5a324c24SSean Christopherson 
5718*5a324c24SSean Christopherson 	write_unlock(&kvm->mmu_lock);
5719c50d8ae3SPaolo Bonzini }
5720c50d8ae3SPaolo Bonzini 
5721c50d8ae3SPaolo Bonzini static bool slot_rmap_write_protect(struct kvm *kvm,
57220a234f5dSSean Christopherson 				    struct kvm_rmap_head *rmap_head,
5723269e9552SHamza Mahfooz 				    const struct kvm_memory_slot *slot)
5724c50d8ae3SPaolo Bonzini {
5725c50d8ae3SPaolo Bonzini 	return __rmap_write_protect(kvm, rmap_head, false);
5726c50d8ae3SPaolo Bonzini }
5727c50d8ae3SPaolo Bonzini 
5728c50d8ae3SPaolo Bonzini void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5729269e9552SHamza Mahfooz 				      const struct kvm_memory_slot *memslot,
57303c9bd400SJay Zhou 				      int start_level)
5731c50d8ae3SPaolo Bonzini {
5732e2209710SBen Gardon 	bool flush = false;
5733c50d8ae3SPaolo Bonzini 
5734e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
5735531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
57363c9bd400SJay Zhou 		flush = slot_handle_level(kvm, memslot, slot_rmap_write_protect,
5737e2209710SBen Gardon 					  start_level, KVM_MAX_HUGEPAGE_LEVEL,
5738e2209710SBen Gardon 					  false);
5739531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
5740e2209710SBen Gardon 	}
5741c50d8ae3SPaolo Bonzini 
574224ae4cfaSBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
574324ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
574424ae4cfaSBen Gardon 		flush |= kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
574524ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
574624ae4cfaSBen Gardon 	}
574724ae4cfaSBen Gardon 
5748c50d8ae3SPaolo Bonzini 	/*
5749c50d8ae3SPaolo Bonzini 	 * We can flush all the TLBs out of the mmu lock without TLB
5750c50d8ae3SPaolo Bonzini 	 * corruption since we just change the spte from writable to
5751c50d8ae3SPaolo Bonzini 	 * readonly so that we only need to care the case of changing
5752c50d8ae3SPaolo Bonzini 	 * spte from present to present (changing the spte from present
5753c50d8ae3SPaolo Bonzini 	 * to nonpresent will flush all the TLBs immediately), in other
5754c50d8ae3SPaolo Bonzini 	 * words, the only case we care is mmu_spte_update() where we
57555fc3424fSSean Christopherson 	 * have checked Host-writable | MMU-writable instead of
57565fc3424fSSean Christopherson 	 * PT_WRITABLE_MASK, that means it does not depend on PT_WRITABLE_MASK
57575fc3424fSSean Christopherson 	 * anymore.
5758c50d8ae3SPaolo Bonzini 	 */
5759c50d8ae3SPaolo Bonzini 	if (flush)
57607f42aa76SSean Christopherson 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
5761c50d8ae3SPaolo Bonzini }
5762c50d8ae3SPaolo Bonzini 
5763c50d8ae3SPaolo Bonzini static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
57640a234f5dSSean Christopherson 					 struct kvm_rmap_head *rmap_head,
5765269e9552SHamza Mahfooz 					 const struct kvm_memory_slot *slot)
5766c50d8ae3SPaolo Bonzini {
5767c50d8ae3SPaolo Bonzini 	u64 *sptep;
5768c50d8ae3SPaolo Bonzini 	struct rmap_iterator iter;
5769c50d8ae3SPaolo Bonzini 	int need_tlb_flush = 0;
5770c50d8ae3SPaolo Bonzini 	kvm_pfn_t pfn;
5771c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
5772c50d8ae3SPaolo Bonzini 
5773c50d8ae3SPaolo Bonzini restart:
5774c50d8ae3SPaolo Bonzini 	for_each_rmap_spte(rmap_head, &iter, sptep) {
577557354682SSean Christopherson 		sp = sptep_to_sp(sptep);
5776c50d8ae3SPaolo Bonzini 		pfn = spte_to_pfn(*sptep);
5777c50d8ae3SPaolo Bonzini 
5778c50d8ae3SPaolo Bonzini 		/*
5779c50d8ae3SPaolo Bonzini 		 * We cannot do huge page mapping for indirect shadow pages,
5780c50d8ae3SPaolo Bonzini 		 * which are found on the last rmap (level = 1) when not using
5781c50d8ae3SPaolo Bonzini 		 * tdp; such shadow pages are synced with the page table in
5782c50d8ae3SPaolo Bonzini 		 * the guest, and the guest page table is using 4K page size
5783c50d8ae3SPaolo Bonzini 		 * mapping if the indirect sp has level = 1.
5784c50d8ae3SPaolo Bonzini 		 */
5785c50d8ae3SPaolo Bonzini 		if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
57869eba50f8SSean Christopherson 		    sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
57879eba50f8SSean Christopherson 							       pfn, PG_LEVEL_NUM)) {
5788c50d8ae3SPaolo Bonzini 			pte_list_remove(rmap_head, sptep);
5789c50d8ae3SPaolo Bonzini 
5790c50d8ae3SPaolo Bonzini 			if (kvm_available_flush_tlb_with_range())
5791c50d8ae3SPaolo Bonzini 				kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5792c50d8ae3SPaolo Bonzini 					KVM_PAGES_PER_HPAGE(sp->role.level));
5793c50d8ae3SPaolo Bonzini 			else
5794c50d8ae3SPaolo Bonzini 				need_tlb_flush = 1;
5795c50d8ae3SPaolo Bonzini 
5796c50d8ae3SPaolo Bonzini 			goto restart;
5797c50d8ae3SPaolo Bonzini 		}
5798c50d8ae3SPaolo Bonzini 	}
5799c50d8ae3SPaolo Bonzini 
5800c50d8ae3SPaolo Bonzini 	return need_tlb_flush;
5801c50d8ae3SPaolo Bonzini }
5802c50d8ae3SPaolo Bonzini 
5803c50d8ae3SPaolo Bonzini void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5804269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *slot)
5805c50d8ae3SPaolo Bonzini {
580631c65657SColin Ian King 	bool flush = false;
58079eba50f8SSean Christopherson 
5808e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
5809531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
5810302695a5SSean Christopherson 		flush = slot_handle_leaf(kvm, slot, kvm_mmu_zap_collapsible_spte, true);
5811302695a5SSean Christopherson 		if (flush)
5812302695a5SSean Christopherson 			kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
5813531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
5814e2209710SBen Gardon 	}
58152db6f772SBen Gardon 
58162db6f772SBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
58172db6f772SBen Gardon 		read_lock(&kvm->mmu_lock);
58182db6f772SBen Gardon 		flush = kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot, flush);
58192db6f772SBen Gardon 		if (flush)
58202db6f772SBen Gardon 			kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
58212db6f772SBen Gardon 		read_unlock(&kvm->mmu_lock);
58222db6f772SBen Gardon 	}
5823c50d8ae3SPaolo Bonzini }
5824c50d8ae3SPaolo Bonzini 
5825b3594ffbSSean Christopherson void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
58266c9dd6d2SPaolo Bonzini 					const struct kvm_memory_slot *memslot)
5827b3594ffbSSean Christopherson {
5828b3594ffbSSean Christopherson 	/*
58297f42aa76SSean Christopherson 	 * All current use cases for flushing the TLBs for a specific memslot
5830302695a5SSean Christopherson 	 * related to dirty logging, and many do the TLB flush out of mmu_lock.
58317f42aa76SSean Christopherson 	 * The interaction between the various operations on memslot must be
58327f42aa76SSean Christopherson 	 * serialized by slots_locks to ensure the TLB flush from one operation
58337f42aa76SSean Christopherson 	 * is observed by any other operation on the same memslot.
5834b3594ffbSSean Christopherson 	 */
5835b3594ffbSSean Christopherson 	lockdep_assert_held(&kvm->slots_lock);
5836cec37648SSean Christopherson 	kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5837cec37648SSean Christopherson 					   memslot->npages);
5838b3594ffbSSean Christopherson }
5839b3594ffbSSean Christopherson 
5840c50d8ae3SPaolo Bonzini void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5841269e9552SHamza Mahfooz 				   const struct kvm_memory_slot *memslot)
5842c50d8ae3SPaolo Bonzini {
5843e2209710SBen Gardon 	bool flush = false;
5844c50d8ae3SPaolo Bonzini 
5845e2209710SBen Gardon 	if (kvm_memslots_have_rmaps(kvm)) {
5846531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
5847e2209710SBen Gardon 		flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty,
5848e2209710SBen Gardon 					 false);
5849531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
5850e2209710SBen Gardon 	}
5851c50d8ae3SPaolo Bonzini 
585224ae4cfaSBen Gardon 	if (is_tdp_mmu_enabled(kvm)) {
585324ae4cfaSBen Gardon 		read_lock(&kvm->mmu_lock);
585424ae4cfaSBen Gardon 		flush |= kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
585524ae4cfaSBen Gardon 		read_unlock(&kvm->mmu_lock);
585624ae4cfaSBen Gardon 	}
585724ae4cfaSBen Gardon 
5858c50d8ae3SPaolo Bonzini 	/*
5859c50d8ae3SPaolo Bonzini 	 * It's also safe to flush TLBs out of mmu lock here as currently this
5860c50d8ae3SPaolo Bonzini 	 * function is only used for dirty logging, in which case flushing TLB
5861c50d8ae3SPaolo Bonzini 	 * out of mmu lock also guarantees no dirty pages will be lost in
5862c50d8ae3SPaolo Bonzini 	 * dirty_bitmap.
5863c50d8ae3SPaolo Bonzini 	 */
5864c50d8ae3SPaolo Bonzini 	if (flush)
58657f42aa76SSean Christopherson 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
5866c50d8ae3SPaolo Bonzini }
5867c50d8ae3SPaolo Bonzini 
5868c50d8ae3SPaolo Bonzini void kvm_mmu_zap_all(struct kvm *kvm)
5869c50d8ae3SPaolo Bonzini {
5870c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp, *node;
5871c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
5872c50d8ae3SPaolo Bonzini 	int ign;
5873c50d8ae3SPaolo Bonzini 
5874531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
5875c50d8ae3SPaolo Bonzini restart:
5876c50d8ae3SPaolo Bonzini 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
5877f95eec9bSSean Christopherson 		if (WARN_ON(sp->role.invalid))
5878c50d8ae3SPaolo Bonzini 			continue;
5879c50d8ae3SPaolo Bonzini 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
5880c50d8ae3SPaolo Bonzini 			goto restart;
5881531810caSBen Gardon 		if (cond_resched_rwlock_write(&kvm->mmu_lock))
5882c50d8ae3SPaolo Bonzini 			goto restart;
5883c50d8ae3SPaolo Bonzini 	}
5884c50d8ae3SPaolo Bonzini 
5885c50d8ae3SPaolo Bonzini 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
5886faaf05b0SBen Gardon 
5887897218ffSPaolo Bonzini 	if (is_tdp_mmu_enabled(kvm))
5888faaf05b0SBen Gardon 		kvm_tdp_mmu_zap_all(kvm);
5889faaf05b0SBen Gardon 
5890531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
5891c50d8ae3SPaolo Bonzini }
5892c50d8ae3SPaolo Bonzini 
5893c50d8ae3SPaolo Bonzini void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5894c50d8ae3SPaolo Bonzini {
5895c50d8ae3SPaolo Bonzini 	WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
5896c50d8ae3SPaolo Bonzini 
5897c50d8ae3SPaolo Bonzini 	gen &= MMIO_SPTE_GEN_MASK;
5898c50d8ae3SPaolo Bonzini 
5899c50d8ae3SPaolo Bonzini 	/*
5900c50d8ae3SPaolo Bonzini 	 * Generation numbers are incremented in multiples of the number of
5901c50d8ae3SPaolo Bonzini 	 * address spaces in order to provide unique generations across all
5902c50d8ae3SPaolo Bonzini 	 * address spaces.  Strip what is effectively the address space
5903c50d8ae3SPaolo Bonzini 	 * modifier prior to checking for a wrap of the MMIO generation so
5904c50d8ae3SPaolo Bonzini 	 * that a wrap in any address space is detected.
5905c50d8ae3SPaolo Bonzini 	 */
5906c50d8ae3SPaolo Bonzini 	gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5907c50d8ae3SPaolo Bonzini 
5908c50d8ae3SPaolo Bonzini 	/*
5909c50d8ae3SPaolo Bonzini 	 * The very rare case: if the MMIO generation number has wrapped,
5910c50d8ae3SPaolo Bonzini 	 * zap all shadow pages.
5911c50d8ae3SPaolo Bonzini 	 */
5912c50d8ae3SPaolo Bonzini 	if (unlikely(gen == 0)) {
5913c50d8ae3SPaolo Bonzini 		kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5914c50d8ae3SPaolo Bonzini 		kvm_mmu_zap_all_fast(kvm);
5915c50d8ae3SPaolo Bonzini 	}
5916c50d8ae3SPaolo Bonzini }
5917c50d8ae3SPaolo Bonzini 
5918c50d8ae3SPaolo Bonzini static unsigned long
5919c50d8ae3SPaolo Bonzini mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5920c50d8ae3SPaolo Bonzini {
5921c50d8ae3SPaolo Bonzini 	struct kvm *kvm;
5922c50d8ae3SPaolo Bonzini 	int nr_to_scan = sc->nr_to_scan;
5923c50d8ae3SPaolo Bonzini 	unsigned long freed = 0;
5924c50d8ae3SPaolo Bonzini 
5925c50d8ae3SPaolo Bonzini 	mutex_lock(&kvm_lock);
5926c50d8ae3SPaolo Bonzini 
5927c50d8ae3SPaolo Bonzini 	list_for_each_entry(kvm, &vm_list, vm_list) {
5928c50d8ae3SPaolo Bonzini 		int idx;
5929c50d8ae3SPaolo Bonzini 		LIST_HEAD(invalid_list);
5930c50d8ae3SPaolo Bonzini 
5931c50d8ae3SPaolo Bonzini 		/*
5932c50d8ae3SPaolo Bonzini 		 * Never scan more than sc->nr_to_scan VM instances.
5933c50d8ae3SPaolo Bonzini 		 * Will not hit this condition practically since we do not try
5934c50d8ae3SPaolo Bonzini 		 * to shrink more than one VM and it is very unlikely to see
5935c50d8ae3SPaolo Bonzini 		 * !n_used_mmu_pages so many times.
5936c50d8ae3SPaolo Bonzini 		 */
5937c50d8ae3SPaolo Bonzini 		if (!nr_to_scan--)
5938c50d8ae3SPaolo Bonzini 			break;
5939c50d8ae3SPaolo Bonzini 		/*
5940c50d8ae3SPaolo Bonzini 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5941c50d8ae3SPaolo Bonzini 		 * here. We may skip a VM instance errorneosly, but we do not
5942c50d8ae3SPaolo Bonzini 		 * want to shrink a VM that only started to populate its MMU
5943c50d8ae3SPaolo Bonzini 		 * anyway.
5944c50d8ae3SPaolo Bonzini 		 */
5945c50d8ae3SPaolo Bonzini 		if (!kvm->arch.n_used_mmu_pages &&
5946c50d8ae3SPaolo Bonzini 		    !kvm_has_zapped_obsolete_pages(kvm))
5947c50d8ae3SPaolo Bonzini 			continue;
5948c50d8ae3SPaolo Bonzini 
5949c50d8ae3SPaolo Bonzini 		idx = srcu_read_lock(&kvm->srcu);
5950531810caSBen Gardon 		write_lock(&kvm->mmu_lock);
5951c50d8ae3SPaolo Bonzini 
5952c50d8ae3SPaolo Bonzini 		if (kvm_has_zapped_obsolete_pages(kvm)) {
5953c50d8ae3SPaolo Bonzini 			kvm_mmu_commit_zap_page(kvm,
5954c50d8ae3SPaolo Bonzini 			      &kvm->arch.zapped_obsolete_pages);
5955c50d8ae3SPaolo Bonzini 			goto unlock;
5956c50d8ae3SPaolo Bonzini 		}
5957c50d8ae3SPaolo Bonzini 
5958ebdb292dSSean Christopherson 		freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
5959c50d8ae3SPaolo Bonzini 
5960c50d8ae3SPaolo Bonzini unlock:
5961531810caSBen Gardon 		write_unlock(&kvm->mmu_lock);
5962c50d8ae3SPaolo Bonzini 		srcu_read_unlock(&kvm->srcu, idx);
5963c50d8ae3SPaolo Bonzini 
5964c50d8ae3SPaolo Bonzini 		/*
5965c50d8ae3SPaolo Bonzini 		 * unfair on small ones
5966c50d8ae3SPaolo Bonzini 		 * per-vm shrinkers cry out
5967c50d8ae3SPaolo Bonzini 		 * sadness comes quickly
5968c50d8ae3SPaolo Bonzini 		 */
5969c50d8ae3SPaolo Bonzini 		list_move_tail(&kvm->vm_list, &vm_list);
5970c50d8ae3SPaolo Bonzini 		break;
5971c50d8ae3SPaolo Bonzini 	}
5972c50d8ae3SPaolo Bonzini 
5973c50d8ae3SPaolo Bonzini 	mutex_unlock(&kvm_lock);
5974c50d8ae3SPaolo Bonzini 	return freed;
5975c50d8ae3SPaolo Bonzini }
5976c50d8ae3SPaolo Bonzini 
5977c50d8ae3SPaolo Bonzini static unsigned long
5978c50d8ae3SPaolo Bonzini mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
5979c50d8ae3SPaolo Bonzini {
5980c50d8ae3SPaolo Bonzini 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
5981c50d8ae3SPaolo Bonzini }
5982c50d8ae3SPaolo Bonzini 
5983c50d8ae3SPaolo Bonzini static struct shrinker mmu_shrinker = {
5984c50d8ae3SPaolo Bonzini 	.count_objects = mmu_shrink_count,
5985c50d8ae3SPaolo Bonzini 	.scan_objects = mmu_shrink_scan,
5986c50d8ae3SPaolo Bonzini 	.seeks = DEFAULT_SEEKS * 10,
5987c50d8ae3SPaolo Bonzini };
5988c50d8ae3SPaolo Bonzini 
5989c50d8ae3SPaolo Bonzini static void mmu_destroy_caches(void)
5990c50d8ae3SPaolo Bonzini {
5991c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(pte_list_desc_cache);
5992c50d8ae3SPaolo Bonzini 	kmem_cache_destroy(mmu_page_header_cache);
5993c50d8ae3SPaolo Bonzini }
5994c50d8ae3SPaolo Bonzini 
5995c50d8ae3SPaolo Bonzini static bool get_nx_auto_mode(void)
5996c50d8ae3SPaolo Bonzini {
5997c50d8ae3SPaolo Bonzini 	/* Return true when CPU has the bug, and mitigations are ON */
5998c50d8ae3SPaolo Bonzini 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
5999c50d8ae3SPaolo Bonzini }
6000c50d8ae3SPaolo Bonzini 
6001c50d8ae3SPaolo Bonzini static void __set_nx_huge_pages(bool val)
6002c50d8ae3SPaolo Bonzini {
6003c50d8ae3SPaolo Bonzini 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6004c50d8ae3SPaolo Bonzini }
6005c50d8ae3SPaolo Bonzini 
6006c50d8ae3SPaolo Bonzini static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6007c50d8ae3SPaolo Bonzini {
6008c50d8ae3SPaolo Bonzini 	bool old_val = nx_huge_pages;
6009c50d8ae3SPaolo Bonzini 	bool new_val;
6010c50d8ae3SPaolo Bonzini 
6011c50d8ae3SPaolo Bonzini 	/* In "auto" mode deploy workaround only if CPU has the bug. */
6012c50d8ae3SPaolo Bonzini 	if (sysfs_streq(val, "off"))
6013c50d8ae3SPaolo Bonzini 		new_val = 0;
6014c50d8ae3SPaolo Bonzini 	else if (sysfs_streq(val, "force"))
6015c50d8ae3SPaolo Bonzini 		new_val = 1;
6016c50d8ae3SPaolo Bonzini 	else if (sysfs_streq(val, "auto"))
6017c50d8ae3SPaolo Bonzini 		new_val = get_nx_auto_mode();
6018c50d8ae3SPaolo Bonzini 	else if (strtobool(val, &new_val) < 0)
6019c50d8ae3SPaolo Bonzini 		return -EINVAL;
6020c50d8ae3SPaolo Bonzini 
6021c50d8ae3SPaolo Bonzini 	__set_nx_huge_pages(new_val);
6022c50d8ae3SPaolo Bonzini 
6023c50d8ae3SPaolo Bonzini 	if (new_val != old_val) {
6024c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6025c50d8ae3SPaolo Bonzini 
6026c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6027c50d8ae3SPaolo Bonzini 
6028c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list) {
6029c50d8ae3SPaolo Bonzini 			mutex_lock(&kvm->slots_lock);
6030c50d8ae3SPaolo Bonzini 			kvm_mmu_zap_all_fast(kvm);
6031c50d8ae3SPaolo Bonzini 			mutex_unlock(&kvm->slots_lock);
6032c50d8ae3SPaolo Bonzini 
6033c50d8ae3SPaolo Bonzini 			wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6034c50d8ae3SPaolo Bonzini 		}
6035c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6036c50d8ae3SPaolo Bonzini 	}
6037c50d8ae3SPaolo Bonzini 
6038c50d8ae3SPaolo Bonzini 	return 0;
6039c50d8ae3SPaolo Bonzini }
6040c50d8ae3SPaolo Bonzini 
6041c50d8ae3SPaolo Bonzini int kvm_mmu_module_init(void)
6042c50d8ae3SPaolo Bonzini {
6043c50d8ae3SPaolo Bonzini 	int ret = -ENOMEM;
6044c50d8ae3SPaolo Bonzini 
6045c50d8ae3SPaolo Bonzini 	if (nx_huge_pages == -1)
6046c50d8ae3SPaolo Bonzini 		__set_nx_huge_pages(get_nx_auto_mode());
6047c50d8ae3SPaolo Bonzini 
6048c50d8ae3SPaolo Bonzini 	/*
6049c50d8ae3SPaolo Bonzini 	 * MMU roles use union aliasing which is, generally speaking, an
6050c50d8ae3SPaolo Bonzini 	 * undefined behavior. However, we supposedly know how compilers behave
6051c50d8ae3SPaolo Bonzini 	 * and the current status quo is unlikely to change. Guardians below are
6052c50d8ae3SPaolo Bonzini 	 * supposed to let us know if the assumption becomes false.
6053c50d8ae3SPaolo Bonzini 	 */
6054c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6055c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6056c50d8ae3SPaolo Bonzini 	BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6057c50d8ae3SPaolo Bonzini 
6058c50d8ae3SPaolo Bonzini 	kvm_mmu_reset_all_pte_masks();
6059c50d8ae3SPaolo Bonzini 
6060c50d8ae3SPaolo Bonzini 	pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6061c50d8ae3SPaolo Bonzini 					    sizeof(struct pte_list_desc),
6062c50d8ae3SPaolo Bonzini 					    0, SLAB_ACCOUNT, NULL);
6063c50d8ae3SPaolo Bonzini 	if (!pte_list_desc_cache)
6064c50d8ae3SPaolo Bonzini 		goto out;
6065c50d8ae3SPaolo Bonzini 
6066c50d8ae3SPaolo Bonzini 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6067c50d8ae3SPaolo Bonzini 						  sizeof(struct kvm_mmu_page),
6068c50d8ae3SPaolo Bonzini 						  0, SLAB_ACCOUNT, NULL);
6069c50d8ae3SPaolo Bonzini 	if (!mmu_page_header_cache)
6070c50d8ae3SPaolo Bonzini 		goto out;
6071c50d8ae3SPaolo Bonzini 
6072c50d8ae3SPaolo Bonzini 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6073c50d8ae3SPaolo Bonzini 		goto out;
6074c50d8ae3SPaolo Bonzini 
6075c50d8ae3SPaolo Bonzini 	ret = register_shrinker(&mmu_shrinker);
6076c50d8ae3SPaolo Bonzini 	if (ret)
6077c50d8ae3SPaolo Bonzini 		goto out;
6078c50d8ae3SPaolo Bonzini 
6079c50d8ae3SPaolo Bonzini 	return 0;
6080c50d8ae3SPaolo Bonzini 
6081c50d8ae3SPaolo Bonzini out:
6082c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6083c50d8ae3SPaolo Bonzini 	return ret;
6084c50d8ae3SPaolo Bonzini }
6085c50d8ae3SPaolo Bonzini 
6086c50d8ae3SPaolo Bonzini /*
6087c50d8ae3SPaolo Bonzini  * Calculate mmu pages needed for kvm.
6088c50d8ae3SPaolo Bonzini  */
6089c50d8ae3SPaolo Bonzini unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6090c50d8ae3SPaolo Bonzini {
6091c50d8ae3SPaolo Bonzini 	unsigned long nr_mmu_pages;
6092c50d8ae3SPaolo Bonzini 	unsigned long nr_pages = 0;
6093c50d8ae3SPaolo Bonzini 	struct kvm_memslots *slots;
6094c50d8ae3SPaolo Bonzini 	struct kvm_memory_slot *memslot;
6095c50d8ae3SPaolo Bonzini 	int i;
6096c50d8ae3SPaolo Bonzini 
6097c50d8ae3SPaolo Bonzini 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6098c50d8ae3SPaolo Bonzini 		slots = __kvm_memslots(kvm, i);
6099c50d8ae3SPaolo Bonzini 
6100c50d8ae3SPaolo Bonzini 		kvm_for_each_memslot(memslot, slots)
6101c50d8ae3SPaolo Bonzini 			nr_pages += memslot->npages;
6102c50d8ae3SPaolo Bonzini 	}
6103c50d8ae3SPaolo Bonzini 
6104c50d8ae3SPaolo Bonzini 	nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6105c50d8ae3SPaolo Bonzini 	nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6106c50d8ae3SPaolo Bonzini 
6107c50d8ae3SPaolo Bonzini 	return nr_mmu_pages;
6108c50d8ae3SPaolo Bonzini }
6109c50d8ae3SPaolo Bonzini 
6110c50d8ae3SPaolo Bonzini void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6111c50d8ae3SPaolo Bonzini {
6112c50d8ae3SPaolo Bonzini 	kvm_mmu_unload(vcpu);
6113c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.root_mmu);
6114c50d8ae3SPaolo Bonzini 	free_mmu_pages(&vcpu->arch.guest_mmu);
6115c50d8ae3SPaolo Bonzini 	mmu_free_memory_caches(vcpu);
6116c50d8ae3SPaolo Bonzini }
6117c50d8ae3SPaolo Bonzini 
6118c50d8ae3SPaolo Bonzini void kvm_mmu_module_exit(void)
6119c50d8ae3SPaolo Bonzini {
6120c50d8ae3SPaolo Bonzini 	mmu_destroy_caches();
6121c50d8ae3SPaolo Bonzini 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6122c50d8ae3SPaolo Bonzini 	unregister_shrinker(&mmu_shrinker);
6123c50d8ae3SPaolo Bonzini 	mmu_audit_disable();
6124c50d8ae3SPaolo Bonzini }
6125c50d8ae3SPaolo Bonzini 
6126c50d8ae3SPaolo Bonzini static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
6127c50d8ae3SPaolo Bonzini {
6128c50d8ae3SPaolo Bonzini 	unsigned int old_val;
6129c50d8ae3SPaolo Bonzini 	int err;
6130c50d8ae3SPaolo Bonzini 
6131c50d8ae3SPaolo Bonzini 	old_val = nx_huge_pages_recovery_ratio;
6132c50d8ae3SPaolo Bonzini 	err = param_set_uint(val, kp);
6133c50d8ae3SPaolo Bonzini 	if (err)
6134c50d8ae3SPaolo Bonzini 		return err;
6135c50d8ae3SPaolo Bonzini 
6136c50d8ae3SPaolo Bonzini 	if (READ_ONCE(nx_huge_pages) &&
6137c50d8ae3SPaolo Bonzini 	    !old_val && nx_huge_pages_recovery_ratio) {
6138c50d8ae3SPaolo Bonzini 		struct kvm *kvm;
6139c50d8ae3SPaolo Bonzini 
6140c50d8ae3SPaolo Bonzini 		mutex_lock(&kvm_lock);
6141c50d8ae3SPaolo Bonzini 
6142c50d8ae3SPaolo Bonzini 		list_for_each_entry(kvm, &vm_list, vm_list)
6143c50d8ae3SPaolo Bonzini 			wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6144c50d8ae3SPaolo Bonzini 
6145c50d8ae3SPaolo Bonzini 		mutex_unlock(&kvm_lock);
6146c50d8ae3SPaolo Bonzini 	}
6147c50d8ae3SPaolo Bonzini 
6148c50d8ae3SPaolo Bonzini 	return err;
6149c50d8ae3SPaolo Bonzini }
6150c50d8ae3SPaolo Bonzini 
6151c50d8ae3SPaolo Bonzini static void kvm_recover_nx_lpages(struct kvm *kvm)
6152c50d8ae3SPaolo Bonzini {
6153ade74e14SSean Christopherson 	unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
6154c50d8ae3SPaolo Bonzini 	int rcu_idx;
6155c50d8ae3SPaolo Bonzini 	struct kvm_mmu_page *sp;
6156c50d8ae3SPaolo Bonzini 	unsigned int ratio;
6157c50d8ae3SPaolo Bonzini 	LIST_HEAD(invalid_list);
6158048f4980SSean Christopherson 	bool flush = false;
6159c50d8ae3SPaolo Bonzini 	ulong to_zap;
6160c50d8ae3SPaolo Bonzini 
6161c50d8ae3SPaolo Bonzini 	rcu_idx = srcu_read_lock(&kvm->srcu);
6162531810caSBen Gardon 	write_lock(&kvm->mmu_lock);
6163c50d8ae3SPaolo Bonzini 
6164c50d8ae3SPaolo Bonzini 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6165ade74e14SSean Christopherson 	to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
61667d919c7aSSean Christopherson 	for ( ; to_zap; --to_zap) {
61677d919c7aSSean Christopherson 		if (list_empty(&kvm->arch.lpage_disallowed_mmu_pages))
61687d919c7aSSean Christopherson 			break;
61697d919c7aSSean Christopherson 
6170c50d8ae3SPaolo Bonzini 		/*
6171c50d8ae3SPaolo Bonzini 		 * We use a separate list instead of just using active_mmu_pages
6172c50d8ae3SPaolo Bonzini 		 * because the number of lpage_disallowed pages is expected to
6173c50d8ae3SPaolo Bonzini 		 * be relatively small compared to the total.
6174c50d8ae3SPaolo Bonzini 		 */
6175c50d8ae3SPaolo Bonzini 		sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6176c50d8ae3SPaolo Bonzini 				      struct kvm_mmu_page,
6177c50d8ae3SPaolo Bonzini 				      lpage_disallowed_link);
6178c50d8ae3SPaolo Bonzini 		WARN_ON_ONCE(!sp->lpage_disallowed);
6179897218ffSPaolo Bonzini 		if (is_tdp_mmu_page(sp)) {
6180315f02c6SPaolo Bonzini 			flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
61818d1a182eSBen Gardon 		} else {
6182c50d8ae3SPaolo Bonzini 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6183c50d8ae3SPaolo Bonzini 			WARN_ON_ONCE(sp->lpage_disallowed);
618429cf0f50SBen Gardon 		}
6185c50d8ae3SPaolo Bonzini 
6186531810caSBen Gardon 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
6187048f4980SSean Christopherson 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
6188531810caSBen Gardon 			cond_resched_rwlock_write(&kvm->mmu_lock);
6189048f4980SSean Christopherson 			flush = false;
6190c50d8ae3SPaolo Bonzini 		}
6191c50d8ae3SPaolo Bonzini 	}
6192048f4980SSean Christopherson 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
6193c50d8ae3SPaolo Bonzini 
6194531810caSBen Gardon 	write_unlock(&kvm->mmu_lock);
6195c50d8ae3SPaolo Bonzini 	srcu_read_unlock(&kvm->srcu, rcu_idx);
6196c50d8ae3SPaolo Bonzini }
6197c50d8ae3SPaolo Bonzini 
6198c50d8ae3SPaolo Bonzini static long get_nx_lpage_recovery_timeout(u64 start_time)
6199c50d8ae3SPaolo Bonzini {
6200c50d8ae3SPaolo Bonzini 	return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
6201c50d8ae3SPaolo Bonzini 		? start_time + 60 * HZ - get_jiffies_64()
6202c50d8ae3SPaolo Bonzini 		: MAX_SCHEDULE_TIMEOUT;
6203c50d8ae3SPaolo Bonzini }
6204c50d8ae3SPaolo Bonzini 
6205c50d8ae3SPaolo Bonzini static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6206c50d8ae3SPaolo Bonzini {
6207c50d8ae3SPaolo Bonzini 	u64 start_time;
6208c50d8ae3SPaolo Bonzini 	long remaining_time;
6209c50d8ae3SPaolo Bonzini 
6210c50d8ae3SPaolo Bonzini 	while (true) {
6211c50d8ae3SPaolo Bonzini 		start_time = get_jiffies_64();
6212c50d8ae3SPaolo Bonzini 		remaining_time = get_nx_lpage_recovery_timeout(start_time);
6213c50d8ae3SPaolo Bonzini 
6214c50d8ae3SPaolo Bonzini 		set_current_state(TASK_INTERRUPTIBLE);
6215c50d8ae3SPaolo Bonzini 		while (!kthread_should_stop() && remaining_time > 0) {
6216c50d8ae3SPaolo Bonzini 			schedule_timeout(remaining_time);
6217c50d8ae3SPaolo Bonzini 			remaining_time = get_nx_lpage_recovery_timeout(start_time);
6218c50d8ae3SPaolo Bonzini 			set_current_state(TASK_INTERRUPTIBLE);
6219c50d8ae3SPaolo Bonzini 		}
6220c50d8ae3SPaolo Bonzini 
6221c50d8ae3SPaolo Bonzini 		set_current_state(TASK_RUNNING);
6222c50d8ae3SPaolo Bonzini 
6223c50d8ae3SPaolo Bonzini 		if (kthread_should_stop())
6224c50d8ae3SPaolo Bonzini 			return 0;
6225c50d8ae3SPaolo Bonzini 
6226c50d8ae3SPaolo Bonzini 		kvm_recover_nx_lpages(kvm);
6227c50d8ae3SPaolo Bonzini 	}
6228c50d8ae3SPaolo Bonzini }
6229c50d8ae3SPaolo Bonzini 
6230c50d8ae3SPaolo Bonzini int kvm_mmu_post_init_vm(struct kvm *kvm)
6231c50d8ae3SPaolo Bonzini {
6232c50d8ae3SPaolo Bonzini 	int err;
6233c50d8ae3SPaolo Bonzini 
6234c50d8ae3SPaolo Bonzini 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6235c50d8ae3SPaolo Bonzini 					  "kvm-nx-lpage-recovery",
6236c50d8ae3SPaolo Bonzini 					  &kvm->arch.nx_lpage_recovery_thread);
6237c50d8ae3SPaolo Bonzini 	if (!err)
6238c50d8ae3SPaolo Bonzini 		kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6239c50d8ae3SPaolo Bonzini 
6240c50d8ae3SPaolo Bonzini 	return err;
6241c50d8ae3SPaolo Bonzini }
6242c50d8ae3SPaolo Bonzini 
6243c50d8ae3SPaolo Bonzini void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6244c50d8ae3SPaolo Bonzini {
6245c50d8ae3SPaolo Bonzini 	if (kvm->arch.nx_lpage_recovery_thread)
6246c50d8ae3SPaolo Bonzini 		kthread_stop(kvm->arch.nx_lpage_recovery_thread);
6247c50d8ae3SPaolo Bonzini }
6248