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