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