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