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