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