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