xref: /openbmc/linux/arch/x86/kvm/mmu/mmu.c (revision 7af6fbdd)
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 			unsigned flags)
1921 {
1922 	return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1923 }
1924 
1925 int kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1926 {
1927 	return kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1928 }
1929 
1930 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1931 			 struct kvm_memory_slot *slot, gfn_t gfn, int level,
1932 			 unsigned long data)
1933 {
1934 	u64 *sptep;
1935 	struct rmap_iterator iter;
1936 	int young = 0;
1937 
1938 	for_each_rmap_spte(rmap_head, &iter, sptep)
1939 		young |= mmu_spte_age(sptep);
1940 
1941 	trace_kvm_age_page(gfn, level, slot, young);
1942 	return young;
1943 }
1944 
1945 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1946 			      struct kvm_memory_slot *slot, gfn_t gfn,
1947 			      int level, unsigned long data)
1948 {
1949 	u64 *sptep;
1950 	struct rmap_iterator iter;
1951 
1952 	for_each_rmap_spte(rmap_head, &iter, sptep)
1953 		if (is_accessed_spte(*sptep))
1954 			return 1;
1955 	return 0;
1956 }
1957 
1958 #define RMAP_RECYCLE_THRESHOLD 1000
1959 
1960 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1961 {
1962 	struct kvm_rmap_head *rmap_head;
1963 	struct kvm_mmu_page *sp;
1964 
1965 	sp = sptep_to_sp(spte);
1966 
1967 	rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1968 
1969 	kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
1970 	kvm_flush_remote_tlbs_with_address(vcpu->kvm, sp->gfn,
1971 			KVM_PAGES_PER_HPAGE(sp->role.level));
1972 }
1973 
1974 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
1975 {
1976 	return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
1977 }
1978 
1979 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
1980 {
1981 	return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
1982 }
1983 
1984 #ifdef MMU_DEBUG
1985 static int is_empty_shadow_page(u64 *spt)
1986 {
1987 	u64 *pos;
1988 	u64 *end;
1989 
1990 	for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
1991 		if (is_shadow_present_pte(*pos)) {
1992 			printk(KERN_ERR "%s: %p %llx\n", __func__,
1993 			       pos, *pos);
1994 			return 0;
1995 		}
1996 	return 1;
1997 }
1998 #endif
1999 
2000 /*
2001  * This value is the sum of all of the kvm instances's
2002  * kvm->arch.n_used_mmu_pages values.  We need a global,
2003  * aggregate version in order to make the slab shrinker
2004  * faster
2005  */
2006 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, unsigned long nr)
2007 {
2008 	kvm->arch.n_used_mmu_pages += nr;
2009 	percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2010 }
2011 
2012 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2013 {
2014 	MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2015 	hlist_del(&sp->hash_link);
2016 	list_del(&sp->link);
2017 	free_page((unsigned long)sp->spt);
2018 	if (!sp->role.direct)
2019 		free_page((unsigned long)sp->gfns);
2020 	kmem_cache_free(mmu_page_header_cache, sp);
2021 }
2022 
2023 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2024 {
2025 	return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2026 }
2027 
2028 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2029 				    struct kvm_mmu_page *sp, u64 *parent_pte)
2030 {
2031 	if (!parent_pte)
2032 		return;
2033 
2034 	pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2035 }
2036 
2037 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2038 				       u64 *parent_pte)
2039 {
2040 	__pte_list_remove(parent_pte, &sp->parent_ptes);
2041 }
2042 
2043 static void drop_parent_pte(struct kvm_mmu_page *sp,
2044 			    u64 *parent_pte)
2045 {
2046 	mmu_page_remove_parent_pte(sp, parent_pte);
2047 	mmu_spte_clear_no_track(parent_pte);
2048 }
2049 
2050 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2051 {
2052 	struct kvm_mmu_page *sp;
2053 
2054 	sp = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2055 	sp->spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_shadow_page_cache);
2056 	if (!direct)
2057 		sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
2058 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2059 
2060 	/*
2061 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
2062 	 * depends on valid pages being added to the head of the list.  See
2063 	 * comments in kvm_zap_obsolete_pages().
2064 	 */
2065 	sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2066 	list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2067 	kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2068 	return sp;
2069 }
2070 
2071 static void mark_unsync(u64 *spte);
2072 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2073 {
2074 	u64 *sptep;
2075 	struct rmap_iterator iter;
2076 
2077 	for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2078 		mark_unsync(sptep);
2079 	}
2080 }
2081 
2082 static void mark_unsync(u64 *spte)
2083 {
2084 	struct kvm_mmu_page *sp;
2085 	unsigned int index;
2086 
2087 	sp = sptep_to_sp(spte);
2088 	index = spte - sp->spt;
2089 	if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2090 		return;
2091 	if (sp->unsync_children++)
2092 		return;
2093 	kvm_mmu_mark_parents_unsync(sp);
2094 }
2095 
2096 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2097 			       struct kvm_mmu_page *sp)
2098 {
2099 	return 0;
2100 }
2101 
2102 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2103 				 struct kvm_mmu_page *sp, u64 *spte,
2104 				 const void *pte)
2105 {
2106 	WARN_ON(1);
2107 }
2108 
2109 #define KVM_PAGE_ARRAY_NR 16
2110 
2111 struct kvm_mmu_pages {
2112 	struct mmu_page_and_offset {
2113 		struct kvm_mmu_page *sp;
2114 		unsigned int idx;
2115 	} page[KVM_PAGE_ARRAY_NR];
2116 	unsigned int nr;
2117 };
2118 
2119 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2120 			 int idx)
2121 {
2122 	int i;
2123 
2124 	if (sp->unsync)
2125 		for (i=0; i < pvec->nr; i++)
2126 			if (pvec->page[i].sp == sp)
2127 				return 0;
2128 
2129 	pvec->page[pvec->nr].sp = sp;
2130 	pvec->page[pvec->nr].idx = idx;
2131 	pvec->nr++;
2132 	return (pvec->nr == KVM_PAGE_ARRAY_NR);
2133 }
2134 
2135 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2136 {
2137 	--sp->unsync_children;
2138 	WARN_ON((int)sp->unsync_children < 0);
2139 	__clear_bit(idx, sp->unsync_child_bitmap);
2140 }
2141 
2142 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2143 			   struct kvm_mmu_pages *pvec)
2144 {
2145 	int i, ret, nr_unsync_leaf = 0;
2146 
2147 	for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2148 		struct kvm_mmu_page *child;
2149 		u64 ent = sp->spt[i];
2150 
2151 		if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2152 			clear_unsync_child_bit(sp, i);
2153 			continue;
2154 		}
2155 
2156 		child = to_shadow_page(ent & PT64_BASE_ADDR_MASK);
2157 
2158 		if (child->unsync_children) {
2159 			if (mmu_pages_add(pvec, child, i))
2160 				return -ENOSPC;
2161 
2162 			ret = __mmu_unsync_walk(child, pvec);
2163 			if (!ret) {
2164 				clear_unsync_child_bit(sp, i);
2165 				continue;
2166 			} else if (ret > 0) {
2167 				nr_unsync_leaf += ret;
2168 			} else
2169 				return ret;
2170 		} else if (child->unsync) {
2171 			nr_unsync_leaf++;
2172 			if (mmu_pages_add(pvec, child, i))
2173 				return -ENOSPC;
2174 		} else
2175 			clear_unsync_child_bit(sp, i);
2176 	}
2177 
2178 	return nr_unsync_leaf;
2179 }
2180 
2181 #define INVALID_INDEX (-1)
2182 
2183 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2184 			   struct kvm_mmu_pages *pvec)
2185 {
2186 	pvec->nr = 0;
2187 	if (!sp->unsync_children)
2188 		return 0;
2189 
2190 	mmu_pages_add(pvec, sp, INVALID_INDEX);
2191 	return __mmu_unsync_walk(sp, pvec);
2192 }
2193 
2194 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2195 {
2196 	WARN_ON(!sp->unsync);
2197 	trace_kvm_mmu_sync_page(sp);
2198 	sp->unsync = 0;
2199 	--kvm->stat.mmu_unsync;
2200 }
2201 
2202 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2203 				     struct list_head *invalid_list);
2204 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2205 				    struct list_head *invalid_list);
2206 
2207 #define for_each_valid_sp(_kvm, _sp, _list)				\
2208 	hlist_for_each_entry(_sp, _list, hash_link)			\
2209 		if (is_obsolete_sp((_kvm), (_sp))) {			\
2210 		} else
2211 
2212 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn)			\
2213 	for_each_valid_sp(_kvm, _sp,					\
2214 	  &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)])	\
2215 		if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2216 
2217 static inline bool is_ept_sp(struct kvm_mmu_page *sp)
2218 {
2219 	return sp->role.cr0_wp && sp->role.smap_andnot_wp;
2220 }
2221 
2222 /* @sp->gfn should be write-protected at the call site */
2223 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2224 			    struct list_head *invalid_list)
2225 {
2226 	if ((!is_ept_sp(sp) && sp->role.gpte_is_8_bytes != !!is_pae(vcpu)) ||
2227 	    vcpu->arch.mmu->sync_page(vcpu, sp) == 0) {
2228 		kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2229 		return false;
2230 	}
2231 
2232 	return true;
2233 }
2234 
2235 static bool kvm_mmu_remote_flush_or_zap(struct kvm *kvm,
2236 					struct list_head *invalid_list,
2237 					bool remote_flush)
2238 {
2239 	if (!remote_flush && list_empty(invalid_list))
2240 		return false;
2241 
2242 	if (!list_empty(invalid_list))
2243 		kvm_mmu_commit_zap_page(kvm, invalid_list);
2244 	else
2245 		kvm_flush_remote_tlbs(kvm);
2246 	return true;
2247 }
2248 
2249 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2250 				 struct list_head *invalid_list,
2251 				 bool remote_flush, bool local_flush)
2252 {
2253 	if (kvm_mmu_remote_flush_or_zap(vcpu->kvm, invalid_list, remote_flush))
2254 		return;
2255 
2256 	if (local_flush)
2257 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2258 }
2259 
2260 #ifdef CONFIG_KVM_MMU_AUDIT
2261 #include "mmu_audit.c"
2262 #else
2263 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2264 static void mmu_audit_disable(void) { }
2265 #endif
2266 
2267 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2268 {
2269 	return sp->role.invalid ||
2270 	       unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2271 }
2272 
2273 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2274 			 struct list_head *invalid_list)
2275 {
2276 	kvm_unlink_unsync_page(vcpu->kvm, sp);
2277 	return __kvm_sync_page(vcpu, sp, invalid_list);
2278 }
2279 
2280 /* @gfn should be write-protected at the call site */
2281 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2282 			   struct list_head *invalid_list)
2283 {
2284 	struct kvm_mmu_page *s;
2285 	bool ret = false;
2286 
2287 	for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2288 		if (!s->unsync)
2289 			continue;
2290 
2291 		WARN_ON(s->role.level != PG_LEVEL_4K);
2292 		ret |= kvm_sync_page(vcpu, s, invalid_list);
2293 	}
2294 
2295 	return ret;
2296 }
2297 
2298 struct mmu_page_path {
2299 	struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2300 	unsigned int idx[PT64_ROOT_MAX_LEVEL];
2301 };
2302 
2303 #define for_each_sp(pvec, sp, parents, i)			\
2304 		for (i = mmu_pages_first(&pvec, &parents);	\
2305 			i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});	\
2306 			i = mmu_pages_next(&pvec, &parents, i))
2307 
2308 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2309 			  struct mmu_page_path *parents,
2310 			  int i)
2311 {
2312 	int n;
2313 
2314 	for (n = i+1; n < pvec->nr; n++) {
2315 		struct kvm_mmu_page *sp = pvec->page[n].sp;
2316 		unsigned idx = pvec->page[n].idx;
2317 		int level = sp->role.level;
2318 
2319 		parents->idx[level-1] = idx;
2320 		if (level == PG_LEVEL_4K)
2321 			break;
2322 
2323 		parents->parent[level-2] = sp;
2324 	}
2325 
2326 	return n;
2327 }
2328 
2329 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2330 			   struct mmu_page_path *parents)
2331 {
2332 	struct kvm_mmu_page *sp;
2333 	int level;
2334 
2335 	if (pvec->nr == 0)
2336 		return 0;
2337 
2338 	WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2339 
2340 	sp = pvec->page[0].sp;
2341 	level = sp->role.level;
2342 	WARN_ON(level == PG_LEVEL_4K);
2343 
2344 	parents->parent[level-2] = sp;
2345 
2346 	/* Also set up a sentinel.  Further entries in pvec are all
2347 	 * children of sp, so this element is never overwritten.
2348 	 */
2349 	parents->parent[level-1] = NULL;
2350 	return mmu_pages_next(pvec, parents, 0);
2351 }
2352 
2353 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2354 {
2355 	struct kvm_mmu_page *sp;
2356 	unsigned int level = 0;
2357 
2358 	do {
2359 		unsigned int idx = parents->idx[level];
2360 		sp = parents->parent[level];
2361 		if (!sp)
2362 			return;
2363 
2364 		WARN_ON(idx == INVALID_INDEX);
2365 		clear_unsync_child_bit(sp, idx);
2366 		level++;
2367 	} while (!sp->unsync_children);
2368 }
2369 
2370 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2371 			      struct kvm_mmu_page *parent)
2372 {
2373 	int i;
2374 	struct kvm_mmu_page *sp;
2375 	struct mmu_page_path parents;
2376 	struct kvm_mmu_pages pages;
2377 	LIST_HEAD(invalid_list);
2378 	bool flush = false;
2379 
2380 	while (mmu_unsync_walk(parent, &pages)) {
2381 		bool protected = false;
2382 
2383 		for_each_sp(pages, sp, parents, i)
2384 			protected |= rmap_write_protect(vcpu, sp->gfn);
2385 
2386 		if (protected) {
2387 			kvm_flush_remote_tlbs(vcpu->kvm);
2388 			flush = false;
2389 		}
2390 
2391 		for_each_sp(pages, sp, parents, i) {
2392 			flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2393 			mmu_pages_clear_parents(&parents);
2394 		}
2395 		if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2396 			kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2397 			cond_resched_lock(&vcpu->kvm->mmu_lock);
2398 			flush = false;
2399 		}
2400 	}
2401 
2402 	kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2403 }
2404 
2405 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2406 {
2407 	atomic_set(&sp->write_flooding_count,  0);
2408 }
2409 
2410 static void clear_sp_write_flooding_count(u64 *spte)
2411 {
2412 	__clear_sp_write_flooding_count(sptep_to_sp(spte));
2413 }
2414 
2415 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2416 					     gfn_t gfn,
2417 					     gva_t gaddr,
2418 					     unsigned level,
2419 					     int direct,
2420 					     unsigned int access)
2421 {
2422 	bool direct_mmu = vcpu->arch.mmu->direct_map;
2423 	union kvm_mmu_page_role role;
2424 	struct hlist_head *sp_list;
2425 	unsigned quadrant;
2426 	struct kvm_mmu_page *sp;
2427 	bool need_sync = false;
2428 	bool flush = false;
2429 	int collisions = 0;
2430 	LIST_HEAD(invalid_list);
2431 
2432 	role = vcpu->arch.mmu->mmu_role.base;
2433 	role.level = level;
2434 	role.direct = direct;
2435 	if (role.direct)
2436 		role.gpte_is_8_bytes = true;
2437 	role.access = access;
2438 	if (!direct_mmu && vcpu->arch.mmu->root_level <= PT32_ROOT_LEVEL) {
2439 		quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2440 		quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2441 		role.quadrant = quadrant;
2442 	}
2443 
2444 	sp_list = &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)];
2445 	for_each_valid_sp(vcpu->kvm, sp, sp_list) {
2446 		if (sp->gfn != gfn) {
2447 			collisions++;
2448 			continue;
2449 		}
2450 
2451 		if (!need_sync && sp->unsync)
2452 			need_sync = true;
2453 
2454 		if (sp->role.word != role.word)
2455 			continue;
2456 
2457 		if (direct_mmu)
2458 			goto trace_get_page;
2459 
2460 		if (sp->unsync) {
2461 			/* The page is good, but __kvm_sync_page might still end
2462 			 * up zapping it.  If so, break in order to rebuild it.
2463 			 */
2464 			if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2465 				break;
2466 
2467 			WARN_ON(!list_empty(&invalid_list));
2468 			kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
2469 		}
2470 
2471 		if (sp->unsync_children)
2472 			kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2473 
2474 		__clear_sp_write_flooding_count(sp);
2475 
2476 trace_get_page:
2477 		trace_kvm_mmu_get_page(sp, false);
2478 		goto out;
2479 	}
2480 
2481 	++vcpu->kvm->stat.mmu_cache_miss;
2482 
2483 	sp = kvm_mmu_alloc_page(vcpu, direct);
2484 
2485 	sp->gfn = gfn;
2486 	sp->role = role;
2487 	hlist_add_head(&sp->hash_link, sp_list);
2488 	if (!direct) {
2489 		/*
2490 		 * we should do write protection before syncing pages
2491 		 * otherwise the content of the synced shadow page may
2492 		 * be inconsistent with guest page table.
2493 		 */
2494 		account_shadowed(vcpu->kvm, sp);
2495 		if (level == PG_LEVEL_4K && rmap_write_protect(vcpu, gfn))
2496 			kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn, 1);
2497 
2498 		if (level > PG_LEVEL_4K && need_sync)
2499 			flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2500 	}
2501 	trace_kvm_mmu_get_page(sp, true);
2502 
2503 	kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2504 out:
2505 	if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2506 		vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2507 	return sp;
2508 }
2509 
2510 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2511 					struct kvm_vcpu *vcpu, hpa_t root,
2512 					u64 addr)
2513 {
2514 	iterator->addr = addr;
2515 	iterator->shadow_addr = root;
2516 	iterator->level = vcpu->arch.mmu->shadow_root_level;
2517 
2518 	if (iterator->level == PT64_ROOT_4LEVEL &&
2519 	    vcpu->arch.mmu->root_level < PT64_ROOT_4LEVEL &&
2520 	    !vcpu->arch.mmu->direct_map)
2521 		--iterator->level;
2522 
2523 	if (iterator->level == PT32E_ROOT_LEVEL) {
2524 		/*
2525 		 * prev_root is currently only used for 64-bit hosts. So only
2526 		 * the active root_hpa is valid here.
2527 		 */
2528 		BUG_ON(root != vcpu->arch.mmu->root_hpa);
2529 
2530 		iterator->shadow_addr
2531 			= vcpu->arch.mmu->pae_root[(addr >> 30) & 3];
2532 		iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2533 		--iterator->level;
2534 		if (!iterator->shadow_addr)
2535 			iterator->level = 0;
2536 	}
2537 }
2538 
2539 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2540 			     struct kvm_vcpu *vcpu, u64 addr)
2541 {
2542 	shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu->root_hpa,
2543 				    addr);
2544 }
2545 
2546 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2547 {
2548 	if (iterator->level < PG_LEVEL_4K)
2549 		return false;
2550 
2551 	iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2552 	iterator->sptep	= ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2553 	return true;
2554 }
2555 
2556 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2557 			       u64 spte)
2558 {
2559 	if (is_last_spte(spte, iterator->level)) {
2560 		iterator->level = 0;
2561 		return;
2562 	}
2563 
2564 	iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2565 	--iterator->level;
2566 }
2567 
2568 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2569 {
2570 	__shadow_walk_next(iterator, *iterator->sptep);
2571 }
2572 
2573 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2574 			     struct kvm_mmu_page *sp)
2575 {
2576 	u64 spte;
2577 
2578 	BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2579 
2580 	spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2581 	       shadow_user_mask | shadow_x_mask | shadow_me_mask;
2582 
2583 	if (sp_ad_disabled(sp))
2584 		spte |= SPTE_AD_DISABLED_MASK;
2585 	else
2586 		spte |= shadow_accessed_mask;
2587 
2588 	mmu_spte_set(sptep, spte);
2589 
2590 	mmu_page_add_parent_pte(vcpu, sp, sptep);
2591 
2592 	if (sp->unsync_children || sp->unsync)
2593 		mark_unsync(sptep);
2594 }
2595 
2596 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2597 				   unsigned direct_access)
2598 {
2599 	if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2600 		struct kvm_mmu_page *child;
2601 
2602 		/*
2603 		 * For the direct sp, if the guest pte's dirty bit
2604 		 * changed form clean to dirty, it will corrupt the
2605 		 * sp's access: allow writable in the read-only sp,
2606 		 * so we should update the spte at this point to get
2607 		 * a new sp with the correct access.
2608 		 */
2609 		child = to_shadow_page(*sptep & PT64_BASE_ADDR_MASK);
2610 		if (child->role.access == direct_access)
2611 			return;
2612 
2613 		drop_parent_pte(child, sptep);
2614 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, child->gfn, 1);
2615 	}
2616 }
2617 
2618 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2619 			     u64 *spte)
2620 {
2621 	u64 pte;
2622 	struct kvm_mmu_page *child;
2623 
2624 	pte = *spte;
2625 	if (is_shadow_present_pte(pte)) {
2626 		if (is_last_spte(pte, sp->role.level)) {
2627 			drop_spte(kvm, spte);
2628 			if (is_large_pte(pte))
2629 				--kvm->stat.lpages;
2630 		} else {
2631 			child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
2632 			drop_parent_pte(child, spte);
2633 		}
2634 		return true;
2635 	}
2636 
2637 	if (is_mmio_spte(pte))
2638 		mmu_spte_clear_no_track(spte);
2639 
2640 	return false;
2641 }
2642 
2643 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2644 					 struct kvm_mmu_page *sp)
2645 {
2646 	unsigned i;
2647 
2648 	for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2649 		mmu_page_zap_pte(kvm, sp, sp->spt + i);
2650 }
2651 
2652 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2653 {
2654 	u64 *sptep;
2655 	struct rmap_iterator iter;
2656 
2657 	while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2658 		drop_parent_pte(sp, sptep);
2659 }
2660 
2661 static int mmu_zap_unsync_children(struct kvm *kvm,
2662 				   struct kvm_mmu_page *parent,
2663 				   struct list_head *invalid_list)
2664 {
2665 	int i, zapped = 0;
2666 	struct mmu_page_path parents;
2667 	struct kvm_mmu_pages pages;
2668 
2669 	if (parent->role.level == PG_LEVEL_4K)
2670 		return 0;
2671 
2672 	while (mmu_unsync_walk(parent, &pages)) {
2673 		struct kvm_mmu_page *sp;
2674 
2675 		for_each_sp(pages, sp, parents, i) {
2676 			kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2677 			mmu_pages_clear_parents(&parents);
2678 			zapped++;
2679 		}
2680 	}
2681 
2682 	return zapped;
2683 }
2684 
2685 static bool __kvm_mmu_prepare_zap_page(struct kvm *kvm,
2686 				       struct kvm_mmu_page *sp,
2687 				       struct list_head *invalid_list,
2688 				       int *nr_zapped)
2689 {
2690 	bool list_unstable;
2691 
2692 	trace_kvm_mmu_prepare_zap_page(sp);
2693 	++kvm->stat.mmu_shadow_zapped;
2694 	*nr_zapped = mmu_zap_unsync_children(kvm, sp, invalid_list);
2695 	kvm_mmu_page_unlink_children(kvm, sp);
2696 	kvm_mmu_unlink_parents(kvm, sp);
2697 
2698 	/* Zapping children means active_mmu_pages has become unstable. */
2699 	list_unstable = *nr_zapped;
2700 
2701 	if (!sp->role.invalid && !sp->role.direct)
2702 		unaccount_shadowed(kvm, sp);
2703 
2704 	if (sp->unsync)
2705 		kvm_unlink_unsync_page(kvm, sp);
2706 	if (!sp->root_count) {
2707 		/* Count self */
2708 		(*nr_zapped)++;
2709 
2710 		/*
2711 		 * Already invalid pages (previously active roots) are not on
2712 		 * the active page list.  See list_del() in the "else" case of
2713 		 * !sp->root_count.
2714 		 */
2715 		if (sp->role.invalid)
2716 			list_add(&sp->link, invalid_list);
2717 		else
2718 			list_move(&sp->link, invalid_list);
2719 		kvm_mod_used_mmu_pages(kvm, -1);
2720 	} else {
2721 		/*
2722 		 * Remove the active root from the active page list, the root
2723 		 * will be explicitly freed when the root_count hits zero.
2724 		 */
2725 		list_del(&sp->link);
2726 
2727 		/*
2728 		 * Obsolete pages cannot be used on any vCPUs, see the comment
2729 		 * in kvm_mmu_zap_all_fast().  Note, is_obsolete_sp() also
2730 		 * treats invalid shadow pages as being obsolete.
2731 		 */
2732 		if (!is_obsolete_sp(kvm, sp))
2733 			kvm_reload_remote_mmus(kvm);
2734 	}
2735 
2736 	if (sp->lpage_disallowed)
2737 		unaccount_huge_nx_page(kvm, sp);
2738 
2739 	sp->role.invalid = 1;
2740 	return list_unstable;
2741 }
2742 
2743 static bool kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2744 				     struct list_head *invalid_list)
2745 {
2746 	int nr_zapped;
2747 
2748 	__kvm_mmu_prepare_zap_page(kvm, sp, invalid_list, &nr_zapped);
2749 	return nr_zapped;
2750 }
2751 
2752 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2753 				    struct list_head *invalid_list)
2754 {
2755 	struct kvm_mmu_page *sp, *nsp;
2756 
2757 	if (list_empty(invalid_list))
2758 		return;
2759 
2760 	/*
2761 	 * We need to make sure everyone sees our modifications to
2762 	 * the page tables and see changes to vcpu->mode here. The barrier
2763 	 * in the kvm_flush_remote_tlbs() achieves this. This pairs
2764 	 * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2765 	 *
2766 	 * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2767 	 * guest mode and/or lockless shadow page table walks.
2768 	 */
2769 	kvm_flush_remote_tlbs(kvm);
2770 
2771 	list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2772 		WARN_ON(!sp->role.invalid || sp->root_count);
2773 		kvm_mmu_free_page(sp);
2774 	}
2775 }
2776 
2777 static unsigned long kvm_mmu_zap_oldest_mmu_pages(struct kvm *kvm,
2778 						  unsigned long nr_to_zap)
2779 {
2780 	unsigned long total_zapped = 0;
2781 	struct kvm_mmu_page *sp, *tmp;
2782 	LIST_HEAD(invalid_list);
2783 	bool unstable;
2784 	int nr_zapped;
2785 
2786 	if (list_empty(&kvm->arch.active_mmu_pages))
2787 		return 0;
2788 
2789 restart:
2790 	list_for_each_entry_safe(sp, tmp, &kvm->arch.active_mmu_pages, link) {
2791 		/*
2792 		 * Don't zap active root pages, the page itself can't be freed
2793 		 * and zapping it will just force vCPUs to realloc and reload.
2794 		 */
2795 		if (sp->root_count)
2796 			continue;
2797 
2798 		unstable = __kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list,
2799 						      &nr_zapped);
2800 		total_zapped += nr_zapped;
2801 		if (total_zapped >= nr_to_zap)
2802 			break;
2803 
2804 		if (unstable)
2805 			goto restart;
2806 	}
2807 
2808 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2809 
2810 	kvm->stat.mmu_recycled += total_zapped;
2811 	return total_zapped;
2812 }
2813 
2814 static inline unsigned long kvm_mmu_available_pages(struct kvm *kvm)
2815 {
2816 	if (kvm->arch.n_max_mmu_pages > kvm->arch.n_used_mmu_pages)
2817 		return kvm->arch.n_max_mmu_pages -
2818 			kvm->arch.n_used_mmu_pages;
2819 
2820 	return 0;
2821 }
2822 
2823 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
2824 {
2825 	unsigned long avail = kvm_mmu_available_pages(vcpu->kvm);
2826 
2827 	if (likely(avail >= KVM_MIN_FREE_MMU_PAGES))
2828 		return 0;
2829 
2830 	kvm_mmu_zap_oldest_mmu_pages(vcpu->kvm, KVM_REFILL_PAGES - avail);
2831 
2832 	if (!kvm_mmu_available_pages(vcpu->kvm))
2833 		return -ENOSPC;
2834 	return 0;
2835 }
2836 
2837 /*
2838  * Changing the number of mmu pages allocated to the vm
2839  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2840  */
2841 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2842 {
2843 	spin_lock(&kvm->mmu_lock);
2844 
2845 	if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2846 		kvm_mmu_zap_oldest_mmu_pages(kvm, kvm->arch.n_used_mmu_pages -
2847 						  goal_nr_mmu_pages);
2848 
2849 		goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2850 	}
2851 
2852 	kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2853 
2854 	spin_unlock(&kvm->mmu_lock);
2855 }
2856 
2857 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2858 {
2859 	struct kvm_mmu_page *sp;
2860 	LIST_HEAD(invalid_list);
2861 	int r;
2862 
2863 	pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2864 	r = 0;
2865 	spin_lock(&kvm->mmu_lock);
2866 	for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2867 		pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2868 			 sp->role.word);
2869 		r = 1;
2870 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2871 	}
2872 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
2873 	spin_unlock(&kvm->mmu_lock);
2874 
2875 	return r;
2876 }
2877 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2878 
2879 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2880 {
2881 	trace_kvm_mmu_unsync_page(sp);
2882 	++vcpu->kvm->stat.mmu_unsync;
2883 	sp->unsync = 1;
2884 
2885 	kvm_mmu_mark_parents_unsync(sp);
2886 }
2887 
2888 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2889 				   bool can_unsync)
2890 {
2891 	struct kvm_mmu_page *sp;
2892 
2893 	if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2894 		return true;
2895 
2896 	for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2897 		if (!can_unsync)
2898 			return true;
2899 
2900 		if (sp->unsync)
2901 			continue;
2902 
2903 		WARN_ON(sp->role.level != PG_LEVEL_4K);
2904 		kvm_unsync_page(vcpu, sp);
2905 	}
2906 
2907 	/*
2908 	 * We need to ensure that the marking of unsync pages is visible
2909 	 * before the SPTE is updated to allow writes because
2910 	 * kvm_mmu_sync_roots() checks the unsync flags without holding
2911 	 * the MMU lock and so can race with this. If the SPTE was updated
2912 	 * before the page had been marked as unsync-ed, something like the
2913 	 * following could happen:
2914 	 *
2915 	 * CPU 1                    CPU 2
2916 	 * ---------------------------------------------------------------------
2917 	 * 1.2 Host updates SPTE
2918 	 *     to be writable
2919 	 *                      2.1 Guest writes a GPTE for GVA X.
2920 	 *                          (GPTE being in the guest page table shadowed
2921 	 *                           by the SP from CPU 1.)
2922 	 *                          This reads SPTE during the page table walk.
2923 	 *                          Since SPTE.W is read as 1, there is no
2924 	 *                          fault.
2925 	 *
2926 	 *                      2.2 Guest issues TLB flush.
2927 	 *                          That causes a VM Exit.
2928 	 *
2929 	 *                      2.3 kvm_mmu_sync_pages() reads sp->unsync.
2930 	 *                          Since it is false, so it just returns.
2931 	 *
2932 	 *                      2.4 Guest accesses GVA X.
2933 	 *                          Since the mapping in the SP was not updated,
2934 	 *                          so the old mapping for GVA X incorrectly
2935 	 *                          gets used.
2936 	 * 1.1 Host marks SP
2937 	 *     as unsync
2938 	 *     (sp->unsync = true)
2939 	 *
2940 	 * The write barrier below ensures that 1.1 happens before 1.2 and thus
2941 	 * the situation in 2.4 does not arise. The implicit barrier in 2.2
2942 	 * pairs with this write barrier.
2943 	 */
2944 	smp_wmb();
2945 
2946 	return false;
2947 }
2948 
2949 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2950 {
2951 	if (pfn_valid(pfn))
2952 		return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2953 			/*
2954 			 * Some reserved pages, such as those from NVDIMM
2955 			 * DAX devices, are not for MMIO, and can be mapped
2956 			 * with cached memory type for better performance.
2957 			 * However, the above check misconceives those pages
2958 			 * as MMIO, and results in KVM mapping them with UC
2959 			 * memory type, which would hurt the performance.
2960 			 * Therefore, we check the host memory type in addition
2961 			 * and only treat UC/UC-/WC pages as MMIO.
2962 			 */
2963 			(!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2964 
2965 	return !e820__mapped_raw_any(pfn_to_hpa(pfn),
2966 				     pfn_to_hpa(pfn + 1) - 1,
2967 				     E820_TYPE_RAM);
2968 }
2969 
2970 /* Bits which may be returned by set_spte() */
2971 #define SET_SPTE_WRITE_PROTECTED_PT	BIT(0)
2972 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH	BIT(1)
2973 
2974 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2975 		    unsigned int pte_access, int level,
2976 		    gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2977 		    bool can_unsync, bool host_writable)
2978 {
2979 	u64 spte = 0;
2980 	int ret = 0;
2981 	struct kvm_mmu_page *sp;
2982 
2983 	if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2984 		return 0;
2985 
2986 	sp = sptep_to_sp(sptep);
2987 	if (sp_ad_disabled(sp))
2988 		spte |= SPTE_AD_DISABLED_MASK;
2989 	else if (kvm_vcpu_ad_need_write_protect(vcpu))
2990 		spte |= SPTE_AD_WRPROT_ONLY_MASK;
2991 
2992 	/*
2993 	 * For the EPT case, shadow_present_mask is 0 if hardware
2994 	 * supports exec-only page table entries.  In that case,
2995 	 * ACC_USER_MASK and shadow_user_mask are used to represent
2996 	 * read access.  See FNAME(gpte_access) in paging_tmpl.h.
2997 	 */
2998 	spte |= shadow_present_mask;
2999 	if (!speculative)
3000 		spte |= spte_shadow_accessed_mask(spte);
3001 
3002 	if (level > PG_LEVEL_4K && (pte_access & ACC_EXEC_MASK) &&
3003 	    is_nx_huge_page_enabled()) {
3004 		pte_access &= ~ACC_EXEC_MASK;
3005 	}
3006 
3007 	if (pte_access & ACC_EXEC_MASK)
3008 		spte |= shadow_x_mask;
3009 	else
3010 		spte |= shadow_nx_mask;
3011 
3012 	if (pte_access & ACC_USER_MASK)
3013 		spte |= shadow_user_mask;
3014 
3015 	if (level > PG_LEVEL_4K)
3016 		spte |= PT_PAGE_SIZE_MASK;
3017 	if (tdp_enabled)
3018 		spte |= kvm_x86_ops.get_mt_mask(vcpu, gfn,
3019 			kvm_is_mmio_pfn(pfn));
3020 
3021 	if (host_writable)
3022 		spte |= SPTE_HOST_WRITEABLE;
3023 	else
3024 		pte_access &= ~ACC_WRITE_MASK;
3025 
3026 	if (!kvm_is_mmio_pfn(pfn))
3027 		spte |= shadow_me_mask;
3028 
3029 	spte |= (u64)pfn << PAGE_SHIFT;
3030 
3031 	if (pte_access & ACC_WRITE_MASK) {
3032 		spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3033 
3034 		/*
3035 		 * Optimization: for pte sync, if spte was writable the hash
3036 		 * lookup is unnecessary (and expensive). Write protection
3037 		 * is responsibility of mmu_get_page / kvm_sync_page.
3038 		 * Same reasoning can be applied to dirty page accounting.
3039 		 */
3040 		if (!can_unsync && is_writable_pte(*sptep))
3041 			goto set_pte;
3042 
3043 		if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3044 			pgprintk("%s: found shadow page for %llx, marking ro\n",
3045 				 __func__, gfn);
3046 			ret |= SET_SPTE_WRITE_PROTECTED_PT;
3047 			pte_access &= ~ACC_WRITE_MASK;
3048 			spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3049 		}
3050 	}
3051 
3052 	if (pte_access & ACC_WRITE_MASK) {
3053 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
3054 		spte |= spte_shadow_dirty_mask(spte);
3055 	}
3056 
3057 	if (speculative)
3058 		spte = mark_spte_for_access_track(spte);
3059 
3060 set_pte:
3061 	if (mmu_spte_update(sptep, spte))
3062 		ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3063 	return ret;
3064 }
3065 
3066 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
3067 			unsigned int pte_access, int write_fault, int level,
3068 			gfn_t gfn, kvm_pfn_t pfn, bool speculative,
3069 			bool host_writable)
3070 {
3071 	int was_rmapped = 0;
3072 	int rmap_count;
3073 	int set_spte_ret;
3074 	int ret = RET_PF_RETRY;
3075 	bool flush = false;
3076 
3077 	pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3078 		 *sptep, write_fault, gfn);
3079 
3080 	if (is_shadow_present_pte(*sptep)) {
3081 		/*
3082 		 * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3083 		 * the parent of the now unreachable PTE.
3084 		 */
3085 		if (level > PG_LEVEL_4K && !is_large_pte(*sptep)) {
3086 			struct kvm_mmu_page *child;
3087 			u64 pte = *sptep;
3088 
3089 			child = to_shadow_page(pte & PT64_BASE_ADDR_MASK);
3090 			drop_parent_pte(child, sptep);
3091 			flush = true;
3092 		} else if (pfn != spte_to_pfn(*sptep)) {
3093 			pgprintk("hfn old %llx new %llx\n",
3094 				 spte_to_pfn(*sptep), pfn);
3095 			drop_spte(vcpu->kvm, sptep);
3096 			flush = true;
3097 		} else
3098 			was_rmapped = 1;
3099 	}
3100 
3101 	set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3102 				speculative, true, host_writable);
3103 	if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3104 		if (write_fault)
3105 			ret = RET_PF_EMULATE;
3106 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
3107 	}
3108 
3109 	if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3110 		kvm_flush_remote_tlbs_with_address(vcpu->kvm, gfn,
3111 				KVM_PAGES_PER_HPAGE(level));
3112 
3113 	if (unlikely(is_mmio_spte(*sptep)))
3114 		ret = RET_PF_EMULATE;
3115 
3116 	pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3117 	trace_kvm_mmu_set_spte(level, gfn, sptep);
3118 	if (!was_rmapped && is_large_pte(*sptep))
3119 		++vcpu->kvm->stat.lpages;
3120 
3121 	if (is_shadow_present_pte(*sptep)) {
3122 		if (!was_rmapped) {
3123 			rmap_count = rmap_add(vcpu, sptep, gfn);
3124 			if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3125 				rmap_recycle(vcpu, sptep, gfn);
3126 		}
3127 	}
3128 
3129 	return ret;
3130 }
3131 
3132 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3133 				     bool no_dirty_log)
3134 {
3135 	struct kvm_memory_slot *slot;
3136 
3137 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3138 	if (!slot)
3139 		return KVM_PFN_ERR_FAULT;
3140 
3141 	return gfn_to_pfn_memslot_atomic(slot, gfn);
3142 }
3143 
3144 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3145 				    struct kvm_mmu_page *sp,
3146 				    u64 *start, u64 *end)
3147 {
3148 	struct page *pages[PTE_PREFETCH_NUM];
3149 	struct kvm_memory_slot *slot;
3150 	unsigned int access = sp->role.access;
3151 	int i, ret;
3152 	gfn_t gfn;
3153 
3154 	gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3155 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3156 	if (!slot)
3157 		return -1;
3158 
3159 	ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3160 	if (ret <= 0)
3161 		return -1;
3162 
3163 	for (i = 0; i < ret; i++, gfn++, start++) {
3164 		mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3165 			     page_to_pfn(pages[i]), true, true);
3166 		put_page(pages[i]);
3167 	}
3168 
3169 	return 0;
3170 }
3171 
3172 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3173 				  struct kvm_mmu_page *sp, u64 *sptep)
3174 {
3175 	u64 *spte, *start = NULL;
3176 	int i;
3177 
3178 	WARN_ON(!sp->role.direct);
3179 
3180 	i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3181 	spte = sp->spt + i;
3182 
3183 	for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3184 		if (is_shadow_present_pte(*spte) || spte == sptep) {
3185 			if (!start)
3186 				continue;
3187 			if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3188 				break;
3189 			start = NULL;
3190 		} else if (!start)
3191 			start = spte;
3192 	}
3193 }
3194 
3195 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3196 {
3197 	struct kvm_mmu_page *sp;
3198 
3199 	sp = sptep_to_sp(sptep);
3200 
3201 	/*
3202 	 * Without accessed bits, there's no way to distinguish between
3203 	 * actually accessed translations and prefetched, so disable pte
3204 	 * prefetch if accessed bits aren't available.
3205 	 */
3206 	if (sp_ad_disabled(sp))
3207 		return;
3208 
3209 	if (sp->role.level > PG_LEVEL_4K)
3210 		return;
3211 
3212 	__direct_pte_prefetch(vcpu, sp, sptep);
3213 }
3214 
3215 static int host_pfn_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn,
3216 				  kvm_pfn_t pfn, struct kvm_memory_slot *slot)
3217 {
3218 	unsigned long hva;
3219 	pte_t *pte;
3220 	int level;
3221 
3222 	if (!PageCompound(pfn_to_page(pfn)) && !kvm_is_zone_device_pfn(pfn))
3223 		return PG_LEVEL_4K;
3224 
3225 	/*
3226 	 * Note, using the already-retrieved memslot and __gfn_to_hva_memslot()
3227 	 * is not solely for performance, it's also necessary to avoid the
3228 	 * "writable" check in __gfn_to_hva_many(), which will always fail on
3229 	 * read-only memslots due to gfn_to_hva() assuming writes.  Earlier
3230 	 * page fault steps have already verified the guest isn't writing a
3231 	 * read-only memslot.
3232 	 */
3233 	hva = __gfn_to_hva_memslot(slot, gfn);
3234 
3235 	pte = lookup_address_in_mm(vcpu->kvm->mm, hva, &level);
3236 	if (unlikely(!pte))
3237 		return PG_LEVEL_4K;
3238 
3239 	return level;
3240 }
3241 
3242 static int kvm_mmu_hugepage_adjust(struct kvm_vcpu *vcpu, gfn_t gfn,
3243 				   int max_level, kvm_pfn_t *pfnp)
3244 {
3245 	struct kvm_memory_slot *slot;
3246 	struct kvm_lpage_info *linfo;
3247 	kvm_pfn_t pfn = *pfnp;
3248 	kvm_pfn_t mask;
3249 	int level;
3250 
3251 	if (unlikely(max_level == PG_LEVEL_4K))
3252 		return PG_LEVEL_4K;
3253 
3254 	if (is_error_noslot_pfn(pfn) || kvm_is_reserved_pfn(pfn))
3255 		return PG_LEVEL_4K;
3256 
3257 	slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, true);
3258 	if (!slot)
3259 		return PG_LEVEL_4K;
3260 
3261 	max_level = min(max_level, max_huge_page_level);
3262 	for ( ; max_level > PG_LEVEL_4K; max_level--) {
3263 		linfo = lpage_info_slot(gfn, slot, max_level);
3264 		if (!linfo->disallow_lpage)
3265 			break;
3266 	}
3267 
3268 	if (max_level == PG_LEVEL_4K)
3269 		return PG_LEVEL_4K;
3270 
3271 	level = host_pfn_mapping_level(vcpu, gfn, pfn, slot);
3272 	if (level == PG_LEVEL_4K)
3273 		return level;
3274 
3275 	level = min(level, max_level);
3276 
3277 	/*
3278 	 * mmu_notifier_retry() was successful and mmu_lock is held, so
3279 	 * the pmd can't be split from under us.
3280 	 */
3281 	mask = KVM_PAGES_PER_HPAGE(level) - 1;
3282 	VM_BUG_ON((gfn & mask) != (pfn & mask));
3283 	*pfnp = pfn & ~mask;
3284 
3285 	return level;
3286 }
3287 
3288 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
3289 				       gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
3290 {
3291 	int level = *levelp;
3292 	u64 spte = *it.sptep;
3293 
3294 	if (it.level == level && level > PG_LEVEL_4K &&
3295 	    is_nx_huge_page_enabled() &&
3296 	    is_shadow_present_pte(spte) &&
3297 	    !is_large_pte(spte)) {
3298 		/*
3299 		 * A small SPTE exists for this pfn, but FNAME(fetch)
3300 		 * and __direct_map would like to create a large PTE
3301 		 * instead: just force them to go down another level,
3302 		 * patching back for them into pfn the next 9 bits of
3303 		 * the address.
3304 		 */
3305 		u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
3306 		*pfnp |= gfn & page_mask;
3307 		(*levelp)--;
3308 	}
3309 }
3310 
3311 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3312 			int map_writable, int max_level, kvm_pfn_t pfn,
3313 			bool prefault, bool account_disallowed_nx_lpage)
3314 {
3315 	struct kvm_shadow_walk_iterator it;
3316 	struct kvm_mmu_page *sp;
3317 	int level, ret;
3318 	gfn_t gfn = gpa >> PAGE_SHIFT;
3319 	gfn_t base_gfn = gfn;
3320 
3321 	if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
3322 		return RET_PF_RETRY;
3323 
3324 	level = kvm_mmu_hugepage_adjust(vcpu, gfn, max_level, &pfn);
3325 
3326 	trace_kvm_mmu_spte_requested(gpa, level, pfn);
3327 	for_each_shadow_entry(vcpu, gpa, it) {
3328 		/*
3329 		 * We cannot overwrite existing page tables with an NX
3330 		 * large page, as the leaf could be executable.
3331 		 */
3332 		disallowed_hugepage_adjust(it, gfn, &pfn, &level);
3333 
3334 		base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3335 		if (it.level == level)
3336 			break;
3337 
3338 		drop_large_spte(vcpu, it.sptep);
3339 		if (!is_shadow_present_pte(*it.sptep)) {
3340 			sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3341 					      it.level - 1, true, ACC_ALL);
3342 
3343 			link_shadow_page(vcpu, it.sptep, sp);
3344 			if (account_disallowed_nx_lpage)
3345 				account_huge_nx_page(vcpu->kvm, sp);
3346 		}
3347 	}
3348 
3349 	ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3350 			   write, level, base_gfn, pfn, prefault,
3351 			   map_writable);
3352 	direct_pte_prefetch(vcpu, it.sptep);
3353 	++vcpu->stat.pf_fixed;
3354 	return ret;
3355 }
3356 
3357 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3358 {
3359 	send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, PAGE_SHIFT, tsk);
3360 }
3361 
3362 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3363 {
3364 	/*
3365 	 * Do not cache the mmio info caused by writing the readonly gfn
3366 	 * into the spte otherwise read access on readonly gfn also can
3367 	 * caused mmio page fault and treat it as mmio access.
3368 	 */
3369 	if (pfn == KVM_PFN_ERR_RO_FAULT)
3370 		return RET_PF_EMULATE;
3371 
3372 	if (pfn == KVM_PFN_ERR_HWPOISON) {
3373 		kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3374 		return RET_PF_RETRY;
3375 	}
3376 
3377 	return -EFAULT;
3378 }
3379 
3380 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3381 				kvm_pfn_t pfn, unsigned int access,
3382 				int *ret_val)
3383 {
3384 	/* The pfn is invalid, report the error! */
3385 	if (unlikely(is_error_pfn(pfn))) {
3386 		*ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3387 		return true;
3388 	}
3389 
3390 	if (unlikely(is_noslot_pfn(pfn)))
3391 		vcpu_cache_mmio_info(vcpu, gva, gfn,
3392 				     access & shadow_mmio_access_mask);
3393 
3394 	return false;
3395 }
3396 
3397 static bool page_fault_can_be_fast(u32 error_code)
3398 {
3399 	/*
3400 	 * Do not fix the mmio spte with invalid generation number which
3401 	 * need to be updated by slow page fault path.
3402 	 */
3403 	if (unlikely(error_code & PFERR_RSVD_MASK))
3404 		return false;
3405 
3406 	/* See if the page fault is due to an NX violation */
3407 	if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3408 		      == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3409 		return false;
3410 
3411 	/*
3412 	 * #PF can be fast if:
3413 	 * 1. The shadow page table entry is not present, which could mean that
3414 	 *    the fault is potentially caused by access tracking (if enabled).
3415 	 * 2. The shadow page table entry is present and the fault
3416 	 *    is caused by write-protect, that means we just need change the W
3417 	 *    bit of the spte which can be done out of mmu-lock.
3418 	 *
3419 	 * However, if access tracking is disabled we know that a non-present
3420 	 * page must be a genuine page fault where we have to create a new SPTE.
3421 	 * So, if access tracking is disabled, we return true only for write
3422 	 * accesses to a present page.
3423 	 */
3424 
3425 	return shadow_acc_track_mask != 0 ||
3426 	       ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3427 		== (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3428 }
3429 
3430 /*
3431  * Returns true if the SPTE was fixed successfully. Otherwise,
3432  * someone else modified the SPTE from its original value.
3433  */
3434 static bool
3435 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3436 			u64 *sptep, u64 old_spte, u64 new_spte)
3437 {
3438 	gfn_t gfn;
3439 
3440 	WARN_ON(!sp->role.direct);
3441 
3442 	/*
3443 	 * Theoretically we could also set dirty bit (and flush TLB) here in
3444 	 * order to eliminate unnecessary PML logging. See comments in
3445 	 * set_spte. But fast_page_fault is very unlikely to happen with PML
3446 	 * enabled, so we do not do this. This might result in the same GPA
3447 	 * to be logged in PML buffer again when the write really happens, and
3448 	 * eventually to be called by mark_page_dirty twice. But it's also no
3449 	 * harm. This also avoids the TLB flush needed after setting dirty bit
3450 	 * so non-PML cases won't be impacted.
3451 	 *
3452 	 * Compare with set_spte where instead shadow_dirty_mask is set.
3453 	 */
3454 	if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3455 		return false;
3456 
3457 	if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3458 		/*
3459 		 * The gfn of direct spte is stable since it is
3460 		 * calculated by sp->gfn.
3461 		 */
3462 		gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3463 		kvm_vcpu_mark_page_dirty(vcpu, gfn);
3464 	}
3465 
3466 	return true;
3467 }
3468 
3469 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3470 {
3471 	if (fault_err_code & PFERR_FETCH_MASK)
3472 		return is_executable_pte(spte);
3473 
3474 	if (fault_err_code & PFERR_WRITE_MASK)
3475 		return is_writable_pte(spte);
3476 
3477 	/* Fault was on Read access */
3478 	return spte & PT_PRESENT_MASK;
3479 }
3480 
3481 /*
3482  * Return value:
3483  * - true: let the vcpu to access on the same address again.
3484  * - false: let the real page fault path to fix it.
3485  */
3486 static bool fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
3487 			    u32 error_code)
3488 {
3489 	struct kvm_shadow_walk_iterator iterator;
3490 	struct kvm_mmu_page *sp;
3491 	bool fault_handled = false;
3492 	u64 spte = 0ull;
3493 	uint retry_count = 0;
3494 
3495 	if (!page_fault_can_be_fast(error_code))
3496 		return false;
3497 
3498 	walk_shadow_page_lockless_begin(vcpu);
3499 
3500 	do {
3501 		u64 new_spte;
3502 
3503 		for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
3504 			if (!is_shadow_present_pte(spte))
3505 				break;
3506 
3507 		sp = sptep_to_sp(iterator.sptep);
3508 		if (!is_last_spte(spte, sp->role.level))
3509 			break;
3510 
3511 		/*
3512 		 * Check whether the memory access that caused the fault would
3513 		 * still cause it if it were to be performed right now. If not,
3514 		 * then this is a spurious fault caused by TLB lazily flushed,
3515 		 * or some other CPU has already fixed the PTE after the
3516 		 * current CPU took the fault.
3517 		 *
3518 		 * Need not check the access of upper level table entries since
3519 		 * they are always ACC_ALL.
3520 		 */
3521 		if (is_access_allowed(error_code, spte)) {
3522 			fault_handled = true;
3523 			break;
3524 		}
3525 
3526 		new_spte = spte;
3527 
3528 		if (is_access_track_spte(spte))
3529 			new_spte = restore_acc_track_spte(new_spte);
3530 
3531 		/*
3532 		 * Currently, to simplify the code, write-protection can
3533 		 * be removed in the fast path only if the SPTE was
3534 		 * write-protected for dirty-logging or access tracking.
3535 		 */
3536 		if ((error_code & PFERR_WRITE_MASK) &&
3537 		    spte_can_locklessly_be_made_writable(spte)) {
3538 			new_spte |= PT_WRITABLE_MASK;
3539 
3540 			/*
3541 			 * Do not fix write-permission on the large spte.  Since
3542 			 * we only dirty the first page into the dirty-bitmap in
3543 			 * fast_pf_fix_direct_spte(), other pages are missed
3544 			 * if its slot has dirty logging enabled.
3545 			 *
3546 			 * Instead, we let the slow page fault path create a
3547 			 * normal spte to fix the access.
3548 			 *
3549 			 * See the comments in kvm_arch_commit_memory_region().
3550 			 */
3551 			if (sp->role.level > PG_LEVEL_4K)
3552 				break;
3553 		}
3554 
3555 		/* Verify that the fault can be handled in the fast path */
3556 		if (new_spte == spte ||
3557 		    !is_access_allowed(error_code, new_spte))
3558 			break;
3559 
3560 		/*
3561 		 * Currently, fast page fault only works for direct mapping
3562 		 * since the gfn is not stable for indirect shadow page. See
3563 		 * Documentation/virt/kvm/locking.rst to get more detail.
3564 		 */
3565 		fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3566 							iterator.sptep, spte,
3567 							new_spte);
3568 		if (fault_handled)
3569 			break;
3570 
3571 		if (++retry_count > 4) {
3572 			printk_once(KERN_WARNING
3573 				"kvm: Fast #PF retrying more than 4 times.\n");
3574 			break;
3575 		}
3576 
3577 	} while (true);
3578 
3579 	trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
3580 			      spte, fault_handled);
3581 	walk_shadow_page_lockless_end(vcpu);
3582 
3583 	return fault_handled;
3584 }
3585 
3586 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3587 			       struct list_head *invalid_list)
3588 {
3589 	struct kvm_mmu_page *sp;
3590 
3591 	if (!VALID_PAGE(*root_hpa))
3592 		return;
3593 
3594 	sp = to_shadow_page(*root_hpa & PT64_BASE_ADDR_MASK);
3595 	--sp->root_count;
3596 	if (!sp->root_count && sp->role.invalid)
3597 		kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3598 
3599 	*root_hpa = INVALID_PAGE;
3600 }
3601 
3602 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3603 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
3604 			ulong roots_to_free)
3605 {
3606 	int i;
3607 	LIST_HEAD(invalid_list);
3608 	bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3609 
3610 	BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3611 
3612 	/* Before acquiring the MMU lock, see if we need to do any real work. */
3613 	if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3614 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3615 			if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3616 			    VALID_PAGE(mmu->prev_roots[i].hpa))
3617 				break;
3618 
3619 		if (i == KVM_MMU_NUM_PREV_ROOTS)
3620 			return;
3621 	}
3622 
3623 	spin_lock(&vcpu->kvm->mmu_lock);
3624 
3625 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3626 		if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3627 			mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3628 					   &invalid_list);
3629 
3630 	if (free_active_root) {
3631 		if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3632 		    (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3633 			mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3634 					   &invalid_list);
3635 		} else {
3636 			for (i = 0; i < 4; ++i)
3637 				if (mmu->pae_root[i] != 0)
3638 					mmu_free_root_page(vcpu->kvm,
3639 							   &mmu->pae_root[i],
3640 							   &invalid_list);
3641 			mmu->root_hpa = INVALID_PAGE;
3642 		}
3643 		mmu->root_pgd = 0;
3644 	}
3645 
3646 	kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3647 	spin_unlock(&vcpu->kvm->mmu_lock);
3648 }
3649 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3650 
3651 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3652 {
3653 	int ret = 0;
3654 
3655 	if (!kvm_vcpu_is_visible_gfn(vcpu, root_gfn)) {
3656 		kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3657 		ret = 1;
3658 	}
3659 
3660 	return ret;
3661 }
3662 
3663 static hpa_t mmu_alloc_root(struct kvm_vcpu *vcpu, gfn_t gfn, gva_t gva,
3664 			    u8 level, bool direct)
3665 {
3666 	struct kvm_mmu_page *sp;
3667 
3668 	spin_lock(&vcpu->kvm->mmu_lock);
3669 
3670 	if (make_mmu_pages_available(vcpu)) {
3671 		spin_unlock(&vcpu->kvm->mmu_lock);
3672 		return INVALID_PAGE;
3673 	}
3674 	sp = kvm_mmu_get_page(vcpu, gfn, gva, level, direct, ACC_ALL);
3675 	++sp->root_count;
3676 
3677 	spin_unlock(&vcpu->kvm->mmu_lock);
3678 	return __pa(sp->spt);
3679 }
3680 
3681 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3682 {
3683 	u8 shadow_root_level = vcpu->arch.mmu->shadow_root_level;
3684 	hpa_t root;
3685 	unsigned i;
3686 
3687 	if (shadow_root_level >= PT64_ROOT_4LEVEL) {
3688 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level, true);
3689 		if (!VALID_PAGE(root))
3690 			return -ENOSPC;
3691 		vcpu->arch.mmu->root_hpa = root;
3692 	} else if (shadow_root_level == PT32E_ROOT_LEVEL) {
3693 		for (i = 0; i < 4; ++i) {
3694 			MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->pae_root[i]));
3695 
3696 			root = mmu_alloc_root(vcpu, i << (30 - PAGE_SHIFT),
3697 					      i << 30, PT32_ROOT_LEVEL, true);
3698 			if (!VALID_PAGE(root))
3699 				return -ENOSPC;
3700 			vcpu->arch.mmu->pae_root[i] = root | PT_PRESENT_MASK;
3701 		}
3702 		vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3703 	} else
3704 		BUG();
3705 
3706 	/* root_pgd is ignored for direct MMUs. */
3707 	vcpu->arch.mmu->root_pgd = 0;
3708 
3709 	return 0;
3710 }
3711 
3712 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3713 {
3714 	u64 pdptr, pm_mask;
3715 	gfn_t root_gfn, root_pgd;
3716 	hpa_t root;
3717 	int i;
3718 
3719 	root_pgd = vcpu->arch.mmu->get_guest_pgd(vcpu);
3720 	root_gfn = root_pgd >> PAGE_SHIFT;
3721 
3722 	if (mmu_check_root(vcpu, root_gfn))
3723 		return 1;
3724 
3725 	/*
3726 	 * Do we shadow a long mode page table? If so we need to
3727 	 * write-protect the guests page table root.
3728 	 */
3729 	if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3730 		MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->root_hpa));
3731 
3732 		root = mmu_alloc_root(vcpu, root_gfn, 0,
3733 				      vcpu->arch.mmu->shadow_root_level, false);
3734 		if (!VALID_PAGE(root))
3735 			return -ENOSPC;
3736 		vcpu->arch.mmu->root_hpa = root;
3737 		goto set_root_pgd;
3738 	}
3739 
3740 	/*
3741 	 * We shadow a 32 bit page table. This may be a legacy 2-level
3742 	 * or a PAE 3-level page table. In either case we need to be aware that
3743 	 * the shadow page table may be a PAE or a long mode page table.
3744 	 */
3745 	pm_mask = PT_PRESENT_MASK;
3746 	if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL)
3747 		pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3748 
3749 	for (i = 0; i < 4; ++i) {
3750 		MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu->pae_root[i]));
3751 		if (vcpu->arch.mmu->root_level == PT32E_ROOT_LEVEL) {
3752 			pdptr = vcpu->arch.mmu->get_pdptr(vcpu, i);
3753 			if (!(pdptr & PT_PRESENT_MASK)) {
3754 				vcpu->arch.mmu->pae_root[i] = 0;
3755 				continue;
3756 			}
3757 			root_gfn = pdptr >> PAGE_SHIFT;
3758 			if (mmu_check_root(vcpu, root_gfn))
3759 				return 1;
3760 		}
3761 
3762 		root = mmu_alloc_root(vcpu, root_gfn, i << 30,
3763 				      PT32_ROOT_LEVEL, false);
3764 		if (!VALID_PAGE(root))
3765 			return -ENOSPC;
3766 		vcpu->arch.mmu->pae_root[i] = root | pm_mask;
3767 	}
3768 	vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->pae_root);
3769 
3770 	/*
3771 	 * If we shadow a 32 bit page table with a long mode page
3772 	 * table we enter this path.
3773 	 */
3774 	if (vcpu->arch.mmu->shadow_root_level == PT64_ROOT_4LEVEL) {
3775 		if (vcpu->arch.mmu->lm_root == NULL) {
3776 			/*
3777 			 * The additional page necessary for this is only
3778 			 * allocated on demand.
3779 			 */
3780 
3781 			u64 *lm_root;
3782 
3783 			lm_root = (void*)get_zeroed_page(GFP_KERNEL_ACCOUNT);
3784 			if (lm_root == NULL)
3785 				return 1;
3786 
3787 			lm_root[0] = __pa(vcpu->arch.mmu->pae_root) | pm_mask;
3788 
3789 			vcpu->arch.mmu->lm_root = lm_root;
3790 		}
3791 
3792 		vcpu->arch.mmu->root_hpa = __pa(vcpu->arch.mmu->lm_root);
3793 	}
3794 
3795 set_root_pgd:
3796 	vcpu->arch.mmu->root_pgd = root_pgd;
3797 
3798 	return 0;
3799 }
3800 
3801 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3802 {
3803 	if (vcpu->arch.mmu->direct_map)
3804 		return mmu_alloc_direct_roots(vcpu);
3805 	else
3806 		return mmu_alloc_shadow_roots(vcpu);
3807 }
3808 
3809 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3810 {
3811 	int i;
3812 	struct kvm_mmu_page *sp;
3813 
3814 	if (vcpu->arch.mmu->direct_map)
3815 		return;
3816 
3817 	if (!VALID_PAGE(vcpu->arch.mmu->root_hpa))
3818 		return;
3819 
3820 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3821 
3822 	if (vcpu->arch.mmu->root_level >= PT64_ROOT_4LEVEL) {
3823 		hpa_t root = vcpu->arch.mmu->root_hpa;
3824 		sp = to_shadow_page(root);
3825 
3826 		/*
3827 		 * Even if another CPU was marking the SP as unsync-ed
3828 		 * simultaneously, any guest page table changes are not
3829 		 * guaranteed to be visible anyway until this VCPU issues a TLB
3830 		 * flush strictly after those changes are made. We only need to
3831 		 * ensure that the other CPU sets these flags before any actual
3832 		 * changes to the page tables are made. The comments in
3833 		 * mmu_need_write_protect() describe what could go wrong if this
3834 		 * requirement isn't satisfied.
3835 		 */
3836 		if (!smp_load_acquire(&sp->unsync) &&
3837 		    !smp_load_acquire(&sp->unsync_children))
3838 			return;
3839 
3840 		spin_lock(&vcpu->kvm->mmu_lock);
3841 		kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3842 
3843 		mmu_sync_children(vcpu, sp);
3844 
3845 		kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3846 		spin_unlock(&vcpu->kvm->mmu_lock);
3847 		return;
3848 	}
3849 
3850 	spin_lock(&vcpu->kvm->mmu_lock);
3851 	kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3852 
3853 	for (i = 0; i < 4; ++i) {
3854 		hpa_t root = vcpu->arch.mmu->pae_root[i];
3855 
3856 		if (root && VALID_PAGE(root)) {
3857 			root &= PT64_BASE_ADDR_MASK;
3858 			sp = to_shadow_page(root);
3859 			mmu_sync_children(vcpu, sp);
3860 		}
3861 	}
3862 
3863 	kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3864 	spin_unlock(&vcpu->kvm->mmu_lock);
3865 }
3866 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3867 
3868 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
3869 				  u32 access, struct x86_exception *exception)
3870 {
3871 	if (exception)
3872 		exception->error_code = 0;
3873 	return vaddr;
3874 }
3875 
3876 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
3877 					 u32 access,
3878 					 struct x86_exception *exception)
3879 {
3880 	if (exception)
3881 		exception->error_code = 0;
3882 	return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3883 }
3884 
3885 static bool
3886 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3887 {
3888 	int bit7 = (pte >> 7) & 1;
3889 
3890 	return pte & rsvd_check->rsvd_bits_mask[bit7][level-1];
3891 }
3892 
3893 static bool __is_bad_mt_xwr(struct rsvd_bits_validate *rsvd_check, u64 pte)
3894 {
3895 	return rsvd_check->bad_mt_xwr & BIT_ULL(pte & 0x3f);
3896 }
3897 
3898 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3899 {
3900 	/*
3901 	 * A nested guest cannot use the MMIO cache if it is using nested
3902 	 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3903 	 */
3904 	if (mmu_is_nested(vcpu))
3905 		return false;
3906 
3907 	if (direct)
3908 		return vcpu_match_mmio_gpa(vcpu, addr);
3909 
3910 	return vcpu_match_mmio_gva(vcpu, addr);
3911 }
3912 
3913 /* return true if reserved bit is detected on spte. */
3914 static bool
3915 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3916 {
3917 	struct kvm_shadow_walk_iterator iterator;
3918 	u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3919 	struct rsvd_bits_validate *rsvd_check;
3920 	int root, leaf;
3921 	bool reserved = false;
3922 
3923 	rsvd_check = &vcpu->arch.mmu->shadow_zero_check;
3924 
3925 	walk_shadow_page_lockless_begin(vcpu);
3926 
3927 	for (shadow_walk_init(&iterator, vcpu, addr),
3928 		 leaf = root = iterator.level;
3929 	     shadow_walk_okay(&iterator);
3930 	     __shadow_walk_next(&iterator, spte)) {
3931 		spte = mmu_spte_get_lockless(iterator.sptep);
3932 
3933 		sptes[leaf - 1] = spte;
3934 		leaf--;
3935 
3936 		if (!is_shadow_present_pte(spte))
3937 			break;
3938 
3939 		/*
3940 		 * Use a bitwise-OR instead of a logical-OR to aggregate the
3941 		 * reserved bit and EPT's invalid memtype/XWR checks to avoid
3942 		 * adding a Jcc in the loop.
3943 		 */
3944 		reserved |= __is_bad_mt_xwr(rsvd_check, spte) |
3945 			    __is_rsvd_bits_set(rsvd_check, spte, iterator.level);
3946 	}
3947 
3948 	walk_shadow_page_lockless_end(vcpu);
3949 
3950 	if (reserved) {
3951 		pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3952 		       __func__, addr);
3953 		while (root > leaf) {
3954 			pr_err("------ spte 0x%llx level %d.\n",
3955 			       sptes[root - 1], root);
3956 			root--;
3957 		}
3958 	}
3959 
3960 	*sptep = spte;
3961 	return reserved;
3962 }
3963 
3964 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3965 {
3966 	u64 spte;
3967 	bool reserved;
3968 
3969 	if (mmio_info_in_cache(vcpu, addr, direct))
3970 		return RET_PF_EMULATE;
3971 
3972 	reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3973 	if (WARN_ON(reserved))
3974 		return -EINVAL;
3975 
3976 	if (is_mmio_spte(spte)) {
3977 		gfn_t gfn = get_mmio_spte_gfn(spte);
3978 		unsigned int access = get_mmio_spte_access(spte);
3979 
3980 		if (!check_mmio_spte(vcpu, spte))
3981 			return RET_PF_INVALID;
3982 
3983 		if (direct)
3984 			addr = 0;
3985 
3986 		trace_handle_mmio_page_fault(addr, gfn, access);
3987 		vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3988 		return RET_PF_EMULATE;
3989 	}
3990 
3991 	/*
3992 	 * If the page table is zapped by other cpus, let CPU fault again on
3993 	 * the address.
3994 	 */
3995 	return RET_PF_RETRY;
3996 }
3997 
3998 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3999 					 u32 error_code, gfn_t gfn)
4000 {
4001 	if (unlikely(error_code & PFERR_RSVD_MASK))
4002 		return false;
4003 
4004 	if (!(error_code & PFERR_PRESENT_MASK) ||
4005 	      !(error_code & PFERR_WRITE_MASK))
4006 		return false;
4007 
4008 	/*
4009 	 * guest is writing the page which is write tracked which can
4010 	 * not be fixed by page fault handler.
4011 	 */
4012 	if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4013 		return true;
4014 
4015 	return false;
4016 }
4017 
4018 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4019 {
4020 	struct kvm_shadow_walk_iterator iterator;
4021 	u64 spte;
4022 
4023 	walk_shadow_page_lockless_begin(vcpu);
4024 	for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4025 		clear_sp_write_flooding_count(iterator.sptep);
4026 		if (!is_shadow_present_pte(spte))
4027 			break;
4028 	}
4029 	walk_shadow_page_lockless_end(vcpu);
4030 }
4031 
4032 static bool kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4033 				    gfn_t gfn)
4034 {
4035 	struct kvm_arch_async_pf arch;
4036 
4037 	arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4038 	arch.gfn = gfn;
4039 	arch.direct_map = vcpu->arch.mmu->direct_map;
4040 	arch.cr3 = vcpu->arch.mmu->get_guest_pgd(vcpu);
4041 
4042 	return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4043 				  kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4044 }
4045 
4046 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4047 			 gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
4048 			 bool *writable)
4049 {
4050 	struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4051 	bool async;
4052 
4053 	/* Don't expose private memslots to L2. */
4054 	if (is_guest_mode(vcpu) && !kvm_is_visible_memslot(slot)) {
4055 		*pfn = KVM_PFN_NOSLOT;
4056 		*writable = false;
4057 		return false;
4058 	}
4059 
4060 	async = false;
4061 	*pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4062 	if (!async)
4063 		return false; /* *pfn has correct page already */
4064 
4065 	if (!prefault && kvm_can_do_async_pf(vcpu)) {
4066 		trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
4067 		if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4068 			trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
4069 			kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4070 			return true;
4071 		} else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
4072 			return true;
4073 	}
4074 
4075 	*pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4076 	return false;
4077 }
4078 
4079 static int direct_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4080 			     bool prefault, int max_level, bool is_tdp)
4081 {
4082 	bool write = error_code & PFERR_WRITE_MASK;
4083 	bool exec = error_code & PFERR_FETCH_MASK;
4084 	bool lpage_disallowed = exec && is_nx_huge_page_enabled();
4085 	bool map_writable;
4086 
4087 	gfn_t gfn = gpa >> PAGE_SHIFT;
4088 	unsigned long mmu_seq;
4089 	kvm_pfn_t pfn;
4090 	int r;
4091 
4092 	if (page_fault_handle_page_track(vcpu, error_code, gfn))
4093 		return RET_PF_EMULATE;
4094 
4095 	if (fast_page_fault(vcpu, gpa, error_code))
4096 		return RET_PF_RETRY;
4097 
4098 	r = mmu_topup_memory_caches(vcpu, false);
4099 	if (r)
4100 		return r;
4101 
4102 	if (lpage_disallowed)
4103 		max_level = PG_LEVEL_4K;
4104 
4105 	mmu_seq = vcpu->kvm->mmu_notifier_seq;
4106 	smp_rmb();
4107 
4108 	if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4109 		return RET_PF_RETRY;
4110 
4111 	if (handle_abnormal_pfn(vcpu, is_tdp ? 0 : gpa, gfn, pfn, ACC_ALL, &r))
4112 		return r;
4113 
4114 	r = RET_PF_RETRY;
4115 	spin_lock(&vcpu->kvm->mmu_lock);
4116 	if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4117 		goto out_unlock;
4118 	r = make_mmu_pages_available(vcpu);
4119 	if (r)
4120 		goto out_unlock;
4121 	r = __direct_map(vcpu, gpa, write, map_writable, max_level, pfn,
4122 			 prefault, is_tdp && lpage_disallowed);
4123 
4124 out_unlock:
4125 	spin_unlock(&vcpu->kvm->mmu_lock);
4126 	kvm_release_pfn_clean(pfn);
4127 	return r;
4128 }
4129 
4130 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
4131 				u32 error_code, bool prefault)
4132 {
4133 	pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
4134 
4135 	/* This path builds a PAE pagetable, we can map 2mb pages at maximum. */
4136 	return direct_page_fault(vcpu, gpa & PAGE_MASK, error_code, prefault,
4137 				 PG_LEVEL_2M, false);
4138 }
4139 
4140 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4141 				u64 fault_address, char *insn, int insn_len)
4142 {
4143 	int r = 1;
4144 	u32 flags = vcpu->arch.apf.host_apf_flags;
4145 
4146 #ifndef CONFIG_X86_64
4147 	/* A 64-bit CR2 should be impossible on 32-bit KVM. */
4148 	if (WARN_ON_ONCE(fault_address >> 32))
4149 		return -EFAULT;
4150 #endif
4151 
4152 	vcpu->arch.l1tf_flush_l1d = true;
4153 	if (!flags) {
4154 		trace_kvm_page_fault(fault_address, error_code);
4155 
4156 		if (kvm_event_needs_reinjection(vcpu))
4157 			kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4158 		r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4159 				insn_len);
4160 	} else if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
4161 		vcpu->arch.apf.host_apf_flags = 0;
4162 		local_irq_disable();
4163 		kvm_async_pf_task_wait_schedule(fault_address);
4164 		local_irq_enable();
4165 	} else {
4166 		WARN_ONCE(1, "Unexpected host async PF flags: %x\n", flags);
4167 	}
4168 
4169 	return r;
4170 }
4171 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4172 
4173 int kvm_tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4174 		       bool prefault)
4175 {
4176 	int max_level;
4177 
4178 	for (max_level = KVM_MAX_HUGEPAGE_LEVEL;
4179 	     max_level > PG_LEVEL_4K;
4180 	     max_level--) {
4181 		int page_num = KVM_PAGES_PER_HPAGE(max_level);
4182 		gfn_t base = (gpa >> PAGE_SHIFT) & ~(page_num - 1);
4183 
4184 		if (kvm_mtrr_check_gfn_range_consistency(vcpu, base, page_num))
4185 			break;
4186 	}
4187 
4188 	return direct_page_fault(vcpu, gpa, error_code, prefault,
4189 				 max_level, true);
4190 }
4191 
4192 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4193 				   struct kvm_mmu *context)
4194 {
4195 	context->page_fault = nonpaging_page_fault;
4196 	context->gva_to_gpa = nonpaging_gva_to_gpa;
4197 	context->sync_page = nonpaging_sync_page;
4198 	context->invlpg = NULL;
4199 	context->update_pte = nonpaging_update_pte;
4200 	context->root_level = 0;
4201 	context->shadow_root_level = PT32E_ROOT_LEVEL;
4202 	context->direct_map = true;
4203 	context->nx = false;
4204 }
4205 
4206 static inline bool is_root_usable(struct kvm_mmu_root_info *root, gpa_t pgd,
4207 				  union kvm_mmu_page_role role)
4208 {
4209 	return (role.direct || pgd == root->pgd) &&
4210 	       VALID_PAGE(root->hpa) && to_shadow_page(root->hpa) &&
4211 	       role.word == to_shadow_page(root->hpa)->role.word;
4212 }
4213 
4214 /*
4215  * Find out if a previously cached root matching the new pgd/role is available.
4216  * The current root is also inserted into the cache.
4217  * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4218  * returned.
4219  * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4220  * false is returned. This root should now be freed by the caller.
4221  */
4222 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4223 				  union kvm_mmu_page_role new_role)
4224 {
4225 	uint i;
4226 	struct kvm_mmu_root_info root;
4227 	struct kvm_mmu *mmu = vcpu->arch.mmu;
4228 
4229 	root.pgd = mmu->root_pgd;
4230 	root.hpa = mmu->root_hpa;
4231 
4232 	if (is_root_usable(&root, new_pgd, new_role))
4233 		return true;
4234 
4235 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4236 		swap(root, mmu->prev_roots[i]);
4237 
4238 		if (is_root_usable(&root, new_pgd, new_role))
4239 			break;
4240 	}
4241 
4242 	mmu->root_hpa = root.hpa;
4243 	mmu->root_pgd = root.pgd;
4244 
4245 	return i < KVM_MMU_NUM_PREV_ROOTS;
4246 }
4247 
4248 static bool fast_pgd_switch(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4249 			    union kvm_mmu_page_role new_role)
4250 {
4251 	struct kvm_mmu *mmu = vcpu->arch.mmu;
4252 
4253 	/*
4254 	 * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4255 	 * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4256 	 * later if necessary.
4257 	 */
4258 	if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4259 	    mmu->root_level >= PT64_ROOT_4LEVEL)
4260 		return cached_root_available(vcpu, new_pgd, new_role);
4261 
4262 	return false;
4263 }
4264 
4265 static void __kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd,
4266 			      union kvm_mmu_page_role new_role,
4267 			      bool skip_tlb_flush, bool skip_mmu_sync)
4268 {
4269 	if (!fast_pgd_switch(vcpu, new_pgd, new_role)) {
4270 		kvm_mmu_free_roots(vcpu, vcpu->arch.mmu, KVM_MMU_ROOT_CURRENT);
4271 		return;
4272 	}
4273 
4274 	/*
4275 	 * It's possible that the cached previous root page is obsolete because
4276 	 * of a change in the MMU generation number. However, changing the
4277 	 * generation number is accompanied by KVM_REQ_MMU_RELOAD, which will
4278 	 * free the root set here and allocate a new one.
4279 	 */
4280 	kvm_make_request(KVM_REQ_LOAD_MMU_PGD, vcpu);
4281 
4282 	if (!skip_mmu_sync || force_flush_and_sync_on_reuse)
4283 		kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4284 	if (!skip_tlb_flush || force_flush_and_sync_on_reuse)
4285 		kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, vcpu);
4286 
4287 	/*
4288 	 * The last MMIO access's GVA and GPA are cached in the VCPU. When
4289 	 * switching to a new CR3, that GVA->GPA mapping may no longer be
4290 	 * valid. So clear any cached MMIO info even when we don't need to sync
4291 	 * the shadow page tables.
4292 	 */
4293 	vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4294 
4295 	__clear_sp_write_flooding_count(to_shadow_page(vcpu->arch.mmu->root_hpa));
4296 }
4297 
4298 void kvm_mmu_new_pgd(struct kvm_vcpu *vcpu, gpa_t new_pgd, bool skip_tlb_flush,
4299 		     bool skip_mmu_sync)
4300 {
4301 	__kvm_mmu_new_pgd(vcpu, new_pgd, kvm_mmu_calc_root_page_role(vcpu),
4302 			  skip_tlb_flush, skip_mmu_sync);
4303 }
4304 EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
4305 
4306 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4307 {
4308 	return kvm_read_cr3(vcpu);
4309 }
4310 
4311 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4312 			   unsigned int access, int *nr_present)
4313 {
4314 	if (unlikely(is_mmio_spte(*sptep))) {
4315 		if (gfn != get_mmio_spte_gfn(*sptep)) {
4316 			mmu_spte_clear_no_track(sptep);
4317 			return true;
4318 		}
4319 
4320 		(*nr_present)++;
4321 		mark_mmio_spte(vcpu, sptep, gfn, access);
4322 		return true;
4323 	}
4324 
4325 	return false;
4326 }
4327 
4328 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4329 				unsigned level, unsigned gpte)
4330 {
4331 	/*
4332 	 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4333 	 * If it is clear, there are no large pages at this level, so clear
4334 	 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4335 	 */
4336 	gpte &= level - mmu->last_nonleaf_level;
4337 
4338 	/*
4339 	 * PG_LEVEL_4K always terminates.  The RHS has bit 7 set
4340 	 * iff level <= PG_LEVEL_4K, which for our purpose means
4341 	 * level == PG_LEVEL_4K; set PT_PAGE_SIZE_MASK in gpte then.
4342 	 */
4343 	gpte |= level - PG_LEVEL_4K - 1;
4344 
4345 	return gpte & PT_PAGE_SIZE_MASK;
4346 }
4347 
4348 #define PTTYPE_EPT 18 /* arbitrary */
4349 #define PTTYPE PTTYPE_EPT
4350 #include "paging_tmpl.h"
4351 #undef PTTYPE
4352 
4353 #define PTTYPE 64
4354 #include "paging_tmpl.h"
4355 #undef PTTYPE
4356 
4357 #define PTTYPE 32
4358 #include "paging_tmpl.h"
4359 #undef PTTYPE
4360 
4361 static void
4362 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4363 			struct rsvd_bits_validate *rsvd_check,
4364 			int maxphyaddr, int level, bool nx, bool gbpages,
4365 			bool pse, bool amd)
4366 {
4367 	u64 exb_bit_rsvd = 0;
4368 	u64 gbpages_bit_rsvd = 0;
4369 	u64 nonleaf_bit8_rsvd = 0;
4370 
4371 	rsvd_check->bad_mt_xwr = 0;
4372 
4373 	if (!nx)
4374 		exb_bit_rsvd = rsvd_bits(63, 63);
4375 	if (!gbpages)
4376 		gbpages_bit_rsvd = rsvd_bits(7, 7);
4377 
4378 	/*
4379 	 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4380 	 * leaf entries) on AMD CPUs only.
4381 	 */
4382 	if (amd)
4383 		nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4384 
4385 	switch (level) {
4386 	case PT32_ROOT_LEVEL:
4387 		/* no rsvd bits for 2 level 4K page table entries */
4388 		rsvd_check->rsvd_bits_mask[0][1] = 0;
4389 		rsvd_check->rsvd_bits_mask[0][0] = 0;
4390 		rsvd_check->rsvd_bits_mask[1][0] =
4391 			rsvd_check->rsvd_bits_mask[0][0];
4392 
4393 		if (!pse) {
4394 			rsvd_check->rsvd_bits_mask[1][1] = 0;
4395 			break;
4396 		}
4397 
4398 		if (is_cpuid_PSE36())
4399 			/* 36bits PSE 4MB page */
4400 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4401 		else
4402 			/* 32 bits PSE 4MB page */
4403 			rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4404 		break;
4405 	case PT32E_ROOT_LEVEL:
4406 		rsvd_check->rsvd_bits_mask[0][2] =
4407 			rsvd_bits(maxphyaddr, 63) |
4408 			rsvd_bits(5, 8) | rsvd_bits(1, 2);	/* PDPTE */
4409 		rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4410 			rsvd_bits(maxphyaddr, 62);	/* PDE */
4411 		rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4412 			rsvd_bits(maxphyaddr, 62); 	/* PTE */
4413 		rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4414 			rsvd_bits(maxphyaddr, 62) |
4415 			rsvd_bits(13, 20);		/* large page */
4416 		rsvd_check->rsvd_bits_mask[1][0] =
4417 			rsvd_check->rsvd_bits_mask[0][0];
4418 		break;
4419 	case PT64_ROOT_5LEVEL:
4420 		rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4421 			nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4422 			rsvd_bits(maxphyaddr, 51);
4423 		rsvd_check->rsvd_bits_mask[1][4] =
4424 			rsvd_check->rsvd_bits_mask[0][4];
4425 		fallthrough;
4426 	case PT64_ROOT_4LEVEL:
4427 		rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4428 			nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4429 			rsvd_bits(maxphyaddr, 51);
4430 		rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4431 			gbpages_bit_rsvd |
4432 			rsvd_bits(maxphyaddr, 51);
4433 		rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4434 			rsvd_bits(maxphyaddr, 51);
4435 		rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4436 			rsvd_bits(maxphyaddr, 51);
4437 		rsvd_check->rsvd_bits_mask[1][3] =
4438 			rsvd_check->rsvd_bits_mask[0][3];
4439 		rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4440 			gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4441 			rsvd_bits(13, 29);
4442 		rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4443 			rsvd_bits(maxphyaddr, 51) |
4444 			rsvd_bits(13, 20);		/* large page */
4445 		rsvd_check->rsvd_bits_mask[1][0] =
4446 			rsvd_check->rsvd_bits_mask[0][0];
4447 		break;
4448 	}
4449 }
4450 
4451 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4452 				  struct kvm_mmu *context)
4453 {
4454 	__reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4455 				cpuid_maxphyaddr(vcpu), context->root_level,
4456 				context->nx,
4457 				guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4458 				is_pse(vcpu),
4459 				guest_cpuid_is_amd_or_hygon(vcpu));
4460 }
4461 
4462 static void
4463 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4464 			    int maxphyaddr, bool execonly)
4465 {
4466 	u64 bad_mt_xwr;
4467 
4468 	rsvd_check->rsvd_bits_mask[0][4] =
4469 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4470 	rsvd_check->rsvd_bits_mask[0][3] =
4471 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4472 	rsvd_check->rsvd_bits_mask[0][2] =
4473 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4474 	rsvd_check->rsvd_bits_mask[0][1] =
4475 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4476 	rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4477 
4478 	/* large page */
4479 	rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4480 	rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4481 	rsvd_check->rsvd_bits_mask[1][2] =
4482 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4483 	rsvd_check->rsvd_bits_mask[1][1] =
4484 		rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4485 	rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4486 
4487 	bad_mt_xwr = 0xFFull << (2 * 8);	/* bits 3..5 must not be 2 */
4488 	bad_mt_xwr |= 0xFFull << (3 * 8);	/* bits 3..5 must not be 3 */
4489 	bad_mt_xwr |= 0xFFull << (7 * 8);	/* bits 3..5 must not be 7 */
4490 	bad_mt_xwr |= REPEAT_BYTE(1ull << 2);	/* bits 0..2 must not be 010 */
4491 	bad_mt_xwr |= REPEAT_BYTE(1ull << 6);	/* bits 0..2 must not be 110 */
4492 	if (!execonly) {
4493 		/* bits 0..2 must not be 100 unless VMX capabilities allow it */
4494 		bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4495 	}
4496 	rsvd_check->bad_mt_xwr = bad_mt_xwr;
4497 }
4498 
4499 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4500 		struct kvm_mmu *context, bool execonly)
4501 {
4502 	__reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4503 				    cpuid_maxphyaddr(vcpu), execonly);
4504 }
4505 
4506 /*
4507  * the page table on host is the shadow page table for the page
4508  * table in guest or amd nested guest, its mmu features completely
4509  * follow the features in guest.
4510  */
4511 void
4512 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4513 {
4514 	bool uses_nx = context->nx ||
4515 		context->mmu_role.base.smep_andnot_wp;
4516 	struct rsvd_bits_validate *shadow_zero_check;
4517 	int i;
4518 
4519 	/*
4520 	 * Passing "true" to the last argument is okay; it adds a check
4521 	 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4522 	 */
4523 	shadow_zero_check = &context->shadow_zero_check;
4524 	__reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4525 				shadow_phys_bits,
4526 				context->shadow_root_level, uses_nx,
4527 				guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4528 				is_pse(vcpu), true);
4529 
4530 	if (!shadow_me_mask)
4531 		return;
4532 
4533 	for (i = context->shadow_root_level; --i >= 0;) {
4534 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4535 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4536 	}
4537 
4538 }
4539 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4540 
4541 static inline bool boot_cpu_is_amd(void)
4542 {
4543 	WARN_ON_ONCE(!tdp_enabled);
4544 	return shadow_x_mask == 0;
4545 }
4546 
4547 /*
4548  * the direct page table on host, use as much mmu features as
4549  * possible, however, kvm currently does not do execution-protection.
4550  */
4551 static void
4552 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4553 				struct kvm_mmu *context)
4554 {
4555 	struct rsvd_bits_validate *shadow_zero_check;
4556 	int i;
4557 
4558 	shadow_zero_check = &context->shadow_zero_check;
4559 
4560 	if (boot_cpu_is_amd())
4561 		__reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4562 					shadow_phys_bits,
4563 					context->shadow_root_level, false,
4564 					boot_cpu_has(X86_FEATURE_GBPAGES),
4565 					true, true);
4566 	else
4567 		__reset_rsvds_bits_mask_ept(shadow_zero_check,
4568 					    shadow_phys_bits,
4569 					    false);
4570 
4571 	if (!shadow_me_mask)
4572 		return;
4573 
4574 	for (i = context->shadow_root_level; --i >= 0;) {
4575 		shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4576 		shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4577 	}
4578 }
4579 
4580 /*
4581  * as the comments in reset_shadow_zero_bits_mask() except it
4582  * is the shadow page table for intel nested guest.
4583  */
4584 static void
4585 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4586 				struct kvm_mmu *context, bool execonly)
4587 {
4588 	__reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4589 				    shadow_phys_bits, execonly);
4590 }
4591 
4592 #define BYTE_MASK(access) \
4593 	((1 & (access) ? 2 : 0) | \
4594 	 (2 & (access) ? 4 : 0) | \
4595 	 (3 & (access) ? 8 : 0) | \
4596 	 (4 & (access) ? 16 : 0) | \
4597 	 (5 & (access) ? 32 : 0) | \
4598 	 (6 & (access) ? 64 : 0) | \
4599 	 (7 & (access) ? 128 : 0))
4600 
4601 
4602 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4603 				      struct kvm_mmu *mmu, bool ept)
4604 {
4605 	unsigned byte;
4606 
4607 	const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4608 	const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4609 	const u8 u = BYTE_MASK(ACC_USER_MASK);
4610 
4611 	bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4612 	bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4613 	bool cr0_wp = is_write_protection(vcpu);
4614 
4615 	for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4616 		unsigned pfec = byte << 1;
4617 
4618 		/*
4619 		 * Each "*f" variable has a 1 bit for each UWX value
4620 		 * that causes a fault with the given PFEC.
4621 		 */
4622 
4623 		/* Faults from writes to non-writable pages */
4624 		u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4625 		/* Faults from user mode accesses to supervisor pages */
4626 		u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4627 		/* Faults from fetches of non-executable pages*/
4628 		u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4629 		/* Faults from kernel mode fetches of user pages */
4630 		u8 smepf = 0;
4631 		/* Faults from kernel mode accesses of user pages */
4632 		u8 smapf = 0;
4633 
4634 		if (!ept) {
4635 			/* Faults from kernel mode accesses to user pages */
4636 			u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4637 
4638 			/* Not really needed: !nx will cause pte.nx to fault */
4639 			if (!mmu->nx)
4640 				ff = 0;
4641 
4642 			/* Allow supervisor writes if !cr0.wp */
4643 			if (!cr0_wp)
4644 				wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4645 
4646 			/* Disallow supervisor fetches of user code if cr4.smep */
4647 			if (cr4_smep)
4648 				smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4649 
4650 			/*
4651 			 * SMAP:kernel-mode data accesses from user-mode
4652 			 * mappings should fault. A fault is considered
4653 			 * as a SMAP violation if all of the following
4654 			 * conditions are true:
4655 			 *   - X86_CR4_SMAP is set in CR4
4656 			 *   - A user page is accessed
4657 			 *   - The access is not a fetch
4658 			 *   - Page fault in kernel mode
4659 			 *   - if CPL = 3 or X86_EFLAGS_AC is clear
4660 			 *
4661 			 * Here, we cover the first three conditions.
4662 			 * The fourth is computed dynamically in permission_fault();
4663 			 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4664 			 * *not* subject to SMAP restrictions.
4665 			 */
4666 			if (cr4_smap)
4667 				smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4668 		}
4669 
4670 		mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4671 	}
4672 }
4673 
4674 /*
4675 * PKU is an additional mechanism by which the paging controls access to
4676 * user-mode addresses based on the value in the PKRU register.  Protection
4677 * key violations are reported through a bit in the page fault error code.
4678 * Unlike other bits of the error code, the PK bit is not known at the
4679 * call site of e.g. gva_to_gpa; it must be computed directly in
4680 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4681 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4682 *
4683 * In particular the following conditions come from the error code, the
4684 * page tables and the machine state:
4685 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4686 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4687 * - PK is always zero if U=0 in the page tables
4688 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4689 *
4690 * The PKRU bitmask caches the result of these four conditions.  The error
4691 * code (minus the P bit) and the page table's U bit form an index into the
4692 * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
4693 * with the two bits of the PKRU register corresponding to the protection key.
4694 * For the first three conditions above the bits will be 00, thus masking
4695 * away both AD and WD.  For all reads or if the last condition holds, WD
4696 * only will be masked away.
4697 */
4698 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4699 				bool ept)
4700 {
4701 	unsigned bit;
4702 	bool wp;
4703 
4704 	if (ept) {
4705 		mmu->pkru_mask = 0;
4706 		return;
4707 	}
4708 
4709 	/* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4710 	if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4711 		mmu->pkru_mask = 0;
4712 		return;
4713 	}
4714 
4715 	wp = is_write_protection(vcpu);
4716 
4717 	for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4718 		unsigned pfec, pkey_bits;
4719 		bool check_pkey, check_write, ff, uf, wf, pte_user;
4720 
4721 		pfec = bit << 1;
4722 		ff = pfec & PFERR_FETCH_MASK;
4723 		uf = pfec & PFERR_USER_MASK;
4724 		wf = pfec & PFERR_WRITE_MASK;
4725 
4726 		/* PFEC.RSVD is replaced by ACC_USER_MASK. */
4727 		pte_user = pfec & PFERR_RSVD_MASK;
4728 
4729 		/*
4730 		 * Only need to check the access which is not an
4731 		 * instruction fetch and is to a user page.
4732 		 */
4733 		check_pkey = (!ff && pte_user);
4734 		/*
4735 		 * write access is controlled by PKRU if it is a
4736 		 * user access or CR0.WP = 1.
4737 		 */
4738 		check_write = check_pkey && wf && (uf || wp);
4739 
4740 		/* PKRU.AD stops both read and write access. */
4741 		pkey_bits = !!check_pkey;
4742 		/* PKRU.WD stops write access. */
4743 		pkey_bits |= (!!check_write) << 1;
4744 
4745 		mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4746 	}
4747 }
4748 
4749 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4750 {
4751 	unsigned root_level = mmu->root_level;
4752 
4753 	mmu->last_nonleaf_level = root_level;
4754 	if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4755 		mmu->last_nonleaf_level++;
4756 }
4757 
4758 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4759 					 struct kvm_mmu *context,
4760 					 int level)
4761 {
4762 	context->nx = is_nx(vcpu);
4763 	context->root_level = level;
4764 
4765 	reset_rsvds_bits_mask(vcpu, context);
4766 	update_permission_bitmask(vcpu, context, false);
4767 	update_pkru_bitmask(vcpu, context, false);
4768 	update_last_nonleaf_level(vcpu, context);
4769 
4770 	MMU_WARN_ON(!is_pae(vcpu));
4771 	context->page_fault = paging64_page_fault;
4772 	context->gva_to_gpa = paging64_gva_to_gpa;
4773 	context->sync_page = paging64_sync_page;
4774 	context->invlpg = paging64_invlpg;
4775 	context->update_pte = paging64_update_pte;
4776 	context->shadow_root_level = level;
4777 	context->direct_map = false;
4778 }
4779 
4780 static void paging64_init_context(struct kvm_vcpu *vcpu,
4781 				  struct kvm_mmu *context)
4782 {
4783 	int root_level = is_la57_mode(vcpu) ?
4784 			 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4785 
4786 	paging64_init_context_common(vcpu, context, root_level);
4787 }
4788 
4789 static void paging32_init_context(struct kvm_vcpu *vcpu,
4790 				  struct kvm_mmu *context)
4791 {
4792 	context->nx = false;
4793 	context->root_level = PT32_ROOT_LEVEL;
4794 
4795 	reset_rsvds_bits_mask(vcpu, context);
4796 	update_permission_bitmask(vcpu, context, false);
4797 	update_pkru_bitmask(vcpu, context, false);
4798 	update_last_nonleaf_level(vcpu, context);
4799 
4800 	context->page_fault = paging32_page_fault;
4801 	context->gva_to_gpa = paging32_gva_to_gpa;
4802 	context->sync_page = paging32_sync_page;
4803 	context->invlpg = paging32_invlpg;
4804 	context->update_pte = paging32_update_pte;
4805 	context->shadow_root_level = PT32E_ROOT_LEVEL;
4806 	context->direct_map = false;
4807 }
4808 
4809 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4810 				   struct kvm_mmu *context)
4811 {
4812 	paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4813 }
4814 
4815 static union kvm_mmu_extended_role kvm_calc_mmu_role_ext(struct kvm_vcpu *vcpu)
4816 {
4817 	union kvm_mmu_extended_role ext = {0};
4818 
4819 	ext.cr0_pg = !!is_paging(vcpu);
4820 	ext.cr4_pae = !!is_pae(vcpu);
4821 	ext.cr4_smep = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4822 	ext.cr4_smap = !!kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4823 	ext.cr4_pse = !!is_pse(vcpu);
4824 	ext.cr4_pke = !!kvm_read_cr4_bits(vcpu, X86_CR4_PKE);
4825 	ext.maxphyaddr = cpuid_maxphyaddr(vcpu);
4826 
4827 	ext.valid = 1;
4828 
4829 	return ext;
4830 }
4831 
4832 static union kvm_mmu_role kvm_calc_mmu_role_common(struct kvm_vcpu *vcpu,
4833 						   bool base_only)
4834 {
4835 	union kvm_mmu_role role = {0};
4836 
4837 	role.base.access = ACC_ALL;
4838 	role.base.nxe = !!is_nx(vcpu);
4839 	role.base.cr0_wp = is_write_protection(vcpu);
4840 	role.base.smm = is_smm(vcpu);
4841 	role.base.guest_mode = is_guest_mode(vcpu);
4842 
4843 	if (base_only)
4844 		return role;
4845 
4846 	role.ext = kvm_calc_mmu_role_ext(vcpu);
4847 
4848 	return role;
4849 }
4850 
4851 static inline int kvm_mmu_get_tdp_level(struct kvm_vcpu *vcpu)
4852 {
4853 	/* Use 5-level TDP if and only if it's useful/necessary. */
4854 	if (max_tdp_level == 5 && cpuid_maxphyaddr(vcpu) <= 48)
4855 		return 4;
4856 
4857 	return max_tdp_level;
4858 }
4859 
4860 static union kvm_mmu_role
4861 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4862 {
4863 	union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4864 
4865 	role.base.ad_disabled = (shadow_accessed_mask == 0);
4866 	role.base.level = kvm_mmu_get_tdp_level(vcpu);
4867 	role.base.direct = true;
4868 	role.base.gpte_is_8_bytes = true;
4869 
4870 	return role;
4871 }
4872 
4873 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4874 {
4875 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
4876 	union kvm_mmu_role new_role =
4877 		kvm_calc_tdp_mmu_root_page_role(vcpu, false);
4878 
4879 	if (new_role.as_u64 == context->mmu_role.as_u64)
4880 		return;
4881 
4882 	context->mmu_role.as_u64 = new_role.as_u64;
4883 	context->page_fault = kvm_tdp_page_fault;
4884 	context->sync_page = nonpaging_sync_page;
4885 	context->invlpg = NULL;
4886 	context->update_pte = nonpaging_update_pte;
4887 	context->shadow_root_level = kvm_mmu_get_tdp_level(vcpu);
4888 	context->direct_map = true;
4889 	context->get_guest_pgd = get_cr3;
4890 	context->get_pdptr = kvm_pdptr_read;
4891 	context->inject_page_fault = kvm_inject_page_fault;
4892 
4893 	if (!is_paging(vcpu)) {
4894 		context->nx = false;
4895 		context->gva_to_gpa = nonpaging_gva_to_gpa;
4896 		context->root_level = 0;
4897 	} else if (is_long_mode(vcpu)) {
4898 		context->nx = is_nx(vcpu);
4899 		context->root_level = is_la57_mode(vcpu) ?
4900 				PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4901 		reset_rsvds_bits_mask(vcpu, context);
4902 		context->gva_to_gpa = paging64_gva_to_gpa;
4903 	} else if (is_pae(vcpu)) {
4904 		context->nx = is_nx(vcpu);
4905 		context->root_level = PT32E_ROOT_LEVEL;
4906 		reset_rsvds_bits_mask(vcpu, context);
4907 		context->gva_to_gpa = paging64_gva_to_gpa;
4908 	} else {
4909 		context->nx = false;
4910 		context->root_level = PT32_ROOT_LEVEL;
4911 		reset_rsvds_bits_mask(vcpu, context);
4912 		context->gva_to_gpa = paging32_gva_to_gpa;
4913 	}
4914 
4915 	update_permission_bitmask(vcpu, context, false);
4916 	update_pkru_bitmask(vcpu, context, false);
4917 	update_last_nonleaf_level(vcpu, context);
4918 	reset_tdp_shadow_zero_bits_mask(vcpu, context);
4919 }
4920 
4921 static union kvm_mmu_role
4922 kvm_calc_shadow_root_page_role_common(struct kvm_vcpu *vcpu, bool base_only)
4923 {
4924 	union kvm_mmu_role role = kvm_calc_mmu_role_common(vcpu, base_only);
4925 
4926 	role.base.smep_andnot_wp = role.ext.cr4_smep &&
4927 		!is_write_protection(vcpu);
4928 	role.base.smap_andnot_wp = role.ext.cr4_smap &&
4929 		!is_write_protection(vcpu);
4930 	role.base.gpte_is_8_bytes = !!is_pae(vcpu);
4931 
4932 	return role;
4933 }
4934 
4935 static union kvm_mmu_role
4936 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu, bool base_only)
4937 {
4938 	union kvm_mmu_role role =
4939 		kvm_calc_shadow_root_page_role_common(vcpu, base_only);
4940 
4941 	role.base.direct = !is_paging(vcpu);
4942 
4943 	if (!is_long_mode(vcpu))
4944 		role.base.level = PT32E_ROOT_LEVEL;
4945 	else if (is_la57_mode(vcpu))
4946 		role.base.level = PT64_ROOT_5LEVEL;
4947 	else
4948 		role.base.level = PT64_ROOT_4LEVEL;
4949 
4950 	return role;
4951 }
4952 
4953 static void shadow_mmu_init_context(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
4954 				    u32 cr0, u32 cr4, u32 efer,
4955 				    union kvm_mmu_role new_role)
4956 {
4957 	if (!(cr0 & X86_CR0_PG))
4958 		nonpaging_init_context(vcpu, context);
4959 	else if (efer & EFER_LMA)
4960 		paging64_init_context(vcpu, context);
4961 	else if (cr4 & X86_CR4_PAE)
4962 		paging32E_init_context(vcpu, context);
4963 	else
4964 		paging32_init_context(vcpu, context);
4965 
4966 	context->mmu_role.as_u64 = new_role.as_u64;
4967 	reset_shadow_zero_bits_mask(vcpu, context);
4968 }
4969 
4970 static void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu, u32 cr0, u32 cr4, u32 efer)
4971 {
4972 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
4973 	union kvm_mmu_role new_role =
4974 		kvm_calc_shadow_mmu_root_page_role(vcpu, false);
4975 
4976 	if (new_role.as_u64 != context->mmu_role.as_u64)
4977 		shadow_mmu_init_context(vcpu, context, cr0, cr4, efer, new_role);
4978 }
4979 
4980 static union kvm_mmu_role
4981 kvm_calc_shadow_npt_root_page_role(struct kvm_vcpu *vcpu)
4982 {
4983 	union kvm_mmu_role role =
4984 		kvm_calc_shadow_root_page_role_common(vcpu, false);
4985 
4986 	role.base.direct = false;
4987 	role.base.level = kvm_mmu_get_tdp_level(vcpu);
4988 
4989 	return role;
4990 }
4991 
4992 void kvm_init_shadow_npt_mmu(struct kvm_vcpu *vcpu, u32 cr0, u32 cr4, u32 efer,
4993 			     gpa_t nested_cr3)
4994 {
4995 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
4996 	union kvm_mmu_role new_role = kvm_calc_shadow_npt_root_page_role(vcpu);
4997 
4998 	context->shadow_root_level = new_role.base.level;
4999 
5000 	__kvm_mmu_new_pgd(vcpu, nested_cr3, new_role.base, false, false);
5001 
5002 	if (new_role.as_u64 != context->mmu_role.as_u64)
5003 		shadow_mmu_init_context(vcpu, context, cr0, cr4, efer, new_role);
5004 }
5005 EXPORT_SYMBOL_GPL(kvm_init_shadow_npt_mmu);
5006 
5007 static union kvm_mmu_role
5008 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty,
5009 				   bool execonly, u8 level)
5010 {
5011 	union kvm_mmu_role role = {0};
5012 
5013 	/* SMM flag is inherited from root_mmu */
5014 	role.base.smm = vcpu->arch.root_mmu.mmu_role.base.smm;
5015 
5016 	role.base.level = level;
5017 	role.base.gpte_is_8_bytes = true;
5018 	role.base.direct = false;
5019 	role.base.ad_disabled = !accessed_dirty;
5020 	role.base.guest_mode = true;
5021 	role.base.access = ACC_ALL;
5022 
5023 	/*
5024 	 * WP=1 and NOT_WP=1 is an impossible combination, use WP and the
5025 	 * SMAP variation to denote shadow EPT entries.
5026 	 */
5027 	role.base.cr0_wp = true;
5028 	role.base.smap_andnot_wp = true;
5029 
5030 	role.ext = kvm_calc_mmu_role_ext(vcpu);
5031 	role.ext.execonly = execonly;
5032 
5033 	return role;
5034 }
5035 
5036 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
5037 			     bool accessed_dirty, gpa_t new_eptp)
5038 {
5039 	struct kvm_mmu *context = &vcpu->arch.guest_mmu;
5040 	u8 level = vmx_eptp_page_walk_level(new_eptp);
5041 	union kvm_mmu_role new_role =
5042 		kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty,
5043 						   execonly, level);
5044 
5045 	__kvm_mmu_new_pgd(vcpu, new_eptp, new_role.base, true, true);
5046 
5047 	if (new_role.as_u64 == context->mmu_role.as_u64)
5048 		return;
5049 
5050 	context->shadow_root_level = level;
5051 
5052 	context->nx = true;
5053 	context->ept_ad = accessed_dirty;
5054 	context->page_fault = ept_page_fault;
5055 	context->gva_to_gpa = ept_gva_to_gpa;
5056 	context->sync_page = ept_sync_page;
5057 	context->invlpg = ept_invlpg;
5058 	context->update_pte = ept_update_pte;
5059 	context->root_level = level;
5060 	context->direct_map = false;
5061 	context->mmu_role.as_u64 = new_role.as_u64;
5062 
5063 	update_permission_bitmask(vcpu, context, true);
5064 	update_pkru_bitmask(vcpu, context, true);
5065 	update_last_nonleaf_level(vcpu, context);
5066 	reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5067 	reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5068 }
5069 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5070 
5071 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5072 {
5073 	struct kvm_mmu *context = &vcpu->arch.root_mmu;
5074 
5075 	kvm_init_shadow_mmu(vcpu,
5076 			    kvm_read_cr0_bits(vcpu, X86_CR0_PG),
5077 			    kvm_read_cr4_bits(vcpu, X86_CR4_PAE),
5078 			    vcpu->arch.efer);
5079 
5080 	context->get_guest_pgd     = get_cr3;
5081 	context->get_pdptr         = kvm_pdptr_read;
5082 	context->inject_page_fault = kvm_inject_page_fault;
5083 }
5084 
5085 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5086 {
5087 	union kvm_mmu_role new_role = kvm_calc_mmu_role_common(vcpu, false);
5088 	struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5089 
5090 	if (new_role.as_u64 == g_context->mmu_role.as_u64)
5091 		return;
5092 
5093 	g_context->mmu_role.as_u64 = new_role.as_u64;
5094 	g_context->get_guest_pgd     = get_cr3;
5095 	g_context->get_pdptr         = kvm_pdptr_read;
5096 	g_context->inject_page_fault = kvm_inject_page_fault;
5097 
5098 	/*
5099 	 * L2 page tables are never shadowed, so there is no need to sync
5100 	 * SPTEs.
5101 	 */
5102 	g_context->invlpg            = NULL;
5103 
5104 	/*
5105 	 * Note that arch.mmu->gva_to_gpa translates l2_gpa to l1_gpa using
5106 	 * L1's nested page tables (e.g. EPT12). The nested translation
5107 	 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5108 	 * L2's page tables as the first level of translation and L1's
5109 	 * nested page tables as the second level of translation. Basically
5110 	 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5111 	 */
5112 	if (!is_paging(vcpu)) {
5113 		g_context->nx = false;
5114 		g_context->root_level = 0;
5115 		g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5116 	} else if (is_long_mode(vcpu)) {
5117 		g_context->nx = is_nx(vcpu);
5118 		g_context->root_level = is_la57_mode(vcpu) ?
5119 					PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5120 		reset_rsvds_bits_mask(vcpu, g_context);
5121 		g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5122 	} else if (is_pae(vcpu)) {
5123 		g_context->nx = is_nx(vcpu);
5124 		g_context->root_level = PT32E_ROOT_LEVEL;
5125 		reset_rsvds_bits_mask(vcpu, g_context);
5126 		g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5127 	} else {
5128 		g_context->nx = false;
5129 		g_context->root_level = PT32_ROOT_LEVEL;
5130 		reset_rsvds_bits_mask(vcpu, g_context);
5131 		g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5132 	}
5133 
5134 	update_permission_bitmask(vcpu, g_context, false);
5135 	update_pkru_bitmask(vcpu, g_context, false);
5136 	update_last_nonleaf_level(vcpu, g_context);
5137 }
5138 
5139 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5140 {
5141 	if (reset_roots) {
5142 		uint i;
5143 
5144 		vcpu->arch.mmu->root_hpa = INVALID_PAGE;
5145 
5146 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5147 			vcpu->arch.mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5148 	}
5149 
5150 	if (mmu_is_nested(vcpu))
5151 		init_kvm_nested_mmu(vcpu);
5152 	else if (tdp_enabled)
5153 		init_kvm_tdp_mmu(vcpu);
5154 	else
5155 		init_kvm_softmmu(vcpu);
5156 }
5157 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5158 
5159 static union kvm_mmu_page_role
5160 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5161 {
5162 	union kvm_mmu_role role;
5163 
5164 	if (tdp_enabled)
5165 		role = kvm_calc_tdp_mmu_root_page_role(vcpu, true);
5166 	else
5167 		role = kvm_calc_shadow_mmu_root_page_role(vcpu, true);
5168 
5169 	return role.base;
5170 }
5171 
5172 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5173 {
5174 	kvm_mmu_unload(vcpu);
5175 	kvm_init_mmu(vcpu, true);
5176 }
5177 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5178 
5179 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5180 {
5181 	int r;
5182 
5183 	r = mmu_topup_memory_caches(vcpu, !vcpu->arch.mmu->direct_map);
5184 	if (r)
5185 		goto out;
5186 	r = mmu_alloc_roots(vcpu);
5187 	kvm_mmu_sync_roots(vcpu);
5188 	if (r)
5189 		goto out;
5190 	kvm_mmu_load_pgd(vcpu);
5191 	kvm_x86_ops.tlb_flush_current(vcpu);
5192 out:
5193 	return r;
5194 }
5195 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5196 
5197 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5198 {
5199 	kvm_mmu_free_roots(vcpu, &vcpu->arch.root_mmu, KVM_MMU_ROOTS_ALL);
5200 	WARN_ON(VALID_PAGE(vcpu->arch.root_mmu.root_hpa));
5201 	kvm_mmu_free_roots(vcpu, &vcpu->arch.guest_mmu, KVM_MMU_ROOTS_ALL);
5202 	WARN_ON(VALID_PAGE(vcpu->arch.guest_mmu.root_hpa));
5203 }
5204 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5205 
5206 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5207 				  struct kvm_mmu_page *sp, u64 *spte,
5208 				  const void *new)
5209 {
5210 	if (sp->role.level != PG_LEVEL_4K) {
5211 		++vcpu->kvm->stat.mmu_pde_zapped;
5212 		return;
5213         }
5214 
5215 	++vcpu->kvm->stat.mmu_pte_updated;
5216 	vcpu->arch.mmu->update_pte(vcpu, sp, spte, new);
5217 }
5218 
5219 static bool need_remote_flush(u64 old, u64 new)
5220 {
5221 	if (!is_shadow_present_pte(old))
5222 		return false;
5223 	if (!is_shadow_present_pte(new))
5224 		return true;
5225 	if ((old ^ new) & PT64_BASE_ADDR_MASK)
5226 		return true;
5227 	old ^= shadow_nx_mask;
5228 	new ^= shadow_nx_mask;
5229 	return (old & ~new & PT64_PERM_MASK) != 0;
5230 }
5231 
5232 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5233 				    int *bytes)
5234 {
5235 	u64 gentry = 0;
5236 	int r;
5237 
5238 	/*
5239 	 * Assume that the pte write on a page table of the same type
5240 	 * as the current vcpu paging mode since we update the sptes only
5241 	 * when they have the same mode.
5242 	 */
5243 	if (is_pae(vcpu) && *bytes == 4) {
5244 		/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5245 		*gpa &= ~(gpa_t)7;
5246 		*bytes = 8;
5247 	}
5248 
5249 	if (*bytes == 4 || *bytes == 8) {
5250 		r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5251 		if (r)
5252 			gentry = 0;
5253 	}
5254 
5255 	return gentry;
5256 }
5257 
5258 /*
5259  * If we're seeing too many writes to a page, it may no longer be a page table,
5260  * or we may be forking, in which case it is better to unmap the page.
5261  */
5262 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5263 {
5264 	/*
5265 	 * Skip write-flooding detected for the sp whose level is 1, because
5266 	 * it can become unsync, then the guest page is not write-protected.
5267 	 */
5268 	if (sp->role.level == PG_LEVEL_4K)
5269 		return false;
5270 
5271 	atomic_inc(&sp->write_flooding_count);
5272 	return atomic_read(&sp->write_flooding_count) >= 3;
5273 }
5274 
5275 /*
5276  * Misaligned accesses are too much trouble to fix up; also, they usually
5277  * indicate a page is not used as a page table.
5278  */
5279 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5280 				    int bytes)
5281 {
5282 	unsigned offset, pte_size, misaligned;
5283 
5284 	pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5285 		 gpa, bytes, sp->role.word);
5286 
5287 	offset = offset_in_page(gpa);
5288 	pte_size = sp->role.gpte_is_8_bytes ? 8 : 4;
5289 
5290 	/*
5291 	 * Sometimes, the OS only writes the last one bytes to update status
5292 	 * bits, for example, in linux, andb instruction is used in clear_bit().
5293 	 */
5294 	if (!(offset & (pte_size - 1)) && bytes == 1)
5295 		return false;
5296 
5297 	misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5298 	misaligned |= bytes < 4;
5299 
5300 	return misaligned;
5301 }
5302 
5303 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5304 {
5305 	unsigned page_offset, quadrant;
5306 	u64 *spte;
5307 	int level;
5308 
5309 	page_offset = offset_in_page(gpa);
5310 	level = sp->role.level;
5311 	*nspte = 1;
5312 	if (!sp->role.gpte_is_8_bytes) {
5313 		page_offset <<= 1;	/* 32->64 */
5314 		/*
5315 		 * A 32-bit pde maps 4MB while the shadow pdes map
5316 		 * only 2MB.  So we need to double the offset again
5317 		 * and zap two pdes instead of one.
5318 		 */
5319 		if (level == PT32_ROOT_LEVEL) {
5320 			page_offset &= ~7; /* kill rounding error */
5321 			page_offset <<= 1;
5322 			*nspte = 2;
5323 		}
5324 		quadrant = page_offset >> PAGE_SHIFT;
5325 		page_offset &= ~PAGE_MASK;
5326 		if (quadrant != sp->role.quadrant)
5327 			return NULL;
5328 	}
5329 
5330 	spte = &sp->spt[page_offset / sizeof(*spte)];
5331 	return spte;
5332 }
5333 
5334 /*
5335  * Ignore various flags when determining if a SPTE can be immediately
5336  * overwritten for the current MMU.
5337  *  - level: explicitly checked in mmu_pte_write_new_pte(), and will never
5338  *    match the current MMU role, as MMU's level tracks the root level.
5339  *  - access: updated based on the new guest PTE
5340  *  - quadrant: handled by get_written_sptes()
5341  *  - invalid: always false (loop only walks valid shadow pages)
5342  */
5343 static const union kvm_mmu_page_role role_ign = {
5344 	.level = 0xf,
5345 	.access = 0x7,
5346 	.quadrant = 0x3,
5347 	.invalid = 0x1,
5348 };
5349 
5350 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5351 			      const u8 *new, int bytes,
5352 			      struct kvm_page_track_notifier_node *node)
5353 {
5354 	gfn_t gfn = gpa >> PAGE_SHIFT;
5355 	struct kvm_mmu_page *sp;
5356 	LIST_HEAD(invalid_list);
5357 	u64 entry, gentry, *spte;
5358 	int npte;
5359 	bool remote_flush, local_flush;
5360 
5361 	/*
5362 	 * If we don't have indirect shadow pages, it means no page is
5363 	 * write-protected, so we can exit simply.
5364 	 */
5365 	if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5366 		return;
5367 
5368 	remote_flush = local_flush = false;
5369 
5370 	pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5371 
5372 	/*
5373 	 * No need to care whether allocation memory is successful
5374 	 * or not since pte prefetch is skiped if it does not have
5375 	 * enough objects in the cache.
5376 	 */
5377 	mmu_topup_memory_caches(vcpu, true);
5378 
5379 	spin_lock(&vcpu->kvm->mmu_lock);
5380 
5381 	gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5382 
5383 	++vcpu->kvm->stat.mmu_pte_write;
5384 	kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5385 
5386 	for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5387 		if (detect_write_misaligned(sp, gpa, bytes) ||
5388 		      detect_write_flooding(sp)) {
5389 			kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5390 			++vcpu->kvm->stat.mmu_flooded;
5391 			continue;
5392 		}
5393 
5394 		spte = get_written_sptes(sp, gpa, &npte);
5395 		if (!spte)
5396 			continue;
5397 
5398 		local_flush = true;
5399 		while (npte--) {
5400 			u32 base_role = vcpu->arch.mmu->mmu_role.base.word;
5401 
5402 			entry = *spte;
5403 			mmu_page_zap_pte(vcpu->kvm, sp, spte);
5404 			if (gentry &&
5405 			    !((sp->role.word ^ base_role) & ~role_ign.word) &&
5406 			    rmap_can_add(vcpu))
5407 				mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5408 			if (need_remote_flush(entry, *spte))
5409 				remote_flush = true;
5410 			++spte;
5411 		}
5412 	}
5413 	kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5414 	kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5415 	spin_unlock(&vcpu->kvm->mmu_lock);
5416 }
5417 
5418 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5419 {
5420 	gpa_t gpa;
5421 	int r;
5422 
5423 	if (vcpu->arch.mmu->direct_map)
5424 		return 0;
5425 
5426 	gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5427 
5428 	r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5429 
5430 	return r;
5431 }
5432 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5433 
5434 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5435 		       void *insn, int insn_len)
5436 {
5437 	int r, emulation_type = EMULTYPE_PF;
5438 	bool direct = vcpu->arch.mmu->direct_map;
5439 
5440 	if (WARN_ON(!VALID_PAGE(vcpu->arch.mmu->root_hpa)))
5441 		return RET_PF_RETRY;
5442 
5443 	r = RET_PF_INVALID;
5444 	if (unlikely(error_code & PFERR_RSVD_MASK)) {
5445 		r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5446 		if (r == RET_PF_EMULATE)
5447 			goto emulate;
5448 	}
5449 
5450 	if (r == RET_PF_INVALID) {
5451 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
5452 					  lower_32_bits(error_code), false);
5453 		WARN_ON(r == RET_PF_INVALID);
5454 	}
5455 
5456 	if (r == RET_PF_RETRY)
5457 		return 1;
5458 	if (r < 0)
5459 		return r;
5460 
5461 	/*
5462 	 * Before emulating the instruction, check if the error code
5463 	 * was due to a RO violation while translating the guest page.
5464 	 * This can occur when using nested virtualization with nested
5465 	 * paging in both guests. If true, we simply unprotect the page
5466 	 * and resume the guest.
5467 	 */
5468 	if (vcpu->arch.mmu->direct_map &&
5469 	    (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5470 		kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5471 		return 1;
5472 	}
5473 
5474 	/*
5475 	 * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5476 	 * optimistically try to just unprotect the page and let the processor
5477 	 * re-execute the instruction that caused the page fault.  Do not allow
5478 	 * retrying MMIO emulation, as it's not only pointless but could also
5479 	 * cause us to enter an infinite loop because the processor will keep
5480 	 * faulting on the non-existent MMIO address.  Retrying an instruction
5481 	 * from a nested guest is also pointless and dangerous as we are only
5482 	 * explicitly shadowing L1's page tables, i.e. unprotecting something
5483 	 * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5484 	 */
5485 	if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5486 		emulation_type |= EMULTYPE_ALLOW_RETRY_PF;
5487 emulate:
5488 	/*
5489 	 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5490 	 * This can happen if a guest gets a page-fault on data access but the HW
5491 	 * table walker is not able to read the instruction page (e.g instruction
5492 	 * page is not present in memory). In those cases we simply restart the
5493 	 * guest, with the exception of AMD Erratum 1096 which is unrecoverable.
5494 	 */
5495 	if (unlikely(insn && !insn_len)) {
5496 		if (!kvm_x86_ops.need_emulation_on_page_fault(vcpu))
5497 			return 1;
5498 	}
5499 
5500 	return x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn,
5501 				       insn_len);
5502 }
5503 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5504 
5505 void kvm_mmu_invalidate_gva(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
5506 			    gva_t gva, hpa_t root_hpa)
5507 {
5508 	int i;
5509 
5510 	/* It's actually a GPA for vcpu->arch.guest_mmu.  */
5511 	if (mmu != &vcpu->arch.guest_mmu) {
5512 		/* INVLPG on a non-canonical address is a NOP according to the SDM.  */
5513 		if (is_noncanonical_address(gva, vcpu))
5514 			return;
5515 
5516 		kvm_x86_ops.tlb_flush_gva(vcpu, gva);
5517 	}
5518 
5519 	if (!mmu->invlpg)
5520 		return;
5521 
5522 	if (root_hpa == INVALID_PAGE) {
5523 		mmu->invlpg(vcpu, gva, mmu->root_hpa);
5524 
5525 		/*
5526 		 * INVLPG is required to invalidate any global mappings for the VA,
5527 		 * irrespective of PCID. Since it would take us roughly similar amount
5528 		 * of work to determine whether any of the prev_root mappings of the VA
5529 		 * is marked global, or to just sync it blindly, so we might as well
5530 		 * just always sync it.
5531 		 *
5532 		 * Mappings not reachable via the current cr3 or the prev_roots will be
5533 		 * synced when switching to that cr3, so nothing needs to be done here
5534 		 * for them.
5535 		 */
5536 		for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5537 			if (VALID_PAGE(mmu->prev_roots[i].hpa))
5538 				mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5539 	} else {
5540 		mmu->invlpg(vcpu, gva, root_hpa);
5541 	}
5542 }
5543 EXPORT_SYMBOL_GPL(kvm_mmu_invalidate_gva);
5544 
5545 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5546 {
5547 	kvm_mmu_invalidate_gva(vcpu, vcpu->arch.mmu, gva, INVALID_PAGE);
5548 	++vcpu->stat.invlpg;
5549 }
5550 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5551 
5552 
5553 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5554 {
5555 	struct kvm_mmu *mmu = vcpu->arch.mmu;
5556 	bool tlb_flush = false;
5557 	uint i;
5558 
5559 	if (pcid == kvm_get_active_pcid(vcpu)) {
5560 		mmu->invlpg(vcpu, gva, mmu->root_hpa);
5561 		tlb_flush = true;
5562 	}
5563 
5564 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5565 		if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5566 		    pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].pgd)) {
5567 			mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5568 			tlb_flush = true;
5569 		}
5570 	}
5571 
5572 	if (tlb_flush)
5573 		kvm_x86_ops.tlb_flush_gva(vcpu, gva);
5574 
5575 	++vcpu->stat.invlpg;
5576 
5577 	/*
5578 	 * Mappings not reachable via the current cr3 or the prev_roots will be
5579 	 * synced when switching to that cr3, so nothing needs to be done here
5580 	 * for them.
5581 	 */
5582 }
5583 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5584 
5585 void kvm_configure_mmu(bool enable_tdp, int tdp_max_root_level,
5586 		       int tdp_huge_page_level)
5587 {
5588 	tdp_enabled = enable_tdp;
5589 	max_tdp_level = tdp_max_root_level;
5590 
5591 	/*
5592 	 * max_huge_page_level reflects KVM's MMU capabilities irrespective
5593 	 * of kernel support, e.g. KVM may be capable of using 1GB pages when
5594 	 * the kernel is not.  But, KVM never creates a page size greater than
5595 	 * what is used by the kernel for any given HVA, i.e. the kernel's
5596 	 * capabilities are ultimately consulted by kvm_mmu_hugepage_adjust().
5597 	 */
5598 	if (tdp_enabled)
5599 		max_huge_page_level = tdp_huge_page_level;
5600 	else if (boot_cpu_has(X86_FEATURE_GBPAGES))
5601 		max_huge_page_level = PG_LEVEL_1G;
5602 	else
5603 		max_huge_page_level = PG_LEVEL_2M;
5604 }
5605 EXPORT_SYMBOL_GPL(kvm_configure_mmu);
5606 
5607 /* The return value indicates if tlb flush on all vcpus is needed. */
5608 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5609 
5610 /* The caller should hold mmu-lock before calling this function. */
5611 static __always_inline bool
5612 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5613 			slot_level_handler fn, int start_level, int end_level,
5614 			gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5615 {
5616 	struct slot_rmap_walk_iterator iterator;
5617 	bool flush = false;
5618 
5619 	for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5620 			end_gfn, &iterator) {
5621 		if (iterator.rmap)
5622 			flush |= fn(kvm, iterator.rmap);
5623 
5624 		if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5625 			if (flush && lock_flush_tlb) {
5626 				kvm_flush_remote_tlbs_with_address(kvm,
5627 						start_gfn,
5628 						iterator.gfn - start_gfn + 1);
5629 				flush = false;
5630 			}
5631 			cond_resched_lock(&kvm->mmu_lock);
5632 		}
5633 	}
5634 
5635 	if (flush && lock_flush_tlb) {
5636 		kvm_flush_remote_tlbs_with_address(kvm, start_gfn,
5637 						   end_gfn - start_gfn + 1);
5638 		flush = false;
5639 	}
5640 
5641 	return flush;
5642 }
5643 
5644 static __always_inline bool
5645 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5646 		  slot_level_handler fn, int start_level, int end_level,
5647 		  bool lock_flush_tlb)
5648 {
5649 	return slot_handle_level_range(kvm, memslot, fn, start_level,
5650 			end_level, memslot->base_gfn,
5651 			memslot->base_gfn + memslot->npages - 1,
5652 			lock_flush_tlb);
5653 }
5654 
5655 static __always_inline bool
5656 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5657 		      slot_level_handler fn, bool lock_flush_tlb)
5658 {
5659 	return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5660 				 KVM_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5661 }
5662 
5663 static __always_inline bool
5664 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5665 			slot_level_handler fn, bool lock_flush_tlb)
5666 {
5667 	return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K + 1,
5668 				 KVM_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5669 }
5670 
5671 static __always_inline bool
5672 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5673 		 slot_level_handler fn, bool lock_flush_tlb)
5674 {
5675 	return slot_handle_level(kvm, memslot, fn, PG_LEVEL_4K,
5676 				 PG_LEVEL_4K, lock_flush_tlb);
5677 }
5678 
5679 static void free_mmu_pages(struct kvm_mmu *mmu)
5680 {
5681 	free_page((unsigned long)mmu->pae_root);
5682 	free_page((unsigned long)mmu->lm_root);
5683 }
5684 
5685 static int alloc_mmu_pages(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
5686 {
5687 	struct page *page;
5688 	int i;
5689 
5690 	/*
5691 	 * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5692 	 * while the PDP table is a per-vCPU construct that's allocated at MMU
5693 	 * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
5694 	 * x86_64.  Therefore we need to allocate the PDP table in the first
5695 	 * 4GB of memory, which happens to fit the DMA32 zone.  Except for
5696 	 * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5697 	 * skip allocating the PDP table.
5698 	 */
5699 	if (tdp_enabled && kvm_mmu_get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5700 		return 0;
5701 
5702 	page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_DMA32);
5703 	if (!page)
5704 		return -ENOMEM;
5705 
5706 	mmu->pae_root = page_address(page);
5707 	for (i = 0; i < 4; ++i)
5708 		mmu->pae_root[i] = INVALID_PAGE;
5709 
5710 	return 0;
5711 }
5712 
5713 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5714 {
5715 	uint i;
5716 	int ret;
5717 
5718 	vcpu->arch.mmu_pte_list_desc_cache.kmem_cache = pte_list_desc_cache;
5719 	vcpu->arch.mmu_pte_list_desc_cache.gfp_zero = __GFP_ZERO;
5720 
5721 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
5722 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
5723 
5724 	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
5725 
5726 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
5727 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
5728 
5729 	vcpu->arch.root_mmu.root_hpa = INVALID_PAGE;
5730 	vcpu->arch.root_mmu.root_pgd = 0;
5731 	vcpu->arch.root_mmu.translate_gpa = translate_gpa;
5732 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5733 		vcpu->arch.root_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5734 
5735 	vcpu->arch.guest_mmu.root_hpa = INVALID_PAGE;
5736 	vcpu->arch.guest_mmu.root_pgd = 0;
5737 	vcpu->arch.guest_mmu.translate_gpa = translate_gpa;
5738 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5739 		vcpu->arch.guest_mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5740 
5741 	vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5742 
5743 	ret = alloc_mmu_pages(vcpu, &vcpu->arch.guest_mmu);
5744 	if (ret)
5745 		return ret;
5746 
5747 	ret = alloc_mmu_pages(vcpu, &vcpu->arch.root_mmu);
5748 	if (ret)
5749 		goto fail_allocate_root;
5750 
5751 	return ret;
5752  fail_allocate_root:
5753 	free_mmu_pages(&vcpu->arch.guest_mmu);
5754 	return ret;
5755 }
5756 
5757 #define BATCH_ZAP_PAGES	10
5758 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5759 {
5760 	struct kvm_mmu_page *sp, *node;
5761 	int nr_zapped, batch = 0;
5762 
5763 restart:
5764 	list_for_each_entry_safe_reverse(sp, node,
5765 	      &kvm->arch.active_mmu_pages, link) {
5766 		/*
5767 		 * No obsolete valid page exists before a newly created page
5768 		 * since active_mmu_pages is a FIFO list.
5769 		 */
5770 		if (!is_obsolete_sp(kvm, sp))
5771 			break;
5772 
5773 		/*
5774 		 * Invalid pages should never land back on the list of active
5775 		 * pages.  Skip the bogus page, otherwise we'll get stuck in an
5776 		 * infinite loop if the page gets put back on the list (again).
5777 		 */
5778 		if (WARN_ON(sp->role.invalid))
5779 			continue;
5780 
5781 		/*
5782 		 * No need to flush the TLB since we're only zapping shadow
5783 		 * pages with an obsolete generation number and all vCPUS have
5784 		 * loaded a new root, i.e. the shadow pages being zapped cannot
5785 		 * be in active use by the guest.
5786 		 */
5787 		if (batch >= BATCH_ZAP_PAGES &&
5788 		    cond_resched_lock(&kvm->mmu_lock)) {
5789 			batch = 0;
5790 			goto restart;
5791 		}
5792 
5793 		if (__kvm_mmu_prepare_zap_page(kvm, sp,
5794 				&kvm->arch.zapped_obsolete_pages, &nr_zapped)) {
5795 			batch += nr_zapped;
5796 			goto restart;
5797 		}
5798 	}
5799 
5800 	/*
5801 	 * Trigger a remote TLB flush before freeing the page tables to ensure
5802 	 * KVM is not in the middle of a lockless shadow page table walk, which
5803 	 * may reference the pages.
5804 	 */
5805 	kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5806 }
5807 
5808 /*
5809  * Fast invalidate all shadow pages and use lock-break technique
5810  * to zap obsolete pages.
5811  *
5812  * It's required when memslot is being deleted or VM is being
5813  * destroyed, in these cases, we should ensure that KVM MMU does
5814  * not use any resource of the being-deleted slot or all slots
5815  * after calling the function.
5816  */
5817 static void kvm_mmu_zap_all_fast(struct kvm *kvm)
5818 {
5819 	lockdep_assert_held(&kvm->slots_lock);
5820 
5821 	spin_lock(&kvm->mmu_lock);
5822 	trace_kvm_mmu_zap_all_fast(kvm);
5823 
5824 	/*
5825 	 * Toggle mmu_valid_gen between '0' and '1'.  Because slots_lock is
5826 	 * held for the entire duration of zapping obsolete pages, it's
5827 	 * impossible for there to be multiple invalid generations associated
5828 	 * with *valid* shadow pages at any given time, i.e. there is exactly
5829 	 * one valid generation and (at most) one invalid generation.
5830 	 */
5831 	kvm->arch.mmu_valid_gen = kvm->arch.mmu_valid_gen ? 0 : 1;
5832 
5833 	/*
5834 	 * Notify all vcpus to reload its shadow page table and flush TLB.
5835 	 * Then all vcpus will switch to new shadow page table with the new
5836 	 * mmu_valid_gen.
5837 	 *
5838 	 * Note: we need to do this under the protection of mmu_lock,
5839 	 * otherwise, vcpu would purge shadow page but miss tlb flush.
5840 	 */
5841 	kvm_reload_remote_mmus(kvm);
5842 
5843 	kvm_zap_obsolete_pages(kvm);
5844 	spin_unlock(&kvm->mmu_lock);
5845 }
5846 
5847 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5848 {
5849 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5850 }
5851 
5852 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5853 			struct kvm_memory_slot *slot,
5854 			struct kvm_page_track_notifier_node *node)
5855 {
5856 	kvm_mmu_zap_all_fast(kvm);
5857 }
5858 
5859 void kvm_mmu_init_vm(struct kvm *kvm)
5860 {
5861 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5862 
5863 	node->track_write = kvm_mmu_pte_write;
5864 	node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5865 	kvm_page_track_register_notifier(kvm, node);
5866 }
5867 
5868 void kvm_mmu_uninit_vm(struct kvm *kvm)
5869 {
5870 	struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5871 
5872 	kvm_page_track_unregister_notifier(kvm, node);
5873 }
5874 
5875 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5876 {
5877 	struct kvm_memslots *slots;
5878 	struct kvm_memory_slot *memslot;
5879 	int i;
5880 
5881 	spin_lock(&kvm->mmu_lock);
5882 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5883 		slots = __kvm_memslots(kvm, i);
5884 		kvm_for_each_memslot(memslot, slots) {
5885 			gfn_t start, end;
5886 
5887 			start = max(gfn_start, memslot->base_gfn);
5888 			end = min(gfn_end, memslot->base_gfn + memslot->npages);
5889 			if (start >= end)
5890 				continue;
5891 
5892 			slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5893 						PG_LEVEL_4K,
5894 						KVM_MAX_HUGEPAGE_LEVEL,
5895 						start, end - 1, true);
5896 		}
5897 	}
5898 
5899 	spin_unlock(&kvm->mmu_lock);
5900 }
5901 
5902 static bool slot_rmap_write_protect(struct kvm *kvm,
5903 				    struct kvm_rmap_head *rmap_head)
5904 {
5905 	return __rmap_write_protect(kvm, rmap_head, false);
5906 }
5907 
5908 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5909 				      struct kvm_memory_slot *memslot,
5910 				      int start_level)
5911 {
5912 	bool flush;
5913 
5914 	spin_lock(&kvm->mmu_lock);
5915 	flush = slot_handle_level(kvm, memslot, slot_rmap_write_protect,
5916 				start_level, KVM_MAX_HUGEPAGE_LEVEL, false);
5917 	spin_unlock(&kvm->mmu_lock);
5918 
5919 	/*
5920 	 * We can flush all the TLBs out of the mmu lock without TLB
5921 	 * corruption since we just change the spte from writable to
5922 	 * readonly so that we only need to care the case of changing
5923 	 * spte from present to present (changing the spte from present
5924 	 * to nonpresent will flush all the TLBs immediately), in other
5925 	 * words, the only case we care is mmu_spte_update() where we
5926 	 * have checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5927 	 * instead of PT_WRITABLE_MASK, that means it does not depend
5928 	 * on PT_WRITABLE_MASK anymore.
5929 	 */
5930 	if (flush)
5931 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
5932 }
5933 
5934 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5935 					 struct kvm_rmap_head *rmap_head)
5936 {
5937 	u64 *sptep;
5938 	struct rmap_iterator iter;
5939 	int need_tlb_flush = 0;
5940 	kvm_pfn_t pfn;
5941 	struct kvm_mmu_page *sp;
5942 
5943 restart:
5944 	for_each_rmap_spte(rmap_head, &iter, sptep) {
5945 		sp = sptep_to_sp(sptep);
5946 		pfn = spte_to_pfn(*sptep);
5947 
5948 		/*
5949 		 * We cannot do huge page mapping for indirect shadow pages,
5950 		 * which are found on the last rmap (level = 1) when not using
5951 		 * tdp; such shadow pages are synced with the page table in
5952 		 * the guest, and the guest page table is using 4K page size
5953 		 * mapping if the indirect sp has level = 1.
5954 		 */
5955 		if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
5956 		    (kvm_is_zone_device_pfn(pfn) ||
5957 		     PageCompound(pfn_to_page(pfn)))) {
5958 			pte_list_remove(rmap_head, sptep);
5959 
5960 			if (kvm_available_flush_tlb_with_range())
5961 				kvm_flush_remote_tlbs_with_address(kvm, sp->gfn,
5962 					KVM_PAGES_PER_HPAGE(sp->role.level));
5963 			else
5964 				need_tlb_flush = 1;
5965 
5966 			goto restart;
5967 		}
5968 	}
5969 
5970 	return need_tlb_flush;
5971 }
5972 
5973 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5974 				   const struct kvm_memory_slot *memslot)
5975 {
5976 	/* FIXME: const-ify all uses of struct kvm_memory_slot.  */
5977 	spin_lock(&kvm->mmu_lock);
5978 	slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5979 			 kvm_mmu_zap_collapsible_spte, true);
5980 	spin_unlock(&kvm->mmu_lock);
5981 }
5982 
5983 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
5984 					struct kvm_memory_slot *memslot)
5985 {
5986 	/*
5987 	 * All current use cases for flushing the TLBs for a specific memslot
5988 	 * are related to dirty logging, and do the TLB flush out of mmu_lock.
5989 	 * The interaction between the various operations on memslot must be
5990 	 * serialized by slots_locks to ensure the TLB flush from one operation
5991 	 * is observed by any other operation on the same memslot.
5992 	 */
5993 	lockdep_assert_held(&kvm->slots_lock);
5994 	kvm_flush_remote_tlbs_with_address(kvm, memslot->base_gfn,
5995 					   memslot->npages);
5996 }
5997 
5998 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5999 				   struct kvm_memory_slot *memslot)
6000 {
6001 	bool flush;
6002 
6003 	spin_lock(&kvm->mmu_lock);
6004 	flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
6005 	spin_unlock(&kvm->mmu_lock);
6006 
6007 	/*
6008 	 * It's also safe to flush TLBs out of mmu lock here as currently this
6009 	 * function is only used for dirty logging, in which case flushing TLB
6010 	 * out of mmu lock also guarantees no dirty pages will be lost in
6011 	 * dirty_bitmap.
6012 	 */
6013 	if (flush)
6014 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6015 }
6016 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
6017 
6018 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
6019 					struct kvm_memory_slot *memslot)
6020 {
6021 	bool flush;
6022 
6023 	spin_lock(&kvm->mmu_lock);
6024 	flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
6025 					false);
6026 	spin_unlock(&kvm->mmu_lock);
6027 
6028 	if (flush)
6029 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6030 }
6031 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
6032 
6033 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
6034 			    struct kvm_memory_slot *memslot)
6035 {
6036 	bool flush;
6037 
6038 	spin_lock(&kvm->mmu_lock);
6039 	flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
6040 	spin_unlock(&kvm->mmu_lock);
6041 
6042 	if (flush)
6043 		kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
6044 }
6045 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
6046 
6047 void kvm_mmu_zap_all(struct kvm *kvm)
6048 {
6049 	struct kvm_mmu_page *sp, *node;
6050 	LIST_HEAD(invalid_list);
6051 	int ign;
6052 
6053 	spin_lock(&kvm->mmu_lock);
6054 restart:
6055 	list_for_each_entry_safe(sp, node, &kvm->arch.active_mmu_pages, link) {
6056 		if (WARN_ON(sp->role.invalid))
6057 			continue;
6058 		if (__kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list, &ign))
6059 			goto restart;
6060 		if (cond_resched_lock(&kvm->mmu_lock))
6061 			goto restart;
6062 	}
6063 
6064 	kvm_mmu_commit_zap_page(kvm, &invalid_list);
6065 	spin_unlock(&kvm->mmu_lock);
6066 }
6067 
6068 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
6069 {
6070 	WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
6071 
6072 	gen &= MMIO_SPTE_GEN_MASK;
6073 
6074 	/*
6075 	 * Generation numbers are incremented in multiples of the number of
6076 	 * address spaces in order to provide unique generations across all
6077 	 * address spaces.  Strip what is effectively the address space
6078 	 * modifier prior to checking for a wrap of the MMIO generation so
6079 	 * that a wrap in any address space is detected.
6080 	 */
6081 	gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
6082 
6083 	/*
6084 	 * The very rare case: if the MMIO generation number has wrapped,
6085 	 * zap all shadow pages.
6086 	 */
6087 	if (unlikely(gen == 0)) {
6088 		kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
6089 		kvm_mmu_zap_all_fast(kvm);
6090 	}
6091 }
6092 
6093 static unsigned long
6094 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
6095 {
6096 	struct kvm *kvm;
6097 	int nr_to_scan = sc->nr_to_scan;
6098 	unsigned long freed = 0;
6099 
6100 	mutex_lock(&kvm_lock);
6101 
6102 	list_for_each_entry(kvm, &vm_list, vm_list) {
6103 		int idx;
6104 		LIST_HEAD(invalid_list);
6105 
6106 		/*
6107 		 * Never scan more than sc->nr_to_scan VM instances.
6108 		 * Will not hit this condition practically since we do not try
6109 		 * to shrink more than one VM and it is very unlikely to see
6110 		 * !n_used_mmu_pages so many times.
6111 		 */
6112 		if (!nr_to_scan--)
6113 			break;
6114 		/*
6115 		 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
6116 		 * here. We may skip a VM instance errorneosly, but we do not
6117 		 * want to shrink a VM that only started to populate its MMU
6118 		 * anyway.
6119 		 */
6120 		if (!kvm->arch.n_used_mmu_pages &&
6121 		    !kvm_has_zapped_obsolete_pages(kvm))
6122 			continue;
6123 
6124 		idx = srcu_read_lock(&kvm->srcu);
6125 		spin_lock(&kvm->mmu_lock);
6126 
6127 		if (kvm_has_zapped_obsolete_pages(kvm)) {
6128 			kvm_mmu_commit_zap_page(kvm,
6129 			      &kvm->arch.zapped_obsolete_pages);
6130 			goto unlock;
6131 		}
6132 
6133 		freed = kvm_mmu_zap_oldest_mmu_pages(kvm, sc->nr_to_scan);
6134 
6135 unlock:
6136 		spin_unlock(&kvm->mmu_lock);
6137 		srcu_read_unlock(&kvm->srcu, idx);
6138 
6139 		/*
6140 		 * unfair on small ones
6141 		 * per-vm shrinkers cry out
6142 		 * sadness comes quickly
6143 		 */
6144 		list_move_tail(&kvm->vm_list, &vm_list);
6145 		break;
6146 	}
6147 
6148 	mutex_unlock(&kvm_lock);
6149 	return freed;
6150 }
6151 
6152 static unsigned long
6153 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6154 {
6155 	return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6156 }
6157 
6158 static struct shrinker mmu_shrinker = {
6159 	.count_objects = mmu_shrink_count,
6160 	.scan_objects = mmu_shrink_scan,
6161 	.seeks = DEFAULT_SEEKS * 10,
6162 };
6163 
6164 static void mmu_destroy_caches(void)
6165 {
6166 	kmem_cache_destroy(pte_list_desc_cache);
6167 	kmem_cache_destroy(mmu_page_header_cache);
6168 }
6169 
6170 static void kvm_set_mmio_spte_mask(void)
6171 {
6172 	u64 mask;
6173 
6174 	/*
6175 	 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
6176 	 * PFEC.RSVD=1 on MMIO accesses.  64-bit PTEs (PAE, x86-64, and EPT
6177 	 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
6178 	 * 52-bit physical addresses then there are no reserved PA bits in the
6179 	 * PTEs and so the reserved PA approach must be disabled.
6180 	 */
6181 	if (shadow_phys_bits < 52)
6182 		mask = BIT_ULL(51) | PT_PRESENT_MASK;
6183 	else
6184 		mask = 0;
6185 
6186 	kvm_mmu_set_mmio_spte_mask(mask, ACC_WRITE_MASK | ACC_USER_MASK);
6187 }
6188 
6189 static bool get_nx_auto_mode(void)
6190 {
6191 	/* Return true when CPU has the bug, and mitigations are ON */
6192 	return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6193 }
6194 
6195 static void __set_nx_huge_pages(bool val)
6196 {
6197 	nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6198 }
6199 
6200 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6201 {
6202 	bool old_val = nx_huge_pages;
6203 	bool new_val;
6204 
6205 	/* In "auto" mode deploy workaround only if CPU has the bug. */
6206 	if (sysfs_streq(val, "off"))
6207 		new_val = 0;
6208 	else if (sysfs_streq(val, "force"))
6209 		new_val = 1;
6210 	else if (sysfs_streq(val, "auto"))
6211 		new_val = get_nx_auto_mode();
6212 	else if (strtobool(val, &new_val) < 0)
6213 		return -EINVAL;
6214 
6215 	__set_nx_huge_pages(new_val);
6216 
6217 	if (new_val != old_val) {
6218 		struct kvm *kvm;
6219 
6220 		mutex_lock(&kvm_lock);
6221 
6222 		list_for_each_entry(kvm, &vm_list, vm_list) {
6223 			mutex_lock(&kvm->slots_lock);
6224 			kvm_mmu_zap_all_fast(kvm);
6225 			mutex_unlock(&kvm->slots_lock);
6226 
6227 			wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6228 		}
6229 		mutex_unlock(&kvm_lock);
6230 	}
6231 
6232 	return 0;
6233 }
6234 
6235 int kvm_mmu_module_init(void)
6236 {
6237 	int ret = -ENOMEM;
6238 
6239 	if (nx_huge_pages == -1)
6240 		__set_nx_huge_pages(get_nx_auto_mode());
6241 
6242 	/*
6243 	 * MMU roles use union aliasing which is, generally speaking, an
6244 	 * undefined behavior. However, we supposedly know how compilers behave
6245 	 * and the current status quo is unlikely to change. Guardians below are
6246 	 * supposed to let us know if the assumption becomes false.
6247 	 */
6248 	BUILD_BUG_ON(sizeof(union kvm_mmu_page_role) != sizeof(u32));
6249 	BUILD_BUG_ON(sizeof(union kvm_mmu_extended_role) != sizeof(u32));
6250 	BUILD_BUG_ON(sizeof(union kvm_mmu_role) != sizeof(u64));
6251 
6252 	kvm_mmu_reset_all_pte_masks();
6253 
6254 	kvm_set_mmio_spte_mask();
6255 
6256 	pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6257 					    sizeof(struct pte_list_desc),
6258 					    0, SLAB_ACCOUNT, NULL);
6259 	if (!pte_list_desc_cache)
6260 		goto out;
6261 
6262 	mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6263 						  sizeof(struct kvm_mmu_page),
6264 						  0, SLAB_ACCOUNT, NULL);
6265 	if (!mmu_page_header_cache)
6266 		goto out;
6267 
6268 	if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6269 		goto out;
6270 
6271 	ret = register_shrinker(&mmu_shrinker);
6272 	if (ret)
6273 		goto out;
6274 
6275 	return 0;
6276 
6277 out:
6278 	mmu_destroy_caches();
6279 	return ret;
6280 }
6281 
6282 /*
6283  * Calculate mmu pages needed for kvm.
6284  */
6285 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm)
6286 {
6287 	unsigned long nr_mmu_pages;
6288 	unsigned long nr_pages = 0;
6289 	struct kvm_memslots *slots;
6290 	struct kvm_memory_slot *memslot;
6291 	int i;
6292 
6293 	for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6294 		slots = __kvm_memslots(kvm, i);
6295 
6296 		kvm_for_each_memslot(memslot, slots)
6297 			nr_pages += memslot->npages;
6298 	}
6299 
6300 	nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6301 	nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6302 
6303 	return nr_mmu_pages;
6304 }
6305 
6306 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6307 {
6308 	kvm_mmu_unload(vcpu);
6309 	free_mmu_pages(&vcpu->arch.root_mmu);
6310 	free_mmu_pages(&vcpu->arch.guest_mmu);
6311 	mmu_free_memory_caches(vcpu);
6312 }
6313 
6314 void kvm_mmu_module_exit(void)
6315 {
6316 	mmu_destroy_caches();
6317 	percpu_counter_destroy(&kvm_total_used_mmu_pages);
6318 	unregister_shrinker(&mmu_shrinker);
6319 	mmu_audit_disable();
6320 }
6321 
6322 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
6323 {
6324 	unsigned int old_val;
6325 	int err;
6326 
6327 	old_val = nx_huge_pages_recovery_ratio;
6328 	err = param_set_uint(val, kp);
6329 	if (err)
6330 		return err;
6331 
6332 	if (READ_ONCE(nx_huge_pages) &&
6333 	    !old_val && nx_huge_pages_recovery_ratio) {
6334 		struct kvm *kvm;
6335 
6336 		mutex_lock(&kvm_lock);
6337 
6338 		list_for_each_entry(kvm, &vm_list, vm_list)
6339 			wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6340 
6341 		mutex_unlock(&kvm_lock);
6342 	}
6343 
6344 	return err;
6345 }
6346 
6347 static void kvm_recover_nx_lpages(struct kvm *kvm)
6348 {
6349 	int rcu_idx;
6350 	struct kvm_mmu_page *sp;
6351 	unsigned int ratio;
6352 	LIST_HEAD(invalid_list);
6353 	ulong to_zap;
6354 
6355 	rcu_idx = srcu_read_lock(&kvm->srcu);
6356 	spin_lock(&kvm->mmu_lock);
6357 
6358 	ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6359 	to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
6360 	while (to_zap && !list_empty(&kvm->arch.lpage_disallowed_mmu_pages)) {
6361 		/*
6362 		 * We use a separate list instead of just using active_mmu_pages
6363 		 * because the number of lpage_disallowed pages is expected to
6364 		 * be relatively small compared to the total.
6365 		 */
6366 		sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6367 				      struct kvm_mmu_page,
6368 				      lpage_disallowed_link);
6369 		WARN_ON_ONCE(!sp->lpage_disallowed);
6370 		kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6371 		WARN_ON_ONCE(sp->lpage_disallowed);
6372 
6373 		if (!--to_zap || need_resched() || spin_needbreak(&kvm->mmu_lock)) {
6374 			kvm_mmu_commit_zap_page(kvm, &invalid_list);
6375 			if (to_zap)
6376 				cond_resched_lock(&kvm->mmu_lock);
6377 		}
6378 	}
6379 
6380 	spin_unlock(&kvm->mmu_lock);
6381 	srcu_read_unlock(&kvm->srcu, rcu_idx);
6382 }
6383 
6384 static long get_nx_lpage_recovery_timeout(u64 start_time)
6385 {
6386 	return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
6387 		? start_time + 60 * HZ - get_jiffies_64()
6388 		: MAX_SCHEDULE_TIMEOUT;
6389 }
6390 
6391 static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6392 {
6393 	u64 start_time;
6394 	long remaining_time;
6395 
6396 	while (true) {
6397 		start_time = get_jiffies_64();
6398 		remaining_time = get_nx_lpage_recovery_timeout(start_time);
6399 
6400 		set_current_state(TASK_INTERRUPTIBLE);
6401 		while (!kthread_should_stop() && remaining_time > 0) {
6402 			schedule_timeout(remaining_time);
6403 			remaining_time = get_nx_lpage_recovery_timeout(start_time);
6404 			set_current_state(TASK_INTERRUPTIBLE);
6405 		}
6406 
6407 		set_current_state(TASK_RUNNING);
6408 
6409 		if (kthread_should_stop())
6410 			return 0;
6411 
6412 		kvm_recover_nx_lpages(kvm);
6413 	}
6414 }
6415 
6416 int kvm_mmu_post_init_vm(struct kvm *kvm)
6417 {
6418 	int err;
6419 
6420 	err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6421 					  "kvm-nx-lpage-recovery",
6422 					  &kvm->arch.nx_lpage_recovery_thread);
6423 	if (!err)
6424 		kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6425 
6426 	return err;
6427 }
6428 
6429 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6430 {
6431 	if (kvm->arch.nx_lpage_recovery_thread)
6432 		kthread_stop(kvm->arch.nx_lpage_recovery_thread);
6433 }
6434