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