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