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