~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/arch/x86/kvm/mmu/mmu.c

Version: ~ [ linux-5.18-rc6 ] ~ [ linux-5.17.6 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.38 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.114 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.192 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.241 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.277 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.312 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.302 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.9 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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