xref: /openbmc/linux/arch/x86/kvm/mmu/mmu.c (revision 3d40aed8)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * This module enables machines with Intel VT-x extensions to run virtual
6  * machines without emulation or binary translation.
7  *
8  * MMU support
9  *
10  * Copyright (C) 2006 Qumranet, Inc.
11  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
12  *
13  * Authors:
14  *   Yaniv Kamay  <yaniv@qumranet.com>
15  *   Avi Kivity   <avi@qumranet.com>
16  */
17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18 
19 #include "irq.h"
20 #include "ioapic.h"
21 #include "mmu.h"
22 #include "mmu_internal.h"
23 #include "tdp_mmu.h"
24 #include "x86.h"
25 #include "kvm_cache_regs.h"
26 #include "smm.h"
27 #include "kvm_emulate.h"
28 #include "cpuid.h"
29 #include "spte.h"
30 
31 #include <linux/kvm_host.h>
32 #include <linux/types.h>
33 #include <linux/string.h>
34 #include <linux/mm.h>
35 #include <linux/highmem.h>
36 #include <linux/moduleparam.h>
37 #include <linux/export.h>
38 #include <linux/swap.h>
39 #include <linux/hugetlb.h>
40 #include <linux/compiler.h>
41 #include <linux/srcu.h>
42 #include <linux/slab.h>
43 #include <linux/sched/signal.h>
44 #include <linux/uaccess.h>
45 #include <linux/hash.h>
46 #include <linux/kern_levels.h>
47 #include <linux/kstrtox.h>
48 #include <linux/kthread.h>
49 
50 #include <asm/page.h>
51 #include <asm/memtype.h>
52 #include <asm/cmpxchg.h>
53 #include <asm/io.h>
54 #include <asm/set_memory.h>
55 #include <asm/vmx.h>
56 #include <asm/kvm_page_track.h>
57 #include "trace.h"
58 
59 extern bool itlb_multihit_kvm_mitigation;
60 
61 static bool nx_hugepage_mitigation_hard_disabled;
62 
63 int __read_mostly nx_huge_pages = -1;
64 static uint __read_mostly nx_huge_pages_recovery_period_ms;
65 #ifdef CONFIG_PREEMPT_RT
66 /* Recovery can cause latency spikes, disable it for PREEMPT_RT.  */
67 static uint __read_mostly nx_huge_pages_recovery_ratio = 0;
68 #else
69 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
70 #endif
71 
72 static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp);
73 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
74 static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp);
75 
76 static const struct kernel_param_ops nx_huge_pages_ops = {
77 	.set = set_nx_huge_pages,
78 	.get = get_nx_huge_pages,
79 };
80 
81 static const struct kernel_param_ops nx_huge_pages_recovery_param_ops = {
82 	.set = set_nx_huge_pages_recovery_param,
83 	.get = param_get_uint,
84 };
85 
86 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
87 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
88 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_param_ops,
89 		&nx_huge_pages_recovery_ratio, 0644);
90 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
91 module_param_cb(nx_huge_pages_recovery_period_ms, &nx_huge_pages_recovery_param_ops,
92 		&nx_huge_pages_recovery_period_ms, 0644);
93 __MODULE_PARM_TYPE(nx_huge_pages_recovery_period_ms, "uint");
94 
95 static bool __read_mostly force_flush_and_sync_on_reuse;
96 module_param_named(flush_on_reuse, force_flush_and_sync_on_reuse, bool, 0644);
97 
98 /*
99  * When setting this variable to true it enables Two-Dimensional-Paging
100  * where the hardware walks 2 page tables:
101  * 1. the guest-virtual to guest-physical
102  * 2. while doing 1. it walks guest-physical to host-physical
103  * If the hardware supports that we don't need to do shadow paging.
104  */
105 bool tdp_enabled = false;
106 
107 static bool __ro_after_init tdp_mmu_allowed;
108 
109 #ifdef CONFIG_X86_64
110 bool __read_mostly tdp_mmu_enabled = true;
111 module_param_named(tdp_mmu, tdp_mmu_enabled, bool, 0444);
112 #endif
113 
114 static int max_huge_page_level __read_mostly;
115 static int tdp_root_level __read_mostly;
116 static int max_tdp_level __read_mostly;
117 
118 #ifdef MMU_DEBUG
119 bool dbg = 0;
120 module_param(dbg, bool, 0644);
121 #endif
122 
123 #define PTE_PREFETCH_NUM		8
124 
125 #include <trace/events/kvm.h>
126 
127 /* make pte_list_desc fit well in cache lines */
128 #define PTE_LIST_EXT 14
129 
130 /*
131  * struct pte_list_desc is the core data structure used to implement a custom
132  * list for tracking a set of related SPTEs, e.g. all the SPTEs that map a
133  * given GFN when used in the context of rmaps.  Using a custom list allows KVM
134  * to optimize for the common case where many GFNs will have at most a handful
135  * of SPTEs pointing at them, i.e. allows packing multiple SPTEs into a small
136  * memory footprint, which in turn improves runtime performance by exploiting
137  * cache locality.
138  *
139  * A list is comprised of one or more pte_list_desc objects (descriptors).
140  * Each individual descriptor stores up to PTE_LIST_EXT SPTEs.  If a descriptor
141  * is full and a new SPTEs needs to be added, a new descriptor is allocated and
142  * becomes the head of the list.  This means that by definitions, all tail
143  * descriptors are full.
144  *
145  * Note, the meta data fields are deliberately placed at the start of the
146  * structure to optimize the cacheline layout; accessing the descriptor will
147  * touch only a single cacheline so long as @spte_count<=6 (or if only the
148  * descriptors metadata is accessed).
149  */
150 struct pte_list_desc {
151 	struct pte_list_desc *more;
152 	/* The number of PTEs stored in _this_ descriptor. */
153 	u32 spte_count;
154 	/* The number of PTEs stored in all tails of this descriptor. */
155 	u32 tail_count;
156 	u64 *sptes[PTE_LIST_EXT];
157 };
158 
159 struct kvm_shadow_walk_iterator {
160 	u64 addr;
161 	hpa_t shadow_addr;
162 	u64 *sptep;
163 	int level;
164 	unsigned index;
165 };
166 
167 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
168 	for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
169 					 (_root), (_addr));                \
170 	     shadow_walk_okay(&(_walker));			           \
171 	     shadow_walk_next(&(_walker)))
172 
173 #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
174 	for (shadow_walk_init(&(_walker), _vcpu, _addr);	\
175 	     shadow_walk_okay(&(_walker));			\
176 	     shadow_walk_next(&(_walker)))
177 
178 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)	\
179 	for (shadow_walk_init(&(_walker), _vcpu, _addr);		\
180 	     shadow_walk_okay(&(_walker)) &&				\
181 		({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });	\
182 	     __shadow_walk_next(&(_walker), spte))
183 
184 static struct kmem_cache *pte_list_desc_cache;
185 struct kmem_cache *mmu_page_header_cache;
186 static struct percpu_counter kvm_total_used_mmu_pages;
187 
188 static void mmu_spte_set(u64 *sptep, u64 spte);
189 
190 struct kvm_mmu_role_regs {
191 	const unsigned long cr0;
192 	const unsigned long cr4;
193 	const u64 efer;
194 };
195 
196 #define CREATE_TRACE_POINTS
197 #include "mmutrace.h"
198 
199 /*
200  * Yes, lot's of underscores.  They're a hint that you probably shouldn't be
201  * reading from the role_regs.  Once the root_role is constructed, it becomes
202  * the single source of truth for the MMU's state.
203  */
204 #define BUILD_MMU_ROLE_REGS_ACCESSOR(reg, name, flag)			\
205 static inline bool __maybe_unused					\
206 ____is_##reg##_##name(const struct kvm_mmu_role_regs *regs)		\
207 {									\
208 	return !!(regs->reg & flag);					\
209 }
210 BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, pg, X86_CR0_PG);
211 BUILD_MMU_ROLE_REGS_ACCESSOR(cr0, wp, X86_CR0_WP);
212 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pse, X86_CR4_PSE);
213 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pae, X86_CR4_PAE);
214 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smep, X86_CR4_SMEP);
215 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, smap, X86_CR4_SMAP);
216 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, pke, X86_CR4_PKE);
217 BUILD_MMU_ROLE_REGS_ACCESSOR(cr4, la57, X86_CR4_LA57);
218 BUILD_MMU_ROLE_REGS_ACCESSOR(efer, nx, EFER_NX);
219 BUILD_MMU_ROLE_REGS_ACCESSOR(efer, lma, EFER_LMA);
220 
221 /*
222  * The MMU itself (with a valid role) is the single source of truth for the
223  * MMU.  Do not use the regs used to build the MMU/role, nor the vCPU.  The
224  * regs don't account for dependencies, e.g. clearing CR4 bits if CR0.PG=1,
225  * and the vCPU may be incorrect/irrelevant.
226  */
227 #define BUILD_MMU_ROLE_ACCESSOR(base_or_ext, reg, name)		\
228 static inline bool __maybe_unused is_##reg##_##name(struct kvm_mmu *mmu)	\
229 {								\
230 	return !!(mmu->cpu_role. base_or_ext . reg##_##name);	\
231 }
232 BUILD_MMU_ROLE_ACCESSOR(base, cr0, wp);
233 BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pse);
234 BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smep);
235 BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, smap);
236 BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, pke);
237 BUILD_MMU_ROLE_ACCESSOR(ext,  cr4, la57);
238 BUILD_MMU_ROLE_ACCESSOR(base, efer, nx);
239 BUILD_MMU_ROLE_ACCESSOR(ext,  efer, lma);
240 
241 static inline bool is_cr0_pg(struct kvm_mmu *mmu)
242 {
243         return mmu->cpu_role.base.level > 0;
244 }
245 
246 static inline bool is_cr4_pae(struct kvm_mmu *mmu)
247 {
248         return !mmu->cpu_role.base.has_4_byte_gpte;
249 }
250 
251 static struct kvm_mmu_role_regs vcpu_to_role_regs(struct kvm_vcpu *vcpu)
252 {
253 	struct kvm_mmu_role_regs regs = {
254 		.cr0 = kvm_read_cr0_bits(vcpu, KVM_MMU_CR0_ROLE_BITS),
255 		.cr4 = kvm_read_cr4_bits(vcpu, KVM_MMU_CR4_ROLE_BITS),
256 		.efer = vcpu->arch.efer,
257 	};
258 
259 	return regs;
260 }
261 
262 static unsigned long get_guest_cr3(struct kvm_vcpu *vcpu)
263 {
264 	return kvm_read_cr3(vcpu);
265 }
266 
267 static inline unsigned long kvm_mmu_get_guest_pgd(struct kvm_vcpu *vcpu,
268 						  struct kvm_mmu *mmu)
269 {
270 	if (IS_ENABLED(CONFIG_RETPOLINE) && mmu->get_guest_pgd == get_guest_cr3)
271 		return kvm_read_cr3(vcpu);
272 
273 	return mmu->get_guest_pgd(vcpu);
274 }
275 
276 static inline bool kvm_available_flush_remote_tlbs_range(void)
277 {
278 	return kvm_x86_ops.flush_remote_tlbs_range;
279 }
280 
281 void kvm_flush_remote_tlbs_range(struct kvm *kvm, gfn_t start_gfn,
282 				 gfn_t nr_pages)
283 {
284 	int ret = -EOPNOTSUPP;
285 
286 	if (kvm_x86_ops.flush_remote_tlbs_range)
287 		ret = static_call(kvm_x86_flush_remote_tlbs_range)(kvm, start_gfn,
288 								   nr_pages);
289 	if (ret)
290 		kvm_flush_remote_tlbs(kvm);
291 }
292 
293 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index);
294 
295 /* Flush the range of guest memory mapped by the given SPTE. */
296 static void kvm_flush_remote_tlbs_sptep(struct kvm *kvm, u64 *sptep)
297 {
298 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
299 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, spte_index(sptep));
300 
301 	kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
302 }
303 
304 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
305 			   unsigned int access)
306 {
307 	u64 spte = make_mmio_spte(vcpu, gfn, access);
308 
309 	trace_mark_mmio_spte(sptep, gfn, spte);
310 	mmu_spte_set(sptep, spte);
311 }
312 
313 static gfn_t get_mmio_spte_gfn(u64 spte)
314 {
315 	u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
316 
317 	gpa |= (spte >> SHADOW_NONPRESENT_OR_RSVD_MASK_LEN)
318 	       & shadow_nonpresent_or_rsvd_mask;
319 
320 	return gpa >> PAGE_SHIFT;
321 }
322 
323 static unsigned get_mmio_spte_access(u64 spte)
324 {
325 	return spte & shadow_mmio_access_mask;
326 }
327 
328 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
329 {
330 	u64 kvm_gen, spte_gen, gen;
331 
332 	gen = kvm_vcpu_memslots(vcpu)->generation;
333 	if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
334 		return false;
335 
336 	kvm_gen = gen & MMIO_SPTE_GEN_MASK;
337 	spte_gen = get_mmio_spte_generation(spte);
338 
339 	trace_check_mmio_spte(spte, kvm_gen, spte_gen);
340 	return likely(kvm_gen == spte_gen);
341 }
342 
343 static int is_cpuid_PSE36(void)
344 {
345 	return 1;
346 }
347 
348 #ifdef CONFIG_X86_64
349 static void __set_spte(u64 *sptep, u64 spte)
350 {
351 	WRITE_ONCE(*sptep, spte);
352 }
353 
354 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
355 {
356 	WRITE_ONCE(*sptep, spte);
357 }
358 
359 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
360 {
361 	return xchg(sptep, spte);
362 }
363 
364 static u64 __get_spte_lockless(u64 *sptep)
365 {
366 	return READ_ONCE(*sptep);
367 }
368 #else
369 union split_spte {
370 	struct {
371 		u32 spte_low;
372 		u32 spte_high;
373 	};
374 	u64 spte;
375 };
376 
377 static void count_spte_clear(u64 *sptep, u64 spte)
378 {
379 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
380 
381 	if (is_shadow_present_pte(spte))
382 		return;
383 
384 	/* Ensure the spte is completely set before we increase the count */
385 	smp_wmb();
386 	sp->clear_spte_count++;
387 }
388 
389 static void __set_spte(u64 *sptep, u64 spte)
390 {
391 	union split_spte *ssptep, sspte;
392 
393 	ssptep = (union split_spte *)sptep;
394 	sspte = (union split_spte)spte;
395 
396 	ssptep->spte_high = sspte.spte_high;
397 
398 	/*
399 	 * If we map the spte from nonpresent to present, We should store
400 	 * the high bits firstly, then set present bit, so cpu can not
401 	 * fetch this spte while we are setting the spte.
402 	 */
403 	smp_wmb();
404 
405 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
406 }
407 
408 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
409 {
410 	union split_spte *ssptep, sspte;
411 
412 	ssptep = (union split_spte *)sptep;
413 	sspte = (union split_spte)spte;
414 
415 	WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
416 
417 	/*
418 	 * If we map the spte from present to nonpresent, we should clear
419 	 * present bit firstly to avoid vcpu fetch the old high bits.
420 	 */
421 	smp_wmb();
422 
423 	ssptep->spte_high = sspte.spte_high;
424 	count_spte_clear(sptep, spte);
425 }
426 
427 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
428 {
429 	union split_spte *ssptep, sspte, orig;
430 
431 	ssptep = (union split_spte *)sptep;
432 	sspte = (union split_spte)spte;
433 
434 	/* xchg acts as a barrier before the setting of the high bits */
435 	orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
436 	orig.spte_high = ssptep->spte_high;
437 	ssptep->spte_high = sspte.spte_high;
438 	count_spte_clear(sptep, spte);
439 
440 	return orig.spte;
441 }
442 
443 /*
444  * The idea using the light way get the spte on x86_32 guest is from
445  * gup_get_pte (mm/gup.c).
446  *
447  * An spte tlb flush may be pending, because kvm_set_pte_rmap
448  * coalesces them and we are running out of the MMU lock.  Therefore
449  * we need to protect against in-progress updates of the spte.
450  *
451  * Reading the spte while an update is in progress may get the old value
452  * for the high part of the spte.  The race is fine for a present->non-present
453  * change (because the high part of the spte is ignored for non-present spte),
454  * but for a present->present change we must reread the spte.
455  *
456  * All such changes are done in two steps (present->non-present and
457  * non-present->present), hence it is enough to count the number of
458  * present->non-present updates: if it changed while reading the spte,
459  * we might have hit the race.  This is done using clear_spte_count.
460  */
461 static u64 __get_spte_lockless(u64 *sptep)
462 {
463 	struct kvm_mmu_page *sp =  sptep_to_sp(sptep);
464 	union split_spte spte, *orig = (union split_spte *)sptep;
465 	int count;
466 
467 retry:
468 	count = sp->clear_spte_count;
469 	smp_rmb();
470 
471 	spte.spte_low = orig->spte_low;
472 	smp_rmb();
473 
474 	spte.spte_high = orig->spte_high;
475 	smp_rmb();
476 
477 	if (unlikely(spte.spte_low != orig->spte_low ||
478 	      count != sp->clear_spte_count))
479 		goto retry;
480 
481 	return spte.spte;
482 }
483 #endif
484 
485 /* Rules for using mmu_spte_set:
486  * Set the sptep from nonpresent to present.
487  * Note: the sptep being assigned *must* be either not present
488  * or in a state where the hardware will not attempt to update
489  * the spte.
490  */
491 static void mmu_spte_set(u64 *sptep, u64 new_spte)
492 {
493 	WARN_ON(is_shadow_present_pte(*sptep));
494 	__set_spte(sptep, new_spte);
495 }
496 
497 /*
498  * Update the SPTE (excluding the PFN), but do not track changes in its
499  * accessed/dirty status.
500  */
501 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
502 {
503 	u64 old_spte = *sptep;
504 
505 	WARN_ON(!is_shadow_present_pte(new_spte));
506 	check_spte_writable_invariants(new_spte);
507 
508 	if (!is_shadow_present_pte(old_spte)) {
509 		mmu_spte_set(sptep, new_spte);
510 		return old_spte;
511 	}
512 
513 	if (!spte_has_volatile_bits(old_spte))
514 		__update_clear_spte_fast(sptep, new_spte);
515 	else
516 		old_spte = __update_clear_spte_slow(sptep, new_spte);
517 
518 	WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
519 
520 	return old_spte;
521 }
522 
523 /* Rules for using mmu_spte_update:
524  * Update the state bits, it means the mapped pfn is not changed.
525  *
526  * Whenever an MMU-writable SPTE is overwritten with a read-only SPTE, remote
527  * TLBs must be flushed. Otherwise rmap_write_protect will find a read-only
528  * spte, even though the writable spte might be cached on a CPU's TLB.
529  *
530  * Returns true if the TLB needs to be flushed
531  */
532 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
533 {
534 	bool flush = false;
535 	u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
536 
537 	if (!is_shadow_present_pte(old_spte))
538 		return false;
539 
540 	/*
541 	 * For the spte updated out of mmu-lock is safe, since
542 	 * we always atomically update it, see the comments in
543 	 * spte_has_volatile_bits().
544 	 */
545 	if (is_mmu_writable_spte(old_spte) &&
546 	      !is_writable_pte(new_spte))
547 		flush = true;
548 
549 	/*
550 	 * Flush TLB when accessed/dirty states are changed in the page tables,
551 	 * to guarantee consistency between TLB and page tables.
552 	 */
553 
554 	if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
555 		flush = true;
556 		kvm_set_pfn_accessed(spte_to_pfn(old_spte));
557 	}
558 
559 	if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
560 		flush = true;
561 		kvm_set_pfn_dirty(spte_to_pfn(old_spte));
562 	}
563 
564 	return flush;
565 }
566 
567 /*
568  * Rules for using mmu_spte_clear_track_bits:
569  * It sets the sptep from present to nonpresent, and track the
570  * state bits, it is used to clear the last level sptep.
571  * Returns the old PTE.
572  */
573 static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
574 {
575 	kvm_pfn_t pfn;
576 	u64 old_spte = *sptep;
577 	int level = sptep_to_sp(sptep)->role.level;
578 	struct page *page;
579 
580 	if (!is_shadow_present_pte(old_spte) ||
581 	    !spte_has_volatile_bits(old_spte))
582 		__update_clear_spte_fast(sptep, 0ull);
583 	else
584 		old_spte = __update_clear_spte_slow(sptep, 0ull);
585 
586 	if (!is_shadow_present_pte(old_spte))
587 		return old_spte;
588 
589 	kvm_update_page_stats(kvm, level, -1);
590 
591 	pfn = spte_to_pfn(old_spte);
592 
593 	/*
594 	 * KVM doesn't hold a reference to any pages mapped into the guest, and
595 	 * instead uses the mmu_notifier to ensure that KVM unmaps any pages
596 	 * before they are reclaimed.  Sanity check that, if the pfn is backed
597 	 * by a refcounted page, the refcount is elevated.
598 	 */
599 	page = kvm_pfn_to_refcounted_page(pfn);
600 	WARN_ON(page && !page_count(page));
601 
602 	if (is_accessed_spte(old_spte))
603 		kvm_set_pfn_accessed(pfn);
604 
605 	if (is_dirty_spte(old_spte))
606 		kvm_set_pfn_dirty(pfn);
607 
608 	return old_spte;
609 }
610 
611 /*
612  * Rules for using mmu_spte_clear_no_track:
613  * Directly clear spte without caring the state bits of sptep,
614  * it is used to set the upper level spte.
615  */
616 static void mmu_spte_clear_no_track(u64 *sptep)
617 {
618 	__update_clear_spte_fast(sptep, 0ull);
619 }
620 
621 static u64 mmu_spte_get_lockless(u64 *sptep)
622 {
623 	return __get_spte_lockless(sptep);
624 }
625 
626 /* Returns the Accessed status of the PTE and resets it at the same time. */
627 static bool mmu_spte_age(u64 *sptep)
628 {
629 	u64 spte = mmu_spte_get_lockless(sptep);
630 
631 	if (!is_accessed_spte(spte))
632 		return false;
633 
634 	if (spte_ad_enabled(spte)) {
635 		clear_bit((ffs(shadow_accessed_mask) - 1),
636 			  (unsigned long *)sptep);
637 	} else {
638 		/*
639 		 * Capture the dirty status of the page, so that it doesn't get
640 		 * lost when the SPTE is marked for access tracking.
641 		 */
642 		if (is_writable_pte(spte))
643 			kvm_set_pfn_dirty(spte_to_pfn(spte));
644 
645 		spte = mark_spte_for_access_track(spte);
646 		mmu_spte_update_no_track(sptep, spte);
647 	}
648 
649 	return true;
650 }
651 
652 static inline bool is_tdp_mmu_active(struct kvm_vcpu *vcpu)
653 {
654 	return tdp_mmu_enabled && vcpu->arch.mmu->root_role.direct;
655 }
656 
657 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
658 {
659 	if (is_tdp_mmu_active(vcpu)) {
660 		kvm_tdp_mmu_walk_lockless_begin();
661 	} else {
662 		/*
663 		 * Prevent page table teardown by making any free-er wait during
664 		 * kvm_flush_remote_tlbs() IPI to all active vcpus.
665 		 */
666 		local_irq_disable();
667 
668 		/*
669 		 * Make sure a following spte read is not reordered ahead of the write
670 		 * to vcpu->mode.
671 		 */
672 		smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
673 	}
674 }
675 
676 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
677 {
678 	if (is_tdp_mmu_active(vcpu)) {
679 		kvm_tdp_mmu_walk_lockless_end();
680 	} else {
681 		/*
682 		 * Make sure the write to vcpu->mode is not reordered in front of
683 		 * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
684 		 * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
685 		 */
686 		smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
687 		local_irq_enable();
688 	}
689 }
690 
691 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
692 {
693 	int r;
694 
695 	/* 1 rmap, 1 parent PTE per level, and the prefetched rmaps. */
696 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
697 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
698 	if (r)
699 		return r;
700 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
701 				       PT64_ROOT_MAX_LEVEL);
702 	if (r)
703 		return r;
704 	if (maybe_indirect) {
705 		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadowed_info_cache,
706 					       PT64_ROOT_MAX_LEVEL);
707 		if (r)
708 			return r;
709 	}
710 	return kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
711 					  PT64_ROOT_MAX_LEVEL);
712 }
713 
714 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
715 {
716 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
717 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
718 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadowed_info_cache);
719 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
720 }
721 
722 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
723 {
724 	kmem_cache_free(pte_list_desc_cache, pte_list_desc);
725 }
726 
727 static bool sp_has_gptes(struct kvm_mmu_page *sp);
728 
729 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
730 {
731 	if (sp->role.passthrough)
732 		return sp->gfn;
733 
734 	if (!sp->role.direct)
735 		return sp->shadowed_translation[index] >> PAGE_SHIFT;
736 
737 	return sp->gfn + (index << ((sp->role.level - 1) * SPTE_LEVEL_BITS));
738 }
739 
740 /*
741  * For leaf SPTEs, fetch the *guest* access permissions being shadowed. Note
742  * that the SPTE itself may have a more constrained access permissions that
743  * what the guest enforces. For example, a guest may create an executable
744  * huge PTE but KVM may disallow execution to mitigate iTLB multihit.
745  */
746 static u32 kvm_mmu_page_get_access(struct kvm_mmu_page *sp, int index)
747 {
748 	if (sp_has_gptes(sp))
749 		return sp->shadowed_translation[index] & ACC_ALL;
750 
751 	/*
752 	 * For direct MMUs (e.g. TDP or non-paging guests) or passthrough SPs,
753 	 * KVM is not shadowing any guest page tables, so the "guest access
754 	 * permissions" are just ACC_ALL.
755 	 *
756 	 * For direct SPs in indirect MMUs (shadow paging), i.e. when KVM
757 	 * is shadowing a guest huge page with small pages, the guest access
758 	 * permissions being shadowed are the access permissions of the huge
759 	 * page.
760 	 *
761 	 * In both cases, sp->role.access contains the correct access bits.
762 	 */
763 	return sp->role.access;
764 }
765 
766 static void kvm_mmu_page_set_translation(struct kvm_mmu_page *sp, int index,
767 					 gfn_t gfn, unsigned int access)
768 {
769 	if (sp_has_gptes(sp)) {
770 		sp->shadowed_translation[index] = (gfn << PAGE_SHIFT) | access;
771 		return;
772 	}
773 
774 	WARN_ONCE(access != kvm_mmu_page_get_access(sp, index),
775 	          "access mismatch under %s page %llx (expected %u, got %u)\n",
776 	          sp->role.passthrough ? "passthrough" : "direct",
777 	          sp->gfn, kvm_mmu_page_get_access(sp, index), access);
778 
779 	WARN_ONCE(gfn != kvm_mmu_page_get_gfn(sp, index),
780 	          "gfn mismatch under %s page %llx (expected %llx, got %llx)\n",
781 	          sp->role.passthrough ? "passthrough" : "direct",
782 	          sp->gfn, kvm_mmu_page_get_gfn(sp, index), gfn);
783 }
784 
785 static void kvm_mmu_page_set_access(struct kvm_mmu_page *sp, int index,
786 				    unsigned int access)
787 {
788 	gfn_t gfn = kvm_mmu_page_get_gfn(sp, index);
789 
790 	kvm_mmu_page_set_translation(sp, index, gfn, access);
791 }
792 
793 /*
794  * Return the pointer to the large page information for a given gfn,
795  * handling slots that are not large page aligned.
796  */
797 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
798 		const struct kvm_memory_slot *slot, int level)
799 {
800 	unsigned long idx;
801 
802 	idx = gfn_to_index(gfn, slot->base_gfn, level);
803 	return &slot->arch.lpage_info[level - 2][idx];
804 }
805 
806 static void update_gfn_disallow_lpage_count(const struct kvm_memory_slot *slot,
807 					    gfn_t gfn, int count)
808 {
809 	struct kvm_lpage_info *linfo;
810 	int i;
811 
812 	for (i = PG_LEVEL_2M; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
813 		linfo = lpage_info_slot(gfn, slot, i);
814 		linfo->disallow_lpage += count;
815 		WARN_ON(linfo->disallow_lpage < 0);
816 	}
817 }
818 
819 void kvm_mmu_gfn_disallow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
820 {
821 	update_gfn_disallow_lpage_count(slot, gfn, 1);
822 }
823 
824 void kvm_mmu_gfn_allow_lpage(const struct kvm_memory_slot *slot, gfn_t gfn)
825 {
826 	update_gfn_disallow_lpage_count(slot, gfn, -1);
827 }
828 
829 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
830 {
831 	struct kvm_memslots *slots;
832 	struct kvm_memory_slot *slot;
833 	gfn_t gfn;
834 
835 	kvm->arch.indirect_shadow_pages++;
836 	gfn = sp->gfn;
837 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
838 	slot = __gfn_to_memslot(slots, gfn);
839 
840 	/* the non-leaf shadow pages are keeping readonly. */
841 	if (sp->role.level > PG_LEVEL_4K)
842 		return kvm_slot_page_track_add_page(kvm, slot, gfn,
843 						    KVM_PAGE_TRACK_WRITE);
844 
845 	kvm_mmu_gfn_disallow_lpage(slot, gfn);
846 
847 	if (kvm_mmu_slot_gfn_write_protect(kvm, slot, gfn, PG_LEVEL_4K))
848 		kvm_flush_remote_tlbs_gfn(kvm, gfn, PG_LEVEL_4K);
849 }
850 
851 void track_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
852 {
853 	/*
854 	 * If it's possible to replace the shadow page with an NX huge page,
855 	 * i.e. if the shadow page is the only thing currently preventing KVM
856 	 * from using a huge page, add the shadow page to the list of "to be
857 	 * zapped for NX recovery" pages.  Note, the shadow page can already be
858 	 * on the list if KVM is reusing an existing shadow page, i.e. if KVM
859 	 * links a shadow page at multiple points.
860 	 */
861 	if (!list_empty(&sp->possible_nx_huge_page_link))
862 		return;
863 
864 	++kvm->stat.nx_lpage_splits;
865 	list_add_tail(&sp->possible_nx_huge_page_link,
866 		      &kvm->arch.possible_nx_huge_pages);
867 }
868 
869 static void account_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp,
870 				 bool nx_huge_page_possible)
871 {
872 	sp->nx_huge_page_disallowed = true;
873 
874 	if (nx_huge_page_possible)
875 		track_possible_nx_huge_page(kvm, sp);
876 }
877 
878 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
879 {
880 	struct kvm_memslots *slots;
881 	struct kvm_memory_slot *slot;
882 	gfn_t gfn;
883 
884 	kvm->arch.indirect_shadow_pages--;
885 	gfn = sp->gfn;
886 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
887 	slot = __gfn_to_memslot(slots, gfn);
888 	if (sp->role.level > PG_LEVEL_4K)
889 		return kvm_slot_page_track_remove_page(kvm, slot, gfn,
890 						       KVM_PAGE_TRACK_WRITE);
891 
892 	kvm_mmu_gfn_allow_lpage(slot, gfn);
893 }
894 
895 void untrack_possible_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
896 {
897 	if (list_empty(&sp->possible_nx_huge_page_link))
898 		return;
899 
900 	--kvm->stat.nx_lpage_splits;
901 	list_del_init(&sp->possible_nx_huge_page_link);
902 }
903 
904 static void unaccount_nx_huge_page(struct kvm *kvm, struct kvm_mmu_page *sp)
905 {
906 	sp->nx_huge_page_disallowed = false;
907 
908 	untrack_possible_nx_huge_page(kvm, sp);
909 }
910 
911 static struct kvm_memory_slot *gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu,
912 							   gfn_t gfn,
913 							   bool no_dirty_log)
914 {
915 	struct kvm_memory_slot *slot;
916 
917 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
918 	if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
919 		return NULL;
920 	if (no_dirty_log && kvm_slot_dirty_track_enabled(slot))
921 		return NULL;
922 
923 	return slot;
924 }
925 
926 /*
927  * About rmap_head encoding:
928  *
929  * If the bit zero of rmap_head->val is clear, then it points to the only spte
930  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
931  * pte_list_desc containing more mappings.
932  */
933 
934 /*
935  * Returns the number of pointers in the rmap chain, not counting the new one.
936  */
937 static int pte_list_add(struct kvm_mmu_memory_cache *cache, u64 *spte,
938 			struct kvm_rmap_head *rmap_head)
939 {
940 	struct pte_list_desc *desc;
941 	int count = 0;
942 
943 	if (!rmap_head->val) {
944 		rmap_printk("%p %llx 0->1\n", spte, *spte);
945 		rmap_head->val = (unsigned long)spte;
946 	} else if (!(rmap_head->val & 1)) {
947 		rmap_printk("%p %llx 1->many\n", spte, *spte);
948 		desc = kvm_mmu_memory_cache_alloc(cache);
949 		desc->sptes[0] = (u64 *)rmap_head->val;
950 		desc->sptes[1] = spte;
951 		desc->spte_count = 2;
952 		desc->tail_count = 0;
953 		rmap_head->val = (unsigned long)desc | 1;
954 		++count;
955 	} else {
956 		rmap_printk("%p %llx many->many\n", spte, *spte);
957 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
958 		count = desc->tail_count + desc->spte_count;
959 
960 		/*
961 		 * If the previous head is full, allocate a new head descriptor
962 		 * as tail descriptors are always kept full.
963 		 */
964 		if (desc->spte_count == PTE_LIST_EXT) {
965 			desc = kvm_mmu_memory_cache_alloc(cache);
966 			desc->more = (struct pte_list_desc *)(rmap_head->val & ~1ul);
967 			desc->spte_count = 0;
968 			desc->tail_count = count;
969 			rmap_head->val = (unsigned long)desc | 1;
970 		}
971 		desc->sptes[desc->spte_count++] = spte;
972 	}
973 	return count;
974 }
975 
976 static void pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
977 				       struct pte_list_desc *desc, int i)
978 {
979 	struct pte_list_desc *head_desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
980 	int j = head_desc->spte_count - 1;
981 
982 	/*
983 	 * The head descriptor should never be empty.  A new head is added only
984 	 * when adding an entry and the previous head is full, and heads are
985 	 * removed (this flow) when they become empty.
986 	 */
987 	BUG_ON(j < 0);
988 
989 	/*
990 	 * Replace the to-be-freed SPTE with the last valid entry from the head
991 	 * descriptor to ensure that tail descriptors are full at all times.
992 	 * Note, this also means that tail_count is stable for each descriptor.
993 	 */
994 	desc->sptes[i] = head_desc->sptes[j];
995 	head_desc->sptes[j] = NULL;
996 	head_desc->spte_count--;
997 	if (head_desc->spte_count)
998 		return;
999 
1000 	/*
1001 	 * The head descriptor is empty.  If there are no tail descriptors,
1002 	 * nullify the rmap head to mark the list as emtpy, else point the rmap
1003 	 * head at the next descriptor, i.e. the new head.
1004 	 */
1005 	if (!head_desc->more)
1006 		rmap_head->val = 0;
1007 	else
1008 		rmap_head->val = (unsigned long)head_desc->more | 1;
1009 	mmu_free_pte_list_desc(head_desc);
1010 }
1011 
1012 static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1013 {
1014 	struct pte_list_desc *desc;
1015 	int i;
1016 
1017 	if (!rmap_head->val) {
1018 		pr_err("%s: %p 0->BUG\n", __func__, spte);
1019 		BUG();
1020 	} else if (!(rmap_head->val & 1)) {
1021 		rmap_printk("%p 1->0\n", spte);
1022 		if ((u64 *)rmap_head->val != spte) {
1023 			pr_err("%s:  %p 1->BUG\n", __func__, spte);
1024 			BUG();
1025 		}
1026 		rmap_head->val = 0;
1027 	} else {
1028 		rmap_printk("%p many->many\n", spte);
1029 		desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1030 		while (desc) {
1031 			for (i = 0; i < desc->spte_count; ++i) {
1032 				if (desc->sptes[i] == spte) {
1033 					pte_list_desc_remove_entry(rmap_head, desc, i);
1034 					return;
1035 				}
1036 			}
1037 			desc = desc->more;
1038 		}
1039 		pr_err("%s: %p many->many\n", __func__, spte);
1040 		BUG();
1041 	}
1042 }
1043 
1044 static void kvm_zap_one_rmap_spte(struct kvm *kvm,
1045 				  struct kvm_rmap_head *rmap_head, u64 *sptep)
1046 {
1047 	mmu_spte_clear_track_bits(kvm, sptep);
1048 	pte_list_remove(sptep, rmap_head);
1049 }
1050 
1051 /* Return true if at least one SPTE was zapped, false otherwise */
1052 static bool kvm_zap_all_rmap_sptes(struct kvm *kvm,
1053 				   struct kvm_rmap_head *rmap_head)
1054 {
1055 	struct pte_list_desc *desc, *next;
1056 	int i;
1057 
1058 	if (!rmap_head->val)
1059 		return false;
1060 
1061 	if (!(rmap_head->val & 1)) {
1062 		mmu_spte_clear_track_bits(kvm, (u64 *)rmap_head->val);
1063 		goto out;
1064 	}
1065 
1066 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1067 
1068 	for (; desc; desc = next) {
1069 		for (i = 0; i < desc->spte_count; i++)
1070 			mmu_spte_clear_track_bits(kvm, desc->sptes[i]);
1071 		next = desc->more;
1072 		mmu_free_pte_list_desc(desc);
1073 	}
1074 out:
1075 	/* rmap_head is meaningless now, remember to reset it */
1076 	rmap_head->val = 0;
1077 	return true;
1078 }
1079 
1080 unsigned int pte_list_count(struct kvm_rmap_head *rmap_head)
1081 {
1082 	struct pte_list_desc *desc;
1083 
1084 	if (!rmap_head->val)
1085 		return 0;
1086 	else if (!(rmap_head->val & 1))
1087 		return 1;
1088 
1089 	desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1090 	return desc->tail_count + desc->spte_count;
1091 }
1092 
1093 static struct kvm_rmap_head *gfn_to_rmap(gfn_t gfn, int level,
1094 					 const struct kvm_memory_slot *slot)
1095 {
1096 	unsigned long idx;
1097 
1098 	idx = gfn_to_index(gfn, slot->base_gfn, level);
1099 	return &slot->arch.rmap[level - PG_LEVEL_4K][idx];
1100 }
1101 
1102 static void rmap_remove(struct kvm *kvm, u64 *spte)
1103 {
1104 	struct kvm_memslots *slots;
1105 	struct kvm_memory_slot *slot;
1106 	struct kvm_mmu_page *sp;
1107 	gfn_t gfn;
1108 	struct kvm_rmap_head *rmap_head;
1109 
1110 	sp = sptep_to_sp(spte);
1111 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(spte));
1112 
1113 	/*
1114 	 * Unlike rmap_add, rmap_remove does not run in the context of a vCPU
1115 	 * so we have to determine which memslots to use based on context
1116 	 * information in sp->role.
1117 	 */
1118 	slots = kvm_memslots_for_spte_role(kvm, sp->role);
1119 
1120 	slot = __gfn_to_memslot(slots, gfn);
1121 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1122 
1123 	pte_list_remove(spte, rmap_head);
1124 }
1125 
1126 /*
1127  * Used by the following functions to iterate through the sptes linked by a
1128  * rmap.  All fields are private and not assumed to be used outside.
1129  */
1130 struct rmap_iterator {
1131 	/* private fields */
1132 	struct pte_list_desc *desc;	/* holds the sptep if not NULL */
1133 	int pos;			/* index of the sptep */
1134 };
1135 
1136 /*
1137  * Iteration must be started by this function.  This should also be used after
1138  * removing/dropping sptes from the rmap link because in such cases the
1139  * information in the iterator may not be valid.
1140  *
1141  * Returns sptep if found, NULL otherwise.
1142  */
1143 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1144 			   struct rmap_iterator *iter)
1145 {
1146 	u64 *sptep;
1147 
1148 	if (!rmap_head->val)
1149 		return NULL;
1150 
1151 	if (!(rmap_head->val & 1)) {
1152 		iter->desc = NULL;
1153 		sptep = (u64 *)rmap_head->val;
1154 		goto out;
1155 	}
1156 
1157 	iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1158 	iter->pos = 0;
1159 	sptep = iter->desc->sptes[iter->pos];
1160 out:
1161 	BUG_ON(!is_shadow_present_pte(*sptep));
1162 	return sptep;
1163 }
1164 
1165 /*
1166  * Must be used with a valid iterator: e.g. after rmap_get_first().
1167  *
1168  * Returns sptep if found, NULL otherwise.
1169  */
1170 static u64 *rmap_get_next(struct rmap_iterator *iter)
1171 {
1172 	u64 *sptep;
1173 
1174 	if (iter->desc) {
1175 		if (iter->pos < PTE_LIST_EXT - 1) {
1176 			++iter->pos;
1177 			sptep = iter->desc->sptes[iter->pos];
1178 			if (sptep)
1179 				goto out;
1180 		}
1181 
1182 		iter->desc = iter->desc->more;
1183 
1184 		if (iter->desc) {
1185 			iter->pos = 0;
1186 			/* desc->sptes[0] cannot be NULL */
1187 			sptep = iter->desc->sptes[iter->pos];
1188 			goto out;
1189 		}
1190 	}
1191 
1192 	return NULL;
1193 out:
1194 	BUG_ON(!is_shadow_present_pte(*sptep));
1195 	return sptep;
1196 }
1197 
1198 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)			\
1199 	for (_spte_ = rmap_get_first(_rmap_head_, _iter_);		\
1200 	     _spte_; _spte_ = rmap_get_next(_iter_))
1201 
1202 static void drop_spte(struct kvm *kvm, u64 *sptep)
1203 {
1204 	u64 old_spte = mmu_spte_clear_track_bits(kvm, sptep);
1205 
1206 	if (is_shadow_present_pte(old_spte))
1207 		rmap_remove(kvm, sptep);
1208 }
1209 
1210 static void drop_large_spte(struct kvm *kvm, u64 *sptep, bool flush)
1211 {
1212 	struct kvm_mmu_page *sp;
1213 
1214 	sp = sptep_to_sp(sptep);
1215 	WARN_ON(sp->role.level == PG_LEVEL_4K);
1216 
1217 	drop_spte(kvm, sptep);
1218 
1219 	if (flush)
1220 		kvm_flush_remote_tlbs_sptep(kvm, sptep);
1221 }
1222 
1223 /*
1224  * Write-protect on the specified @sptep, @pt_protect indicates whether
1225  * spte write-protection is caused by protecting shadow page table.
1226  *
1227  * Note: write protection is difference between dirty logging and spte
1228  * protection:
1229  * - for dirty logging, the spte can be set to writable at anytime if
1230  *   its dirty bitmap is properly set.
1231  * - for spte protection, the spte can be writable only after unsync-ing
1232  *   shadow page.
1233  *
1234  * Return true if tlb need be flushed.
1235  */
1236 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1237 {
1238 	u64 spte = *sptep;
1239 
1240 	if (!is_writable_pte(spte) &&
1241 	    !(pt_protect && is_mmu_writable_spte(spte)))
1242 		return false;
1243 
1244 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1245 
1246 	if (pt_protect)
1247 		spte &= ~shadow_mmu_writable_mask;
1248 	spte = spte & ~PT_WRITABLE_MASK;
1249 
1250 	return mmu_spte_update(sptep, spte);
1251 }
1252 
1253 static bool rmap_write_protect(struct kvm_rmap_head *rmap_head,
1254 			       bool pt_protect)
1255 {
1256 	u64 *sptep;
1257 	struct rmap_iterator iter;
1258 	bool flush = false;
1259 
1260 	for_each_rmap_spte(rmap_head, &iter, sptep)
1261 		flush |= spte_write_protect(sptep, pt_protect);
1262 
1263 	return flush;
1264 }
1265 
1266 static bool spte_clear_dirty(u64 *sptep)
1267 {
1268 	u64 spte = *sptep;
1269 
1270 	rmap_printk("spte %p %llx\n", sptep, *sptep);
1271 
1272 	MMU_WARN_ON(!spte_ad_enabled(spte));
1273 	spte &= ~shadow_dirty_mask;
1274 	return mmu_spte_update(sptep, spte);
1275 }
1276 
1277 static bool spte_wrprot_for_clear_dirty(u64 *sptep)
1278 {
1279 	bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1280 					       (unsigned long *)sptep);
1281 	if (was_writable && !spte_ad_enabled(*sptep))
1282 		kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1283 
1284 	return was_writable;
1285 }
1286 
1287 /*
1288  * Gets the GFN ready for another round of dirty logging by clearing the
1289  *	- D bit on ad-enabled SPTEs, and
1290  *	- W bit on ad-disabled SPTEs.
1291  * Returns true iff any D or W bits were cleared.
1292  */
1293 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1294 			       const struct kvm_memory_slot *slot)
1295 {
1296 	u64 *sptep;
1297 	struct rmap_iterator iter;
1298 	bool flush = false;
1299 
1300 	for_each_rmap_spte(rmap_head, &iter, sptep)
1301 		if (spte_ad_need_write_protect(*sptep))
1302 			flush |= spte_wrprot_for_clear_dirty(sptep);
1303 		else
1304 			flush |= spte_clear_dirty(sptep);
1305 
1306 	return flush;
1307 }
1308 
1309 /**
1310  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1311  * @kvm: kvm instance
1312  * @slot: slot to protect
1313  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1314  * @mask: indicates which pages we should protect
1315  *
1316  * Used when we do not need to care about huge page mappings.
1317  */
1318 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1319 				     struct kvm_memory_slot *slot,
1320 				     gfn_t gfn_offset, unsigned long mask)
1321 {
1322 	struct kvm_rmap_head *rmap_head;
1323 
1324 	if (tdp_mmu_enabled)
1325 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1326 				slot->base_gfn + gfn_offset, mask, true);
1327 
1328 	if (!kvm_memslots_have_rmaps(kvm))
1329 		return;
1330 
1331 	while (mask) {
1332 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1333 					PG_LEVEL_4K, slot);
1334 		rmap_write_protect(rmap_head, false);
1335 
1336 		/* clear the first set bit */
1337 		mask &= mask - 1;
1338 	}
1339 }
1340 
1341 /**
1342  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1343  * protect the page if the D-bit isn't supported.
1344  * @kvm: kvm instance
1345  * @slot: slot to clear D-bit
1346  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1347  * @mask: indicates which pages we should clear D-bit
1348  *
1349  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1350  */
1351 static void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1352 					 struct kvm_memory_slot *slot,
1353 					 gfn_t gfn_offset, unsigned long mask)
1354 {
1355 	struct kvm_rmap_head *rmap_head;
1356 
1357 	if (tdp_mmu_enabled)
1358 		kvm_tdp_mmu_clear_dirty_pt_masked(kvm, slot,
1359 				slot->base_gfn + gfn_offset, mask, false);
1360 
1361 	if (!kvm_memslots_have_rmaps(kvm))
1362 		return;
1363 
1364 	while (mask) {
1365 		rmap_head = gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1366 					PG_LEVEL_4K, slot);
1367 		__rmap_clear_dirty(kvm, rmap_head, slot);
1368 
1369 		/* clear the first set bit */
1370 		mask &= mask - 1;
1371 	}
1372 }
1373 
1374 /**
1375  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1376  * PT level pages.
1377  *
1378  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1379  * enable dirty logging for them.
1380  *
1381  * We need to care about huge page mappings: e.g. during dirty logging we may
1382  * have such mappings.
1383  */
1384 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1385 				struct kvm_memory_slot *slot,
1386 				gfn_t gfn_offset, unsigned long mask)
1387 {
1388 	/*
1389 	 * Huge pages are NOT write protected when we start dirty logging in
1390 	 * initially-all-set mode; must write protect them here so that they
1391 	 * are split to 4K on the first write.
1392 	 *
1393 	 * The gfn_offset is guaranteed to be aligned to 64, but the base_gfn
1394 	 * of memslot has no such restriction, so the range can cross two large
1395 	 * pages.
1396 	 */
1397 	if (kvm_dirty_log_manual_protect_and_init_set(kvm)) {
1398 		gfn_t start = slot->base_gfn + gfn_offset + __ffs(mask);
1399 		gfn_t end = slot->base_gfn + gfn_offset + __fls(mask);
1400 
1401 		if (READ_ONCE(eager_page_split))
1402 			kvm_mmu_try_split_huge_pages(kvm, slot, start, end, PG_LEVEL_4K);
1403 
1404 		kvm_mmu_slot_gfn_write_protect(kvm, slot, start, PG_LEVEL_2M);
1405 
1406 		/* Cross two large pages? */
1407 		if (ALIGN(start << PAGE_SHIFT, PMD_SIZE) !=
1408 		    ALIGN(end << PAGE_SHIFT, PMD_SIZE))
1409 			kvm_mmu_slot_gfn_write_protect(kvm, slot, end,
1410 						       PG_LEVEL_2M);
1411 	}
1412 
1413 	/* Now handle 4K PTEs.  */
1414 	if (kvm_x86_ops.cpu_dirty_log_size)
1415 		kvm_mmu_clear_dirty_pt_masked(kvm, slot, gfn_offset, mask);
1416 	else
1417 		kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1418 }
1419 
1420 int kvm_cpu_dirty_log_size(void)
1421 {
1422 	return kvm_x86_ops.cpu_dirty_log_size;
1423 }
1424 
1425 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1426 				    struct kvm_memory_slot *slot, u64 gfn,
1427 				    int min_level)
1428 {
1429 	struct kvm_rmap_head *rmap_head;
1430 	int i;
1431 	bool write_protected = false;
1432 
1433 	if (kvm_memslots_have_rmaps(kvm)) {
1434 		for (i = min_level; i <= KVM_MAX_HUGEPAGE_LEVEL; ++i) {
1435 			rmap_head = gfn_to_rmap(gfn, i, slot);
1436 			write_protected |= rmap_write_protect(rmap_head, true);
1437 		}
1438 	}
1439 
1440 	if (tdp_mmu_enabled)
1441 		write_protected |=
1442 			kvm_tdp_mmu_write_protect_gfn(kvm, slot, gfn, min_level);
1443 
1444 	return write_protected;
1445 }
1446 
1447 static bool kvm_vcpu_write_protect_gfn(struct kvm_vcpu *vcpu, u64 gfn)
1448 {
1449 	struct kvm_memory_slot *slot;
1450 
1451 	slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1452 	return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn, PG_LEVEL_4K);
1453 }
1454 
1455 static bool __kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1456 			   const struct kvm_memory_slot *slot)
1457 {
1458 	return kvm_zap_all_rmap_sptes(kvm, rmap_head);
1459 }
1460 
1461 static bool kvm_zap_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1462 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1463 			 pte_t unused)
1464 {
1465 	return __kvm_zap_rmap(kvm, rmap_head, slot);
1466 }
1467 
1468 static bool kvm_set_pte_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1469 			     struct kvm_memory_slot *slot, gfn_t gfn, int level,
1470 			     pte_t pte)
1471 {
1472 	u64 *sptep;
1473 	struct rmap_iterator iter;
1474 	bool need_flush = false;
1475 	u64 new_spte;
1476 	kvm_pfn_t new_pfn;
1477 
1478 	WARN_ON(pte_huge(pte));
1479 	new_pfn = pte_pfn(pte);
1480 
1481 restart:
1482 	for_each_rmap_spte(rmap_head, &iter, sptep) {
1483 		rmap_printk("spte %p %llx gfn %llx (%d)\n",
1484 			    sptep, *sptep, gfn, level);
1485 
1486 		need_flush = true;
1487 
1488 		if (pte_write(pte)) {
1489 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
1490 			goto restart;
1491 		} else {
1492 			new_spte = kvm_mmu_changed_pte_notifier_make_spte(
1493 					*sptep, new_pfn);
1494 
1495 			mmu_spte_clear_track_bits(kvm, sptep);
1496 			mmu_spte_set(sptep, new_spte);
1497 		}
1498 	}
1499 
1500 	if (need_flush && kvm_available_flush_remote_tlbs_range()) {
1501 		kvm_flush_remote_tlbs_gfn(kvm, gfn, level);
1502 		return false;
1503 	}
1504 
1505 	return need_flush;
1506 }
1507 
1508 struct slot_rmap_walk_iterator {
1509 	/* input fields. */
1510 	const struct kvm_memory_slot *slot;
1511 	gfn_t start_gfn;
1512 	gfn_t end_gfn;
1513 	int start_level;
1514 	int end_level;
1515 
1516 	/* output fields. */
1517 	gfn_t gfn;
1518 	struct kvm_rmap_head *rmap;
1519 	int level;
1520 
1521 	/* private field. */
1522 	struct kvm_rmap_head *end_rmap;
1523 };
1524 
1525 static void rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator,
1526 				 int level)
1527 {
1528 	iterator->level = level;
1529 	iterator->gfn = iterator->start_gfn;
1530 	iterator->rmap = gfn_to_rmap(iterator->gfn, level, iterator->slot);
1531 	iterator->end_rmap = gfn_to_rmap(iterator->end_gfn, level, iterator->slot);
1532 }
1533 
1534 static void slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1535 				const struct kvm_memory_slot *slot,
1536 				int start_level, int end_level,
1537 				gfn_t start_gfn, gfn_t end_gfn)
1538 {
1539 	iterator->slot = slot;
1540 	iterator->start_level = start_level;
1541 	iterator->end_level = end_level;
1542 	iterator->start_gfn = start_gfn;
1543 	iterator->end_gfn = end_gfn;
1544 
1545 	rmap_walk_init_level(iterator, iterator->start_level);
1546 }
1547 
1548 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1549 {
1550 	return !!iterator->rmap;
1551 }
1552 
1553 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1554 {
1555 	while (++iterator->rmap <= iterator->end_rmap) {
1556 		iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1557 
1558 		if (iterator->rmap->val)
1559 			return;
1560 	}
1561 
1562 	if (++iterator->level > iterator->end_level) {
1563 		iterator->rmap = NULL;
1564 		return;
1565 	}
1566 
1567 	rmap_walk_init_level(iterator, iterator->level);
1568 }
1569 
1570 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,	\
1571 	   _start_gfn, _end_gfn, _iter_)				\
1572 	for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,		\
1573 				 _end_level_, _start_gfn, _end_gfn);	\
1574 	     slot_rmap_walk_okay(_iter_);				\
1575 	     slot_rmap_walk_next(_iter_))
1576 
1577 typedef bool (*rmap_handler_t)(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1578 			       struct kvm_memory_slot *slot, gfn_t gfn,
1579 			       int level, pte_t pte);
1580 
1581 static __always_inline bool kvm_handle_gfn_range(struct kvm *kvm,
1582 						 struct kvm_gfn_range *range,
1583 						 rmap_handler_t handler)
1584 {
1585 	struct slot_rmap_walk_iterator iterator;
1586 	bool ret = false;
1587 
1588 	for_each_slot_rmap_range(range->slot, PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
1589 				 range->start, range->end - 1, &iterator)
1590 		ret |= handler(kvm, iterator.rmap, range->slot, iterator.gfn,
1591 			       iterator.level, range->pte);
1592 
1593 	return ret;
1594 }
1595 
1596 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
1597 {
1598 	bool flush = false;
1599 
1600 	if (kvm_memslots_have_rmaps(kvm))
1601 		flush = kvm_handle_gfn_range(kvm, range, kvm_zap_rmap);
1602 
1603 	if (tdp_mmu_enabled)
1604 		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
1605 
1606 	if (kvm_x86_ops.set_apic_access_page_addr &&
1607 	    range->slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT)
1608 		kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
1609 
1610 	return flush;
1611 }
1612 
1613 bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1614 {
1615 	bool flush = false;
1616 
1617 	if (kvm_memslots_have_rmaps(kvm))
1618 		flush = kvm_handle_gfn_range(kvm, range, kvm_set_pte_rmap);
1619 
1620 	if (tdp_mmu_enabled)
1621 		flush |= kvm_tdp_mmu_set_spte_gfn(kvm, range);
1622 
1623 	return flush;
1624 }
1625 
1626 static bool kvm_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1627 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1628 			 pte_t unused)
1629 {
1630 	u64 *sptep;
1631 	struct rmap_iterator iter;
1632 	int young = 0;
1633 
1634 	for_each_rmap_spte(rmap_head, &iter, sptep)
1635 		young |= mmu_spte_age(sptep);
1636 
1637 	return young;
1638 }
1639 
1640 static bool kvm_test_age_rmap(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1641 			      struct kvm_memory_slot *slot, gfn_t gfn,
1642 			      int level, pte_t unused)
1643 {
1644 	u64 *sptep;
1645 	struct rmap_iterator iter;
1646 
1647 	for_each_rmap_spte(rmap_head, &iter, sptep)
1648 		if (is_accessed_spte(*sptep))
1649 			return true;
1650 	return false;
1651 }
1652 
1653 #define RMAP_RECYCLE_THRESHOLD 1000
1654 
1655 static void __rmap_add(struct kvm *kvm,
1656 		       struct kvm_mmu_memory_cache *cache,
1657 		       const struct kvm_memory_slot *slot,
1658 		       u64 *spte, gfn_t gfn, unsigned int access)
1659 {
1660 	struct kvm_mmu_page *sp;
1661 	struct kvm_rmap_head *rmap_head;
1662 	int rmap_count;
1663 
1664 	sp = sptep_to_sp(spte);
1665 	kvm_mmu_page_set_translation(sp, spte_index(spte), gfn, access);
1666 	kvm_update_page_stats(kvm, sp->role.level, 1);
1667 
1668 	rmap_head = gfn_to_rmap(gfn, sp->role.level, slot);
1669 	rmap_count = pte_list_add(cache, spte, rmap_head);
1670 
1671 	if (rmap_count > kvm->stat.max_mmu_rmap_size)
1672 		kvm->stat.max_mmu_rmap_size = rmap_count;
1673 	if (rmap_count > RMAP_RECYCLE_THRESHOLD) {
1674 		kvm_zap_all_rmap_sptes(kvm, rmap_head);
1675 		kvm_flush_remote_tlbs_gfn(kvm, gfn, sp->role.level);
1676 	}
1677 }
1678 
1679 static void rmap_add(struct kvm_vcpu *vcpu, const struct kvm_memory_slot *slot,
1680 		     u64 *spte, gfn_t gfn, unsigned int access)
1681 {
1682 	struct kvm_mmu_memory_cache *cache = &vcpu->arch.mmu_pte_list_desc_cache;
1683 
1684 	__rmap_add(vcpu->kvm, cache, slot, spte, gfn, access);
1685 }
1686 
1687 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1688 {
1689 	bool young = false;
1690 
1691 	if (kvm_memslots_have_rmaps(kvm))
1692 		young = kvm_handle_gfn_range(kvm, range, kvm_age_rmap);
1693 
1694 	if (tdp_mmu_enabled)
1695 		young |= kvm_tdp_mmu_age_gfn_range(kvm, range);
1696 
1697 	return young;
1698 }
1699 
1700 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
1701 {
1702 	bool young = false;
1703 
1704 	if (kvm_memslots_have_rmaps(kvm))
1705 		young = kvm_handle_gfn_range(kvm, range, kvm_test_age_rmap);
1706 
1707 	if (tdp_mmu_enabled)
1708 		young |= kvm_tdp_mmu_test_age_gfn(kvm, range);
1709 
1710 	return young;
1711 }
1712 
1713 #ifdef MMU_DEBUG
1714 static int is_empty_shadow_page(u64 *spt)
1715 {
1716 	u64 *pos;
1717 	u64 *end;
1718 
1719 	for (pos = spt, end = pos + SPTE_ENT_PER_PAGE; pos != end; pos++)
1720 		if (is_shadow_present_pte(*pos)) {
1721 			printk(KERN_ERR "%s: %p %llx\n", __func__,
1722 			       pos, *pos);
1723 			return 0;
1724 		}
1725 	return 1;
1726 }
1727 #endif
1728 
1729 /*
1730  * This value is the sum of all of the kvm instances's
1731  * kvm->arch.n_used_mmu_pages values.  We need a global,
1732  * aggregate version in order to make the slab shrinker
1733  * faster
1734  */
1735 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
1736 {
1737 	kvm->arch.n_used_mmu_pages += nr;
1738 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
1739 }
1740 
1741 static void kvm_account_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1742 {
1743 	kvm_mod_used_mmu_pages(kvm, +1);
1744 	kvm_account_pgtable_pages((void *)sp->spt, +1);
1745 }
1746 
1747 static void kvm_unaccount_mmu_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1748 {
1749 	kvm_mod_used_mmu_pages(kvm, -1);
1750 	kvm_account_pgtable_pages((void *)sp->spt, -1);
1751 }
1752 
1753 static void kvm_mmu_free_shadow_page(struct kvm_mmu_page *sp)
1754 {
1755 	MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
1756 	hlist_del(&sp->hash_link);
1757 	list_del(&sp->link);
1758 	free_page((unsigned long)sp->spt);
1759 	if (!sp->role.direct)
1760 		free_page((unsigned long)sp->shadowed_translation);
1761 	kmem_cache_free(mmu_page_header_cache, sp);
1762 }
1763 
1764 static unsigned kvm_page_table_hashfn(gfn_t gfn)
1765 {
1766 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
1767 }
1768 
1769 static void mmu_page_add_parent_pte(struct kvm_mmu_memory_cache *cache,
1770 				    struct kvm_mmu_page *sp, u64 *parent_pte)
1771 {
1772 	if (!parent_pte)
1773 		return;
1774 
1775 	pte_list_add(cache, parent_pte, &sp->parent_ptes);
1776 }
1777 
1778 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
1779 				       u64 *parent_pte)
1780 {
1781 	pte_list_remove(parent_pte, &sp->parent_ptes);
1782 }
1783 
1784 static void drop_parent_pte(struct kvm_mmu_page *sp,
1785 			    u64 *parent_pte)
1786 {
1787 	mmu_page_remove_parent_pte(sp, parent_pte);
1788 	mmu_spte_clear_no_track(parent_pte);
1789 }
1790 
1791 static void mark_unsync(u64 *spte);
1792 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
1793 {
1794 	u64 *sptep;
1795 	struct rmap_iterator iter;
1796 
1797 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
1798 		mark_unsync(sptep);
1799 	}
1800 }
1801 
1802 static void mark_unsync(u64 *spte)
1803 {
1804 	struct kvm_mmu_page *sp;
1805 
1806 	sp = sptep_to_sp(spte);
1807 	if (__test_and_set_bit(spte_index(spte), sp->unsync_child_bitmap))
1808 		return;
1809 	if (sp->unsync_children++)
1810 		return;
1811 	kvm_mmu_mark_parents_unsync(sp);
1812 }
1813 
1814 #define KVM_PAGE_ARRAY_NR 16
1815 
1816 struct kvm_mmu_pages {
1817 	struct mmu_page_and_offset {
1818 		struct kvm_mmu_page *sp;
1819 		unsigned int idx;
1820 	} page[KVM_PAGE_ARRAY_NR];
1821 	unsigned int nr;
1822 };
1823 
1824 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
1825 			 int idx)
1826 {
1827 	int i;
1828 
1829 	if (sp->unsync)
1830 		for (i=0; i < pvec->nr; i++)
1831 			if (pvec->page[i].sp == sp)
1832 				return 0;
1833 
1834 	pvec->page[pvec->nr].sp = sp;
1835 	pvec->page[pvec->nr].idx = idx;
1836 	pvec->nr++;
1837 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
1838 }
1839 
1840 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
1841 {
1842 	--sp->unsync_children;
1843 	WARN_ON((int)sp->unsync_children < 0);
1844 	__clear_bit(idx, sp->unsync_child_bitmap);
1845 }
1846 
1847 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
1848 			   struct kvm_mmu_pages *pvec)
1849 {
1850 	int i, ret, nr_unsync_leaf = 0;
1851 
1852 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
1853 		struct kvm_mmu_page *child;
1854 		u64 ent = sp->spt[i];
1855 
1856 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
1857 			clear_unsync_child_bit(sp, i);
1858 			continue;
1859 		}
1860 
1861 		child = spte_to_child_sp(ent);
1862 
1863 		if (child->unsync_children) {
1864 			if (mmu_pages_add(pvec, child, i))
1865 				return -ENOSPC;
1866 
1867 			ret = __mmu_unsync_walk(child, pvec);
1868 			if (!ret) {
1869 				clear_unsync_child_bit(sp, i);
1870 				continue;
1871 			} else if (ret > 0) {
1872 				nr_unsync_leaf += ret;
1873 			} else
1874 				return ret;
1875 		} else if (child->unsync) {
1876 			nr_unsync_leaf++;
1877 			if (mmu_pages_add(pvec, child, i))
1878 				return -ENOSPC;
1879 		} else
1880 			clear_unsync_child_bit(sp, i);
1881 	}
1882 
1883 	return nr_unsync_leaf;
1884 }
1885 
1886 #define INVALID_INDEX (-1)
1887 
1888 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
1889 			   struct kvm_mmu_pages *pvec)
1890 {
1891 	pvec->nr = 0;
1892 	if (!sp->unsync_children)
1893 		return 0;
1894 
1895 	mmu_pages_add(pvec, sp, INVALID_INDEX);
1896 	return __mmu_unsync_walk(sp, pvec);
1897 }
1898 
1899 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1900 {
1901 	WARN_ON(!sp->unsync);
1902 	trace_kvm_mmu_sync_page(sp);
1903 	sp->unsync = 0;
1904 	--kvm->stat.mmu_unsync;
1905 }
1906 
1907 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
1908 				     struct list_head *invalid_list);
1909 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
1910 				    struct list_head *invalid_list);
1911 
1912 static bool sp_has_gptes(struct kvm_mmu_page *sp)
1913 {
1914 	if (sp->role.direct)
1915 		return false;
1916 
1917 	if (sp->role.passthrough)
1918 		return false;
1919 
1920 	return true;
1921 }
1922 
1923 #define for_each_valid_sp(_kvm, _sp, _list)				\
1924 	hlist_for_each_entry(_sp, _list, hash_link)			\
1925 		if (is_obsolete_sp((_kvm), (_sp))) {			\
1926 		} else
1927 
1928 #define for_each_gfn_valid_sp_with_gptes(_kvm, _sp, _gfn)		\
1929 	for_each_valid_sp(_kvm, _sp,					\
1930 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
1931 		if ((_sp)->gfn != (_gfn) || !sp_has_gptes(_sp)) {} else
1932 
1933 static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1934 {
1935 	union kvm_mmu_page_role root_role = vcpu->arch.mmu->root_role;
1936 
1937 	/*
1938 	 * Ignore various flags when verifying that it's safe to sync a shadow
1939 	 * page using the current MMU context.
1940 	 *
1941 	 *  - level: not part of the overall MMU role and will never match as the MMU's
1942 	 *           level tracks the root level
1943 	 *  - access: updated based on the new guest PTE
1944 	 *  - quadrant: not part of the overall MMU role (similar to level)
1945 	 */
1946 	const union kvm_mmu_page_role sync_role_ign = {
1947 		.level = 0xf,
1948 		.access = 0x7,
1949 		.quadrant = 0x3,
1950 		.passthrough = 0x1,
1951 	};
1952 
1953 	/*
1954 	 * Direct pages can never be unsync, and KVM should never attempt to
1955 	 * sync a shadow page for a different MMU context, e.g. if the role
1956 	 * differs then the memslot lookup (SMM vs. non-SMM) will be bogus, the
1957 	 * reserved bits checks will be wrong, etc...
1958 	 */
1959 	if (WARN_ON_ONCE(sp->role.direct || !vcpu->arch.mmu->sync_spte ||
1960 			 (sp->role.word ^ root_role.word) & ~sync_role_ign.word))
1961 		return false;
1962 
1963 	return true;
1964 }
1965 
1966 static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
1967 {
1968 	if (!sp->spt[i])
1969 		return 0;
1970 
1971 	return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
1972 }
1973 
1974 static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
1975 {
1976 	int flush = 0;
1977 	int i;
1978 
1979 	if (!kvm_sync_page_check(vcpu, sp))
1980 		return -1;
1981 
1982 	for (i = 0; i < SPTE_ENT_PER_PAGE; i++) {
1983 		int ret = kvm_sync_spte(vcpu, sp, i);
1984 
1985 		if (ret < -1)
1986 			return -1;
1987 		flush |= ret;
1988 	}
1989 
1990 	/*
1991 	 * Note, any flush is purely for KVM's correctness, e.g. when dropping
1992 	 * an existing SPTE or clearing W/A/D bits to ensure an mmu_notifier
1993 	 * unmap or dirty logging event doesn't fail to flush.  The guest is
1994 	 * responsible for flushing the TLB to ensure any changes in protection
1995 	 * bits are recognized, i.e. until the guest flushes or page faults on
1996 	 * a relevant address, KVM is architecturally allowed to let vCPUs use
1997 	 * cached translations with the old protection bits.
1998 	 */
1999 	return flush;
2000 }
2001 
2002 static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2003 			 struct list_head *invalid_list)
2004 {
2005 	int ret = __kvm_sync_page(vcpu, sp);
2006 
2007 	if (ret < 0)
2008 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2009 	return ret;
2010 }
2011 
2012 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2013 					struct list_head *invalid_list,
2014 					bool remote_flush)
2015 {
2016 	if (!remote_flush && list_empty(invalid_list))
2017 		return false;
2018 
2019 	if (!list_empty(invalid_list))
2020 		kvm_mmu_commit_zap_page(kvm, invalid_list);
2021 	else
2022 		kvm_flush_remote_tlbs(kvm);
2023 	return true;
2024 }
2025 
2026 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2027 {
2028 	if (sp->role.invalid)
2029 		return true;
2030 
2031 	/* TDP MMU pages do not use the MMU generation. */
2032 	return !is_tdp_mmu_page(sp) &&
2033 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2034 }
2035 
2036 struct mmu_page_path {
2037 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2038 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
2039 };
2040 
2041 #define for_each_sp(pvec, sp, parents, i)			\
2042 		for (i = mmu_pages_first(&pvec, &parents);	\
2043 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
2044 			i = mmu_pages_next(&pvec, &parents, i))
2045 
2046 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2047 			  struct mmu_page_path *parents,
2048 			  int i)
2049 {
2050 	int n;
2051 
2052 	for (n = i+1; n < pvec->nr; n++) {
2053 		struct kvm_mmu_page *sp = pvec->page[n].sp;
2054 		unsigned idx = pvec->page[n].idx;
2055 		int level = sp->role.level;
2056 
2057 		parents->idx[level-1] = idx;
2058 		if (level == PG_LEVEL_4K)
2059 			break;
2060 
2061 		parents->parent[level-2] = sp;
2062 	}
2063 
2064 	return n;
2065 }
2066 
2067 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2068 			   struct mmu_page_path *parents)
2069 {
2070 	struct kvm_mmu_page *sp;
2071 	int level;
2072 
2073 	if (pvec->nr == 0)
2074 		return 0;
2075 
2076 	WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2077 
2078 	sp = pvec->page[0].sp;
2079 	level = sp->role.level;
2080 	WARN_ON(level == PG_LEVEL_4K);
2081 
2082 	parents->parent[level-2] = sp;
2083 
2084 	/* Also set up a sentinel.  Further entries in pvec are all
2085 	 * children of sp, so this element is never overwritten.
2086 	 */
2087 	parents->parent[level-1] = NULL;
2088 	return mmu_pages_next(pvec, parents, 0);
2089 }
2090 
2091 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2092 {
2093 	struct kvm_mmu_page *sp;
2094 	unsigned int level = 0;
2095 
2096 	do {
2097 		unsigned int idx = parents->idx[level];
2098 		sp = parents->parent[level];
2099 		if (!sp)
2100 			return;
2101 
2102 		WARN_ON(idx == INVALID_INDEX);
2103 		clear_unsync_child_bit(sp, idx);
2104 		level++;
2105 	} while (!sp->unsync_children);
2106 }
2107 
2108 static int mmu_sync_children(struct kvm_vcpu *vcpu,
2109 			     struct kvm_mmu_page *parent, bool can_yield)
2110 {
2111 	int i;
2112 	struct kvm_mmu_page *sp;
2113 	struct mmu_page_path parents;
2114 	struct kvm_mmu_pages pages;
2115 	LIST_HEAD(invalid_list);
2116 	bool flush = false;
2117 
2118 	while (mmu_unsync_walk(parent, &pages)) {
2119 		bool protected = false;
2120 
2121 		for_each_sp(pages, sp, parents, i)
2122 			protected |= kvm_vcpu_write_protect_gfn(vcpu, sp->gfn);
2123 
2124 		if (protected) {
2125 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, true);
2126 			flush = false;
2127 		}
2128 
2129 		for_each_sp(pages, sp, parents, i) {
2130 			kvm_unlink_unsync_page(vcpu->kvm, sp);
2131 			flush |= kvm_sync_page(vcpu, sp, &invalid_list) > 0;
2132 			mmu_pages_clear_parents(&parents);
2133 		}
2134 		if (need_resched() || rwlock_needbreak(&vcpu->kvm->mmu_lock)) {
2135 			kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2136 			if (!can_yield) {
2137 				kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2138 				return -EINTR;
2139 			}
2140 
2141 			cond_resched_rwlock_write(&vcpu->kvm->mmu_lock);
2142 			flush = false;
2143 		}
2144 	}
2145 
2146 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
2147 	return 0;
2148 }
2149 
2150 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2151 {
2152 	atomic_set(&sp->write_flooding_count,  0);
2153 }
2154 
2155 static void clear_sp_write_flooding_count(u64 *spte)
2156 {
2157 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
2158 }
2159 
2160 /*
2161  * The vCPU is required when finding indirect shadow pages; the shadow
2162  * page may already exist and syncing it needs the vCPU pointer in
2163  * order to read guest page tables.  Direct shadow pages are never
2164  * unsync, thus @vcpu can be NULL if @role.direct is true.
2165  */
2166 static struct kvm_mmu_page *kvm_mmu_find_shadow_page(struct kvm *kvm,
2167 						     struct kvm_vcpu *vcpu,
2168 						     gfn_t gfn,
2169 						     struct hlist_head *sp_list,
2170 						     union kvm_mmu_page_role role)
2171 {
2172 	struct kvm_mmu_page *sp;
2173 	int ret;
2174 	int collisions = 0;
2175 	LIST_HEAD(invalid_list);
2176 
2177 	for_each_valid_sp(kvm, sp, sp_list) {
2178 		if (sp->gfn != gfn) {
2179 			collisions++;
2180 			continue;
2181 		}
2182 
2183 		if (sp->role.word != role.word) {
2184 			/*
2185 			 * If the guest is creating an upper-level page, zap
2186 			 * unsync pages for the same gfn.  While it's possible
2187 			 * the guest is using recursive page tables, in all
2188 			 * likelihood the guest has stopped using the unsync
2189 			 * page and is installing a completely unrelated page.
2190 			 * Unsync pages must not be left as is, because the new
2191 			 * upper-level page will be write-protected.
2192 			 */
2193 			if (role.level > PG_LEVEL_4K && sp->unsync)
2194 				kvm_mmu_prepare_zap_page(kvm, sp,
2195 							 &invalid_list);
2196 			continue;
2197 		}
2198 
2199 		/* unsync and write-flooding only apply to indirect SPs. */
2200 		if (sp->role.direct)
2201 			goto out;
2202 
2203 		if (sp->unsync) {
2204 			if (KVM_BUG_ON(!vcpu, kvm))
2205 				break;
2206 
2207 			/*
2208 			 * The page is good, but is stale.  kvm_sync_page does
2209 			 * get the latest guest state, but (unlike mmu_unsync_children)
2210 			 * it doesn't write-protect the page or mark it synchronized!
2211 			 * This way the validity of the mapping is ensured, but the
2212 			 * overhead of write protection is not incurred until the
2213 			 * guest invalidates the TLB mapping.  This allows multiple
2214 			 * SPs for a single gfn to be unsync.
2215 			 *
2216 			 * If the sync fails, the page is zapped.  If so, break
2217 			 * in order to rebuild it.
2218 			 */
2219 			ret = kvm_sync_page(vcpu, sp, &invalid_list);
2220 			if (ret < 0)
2221 				break;
2222 
2223 			WARN_ON(!list_empty(&invalid_list));
2224 			if (ret > 0)
2225 				kvm_flush_remote_tlbs(kvm);
2226 		}
2227 
2228 		__clear_sp_write_flooding_count(sp);
2229 
2230 		goto out;
2231 	}
2232 
2233 	sp = NULL;
2234 	++kvm->stat.mmu_cache_miss;
2235 
2236 out:
2237 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2238 
2239 	if (collisions > kvm->stat.max_mmu_page_hash_collisions)
2240 		kvm->stat.max_mmu_page_hash_collisions = collisions;
2241 	return sp;
2242 }
2243 
2244 /* Caches used when allocating a new shadow page. */
2245 struct shadow_page_caches {
2246 	struct kvm_mmu_memory_cache *page_header_cache;
2247 	struct kvm_mmu_memory_cache *shadow_page_cache;
2248 	struct kvm_mmu_memory_cache *shadowed_info_cache;
2249 };
2250 
2251 static struct kvm_mmu_page *kvm_mmu_alloc_shadow_page(struct kvm *kvm,
2252 						      struct shadow_page_caches *caches,
2253 						      gfn_t gfn,
2254 						      struct hlist_head *sp_list,
2255 						      union kvm_mmu_page_role role)
2256 {
2257 	struct kvm_mmu_page *sp;
2258 
2259 	sp = kvm_mmu_memory_cache_alloc(caches->page_header_cache);
2260 	sp->spt = kvm_mmu_memory_cache_alloc(caches->shadow_page_cache);
2261 	if (!role.direct)
2262 		sp->shadowed_translation = kvm_mmu_memory_cache_alloc(caches->shadowed_info_cache);
2263 
2264 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2265 
2266 	INIT_LIST_HEAD(&sp->possible_nx_huge_page_link);
2267 
2268 	/*
2269 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2270 	 * depends on valid pages being added to the head of the list.  See
2271 	 * comments in kvm_zap_obsolete_pages().
2272 	 */
2273 	sp->mmu_valid_gen = kvm->arch.mmu_valid_gen;
2274 	list_add(&sp->link, &kvm->arch.active_mmu_pages);
2275 	kvm_account_mmu_page(kvm, sp);
2276 
2277 	sp->gfn = gfn;
2278 	sp->role = role;
2279 	hlist_add_head(&sp->hash_link, sp_list);
2280 	if (sp_has_gptes(sp))
2281 		account_shadowed(kvm, sp);
2282 
2283 	return sp;
2284 }
2285 
2286 /* Note, @vcpu may be NULL if @role.direct is true; see kvm_mmu_find_shadow_page. */
2287 static struct kvm_mmu_page *__kvm_mmu_get_shadow_page(struct kvm *kvm,
2288 						      struct kvm_vcpu *vcpu,
2289 						      struct shadow_page_caches *caches,
2290 						      gfn_t gfn,
2291 						      union kvm_mmu_page_role role)
2292 {
2293 	struct hlist_head *sp_list;
2294 	struct kvm_mmu_page *sp;
2295 	bool created = false;
2296 
2297 	sp_list = &kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2298 
2299 	sp = kvm_mmu_find_shadow_page(kvm, vcpu, gfn, sp_list, role);
2300 	if (!sp) {
2301 		created = true;
2302 		sp = kvm_mmu_alloc_shadow_page(kvm, caches, gfn, sp_list, role);
2303 	}
2304 
2305 	trace_kvm_mmu_get_page(sp, created);
2306 	return sp;
2307 }
2308 
2309 static struct kvm_mmu_page *kvm_mmu_get_shadow_page(struct kvm_vcpu *vcpu,
2310 						    gfn_t gfn,
2311 						    union kvm_mmu_page_role role)
2312 {
2313 	struct shadow_page_caches caches = {
2314 		.page_header_cache = &vcpu->arch.mmu_page_header_cache,
2315 		.shadow_page_cache = &vcpu->arch.mmu_shadow_page_cache,
2316 		.shadowed_info_cache = &vcpu->arch.mmu_shadowed_info_cache,
2317 	};
2318 
2319 	return __kvm_mmu_get_shadow_page(vcpu->kvm, vcpu, &caches, gfn, role);
2320 }
2321 
2322 static union kvm_mmu_page_role kvm_mmu_child_role(u64 *sptep, bool direct,
2323 						  unsigned int access)
2324 {
2325 	struct kvm_mmu_page *parent_sp = sptep_to_sp(sptep);
2326 	union kvm_mmu_page_role role;
2327 
2328 	role = parent_sp->role;
2329 	role.level--;
2330 	role.access = access;
2331 	role.direct = direct;
2332 	role.passthrough = 0;
2333 
2334 	/*
2335 	 * If the guest has 4-byte PTEs then that means it's using 32-bit,
2336 	 * 2-level, non-PAE paging. KVM shadows such guests with PAE paging
2337 	 * (i.e. 8-byte PTEs). The difference in PTE size means that KVM must
2338 	 * shadow each guest page table with multiple shadow page tables, which
2339 	 * requires extra bookkeeping in the role.
2340 	 *
2341 	 * Specifically, to shadow the guest's page directory (which covers a
2342 	 * 4GiB address space), KVM uses 4 PAE page directories, each mapping
2343 	 * 1GiB of the address space. @role.quadrant encodes which quarter of
2344 	 * the address space each maps.
2345 	 *
2346 	 * To shadow the guest's page tables (which each map a 4MiB region), KVM
2347 	 * uses 2 PAE page tables, each mapping a 2MiB region. For these,
2348 	 * @role.quadrant encodes which half of the region they map.
2349 	 *
2350 	 * Concretely, a 4-byte PDE consumes bits 31:22, while an 8-byte PDE
2351 	 * consumes bits 29:21.  To consume bits 31:30, KVM's uses 4 shadow
2352 	 * PDPTEs; those 4 PAE page directories are pre-allocated and their
2353 	 * quadrant is assigned in mmu_alloc_root().   A 4-byte PTE consumes
2354 	 * bits 21:12, while an 8-byte PTE consumes bits 20:12.  To consume
2355 	 * bit 21 in the PTE (the child here), KVM propagates that bit to the
2356 	 * quadrant, i.e. sets quadrant to '0' or '1'.  The parent 8-byte PDE
2357 	 * covers bit 21 (see above), thus the quadrant is calculated from the
2358 	 * _least_ significant bit of the PDE index.
2359 	 */
2360 	if (role.has_4_byte_gpte) {
2361 		WARN_ON_ONCE(role.level != PG_LEVEL_4K);
2362 		role.quadrant = spte_index(sptep) & 1;
2363 	}
2364 
2365 	return role;
2366 }
2367 
2368 static struct kvm_mmu_page *kvm_mmu_get_child_sp(struct kvm_vcpu *vcpu,
2369 						 u64 *sptep, gfn_t gfn,
2370 						 bool direct, unsigned int access)
2371 {
2372 	union kvm_mmu_page_role role;
2373 
2374 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep))
2375 		return ERR_PTR(-EEXIST);
2376 
2377 	role = kvm_mmu_child_role(sptep, direct, access);
2378 	return kvm_mmu_get_shadow_page(vcpu, gfn, role);
2379 }
2380 
2381 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2382 					struct kvm_vcpu *vcpu, hpa_t root,
2383 					u64 addr)
2384 {
2385 	iterator->addr = addr;
2386 	iterator->shadow_addr = root;
2387 	iterator->level = vcpu->arch.mmu->root_role.level;
2388 
2389 	if (iterator->level >= PT64_ROOT_4LEVEL &&
2390 	    vcpu->arch.mmu->cpu_role.base.level < PT64_ROOT_4LEVEL &&
2391 	    !vcpu->arch.mmu->root_role.direct)
2392 		iterator->level = PT32E_ROOT_LEVEL;
2393 
2394 	if (iterator->level == PT32E_ROOT_LEVEL) {
2395 		/*
2396 		 * prev_root is currently only used for 64-bit hosts. So only
2397 		 * the active root_hpa is valid here.
2398 		 */
2399 		BUG_ON(root != vcpu->arch.mmu->root.hpa);
2400 
2401 		iterator->shadow_addr
2402 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2403 		iterator->shadow_addr &= SPTE_BASE_ADDR_MASK;
2404 		--iterator->level;
2405 		if (!iterator->shadow_addr)
2406 			iterator->level = 0;
2407 	}
2408 }
2409 
2410 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2411 			     struct kvm_vcpu *vcpu, u64 addr)
2412 {
2413 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root.hpa,
2414 				    addr);
2415 }
2416 
2417 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2418 {
2419 	if (iterator->level < PG_LEVEL_4K)
2420 		return false;
2421 
2422 	iterator->index = SPTE_INDEX(iterator->addr, iterator->level);
2423 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2424 	return true;
2425 }
2426 
2427 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2428 			       u64 spte)
2429 {
2430 	if (!is_shadow_present_pte(spte) || is_last_spte(spte, iterator->level)) {
2431 		iterator->level = 0;
2432 		return;
2433 	}
2434 
2435 	iterator->shadow_addr = spte & SPTE_BASE_ADDR_MASK;
2436 	--iterator->level;
2437 }
2438 
2439 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2440 {
2441 	__shadow_walk_next(iterator, *iterator->sptep);
2442 }
2443 
2444 static void __link_shadow_page(struct kvm *kvm,
2445 			       struct kvm_mmu_memory_cache *cache, u64 *sptep,
2446 			       struct kvm_mmu_page *sp, bool flush)
2447 {
2448 	u64 spte;
2449 
2450 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2451 
2452 	/*
2453 	 * If an SPTE is present already, it must be a leaf and therefore
2454 	 * a large one.  Drop it, and flush the TLB if needed, before
2455 	 * installing sp.
2456 	 */
2457 	if (is_shadow_present_pte(*sptep))
2458 		drop_large_spte(kvm, sptep, flush);
2459 
2460 	spte = make_nonleaf_spte(sp->spt, sp_ad_disabled(sp));
2461 
2462 	mmu_spte_set(sptep, spte);
2463 
2464 	mmu_page_add_parent_pte(cache, sp, sptep);
2465 
2466 	/*
2467 	 * The non-direct sub-pagetable must be updated before linking.  For
2468 	 * L1 sp, the pagetable is updated via kvm_sync_page() in
2469 	 * kvm_mmu_find_shadow_page() without write-protecting the gfn,
2470 	 * so sp->unsync can be true or false.  For higher level non-direct
2471 	 * sp, the pagetable is updated/synced via mmu_sync_children() in
2472 	 * FNAME(fetch)(), so sp->unsync_children can only be false.
2473 	 * WARN_ON_ONCE() if anything happens unexpectedly.
2474 	 */
2475 	if (WARN_ON_ONCE(sp->unsync_children) || sp->unsync)
2476 		mark_unsync(sptep);
2477 }
2478 
2479 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2480 			     struct kvm_mmu_page *sp)
2481 {
2482 	__link_shadow_page(vcpu->kvm, &vcpu->arch.mmu_pte_list_desc_cache, sptep, sp, true);
2483 }
2484 
2485 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2486 				   unsigned direct_access)
2487 {
2488 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2489 		struct kvm_mmu_page *child;
2490 
2491 		/*
2492 		 * For the direct sp, if the guest pte's dirty bit
2493 		 * changed form clean to dirty, it will corrupt the
2494 		 * sp's access: allow writable in the read-only sp,
2495 		 * so we should update the spte at this point to get
2496 		 * a new sp with the correct access.
2497 		 */
2498 		child = spte_to_child_sp(*sptep);
2499 		if (child->role.access == direct_access)
2500 			return;
2501 
2502 		drop_parent_pte(child, sptep);
2503 		kvm_flush_remote_tlbs_sptep(vcpu->kvm, sptep);
2504 	}
2505 }
2506 
2507 /* Returns the number of zapped non-leaf child shadow pages. */
2508 static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2509 			    u64 *spte, struct list_head *invalid_list)
2510 {
2511 	u64 pte;
2512 	struct kvm_mmu_page *child;
2513 
2514 	pte = *spte;
2515 	if (is_shadow_present_pte(pte)) {
2516 		if (is_last_spte(pte, sp->role.level)) {
2517 			drop_spte(kvm, spte);
2518 		} else {
2519 			child = spte_to_child_sp(pte);
2520 			drop_parent_pte(child, spte);
2521 
2522 			/*
2523 			 * Recursively zap nested TDP SPs, parentless SPs are
2524 			 * unlikely to be used again in the near future.  This
2525 			 * avoids retaining a large number of stale nested SPs.
2526 			 */
2527 			if (tdp_enabled && invalid_list &&
2528 			    child->role.guest_mode && !child->parent_ptes.val)
2529 				return kvm_mmu_prepare_zap_page(kvm, child,
2530 								invalid_list);
2531 		}
2532 	} else if (is_mmio_spte(pte)) {
2533 		mmu_spte_clear_no_track(spte);
2534 	}
2535 	return 0;
2536 }
2537 
2538 static int kvm_mmu_page_unlink_children(struct kvm *kvm,
2539 					struct kvm_mmu_page *sp,
2540 					struct list_head *invalid_list)
2541 {
2542 	int zapped = 0;
2543 	unsigned i;
2544 
2545 	for (i = 0; i < SPTE_ENT_PER_PAGE; ++i)
2546 		zapped += mmu_page_zap_pte(kvm, sp, sp->spt + i, invalid_list);
2547 
2548 	return zapped;
2549 }
2550 
2551 static void kvm_mmu_unlink_parents(struct kvm_mmu_page *sp)
2552 {
2553 	u64 *sptep;
2554 	struct rmap_iterator iter;
2555 
2556 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2557 		drop_parent_pte(sp, sptep);
2558 }
2559 
2560 static int mmu_zap_unsync_children(struct kvm *kvm,
2561 				   struct kvm_mmu_page *parent,
2562 				   struct list_head *invalid_list)
2563 {
2564 	int i, zapped = 0;
2565 	struct mmu_page_path parents;
2566 	struct kvm_mmu_pages pages;
2567 
2568 	if (parent->role.level == PG_LEVEL_4K)
2569 		return 0;
2570 
2571 	while (mmu_unsync_walk(parent, &pages)) {
2572 		struct kvm_mmu_page *sp;
2573 
2574 		for_each_sp(pages, sp, parents, i) {
2575 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2576 			mmu_pages_clear_parents(&parents);
2577 			zapped++;
2578 		}
2579 	}
2580 
2581 	return zapped;
2582 }
2583 
2584 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2585 				       struct kvm_mmu_page *sp,
2586 				       struct list_head *invalid_list,
2587 				       int *nr_zapped)
2588 {
2589 	bool list_unstable, zapped_root = false;
2590 
2591 	lockdep_assert_held_write(&kvm->mmu_lock);
2592 	trace_kvm_mmu_prepare_zap_page(sp);
2593 	++kvm->stat.mmu_shadow_zapped;
2594 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2595 	*nr_zapped += kvm_mmu_page_unlink_children(kvm, sp, invalid_list);
2596 	kvm_mmu_unlink_parents(sp);
2597 
2598 	/* Zapping children means active_mmu_pages has become unstable. */
2599 	list_unstable = *nr_zapped;
2600 
2601 	if (!sp->role.invalid && sp_has_gptes(sp))
2602 		unaccount_shadowed(kvm, sp);
2603 
2604 	if (sp->unsync)
2605 		kvm_unlink_unsync_page(kvm, sp);
2606 	if (!sp->root_count) {
2607 		/* Count self */
2608 		(*nr_zapped)++;
2609 
2610 		/*
2611 		 * Already invalid pages (previously active roots) are not on
2612 		 * the active page list.  See list_del() in the "else" case of
2613 		 * !sp->root_count.
2614 		 */
2615 		if (sp->role.invalid)
2616 			list_add(&sp->link, invalid_list);
2617 		else
2618 			list_move(&sp->link, invalid_list);
2619 		kvm_unaccount_mmu_page(kvm, sp);
2620 	} else {
2621 		/*
2622 		 * Remove the active root from the active page list, the root
2623 		 * will be explicitly freed when the root_count hits zero.
2624 		 */
2625 		list_del(&sp->link);
2626 
2627 		/*
2628 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2629 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2630 		 * treats invalid shadow pages as being obsolete.
2631 		 */
2632 		zapped_root = !is_obsolete_sp(kvm, sp);
2633 	}
2634 
2635 	if (sp->nx_huge_page_disallowed)
2636 		unaccount_nx_huge_page(kvm, sp);
2637 
2638 	sp->role.invalid = 1;
2639 
2640 	/*
2641 	 * Make the request to free obsolete roots after marking the root
2642 	 * invalid, otherwise other vCPUs may not see it as invalid.
2643 	 */
2644 	if (zapped_root)
2645 		kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
2646 	return list_unstable;
2647 }
2648 
2649 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2650 				     struct list_head *invalid_list)
2651 {
2652 	int nr_zapped;
2653 
2654 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2655 	return nr_zapped;
2656 }
2657 
2658 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2659 				    struct list_head *invalid_list)
2660 {
2661 	struct kvm_mmu_page *sp, *nsp;
2662 
2663 	if (list_empty(invalid_list))
2664 		return;
2665 
2666 	/*
2667 	 * We need to make sure everyone sees our modifications to
2668 	 * the page tables and see changes to vcpu->mode here. The barrier
2669 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2670 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2671 	 *
2672 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2673 	 * guest mode and/or lockless shadow page table walks.
2674 	 */
2675 	kvm_flush_remote_tlbs(kvm);
2676 
2677 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2678 		WARN_ON(!sp->role.invalid || sp->root_count);
2679 		kvm_mmu_free_shadow_page(sp);
2680 	}
2681 }
2682 
2683 static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2684 						  unsigned long nr_to_zap)
2685 {
2686 	unsigned long total_zapped = 0;
2687 	struct kvm_mmu_page *sp, *tmp;
2688 	LIST_HEAD(invalid_list);
2689 	bool unstable;
2690 	int nr_zapped;
2691 
2692 	if (list_empty(&kvm->arch.active_mmu_pages))
2693 		return 0;
2694 
2695 restart:
2696 	list_for_each_entry_safe_reverse(sp, tmp, &kvm->arch.active_mmu_pages, link) {
2697 		/*
2698 		 * Don't zap active root pages, the page itself can't be freed
2699 		 * and zapping it will just force vCPUs to realloc and reload.
2700 		 */
2701 		if (sp->root_count)
2702 			continue;
2703 
2704 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2705 						      &nr_zapped);
2706 		total_zapped += nr_zapped;
2707 		if (total_zapped >= nr_to_zap)
2708 			break;
2709 
2710 		if (unstable)
2711 			goto restart;
2712 	}
2713 
2714 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2715 
2716 	kvm->stat.mmu_recycled += total_zapped;
2717 	return total_zapped;
2718 }
2719 
2720 static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2721 {
2722 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2723 		return kvm->arch.n_max_mmu_pages -
2724 			kvm->arch.n_used_mmu_pages;
2725 
2726 	return 0;
2727 }
2728 
2729 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2730 {
2731 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2732 
2733 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2734 		return 0;
2735 
2736 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2737 
2738 	/*
2739 	 * Note, this check is intentionally soft, it only guarantees that one
2740 	 * page is available, while the caller may end up allocating as many as
2741 	 * four pages, e.g. for PAE roots or for 5-level paging.  Temporarily
2742 	 * exceeding the (arbitrary by default) limit will not harm the host,
2743 	 * being too aggressive may unnecessarily kill the guest, and getting an
2744 	 * exact count is far more trouble than it's worth, especially in the
2745 	 * page fault paths.
2746 	 */
2747 	if (!kvm_mmu_available_pages(vcpu->kvm))
2748 		return -ENOSPC;
2749 	return 0;
2750 }
2751 
2752 /*
2753  * Changing the number of mmu pages allocated to the vm
2754  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2755  */
2756 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2757 {
2758 	write_lock(&kvm->mmu_lock);
2759 
2760 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2761 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2762 						  goal_nr_mmu_pages);
2763 
2764 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2765 	}
2766 
2767 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2768 
2769 	write_unlock(&kvm->mmu_lock);
2770 }
2771 
2772 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2773 {
2774 	struct kvm_mmu_page *sp;
2775 	LIST_HEAD(invalid_list);
2776 	int r;
2777 
2778 	pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2779 	r = 0;
2780 	write_lock(&kvm->mmu_lock);
2781 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2782 		pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2783 			 sp->role.word);
2784 		r = 1;
2785 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2786 	}
2787 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2788 	write_unlock(&kvm->mmu_lock);
2789 
2790 	return r;
2791 }
2792 
2793 static int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
2794 {
2795 	gpa_t gpa;
2796 	int r;
2797 
2798 	if (vcpu->arch.mmu->root_role.direct)
2799 		return 0;
2800 
2801 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
2802 
2803 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
2804 
2805 	return r;
2806 }
2807 
2808 static void kvm_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2809 {
2810 	trace_kvm_mmu_unsync_page(sp);
2811 	++kvm->stat.mmu_unsync;
2812 	sp->unsync = 1;
2813 
2814 	kvm_mmu_mark_parents_unsync(sp);
2815 }
2816 
2817 /*
2818  * Attempt to unsync any shadow pages that can be reached by the specified gfn,
2819  * KVM is creating a writable mapping for said gfn.  Returns 0 if all pages
2820  * were marked unsync (or if there is no shadow page), -EPERM if the SPTE must
2821  * be write-protected.
2822  */
2823 int mmu_try_to_unsync_pages(struct kvm *kvm, const struct kvm_memory_slot *slot,
2824 			    gfn_t gfn, bool can_unsync, bool prefetch)
2825 {
2826 	struct kvm_mmu_page *sp;
2827 	bool locked = false;
2828 
2829 	/*
2830 	 * Force write-protection if the page is being tracked.  Note, the page
2831 	 * track machinery is used to write-protect upper-level shadow pages,
2832 	 * i.e. this guards the role.level == 4K assertion below!
2833 	 */
2834 	if (kvm_slot_page_track_is_active(kvm, slot, gfn, KVM_PAGE_TRACK_WRITE))
2835 		return -EPERM;
2836 
2837 	/*
2838 	 * The page is not write-tracked, mark existing shadow pages unsync
2839 	 * unless KVM is synchronizing an unsync SP (can_unsync = false).  In
2840 	 * that case, KVM must complete emulation of the guest TLB flush before
2841 	 * allowing shadow pages to become unsync (writable by the guest).
2842 	 */
2843 	for_each_gfn_valid_sp_with_gptes(kvm, sp, gfn) {
2844 		if (!can_unsync)
2845 			return -EPERM;
2846 
2847 		if (sp->unsync)
2848 			continue;
2849 
2850 		if (prefetch)
2851 			return -EEXIST;
2852 
2853 		/*
2854 		 * TDP MMU page faults require an additional spinlock as they
2855 		 * run with mmu_lock held for read, not write, and the unsync
2856 		 * logic is not thread safe.  Take the spinklock regardless of
2857 		 * the MMU type to avoid extra conditionals/parameters, there's
2858 		 * no meaningful penalty if mmu_lock is held for write.
2859 		 */
2860 		if (!locked) {
2861 			locked = true;
2862 			spin_lock(&kvm->arch.mmu_unsync_pages_lock);
2863 
2864 			/*
2865 			 * Recheck after taking the spinlock, a different vCPU
2866 			 * may have since marked the page unsync.  A false
2867 			 * positive on the unprotected check above is not
2868 			 * possible as clearing sp->unsync _must_ hold mmu_lock
2869 			 * for write, i.e. unsync cannot transition from 0->1
2870 			 * while this CPU holds mmu_lock for read (or write).
2871 			 */
2872 			if (READ_ONCE(sp->unsync))
2873 				continue;
2874 		}
2875 
2876 		WARN_ON(sp->role.level != PG_LEVEL_4K);
2877 		kvm_unsync_page(kvm, sp);
2878 	}
2879 	if (locked)
2880 		spin_unlock(&kvm->arch.mmu_unsync_pages_lock);
2881 
2882 	/*
2883 	 * We need to ensure that the marking of unsync pages is visible
2884 	 * before the SPTE is updated to allow writes because
2885 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2886 	 * the MMU lock and so can race with this. If the SPTE was updated
2887 	 * before the page had been marked as unsync-ed, something like the
2888 	 * following could happen:
2889 	 *
2890 	 * CPU 1                    CPU 2
2891 	 * ---------------------------------------------------------------------
2892 	 * 1.2 Host updates SPTE
2893 	 *     to be writable
2894 	 *                      2.1 Guest writes a GPTE for GVA X.
2895 	 *                          (GPTE being in the guest page table shadowed
2896 	 *                           by the SP from CPU 1.)
2897 	 *                          This reads SPTE during the page table walk.
2898 	 *                          Since SPTE.W is read as 1, there is no
2899 	 *                          fault.
2900 	 *
2901 	 *                      2.2 Guest issues TLB flush.
2902 	 *                          That causes a VM Exit.
2903 	 *
2904 	 *                      2.3 Walking of unsync pages sees sp->unsync is
2905 	 *                          false and skips the page.
2906 	 *
2907 	 *                      2.4 Guest accesses GVA X.
2908 	 *                          Since the mapping in the SP was not updated,
2909 	 *                          so the old mapping for GVA X incorrectly
2910 	 *                          gets used.
2911 	 * 1.1 Host marks SP
2912 	 *     as unsync
2913 	 *     (sp->unsync = true)
2914 	 *
2915 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2916 	 * the situation in 2.4 does not arise.  It pairs with the read barrier
2917 	 * in is_unsync_root(), placed between 2.1's load of SPTE.W and 2.3.
2918 	 */
2919 	smp_wmb();
2920 
2921 	return 0;
2922 }
2923 
2924 static int mmu_set_spte(struct kvm_vcpu *vcpu, struct kvm_memory_slot *slot,
2925 			u64 *sptep, unsigned int pte_access, gfn_t gfn,
2926 			kvm_pfn_t pfn, struct kvm_page_fault *fault)
2927 {
2928 	struct kvm_mmu_page *sp = sptep_to_sp(sptep);
2929 	int level = sp->role.level;
2930 	int was_rmapped = 0;
2931 	int ret = RET_PF_FIXED;
2932 	bool flush = false;
2933 	bool wrprot;
2934 	u64 spte;
2935 
2936 	/* Prefetching always gets a writable pfn.  */
2937 	bool host_writable = !fault || fault->map_writable;
2938 	bool prefetch = !fault || fault->prefetch;
2939 	bool write_fault = fault && fault->write;
2940 
2941 	pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
2942 		 *sptep, write_fault, gfn);
2943 
2944 	if (unlikely(is_noslot_pfn(pfn))) {
2945 		vcpu->stat.pf_mmio_spte_created++;
2946 		mark_mmio_spte(vcpu, sptep, gfn, pte_access);
2947 		return RET_PF_EMULATE;
2948 	}
2949 
2950 	if (is_shadow_present_pte(*sptep)) {
2951 		/*
2952 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
2953 		 * the parent of the now unreachable PTE.
2954 		 */
2955 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
2956 			struct kvm_mmu_page *child;
2957 			u64 pte = *sptep;
2958 
2959 			child = spte_to_child_sp(pte);
2960 			drop_parent_pte(child, sptep);
2961 			flush = true;
2962 		} else if (pfn != spte_to_pfn(*sptep)) {
2963 			pgprintk("hfn old %llx new %llx\n",
2964 				 spte_to_pfn(*sptep), pfn);
2965 			drop_spte(vcpu->kvm, sptep);
2966 			flush = true;
2967 		} else
2968 			was_rmapped = 1;
2969 	}
2970 
2971 	wrprot = make_spte(vcpu, sp, slot, pte_access, gfn, pfn, *sptep, prefetch,
2972 			   true, host_writable, &spte);
2973 
2974 	if (*sptep == spte) {
2975 		ret = RET_PF_SPURIOUS;
2976 	} else {
2977 		flush |= mmu_spte_update(sptep, spte);
2978 		trace_kvm_mmu_set_spte(level, gfn, sptep);
2979 	}
2980 
2981 	if (wrprot) {
2982 		if (write_fault)
2983 			ret = RET_PF_EMULATE;
2984 	}
2985 
2986 	if (flush)
2987 		kvm_flush_remote_tlbs_gfn(vcpu->kvm, gfn, level);
2988 
2989 	pgprintk("%s: setting spte %llx\n", __func__, *sptep);
2990 
2991 	if (!was_rmapped) {
2992 		WARN_ON_ONCE(ret == RET_PF_SPURIOUS);
2993 		rmap_add(vcpu, slot, sptep, gfn, pte_access);
2994 	} else {
2995 		/* Already rmapped but the pte_access bits may have changed. */
2996 		kvm_mmu_page_set_access(sp, spte_index(sptep), pte_access);
2997 	}
2998 
2999 	return ret;
3000 }
3001 
3002 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3003 				    struct kvm_mmu_page *sp,
3004 				    u64 *start, u64 *end)
3005 {
3006 	struct page *pages[PTE_PREFETCH_NUM];
3007 	struct kvm_memory_slot *slot;
3008 	unsigned int access = sp->role.access;
3009 	int i, ret;
3010 	gfn_t gfn;
3011 
3012 	gfn = kvm_mmu_page_get_gfn(sp, spte_index(start));
3013 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3014 	if (!slot)
3015 		return -1;
3016 
3017 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3018 	if (ret <= 0)
3019 		return -1;
3020 
3021 	for (i = 0; i < ret; i++, gfn++, start++) {
3022 		mmu_set_spte(vcpu, slot, start, access, gfn,
3023 			     page_to_pfn(pages[i]), NULL);
3024 		put_page(pages[i]);
3025 	}
3026 
3027 	return 0;
3028 }
3029 
3030 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3031 				  struct kvm_mmu_page *sp, u64 *sptep)
3032 {
3033 	u64 *spte, *start = NULL;
3034 	int i;
3035 
3036 	WARN_ON(!sp->role.direct);
3037 
3038 	i = spte_index(sptep) & ~(PTE_PREFETCH_NUM - 1);
3039 	spte = sp->spt + i;
3040 
3041 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3042 		if (is_shadow_present_pte(*spte) || spte == sptep) {
3043 			if (!start)
3044 				continue;
3045 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3046 				return;
3047 			start = NULL;
3048 		} else if (!start)
3049 			start = spte;
3050 	}
3051 	if (start)
3052 		direct_pte_prefetch_many(vcpu, sp, start, spte);
3053 }
3054 
3055 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3056 {
3057 	struct kvm_mmu_page *sp;
3058 
3059 	sp = sptep_to_sp(sptep);
3060 
3061 	/*
3062 	 * Without accessed bits, there's no way to distinguish between
3063 	 * actually accessed translations and prefetched, so disable pte
3064 	 * prefetch if accessed bits aren't available.
3065 	 */
3066 	if (sp_ad_disabled(sp))
3067 		return;
3068 
3069 	if (sp->role.level > PG_LEVEL_4K)
3070 		return;
3071 
3072 	/*
3073 	 * If addresses are being invalidated, skip prefetching to avoid
3074 	 * accidentally prefetching those addresses.
3075 	 */
3076 	if (unlikely(vcpu->kvm->mmu_invalidate_in_progress))
3077 		return;
3078 
3079 	__direct_pte_prefetch(vcpu, sp, sptep);
3080 }
3081 
3082 /*
3083  * Lookup the mapping level for @gfn in the current mm.
3084  *
3085  * WARNING!  Use of host_pfn_mapping_level() requires the caller and the end
3086  * consumer to be tied into KVM's handlers for MMU notifier events!
3087  *
3088  * There are several ways to safely use this helper:
3089  *
3090  * - Check mmu_invalidate_retry_hva() after grabbing the mapping level, before
3091  *   consuming it.  In this case, mmu_lock doesn't need to be held during the
3092  *   lookup, but it does need to be held while checking the MMU notifier.
3093  *
3094  * - Hold mmu_lock AND ensure there is no in-progress MMU notifier invalidation
3095  *   event for the hva.  This can be done by explicit checking the MMU notifier
3096  *   or by ensuring that KVM already has a valid mapping that covers the hva.
3097  *
3098  * - Do not use the result to install new mappings, e.g. use the host mapping
3099  *   level only to decide whether or not to zap an entry.  In this case, it's
3100  *   not required to hold mmu_lock (though it's highly likely the caller will
3101  *   want to hold mmu_lock anyways, e.g. to modify SPTEs).
3102  *
3103  * Note!  The lookup can still race with modifications to host page tables, but
3104  * the above "rules" ensure KVM will not _consume_ the result of the walk if a
3105  * race with the primary MMU occurs.
3106  */
3107 static int host_pfn_mapping_level(struct kvm *kvm, gfn_t gfn,
3108 				  const struct kvm_memory_slot *slot)
3109 {
3110 	int level = PG_LEVEL_4K;
3111 	unsigned long hva;
3112 	unsigned long flags;
3113 	pgd_t pgd;
3114 	p4d_t p4d;
3115 	pud_t pud;
3116 	pmd_t pmd;
3117 
3118 	/*
3119 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3120 	 * is not solely for performance, it's also necessary to avoid the
3121 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
3122 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
3123 	 * page fault steps have already verified the guest isn't writing a
3124 	 * read-only memslot.
3125 	 */
3126 	hva = __gfn_to_hva_memslot(slot, gfn);
3127 
3128 	/*
3129 	 * Disable IRQs to prevent concurrent tear down of host page tables,
3130 	 * e.g. if the primary MMU promotes a P*D to a huge page and then frees
3131 	 * the original page table.
3132 	 */
3133 	local_irq_save(flags);
3134 
3135 	/*
3136 	 * Read each entry once.  As above, a non-leaf entry can be promoted to
3137 	 * a huge page _during_ this walk.  Re-reading the entry could send the
3138 	 * walk into the weeks, e.g. p*d_large() returns false (sees the old
3139 	 * value) and then p*d_offset() walks into the target huge page instead
3140 	 * of the old page table (sees the new value).
3141 	 */
3142 	pgd = READ_ONCE(*pgd_offset(kvm->mm, hva));
3143 	if (pgd_none(pgd))
3144 		goto out;
3145 
3146 	p4d = READ_ONCE(*p4d_offset(&pgd, hva));
3147 	if (p4d_none(p4d) || !p4d_present(p4d))
3148 		goto out;
3149 
3150 	pud = READ_ONCE(*pud_offset(&p4d, hva));
3151 	if (pud_none(pud) || !pud_present(pud))
3152 		goto out;
3153 
3154 	if (pud_large(pud)) {
3155 		level = PG_LEVEL_1G;
3156 		goto out;
3157 	}
3158 
3159 	pmd = READ_ONCE(*pmd_offset(&pud, hva));
3160 	if (pmd_none(pmd) || !pmd_present(pmd))
3161 		goto out;
3162 
3163 	if (pmd_large(pmd))
3164 		level = PG_LEVEL_2M;
3165 
3166 out:
3167 	local_irq_restore(flags);
3168 	return level;
3169 }
3170 
3171 int kvm_mmu_max_mapping_level(struct kvm *kvm,
3172 			      const struct kvm_memory_slot *slot, gfn_t gfn,
3173 			      int max_level)
3174 {
3175 	struct kvm_lpage_info *linfo;
3176 	int host_level;
3177 
3178 	max_level = min(max_level, max_huge_page_level);
3179 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
3180 		linfo = lpage_info_slot(gfn, slot, max_level);
3181 		if (!linfo->disallow_lpage)
3182 			break;
3183 	}
3184 
3185 	if (max_level == PG_LEVEL_4K)
3186 		return PG_LEVEL_4K;
3187 
3188 	host_level = host_pfn_mapping_level(kvm, gfn, slot);
3189 	return min(host_level, max_level);
3190 }
3191 
3192 void kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3193 {
3194 	struct kvm_memory_slot *slot = fault->slot;
3195 	kvm_pfn_t mask;
3196 
3197 	fault->huge_page_disallowed = fault->exec && fault->nx_huge_page_workaround_enabled;
3198 
3199 	if (unlikely(fault->max_level == PG_LEVEL_4K))
3200 		return;
3201 
3202 	if (is_error_noslot_pfn(fault->pfn))
3203 		return;
3204 
3205 	if (kvm_slot_dirty_track_enabled(slot))
3206 		return;
3207 
3208 	/*
3209 	 * Enforce the iTLB multihit workaround after capturing the requested
3210 	 * level, which will be used to do precise, accurate accounting.
3211 	 */
3212 	fault->req_level = kvm_mmu_max_mapping_level(vcpu->kvm, slot,
3213 						     fault->gfn, fault->max_level);
3214 	if (fault->req_level == PG_LEVEL_4K || fault->huge_page_disallowed)
3215 		return;
3216 
3217 	/*
3218 	 * mmu_invalidate_retry() was successful and mmu_lock is held, so
3219 	 * the pmd can't be split from under us.
3220 	 */
3221 	fault->goal_level = fault->req_level;
3222 	mask = KVM_PAGES_PER_HPAGE(fault->goal_level) - 1;
3223 	VM_BUG_ON((fault->gfn & mask) != (fault->pfn & mask));
3224 	fault->pfn &= ~mask;
3225 }
3226 
3227 void disallowed_hugepage_adjust(struct kvm_page_fault *fault, u64 spte, int cur_level)
3228 {
3229 	if (cur_level > PG_LEVEL_4K &&
3230 	    cur_level == fault->goal_level &&
3231 	    is_shadow_present_pte(spte) &&
3232 	    !is_large_pte(spte) &&
3233 	    spte_to_child_sp(spte)->nx_huge_page_disallowed) {
3234 		/*
3235 		 * A small SPTE exists for this pfn, but FNAME(fetch),
3236 		 * direct_map(), or kvm_tdp_mmu_map() would like to create a
3237 		 * large PTE instead: just force them to go down another level,
3238 		 * patching back for them into pfn the next 9 bits of the
3239 		 * address.
3240 		 */
3241 		u64 page_mask = KVM_PAGES_PER_HPAGE(cur_level) -
3242 				KVM_PAGES_PER_HPAGE(cur_level - 1);
3243 		fault->pfn |= fault->gfn & page_mask;
3244 		fault->goal_level--;
3245 	}
3246 }
3247 
3248 static int direct_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3249 {
3250 	struct kvm_shadow_walk_iterator it;
3251 	struct kvm_mmu_page *sp;
3252 	int ret;
3253 	gfn_t base_gfn = fault->gfn;
3254 
3255 	kvm_mmu_hugepage_adjust(vcpu, fault);
3256 
3257 	trace_kvm_mmu_spte_requested(fault);
3258 	for_each_shadow_entry(vcpu, fault->addr, it) {
3259 		/*
3260 		 * We cannot overwrite existing page tables with an NX
3261 		 * large page, as the leaf could be executable.
3262 		 */
3263 		if (fault->nx_huge_page_workaround_enabled)
3264 			disallowed_hugepage_adjust(fault, *it.sptep, it.level);
3265 
3266 		base_gfn = gfn_round_for_level(fault->gfn, it.level);
3267 		if (it.level == fault->goal_level)
3268 			break;
3269 
3270 		sp = kvm_mmu_get_child_sp(vcpu, it.sptep, base_gfn, true, ACC_ALL);
3271 		if (sp == ERR_PTR(-EEXIST))
3272 			continue;
3273 
3274 		link_shadow_page(vcpu, it.sptep, sp);
3275 		if (fault->huge_page_disallowed)
3276 			account_nx_huge_page(vcpu->kvm, sp,
3277 					     fault->req_level >= it.level);
3278 	}
3279 
3280 	if (WARN_ON_ONCE(it.level != fault->goal_level))
3281 		return -EFAULT;
3282 
3283 	ret = mmu_set_spte(vcpu, fault->slot, it.sptep, ACC_ALL,
3284 			   base_gfn, fault->pfn, fault);
3285 	if (ret == RET_PF_SPURIOUS)
3286 		return ret;
3287 
3288 	direct_pte_prefetch(vcpu, it.sptep);
3289 	return ret;
3290 }
3291 
3292 static void kvm_send_hwpoison_signal(struct kvm_memory_slot *slot, gfn_t gfn)
3293 {
3294 	unsigned long hva = gfn_to_hva_memslot(slot, gfn);
3295 
3296 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)hva, PAGE_SHIFT, current);
3297 }
3298 
3299 static int kvm_handle_error_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3300 {
3301 	if (is_sigpending_pfn(fault->pfn)) {
3302 		kvm_handle_signal_exit(vcpu);
3303 		return -EINTR;
3304 	}
3305 
3306 	/*
3307 	 * Do not cache the mmio info caused by writing the readonly gfn
3308 	 * into the spte otherwise read access on readonly gfn also can
3309 	 * caused mmio page fault and treat it as mmio access.
3310 	 */
3311 	if (fault->pfn == KVM_PFN_ERR_RO_FAULT)
3312 		return RET_PF_EMULATE;
3313 
3314 	if (fault->pfn == KVM_PFN_ERR_HWPOISON) {
3315 		kvm_send_hwpoison_signal(fault->slot, fault->gfn);
3316 		return RET_PF_RETRY;
3317 	}
3318 
3319 	return -EFAULT;
3320 }
3321 
3322 static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
3323 				   struct kvm_page_fault *fault,
3324 				   unsigned int access)
3325 {
3326 	gva_t gva = fault->is_tdp ? 0 : fault->addr;
3327 
3328 	vcpu_cache_mmio_info(vcpu, gva, fault->gfn,
3329 			     access & shadow_mmio_access_mask);
3330 
3331 	/*
3332 	 * If MMIO caching is disabled, emulate immediately without
3333 	 * touching the shadow page tables as attempting to install an
3334 	 * MMIO SPTE will just be an expensive nop.
3335 	 */
3336 	if (unlikely(!enable_mmio_caching))
3337 		return RET_PF_EMULATE;
3338 
3339 	/*
3340 	 * Do not create an MMIO SPTE for a gfn greater than host.MAXPHYADDR,
3341 	 * any guest that generates such gfns is running nested and is being
3342 	 * tricked by L0 userspace (you can observe gfn > L1.MAXPHYADDR if and
3343 	 * only if L1's MAXPHYADDR is inaccurate with respect to the
3344 	 * hardware's).
3345 	 */
3346 	if (unlikely(fault->gfn > kvm_mmu_max_gfn()))
3347 		return RET_PF_EMULATE;
3348 
3349 	return RET_PF_CONTINUE;
3350 }
3351 
3352 static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
3353 {
3354 	/*
3355 	 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
3356 	 * reach the common page fault handler if the SPTE has an invalid MMIO
3357 	 * generation number.  Refreshing the MMIO generation needs to go down
3358 	 * the slow path.  Note, EPT Misconfigs do NOT set the PRESENT flag!
3359 	 */
3360 	if (fault->rsvd)
3361 		return false;
3362 
3363 	/*
3364 	 * #PF can be fast if:
3365 	 *
3366 	 * 1. The shadow page table entry is not present and A/D bits are
3367 	 *    disabled _by KVM_, which could mean that the fault is potentially
3368 	 *    caused by access tracking (if enabled).  If A/D bits are enabled
3369 	 *    by KVM, but disabled by L1 for L2, KVM is forced to disable A/D
3370 	 *    bits for L2 and employ access tracking, but the fast page fault
3371 	 *    mechanism only supports direct MMUs.
3372 	 * 2. The shadow page table entry is present, the access is a write,
3373 	 *    and no reserved bits are set (MMIO SPTEs cannot be "fixed"), i.e.
3374 	 *    the fault was caused by a write-protection violation.  If the
3375 	 *    SPTE is MMU-writable (determined later), the fault can be fixed
3376 	 *    by setting the Writable bit, which can be done out of mmu_lock.
3377 	 */
3378 	if (!fault->present)
3379 		return !kvm_ad_enabled();
3380 
3381 	/*
3382 	 * Note, instruction fetches and writes are mutually exclusive, ignore
3383 	 * the "exec" flag.
3384 	 */
3385 	return fault->write;
3386 }
3387 
3388 /*
3389  * Returns true if the SPTE was fixed successfully. Otherwise,
3390  * someone else modified the SPTE from its original value.
3391  */
3392 static bool fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu,
3393 				    struct kvm_page_fault *fault,
3394 				    u64 *sptep, u64 old_spte, u64 new_spte)
3395 {
3396 	/*
3397 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3398 	 * order to eliminate unnecessary PML logging. See comments in
3399 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3400 	 * enabled, so we do not do this. This might result in the same GPA
3401 	 * to be logged in PML buffer again when the write really happens, and
3402 	 * eventually to be called by mark_page_dirty twice. But it's also no
3403 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3404 	 * so non-PML cases won't be impacted.
3405 	 *
3406 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3407 	 */
3408 	if (!try_cmpxchg64(sptep, &old_spte, new_spte))
3409 		return false;
3410 
3411 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte))
3412 		mark_page_dirty_in_slot(vcpu->kvm, fault->slot, fault->gfn);
3413 
3414 	return true;
3415 }
3416 
3417 static bool is_access_allowed(struct kvm_page_fault *fault, u64 spte)
3418 {
3419 	if (fault->exec)
3420 		return is_executable_pte(spte);
3421 
3422 	if (fault->write)
3423 		return is_writable_pte(spte);
3424 
3425 	/* Fault was on Read access */
3426 	return spte & PT_PRESENT_MASK;
3427 }
3428 
3429 /*
3430  * Returns the last level spte pointer of the shadow page walk for the given
3431  * gpa, and sets *spte to the spte value. This spte may be non-preset. If no
3432  * walk could be performed, returns NULL and *spte does not contain valid data.
3433  *
3434  * Contract:
3435  *  - Must be called between walk_shadow_page_lockless_{begin,end}.
3436  *  - The returned sptep must not be used after walk_shadow_page_lockless_end.
3437  */
3438 static u64 *fast_pf_get_last_sptep(struct kvm_vcpu *vcpu, gpa_t gpa, u64 *spte)
3439 {
3440 	struct kvm_shadow_walk_iterator iterator;
3441 	u64 old_spte;
3442 	u64 *sptep = NULL;
3443 
3444 	for_each_shadow_entry_lockless(vcpu, gpa, iterator, old_spte) {
3445 		sptep = iterator.sptep;
3446 		*spte = old_spte;
3447 	}
3448 
3449 	return sptep;
3450 }
3451 
3452 /*
3453  * Returns one of RET_PF_INVALID, RET_PF_FIXED or RET_PF_SPURIOUS.
3454  */
3455 static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
3456 {
3457 	struct kvm_mmu_page *sp;
3458 	int ret = RET_PF_INVALID;
3459 	u64 spte = 0ull;
3460 	u64 *sptep = NULL;
3461 	uint retry_count = 0;
3462 
3463 	if (!page_fault_can_be_fast(fault))
3464 		return ret;
3465 
3466 	walk_shadow_page_lockless_begin(vcpu);
3467 
3468 	do {
3469 		u64 new_spte;
3470 
3471 		if (tdp_mmu_enabled)
3472 			sptep = kvm_tdp_mmu_fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3473 		else
3474 			sptep = fast_pf_get_last_sptep(vcpu, fault->addr, &spte);
3475 
3476 		if (!is_shadow_present_pte(spte))
3477 			break;
3478 
3479 		sp = sptep_to_sp(sptep);
3480 		if (!is_last_spte(spte, sp->role.level))
3481 			break;
3482 
3483 		/*
3484 		 * Check whether the memory access that caused the fault would
3485 		 * still cause it if it were to be performed right now. If not,
3486 		 * then this is a spurious fault caused by TLB lazily flushed,
3487 		 * or some other CPU has already fixed the PTE after the
3488 		 * current CPU took the fault.
3489 		 *
3490 		 * Need not check the access of upper level table entries since
3491 		 * they are always ACC_ALL.
3492 		 */
3493 		if (is_access_allowed(fault, spte)) {
3494 			ret = RET_PF_SPURIOUS;
3495 			break;
3496 		}
3497 
3498 		new_spte = spte;
3499 
3500 		/*
3501 		 * KVM only supports fixing page faults outside of MMU lock for
3502 		 * direct MMUs, nested MMUs are always indirect, and KVM always
3503 		 * uses A/D bits for non-nested MMUs.  Thus, if A/D bits are
3504 		 * enabled, the SPTE can't be an access-tracked SPTE.
3505 		 */
3506 		if (unlikely(!kvm_ad_enabled()) && is_access_track_spte(spte))
3507 			new_spte = restore_acc_track_spte(new_spte);
3508 
3509 		/*
3510 		 * To keep things simple, only SPTEs that are MMU-writable can
3511 		 * be made fully writable outside of mmu_lock, e.g. only SPTEs
3512 		 * that were write-protected for dirty-logging or access
3513 		 * tracking are handled here.  Don't bother checking if the
3514 		 * SPTE is writable to prioritize running with A/D bits enabled.
3515 		 * The is_access_allowed() check above handles the common case
3516 		 * of the fault being spurious, and the SPTE is known to be
3517 		 * shadow-present, i.e. except for access tracking restoration
3518 		 * making the new SPTE writable, the check is wasteful.
3519 		 */
3520 		if (fault->write && is_mmu_writable_spte(spte)) {
3521 			new_spte |= PT_WRITABLE_MASK;
3522 
3523 			/*
3524 			 * Do not fix write-permission on the large spte when
3525 			 * dirty logging is enabled. Since we only dirty the
3526 			 * first page into the dirty-bitmap in
3527 			 * fast_pf_fix_direct_spte(), other pages are missed
3528 			 * if its slot has dirty logging enabled.
3529 			 *
3530 			 * Instead, we let the slow page fault path create a
3531 			 * normal spte to fix the access.
3532 			 */
3533 			if (sp->role.level > PG_LEVEL_4K &&
3534 			    kvm_slot_dirty_track_enabled(fault->slot))
3535 				break;
3536 		}
3537 
3538 		/* Verify that the fault can be handled in the fast path */
3539 		if (new_spte == spte ||
3540 		    !is_access_allowed(fault, new_spte))
3541 			break;
3542 
3543 		/*
3544 		 * Currently, fast page fault only works for direct mapping
3545 		 * since the gfn is not stable for indirect shadow page. See
3546 		 * Documentation/virt/kvm/locking.rst to get more detail.
3547 		 */
3548 		if (fast_pf_fix_direct_spte(vcpu, fault, sptep, spte, new_spte)) {
3549 			ret = RET_PF_FIXED;
3550 			break;
3551 		}
3552 
3553 		if (++retry_count > 4) {
3554 			pr_warn_once("Fast #PF retrying more than 4 times.\n");
3555 			break;
3556 		}
3557 
3558 	} while (true);
3559 
3560 	trace_fast_page_fault(vcpu, fault, sptep, spte, ret);
3561 	walk_shadow_page_lockless_end(vcpu);
3562 
3563 	if (ret != RET_PF_INVALID)
3564 		vcpu->stat.pf_fast++;
3565 
3566 	return ret;
3567 }
3568 
3569 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3570 			       struct list_head *invalid_list)
3571 {
3572 	struct kvm_mmu_page *sp;
3573 
3574 	if (!VALID_PAGE(*root_hpa))
3575 		return;
3576 
3577 	/*
3578 	 * The "root" may be a special root, e.g. a PAE entry, treat it as a
3579 	 * SPTE to ensure any non-PA bits are dropped.
3580 	 */
3581 	sp = spte_to_child_sp(*root_hpa);
3582 	if (WARN_ON(!sp))
3583 		return;
3584 
3585 	if (is_tdp_mmu_page(sp))
3586 		kvm_tdp_mmu_put_root(kvm, sp, false);
3587 	else if (!--sp->root_count && sp->role.invalid)
3588 		kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3589 
3590 	*root_hpa = INVALID_PAGE;
3591 }
3592 
3593 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3594 void kvm_mmu_free_roots(struct kvm *kvm, struct kvm_mmu *mmu,
3595 			ulong roots_to_free)
3596 {
3597 	int i;
3598 	LIST_HEAD(invalid_list);
3599 	bool free_active_root;
3600 
3601 	WARN_ON_ONCE(roots_to_free & ~KVM_MMU_ROOTS_ALL);
3602 
3603 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3604 
3605 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3606 	free_active_root = (roots_to_free & KVM_MMU_ROOT_CURRENT)
3607 		&& VALID_PAGE(mmu->root.hpa);
3608 
3609 	if (!free_active_root) {
3610 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3611 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3612 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3613 				break;
3614 
3615 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3616 			return;
3617 	}
3618 
3619 	write_lock(&kvm->mmu_lock);
3620 
3621 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3622 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3623 			mmu_free_root_page(kvm, &mmu->prev_roots[i].hpa,
3624 					   &invalid_list);
3625 
3626 	if (free_active_root) {
3627 		if (to_shadow_page(mmu->root.hpa)) {
3628 			mmu_free_root_page(kvm, &mmu->root.hpa, &invalid_list);
3629 		} else if (mmu->pae_root) {
3630 			for (i = 0; i < 4; ++i) {
3631 				if (!IS_VALID_PAE_ROOT(mmu->pae_root[i]))
3632 					continue;
3633 
3634 				mmu_free_root_page(kvm, &mmu->pae_root[i],
3635 						   &invalid_list);
3636 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3637 			}
3638 		}
3639 		mmu->root.hpa = INVALID_PAGE;
3640 		mmu->root.pgd = 0;
3641 	}
3642 
3643 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
3644 	write_unlock(&kvm->mmu_lock);
3645 }
3646 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3647 
3648 void kvm_mmu_free_guest_mode_roots(struct kvm *kvm, struct kvm_mmu *mmu)
3649 {
3650 	unsigned long roots_to_free = 0;
3651 	hpa_t root_hpa;
3652 	int i;
3653 
3654 	/*
3655 	 * This should not be called while L2 is active, L2 can't invalidate
3656 	 * _only_ its own roots, e.g. INVVPID unconditionally exits.
3657 	 */
3658 	WARN_ON_ONCE(mmu->root_role.guest_mode);
3659 
3660 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
3661 		root_hpa = mmu->prev_roots[i].hpa;
3662 		if (!VALID_PAGE(root_hpa))
3663 			continue;
3664 
3665 		if (!to_shadow_page(root_hpa) ||
3666 			to_shadow_page(root_hpa)->role.guest_mode)
3667 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
3668 	}
3669 
3670 	kvm_mmu_free_roots(kvm, mmu, roots_to_free);
3671 }
3672 EXPORT_SYMBOL_GPL(kvm_mmu_free_guest_mode_roots);
3673 
3674 
3675 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3676 {
3677 	int ret = 0;
3678 
3679 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3680 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3681 		ret = 1;
3682 	}
3683 
3684 	return ret;
3685 }
3686 
3687 static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, int quadrant,
3688 			    u8 level)
3689 {
3690 	union kvm_mmu_page_role role = vcpu->arch.mmu->root_role;
3691 	struct kvm_mmu_page *sp;
3692 
3693 	role.level = level;
3694 	role.quadrant = quadrant;
3695 
3696 	WARN_ON_ONCE(quadrant && !role.has_4_byte_gpte);
3697 	WARN_ON_ONCE(role.direct && role.has_4_byte_gpte);
3698 
3699 	sp = kvm_mmu_get_shadow_page(vcpu, gfn, role);
3700 	++sp->root_count;
3701 
3702 	return __pa(sp->spt);
3703 }
3704 
3705 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3706 {
3707 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3708 	u8 shadow_root_level = mmu->root_role.level;
3709 	hpa_t root;
3710 	unsigned i;
3711 	int r;
3712 
3713 	write_lock(&vcpu->kvm->mmu_lock);
3714 	r = make_mmu_pages_available(vcpu);
3715 	if (r < 0)
3716 		goto out_unlock;
3717 
3718 	if (tdp_mmu_enabled) {
3719 		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
3720 		mmu->root.hpa = root;
3721 	} else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
3722 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level);
3723 		mmu->root.hpa = root;
3724 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
3725 		if (WARN_ON_ONCE(!mmu->pae_root)) {
3726 			r = -EIO;
3727 			goto out_unlock;
3728 		}
3729 
3730 		for (i = 0; i < 4; ++i) {
3731 			WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3732 
3733 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT), 0,
3734 					      PT32_ROOT_LEVEL);
3735 			mmu->pae_root[i] = root | PT_PRESENT_MASK |
3736 					   shadow_me_value;
3737 		}
3738 		mmu->root.hpa = __pa(mmu->pae_root);
3739 	} else {
3740 		WARN_ONCE(1, "Bad TDP root level = %d\n", shadow_root_level);
3741 		r = -EIO;
3742 		goto out_unlock;
3743 	}
3744 
3745 	/* root.pgd is ignored for direct MMUs. */
3746 	mmu->root.pgd = 0;
3747 out_unlock:
3748 	write_unlock(&vcpu->kvm->mmu_lock);
3749 	return r;
3750 }
3751 
3752 static int mmu_first_shadow_root_alloc(struct kvm *kvm)
3753 {
3754 	struct kvm_memslots *slots;
3755 	struct kvm_memory_slot *slot;
3756 	int r = 0, i, bkt;
3757 
3758 	/*
3759 	 * Check if this is the first shadow root being allocated before
3760 	 * taking the lock.
3761 	 */
3762 	if (kvm_shadow_root_allocated(kvm))
3763 		return 0;
3764 
3765 	mutex_lock(&kvm->slots_arch_lock);
3766 
3767 	/* Recheck, under the lock, whether this is the first shadow root. */
3768 	if (kvm_shadow_root_allocated(kvm))
3769 		goto out_unlock;
3770 
3771 	/*
3772 	 * Check if anything actually needs to be allocated, e.g. all metadata
3773 	 * will be allocated upfront if TDP is disabled.
3774 	 */
3775 	if (kvm_memslots_have_rmaps(kvm) &&
3776 	    kvm_page_track_write_tracking_enabled(kvm))
3777 		goto out_success;
3778 
3779 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
3780 		slots = __kvm_memslots(kvm, i);
3781 		kvm_for_each_memslot(slot, bkt, slots) {
3782 			/*
3783 			 * Both of these functions are no-ops if the target is
3784 			 * already allocated, so unconditionally calling both
3785 			 * is safe.  Intentionally do NOT free allocations on
3786 			 * failure to avoid having to track which allocations
3787 			 * were made now versus when the memslot was created.
3788 			 * The metadata is guaranteed to be freed when the slot
3789 			 * is freed, and will be kept/used if userspace retries
3790 			 * KVM_RUN instead of killing the VM.
3791 			 */
3792 			r = memslot_rmap_alloc(slot, slot->npages);
3793 			if (r)
3794 				goto out_unlock;
3795 			r = kvm_page_track_write_tracking_alloc(slot);
3796 			if (r)
3797 				goto out_unlock;
3798 		}
3799 	}
3800 
3801 	/*
3802 	 * Ensure that shadow_root_allocated becomes true strictly after
3803 	 * all the related pointers are set.
3804 	 */
3805 out_success:
3806 	smp_store_release(&kvm->arch.shadow_root_allocated, true);
3807 
3808 out_unlock:
3809 	mutex_unlock(&kvm->slots_arch_lock);
3810 	return r;
3811 }
3812 
3813 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3814 {
3815 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3816 	u64 pdptrs[4], pm_mask;
3817 	gfn_t root_gfn, root_pgd;
3818 	int quadrant, i, r;
3819 	hpa_t root;
3820 
3821 	root_pgd = kvm_mmu_get_guest_pgd(vcpu, mmu);
3822 	root_gfn = root_pgd >> PAGE_SHIFT;
3823 
3824 	if (mmu_check_root(vcpu, root_gfn))
3825 		return 1;
3826 
3827 	/*
3828 	 * On SVM, reading PDPTRs might access guest memory, which might fault
3829 	 * and thus might sleep.  Grab the PDPTRs before acquiring mmu_lock.
3830 	 */
3831 	if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
3832 		for (i = 0; i < 4; ++i) {
3833 			pdptrs[i] = mmu->get_pdptr(vcpu, i);
3834 			if (!(pdptrs[i] & PT_PRESENT_MASK))
3835 				continue;
3836 
3837 			if (mmu_check_root(vcpu, pdptrs[i] >> PAGE_SHIFT))
3838 				return 1;
3839 		}
3840 	}
3841 
3842 	r = mmu_first_shadow_root_alloc(vcpu->kvm);
3843 	if (r)
3844 		return r;
3845 
3846 	write_lock(&vcpu->kvm->mmu_lock);
3847 	r = make_mmu_pages_available(vcpu);
3848 	if (r < 0)
3849 		goto out_unlock;
3850 
3851 	/*
3852 	 * Do we shadow a long mode page table? If so we need to
3853 	 * write-protect the guests page table root.
3854 	 */
3855 	if (mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
3856 		root = mmu_alloc_root(vcpu, root_gfn, 0,
3857 				      mmu->root_role.level);
3858 		mmu->root.hpa = root;
3859 		goto set_root_pgd;
3860 	}
3861 
3862 	if (WARN_ON_ONCE(!mmu->pae_root)) {
3863 		r = -EIO;
3864 		goto out_unlock;
3865 	}
3866 
3867 	/*
3868 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3869 	 * or a PAE 3-level page table. In either case we need to be aware that
3870 	 * the shadow page table may be a PAE or a long mode page table.
3871 	 */
3872 	pm_mask = PT_PRESENT_MASK | shadow_me_value;
3873 	if (mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3874 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3875 
3876 		if (WARN_ON_ONCE(!mmu->pml4_root)) {
3877 			r = -EIO;
3878 			goto out_unlock;
3879 		}
3880 		mmu->pml4_root[0] = __pa(mmu->pae_root) | pm_mask;
3881 
3882 		if (mmu->root_role.level == PT64_ROOT_5LEVEL) {
3883 			if (WARN_ON_ONCE(!mmu->pml5_root)) {
3884 				r = -EIO;
3885 				goto out_unlock;
3886 			}
3887 			mmu->pml5_root[0] = __pa(mmu->pml4_root) | pm_mask;
3888 		}
3889 	}
3890 
3891 	for (i = 0; i < 4; ++i) {
3892 		WARN_ON_ONCE(IS_VALID_PAE_ROOT(mmu->pae_root[i]));
3893 
3894 		if (mmu->cpu_role.base.level == PT32E_ROOT_LEVEL) {
3895 			if (!(pdptrs[i] & PT_PRESENT_MASK)) {
3896 				mmu->pae_root[i] = INVALID_PAE_ROOT;
3897 				continue;
3898 			}
3899 			root_gfn = pdptrs[i] >> PAGE_SHIFT;
3900 		}
3901 
3902 		/*
3903 		 * If shadowing 32-bit non-PAE page tables, each PAE page
3904 		 * directory maps one quarter of the guest's non-PAE page
3905 		 * directory. Othwerise each PAE page direct shadows one guest
3906 		 * PAE page directory so that quadrant should be 0.
3907 		 */
3908 		quadrant = (mmu->cpu_role.base.level == PT32_ROOT_LEVEL) ? i : 0;
3909 
3910 		root = mmu_alloc_root(vcpu, root_gfn, quadrant, PT32_ROOT_LEVEL);
3911 		mmu->pae_root[i] = root | pm_mask;
3912 	}
3913 
3914 	if (mmu->root_role.level == PT64_ROOT_5LEVEL)
3915 		mmu->root.hpa = __pa(mmu->pml5_root);
3916 	else if (mmu->root_role.level == PT64_ROOT_4LEVEL)
3917 		mmu->root.hpa = __pa(mmu->pml4_root);
3918 	else
3919 		mmu->root.hpa = __pa(mmu->pae_root);
3920 
3921 set_root_pgd:
3922 	mmu->root.pgd = root_pgd;
3923 out_unlock:
3924 	write_unlock(&vcpu->kvm->mmu_lock);
3925 
3926 	return r;
3927 }
3928 
3929 static int mmu_alloc_special_roots(struct kvm_vcpu *vcpu)
3930 {
3931 	struct kvm_mmu *mmu = vcpu->arch.mmu;
3932 	bool need_pml5 = mmu->root_role.level > PT64_ROOT_4LEVEL;
3933 	u64 *pml5_root = NULL;
3934 	u64 *pml4_root = NULL;
3935 	u64 *pae_root;
3936 
3937 	/*
3938 	 * When shadowing 32-bit or PAE NPT with 64-bit NPT, the PML4 and PDP
3939 	 * tables are allocated and initialized at root creation as there is no
3940 	 * equivalent level in the guest's NPT to shadow.  Allocate the tables
3941 	 * on demand, as running a 32-bit L1 VMM on 64-bit KVM is very rare.
3942 	 */
3943 	if (mmu->root_role.direct ||
3944 	    mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL ||
3945 	    mmu->root_role.level < PT64_ROOT_4LEVEL)
3946 		return 0;
3947 
3948 	/*
3949 	 * NPT, the only paging mode that uses this horror, uses a fixed number
3950 	 * of levels for the shadow page tables, e.g. all MMUs are 4-level or
3951 	 * all MMus are 5-level.  Thus, this can safely require that pml5_root
3952 	 * is allocated if the other roots are valid and pml5 is needed, as any
3953 	 * prior MMU would also have required pml5.
3954 	 */
3955 	if (mmu->pae_root && mmu->pml4_root && (!need_pml5 || mmu->pml5_root))
3956 		return 0;
3957 
3958 	/*
3959 	 * The special roots should always be allocated in concert.  Yell and
3960 	 * bail if KVM ends up in a state where only one of the roots is valid.
3961 	 */
3962 	if (WARN_ON_ONCE(!tdp_enabled || mmu->pae_root || mmu->pml4_root ||
3963 			 (need_pml5 && mmu->pml5_root)))
3964 		return -EIO;
3965 
3966 	/*
3967 	 * Unlike 32-bit NPT, the PDP table doesn't need to be in low mem, and
3968 	 * doesn't need to be decrypted.
3969 	 */
3970 	pae_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3971 	if (!pae_root)
3972 		return -ENOMEM;
3973 
3974 #ifdef CONFIG_X86_64
3975 	pml4_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3976 	if (!pml4_root)
3977 		goto err_pml4;
3978 
3979 	if (need_pml5) {
3980 		pml5_root = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3981 		if (!pml5_root)
3982 			goto err_pml5;
3983 	}
3984 #endif
3985 
3986 	mmu->pae_root = pae_root;
3987 	mmu->pml4_root = pml4_root;
3988 	mmu->pml5_root = pml5_root;
3989 
3990 	return 0;
3991 
3992 #ifdef CONFIG_X86_64
3993 err_pml5:
3994 	free_page((unsigned long)pml4_root);
3995 err_pml4:
3996 	free_page((unsigned long)pae_root);
3997 	return -ENOMEM;
3998 #endif
3999 }
4000 
4001 static bool is_unsync_root(hpa_t root)
4002 {
4003 	struct kvm_mmu_page *sp;
4004 
4005 	if (!VALID_PAGE(root))
4006 		return false;
4007 
4008 	/*
4009 	 * The read barrier orders the CPU's read of SPTE.W during the page table
4010 	 * walk before the reads of sp->unsync/sp->unsync_children here.
4011 	 *
4012 	 * Even if another CPU was marking the SP as unsync-ed simultaneously,
4013 	 * any guest page table changes are not guaranteed to be visible anyway
4014 	 * until this VCPU issues a TLB flush strictly after those changes are
4015 	 * made.  We only need to ensure that the other CPU sets these flags
4016 	 * before any actual changes to the page tables are made.  The comments
4017 	 * in mmu_try_to_unsync_pages() describe what could go wrong if this
4018 	 * requirement isn't satisfied.
4019 	 */
4020 	smp_rmb();
4021 	sp = to_shadow_page(root);
4022 
4023 	/*
4024 	 * PAE roots (somewhat arbitrarily) aren't backed by shadow pages, the
4025 	 * PDPTEs for a given PAE root need to be synchronized individually.
4026 	 */
4027 	if (WARN_ON_ONCE(!sp))
4028 		return false;
4029 
4030 	if (sp->unsync || sp->unsync_children)
4031 		return true;
4032 
4033 	return false;
4034 }
4035 
4036 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
4037 {
4038 	int i;
4039 	struct kvm_mmu_page *sp;
4040 
4041 	if (vcpu->arch.mmu->root_role.direct)
4042 		return;
4043 
4044 	if (!VALID_PAGE(vcpu->arch.mmu->root.hpa))
4045 		return;
4046 
4047 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4048 
4049 	if (vcpu->arch.mmu->cpu_role.base.level >= PT64_ROOT_4LEVEL) {
4050 		hpa_t root = vcpu->arch.mmu->root.hpa;
4051 		sp = to_shadow_page(root);
4052 
4053 		if (!is_unsync_root(root))
4054 			return;
4055 
4056 		write_lock(&vcpu->kvm->mmu_lock);
4057 		mmu_sync_children(vcpu, sp, true);
4058 		write_unlock(&vcpu->kvm->mmu_lock);
4059 		return;
4060 	}
4061 
4062 	write_lock(&vcpu->kvm->mmu_lock);
4063 
4064 	for (i = 0; i < 4; ++i) {
4065 		hpa_t root = vcpu->arch.mmu->pae_root[i];
4066 
4067 		if (IS_VALID_PAE_ROOT(root)) {
4068 			sp = spte_to_child_sp(root);
4069 			mmu_sync_children(vcpu, sp, true);
4070 		}
4071 	}
4072 
4073 	write_unlock(&vcpu->kvm->mmu_lock);
4074 }
4075 
4076 void kvm_mmu_sync_prev_roots(struct kvm_vcpu *vcpu)
4077 {
4078 	unsigned long roots_to_free = 0;
4079 	int i;
4080 
4081 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4082 		if (is_unsync_root(vcpu->arch.mmu->prev_roots[i].hpa))
4083 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
4084 
4085 	/* sync prev_roots by simply freeing them */
4086 	kvm_mmu_free_roots(vcpu->kvm, vcpu->arch.mmu, roots_to_free);
4087 }
4088 
4089 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4090 				  gpa_t vaddr, u64 access,
4091 				  struct x86_exception *exception)
4092 {
4093 	if (exception)
4094 		exception->error_code = 0;
4095 	return kvm_translate_gpa(vcpu, mmu, vaddr, access, exception);
4096 }
4097 
4098 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4099 {
4100 	/*
4101 	 * A nested guest cannot use the MMIO cache if it is using nested
4102 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
4103 	 */
4104 	if (mmu_is_nested(vcpu))
4105 		return false;
4106 
4107 	if (direct)
4108 		return vcpu_match_mmio_gpa(vcpu, addr);
4109 
4110 	return vcpu_match_mmio_gva(vcpu, addr);
4111 }
4112 
4113 /*
4114  * Return the level of the lowest level SPTE added to sptes.
4115  * That SPTE may be non-present.
4116  *
4117  * Must be called between walk_shadow_page_lockless_{begin,end}.
4118  */
4119 static int get_walk(struct kvm_vcpu *vcpu, u64 addr, u64 *sptes, int *root_level)
4120 {
4121 	struct kvm_shadow_walk_iterator iterator;
4122 	int leaf = -1;
4123 	u64 spte;
4124 
4125 	for (shadow_walk_init(&iterator, vcpu, addr),
4126 	     *root_level = iterator.level;
4127 	     shadow_walk_okay(&iterator);
4128 	     __shadow_walk_next(&iterator, spte)) {
4129 		leaf = iterator.level;
4130 		spte = mmu_spte_get_lockless(iterator.sptep);
4131 
4132 		sptes[leaf] = spte;
4133 	}
4134 
4135 	return leaf;
4136 }
4137 
4138 /* return true if reserved bit(s) are detected on a valid, non-MMIO SPTE. */
4139 static bool get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
4140 {
4141 	u64 sptes[PT64_ROOT_MAX_LEVEL + 1];
4142 	struct rsvd_bits_validate *rsvd_check;
4143 	int root, leaf, level;
4144 	bool reserved = false;
4145 
4146 	walk_shadow_page_lockless_begin(vcpu);
4147 
4148 	if (is_tdp_mmu_active(vcpu))
4149 		leaf = kvm_tdp_mmu_get_walk(vcpu, addr, sptes, &root);
4150 	else
4151 		leaf = get_walk(vcpu, addr, sptes, &root);
4152 
4153 	walk_shadow_page_lockless_end(vcpu);
4154 
4155 	if (unlikely(leaf < 0)) {
4156 		*sptep = 0ull;
4157 		return reserved;
4158 	}
4159 
4160 	*sptep = sptes[leaf];
4161 
4162 	/*
4163 	 * Skip reserved bits checks on the terminal leaf if it's not a valid
4164 	 * SPTE.  Note, this also (intentionally) skips MMIO SPTEs, which, by
4165 	 * design, always have reserved bits set.  The purpose of the checks is
4166 	 * to detect reserved bits on non-MMIO SPTEs. i.e. buggy SPTEs.
4167 	 */
4168 	if (!is_shadow_present_pte(sptes[leaf]))
4169 		leaf++;
4170 
4171 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
4172 
4173 	for (level = root; level >= leaf; level--)
4174 		reserved |= is_rsvd_spte(rsvd_check, sptes[level], level);
4175 
4176 	if (reserved) {
4177 		pr_err("%s: reserved bits set on MMU-present spte, addr 0x%llx, hierarchy:\n",
4178 		       __func__, addr);
4179 		for (level = root; level >= leaf; level--)
4180 			pr_err("------ spte = 0x%llx level = %d, rsvd bits = 0x%llx",
4181 			       sptes[level], level,
4182 			       get_rsvd_bits(rsvd_check, sptes[level], level));
4183 	}
4184 
4185 	return reserved;
4186 }
4187 
4188 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
4189 {
4190 	u64 spte;
4191 	bool reserved;
4192 
4193 	if (mmio_info_in_cache(vcpu, addr, direct))
4194 		return RET_PF_EMULATE;
4195 
4196 	reserved = get_mmio_spte(vcpu, addr, &spte);
4197 	if (WARN_ON(reserved))
4198 		return -EINVAL;
4199 
4200 	if (is_mmio_spte(spte)) {
4201 		gfn_t gfn = get_mmio_spte_gfn(spte);
4202 		unsigned int access = get_mmio_spte_access(spte);
4203 
4204 		if (!check_mmio_spte(vcpu, spte))
4205 			return RET_PF_INVALID;
4206 
4207 		if (direct)
4208 			addr = 0;
4209 
4210 		trace_handle_mmio_page_fault(addr, gfn, access);
4211 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
4212 		return RET_PF_EMULATE;
4213 	}
4214 
4215 	/*
4216 	 * If the page table is zapped by other cpus, let CPU fault again on
4217 	 * the address.
4218 	 */
4219 	return RET_PF_RETRY;
4220 }
4221 
4222 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4223 					 struct kvm_page_fault *fault)
4224 {
4225 	if (unlikely(fault->rsvd))
4226 		return false;
4227 
4228 	if (!fault->present || !fault->write)
4229 		return false;
4230 
4231 	/*
4232 	 * guest is writing the page which is write tracked which can
4233 	 * not be fixed by page fault handler.
4234 	 */
4235 	if (kvm_slot_page_track_is_active(vcpu->kvm, fault->slot, fault->gfn, KVM_PAGE_TRACK_WRITE))
4236 		return true;
4237 
4238 	return false;
4239 }
4240 
4241 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4242 {
4243 	struct kvm_shadow_walk_iterator iterator;
4244 	u64 spte;
4245 
4246 	walk_shadow_page_lockless_begin(vcpu);
4247 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
4248 		clear_sp_write_flooding_count(iterator.sptep);
4249 	walk_shadow_page_lockless_end(vcpu);
4250 }
4251 
4252 static u32 alloc_apf_token(struct kvm_vcpu *vcpu)
4253 {
4254 	/* make sure the token value is not 0 */
4255 	u32 id = vcpu->arch.apf.id;
4256 
4257 	if (id << 12 == 0)
4258 		vcpu->arch.apf.id = 1;
4259 
4260 	return (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4261 }
4262 
4263 static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4264 				    gfn_t gfn)
4265 {
4266 	struct kvm_arch_async_pf arch;
4267 
4268 	arch.token = alloc_apf_token(vcpu);
4269 	arch.gfn = gfn;
4270 	arch.direct_map = vcpu->arch.mmu->root_role.direct;
4271 	arch.cr3 = kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu);
4272 
4273 	return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4274 				  kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4275 }
4276 
4277 void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
4278 {
4279 	int r;
4280 
4281 	if ((vcpu->arch.mmu->root_role.direct != work->arch.direct_map) ||
4282 	      work->wakeup_all)
4283 		return;
4284 
4285 	r = kvm_mmu_reload(vcpu);
4286 	if (unlikely(r))
4287 		return;
4288 
4289 	if (!vcpu->arch.mmu->root_role.direct &&
4290 	      work->arch.cr3 != kvm_mmu_get_guest_pgd(vcpu, vcpu->arch.mmu))
4291 		return;
4292 
4293 	kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true, NULL);
4294 }
4295 
4296 static int __kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4297 {
4298 	struct kvm_memory_slot *slot = fault->slot;
4299 	bool async;
4300 
4301 	/*
4302 	 * Retry the page fault if the gfn hit a memslot that is being deleted
4303 	 * or moved.  This ensures any existing SPTEs for the old memslot will
4304 	 * be zapped before KVM inserts a new MMIO SPTE for the gfn.
4305 	 */
4306 	if (slot && (slot->flags & KVM_MEMSLOT_INVALID))
4307 		return RET_PF_RETRY;
4308 
4309 	if (!kvm_is_visible_memslot(slot)) {
4310 		/* Don't expose private memslots to L2. */
4311 		if (is_guest_mode(vcpu)) {
4312 			fault->slot = NULL;
4313 			fault->pfn = KVM_PFN_NOSLOT;
4314 			fault->map_writable = false;
4315 			return RET_PF_CONTINUE;
4316 		}
4317 		/*
4318 		 * If the APIC access page exists but is disabled, go directly
4319 		 * to emulation without caching the MMIO access or creating a
4320 		 * MMIO SPTE.  That way the cache doesn't need to be purged
4321 		 * when the AVIC is re-enabled.
4322 		 */
4323 		if (slot && slot->id == APIC_ACCESS_PAGE_PRIVATE_MEMSLOT &&
4324 		    !kvm_apicv_activated(vcpu->kvm))
4325 			return RET_PF_EMULATE;
4326 	}
4327 
4328 	async = false;
4329 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, false, &async,
4330 					  fault->write, &fault->map_writable,
4331 					  &fault->hva);
4332 	if (!async)
4333 		return RET_PF_CONTINUE; /* *pfn has correct page already */
4334 
4335 	if (!fault->prefetch && kvm_can_do_async_pf(vcpu)) {
4336 		trace_kvm_try_async_get_page(fault->addr, fault->gfn);
4337 		if (kvm_find_async_pf_gfn(vcpu, fault->gfn)) {
4338 			trace_kvm_async_pf_repeated_fault(fault->addr, fault->gfn);
4339 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4340 			return RET_PF_RETRY;
4341 		} else if (kvm_arch_setup_async_pf(vcpu, fault->addr, fault->gfn)) {
4342 			return RET_PF_RETRY;
4343 		}
4344 	}
4345 
4346 	/*
4347 	 * Allow gup to bail on pending non-fatal signals when it's also allowed
4348 	 * to wait for IO.  Note, gup always bails if it is unable to quickly
4349 	 * get a page and a fatal signal, i.e. SIGKILL, is pending.
4350 	 */
4351 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, true, NULL,
4352 					  fault->write, &fault->map_writable,
4353 					  &fault->hva);
4354 	return RET_PF_CONTINUE;
4355 }
4356 
4357 static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault,
4358 			   unsigned int access)
4359 {
4360 	int ret;
4361 
4362 	fault->mmu_seq = vcpu->kvm->mmu_invalidate_seq;
4363 	smp_rmb();
4364 
4365 	ret = __kvm_faultin_pfn(vcpu, fault);
4366 	if (ret != RET_PF_CONTINUE)
4367 		return ret;
4368 
4369 	if (unlikely(is_error_pfn(fault->pfn)))
4370 		return kvm_handle_error_pfn(vcpu, fault);
4371 
4372 	if (unlikely(!fault->slot))
4373 		return kvm_handle_noslot_fault(vcpu, fault, access);
4374 
4375 	return RET_PF_CONTINUE;
4376 }
4377 
4378 /*
4379  * Returns true if the page fault is stale and needs to be retried, i.e. if the
4380  * root was invalidated by a memslot update or a relevant mmu_notifier fired.
4381  */
4382 static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
4383 				struct kvm_page_fault *fault)
4384 {
4385 	struct kvm_mmu_page *sp = to_shadow_page(vcpu->arch.mmu->root.hpa);
4386 
4387 	/* Special roots, e.g. pae_root, are not backed by shadow pages. */
4388 	if (sp && is_obsolete_sp(vcpu->kvm, sp))
4389 		return true;
4390 
4391 	/*
4392 	 * Roots without an associated shadow page are considered invalid if
4393 	 * there is a pending request to free obsolete roots.  The request is
4394 	 * only a hint that the current root _may_ be obsolete and needs to be
4395 	 * reloaded, e.g. if the guest frees a PGD that KVM is tracking as a
4396 	 * previous root, then __kvm_mmu_prepare_zap_page() signals all vCPUs
4397 	 * to reload even if no vCPU is actively using the root.
4398 	 */
4399 	if (!sp && kvm_test_request(KVM_REQ_MMU_FREE_OBSOLETE_ROOTS, vcpu))
4400 		return true;
4401 
4402 	return fault->slot &&
4403 	       mmu_invalidate_retry_hva(vcpu->kvm, fault->mmu_seq, fault->hva);
4404 }
4405 
4406 static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4407 {
4408 	int r;
4409 
4410 	if (page_fault_handle_page_track(vcpu, fault))
4411 		return RET_PF_EMULATE;
4412 
4413 	r = fast_page_fault(vcpu, fault);
4414 	if (r != RET_PF_INVALID)
4415 		return r;
4416 
4417 	r = mmu_topup_memory_caches(vcpu, false);
4418 	if (r)
4419 		return r;
4420 
4421 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
4422 	if (r != RET_PF_CONTINUE)
4423 		return r;
4424 
4425 	r = RET_PF_RETRY;
4426 	write_lock(&vcpu->kvm->mmu_lock);
4427 
4428 	if (is_page_fault_stale(vcpu, fault))
4429 		goto out_unlock;
4430 
4431 	r = make_mmu_pages_available(vcpu);
4432 	if (r)
4433 		goto out_unlock;
4434 
4435 	r = direct_map(vcpu, fault);
4436 
4437 out_unlock:
4438 	write_unlock(&vcpu->kvm->mmu_lock);
4439 	kvm_release_pfn_clean(fault->pfn);
4440 	return r;
4441 }
4442 
4443 static int nonpaging_page_fault(struct kvm_vcpu *vcpu,
4444 				struct kvm_page_fault *fault)
4445 {
4446 	pgprintk("%s: gva %lx error %x\n", __func__, fault->addr, fault->error_code);
4447 
4448 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
4449 	fault->max_level = PG_LEVEL_2M;
4450 	return direct_page_fault(vcpu, fault);
4451 }
4452 
4453 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4454 				u64 fault_address, char *insn, int insn_len)
4455 {
4456 	int r = 1;
4457 	u32 flags = vcpu->arch.apf.host_apf_flags;
4458 
4459 #ifndef CONFIG_X86_64
4460 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4461 	if (WARN_ON_ONCE(fault_address >> 32))
4462 		return -EFAULT;
4463 #endif
4464 
4465 	vcpu->arch.l1tf_flush_l1d = true;
4466 	if (!flags) {
4467 		trace_kvm_page_fault(vcpu, fault_address, error_code);
4468 
4469 		if (kvm_event_needs_reinjection(vcpu))
4470 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4471 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4472 				insn_len);
4473 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
4474 		vcpu->arch.apf.host_apf_flags = 0;
4475 		local_irq_disable();
4476 		kvm_async_pf_task_wait_schedule(fault_address);
4477 		local_irq_enable();
4478 	} else {
4479 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4480 	}
4481 
4482 	return r;
4483 }
4484 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4485 
4486 #ifdef CONFIG_X86_64
4487 static int kvm_tdp_mmu_page_fault(struct kvm_vcpu *vcpu,
4488 				  struct kvm_page_fault *fault)
4489 {
4490 	int r;
4491 
4492 	if (page_fault_handle_page_track(vcpu, fault))
4493 		return RET_PF_EMULATE;
4494 
4495 	r = fast_page_fault(vcpu, fault);
4496 	if (r != RET_PF_INVALID)
4497 		return r;
4498 
4499 	r = mmu_topup_memory_caches(vcpu, false);
4500 	if (r)
4501 		return r;
4502 
4503 	r = kvm_faultin_pfn(vcpu, fault, ACC_ALL);
4504 	if (r != RET_PF_CONTINUE)
4505 		return r;
4506 
4507 	r = RET_PF_RETRY;
4508 	read_lock(&vcpu->kvm->mmu_lock);
4509 
4510 	if (is_page_fault_stale(vcpu, fault))
4511 		goto out_unlock;
4512 
4513 	r = kvm_tdp_mmu_map(vcpu, fault);
4514 
4515 out_unlock:
4516 	read_unlock(&vcpu->kvm->mmu_lock);
4517 	kvm_release_pfn_clean(fault->pfn);
4518 	return r;
4519 }
4520 #endif
4521 
4522 int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
4523 {
4524 	/*
4525 	 * If the guest's MTRRs may be used to compute the "real" memtype,
4526 	 * restrict the mapping level to ensure KVM uses a consistent memtype
4527 	 * across the entire mapping.  If the host MTRRs are ignored by TDP
4528 	 * (shadow_memtype_mask is non-zero), and the VM has non-coherent DMA
4529 	 * (DMA doesn't snoop CPU caches), KVM's ABI is to honor the memtype
4530 	 * from the guest's MTRRs so that guest accesses to memory that is
4531 	 * DMA'd aren't cached against the guest's wishes.
4532 	 *
4533 	 * Note, KVM may still ultimately ignore guest MTRRs for certain PFNs,
4534 	 * e.g. KVM will force UC memtype for host MMIO.
4535 	 */
4536 	if (shadow_memtype_mask && kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
4537 		for ( ; fault->max_level > PG_LEVEL_4K; --fault->max_level) {
4538 			int page_num = KVM_PAGES_PER_HPAGE(fault->max_level);
4539 			gfn_t base = gfn_round_for_level(fault->gfn,
4540 							 fault->max_level);
4541 
4542 			if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4543 				break;
4544 		}
4545 	}
4546 
4547 #ifdef CONFIG_X86_64
4548 	if (tdp_mmu_enabled)
4549 		return kvm_tdp_mmu_page_fault(vcpu, fault);
4550 #endif
4551 
4552 	return direct_page_fault(vcpu, fault);
4553 }
4554 
4555 static void nonpaging_init_context(struct kvm_mmu *context)
4556 {
4557 	context->page_fault = nonpaging_page_fault;
4558 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4559 	context->sync_spte = NULL;
4560 }
4561 
4562 static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
4563 				  union kvm_mmu_page_role role)
4564 {
4565 	return (role.direct || pgd == root->pgd) &&
4566 	       VALID_PAGE(root->hpa) &&
4567 	       role.word == to_shadow_page(root->hpa)->role.word;
4568 }
4569 
4570 /*
4571  * Find out if a previously cached root matching the new pgd/role is available,
4572  * and insert the current root as the MRU in the cache.
4573  * If a matching root is found, it is assigned to kvm_mmu->root and
4574  * true is returned.
4575  * If no match is found, kvm_mmu->root is left invalid, the LRU root is
4576  * evicted to make room for the current root, and false is returned.
4577  */
4578 static bool cached_root_find_and_keep_current(struct kvm *kvm, struct kvm_mmu *mmu,
4579 					      gpa_t new_pgd,
4580 					      union kvm_mmu_page_role new_role)
4581 {
4582 	uint i;
4583 
4584 	if (is_root_usable(&mmu->root, new_pgd, new_role))
4585 		return true;
4586 
4587 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4588 		/*
4589 		 * The swaps end up rotating the cache like this:
4590 		 *   C   0 1 2 3   (on entry to the function)
4591 		 *   0   C 1 2 3
4592 		 *   1   C 0 2 3
4593 		 *   2   C 0 1 3
4594 		 *   3   C 0 1 2   (on exit from the loop)
4595 		 */
4596 		swap(mmu->root, mmu->prev_roots[i]);
4597 		if (is_root_usable(&mmu->root, new_pgd, new_role))
4598 			return true;
4599 	}
4600 
4601 	kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4602 	return false;
4603 }
4604 
4605 /*
4606  * Find out if a previously cached root matching the new pgd/role is available.
4607  * On entry, mmu->root is invalid.
4608  * If a matching root is found, it is assigned to kvm_mmu->root, the LRU entry
4609  * of the cache becomes invalid, and true is returned.
4610  * If no match is found, kvm_mmu->root is left invalid and false is returned.
4611  */
4612 static bool cached_root_find_without_current(struct kvm *kvm, struct kvm_mmu *mmu,
4613 					     gpa_t new_pgd,
4614 					     union kvm_mmu_page_role new_role)
4615 {
4616 	uint i;
4617 
4618 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
4619 		if (is_root_usable(&mmu->prev_roots[i], new_pgd, new_role))
4620 			goto hit;
4621 
4622 	return false;
4623 
4624 hit:
4625 	swap(mmu->root, mmu->prev_roots[i]);
4626 	/* Bubble up the remaining roots.  */
4627 	for (; i < KVM_MMU_NUM_PREV_ROOTS - 1; i++)
4628 		mmu->prev_roots[i] = mmu->prev_roots[i + 1];
4629 	mmu->prev_roots[i].hpa = INVALID_PAGE;
4630 	return true;
4631 }
4632 
4633 static bool fast_pgd_switch(struct kvm *kvm, struct kvm_mmu *mmu,
4634 			    gpa_t new_pgd, union kvm_mmu_page_role new_role)
4635 {
4636 	/*
4637 	 * For now, limit the caching to 64-bit hosts+VMs in order to avoid
4638 	 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4639 	 * later if necessary.
4640 	 */
4641 	if (VALID_PAGE(mmu->root.hpa) && !to_shadow_page(mmu->root.hpa))
4642 		kvm_mmu_free_roots(kvm, mmu, KVM_MMU_ROOT_CURRENT);
4643 
4644 	if (VALID_PAGE(mmu->root.hpa))
4645 		return cached_root_find_and_keep_current(kvm, mmu, new_pgd, new_role);
4646 	else
4647 		return cached_root_find_without_current(kvm, mmu, new_pgd, new_role);
4648 }
4649 
4650 void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd)
4651 {
4652 	struct kvm_mmu *mmu = vcpu->arch.mmu;
4653 	union kvm_mmu_page_role new_role = mmu->root_role;
4654 
4655 	/*
4656 	 * Return immediately if no usable root was found, kvm_mmu_reload()
4657 	 * will establish a valid root prior to the next VM-Enter.
4658 	 */
4659 	if (!fast_pgd_switch(vcpu->kvm, mmu, new_pgd, new_role))
4660 		return;
4661 
4662 	/*
4663 	 * It's possible that the cached previous root page is obsolete because
4664 	 * of a change in the MMU generation number. However, changing the
4665 	 * generation number is accompanied by KVM_REQ_MMU_FREE_OBSOLETE_ROOTS,
4666 	 * which will free the root set here and allocate a new one.
4667 	 */
4668 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4669 
4670 	if (force_flush_and_sync_on_reuse) {
4671 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4672 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4673 	}
4674 
4675 	/*
4676 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4677 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
4678 	 * valid. So clear any cached MMIO info even when we don't need to sync
4679 	 * the shadow page tables.
4680 	 */
4681 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4682 
4683 	/*
4684 	 * If this is a direct root page, it doesn't have a write flooding
4685 	 * count. Otherwise, clear the write flooding count.
4686 	 */
4687 	if (!new_role.direct)
4688 		__clear_sp_write_flooding_count(
4689 				to_shadow_page(vcpu->arch.mmu->root.hpa));
4690 }
4691 EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4692 
4693 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4694 			   unsigned int access)
4695 {
4696 	if (unlikely(is_mmio_spte(*sptep))) {
4697 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4698 			mmu_spte_clear_no_track(sptep);
4699 			return true;
4700 		}
4701 
4702 		mark_mmio_spte(vcpu, sptep, gfn, access);
4703 		return true;
4704 	}
4705 
4706 	return false;
4707 }
4708 
4709 #define PTTYPE_EPT 18 /* arbitrary */
4710 #define PTTYPE PTTYPE_EPT
4711 #include "paging_tmpl.h"
4712 #undef PTTYPE
4713 
4714 #define PTTYPE 64
4715 #include "paging_tmpl.h"
4716 #undef PTTYPE
4717 
4718 #define PTTYPE 32
4719 #include "paging_tmpl.h"
4720 #undef PTTYPE
4721 
4722 static void __reset_rsvds_bits_mask(struct rsvd_bits_validate *rsvd_check,
4723 				    u64 pa_bits_rsvd, int level, bool nx,
4724 				    bool gbpages, bool pse, bool amd)
4725 {
4726 	u64 gbpages_bit_rsvd = 0;
4727 	u64 nonleaf_bit8_rsvd = 0;
4728 	u64 high_bits_rsvd;
4729 
4730 	rsvd_check->bad_mt_xwr = 0;
4731 
4732 	if (!gbpages)
4733 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4734 
4735 	if (level == PT32E_ROOT_LEVEL)
4736 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 62);
4737 	else
4738 		high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
4739 
4740 	/* Note, NX doesn't exist in PDPTEs, this is handled below. */
4741 	if (!nx)
4742 		high_bits_rsvd |= rsvd_bits(63, 63);
4743 
4744 	/*
4745 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4746 	 * leaf entries) on AMD CPUs only.
4747 	 */
4748 	if (amd)
4749 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4750 
4751 	switch (level) {
4752 	case PT32_ROOT_LEVEL:
4753 		/* no rsvd bits for 2 level 4K page table entries */
4754 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4755 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4756 		rsvd_check->rsvd_bits_mask[1][0] =
4757 			rsvd_check->rsvd_bits_mask[0][0];
4758 
4759 		if (!pse) {
4760 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4761 			break;
4762 		}
4763 
4764 		if (is_cpuid_PSE36())
4765 			/* 36bits PSE 4MB page */
4766 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4767 		else
4768 			/* 32 bits PSE 4MB page */
4769 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4770 		break;
4771 	case PT32E_ROOT_LEVEL:
4772 		rsvd_check->rsvd_bits_mask[0][2] = rsvd_bits(63, 63) |
4773 						   high_bits_rsvd |
4774 						   rsvd_bits(5, 8) |
4775 						   rsvd_bits(1, 2);	/* PDPTE */
4776 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;	/* PDE */
4777 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;	/* PTE */
4778 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4779 						   rsvd_bits(13, 20);	/* large page */
4780 		rsvd_check->rsvd_bits_mask[1][0] =
4781 			rsvd_check->rsvd_bits_mask[0][0];
4782 		break;
4783 	case PT64_ROOT_5LEVEL:
4784 		rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd |
4785 						   nonleaf_bit8_rsvd |
4786 						   rsvd_bits(7, 7);
4787 		rsvd_check->rsvd_bits_mask[1][4] =
4788 			rsvd_check->rsvd_bits_mask[0][4];
4789 		fallthrough;
4790 	case PT64_ROOT_4LEVEL:
4791 		rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd |
4792 						   nonleaf_bit8_rsvd |
4793 						   rsvd_bits(7, 7);
4794 		rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd |
4795 						   gbpages_bit_rsvd;
4796 		rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd;
4797 		rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4798 		rsvd_check->rsvd_bits_mask[1][3] =
4799 			rsvd_check->rsvd_bits_mask[0][3];
4800 		rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd |
4801 						   gbpages_bit_rsvd |
4802 						   rsvd_bits(13, 29);
4803 		rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd |
4804 						   rsvd_bits(13, 20); /* large page */
4805 		rsvd_check->rsvd_bits_mask[1][0] =
4806 			rsvd_check->rsvd_bits_mask[0][0];
4807 		break;
4808 	}
4809 }
4810 
4811 static bool guest_can_use_gbpages(struct kvm_vcpu *vcpu)
4812 {
4813 	/*
4814 	 * If TDP is enabled, let the guest use GBPAGES if they're supported in
4815 	 * hardware.  The hardware page walker doesn't let KVM disable GBPAGES,
4816 	 * i.e. won't treat them as reserved, and KVM doesn't redo the GVA->GPA
4817 	 * walk for performance and complexity reasons.  Not to mention KVM
4818 	 * _can't_ solve the problem because GVA->GPA walks aren't visible to
4819 	 * KVM once a TDP translation is installed.  Mimic hardware behavior so
4820 	 * that KVM's is at least consistent, i.e. doesn't randomly inject #PF.
4821 	 */
4822 	return tdp_enabled ? boot_cpu_has(X86_FEATURE_GBPAGES) :
4823 			     guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES);
4824 }
4825 
4826 static void reset_guest_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4827 					struct kvm_mmu *context)
4828 {
4829 	__reset_rsvds_bits_mask(&context->guest_rsvd_check,
4830 				vcpu->arch.reserved_gpa_bits,
4831 				context->cpu_role.base.level, is_efer_nx(context),
4832 				guest_can_use_gbpages(vcpu),
4833 				is_cr4_pse(context),
4834 				guest_cpuid_is_amd_or_hygon(vcpu));
4835 }
4836 
4837 static void __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4838 					u64 pa_bits_rsvd, bool execonly,
4839 					int huge_page_level)
4840 {
4841 	u64 high_bits_rsvd = pa_bits_rsvd & rsvd_bits(0, 51);
4842 	u64 large_1g_rsvd = 0, large_2m_rsvd = 0;
4843 	u64 bad_mt_xwr;
4844 
4845 	if (huge_page_level < PG_LEVEL_1G)
4846 		large_1g_rsvd = rsvd_bits(7, 7);
4847 	if (huge_page_level < PG_LEVEL_2M)
4848 		large_2m_rsvd = rsvd_bits(7, 7);
4849 
4850 	rsvd_check->rsvd_bits_mask[0][4] = high_bits_rsvd | rsvd_bits(3, 7);
4851 	rsvd_check->rsvd_bits_mask[0][3] = high_bits_rsvd | rsvd_bits(3, 7);
4852 	rsvd_check->rsvd_bits_mask[0][2] = high_bits_rsvd | rsvd_bits(3, 6) | large_1g_rsvd;
4853 	rsvd_check->rsvd_bits_mask[0][1] = high_bits_rsvd | rsvd_bits(3, 6) | large_2m_rsvd;
4854 	rsvd_check->rsvd_bits_mask[0][0] = high_bits_rsvd;
4855 
4856 	/* large page */
4857 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4858 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4859 	rsvd_check->rsvd_bits_mask[1][2] = high_bits_rsvd | rsvd_bits(12, 29) | large_1g_rsvd;
4860 	rsvd_check->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(12, 20) | large_2m_rsvd;
4861 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4862 
4863 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
4864 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
4865 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
4866 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
4867 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
4868 	if (!execonly) {
4869 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
4870 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4871 	}
4872 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
4873 }
4874 
4875 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4876 		struct kvm_mmu *context, bool execonly, int huge_page_level)
4877 {
4878 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4879 				    vcpu->arch.reserved_gpa_bits, execonly,
4880 				    huge_page_level);
4881 }
4882 
4883 static inline u64 reserved_hpa_bits(void)
4884 {
4885 	return rsvd_bits(shadow_phys_bits, 63);
4886 }
4887 
4888 /*
4889  * the page table on host is the shadow page table for the page
4890  * table in guest or amd nested guest, its mmu features completely
4891  * follow the features in guest.
4892  */
4893 static void reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4894 					struct kvm_mmu *context)
4895 {
4896 	/* @amd adds a check on bit of SPTEs, which KVM shouldn't use anyways. */
4897 	bool is_amd = true;
4898 	/* KVM doesn't use 2-level page tables for the shadow MMU. */
4899 	bool is_pse = false;
4900 	struct rsvd_bits_validate *shadow_zero_check;
4901 	int i;
4902 
4903 	WARN_ON_ONCE(context->root_role.level < PT32E_ROOT_LEVEL);
4904 
4905 	shadow_zero_check = &context->shadow_zero_check;
4906 	__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4907 				context->root_role.level,
4908 				context->root_role.efer_nx,
4909 				guest_can_use_gbpages(vcpu), is_pse, is_amd);
4910 
4911 	if (!shadow_me_mask)
4912 		return;
4913 
4914 	for (i = context->root_role.level; --i >= 0;) {
4915 		/*
4916 		 * So far shadow_me_value is a constant during KVM's life
4917 		 * time.  Bits in shadow_me_value are allowed to be set.
4918 		 * Bits in shadow_me_mask but not in shadow_me_value are
4919 		 * not allowed to be set.
4920 		 */
4921 		shadow_zero_check->rsvd_bits_mask[0][i] |= shadow_me_mask;
4922 		shadow_zero_check->rsvd_bits_mask[1][i] |= shadow_me_mask;
4923 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_value;
4924 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_value;
4925 	}
4926 
4927 }
4928 
4929 static inline bool boot_cpu_is_amd(void)
4930 {
4931 	WARN_ON_ONCE(!tdp_enabled);
4932 	return shadow_x_mask == 0;
4933 }
4934 
4935 /*
4936  * the direct page table on host, use as much mmu features as
4937  * possible, however, kvm currently does not do execution-protection.
4938  */
4939 static void reset_tdp_shadow_zero_bits_mask(struct kvm_mmu *context)
4940 {
4941 	struct rsvd_bits_validate *shadow_zero_check;
4942 	int i;
4943 
4944 	shadow_zero_check = &context->shadow_zero_check;
4945 
4946 	if (boot_cpu_is_amd())
4947 		__reset_rsvds_bits_mask(shadow_zero_check, reserved_hpa_bits(),
4948 					context->root_role.level, true,
4949 					boot_cpu_has(X86_FEATURE_GBPAGES),
4950 					false, true);
4951 	else
4952 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
4953 					    reserved_hpa_bits(), false,
4954 					    max_huge_page_level);
4955 
4956 	if (!shadow_me_mask)
4957 		return;
4958 
4959 	for (i = context->root_role.level; --i >= 0;) {
4960 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4961 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4962 	}
4963 }
4964 
4965 /*
4966  * as the comments in reset_shadow_zero_bits_mask() except it
4967  * is the shadow page table for intel nested guest.
4968  */
4969 static void
4970 reset_ept_shadow_zero_bits_mask(struct kvm_mmu *context, bool execonly)
4971 {
4972 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4973 				    reserved_hpa_bits(), execonly,
4974 				    max_huge_page_level);
4975 }
4976 
4977 #define BYTE_MASK(access) \
4978 	((1 & (access) ? 2 : 0) | \
4979 	 (2 & (access) ? 4 : 0) | \
4980 	 (3 & (access) ? 8 : 0) | \
4981 	 (4 & (access) ? 16 : 0) | \
4982 	 (5 & (access) ? 32 : 0) | \
4983 	 (6 & (access) ? 64 : 0) | \
4984 	 (7 & (access) ? 128 : 0))
4985 
4986 
4987 static void update_permission_bitmask(struct kvm_mmu *mmu, bool ept)
4988 {
4989 	unsigned byte;
4990 
4991 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4992 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4993 	const u8 u = BYTE_MASK(ACC_USER_MASK);
4994 
4995 	bool cr4_smep = is_cr4_smep(mmu);
4996 	bool cr4_smap = is_cr4_smap(mmu);
4997 	bool cr0_wp = is_cr0_wp(mmu);
4998 	bool efer_nx = is_efer_nx(mmu);
4999 
5000 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
5001 		unsigned pfec = byte << 1;
5002 
5003 		/*
5004 		 * Each "*f" variable has a 1 bit for each UWX value
5005 		 * that causes a fault with the given PFEC.
5006 		 */
5007 
5008 		/* Faults from writes to non-writable pages */
5009 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
5010 		/* Faults from user mode accesses to supervisor pages */
5011 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
5012 		/* Faults from fetches of non-executable pages*/
5013 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
5014 		/* Faults from kernel mode fetches of user pages */
5015 		u8 smepf = 0;
5016 		/* Faults from kernel mode accesses of user pages */
5017 		u8 smapf = 0;
5018 
5019 		if (!ept) {
5020 			/* Faults from kernel mode accesses to user pages */
5021 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
5022 
5023 			/* Not really needed: !nx will cause pte.nx to fault */
5024 			if (!efer_nx)
5025 				ff = 0;
5026 
5027 			/* Allow supervisor writes if !cr0.wp */
5028 			if (!cr0_wp)
5029 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
5030 
5031 			/* Disallow supervisor fetches of user code if cr4.smep */
5032 			if (cr4_smep)
5033 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
5034 
5035 			/*
5036 			 * SMAP:kernel-mode data accesses from user-mode
5037 			 * mappings should fault. A fault is considered
5038 			 * as a SMAP violation if all of the following
5039 			 * conditions are true:
5040 			 *   - X86_CR4_SMAP is set in CR4
5041 			 *   - A user page is accessed
5042 			 *   - The access is not a fetch
5043 			 *   - The access is supervisor mode
5044 			 *   - If implicit supervisor access or X86_EFLAGS_AC is clear
5045 			 *
5046 			 * Here, we cover the first four conditions.
5047 			 * The fifth is computed dynamically in permission_fault();
5048 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
5049 			 * *not* subject to SMAP restrictions.
5050 			 */
5051 			if (cr4_smap)
5052 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
5053 		}
5054 
5055 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
5056 	}
5057 }
5058 
5059 /*
5060 * PKU is an additional mechanism by which the paging controls access to
5061 * user-mode addresses based on the value in the PKRU register.  Protection
5062 * key violations are reported through a bit in the page fault error code.
5063 * Unlike other bits of the error code, the PK bit is not known at the
5064 * call site of e.g. gva_to_gpa; it must be computed directly in
5065 * permission_fault based on two bits of PKRU, on some machine state (CR4,
5066 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
5067 *
5068 * In particular the following conditions come from the error code, the
5069 * page tables and the machine state:
5070 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
5071 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
5072 * - PK is always zero if U=0 in the page tables
5073 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
5074 *
5075 * The PKRU bitmask caches the result of these four conditions.  The error
5076 * code (minus the P bit) and the page table's U bit form an index into the
5077 * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
5078 * with the two bits of the PKRU register corresponding to the protection key.
5079 * For the first three conditions above the bits will be 00, thus masking
5080 * away both AD and WD.  For all reads or if the last condition holds, WD
5081 * only will be masked away.
5082 */
5083 static void update_pkru_bitmask(struct kvm_mmu *mmu)
5084 {
5085 	unsigned bit;
5086 	bool wp;
5087 
5088 	mmu->pkru_mask = 0;
5089 
5090 	if (!is_cr4_pke(mmu))
5091 		return;
5092 
5093 	wp = is_cr0_wp(mmu);
5094 
5095 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
5096 		unsigned pfec, pkey_bits;
5097 		bool check_pkey, check_write, ff, uf, wf, pte_user;
5098 
5099 		pfec = bit << 1;
5100 		ff = pfec & PFERR_FETCH_MASK;
5101 		uf = pfec & PFERR_USER_MASK;
5102 		wf = pfec & PFERR_WRITE_MASK;
5103 
5104 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
5105 		pte_user = pfec & PFERR_RSVD_MASK;
5106 
5107 		/*
5108 		 * Only need to check the access which is not an
5109 		 * instruction fetch and is to a user page.
5110 		 */
5111 		check_pkey = (!ff && pte_user);
5112 		/*
5113 		 * write access is controlled by PKRU if it is a
5114 		 * user access or CR0.WP = 1.
5115 		 */
5116 		check_write = check_pkey && wf && (uf || wp);
5117 
5118 		/* PKRU.AD stops both read and write access. */
5119 		pkey_bits = !!check_pkey;
5120 		/* PKRU.WD stops write access. */
5121 		pkey_bits |= (!!check_write) << 1;
5122 
5123 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
5124 	}
5125 }
5126 
5127 static void reset_guest_paging_metadata(struct kvm_vcpu *vcpu,
5128 					struct kvm_mmu *mmu)
5129 {
5130 	if (!is_cr0_pg(mmu))
5131 		return;
5132 
5133 	reset_guest_rsvds_bits_mask(vcpu, mmu);
5134 	update_permission_bitmask(mmu, false);
5135 	update_pkru_bitmask(mmu);
5136 }
5137 
5138 static void paging64_init_context(struct kvm_mmu *context)
5139 {
5140 	context->page_fault = paging64_page_fault;
5141 	context->gva_to_gpa = paging64_gva_to_gpa;
5142 	context->sync_spte = paging64_sync_spte;
5143 }
5144 
5145 static void paging32_init_context(struct kvm_mmu *context)
5146 {
5147 	context->page_fault = paging32_page_fault;
5148 	context->gva_to_gpa = paging32_gva_to_gpa;
5149 	context->sync_spte = paging32_sync_spte;
5150 }
5151 
5152 static union kvm_cpu_role kvm_calc_cpu_role(struct kvm_vcpu *vcpu,
5153 					    const struct kvm_mmu_role_regs *regs)
5154 {
5155 	union kvm_cpu_role role = {0};
5156 
5157 	role.base.access = ACC_ALL;
5158 	role.base.smm = is_smm(vcpu);
5159 	role.base.guest_mode = is_guest_mode(vcpu);
5160 	role.ext.valid = 1;
5161 
5162 	if (!____is_cr0_pg(regs)) {
5163 		role.base.direct = 1;
5164 		return role;
5165 	}
5166 
5167 	role.base.efer_nx = ____is_efer_nx(regs);
5168 	role.base.cr0_wp = ____is_cr0_wp(regs);
5169 	role.base.smep_andnot_wp = ____is_cr4_smep(regs) && !____is_cr0_wp(regs);
5170 	role.base.smap_andnot_wp = ____is_cr4_smap(regs) && !____is_cr0_wp(regs);
5171 	role.base.has_4_byte_gpte = !____is_cr4_pae(regs);
5172 
5173 	if (____is_efer_lma(regs))
5174 		role.base.level = ____is_cr4_la57(regs) ? PT64_ROOT_5LEVEL
5175 							: PT64_ROOT_4LEVEL;
5176 	else if (____is_cr4_pae(regs))
5177 		role.base.level = PT32E_ROOT_LEVEL;
5178 	else
5179 		role.base.level = PT32_ROOT_LEVEL;
5180 
5181 	role.ext.cr4_smep = ____is_cr4_smep(regs);
5182 	role.ext.cr4_smap = ____is_cr4_smap(regs);
5183 	role.ext.cr4_pse = ____is_cr4_pse(regs);
5184 
5185 	/* PKEY and LA57 are active iff long mode is active. */
5186 	role.ext.cr4_pke = ____is_efer_lma(regs) && ____is_cr4_pke(regs);
5187 	role.ext.cr4_la57 = ____is_efer_lma(regs) && ____is_cr4_la57(regs);
5188 	role.ext.efer_lma = ____is_efer_lma(regs);
5189 	return role;
5190 }
5191 
5192 void __kvm_mmu_refresh_passthrough_bits(struct kvm_vcpu *vcpu,
5193 					struct kvm_mmu *mmu)
5194 {
5195 	const bool cr0_wp = kvm_is_cr0_bit_set(vcpu, X86_CR0_WP);
5196 
5197 	BUILD_BUG_ON((KVM_MMU_CR0_ROLE_BITS & KVM_POSSIBLE_CR0_GUEST_BITS) != X86_CR0_WP);
5198 	BUILD_BUG_ON((KVM_MMU_CR4_ROLE_BITS & KVM_POSSIBLE_CR4_GUEST_BITS));
5199 
5200 	if (is_cr0_wp(mmu) == cr0_wp)
5201 		return;
5202 
5203 	mmu->cpu_role.base.cr0_wp = cr0_wp;
5204 	reset_guest_paging_metadata(vcpu, mmu);
5205 }
5206 
5207 static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
5208 {
5209 	/* tdp_root_level is architecture forced level, use it if nonzero */
5210 	if (tdp_root_level)
5211 		return tdp_root_level;
5212 
5213 	/* Use 5-level TDP if and only if it's useful/necessary. */
5214 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
5215 		return 4;
5216 
5217 	return max_tdp_level;
5218 }
5219 
5220 static union kvm_mmu_page_role
5221 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu,
5222 				union kvm_cpu_role cpu_role)
5223 {
5224 	union kvm_mmu_page_role role = {0};
5225 
5226 	role.access = ACC_ALL;
5227 	role.cr0_wp = true;
5228 	role.efer_nx = true;
5229 	role.smm = cpu_role.base.smm;
5230 	role.guest_mode = cpu_role.base.guest_mode;
5231 	role.ad_disabled = !kvm_ad_enabled();
5232 	role.level = kvm_mmu_get_tdp_level(vcpu);
5233 	role.direct = true;
5234 	role.has_4_byte_gpte = false;
5235 
5236 	return role;
5237 }
5238 
5239 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu,
5240 			     union kvm_cpu_role cpu_role)
5241 {
5242 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5243 	union kvm_mmu_page_role root_role = kvm_calc_tdp_mmu_root_page_role(vcpu, cpu_role);
5244 
5245 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5246 	    root_role.word == context->root_role.word)
5247 		return;
5248 
5249 	context->cpu_role.as_u64 = cpu_role.as_u64;
5250 	context->root_role.word = root_role.word;
5251 	context->page_fault = kvm_tdp_page_fault;
5252 	context->sync_spte = NULL;
5253 	context->get_guest_pgd = get_guest_cr3;
5254 	context->get_pdptr = kvm_pdptr_read;
5255 	context->inject_page_fault = kvm_inject_page_fault;
5256 
5257 	if (!is_cr0_pg(context))
5258 		context->gva_to_gpa = nonpaging_gva_to_gpa;
5259 	else if (is_cr4_pae(context))
5260 		context->gva_to_gpa = paging64_gva_to_gpa;
5261 	else
5262 		context->gva_to_gpa = paging32_gva_to_gpa;
5263 
5264 	reset_guest_paging_metadata(vcpu, context);
5265 	reset_tdp_shadow_zero_bits_mask(context);
5266 }
5267 
5268 static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
5269 				    union kvm_cpu_role cpu_role,
5270 				    union kvm_mmu_page_role root_role)
5271 {
5272 	if (cpu_role.as_u64 == context->cpu_role.as_u64 &&
5273 	    root_role.word == context->root_role.word)
5274 		return;
5275 
5276 	context->cpu_role.as_u64 = cpu_role.as_u64;
5277 	context->root_role.word = root_role.word;
5278 
5279 	if (!is_cr0_pg(context))
5280 		nonpaging_init_context(context);
5281 	else if (is_cr4_pae(context))
5282 		paging64_init_context(context);
5283 	else
5284 		paging32_init_context(context);
5285 
5286 	reset_guest_paging_metadata(vcpu, context);
5287 	reset_shadow_zero_bits_mask(vcpu, context);
5288 }
5289 
5290 static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu,
5291 				union kvm_cpu_role cpu_role)
5292 {
5293 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5294 	union kvm_mmu_page_role root_role;
5295 
5296 	root_role = cpu_role.base;
5297 
5298 	/* KVM uses PAE paging whenever the guest isn't using 64-bit paging. */
5299 	root_role.level = max_t(u32, root_role.level, PT32E_ROOT_LEVEL);
5300 
5301 	/*
5302 	 * KVM forces EFER.NX=1 when TDP is disabled, reflect it in the MMU role.
5303 	 * KVM uses NX when TDP is disabled to handle a variety of scenarios,
5304 	 * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
5305 	 * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
5306 	 * The iTLB multi-hit workaround can be toggled at any time, so assume
5307 	 * NX can be used by any non-nested shadow MMU to avoid having to reset
5308 	 * MMU contexts.
5309 	 */
5310 	root_role.efer_nx = true;
5311 
5312 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5313 }
5314 
5315 void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, unsigned long cr0,
5316 			     unsigned long cr4, u64 efer, gpa_t nested_cr3)
5317 {
5318 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5319 	struct kvm_mmu_role_regs regs = {
5320 		.cr0 = cr0,
5321 		.cr4 = cr4 & ~X86_CR4_PKE,
5322 		.efer = efer,
5323 	};
5324 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
5325 	union kvm_mmu_page_role root_role;
5326 
5327 	/* NPT requires CR0.PG=1. */
5328 	WARN_ON_ONCE(cpu_role.base.direct);
5329 
5330 	root_role = cpu_role.base;
5331 	root_role.level = kvm_mmu_get_tdp_level(vcpu);
5332 	if (root_role.level == PT64_ROOT_5LEVEL &&
5333 	    cpu_role.base.level == PT64_ROOT_4LEVEL)
5334 		root_role.passthrough = 1;
5335 
5336 	shadow_mmu_init_context(vcpu, context, cpu_role, root_role);
5337 	kvm_mmu_new_pgd(vcpu, nested_cr3);
5338 }
5339 EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5340 
5341 static union kvm_cpu_role
5342 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5343 				   bool execonly, u8 level)
5344 {
5345 	union kvm_cpu_role role = {0};
5346 
5347 	/*
5348 	 * KVM does not support SMM transfer monitors, and consequently does not
5349 	 * support the "entry to SMM" control either.  role.base.smm is always 0.
5350 	 */
5351 	WARN_ON_ONCE(is_smm(vcpu));
5352 	role.base.level = level;
5353 	role.base.has_4_byte_gpte = false;
5354 	role.base.direct = false;
5355 	role.base.ad_disabled = !accessed_dirty;
5356 	role.base.guest_mode = true;
5357 	role.base.access = ACC_ALL;
5358 
5359 	role.ext.word = 0;
5360 	role.ext.execonly = execonly;
5361 	role.ext.valid = 1;
5362 
5363 	return role;
5364 }
5365 
5366 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5367 			     int huge_page_level, bool accessed_dirty,
5368 			     gpa_t new_eptp)
5369 {
5370 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5371 	u8 level = vmx_eptp_page_walk_level(new_eptp);
5372 	union kvm_cpu_role new_mode =
5373 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5374 						   execonly, level);
5375 
5376 	if (new_mode.as_u64 != context->cpu_role.as_u64) {
5377 		/* EPT, and thus nested EPT, does not consume CR0, CR4, nor EFER. */
5378 		context->cpu_role.as_u64 = new_mode.as_u64;
5379 		context->root_role.word = new_mode.base.word;
5380 
5381 		context->page_fault = ept_page_fault;
5382 		context->gva_to_gpa = ept_gva_to_gpa;
5383 		context->sync_spte = ept_sync_spte;
5384 
5385 		update_permission_bitmask(context, true);
5386 		context->pkru_mask = 0;
5387 		reset_rsvds_bits_mask_ept(vcpu, context, execonly, huge_page_level);
5388 		reset_ept_shadow_zero_bits_mask(context, execonly);
5389 	}
5390 
5391 	kvm_mmu_new_pgd(vcpu, new_eptp);
5392 }
5393 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5394 
5395 static void init_kvm_softmmu(struct kvm_vcpu *vcpu,
5396 			     union kvm_cpu_role cpu_role)
5397 {
5398 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5399 
5400 	kvm_init_shadow_mmu(vcpu, cpu_role);
5401 
5402 	context->get_guest_pgd     = get_guest_cr3;
5403 	context->get_pdptr         = kvm_pdptr_read;
5404 	context->inject_page_fault = kvm_inject_page_fault;
5405 }
5406 
5407 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu,
5408 				union kvm_cpu_role new_mode)
5409 {
5410 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5411 
5412 	if (new_mode.as_u64 == g_context->cpu_role.as_u64)
5413 		return;
5414 
5415 	g_context->cpu_role.as_u64   = new_mode.as_u64;
5416 	g_context->get_guest_pgd     = get_guest_cr3;
5417 	g_context->get_pdptr         = kvm_pdptr_read;
5418 	g_context->inject_page_fault = kvm_inject_page_fault;
5419 
5420 	/*
5421 	 * L2 page tables are never shadowed, so there is no need to sync
5422 	 * SPTEs.
5423 	 */
5424 	g_context->sync_spte         = NULL;
5425 
5426 	/*
5427 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5428 	 * L1's nested page tables (e.g. EPT12). The nested translation
5429 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5430 	 * L2's page tables as the first level of translation and L1's
5431 	 * nested page tables as the second level of translation. Basically
5432 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5433 	 */
5434 	if (!is_paging(vcpu))
5435 		g_context->gva_to_gpa = nonpaging_gva_to_gpa;
5436 	else if (is_long_mode(vcpu))
5437 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5438 	else if (is_pae(vcpu))
5439 		g_context->gva_to_gpa = paging64_gva_to_gpa;
5440 	else
5441 		g_context->gva_to_gpa = paging32_gva_to_gpa;
5442 
5443 	reset_guest_paging_metadata(vcpu, g_context);
5444 }
5445 
5446 void kvm_init_mmu(struct kvm_vcpu *vcpu)
5447 {
5448 	struct kvm_mmu_role_regs regs = vcpu_to_role_regs(vcpu);
5449 	union kvm_cpu_role cpu_role = kvm_calc_cpu_role(vcpu, &regs);
5450 
5451 	if (mmu_is_nested(vcpu))
5452 		init_kvm_nested_mmu(vcpu, cpu_role);
5453 	else if (tdp_enabled)
5454 		init_kvm_tdp_mmu(vcpu, cpu_role);
5455 	else
5456 		init_kvm_softmmu(vcpu, cpu_role);
5457 }
5458 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5459 
5460 void kvm_mmu_after_set_cpuid(struct kvm_vcpu *vcpu)
5461 {
5462 	/*
5463 	 * Invalidate all MMU roles to force them to reinitialize as CPUID
5464 	 * information is factored into reserved bit calculations.
5465 	 *
5466 	 * Correctly handling multiple vCPU models with respect to paging and
5467 	 * physical address properties) in a single VM would require tracking
5468 	 * all relevant CPUID information in kvm_mmu_page_role. That is very
5469 	 * undesirable as it would increase the memory requirements for
5470 	 * gfn_track (see struct kvm_mmu_page_role comments).  For now that
5471 	 * problem is swept under the rug; KVM's CPUID API is horrific and
5472 	 * it's all but impossible to solve it without introducing a new API.
5473 	 */
5474 	vcpu->arch.root_mmu.root_role.word = 0;
5475 	vcpu->arch.guest_mmu.root_role.word = 0;
5476 	vcpu->arch.nested_mmu.root_role.word = 0;
5477 	vcpu->arch.root_mmu.cpu_role.ext.valid = 0;
5478 	vcpu->arch.guest_mmu.cpu_role.ext.valid = 0;
5479 	vcpu->arch.nested_mmu.cpu_role.ext.valid = 0;
5480 	kvm_mmu_reset_context(vcpu);
5481 
5482 	/*
5483 	 * Changing guest CPUID after KVM_RUN is forbidden, see the comment in
5484 	 * kvm_arch_vcpu_ioctl().
5485 	 */
5486 	KVM_BUG_ON(kvm_vcpu_has_run(vcpu), vcpu->kvm);
5487 }
5488 
5489 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5490 {
5491 	kvm_mmu_unload(vcpu);
5492 	kvm_init_mmu(vcpu);
5493 }
5494 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5495 
5496 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5497 {
5498 	int r;
5499 
5500 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->root_role.direct);
5501 	if (r)
5502 		goto out;
5503 	r = mmu_alloc_special_roots(vcpu);
5504 	if (r)
5505 		goto out;
5506 	if (vcpu->arch.mmu->root_role.direct)
5507 		r = mmu_alloc_direct_roots(vcpu);
5508 	else
5509 		r = mmu_alloc_shadow_roots(vcpu);
5510 	if (r)
5511 		goto out;
5512 
5513 	kvm_mmu_sync_roots(vcpu);
5514 
5515 	kvm_mmu_load_pgd(vcpu);
5516 
5517 	/*
5518 	 * Flush any TLB entries for the new root, the provenance of the root
5519 	 * is unknown.  Even if KVM ensures there are no stale TLB entries
5520 	 * for a freed root, in theory another hypervisor could have left
5521 	 * stale entries.  Flushing on alloc also allows KVM to skip the TLB
5522 	 * flush when freeing a root (see kvm_tdp_mmu_put_root()).
5523 	 */
5524 	static_call(kvm_x86_flush_tlb_current)(vcpu);
5525 out:
5526 	return r;
5527 }
5528 
5529 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5530 {
5531 	struct kvm *kvm = vcpu->kvm;
5532 
5533 	kvm_mmu_free_roots(kvm, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5534 	WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root.hpa));
5535 	kvm_mmu_free_roots(kvm, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5536 	WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root.hpa));
5537 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
5538 }
5539 
5540 static bool is_obsolete_root(struct kvm *kvm, hpa_t root_hpa)
5541 {
5542 	struct kvm_mmu_page *sp;
5543 
5544 	if (!VALID_PAGE(root_hpa))
5545 		return false;
5546 
5547 	/*
5548 	 * When freeing obsolete roots, treat roots as obsolete if they don't
5549 	 * have an associated shadow page.  This does mean KVM will get false
5550 	 * positives and free roots that don't strictly need to be freed, but
5551 	 * such false positives are relatively rare:
5552 	 *
5553 	 *  (a) only PAE paging and nested NPT has roots without shadow pages
5554 	 *  (b) remote reloads due to a memslot update obsoletes _all_ roots
5555 	 *  (c) KVM doesn't track previous roots for PAE paging, and the guest
5556 	 *      is unlikely to zap an in-use PGD.
5557 	 */
5558 	sp = to_shadow_page(root_hpa);
5559 	return !sp || is_obsolete_sp(kvm, sp);
5560 }
5561 
5562 static void __kvm_mmu_free_obsolete_roots(struct kvm *kvm, struct kvm_mmu *mmu)
5563 {
5564 	unsigned long roots_to_free = 0;
5565 	int i;
5566 
5567 	if (is_obsolete_root(kvm, mmu->root.hpa))
5568 		roots_to_free |= KVM_MMU_ROOT_CURRENT;
5569 
5570 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5571 		if (is_obsolete_root(kvm, mmu->prev_roots[i].hpa))
5572 			roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
5573 	}
5574 
5575 	if (roots_to_free)
5576 		kvm_mmu_free_roots(kvm, mmu, roots_to_free);
5577 }
5578 
5579 void kvm_mmu_free_obsolete_roots(struct kvm_vcpu *vcpu)
5580 {
5581 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.root_mmu);
5582 	__kvm_mmu_free_obsolete_roots(vcpu->kvm, &vcpu->arch.guest_mmu);
5583 }
5584 
5585 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5586 				    int *bytes)
5587 {
5588 	u64 gentry = 0;
5589 	int r;
5590 
5591 	/*
5592 	 * Assume that the pte write on a page table of the same type
5593 	 * as the current vcpu paging mode since we update the sptes only
5594 	 * when they have the same mode.
5595 	 */
5596 	if (is_pae(vcpu) && *bytes == 4) {
5597 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5598 		*gpa &= ~(gpa_t)7;
5599 		*bytes = 8;
5600 	}
5601 
5602 	if (*bytes == 4 || *bytes == 8) {
5603 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5604 		if (r)
5605 			gentry = 0;
5606 	}
5607 
5608 	return gentry;
5609 }
5610 
5611 /*
5612  * If we're seeing too many writes to a page, it may no longer be a page table,
5613  * or we may be forking, in which case it is better to unmap the page.
5614  */
5615 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5616 {
5617 	/*
5618 	 * Skip write-flooding detected for the sp whose level is 1, because
5619 	 * it can become unsync, then the guest page is not write-protected.
5620 	 */
5621 	if (sp->role.level == PG_LEVEL_4K)
5622 		return false;
5623 
5624 	atomic_inc(&sp->write_flooding_count);
5625 	return atomic_read(&sp->write_flooding_count) >= 3;
5626 }
5627 
5628 /*
5629  * Misaligned accesses are too much trouble to fix up; also, they usually
5630  * indicate a page is not used as a page table.
5631  */
5632 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5633 				    int bytes)
5634 {
5635 	unsigned offset, pte_size, misaligned;
5636 
5637 	pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5638 		 gpa, bytes, sp->role.word);
5639 
5640 	offset = offset_in_page(gpa);
5641 	pte_size = sp->role.has_4_byte_gpte ? 4 : 8;
5642 
5643 	/*
5644 	 * Sometimes, the OS only writes the last one bytes to update status
5645 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5646 	 */
5647 	if (!(offset & (pte_size - 1)) && bytes == 1)
5648 		return false;
5649 
5650 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5651 	misaligned |= bytes < 4;
5652 
5653 	return misaligned;
5654 }
5655 
5656 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5657 {
5658 	unsigned page_offset, quadrant;
5659 	u64 *spte;
5660 	int level;
5661 
5662 	page_offset = offset_in_page(gpa);
5663 	level = sp->role.level;
5664 	*nspte = 1;
5665 	if (sp->role.has_4_byte_gpte) {
5666 		page_offset <<= 1;	/* 32->64 */
5667 		/*
5668 		 * A 32-bit pde maps 4MB while the shadow pdes map
5669 		 * only 2MB.  So we need to double the offset again
5670 		 * and zap two pdes instead of one.
5671 		 */
5672 		if (level == PT32_ROOT_LEVEL) {
5673 			page_offset &= ~7; /* kill rounding error */
5674 			page_offset <<= 1;
5675 			*nspte = 2;
5676 		}
5677 		quadrant = page_offset >> PAGE_SHIFT;
5678 		page_offset &= ~PAGE_MASK;
5679 		if (quadrant != sp->role.quadrant)
5680 			return NULL;
5681 	}
5682 
5683 	spte = &sp->spt[page_offset / sizeof(*spte)];
5684 	return spte;
5685 }
5686 
5687 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5688 			      const u8 *new, int bytes,
5689 			      struct kvm_page_track_notifier_node *node)
5690 {
5691 	gfn_t gfn = gpa >> PAGE_SHIFT;
5692 	struct kvm_mmu_page *sp;
5693 	LIST_HEAD(invalid_list);
5694 	u64 entry, gentry, *spte;
5695 	int npte;
5696 	bool flush = false;
5697 
5698 	/*
5699 	 * If we don't have indirect shadow pages, it means no page is
5700 	 * write-protected, so we can exit simply.
5701 	 */
5702 	if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5703 		return;
5704 
5705 	pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5706 
5707 	write_lock(&vcpu->kvm->mmu_lock);
5708 
5709 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5710 
5711 	++vcpu->kvm->stat.mmu_pte_write;
5712 
5713 	for_each_gfn_valid_sp_with_gptes(vcpu->kvm, sp, gfn) {
5714 		if (detect_write_misaligned(sp, gpa, bytes) ||
5715 		      detect_write_flooding(sp)) {
5716 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5717 			++vcpu->kvm->stat.mmu_flooded;
5718 			continue;
5719 		}
5720 
5721 		spte = get_written_sptes(sp, gpa, &npte);
5722 		if (!spte)
5723 			continue;
5724 
5725 		while (npte--) {
5726 			entry = *spte;
5727 			mmu_page_zap_pte(vcpu->kvm, sp, spte, NULL);
5728 			if (gentry && sp->role.level != PG_LEVEL_4K)
5729 				++vcpu->kvm->stat.mmu_pde_zapped;
5730 			if (is_shadow_present_pte(entry))
5731 				flush = true;
5732 			++spte;
5733 		}
5734 	}
5735 	kvm_mmu_remote_flush_or_zap(vcpu->kvm, &invalid_list, flush);
5736 	write_unlock(&vcpu->kvm->mmu_lock);
5737 }
5738 
5739 int noinline kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5740 		       void *insn, int insn_len)
5741 {
5742 	int r, emulation_type = EMULTYPE_PF;
5743 	bool direct = vcpu->arch.mmu->root_role.direct;
5744 
5745 	if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root.hpa)))
5746 		return RET_PF_RETRY;
5747 
5748 	r = RET_PF_INVALID;
5749 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
5750 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5751 		if (r == RET_PF_EMULATE)
5752 			goto emulate;
5753 	}
5754 
5755 	if (r == RET_PF_INVALID) {
5756 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
5757 					  lower_32_bits(error_code), false,
5758 					  &emulation_type);
5759 		if (KVM_BUG_ON(r == RET_PF_INVALID, vcpu->kvm))
5760 			return -EIO;
5761 	}
5762 
5763 	if (r < 0)
5764 		return r;
5765 	if (r != RET_PF_EMULATE)
5766 		return 1;
5767 
5768 	/*
5769 	 * Before emulating the instruction, check if the error code
5770 	 * was due to a RO violation while translating the guest page.
5771 	 * This can occur when using nested virtualization with nested
5772 	 * paging in both guests. If true, we simply unprotect the page
5773 	 * and resume the guest.
5774 	 */
5775 	if (vcpu->arch.mmu->root_role.direct &&
5776 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5777 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5778 		return 1;
5779 	}
5780 
5781 	/*
5782 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5783 	 * optimistically try to just unprotect the page and let the processor
5784 	 * re-execute the instruction that caused the page fault.  Do not allow
5785 	 * retrying MMIO emulation, as it's not only pointless but could also
5786 	 * cause us to enter an infinite loop because the processor will keep
5787 	 * faulting on the non-existent MMIO address.  Retrying an instruction
5788 	 * from a nested guest is also pointless and dangerous as we are only
5789 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
5790 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5791 	 */
5792 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5793 		emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5794 emulate:
5795 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5796 				       insn_len);
5797 }
5798 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5799 
5800 static void __kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5801 				      u64 addr, hpa_t root_hpa)
5802 {
5803 	struct kvm_shadow_walk_iterator iterator;
5804 
5805 	vcpu_clear_mmio_info(vcpu, addr);
5806 
5807 	/*
5808 	 * Walking and synchronizing SPTEs both assume they are operating in
5809 	 * the context of the current MMU, and would need to be reworked if
5810 	 * this is ever used to sync the guest_mmu, e.g. to emulate INVEPT.
5811 	 */
5812 	if (WARN_ON_ONCE(mmu != vcpu->arch.mmu))
5813 		return;
5814 
5815 	if (!VALID_PAGE(root_hpa))
5816 		return;
5817 
5818 	write_lock(&vcpu->kvm->mmu_lock);
5819 	for_each_shadow_entry_using_root(vcpu, root_hpa, addr, iterator) {
5820 		struct kvm_mmu_page *sp = sptep_to_sp(iterator.sptep);
5821 
5822 		if (sp->unsync) {
5823 			int ret = kvm_sync_spte(vcpu, sp, iterator.index);
5824 
5825 			if (ret < 0)
5826 				mmu_page_zap_pte(vcpu->kvm, sp, iterator.sptep, NULL);
5827 			if (ret)
5828 				kvm_flush_remote_tlbs_sptep(vcpu->kvm, iterator.sptep);
5829 		}
5830 
5831 		if (!sp->unsync_children)
5832 			break;
5833 	}
5834 	write_unlock(&vcpu->kvm->mmu_lock);
5835 }
5836 
5837 void kvm_mmu_invalidate_addr(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5838 			     u64 addr, unsigned long roots)
5839 {
5840 	int i;
5841 
5842 	WARN_ON_ONCE(roots & ~KVM_MMU_ROOTS_ALL);
5843 
5844 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
5845 	if (mmu != &vcpu->arch.guest_mmu) {
5846 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
5847 		if (is_noncanonical_address(addr, vcpu))
5848 			return;
5849 
5850 		static_call(kvm_x86_flush_tlb_gva)(vcpu, addr);
5851 	}
5852 
5853 	if (!mmu->sync_spte)
5854 		return;
5855 
5856 	if (roots & KVM_MMU_ROOT_CURRENT)
5857 		__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->root.hpa);
5858 
5859 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5860 		if (roots & KVM_MMU_ROOT_PREVIOUS(i))
5861 			__kvm_mmu_invalidate_addr(vcpu, mmu, addr, mmu->prev_roots[i].hpa);
5862 	}
5863 }
5864 EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_addr);
5865 
5866 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5867 {
5868 	/*
5869 	 * INVLPG is required to invalidate any global mappings for the VA,
5870 	 * irrespective of PCID.  Blindly sync all roots as it would take
5871 	 * roughly the same amount of work/time to determine whether any of the
5872 	 * previous roots have a global mapping.
5873 	 *
5874 	 * Mappings not reachable via the current or previous cached roots will
5875 	 * be synced when switching to that new cr3, so nothing needs to be
5876 	 * done here for them.
5877 	 */
5878 	kvm_mmu_invalidate_addr(vcpu, vcpu->arch.walk_mmu, gva, KVM_MMU_ROOTS_ALL);
5879 	++vcpu->stat.invlpg;
5880 }
5881 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5882 
5883 
5884 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5885 {
5886 	struct kvm_mmu *mmu = vcpu->arch.mmu;
5887 	unsigned long roots = 0;
5888 	uint i;
5889 
5890 	if (pcid == kvm_get_active_pcid(vcpu))
5891 		roots |= KVM_MMU_ROOT_CURRENT;
5892 
5893 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5894 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5895 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd))
5896 			roots |= KVM_MMU_ROOT_PREVIOUS(i);
5897 	}
5898 
5899 	if (roots)
5900 		kvm_mmu_invalidate_addr(vcpu, mmu, gva, roots);
5901 	++vcpu->stat.invlpg;
5902 
5903 	/*
5904 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5905 	 * synced when switching to that cr3, so nothing needs to be done here
5906 	 * for them.
5907 	 */
5908 }
5909 
5910 void kvm_configure_mmu(bool enable_tdp, int tdp_forced_root_level,
5911 		       int tdp_max_root_level, int tdp_huge_page_level)
5912 {
5913 	tdp_enabled = enable_tdp;
5914 	tdp_root_level = tdp_forced_root_level;
5915 	max_tdp_level = tdp_max_root_level;
5916 
5917 #ifdef CONFIG_X86_64
5918 	tdp_mmu_enabled = tdp_mmu_allowed && tdp_enabled;
5919 #endif
5920 	/*
5921 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5922 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5923 	 * the kernel is not.  But, KVM never creates a page size greater than
5924 	 * what is used by the kernel for any given HVA, i.e. the kernel's
5925 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5926 	 */
5927 	if (tdp_enabled)
5928 		max_huge_page_level = tdp_huge_page_level;
5929 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
5930 		max_huge_page_level = PG_LEVEL_1G;
5931 	else
5932 		max_huge_page_level = PG_LEVEL_2M;
5933 }
5934 EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5935 
5936 /* The return value indicates if tlb flush on all vcpus is needed. */
5937 typedef bool (*slot_rmaps_handler) (struct kvm *kvm,
5938 				    struct kvm_rmap_head *rmap_head,
5939 				    const struct kvm_memory_slot *slot);
5940 
5941 static __always_inline bool __walk_slot_rmaps(struct kvm *kvm,
5942 					      const struct kvm_memory_slot *slot,
5943 					      slot_rmaps_handler fn,
5944 					      int start_level, int end_level,
5945 					      gfn_t start_gfn, gfn_t end_gfn,
5946 					      bool flush_on_yield, bool flush)
5947 {
5948 	struct slot_rmap_walk_iterator iterator;
5949 
5950 	lockdep_assert_held_write(&kvm->mmu_lock);
5951 
5952 	for_each_slot_rmap_range(slot, start_level, end_level, start_gfn,
5953 			end_gfn, &iterator) {
5954 		if (iterator.rmap)
5955 			flush |= fn(kvm, iterator.rmap, slot);
5956 
5957 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
5958 			if (flush && flush_on_yield) {
5959 				kvm_flush_remote_tlbs_range(kvm, start_gfn,
5960 							    iterator.gfn - start_gfn + 1);
5961 				flush = false;
5962 			}
5963 			cond_resched_rwlock_write(&kvm->mmu_lock);
5964 		}
5965 	}
5966 
5967 	return flush;
5968 }
5969 
5970 static __always_inline bool walk_slot_rmaps(struct kvm *kvm,
5971 					    const struct kvm_memory_slot *slot,
5972 					    slot_rmaps_handler fn,
5973 					    int start_level, int end_level,
5974 					    bool flush_on_yield)
5975 {
5976 	return __walk_slot_rmaps(kvm, slot, fn, start_level, end_level,
5977 				 slot->base_gfn, slot->base_gfn + slot->npages - 1,
5978 				 flush_on_yield, false);
5979 }
5980 
5981 static __always_inline bool walk_slot_rmaps_4k(struct kvm *kvm,
5982 					       const struct kvm_memory_slot *slot,
5983 					       slot_rmaps_handler fn,
5984 					       bool flush_on_yield)
5985 {
5986 	return walk_slot_rmaps(kvm, slot, fn, PG_LEVEL_4K, PG_LEVEL_4K, flush_on_yield);
5987 }
5988 
5989 static void free_mmu_pages(struct kvm_mmu *mmu)
5990 {
5991 	if (!tdp_enabled && mmu->pae_root)
5992 		set_memory_encrypted((unsigned long)mmu->pae_root, 1);
5993 	free_page((unsigned long)mmu->pae_root);
5994 	free_page((unsigned long)mmu->pml4_root);
5995 	free_page((unsigned long)mmu->pml5_root);
5996 }
5997 
5998 static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5999 {
6000 	struct page *page;
6001 	int i;
6002 
6003 	mmu->root.hpa = INVALID_PAGE;
6004 	mmu->root.pgd = 0;
6005 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
6006 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
6007 
6008 	/* vcpu->arch.guest_mmu isn't used when !tdp_enabled. */
6009 	if (!tdp_enabled && mmu == &vcpu->arch.guest_mmu)
6010 		return 0;
6011 
6012 	/*
6013 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
6014 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
6015 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
6016 	 * x86_64.  Therefore we need to allocate the PDP table in the first
6017 	 * 4GB of memory, which happens to fit the DMA32 zone.  TDP paging
6018 	 * generally doesn't use PAE paging and can skip allocating the PDP
6019 	 * table.  The main exception, handled here, is SVM's 32-bit NPT.  The
6020 	 * other exception is for shadowing L1's 32-bit or PAE NPT on 64-bit
6021 	 * KVM; that horror is handled on-demand by mmu_alloc_special_roots().
6022 	 */
6023 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
6024 		return 0;
6025 
6026 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
6027 	if (!page)
6028 		return -ENOMEM;
6029 
6030 	mmu->pae_root = page_address(page);
6031 
6032 	/*
6033 	 * CR3 is only 32 bits when PAE paging is used, thus it's impossible to
6034 	 * get the CPU to treat the PDPTEs as encrypted.  Decrypt the page so
6035 	 * that KVM's writes and the CPU's reads get along.  Note, this is
6036 	 * only necessary when using shadow paging, as 64-bit NPT can get at
6037 	 * the C-bit even when shadowing 32-bit NPT, and SME isn't supported
6038 	 * by 32-bit kernels (when KVM itself uses 32-bit NPT).
6039 	 */
6040 	if (!tdp_enabled)
6041 		set_memory_decrypted((unsigned long)mmu->pae_root, 1);
6042 	else
6043 		WARN_ON_ONCE(shadow_me_value);
6044 
6045 	for (i = 0; i < 4; ++i)
6046 		mmu->pae_root[i] = INVALID_PAE_ROOT;
6047 
6048 	return 0;
6049 }
6050 
6051 int kvm_mmu_create(struct kvm_vcpu *vcpu)
6052 {
6053 	int ret;
6054 
6055 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
6056 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
6057 
6058 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
6059 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
6060 
6061 	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
6062 
6063 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
6064 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
6065 
6066 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.guest_mmu);
6067 	if (ret)
6068 		return ret;
6069 
6070 	ret = __kvm_mmu_create(vcpu, &vcpu->arch.root_mmu);
6071 	if (ret)
6072 		goto fail_allocate_root;
6073 
6074 	return ret;
6075  fail_allocate_root:
6076 	free_mmu_pages(&vcpu->arch.guest_mmu);
6077 	return ret;
6078 }
6079 
6080 #define BATCH_ZAP_PAGES	10
6081 static void kvm_zap_obsolete_pages(struct kvm *kvm)
6082 {
6083 	struct kvm_mmu_page *sp, *node;
6084 	int nr_zapped, batch = 0;
6085 	bool unstable;
6086 
6087 restart:
6088 	list_for_each_entry_safe_reverse(sp, node,
6089 	      &kvm->arch.active_mmu_pages, link) {
6090 		/*
6091 		 * No obsolete valid page exists before a newly created page
6092 		 * since active_mmu_pages is a FIFO list.
6093 		 */
6094 		if (!is_obsolete_sp(kvm, sp))
6095 			break;
6096 
6097 		/*
6098 		 * Invalid pages should never land back on the list of active
6099 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
6100 		 * infinite loop if the page gets put back on the list (again).
6101 		 */
6102 		if (WARN_ON(sp->role.invalid))
6103 			continue;
6104 
6105 		/*
6106 		 * No need to flush the TLB since we're only zapping shadow
6107 		 * pages with an obsolete generation number and all vCPUS have
6108 		 * loaded a new root, i.e. the shadow pages being zapped cannot
6109 		 * be in active use by the guest.
6110 		 */
6111 		if (batch >= BATCH_ZAP_PAGES &&
6112 		    cond_resched_rwlock_write(&kvm->mmu_lock)) {
6113 			batch = 0;
6114 			goto restart;
6115 		}
6116 
6117 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp,
6118 				&kvm->arch.zapped_obsolete_pages, &nr_zapped);
6119 		batch += nr_zapped;
6120 
6121 		if (unstable)
6122 			goto restart;
6123 	}
6124 
6125 	/*
6126 	 * Kick all vCPUs (via remote TLB flush) before freeing the page tables
6127 	 * to ensure KVM is not in the middle of a lockless shadow page table
6128 	 * walk, which may reference the pages.  The remote TLB flush itself is
6129 	 * not required and is simply a convenient way to kick vCPUs as needed.
6130 	 * KVM performs a local TLB flush when allocating a new root (see
6131 	 * kvm_mmu_load()), and the reload in the caller ensure no vCPUs are
6132 	 * running with an obsolete MMU.
6133 	 */
6134 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
6135 }
6136 
6137 /*
6138  * Fast invalidate all shadow pages and use lock-break technique
6139  * to zap obsolete pages.
6140  *
6141  * It's required when memslot is being deleted or VM is being
6142  * destroyed, in these cases, we should ensure that KVM MMU does
6143  * not use any resource of the being-deleted slot or all slots
6144  * after calling the function.
6145  */
6146 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
6147 {
6148 	lockdep_assert_held(&kvm->slots_lock);
6149 
6150 	write_lock(&kvm->mmu_lock);
6151 	trace_kvm_mmu_zap_all_fast(kvm);
6152 
6153 	/*
6154 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
6155 	 * held for the entire duration of zapping obsolete pages, it's
6156 	 * impossible for there to be multiple invalid generations associated
6157 	 * with *valid* shadow pages at any given time, i.e. there is exactly
6158 	 * one valid generation and (at most) one invalid generation.
6159 	 */
6160 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
6161 
6162 	/*
6163 	 * In order to ensure all vCPUs drop their soon-to-be invalid roots,
6164 	 * invalidating TDP MMU roots must be done while holding mmu_lock for
6165 	 * write and in the same critical section as making the reload request,
6166 	 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
6167 	 */
6168 	if (tdp_mmu_enabled)
6169 		kvm_tdp_mmu_invalidate_all_roots(kvm);
6170 
6171 	/*
6172 	 * Notify all vcpus to reload its shadow page table and flush TLB.
6173 	 * Then all vcpus will switch to new shadow page table with the new
6174 	 * mmu_valid_gen.
6175 	 *
6176 	 * Note: we need to do this under the protection of mmu_lock,
6177 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
6178 	 */
6179 	kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_FREE_OBSOLETE_ROOTS);
6180 
6181 	kvm_zap_obsolete_pages(kvm);
6182 
6183 	write_unlock(&kvm->mmu_lock);
6184 
6185 	/*
6186 	 * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
6187 	 * returning to the caller, e.g. if the zap is in response to a memslot
6188 	 * deletion, mmu_notifier callbacks will be unable to reach the SPTEs
6189 	 * associated with the deleted memslot once the update completes, and
6190 	 * Deferring the zap until the final reference to the root is put would
6191 	 * lead to use-after-free.
6192 	 */
6193 	if (tdp_mmu_enabled)
6194 		kvm_tdp_mmu_zap_invalidated_roots(kvm);
6195 }
6196 
6197 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
6198 {
6199 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
6200 }
6201 
6202 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
6203 			struct kvm_memory_slot *slot,
6204 			struct kvm_page_track_notifier_node *node)
6205 {
6206 	kvm_mmu_zap_all_fast(kvm);
6207 }
6208 
6209 int kvm_mmu_init_vm(struct kvm *kvm)
6210 {
6211 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6212 	int r;
6213 
6214 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
6215 	INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
6216 	INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
6217 	spin_lock_init(&kvm->arch.mmu_unsync_pages_lock);
6218 
6219 	if (tdp_mmu_enabled) {
6220 		r = kvm_mmu_init_tdp_mmu(kvm);
6221 		if (r < 0)
6222 			return r;
6223 	}
6224 
6225 	node->track_write = kvm_mmu_pte_write;
6226 	node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
6227 	kvm_page_track_register_notifier(kvm, node);
6228 
6229 	kvm->arch.split_page_header_cache.kmem_cache = mmu_page_header_cache;
6230 	kvm->arch.split_page_header_cache.gfp_zero = __GFP_ZERO;
6231 
6232 	kvm->arch.split_shadow_page_cache.gfp_zero = __GFP_ZERO;
6233 
6234 	kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache;
6235 	kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO;
6236 
6237 	return 0;
6238 }
6239 
6240 static void mmu_free_vm_memory_caches(struct kvm *kvm)
6241 {
6242 	kvm_mmu_free_memory_cache(&kvm->arch.split_desc_cache);
6243 	kvm_mmu_free_memory_cache(&kvm->arch.split_page_header_cache);
6244 	kvm_mmu_free_memory_cache(&kvm->arch.split_shadow_page_cache);
6245 }
6246 
6247 void kvm_mmu_uninit_vm(struct kvm *kvm)
6248 {
6249 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
6250 
6251 	kvm_page_track_unregister_notifier(kvm, node);
6252 
6253 	if (tdp_mmu_enabled)
6254 		kvm_mmu_uninit_tdp_mmu(kvm);
6255 
6256 	mmu_free_vm_memory_caches(kvm);
6257 }
6258 
6259 static bool kvm_rmap_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6260 {
6261 	const struct kvm_memory_slot *memslot;
6262 	struct kvm_memslots *slots;
6263 	struct kvm_memslot_iter iter;
6264 	bool flush = false;
6265 	gfn_t start, end;
6266 	int i;
6267 
6268 	if (!kvm_memslots_have_rmaps(kvm))
6269 		return flush;
6270 
6271 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6272 		slots = __kvm_memslots(kvm, i);
6273 
6274 		kvm_for_each_memslot_in_gfn_range(&iter, slots, gfn_start, gfn_end) {
6275 			memslot = iter.slot;
6276 			start = max(gfn_start, memslot->base_gfn);
6277 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
6278 			if (WARN_ON_ONCE(start >= end))
6279 				continue;
6280 
6281 			flush = __walk_slot_rmaps(kvm, memslot, __kvm_zap_rmap,
6282 						  PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL,
6283 						  start, end - 1, true, flush);
6284 		}
6285 	}
6286 
6287 	return flush;
6288 }
6289 
6290 /*
6291  * Invalidate (zap) SPTEs that cover GFNs from gfn_start and up to gfn_end
6292  * (not including it)
6293  */
6294 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
6295 {
6296 	bool flush;
6297 	int i;
6298 
6299 	if (WARN_ON_ONCE(gfn_end <= gfn_start))
6300 		return;
6301 
6302 	write_lock(&kvm->mmu_lock);
6303 
6304 	kvm_mmu_invalidate_begin(kvm, 0, -1ul);
6305 
6306 	flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
6307 
6308 	if (tdp_mmu_enabled) {
6309 		for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
6310 			flush = kvm_tdp_mmu_zap_leafs(kvm, i, gfn_start,
6311 						      gfn_end, true, flush);
6312 	}
6313 
6314 	if (flush)
6315 		kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);
6316 
6317 	kvm_mmu_invalidate_end(kvm, 0, -1ul);
6318 
6319 	write_unlock(&kvm->mmu_lock);
6320 }
6321 
6322 static bool slot_rmap_write_protect(struct kvm *kvm,
6323 				    struct kvm_rmap_head *rmap_head,
6324 				    const struct kvm_memory_slot *slot)
6325 {
6326 	return rmap_write_protect(rmap_head, false);
6327 }
6328 
6329 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
6330 				      const struct kvm_memory_slot *memslot,
6331 				      int start_level)
6332 {
6333 	if (kvm_memslots_have_rmaps(kvm)) {
6334 		write_lock(&kvm->mmu_lock);
6335 		walk_slot_rmaps(kvm, memslot, slot_rmap_write_protect,
6336 				start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
6337 		write_unlock(&kvm->mmu_lock);
6338 	}
6339 
6340 	if (tdp_mmu_enabled) {
6341 		read_lock(&kvm->mmu_lock);
6342 		kvm_tdp_mmu_wrprot_slot(kvm, memslot, start_level);
6343 		read_unlock(&kvm->mmu_lock);
6344 	}
6345 }
6346 
6347 static inline bool need_topup(struct kvm_mmu_memory_cache *cache, int min)
6348 {
6349 	return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
6350 }
6351 
6352 static bool need_topup_split_caches_or_resched(struct kvm *kvm)
6353 {
6354 	if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
6355 		return true;
6356 
6357 	/*
6358 	 * In the worst case, SPLIT_DESC_CACHE_MIN_NR_OBJECTS descriptors are needed
6359 	 * to split a single huge page. Calculating how many are actually needed
6360 	 * is possible but not worth the complexity.
6361 	 */
6362 	return need_topup(&kvm->arch.split_desc_cache, SPLIT_DESC_CACHE_MIN_NR_OBJECTS) ||
6363 	       need_topup(&kvm->arch.split_page_header_cache, 1) ||
6364 	       need_topup(&kvm->arch.split_shadow_page_cache, 1);
6365 }
6366 
6367 static int topup_split_caches(struct kvm *kvm)
6368 {
6369 	/*
6370 	 * Allocating rmap list entries when splitting huge pages for nested
6371 	 * MMUs is uncommon as KVM needs to use a list if and only if there is
6372 	 * more than one rmap entry for a gfn, i.e. requires an L1 gfn to be
6373 	 * aliased by multiple L2 gfns and/or from multiple nested roots with
6374 	 * different roles.  Aliasing gfns when using TDP is atypical for VMMs;
6375 	 * a few gfns are often aliased during boot, e.g. when remapping BIOS,
6376 	 * but aliasing rarely occurs post-boot or for many gfns.  If there is
6377 	 * only one rmap entry, rmap->val points directly at that one entry and
6378 	 * doesn't need to allocate a list.  Buffer the cache by the default
6379 	 * capacity so that KVM doesn't have to drop mmu_lock to topup if KVM
6380 	 * encounters an aliased gfn or two.
6381 	 */
6382 	const int capacity = SPLIT_DESC_CACHE_MIN_NR_OBJECTS +
6383 			     KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE;
6384 	int r;
6385 
6386 	lockdep_assert_held(&kvm->slots_lock);
6387 
6388 	r = __kvm_mmu_topup_memory_cache(&kvm->arch.split_desc_cache, capacity,
6389 					 SPLIT_DESC_CACHE_MIN_NR_OBJECTS);
6390 	if (r)
6391 		return r;
6392 
6393 	r = kvm_mmu_topup_memory_cache(&kvm->arch.split_page_header_cache, 1);
6394 	if (r)
6395 		return r;
6396 
6397 	return kvm_mmu_topup_memory_cache(&kvm->arch.split_shadow_page_cache, 1);
6398 }
6399 
6400 static struct kvm_mmu_page *shadow_mmu_get_sp_for_split(struct kvm *kvm, u64 *huge_sptep)
6401 {
6402 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6403 	struct shadow_page_caches caches = {};
6404 	union kvm_mmu_page_role role;
6405 	unsigned int access;
6406 	gfn_t gfn;
6407 
6408 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6409 	access = kvm_mmu_page_get_access(huge_sp, spte_index(huge_sptep));
6410 
6411 	/*
6412 	 * Note, huge page splitting always uses direct shadow pages, regardless
6413 	 * of whether the huge page itself is mapped by a direct or indirect
6414 	 * shadow page, since the huge page region itself is being directly
6415 	 * mapped with smaller pages.
6416 	 */
6417 	role = kvm_mmu_child_role(huge_sptep, /*direct=*/true, access);
6418 
6419 	/* Direct SPs do not require a shadowed_info_cache. */
6420 	caches.page_header_cache = &kvm->arch.split_page_header_cache;
6421 	caches.shadow_page_cache = &kvm->arch.split_shadow_page_cache;
6422 
6423 	/* Safe to pass NULL for vCPU since requesting a direct SP. */
6424 	return __kvm_mmu_get_shadow_page(kvm, NULL, &caches, gfn, role);
6425 }
6426 
6427 static void shadow_mmu_split_huge_page(struct kvm *kvm,
6428 				       const struct kvm_memory_slot *slot,
6429 				       u64 *huge_sptep)
6430 
6431 {
6432 	struct kvm_mmu_memory_cache *cache = &kvm->arch.split_desc_cache;
6433 	u64 huge_spte = READ_ONCE(*huge_sptep);
6434 	struct kvm_mmu_page *sp;
6435 	bool flush = false;
6436 	u64 *sptep, spte;
6437 	gfn_t gfn;
6438 	int index;
6439 
6440 	sp = shadow_mmu_get_sp_for_split(kvm, huge_sptep);
6441 
6442 	for (index = 0; index < SPTE_ENT_PER_PAGE; index++) {
6443 		sptep = &sp->spt[index];
6444 		gfn = kvm_mmu_page_get_gfn(sp, index);
6445 
6446 		/*
6447 		 * The SP may already have populated SPTEs, e.g. if this huge
6448 		 * page is aliased by multiple sptes with the same access
6449 		 * permissions. These entries are guaranteed to map the same
6450 		 * gfn-to-pfn translation since the SP is direct, so no need to
6451 		 * modify them.
6452 		 *
6453 		 * However, if a given SPTE points to a lower level page table,
6454 		 * that lower level page table may only be partially populated.
6455 		 * Installing such SPTEs would effectively unmap a potion of the
6456 		 * huge page. Unmapping guest memory always requires a TLB flush
6457 		 * since a subsequent operation on the unmapped regions would
6458 		 * fail to detect the need to flush.
6459 		 */
6460 		if (is_shadow_present_pte(*sptep)) {
6461 			flush |= !is_last_spte(*sptep, sp->role.level);
6462 			continue;
6463 		}
6464 
6465 		spte = make_huge_page_split_spte(kvm, huge_spte, sp->role, index);
6466 		mmu_spte_set(sptep, spte);
6467 		__rmap_add(kvm, cache, slot, sptep, gfn, sp->role.access);
6468 	}
6469 
6470 	__link_shadow_page(kvm, cache, huge_sptep, sp, flush);
6471 }
6472 
6473 static int shadow_mmu_try_split_huge_page(struct kvm *kvm,
6474 					  const struct kvm_memory_slot *slot,
6475 					  u64 *huge_sptep)
6476 {
6477 	struct kvm_mmu_page *huge_sp = sptep_to_sp(huge_sptep);
6478 	int level, r = 0;
6479 	gfn_t gfn;
6480 	u64 spte;
6481 
6482 	/* Grab information for the tracepoint before dropping the MMU lock. */
6483 	gfn = kvm_mmu_page_get_gfn(huge_sp, spte_index(huge_sptep));
6484 	level = huge_sp->role.level;
6485 	spte = *huge_sptep;
6486 
6487 	if (kvm_mmu_available_pages(kvm) <= KVM_MIN_FREE_MMU_PAGES) {
6488 		r = -ENOSPC;
6489 		goto out;
6490 	}
6491 
6492 	if (need_topup_split_caches_or_resched(kvm)) {
6493 		write_unlock(&kvm->mmu_lock);
6494 		cond_resched();
6495 		/*
6496 		 * If the topup succeeds, return -EAGAIN to indicate that the
6497 		 * rmap iterator should be restarted because the MMU lock was
6498 		 * dropped.
6499 		 */
6500 		r = topup_split_caches(kvm) ?: -EAGAIN;
6501 		write_lock(&kvm->mmu_lock);
6502 		goto out;
6503 	}
6504 
6505 	shadow_mmu_split_huge_page(kvm, slot, huge_sptep);
6506 
6507 out:
6508 	trace_kvm_mmu_split_huge_page(gfn, spte, level, r);
6509 	return r;
6510 }
6511 
6512 static bool shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6513 					    struct kvm_rmap_head *rmap_head,
6514 					    const struct kvm_memory_slot *slot)
6515 {
6516 	struct rmap_iterator iter;
6517 	struct kvm_mmu_page *sp;
6518 	u64 *huge_sptep;
6519 	int r;
6520 
6521 restart:
6522 	for_each_rmap_spte(rmap_head, &iter, huge_sptep) {
6523 		sp = sptep_to_sp(huge_sptep);
6524 
6525 		/* TDP MMU is enabled, so rmap only contains nested MMU SPs. */
6526 		if (WARN_ON_ONCE(!sp->role.guest_mode))
6527 			continue;
6528 
6529 		/* The rmaps should never contain non-leaf SPTEs. */
6530 		if (WARN_ON_ONCE(!is_large_pte(*huge_sptep)))
6531 			continue;
6532 
6533 		/* SPs with level >PG_LEVEL_4K should never by unsync. */
6534 		if (WARN_ON_ONCE(sp->unsync))
6535 			continue;
6536 
6537 		/* Don't bother splitting huge pages on invalid SPs. */
6538 		if (sp->role.invalid)
6539 			continue;
6540 
6541 		r = shadow_mmu_try_split_huge_page(kvm, slot, huge_sptep);
6542 
6543 		/*
6544 		 * The split succeeded or needs to be retried because the MMU
6545 		 * lock was dropped. Either way, restart the iterator to get it
6546 		 * back into a consistent state.
6547 		 */
6548 		if (!r || r == -EAGAIN)
6549 			goto restart;
6550 
6551 		/* The split failed and shouldn't be retried (e.g. -ENOMEM). */
6552 		break;
6553 	}
6554 
6555 	return false;
6556 }
6557 
6558 static void kvm_shadow_mmu_try_split_huge_pages(struct kvm *kvm,
6559 						const struct kvm_memory_slot *slot,
6560 						gfn_t start, gfn_t end,
6561 						int target_level)
6562 {
6563 	int level;
6564 
6565 	/*
6566 	 * Split huge pages starting with KVM_MAX_HUGEPAGE_LEVEL and working
6567 	 * down to the target level. This ensures pages are recursively split
6568 	 * all the way to the target level. There's no need to split pages
6569 	 * already at the target level.
6570 	 */
6571 	for (level = KVM_MAX_HUGEPAGE_LEVEL; level > target_level; level--)
6572 		__walk_slot_rmaps(kvm, slot, shadow_mmu_try_split_huge_pages,
6573 				  level, level, start, end - 1, true, false);
6574 }
6575 
6576 /* Must be called with the mmu_lock held in write-mode. */
6577 void kvm_mmu_try_split_huge_pages(struct kvm *kvm,
6578 				   const struct kvm_memory_slot *memslot,
6579 				   u64 start, u64 end,
6580 				   int target_level)
6581 {
6582 	if (!tdp_mmu_enabled)
6583 		return;
6584 
6585 	if (kvm_memslots_have_rmaps(kvm))
6586 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6587 
6588 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, false);
6589 
6590 	/*
6591 	 * A TLB flush is unnecessary at this point for the same resons as in
6592 	 * kvm_mmu_slot_try_split_huge_pages().
6593 	 */
6594 }
6595 
6596 void kvm_mmu_slot_try_split_huge_pages(struct kvm *kvm,
6597 					const struct kvm_memory_slot *memslot,
6598 					int target_level)
6599 {
6600 	u64 start = memslot->base_gfn;
6601 	u64 end = start + memslot->npages;
6602 
6603 	if (!tdp_mmu_enabled)
6604 		return;
6605 
6606 	if (kvm_memslots_have_rmaps(kvm)) {
6607 		write_lock(&kvm->mmu_lock);
6608 		kvm_shadow_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level);
6609 		write_unlock(&kvm->mmu_lock);
6610 	}
6611 
6612 	read_lock(&kvm->mmu_lock);
6613 	kvm_tdp_mmu_try_split_huge_pages(kvm, memslot, start, end, target_level, true);
6614 	read_unlock(&kvm->mmu_lock);
6615 
6616 	/*
6617 	 * No TLB flush is necessary here. KVM will flush TLBs after
6618 	 * write-protecting and/or clearing dirty on the newly split SPTEs to
6619 	 * ensure that guest writes are reflected in the dirty log before the
6620 	 * ioctl to enable dirty logging on this memslot completes. Since the
6621 	 * split SPTEs retain the write and dirty bits of the huge SPTE, it is
6622 	 * safe for KVM to decide if a TLB flush is necessary based on the split
6623 	 * SPTEs.
6624 	 */
6625 }
6626 
6627 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
6628 					 struct kvm_rmap_head *rmap_head,
6629 					 const struct kvm_memory_slot *slot)
6630 {
6631 	u64 *sptep;
6632 	struct rmap_iterator iter;
6633 	int need_tlb_flush = 0;
6634 	struct kvm_mmu_page *sp;
6635 
6636 restart:
6637 	for_each_rmap_spte(rmap_head, &iter, sptep) {
6638 		sp = sptep_to_sp(sptep);
6639 
6640 		/*
6641 		 * We cannot do huge page mapping for indirect shadow pages,
6642 		 * which are found on the last rmap (level = 1) when not using
6643 		 * tdp; such shadow pages are synced with the page table in
6644 		 * the guest, and the guest page table is using 4K page size
6645 		 * mapping if the indirect sp has level = 1.
6646 		 */
6647 		if (sp->role.direct &&
6648 		    sp->role.level < kvm_mmu_max_mapping_level(kvm, slot, sp->gfn,
6649 							       PG_LEVEL_NUM)) {
6650 			kvm_zap_one_rmap_spte(kvm, rmap_head, sptep);
6651 
6652 			if (kvm_available_flush_remote_tlbs_range())
6653 				kvm_flush_remote_tlbs_sptep(kvm, sptep);
6654 			else
6655 				need_tlb_flush = 1;
6656 
6657 			goto restart;
6658 		}
6659 	}
6660 
6661 	return need_tlb_flush;
6662 }
6663 
6664 static void kvm_rmap_zap_collapsible_sptes(struct kvm *kvm,
6665 					   const struct kvm_memory_slot *slot)
6666 {
6667 	/*
6668 	 * Note, use KVM_MAX_HUGEPAGE_LEVEL - 1 since there's no need to zap
6669 	 * pages that are already mapped at the maximum hugepage level.
6670 	 */
6671 	if (walk_slot_rmaps(kvm, slot, kvm_mmu_zap_collapsible_spte,
6672 			    PG_LEVEL_4K, KVM_MAX_HUGEPAGE_LEVEL - 1, true))
6673 		kvm_arch_flush_remote_tlbs_memslot(kvm, slot);
6674 }
6675 
6676 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
6677 				   const struct kvm_memory_slot *slot)
6678 {
6679 	if (kvm_memslots_have_rmaps(kvm)) {
6680 		write_lock(&kvm->mmu_lock);
6681 		kvm_rmap_zap_collapsible_sptes(kvm, slot);
6682 		write_unlock(&kvm->mmu_lock);
6683 	}
6684 
6685 	if (tdp_mmu_enabled) {
6686 		read_lock(&kvm->mmu_lock);
6687 		kvm_tdp_mmu_zap_collapsible_sptes(kvm, slot);
6688 		read_unlock(&kvm->mmu_lock);
6689 	}
6690 }
6691 
6692 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
6693 					const struct kvm_memory_slot *memslot)
6694 {
6695 	/*
6696 	 * All current use cases for flushing the TLBs for a specific memslot
6697 	 * related to dirty logging, and many do the TLB flush out of mmu_lock.
6698 	 * The interaction between the various operations on memslot must be
6699 	 * serialized by slots_locks to ensure the TLB flush from one operation
6700 	 * is observed by any other operation on the same memslot.
6701 	 */
6702 	lockdep_assert_held(&kvm->slots_lock);
6703 	kvm_flush_remote_tlbs_range(kvm, memslot->base_gfn, memslot->npages);
6704 }
6705 
6706 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
6707 				   const struct kvm_memory_slot *memslot)
6708 {
6709 	if (kvm_memslots_have_rmaps(kvm)) {
6710 		write_lock(&kvm->mmu_lock);
6711 		/*
6712 		 * Clear dirty bits only on 4k SPTEs since the legacy MMU only
6713 		 * support dirty logging at a 4k granularity.
6714 		 */
6715 		walk_slot_rmaps_4k(kvm, memslot, __rmap_clear_dirty, false);
6716 		write_unlock(&kvm->mmu_lock);
6717 	}
6718 
6719 	if (tdp_mmu_enabled) {
6720 		read_lock(&kvm->mmu_lock);
6721 		kvm_tdp_mmu_clear_dirty_slot(kvm, memslot);
6722 		read_unlock(&kvm->mmu_lock);
6723 	}
6724 
6725 	/*
6726 	 * The caller will flush the TLBs after this function returns.
6727 	 *
6728 	 * It's also safe to flush TLBs out of mmu lock here as currently this
6729 	 * function is only used for dirty logging, in which case flushing TLB
6730 	 * out of mmu lock also guarantees no dirty pages will be lost in
6731 	 * dirty_bitmap.
6732 	 */
6733 }
6734 
6735 void kvm_mmu_zap_all(struct kvm *kvm)
6736 {
6737 	struct kvm_mmu_page *sp, *node;
6738 	LIST_HEAD(invalid_list);
6739 	int ign;
6740 
6741 	write_lock(&kvm->mmu_lock);
6742 restart:
6743 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6744 		if (WARN_ON(sp->role.invalid))
6745 			continue;
6746 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6747 			goto restart;
6748 		if (cond_resched_rwlock_write(&kvm->mmu_lock))
6749 			goto restart;
6750 	}
6751 
6752 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6753 
6754 	if (tdp_mmu_enabled)
6755 		kvm_tdp_mmu_zap_all(kvm);
6756 
6757 	write_unlock(&kvm->mmu_lock);
6758 }
6759 
6760 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6761 {
6762 	WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6763 
6764 	gen &= MMIO_SPTE_GEN_MASK;
6765 
6766 	/*
6767 	 * Generation numbers are incremented in multiples of the number of
6768 	 * address spaces in order to provide unique generations across all
6769 	 * address spaces.  Strip what is effectively the address space
6770 	 * modifier prior to checking for a wrap of the MMIO generation so
6771 	 * that a wrap in any address space is detected.
6772 	 */
6773 	gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6774 
6775 	/*
6776 	 * The very rare case: if the MMIO generation number has wrapped,
6777 	 * zap all shadow pages.
6778 	 */
6779 	if (unlikely(gen == 0)) {
6780 		kvm_debug_ratelimited("zapping shadow pages for mmio generation wraparound\n");
6781 		kvm_mmu_zap_all_fast(kvm);
6782 	}
6783 }
6784 
6785 static unsigned long mmu_shrink_scan(struct shrinker *shrink,
6786 				     struct shrink_control *sc)
6787 {
6788 	struct kvm *kvm;
6789 	int nr_to_scan = sc->nr_to_scan;
6790 	unsigned long freed = 0;
6791 
6792 	mutex_lock(&kvm_lock);
6793 
6794 	list_for_each_entry(kvm, &vm_list, vm_list) {
6795 		int idx;
6796 		LIST_HEAD(invalid_list);
6797 
6798 		/*
6799 		 * Never scan more than sc->nr_to_scan VM instances.
6800 		 * Will not hit this condition practically since we do not try
6801 		 * to shrink more than one VM and it is very unlikely to see
6802 		 * !n_used_mmu_pages so many times.
6803 		 */
6804 		if (!nr_to_scan--)
6805 			break;
6806 		/*
6807 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6808 		 * here. We may skip a VM instance errorneosly, but we do not
6809 		 * want to shrink a VM that only started to populate its MMU
6810 		 * anyway.
6811 		 */
6812 		if (!kvm->arch.n_used_mmu_pages &&
6813 		    !kvm_has_zapped_obsolete_pages(kvm))
6814 			continue;
6815 
6816 		idx = srcu_read_lock(&kvm->srcu);
6817 		write_lock(&kvm->mmu_lock);
6818 
6819 		if (kvm_has_zapped_obsolete_pages(kvm)) {
6820 			kvm_mmu_commit_zap_page(kvm,
6821 			      &kvm->arch.zapped_obsolete_pages);
6822 			goto unlock;
6823 		}
6824 
6825 		freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6826 
6827 unlock:
6828 		write_unlock(&kvm->mmu_lock);
6829 		srcu_read_unlock(&kvm->srcu, idx);
6830 
6831 		/*
6832 		 * unfair on small ones
6833 		 * per-vm shrinkers cry out
6834 		 * sadness comes quickly
6835 		 */
6836 		list_move_tail(&kvm->vm_list, &vm_list);
6837 		break;
6838 	}
6839 
6840 	mutex_unlock(&kvm_lock);
6841 	return freed;
6842 }
6843 
6844 static unsigned long mmu_shrink_count(struct shrinker *shrink,
6845 				      struct shrink_control *sc)
6846 {
6847 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6848 }
6849 
6850 static struct shrinker mmu_shrinker = {
6851 	.count_objects = mmu_shrink_count,
6852 	.scan_objects = mmu_shrink_scan,
6853 	.seeks = DEFAULT_SEEKS * 10,
6854 };
6855 
6856 static void mmu_destroy_caches(void)
6857 {
6858 	kmem_cache_destroy(pte_list_desc_cache);
6859 	kmem_cache_destroy(mmu_page_header_cache);
6860 }
6861 
6862 static int get_nx_huge_pages(char *buffer, const struct kernel_param *kp)
6863 {
6864 	if (nx_hugepage_mitigation_hard_disabled)
6865 		return sprintf(buffer, "never\n");
6866 
6867 	return param_get_bool(buffer, kp);
6868 }
6869 
6870 static bool get_nx_auto_mode(void)
6871 {
6872 	/* Return true when CPU has the bug, and mitigations are ON */
6873 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6874 }
6875 
6876 static void __set_nx_huge_pages(bool val)
6877 {
6878 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6879 }
6880 
6881 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6882 {
6883 	bool old_val = nx_huge_pages;
6884 	bool new_val;
6885 
6886 	if (nx_hugepage_mitigation_hard_disabled)
6887 		return -EPERM;
6888 
6889 	/* In "auto" mode deploy workaround only if CPU has the bug. */
6890 	if (sysfs_streq(val, "off")) {
6891 		new_val = 0;
6892 	} else if (sysfs_streq(val, "force")) {
6893 		new_val = 1;
6894 	} else if (sysfs_streq(val, "auto")) {
6895 		new_val = get_nx_auto_mode();
6896 	} else if (sysfs_streq(val, "never")) {
6897 		new_val = 0;
6898 
6899 		mutex_lock(&kvm_lock);
6900 		if (!list_empty(&vm_list)) {
6901 			mutex_unlock(&kvm_lock);
6902 			return -EBUSY;
6903 		}
6904 		nx_hugepage_mitigation_hard_disabled = true;
6905 		mutex_unlock(&kvm_lock);
6906 	} else if (kstrtobool(val, &new_val) < 0) {
6907 		return -EINVAL;
6908 	}
6909 
6910 	__set_nx_huge_pages(new_val);
6911 
6912 	if (new_val != old_val) {
6913 		struct kvm *kvm;
6914 
6915 		mutex_lock(&kvm_lock);
6916 
6917 		list_for_each_entry(kvm, &vm_list, vm_list) {
6918 			mutex_lock(&kvm->slots_lock);
6919 			kvm_mmu_zap_all_fast(kvm);
6920 			mutex_unlock(&kvm->slots_lock);
6921 
6922 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
6923 		}
6924 		mutex_unlock(&kvm_lock);
6925 	}
6926 
6927 	return 0;
6928 }
6929 
6930 /*
6931  * nx_huge_pages needs to be resolved to true/false when kvm.ko is loaded, as
6932  * its default value of -1 is technically undefined behavior for a boolean.
6933  * Forward the module init call to SPTE code so that it too can handle module
6934  * params that need to be resolved/snapshot.
6935  */
6936 void __init kvm_mmu_x86_module_init(void)
6937 {
6938 	if (nx_huge_pages == -1)
6939 		__set_nx_huge_pages(get_nx_auto_mode());
6940 
6941 	/*
6942 	 * Snapshot userspace's desire to enable the TDP MMU. Whether or not the
6943 	 * TDP MMU is actually enabled is determined in kvm_configure_mmu()
6944 	 * when the vendor module is loaded.
6945 	 */
6946 	tdp_mmu_allowed = tdp_mmu_enabled;
6947 
6948 	kvm_mmu_spte_module_init();
6949 }
6950 
6951 /*
6952  * The bulk of the MMU initialization is deferred until the vendor module is
6953  * loaded as many of the masks/values may be modified by VMX or SVM, i.e. need
6954  * to be reset when a potentially different vendor module is loaded.
6955  */
6956 int kvm_mmu_vendor_module_init(void)
6957 {
6958 	int ret = -ENOMEM;
6959 
6960 	/*
6961 	 * MMU roles use union aliasing which is, generally speaking, an
6962 	 * undefined behavior. However, we supposedly know how compilers behave
6963 	 * and the current status quo is unlikely to change. Guardians below are
6964 	 * supposed to let us know if the assumption becomes false.
6965 	 */
6966 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6967 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6968 	BUILD_BUG_ON(sizeof(union kvm_cpu_role) != sizeof(u64));
6969 
6970 	kvm_mmu_reset_all_pte_masks();
6971 
6972 	pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6973 					    sizeof(struct pte_list_desc),
6974 					    0, SLAB_ACCOUNT, NULL);
6975 	if (!pte_list_desc_cache)
6976 		goto out;
6977 
6978 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6979 						  sizeof(struct kvm_mmu_page),
6980 						  0, SLAB_ACCOUNT, NULL);
6981 	if (!mmu_page_header_cache)
6982 		goto out;
6983 
6984 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6985 		goto out;
6986 
6987 	ret = register_shrinker(&mmu_shrinker, "x86-mmu");
6988 	if (ret)
6989 		goto out_shrinker;
6990 
6991 	return 0;
6992 
6993 out_shrinker:
6994 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6995 out:
6996 	mmu_destroy_caches();
6997 	return ret;
6998 }
6999 
7000 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
7001 {
7002 	kvm_mmu_unload(vcpu);
7003 	free_mmu_pages(&vcpu->arch.root_mmu);
7004 	free_mmu_pages(&vcpu->arch.guest_mmu);
7005 	mmu_free_memory_caches(vcpu);
7006 }
7007 
7008 void kvm_mmu_vendor_module_exit(void)
7009 {
7010 	mmu_destroy_caches();
7011 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
7012 	unregister_shrinker(&mmu_shrinker);
7013 }
7014 
7015 /*
7016  * Calculate the effective recovery period, accounting for '0' meaning "let KVM
7017  * select a halving time of 1 hour".  Returns true if recovery is enabled.
7018  */
7019 static bool calc_nx_huge_pages_recovery_period(uint *period)
7020 {
7021 	/*
7022 	 * Use READ_ONCE to get the params, this may be called outside of the
7023 	 * param setters, e.g. by the kthread to compute its next timeout.
7024 	 */
7025 	bool enabled = READ_ONCE(nx_huge_pages);
7026 	uint ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7027 
7028 	if (!enabled || !ratio)
7029 		return false;
7030 
7031 	*period = READ_ONCE(nx_huge_pages_recovery_period_ms);
7032 	if (!*period) {
7033 		/* Make sure the period is not less than one second.  */
7034 		ratio = min(ratio, 3600u);
7035 		*period = 60 * 60 * 1000 / ratio;
7036 	}
7037 	return true;
7038 }
7039 
7040 static int set_nx_huge_pages_recovery_param(const char *val, const struct kernel_param *kp)
7041 {
7042 	bool was_recovery_enabled, is_recovery_enabled;
7043 	uint old_period, new_period;
7044 	int err;
7045 
7046 	if (nx_hugepage_mitigation_hard_disabled)
7047 		return -EPERM;
7048 
7049 	was_recovery_enabled = calc_nx_huge_pages_recovery_period(&old_period);
7050 
7051 	err = param_set_uint(val, kp);
7052 	if (err)
7053 		return err;
7054 
7055 	is_recovery_enabled = calc_nx_huge_pages_recovery_period(&new_period);
7056 
7057 	if (is_recovery_enabled &&
7058 	    (!was_recovery_enabled || old_period > new_period)) {
7059 		struct kvm *kvm;
7060 
7061 		mutex_lock(&kvm_lock);
7062 
7063 		list_for_each_entry(kvm, &vm_list, vm_list)
7064 			wake_up_process(kvm->arch.nx_huge_page_recovery_thread);
7065 
7066 		mutex_unlock(&kvm_lock);
7067 	}
7068 
7069 	return err;
7070 }
7071 
7072 static void kvm_recover_nx_huge_pages(struct kvm *kvm)
7073 {
7074 	unsigned long nx_lpage_splits = kvm->stat.nx_lpage_splits;
7075 	struct kvm_memory_slot *slot;
7076 	int rcu_idx;
7077 	struct kvm_mmu_page *sp;
7078 	unsigned int ratio;
7079 	LIST_HEAD(invalid_list);
7080 	bool flush = false;
7081 	ulong to_zap;
7082 
7083 	rcu_idx = srcu_read_lock(&kvm->srcu);
7084 	write_lock(&kvm->mmu_lock);
7085 
7086 	/*
7087 	 * Zapping TDP MMU shadow pages, including the remote TLB flush, must
7088 	 * be done under RCU protection, because the pages are freed via RCU
7089 	 * callback.
7090 	 */
7091 	rcu_read_lock();
7092 
7093 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
7094 	to_zap = ratio ? DIV_ROUND_UP(nx_lpage_splits, ratio) : 0;
7095 	for ( ; to_zap; --to_zap) {
7096 		if (list_empty(&kvm->arch.possible_nx_huge_pages))
7097 			break;
7098 
7099 		/*
7100 		 * We use a separate list instead of just using active_mmu_pages
7101 		 * because the number of shadow pages that be replaced with an
7102 		 * NX huge page is expected to be relatively small compared to
7103 		 * the total number of shadow pages.  And because the TDP MMU
7104 		 * doesn't use active_mmu_pages.
7105 		 */
7106 		sp = list_first_entry(&kvm->arch.possible_nx_huge_pages,
7107 				      struct kvm_mmu_page,
7108 				      possible_nx_huge_page_link);
7109 		WARN_ON_ONCE(!sp->nx_huge_page_disallowed);
7110 		WARN_ON_ONCE(!sp->role.direct);
7111 
7112 		/*
7113 		 * Unaccount and do not attempt to recover any NX Huge Pages
7114 		 * that are being dirty tracked, as they would just be faulted
7115 		 * back in as 4KiB pages. The NX Huge Pages in this slot will be
7116 		 * recovered, along with all the other huge pages in the slot,
7117 		 * when dirty logging is disabled.
7118 		 *
7119 		 * Since gfn_to_memslot() is relatively expensive, it helps to
7120 		 * skip it if it the test cannot possibly return true.  On the
7121 		 * other hand, if any memslot has logging enabled, chances are
7122 		 * good that all of them do, in which case unaccount_nx_huge_page()
7123 		 * is much cheaper than zapping the page.
7124 		 *
7125 		 * If a memslot update is in progress, reading an incorrect value
7126 		 * of kvm->nr_memslots_dirty_logging is not a problem: if it is
7127 		 * becoming zero, gfn_to_memslot() will be done unnecessarily; if
7128 		 * it is becoming nonzero, the page will be zapped unnecessarily.
7129 		 * Either way, this only affects efficiency in racy situations,
7130 		 * and not correctness.
7131 		 */
7132 		slot = NULL;
7133 		if (atomic_read(&kvm->nr_memslots_dirty_logging)) {
7134 			struct kvm_memslots *slots;
7135 
7136 			slots = kvm_memslots_for_spte_role(kvm, sp->role);
7137 			slot = __gfn_to_memslot(slots, sp->gfn);
7138 			WARN_ON_ONCE(!slot);
7139 		}
7140 
7141 		if (slot && kvm_slot_dirty_track_enabled(slot))
7142 			unaccount_nx_huge_page(kvm, sp);
7143 		else if (is_tdp_mmu_page(sp))
7144 			flush |= kvm_tdp_mmu_zap_sp(kvm, sp);
7145 		else
7146 			kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
7147 		WARN_ON_ONCE(sp->nx_huge_page_disallowed);
7148 
7149 		if (need_resched() || rwlock_needbreak(&kvm->mmu_lock)) {
7150 			kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7151 			rcu_read_unlock();
7152 
7153 			cond_resched_rwlock_write(&kvm->mmu_lock);
7154 			flush = false;
7155 
7156 			rcu_read_lock();
7157 		}
7158 	}
7159 	kvm_mmu_remote_flush_or_zap(kvm, &invalid_list, flush);
7160 
7161 	rcu_read_unlock();
7162 
7163 	write_unlock(&kvm->mmu_lock);
7164 	srcu_read_unlock(&kvm->srcu, rcu_idx);
7165 }
7166 
7167 static long get_nx_huge_page_recovery_timeout(u64 start_time)
7168 {
7169 	bool enabled;
7170 	uint period;
7171 
7172 	enabled = calc_nx_huge_pages_recovery_period(&period);
7173 
7174 	return enabled ? start_time + msecs_to_jiffies(period) - get_jiffies_64()
7175 		       : MAX_SCHEDULE_TIMEOUT;
7176 }
7177 
7178 static int kvm_nx_huge_page_recovery_worker(struct kvm *kvm, uintptr_t data)
7179 {
7180 	u64 start_time;
7181 	long remaining_time;
7182 
7183 	while (true) {
7184 		start_time = get_jiffies_64();
7185 		remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7186 
7187 		set_current_state(TASK_INTERRUPTIBLE);
7188 		while (!kthread_should_stop() && remaining_time > 0) {
7189 			schedule_timeout(remaining_time);
7190 			remaining_time = get_nx_huge_page_recovery_timeout(start_time);
7191 			set_current_state(TASK_INTERRUPTIBLE);
7192 		}
7193 
7194 		set_current_state(TASK_RUNNING);
7195 
7196 		if (kthread_should_stop())
7197 			return 0;
7198 
7199 		kvm_recover_nx_huge_pages(kvm);
7200 	}
7201 }
7202 
7203 int kvm_mmu_post_init_vm(struct kvm *kvm)
7204 {
7205 	int err;
7206 
7207 	if (nx_hugepage_mitigation_hard_disabled)
7208 		return 0;
7209 
7210 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_huge_page_recovery_worker, 0,
7211 					  "kvm-nx-lpage-recovery",
7212 					  &kvm->arch.nx_huge_page_recovery_thread);
7213 	if (!err)
7214 		kthread_unpark(kvm->arch.nx_huge_page_recovery_thread);
7215 
7216 	return err;
7217 }
7218 
7219 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
7220 {
7221 	if (kvm->arch.nx_huge_page_recovery_thread)
7222 		kthread_stop(kvm->arch.nx_huge_page_recovery_thread);
7223 }
7224