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