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