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