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