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