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